<commit_before>// ascii plain text
// Licence: Lesser GNU Public License 2.1 (LGPL)
// $Id$

#define BUILDING_XYLIB
#include "text.h"

#include <cerrno>
#include <cstdlib>

#include "util.h"

using namespace std;
using namespace xylib::util;

namespace xylib {

const FormatInfo TextDataSet::fmt_info(
    "text",
    "ascii text",
    "", // "txt dat asc",
    false,                      // whether binary
    false,                      // whether has multi-blocks
    &TextDataSet::ctor,
    &TextDataSet::check
);

bool TextDataSet::check(istream & /*f*/)
{
    return true;
}

namespace {

// the title-line is either a name of block or contains names of columns
// we assume that it's the latter if the number of words is the same
// as number of columns
void use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk)
{
    const char* delim = " \t";
    vector<string> words;
    std::string::size_type pos = 0;
    while (pos != std::string::npos) {
        std::string::size_type start_pos = line.find_first_not_of(delim, pos);
        pos = line.find_first_of(delim, start_pos);
        words.push_back(std::string(line, start_pos, pos-start_pos));
    }
    if (words.size() == cols.size()) {
        for (size_t i = 0; i < words.size(); ++i)
            cols[i]->set_name(words[i]);
    }
    else
        blk->set_name(line);
}

} // anonymous namespace

void TextDataSet::load_data(std::istream &f)
{
    vector<VecColumn*> cols;
    vector<double> row; // temporary storage for values from one line
    string title_line;
    string s;

    bool strict = has_option("strict");
    bool first_line_header = has_option("first-line-header");
    // header is in last comment line - the line before the first data line
    bool last_line_header = has_option("last-line-header");

    if (first_line_header) {
        title_line = str_trim(read_line(f));
        if (!title_line.empty() && title_line[0] == '#')
            title_line = title_line.substr(1);
    }

    // read lines until the first data line is read and columns are created
    string last_line;
    while (getline(f, s)) {
        // Basic support for LAMMPS log file.
        // There is a chance that output from thermo command will be read
        // properly, but because the LAMMPS log file doesn't have
        // a well-defined syntax, it can not be guaranteed.
        // All data blocks (numeric lines after `run' command) should have
        // the same columns (do not use thermo_style/thermo_modify between
        // runs).
        if (!strict && str_startwith(s, "LAMMPS (")) {
            last_line_header = true;
            continue;
        }
        const char *p = read_numbers(s, row);
        // We skip lines with no data.
        // If there is only one number in first line, skip it if there
        // is a text after the number.
        if (row.size() > 1 ||
                (row.size() == 1 && (strict || *p == '\0' || *p == '#'))) {
            // columns initialization
            for (size_t i = 0; i != row.size(); ++i) {
                cols.push_back(new VecColumn);
                cols[i]->add_val(row[i]);
            }
            break;
        }
        if (last_line_header) {
            string t = str_trim(s);
            if (!t.empty())
                last_line = (t[0] != '#' ? t : t.substr(1));
        }
    }

    // read all the next data lines (the first data line was read above)
    while (getline(f, s)) {
        read_numbers(s, row);

        // We silently skip lines with no data.
        if (row.empty())
            continue;

        if (row.size() < cols.size()) {
            // Some non-data lines may start with numbers. The example is
            // LAMMPS log file. The exceptions below are made to allow plotting
            // such a file. In strict mode, no exceptions are made.
            if (!strict) {
                // if it's the last line, we ignore the line
                if (f.eof())
                    break;

                // line with only one number is probably not a data line
                if (row.size() == 1)
                    continue;

                // if it's the single line with smaller length, we ignore it
                vector<double> row2;
                getline(f, s);
                read_numbers(s, row2);
                if (row2.size() <= 1)
                    continue;
                if (row2.size() < cols.size()) {
                    // add the previous row
                    for (size_t i = 0; i != row.size(); ++i)
                        cols[i]->add_val(row[i]);
                    // number of columns will be shrinked to the size of the
                    // last row. If the previous row was shorter, shrink
                    // the last row.
                    if (row.size() < row2.size())
                        row2.resize(row.size());
                }
                // if we are here, row2 needs to be stored
                row = row2;
            }

            // decrease the number of columns to the new minimum of numbers
            // in line
            for (size_t i = row.size(); i != cols.size(); ++i)
                delete cols[i];
            cols.resize(row.size());
        }

        else if (row.size() > cols.size()) {
            // Generally, we ignore extra columns. But if this is the second
            // data line, we ignore the first line instead.
            // Rationale: some data files have one or two numbers in the first
            // line, that can mean number of points or number of colums, and
            // the real data starts from the next line.
            if (cols[0]->get_point_count() == 1) {
                purge_all_elements(cols);
                for (size_t i = 0; i != row.size(); ++i)
                    cols.push_back(new VecColumn);
            }
        }

        for (size_t i = 0; i != cols.size(); ++i)
            cols[i]->add_val(row[i]);
    }

    format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2,
                  "data not found in file.");

    Block* blk = new Block;
    for (unsigned i = 0; i < cols.size(); ++i)
        blk->add_column(cols[i]);

    if (!title_line.empty())
        use_title_line(title_line, cols, blk);
    if (!last_line.empty())
        use_title_line(last_line, cols, blk);

    add_block(blk);
}

} // end of namespace xylib

<commit_msg>removed unused header<commit_after>// ascii plain text
// Licence: Lesser GNU Public License 2.1 (LGPL)
// $Id$

#define BUILDING_XYLIB
#include "text.h"
#include <cstdlib>
#include "util.h"

using namespace std;
using namespace xylib::util;

namespace xylib {

const FormatInfo TextDataSet::fmt_info(
    "text",
    "ascii text",
    "", // "txt dat asc",
    false,                      // whether binary
    false,                      // whether has multi-blocks
    &TextDataSet::ctor,
    &TextDataSet::check
);

bool TextDataSet::check(istream & /*f*/)
{
    return true;
}

namespace {

// the title-line is either a name of block or contains names of columns
// we assume that it's the latter if the number of words is the same
// as number of columns
void use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk)
{
    const char* delim = " \t";
    vector<string> words;
    std::string::size_type pos = 0;
    while (pos != std::string::npos) {
        std::string::size_type start_pos = line.find_first_not_of(delim, pos);
        pos = line.find_first_of(delim, start_pos);
        words.push_back(std::string(line, start_pos, pos-start_pos));
    }
    if (words.size() == cols.size()) {
        for (size_t i = 0; i < words.size(); ++i)
            cols[i]->set_name(words[i]);
    }
    else
        blk->set_name(line);
}

} // anonymous namespace

void TextDataSet::load_data(std::istream &f)
{
    vector<VecColumn*> cols;
    vector<double> row; // temporary storage for values from one line
    string title_line;
    string s;

    bool strict = has_option("strict");
    bool first_line_header = has_option("first-line-header");
    // header is in last comment line - the line before the first data line
    bool last_line_header = has_option("last-line-header");

    if (first_line_header) {
        title_line = str_trim(read_line(f));
        if (!title_line.empty() && title_line[0] == '#')
            title_line = title_line.substr(1);
    }

    // read lines until the first data line is read and columns are created
    string last_line;
    while (getline(f, s)) {
        // Basic support for LAMMPS log file.
        // There is a chance that output from thermo command will be read
        // properly, but because the LAMMPS log file doesn't have
        // a well-defined syntax, it can not be guaranteed.
        // All data blocks (numeric lines after `run' command) should have
        // the same columns (do not use thermo_style/thermo_modify between
        // runs).
        if (!strict && str_startwith(s, "LAMMPS (")) {
            last_line_header = true;
            continue;
        }
        const char *p = read_numbers(s, row);
        // We skip lines with no data.
        // If there is only one number in first line, skip it if there
        // is a text after the number.
        if (row.size() > 1 ||
                (row.size() == 1 && (strict || *p == '\0' || *p == '#'))) {
            // columns initialization
            for (size_t i = 0; i != row.size(); ++i) {
                cols.push_back(new VecColumn);
                cols[i]->add_val(row[i]);
            }
            break;
        }
        if (last_line_header) {
            string t = str_trim(s);
            if (!t.empty())
                last_line = (t[0] != '#' ? t : t.substr(1));
        }
    }

    // read all the next data lines (the first data line was read above)
    while (getline(f, s)) {
        read_numbers(s, row);

        // We silently skip lines with no data.
        if (row.empty())
            continue;

        if (row.size() < cols.size()) {
            // Some non-data lines may start with numbers. The example is
            // LAMMPS log file. The exceptions below are made to allow plotting
            // such a file. In strict mode, no exceptions are made.
            if (!strict) {
                // if it's the last line, we ignore the line
                if (f.eof())
                    break;

                // line with only one number is probably not a data line
                if (row.size() == 1)
                    continue;

                // if it's the single line with smaller length, we ignore it
                vector<double> row2;
                getline(f, s);
                read_numbers(s, row2);
                if (row2.size() <= 1)
                    continue;
                if (row2.size() < cols.size()) {
                    // add the previous row
                    for (size_t i = 0; i != row.size(); ++i)
                        cols[i]->add_val(row[i]);
                    // number of columns will be shrinked to the size of the
                    // last row. If the previous row was shorter, shrink
                    // the last row.
                    if (row.size() < row2.size())
                        row2.resize(row.size());
                }
                // if we are here, row2 needs to be stored
                row = row2;
            }

            // decrease the number of columns to the new minimum of numbers
            // in line
            for (size_t i = row.size(); i != cols.size(); ++i)
                delete cols[i];
            cols.resize(row.size());
        }

        else if (row.size() > cols.size()) {
            // Generally, we ignore extra columns. But if this is the second
            // data line, we ignore the first line instead.
            // Rationale: some data files have one or two numbers in the first
            // line, that can mean number of points or number of colums, and
            // the real data starts from the next line.
            if (cols[0]->get_point_count() == 1) {
                purge_all_elements(cols);
                for (size_t i = 0; i != row.size(); ++i)
                    cols.push_back(new VecColumn);
            }
        }

        for (size_t i = 0; i != cols.size(); ++i)
            cols[i]->add_val(row[i]);
    }

    format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2,
                  "data not found in file.");

    Block* blk = new Block;
    for (unsigned i = 0; i < cols.size(); ++i)
        blk->add_column(cols[i]);

    if (!title_line.empty())
        use_title_line(title_line, cols, blk);
    if (!last_line.empty())
        use_title_line(last_line, cols, blk);

    add_block(blk);
}

} // end of namespace xylib

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef DISPATCHER_HH
#define DISPATCHER_HH

#include <stdexcept>
#include <queue>

#include "common.hh"
#include "locks.hh"

class Dispatcher;

enum task_state {
    task_dead,
    task_running,
    task_sleeping
};

enum dispatcher_state {
    dispatcher_running,
    dispatcher_stopping,
    dispatcher_stopped
};

class Task;

typedef shared_ptr<Task> TaskId;

class DispatcherCallback {
public:
    virtual ~DispatcherCallback() {}
    virtual bool callback(Dispatcher &d, TaskId t) = 0;
};

class CompareTasks;

class Task {
friend class CompareTasks;
public:
    ~Task() { }
private:
    Task(shared_ptr<DispatcherCallback> cb, int p=0, double sleeptime=0) :
         callback(cb), priority(p) {
        if (sleeptime > 0) {
            snooze(sleeptime);
        } else {
            state = task_running;
        }
    }

    Task(const Task &task) {
        priority = task.priority;
        state = task_running;
        callback = task.callback;
    }

    void snooze(const double secs) {
        LockHolder lh(mutex);
        gettimeofday(&waketime, NULL);
        advance_tv(waketime, secs);
        state = task_sleeping;
    }

    bool run(Dispatcher &d, TaskId t) {
        return callback->callback(d, t);
    }

    void cancel() {
        LockHolder lh(mutex);
        state = task_dead;
    }

    friend class Dispatcher;
    std::string name;
    struct timeval waketime;
    shared_ptr<DispatcherCallback> callback;
    int priority;
    enum task_state state;
    Mutex mutex;
};

class CompareTasks {
public:
    bool operator()(TaskId &t1, TaskId &t2) {
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Comparing two tasks\n");
        if (t1->state == task_running) {
            if (t2->state == task_running) {
                return t1->priority > t2->priority;
            } else if (t2->state == task_sleeping) {
                return false;
            }
        } else if (t1->state == task_sleeping && t2->state == task_sleeping) {
            return less_tv(t2->waketime, t1->waketime);
        }
        return true;
    }
};

class Dispatcher {
public:
    Dispatcher() : state(dispatcher_running) { }

    ~Dispatcher() {
        stop();
    }

    TaskId schedule(shared_ptr<DispatcherCallback> callback, int priority=0,
                    double sleeptime=0) {
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Scheduling a new task\n");
        LockHolder lh(mutex);
        TaskId task(new Task(callback, priority, sleeptime));
        queue.push(task);
        mutex.notify();
        return TaskId(task);
    }

    TaskId wake(TaskId task) {
        cancel(task);
        TaskId oldTask(task);
        TaskId newTask(new Task(*oldTask));
        queue.push(newTask);
        mutex.notify();
        return TaskId(newTask);
    }

    void start();

    void run() {
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher starting\n");
        while (state == dispatcher_running) {
            LockHolder lh(mutex);
            if (queue.empty()) {
                // Wait forever
                mutex.wait();
            } else {
                TaskId task = queue.top();
                LockHolder tlh(task->mutex);
                switch (task->state) {
                case task_sleeping:
                    {
                        struct timeval tv;
                        gettimeofday(&tv, NULL);
                        if (less_tv(tv, task->waketime)) {
                            tlh.unlock();
                            mutex.wait(task->waketime);
                        } else {
                            task->state = task_running;
                        }
                    }
                    break;
                case task_running:
                    queue.pop();
                    lh.unlock();
                    tlh.unlock();
                    try {
                        if(task->run(*this, TaskId(task))) {
                            reschedule(task);
                        }
                    } catch (std::exception& e) {
                        std::cerr << "exception caught in task " << task->name << ": " << e.what() << std::endl;
                    } catch(...) {
                        std::cerr << "Caught a fatal exception in task" << task->name <<std::endl;
                    }
                    break;
                case task_dead:
                    queue.pop();
                    break;
                default:
                    throw std::runtime_error("Unexpected state for task");
                }
            }
        }

        state = dispatcher_stopped;
        mutex.notify();
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher exited\n");
    }

    void stop() {
        LockHolder lh(mutex);
        if (state == dispatcher_stopped) {
            return;
        }
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Stopping dispatcher\n");
        state = dispatcher_stopping;
        mutex.notify();
        lh.unlock();
        pthread_join(thread, NULL);
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher stopped\n");
    }

    void snooze(TaskId t, double sleeptime) {
        t->snooze(sleeptime);
    }

    void cancel(TaskId t) {
        t->cancel();
    }

private:
    void reschedule(TaskId task) {
        // If the task is already in the queue it'll get run twice
        LockHolder lh(mutex);
        queue.push(task);
    }

    pthread_t thread;
    SyncObject mutex;
    std::priority_queue<TaskId, std::deque<TaskId >,
                        CompareTasks> queue;
    enum dispatcher_state state;
};

#endif
<commit_msg>Make the dispatcher less chatty<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef DISPATCHER_HH
#define DISPATCHER_HH

#include <stdexcept>
#include <queue>

#include "common.hh"
#include "locks.hh"

class Dispatcher;

enum task_state {
    task_dead,
    task_running,
    task_sleeping
};

enum dispatcher_state {
    dispatcher_running,
    dispatcher_stopping,
    dispatcher_stopped
};

class Task;

typedef shared_ptr<Task> TaskId;

class DispatcherCallback {
public:
    virtual ~DispatcherCallback() {}
    virtual bool callback(Dispatcher &d, TaskId t) = 0;
};

class CompareTasks;

class Task {
friend class CompareTasks;
public:
    ~Task() { }
private:
    Task(shared_ptr<DispatcherCallback> cb, int p=0, double sleeptime=0) :
         callback(cb), priority(p) {
        if (sleeptime > 0) {
            snooze(sleeptime);
        } else {
            state = task_running;
        }
    }

    Task(const Task &task) {
        priority = task.priority;
        state = task_running;
        callback = task.callback;
    }

    void snooze(const double secs) {
        LockHolder lh(mutex);
        gettimeofday(&waketime, NULL);
        advance_tv(waketime, secs);
        state = task_sleeping;
    }

    bool run(Dispatcher &d, TaskId t) {
        return callback->callback(d, t);
    }

    void cancel() {
        LockHolder lh(mutex);
        state = task_dead;
    }

    friend class Dispatcher;
    std::string name;
    struct timeval waketime;
    shared_ptr<DispatcherCallback> callback;
    int priority;
    enum task_state state;
    Mutex mutex;
};

class CompareTasks {
public:
    bool operator()(TaskId t1, TaskId t2) {
        if (t1->state == task_running) {
            if (t2->state == task_running) {
                return t1->priority > t2->priority;
            } else if (t2->state == task_sleeping) {
                return false;
            }
        } else if (t1->state == task_sleeping && t2->state == task_sleeping) {
            return less_tv(t2->waketime, t1->waketime);
        }
        return true;
    }
};

class Dispatcher {
public:
    Dispatcher() : state(dispatcher_running) { }

    ~Dispatcher() {
        stop();
    }

    TaskId schedule(shared_ptr<DispatcherCallback> callback, int priority=0,
                    double sleeptime=0) {
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Scheduling a new task\n");
        LockHolder lh(mutex);
        TaskId task(new Task(callback, priority, sleeptime));
        queue.push(task);
        mutex.notify();
        return TaskId(task);
    }

    TaskId wake(TaskId task) {
        cancel(task);
        TaskId oldTask(task);
        TaskId newTask(new Task(*oldTask));
        queue.push(newTask);
        mutex.notify();
        return TaskId(newTask);
    }

    void start();

    void run() {
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher starting\n");
        while (state == dispatcher_running) {
            LockHolder lh(mutex);
            if (queue.empty()) {
                // Wait forever
                mutex.wait();
            } else {
                TaskId task = queue.top();
                LockHolder tlh(task->mutex);
                switch (task->state) {
                case task_sleeping:
                    {
                        struct timeval tv;
                        gettimeofday(&tv, NULL);
                        if (less_tv(tv, task->waketime)) {
                            tlh.unlock();
                            mutex.wait(task->waketime);
                        } else {
                            task->state = task_running;
                        }
                    }
                    break;
                case task_running:
                    queue.pop();
                    lh.unlock();
                    tlh.unlock();
                    try {
                        if(task->run(*this, TaskId(task))) {
                            reschedule(task);
                        }
                    } catch (std::exception& e) {
                        std::cerr << "exception caught in task " << task->name << ": " << e.what() << std::endl;
                    } catch(...) {
                        std::cerr << "Caught a fatal exception in task" << task->name <<std::endl;
                    }
                    break;
                case task_dead:
                    queue.pop();
                    break;
                default:
                    throw std::runtime_error("Unexpected state for task");
                }
            }
        }

        state = dispatcher_stopped;
        mutex.notify();
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher exited\n");
    }

    void stop() {
        LockHolder lh(mutex);
        if (state == dispatcher_stopped) {
            return;
        }
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Stopping dispatcher\n");
        state = dispatcher_stopping;
        mutex.notify();
        lh.unlock();
        pthread_join(thread, NULL);
        getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher stopped\n");
    }

    void snooze(TaskId t, double sleeptime) {
        t->snooze(sleeptime);
    }

    void cancel(TaskId t) {
        t->cancel();
    }

private:
    void reschedule(TaskId task) {
        // If the task is already in the queue it'll get run twice
        LockHolder lh(mutex);
        queue.push(task);
    }

    pthread_t thread;
    SyncObject mutex;
    std::priority_queue<TaskId, std::deque<TaskId >,
                        CompareTasks> queue;
    enum dispatcher_state state;
};

#endif
<|endoftext|>


<commit_before>#include <errno.h>
#include <QMessageBox>
#include <QCloseEvent>
#include "mainwindow.h"
#include "ui_mainwindow.h"

const char MainWindow::pol_pm[] =
        "+ -";
const char MainWindow::pol_mp[] =
        "- +";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    configUI()
{
    ui->setupUi(this);

    QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show()));

    currentTimer.setInterval(500);
    currentTimer.setSingleShot(false);
    QObject::connect(&currentTimer, SIGNAL(timeout()), this,
                     SLOT(on_currentTimer_timeout()));
}

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

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (configUI.isHidden() && configUI.result() == QDialog::Accepted) {
        event->ignore();
        hide();
        configUI.show();

        return;
    }

    QMainWindow::closeEvent(event);
}

bool MainWindow::openDevs()
{
    QString err_text, err_title;
    QString s;
    int err;

    s = settings.value(ConfigUI::cfg_powerSupplyPort).toString();
    err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN);
    if (err < 0)
        goto sdp_err0;

    /* Set value limit in current input spin  box. */
    sdp_va_t limits;
    err = sdp_get_va_maximums(&sdp, &limits);
    if (err < 0)
        goto sdp_err;
    ui->coilCurrDoubleSpinBox->setMaximum(limits.curr);

    /* Set current to actual value, avoiding anny jumps. */
    sdp_va_data_t va_data;
    err = sdp_get_va_data(&sdp, &va_data);
    if (err < 0)
        goto sdp_err;
    err = sdp_set_curr(&sdp, va_data.curr);
    if (err < 0)
        goto sdp_err;
    /* Set voltage to maximum, Hall is current driven. */
    err = sdp_set_volt_limit(&sdp, va_data.volt);
    if (err < 0)
        goto sdp_err;
    err = sdp_set_volt(&sdp, va_data.volt);
    if (err < 0)
        goto sdp_err;

    sdp_lcd_info_t lcd_info;
    if (err < 0)
        goto sdp_err;
    ui->coilPowerCheckBox->setChecked(lcd_info.output);

    s = settings.value(ConfigUI::cfg_polSwitchPort).toString();
    if (!powerSwitch.open(s.toLocal8Bit().constData())) {
        err = errno;
        goto mag_pwr_switch_err;
    }

    bool cross;
    cross = powerSwitch.polarity() == PolaritySwitch::cross;
    ui->coilPolCrossCheckBox->setChecked(cross);

    /* TODO ... */

    currentTimer.start();

    return true;

    // powerSwitch.close();

mag_pwr_switch_err:
    if (err_title.isEmpty()) {

        err_title = QString::fromLocal8Bit(
                    "Failed to open power supply switch");
        err_text = QString::fromLocal8Bit(strerror(err));
    }

sdp_err:
    sdp_close(&sdp);

sdp_err0:
    if (err_title.isEmpty()) {
        err_title = QString::fromLocal8Bit(
                    "Failed to open Manson SDP power supply");
        err_text = QString::fromLocal8Bit(sdp_strerror(err));
    }

    err_text = QString("%1:\n\n%2").arg(err_title).arg(err_text);
    QMessageBox::critical(this, err_title, err_text);
    statusBar()->showMessage(err_title);

    return false;
}

void MainWindow::closeDevs()
{
    sdp_close(&sdp);
}

void MainWindow::on_coilPowerCheckBox_toggled(bool checked)
{
    if (checked) {
        // FIXME
        // sdp_set_curr(&sdp, 0);
        // sdp_set_output(&sdp, true);
    }
    currentTimer.start();
}

void MainWindow::on_measurePushButton_clicked()
{
    /* TODO */
}

void MainWindow::on_currentTimer_timeout()
{
    /* TODO */
}

void MainWindow::updateCurrent()
{
    double current;

    current = ui->coilCurrDoubleSpinBox->value();
    if (ui->coilPolCrossCheckBox->isChecked())
        current = -current;

    sdp_set_curr(&sdp, current);

    /* TODO */
}

void MainWindow::on_coilPolCrossCheckBox_toggled(bool checked)
{
    /*if (checked) {
        powerSwitch.setPolarity(PolaritySwitch::cross);
        ui->polarityLabel->setText(pol_mp);
    } else {
        powerSwitch.setPolarity(PolaritySwitch::direct);
        ui->polarityLabel->setText(pol_pm);
    }*/

    currentTimer.start();
}

void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double )
{
    currentTimer.start();
}

void MainWindow::show()
{
    if (!openDevs()) {
        configUI.show();

        return;
    }

    QWidget::show();
}

void MainWindow::startApp()
{
    configUI.show();
}

void MainWindow::on_samplePowerCheckBox_toggled(bool )
{

}

void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double )
{

}

void MainWindow::on_samplePolCrossCheckBox_toggled(bool )
{

}
<commit_msg>Function reorder by alphabet<commit_after>#include <errno.h>
#include <QMessageBox>
#include <QCloseEvent>
#include "mainwindow.h"
#include "ui_mainwindow.h"

const char MainWindow::pol_pm[] =
        "+ -";
const char MainWindow::pol_mp[] =
        "- +";

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    configUI()
{
    ui->setupUi(this);

    QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show()));

    currentTimer.setInterval(500);
    currentTimer.setSingleShot(false);
    QObject::connect(&currentTimer, SIGNAL(timeout()), this,
                     SLOT(on_currentTimer_timeout()));
}

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

void MainWindow::closeDevs()
{
    currentTimer.stop();
    powerSwitch.close();
    sdp_close(&sdp);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (configUI.isHidden() && configUI.result() == QDialog::Accepted) {
        closeDevs();
        event->ignore();
        hide();
        configUI.show();

        return;
    }

    QMainWindow::closeEvent(event);
}

void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double )
{
    //currentTimer.start();
}

void MainWindow::on_coilPolCrossCheckBox_toggled(bool)
{
    /*if (checked) {
        powerSwitch.setPolarity(PolaritySwitch::cross);
        ui->polarityLabel->setText(pol_mp);
    } else {
        powerSwitch.setPolarity(PolaritySwitch::direct);
        ui->polarityLabel->setText(pol_pm);
    }*/

    //currentTimer.start();
}

void MainWindow::on_coilPowerCheckBox_toggled(bool checked)
{
    if (checked) {
        // FIXME
        // sdp_set_curr(&sdp, 0);
        // sdp_set_output(&sdp, true);
    }
    //currentTimer.start();
}

void MainWindow::on_currentTimer_timeout()
{
    sdp_va_data_t va_data;

    if (sdp_get_va_data(&sdp, &va_data) < 0) {
        // TODO
        close();
        return;
    }

    ui->coilCurrMeasDoubleSpinBox->setValue(va_data.curr);
    /* TODO */
}

void MainWindow::on_measurePushButton_clicked()
{
    /* TODO */
}

void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double )
{

}

void MainWindow::on_samplePolCrossCheckBox_toggled(bool )
{

}

void MainWindow::on_samplePowerCheckBox_toggled(bool )
{

}

bool MainWindow::openDevs()
{
    QString err_text, err_title;
    QString s;
    int err;

    s = settings.value(ConfigUI::cfg_powerSupplyPort).toString();
    err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN);
    if (err < 0)
        goto sdp_err0;

    /* Set value limit in current input spin  box. */
    sdp_va_t limits;
    err = sdp_get_va_maximums(&sdp, &limits);
    if (err < 0)
        goto sdp_err;
    ui->coilCurrDoubleSpinBox->setMaximum(limits.curr);

    /* Set current to actual value, avoiding anny jumps. */
    sdp_va_data_t va_data;
    err = sdp_get_va_data(&sdp, &va_data);
    if (err < 0)
        goto sdp_err;
    err = sdp_set_curr(&sdp, va_data.curr);
    if (err < 0)
        goto sdp_err;
    /* Set voltage to maximum, Hall is current driven. */
    err = sdp_set_volt_limit(&sdp, va_data.volt);
    if (err < 0)
        goto sdp_err;
    err = sdp_set_volt(&sdp, va_data.volt);
    if (err < 0)
        goto sdp_err;

    sdp_lcd_info_t lcd_info;
    if (err < 0)
        goto sdp_err;
    ui->coilPowerCheckBox->setChecked(lcd_info.output);

    s = settings.value(ConfigUI::cfg_polSwitchPort).toString();
    if (!powerSwitch.open(s.toLocal8Bit().constData())) {
        err = errno;
        goto mag_pwr_switch_err;
    }

    bool cross;
    cross = powerSwitch.polarity() == PolaritySwitch::cross;
    ui->coilPolCrossCheckBox->setChecked(cross);

    /* TODO ... */

    currentTimer.start();

    return true;

    // powerSwitch.close();

mag_pwr_switch_err:
    if (err_title.isEmpty()) {

        err_title = QString::fromLocal8Bit(
                    "Failed to open power supply switch");
        err_text = QString::fromLocal8Bit(strerror(err));
    }

sdp_err:
    sdp_close(&sdp);

sdp_err0:
    if (err_title.isEmpty()) {
        err_title = QString::fromLocal8Bit(
                    "Failed to open Manson SDP power supply");
        err_text = QString::fromLocal8Bit(sdp_strerror(err));
    }

    err_text = QString("%1:\n\n%2").arg(err_title).arg(err_text);
    QMessageBox::critical(this, err_title, err_text);
    statusBar()->showMessage(err_title);

    return false;
}

void MainWindow::show()
{
    if (!openDevs()) {
        configUI.show();

        return;
    }

    QWidget::show();
}

void MainWindow::startApp()
{
    configUI.show();
}

void MainWindow::updateCurrent()
{
    double current;

    current = ui->coilCurrDoubleSpinBox->value();
    if (ui->coilPolCrossCheckBox->isChecked())
        current = -current;

    sdp_set_curr(&sdp, current);

    /* TODO */
}
<|endoftext|>


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

#ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
#include "toolkit/controls/geometrycontrolmodel.hxx"
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif

#define GCM_PROPERTY_ID_POS_X       1
#define GCM_PROPERTY_ID_POS_Y       2
#define GCM_PROPERTY_ID_WIDTH       3
#define GCM_PROPERTY_ID_HEIGHT      4

#define GCM_PROPERTY_POS_X  ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionX"))
#define GCM_PROPERTY_POS_Y  ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionY"))
#define GCM_PROPERTY_WIDTH  ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Width"))
#define GCM_PROPERTY_HEIGHT ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Height"))

#define DEFAULT_ATTRIBS()       PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT

//........................................................................
// namespace toolkit
// {
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::comphelper;

    //====================================================================
    //= OGeometryControlModel_Base
    //====================================================================
    //--------------------------------------------------------------------
    OGeometryControlModel_Base::OGeometryControlModel_Base(XAggregation* _pAggregateInstance)
        :OPropertySetAggregationHelper(m_aBHelper)
        ,OPropertyContainer(m_aBHelper)
        ,m_nPosX(0)
        ,m_nPosY(0)
        ,m_nWidth(0)
        ,m_nHeight(0)
    {
        OSL_ENSURE(NULL != _pAggregateInstance, "OGeometryControlModel_Base::OGeometryControlModel_Base: invalid aggregate!");

        // create our aggregate
        increment(m_refCount);
        {
            m_xAggregate = _pAggregateInstance;
            setAggregation(m_xAggregate);
            m_xAggregate->setDelegator(static_cast< XWeak* >(this));
        }
        decrement(m_refCount);

        // register our members for the property handling of the OPropertyContainer
        registerProperty(GCM_PROPERTY_POS_X,    GCM_PROPERTY_ID_POS_X,  DEFAULT_ATTRIBS(), &m_nPosX, ::getCppuType(&m_nPosX));
        registerProperty(GCM_PROPERTY_POS_Y,    GCM_PROPERTY_ID_POS_Y,  DEFAULT_ATTRIBS(), &m_nPosY, ::getCppuType(&m_nPosY));
        registerProperty(GCM_PROPERTY_WIDTH,    GCM_PROPERTY_ID_WIDTH,  DEFAULT_ATTRIBS(), &m_nWidth, ::getCppuType(&m_nWidth));
        registerProperty(GCM_PROPERTY_HEIGHT,   GCM_PROPERTY_ID_HEIGHT, DEFAULT_ATTRIBS(), &m_nHeight, ::getCppuType(&m_nHeight));
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OGeometryControlModel_Base::queryAggregation( const Type& _rType ) throw(RuntimeException)
    {
        Any aReturn = OWeakAggObject::queryAggregation(_rType);
            // the basic interfaces (XInterface, XAggregation etc)

        if (!aReturn.hasValue())
            aReturn = OPropertySetAggregationHelper::queryInterface(_rType);
            // the property set related interfaces

        if (!aReturn.hasValue() && m_xAggregate.is())
            aReturn = m_xAggregate->queryAggregation(_rType);
            // the interfaces our aggregate can provide

        return aReturn;
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OGeometryControlModel_Base::queryInterface( const Type& _rType ) throw(RuntimeException)
    {
        return OWeakAggObject::queryInterface(_rType);
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::acquire(  ) throw()
    {
        OWeakAggObject::acquire();
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::release(  ) throw()
    {
        OWeakAggObject::release();
    }

    //--------------------------------------------------------------------
    OGeometryControlModel_Base::~OGeometryControlModel_Base()
    {
        // release the aggregate (_before_ clearing m_xAggregate)
        if (m_xAggregate.is())
            m_xAggregate->setDelegator(NULL);
        setAggregation(NULL);
    }

    //--------------------------------------------------------------------
    sal_Bool SAL_CALL OGeometryControlModel_Base::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,
            sal_Int32 _nHandle, const Any& _rValue) throw (IllegalArgumentException)
    {
        return OPropertyContainer::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue);
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw (Exception)
    {
        OPropertyContainer::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle) const
    {
        OPropertyArrayAggregationHelper& rPH = static_cast<OPropertyArrayAggregationHelper&>(const_cast<OGeometryControlModel_Base*>(this)->getInfoHelper());
        ::rtl::OUString sPropName;
        sal_Int32   nOriginalHandle = -1;

        if (rPH.fillAggregatePropertyInfoByHandle(&sPropName, &nOriginalHandle, _nHandle))
            OPropertySetAggregationHelper::getFastPropertyValue(_rValue, _nHandle);
        else
            OPropertyContainer::getFastPropertyValue(_rValue, _nHandle);
    }

    //--------------------------------------------------------------------
    Reference< XPropertySetInfo> SAL_CALL OGeometryControlModel_Base::getPropertySetInfo() throw(RuntimeException)
    {
        return OPropertySetAggregationHelper::createPropertySetInfo(getInfoHelper());
    }

//........................................................................
// }    // namespace toolkit
//........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *
 *  Revision 1.0 17.01.01 11:35:20  fs
 ************************************************************************/

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

#ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_
#include "toolkit/controls/geometrycontrolmodel.hxx"
#endif

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
#include "toolkit/controls/eventcontainer.hxx"

#define GCM_PROPERTY_ID_POS_X       1
#define GCM_PROPERTY_ID_POS_Y       2
#define GCM_PROPERTY_ID_WIDTH       3
#define GCM_PROPERTY_ID_HEIGHT      4

#define GCM_PROPERTY_POS_X  ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionX"))
#define GCM_PROPERTY_POS_Y  ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionY"))
#define GCM_PROPERTY_WIDTH  ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Width"))
#define GCM_PROPERTY_HEIGHT ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Height"))

#define DEFAULT_ATTRIBS()       PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT

//........................................................................
// namespace toolkit
// {
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::comphelper;

    //====================================================================
    //= OGeometryControlModel_Base
    //====================================================================
    //--------------------------------------------------------------------
    OGeometryControlModel_Base::OGeometryControlModel_Base(XAggregation* _pAggregateInstance)
        :OPropertySetAggregationHelper(m_aBHelper)
        ,OPropertyContainer(m_aBHelper)
        ,m_nPosX(0)
        ,m_nPosY(0)
        ,m_nWidth(0)
        ,m_nHeight(0)
    {
        OSL_ENSURE(NULL != _pAggregateInstance, "OGeometryControlModel_Base::OGeometryControlModel_Base: invalid aggregate!");

        // create our aggregate
        increment(m_refCount);
        {
            m_xAggregate = _pAggregateInstance;
            setAggregation(m_xAggregate);
            m_xAggregate->setDelegator(static_cast< XWeak* >(this));
        }
        decrement(m_refCount);

        // register our members for the property handling of the OPropertyContainer
        registerProperty(GCM_PROPERTY_POS_X,    GCM_PROPERTY_ID_POS_X,  DEFAULT_ATTRIBS(), &m_nPosX, ::getCppuType(&m_nPosX));
        registerProperty(GCM_PROPERTY_POS_Y,    GCM_PROPERTY_ID_POS_Y,  DEFAULT_ATTRIBS(), &m_nPosY, ::getCppuType(&m_nPosY));
        registerProperty(GCM_PROPERTY_WIDTH,    GCM_PROPERTY_ID_WIDTH,  DEFAULT_ATTRIBS(), &m_nWidth, ::getCppuType(&m_nWidth));
        registerProperty(GCM_PROPERTY_HEIGHT,   GCM_PROPERTY_ID_HEIGHT, DEFAULT_ATTRIBS(), &m_nHeight, ::getCppuType(&m_nHeight));
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OGeometryControlModel_Base::queryAggregation( const Type& _rType ) throw(RuntimeException)
    {
        Any aReturn = OWeakAggObject::queryAggregation(_rType);
            // the basic interfaces (XInterface, XAggregation etc)

        if (!aReturn.hasValue())
            aReturn = OPropertySetAggregationHelper::queryInterface(_rType);
            // the property set related interfaces

        if (!aReturn.hasValue() && m_xAggregate.is())
            aReturn = m_xAggregate->queryAggregation(_rType);
            // the interfaces our aggregate can provide

        if (!aReturn.hasValue() && m_xAggregate.is())
        {
            aReturn = ::cppu::queryInterface( _rType,
                static_cast< ::com::sun::star::script::XScriptEventsSupplier* >( this ) );
        }

        return aReturn;
    }

    //--------------------------------------------------------------------
    Any SAL_CALL OGeometryControlModel_Base::queryInterface( const Type& _rType ) throw(RuntimeException)
    {
        return OWeakAggObject::queryInterface(_rType);
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::acquire(  ) throw()
    {
        OWeakAggObject::acquire();
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::release(  ) throw()
    {
        OWeakAggObject::release();
    }

    //--------------------------------------------------------------------
    OGeometryControlModel_Base::~OGeometryControlModel_Base()
    {
        // release the aggregate (_before_ clearing m_xAggregate)
        if (m_xAggregate.is())
            m_xAggregate->setDelegator(NULL);
        setAggregation(NULL);
    }

    //--------------------------------------------------------------------
    sal_Bool SAL_CALL OGeometryControlModel_Base::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,
            sal_Int32 _nHandle, const Any& _rValue) throw (IllegalArgumentException)
    {
        return OPropertyContainer::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue);
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw (Exception)
    {
        OPropertyContainer::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
    }

    //--------------------------------------------------------------------
    void SAL_CALL OGeometryControlModel_Base::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle) const
    {
        OPropertyArrayAggregationHelper& rPH = static_cast<OPropertyArrayAggregationHelper&>(const_cast<OGeometryControlModel_Base*>(this)->getInfoHelper());
        ::rtl::OUString sPropName;
        sal_Int32   nOriginalHandle = -1;

        if (rPH.fillAggregatePropertyInfoByHandle(&sPropName, &nOriginalHandle, _nHandle))
            OPropertySetAggregationHelper::getFastPropertyValue(_rValue, _nHandle);
        else
            OPropertyContainer::getFastPropertyValue(_rValue, _nHandle);
    }

    //--------------------------------------------------------------------
    Reference< XPropertySetInfo> SAL_CALL OGeometryControlModel_Base::getPropertySetInfo() throw(RuntimeException)
    {
        return OPropertySetAggregationHelper::createPropertySetInfo(getInfoHelper());
    }

    //--------------------------------------------------------------------
    Reference< XNameContainer > SAL_CALL OGeometryControlModel_Base::getEvents() throw(RuntimeException)
    {
        if( !mxEventContainer.is() )
            mxEventContainer = (XNameContainer*)new ScriptEventContainer();
        return mxEventContainer;
    }

//........................................................................
// }    // namespace toolkit
//........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1  2001/01/24 14:55:12  mt
 *  model for dialog controls (weith pos/size)
 *
 *
 *  Revision 1.0 17.01.01 11:35:20  fs
 ************************************************************************/

<|endoftext|>


<commit_before>// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp

#include <NDK/Systems/DebugSystem.hpp>
#include <Nazara/Core/Primitive.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Utility/IndexIterator.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/DebugComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>

namespace Ndk
{
	namespace
	{
		class DebugRenderable : public Nz::InstancedRenderable
		{
			public:
				DebugRenderable(Ndk::Entity* owner, Nz::MaterialRef mat, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :
				m_entityOwner(owner),
				m_material(std::move(mat)),
				m_indexBuffer(std::move(indexBuffer)),
				m_vertexBuffer(std::move(vertexBuffer))
				{
					ResetMaterials(1);

					m_meshData.indexBuffer = m_indexBuffer;
					m_meshData.primitiveMode = Nz::PrimitiveMode_LineList;
					m_meshData.vertexBuffer = m_vertexBuffer;
				}

				void UpdateBoundingVolume(InstanceData* instanceData) const override
				{
				}

				void MakeBoundingVolume() const override
				{
					m_boundingVolume.MakeNull();
				}

			protected:
				Ndk::EntityHandle m_entityOwner;
				Nz::IndexBufferRef m_indexBuffer;
				Nz::MaterialRef m_material;
				Nz::MeshData m_meshData;
				Nz::VertexBufferRef m_vertexBuffer;
		};

		class AABBDebugRenderable : public DebugRenderable
		{
			public:
				using DebugRenderable::DebugRenderable;

				void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override
				{
					NazaraAssert(m_entityOwner, "DebugRenderable has no owner");

					const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();
					const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();

					Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity();
					transformMatrix.SetScale(entityGfx.GetBoundingVolume().aabb.GetLengths());
					transformMatrix.SetTranslation(entityGfx.GetBoundingVolume().aabb.GetCenter());

					renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);
				}
		};

		class OBBDebugRenderable : public DebugRenderable
		{
			public:
				using DebugRenderable::DebugRenderable;

				void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override
				{
					NazaraAssert(m_entityOwner, "DebugRenderable has no owner");

					const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();
					const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();

					Nz::Matrix4f transformMatrix = instanceData.transformMatrix;
					transformMatrix.ApplyScale(entityGfx.GetBoundingVolume().obb.localBox.GetLengths());

					renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);
				}
		};
	}

	/*!
	* \ingroup NDK
	* \class Ndk::DebugSystem
	* \brief NDK class that represents the debug system
	*
	* \remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent
	*/

	/*!
	* \brief Constructs an DebugSystem object by default
	*/
	DebugSystem::DebugSystem()
	{
		Requires<DebugComponent, GraphicsComponent>();
		SetUpdateOrder(1000); //< Update last
	}

	std::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh()
	{
		if (!m_boxMeshIndexBuffer)
		{
			std::array<Nz::UInt16, 24> indices = {
				{
					0, 1,
					1, 2,
					2, 3,
					3, 0,

					4, 5,
					5, 6,
					6, 7,
					7, 4,

					0, 4,
					1, 5,
					2, 6,
					3, 7
				}
			};

			m_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, indices.size(), Nz::DataStorage_Hardware, 0);
			m_boxMeshIndexBuffer->Fill(indices.data(), 0, indices.size());
		}

		if (!m_boxMeshVertexBuffer)
		{
			Nz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f);

			std::array<Nz::Vector3f, 8> positions = {
				{
					box.GetCorner(Nz::BoxCorner_FarLeftBottom),
					box.GetCorner(Nz::BoxCorner_NearLeftBottom),
					box.GetCorner(Nz::BoxCorner_NearRightBottom),
					box.GetCorner(Nz::BoxCorner_FarRightBottom),
					box.GetCorner(Nz::BoxCorner_FarLeftTop),
					box.GetCorner(Nz::BoxCorner_NearLeftTop),
					box.GetCorner(Nz::BoxCorner_NearRightTop),
					box.GetCorner(Nz::BoxCorner_FarRightTop)
				}
			};

			m_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), positions.size(), Nz::DataStorage_Hardware, 0);
			m_boxMeshVertexBuffer->Fill(positions.data(), 0, positions.size());
		}

		return { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer };
	}

	void DebugSystem::OnEntityValidation(Entity* entity, bool /*justAdded*/)
	{
		static constexpr int DebugDrawOrder = 1'000;

		DebugComponent& entityDebug = entity->GetComponent<DebugComponent>();
		GraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>();

		DebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags();
		DebugDrawFlags flags = entityDebug.GetFlags();

		DebugDrawFlags flagsToEnable = flags & ~enabledFlags;
		for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)
		{
			DebugDraw option = static_cast<DebugDraw>(i);
			if (flagsToEnable & option)
			{
				switch (option)
				{
					case DebugDraw::Collider3D:
					{
						const Nz::Boxf& obb = entityGfx.GetBoundingVolume().obb.localBox;

						Nz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity);
						renderable->SetPersistent(false);

						entityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter()), DebugDrawOrder);

						entityDebug.UpdateDebugRenderable(option, std::move(renderable));
						break;
					}

					case DebugDraw::GraphicsAABB:
					{
						auto indexVertexBuffers = GetBoxMesh();

						Nz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);
						renderable->SetPersistent(false);

						entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);

						entityDebug.UpdateDebugRenderable(option, std::move(renderable));
						break;
					}

					case DebugDraw::GraphicsOBB:
					{
						auto indexVertexBuffers = GetBoxMesh();

						Nz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);
						renderable->SetPersistent(false);

						entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);

						entityDebug.UpdateDebugRenderable(option, std::move(renderable));
						break;
					}

					default:
						break;
				}
			}
		}

		DebugDrawFlags flagsToDisable = enabledFlags & ~flags;
		for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)
		{
			DebugDraw option = static_cast<DebugDraw>(i);
			if (flagsToDisable & option)
				entityGfx.Detach(entityDebug.GetDebugRenderable(option));
		}

		entityDebug.UpdateEnabledFlags(flags);
	}

	void DebugSystem::OnUpdate(float elapsedTime)
	{
		// Nothing to do
	}

	Nz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box)
	{
		Nz::MeshRef mesh = Nz::Mesh::New();
		mesh->CreateStatic();

		mesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths()));
		mesh->SetMaterialCount(1);

		Nz::ModelRef model = Nz::Model::New();
		model->SetMesh(mesh);
		model->SetMaterial(0, GetOBBMaterial());

		return model;
	}

	Nz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity)
	{
		if (entity->HasComponent<CollisionComponent3D>())
		{
			CollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>();
			const Nz::Collider3DRef& geom = entityCollision.GetGeom();

			std::vector<Nz::Vector3f> vertices;
			std::vector<std::size_t> indices;

			geom->ForEachPolygon([&](const float* polygonVertices, std::size_t vertexCount)
			{
				std::size_t firstIndex = vertices.size();

				for (std::size_t i = 0; i < vertexCount; ++i)
				{
					const float* vertexData = &polygonVertices[i * 3];
					vertices.emplace_back(vertexData[0], vertexData[1], vertexData[2]);
				}

				for (std::size_t i = 0; i < vertexCount - 1; ++i)
				{
					indices.push_back(firstIndex + i);
					indices.push_back(firstIndex + i + 1);
				}

				indices.push_back(firstIndex + vertexCount - 1);
				indices.push_back(firstIndex);
			});

			Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, indices.size(), Nz::DataStorage_Hardware, 0);
			Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly);

			Nz::IndexIterator indexPtr = indexMapper.begin();
			for (std::size_t index : indices)
				*indexPtr++ = static_cast<Nz::UInt32>(index);

			indexMapper.Unmap();

			Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), vertices.size(), Nz::DataStorage_Hardware, 0);
			vertexBuffer->Fill(vertices.data(), 0, vertices.size());

			Nz::MeshRef mesh = Nz::Mesh::New();
			mesh->CreateStatic();

			Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(mesh);
			subMesh->Create(vertexBuffer);
			subMesh->SetIndexBuffer(indexBuffer);
			subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList);
			subMesh->SetMaterialIndex(0);
			subMesh->GenerateAABB();

			mesh->SetMaterialCount(1);
			mesh->AddSubMesh(subMesh);

			Nz::ModelRef model = Nz::Model::New();
			model->SetMesh(mesh);
			model->SetMaterial(0, GetCollisionMaterial());

			return model;
		}
		else
			return nullptr;
	}

	Nz::MaterialRef DebugSystem::GetAABBMaterial()
	{
		if (!m_aabbMaterial)
		{
			m_aabbMaterial = Nz::Material::New();
			m_aabbMaterial->EnableFaceCulling(false);
			m_aabbMaterial->EnableDepthBuffer(true);
			m_aabbMaterial->SetDiffuseColor(Nz::Color::Red);
			m_aabbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
		}

		return m_aabbMaterial;
	}

	Nz::MaterialRef DebugSystem::GetCollisionMaterial()
	{
		if (!m_collisionMaterial)
		{
			m_collisionMaterial = Nz::Material::New();
			m_collisionMaterial->EnableFaceCulling(false);
			m_collisionMaterial->EnableDepthBuffer(true);
			m_collisionMaterial->SetDiffuseColor(Nz::Color::Blue);
			m_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line);
		}

		return m_collisionMaterial;
	}

	Nz::MaterialRef DebugSystem::GetOBBMaterial()
	{
		if (!m_obbMaterial)
		{
			m_obbMaterial = Nz::Material::New();
			m_obbMaterial->EnableFaceCulling(false);
			m_obbMaterial->EnableDepthBuffer(true);
			m_obbMaterial->SetDiffuseColor(Nz::Color::Green);
			m_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
		}

		return m_obbMaterial;
	}

	SystemIndex DebugSystem::systemIndex;
}
<commit_msg>Sdk/DebugSystem: Fix some warnings<commit_after>// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequisites.hpp

#include <NDK/Systems/DebugSystem.hpp>
#include <Nazara/Core/Primitive.hpp>
#include <Nazara/Graphics/Model.hpp>
#include <Nazara/Utility/IndexIterator.hpp>
#include <Nazara/Utility/Mesh.hpp>
#include <Nazara/Utility/StaticMesh.hpp>
#include <NDK/Components/CollisionComponent3D.hpp>
#include <NDK/Components/DebugComponent.hpp>
#include <NDK/Components/GraphicsComponent.hpp>
#include <NDK/Components/NodeComponent.hpp>

namespace Ndk
{
	namespace
	{
		class DebugRenderable : public Nz::InstancedRenderable
		{
			public:
				DebugRenderable(Ndk::Entity* owner, Nz::MaterialRef mat, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :
				m_entityOwner(owner),
				m_material(std::move(mat)),
				m_indexBuffer(std::move(indexBuffer)),
				m_vertexBuffer(std::move(vertexBuffer))
				{
					ResetMaterials(1);

					m_meshData.indexBuffer = m_indexBuffer;
					m_meshData.primitiveMode = Nz::PrimitiveMode_LineList;
					m_meshData.vertexBuffer = m_vertexBuffer;
				}

				void UpdateBoundingVolume(InstanceData* instanceData) const override
				{
				}

				void MakeBoundingVolume() const override
				{
					m_boundingVolume.MakeNull();
				}

			protected:
				Ndk::EntityHandle m_entityOwner;
				Nz::IndexBufferRef m_indexBuffer;
				Nz::MaterialRef m_material;
				Nz::MeshData m_meshData;
				Nz::VertexBufferRef m_vertexBuffer;
		};

		class AABBDebugRenderable : public DebugRenderable
		{
			public:
				using DebugRenderable::DebugRenderable;

				void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override
				{
					NazaraAssert(m_entityOwner, "DebugRenderable has no owner");

					const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();
					const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();

					Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity();
					transformMatrix.SetScale(entityGfx.GetBoundingVolume().aabb.GetLengths());
					transformMatrix.SetTranslation(entityGfx.GetBoundingVolume().aabb.GetCenter());

					renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);
				}
		};

		class OBBDebugRenderable : public DebugRenderable
		{
			public:
				using DebugRenderable::DebugRenderable;

				void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override
				{
					NazaraAssert(m_entityOwner, "DebugRenderable has no owner");

					const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();
					const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();

					Nz::Matrix4f transformMatrix = instanceData.transformMatrix;
					transformMatrix.ApplyScale(entityGfx.GetBoundingVolume().obb.localBox.GetLengths());

					renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);
				}
		};
	}

	/*!
	* \ingroup NDK
	* \class Ndk::DebugSystem
	* \brief NDK class that represents the debug system
	*
	* \remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent
	*/

	/*!
	* \brief Constructs an DebugSystem object by default
	*/
	DebugSystem::DebugSystem()
	{
		Requires<DebugComponent, GraphicsComponent>();
		SetUpdateOrder(1000); //< Update last
	}

	std::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh()
	{
		if (!m_boxMeshIndexBuffer)
		{
			std::array<Nz::UInt16, 24> indices = {
				{
					0, 1,
					1, 2,
					2, 3,
					3, 0,

					4, 5,
					5, 6,
					6, 7,
					7, 4,

					0, 4,
					1, 5,
					2, 6,
					3, 7
				}
			};

			m_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);
			m_boxMeshIndexBuffer->Fill(indices.data(), 0, Nz::UInt32(indices.size()));
		}

		if (!m_boxMeshVertexBuffer)
		{
			Nz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f);

			std::array<Nz::Vector3f, 8> positions = {
				{
					box.GetCorner(Nz::BoxCorner_FarLeftBottom),
					box.GetCorner(Nz::BoxCorner_NearLeftBottom),
					box.GetCorner(Nz::BoxCorner_NearRightBottom),
					box.GetCorner(Nz::BoxCorner_FarRightBottom),
					box.GetCorner(Nz::BoxCorner_FarLeftTop),
					box.GetCorner(Nz::BoxCorner_NearLeftTop),
					box.GetCorner(Nz::BoxCorner_NearRightTop),
					box.GetCorner(Nz::BoxCorner_FarRightTop)
				}
			};

			m_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, 0);
			m_boxMeshVertexBuffer->Fill(positions.data(), 0, Nz::UInt32(positions.size()));
		}

		return { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer };
	}

	void DebugSystem::OnEntityValidation(Entity* entity, bool /*justAdded*/)
	{
		static constexpr int DebugDrawOrder = 1'000;

		DebugComponent& entityDebug = entity->GetComponent<DebugComponent>();
		GraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>();

		DebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags();
		DebugDrawFlags flags = entityDebug.GetFlags();

		DebugDrawFlags flagsToEnable = flags & ~enabledFlags;
		for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)
		{
			DebugDraw option = static_cast<DebugDraw>(i);
			if (flagsToEnable & option)
			{
				switch (option)
				{
					case DebugDraw::Collider3D:
					{
						const Nz::Boxf& obb = entityGfx.GetBoundingVolume().obb.localBox;

						Nz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity);
						renderable->SetPersistent(false);

						entityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter()), DebugDrawOrder);

						entityDebug.UpdateDebugRenderable(option, std::move(renderable));
						break;
					}

					case DebugDraw::GraphicsAABB:
					{
						auto indexVertexBuffers = GetBoxMesh();

						Nz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);
						renderable->SetPersistent(false);

						entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);

						entityDebug.UpdateDebugRenderable(option, std::move(renderable));
						break;
					}

					case DebugDraw::GraphicsOBB:
					{
						auto indexVertexBuffers = GetBoxMesh();

						Nz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);
						renderable->SetPersistent(false);

						entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);

						entityDebug.UpdateDebugRenderable(option, std::move(renderable));
						break;
					}

					default:
						break;
				}
			}
		}

		DebugDrawFlags flagsToDisable = enabledFlags & ~flags;
		for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)
		{
			DebugDraw option = static_cast<DebugDraw>(i);
			if (flagsToDisable & option)
				entityGfx.Detach(entityDebug.GetDebugRenderable(option));
		}

		entityDebug.UpdateEnabledFlags(flags);
	}

	void DebugSystem::OnUpdate(float elapsedTime)
	{
		// Nothing to do
	}

	Nz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box)
	{
		Nz::MeshRef mesh = Nz::Mesh::New();
		mesh->CreateStatic();

		mesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths()));
		mesh->SetMaterialCount(1);

		Nz::ModelRef model = Nz::Model::New();
		model->SetMesh(mesh);
		model->SetMaterial(0, GetOBBMaterial());

		return model;
	}

	Nz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity)
	{
		if (entity->HasComponent<CollisionComponent3D>())
		{
			CollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>();
			const Nz::Collider3DRef& geom = entityCollision.GetGeom();

			std::vector<Nz::Vector3f> vertices;
			std::vector<std::size_t> indices;

			geom->ForEachPolygon([&](const float* polygonVertices, std::size_t vertexCount)
			{
				std::size_t firstIndex = vertices.size();

				for (std::size_t i = 0; i < vertexCount; ++i)
				{
					const float* vertexData = &polygonVertices[i * 3];
					vertices.emplace_back(vertexData[0], vertexData[1], vertexData[2]);
				}

				for (std::size_t i = 0; i < vertexCount - 1; ++i)
				{
					indices.push_back(firstIndex + i);
					indices.push_back(firstIndex + i + 1);
				}

				indices.push_back(firstIndex + vertexCount - 1);
				indices.push_back(firstIndex);
			});

			Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);
			Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly);

			Nz::IndexIterator indexPtr = indexMapper.begin();
			for (std::size_t index : indices)
				*indexPtr++ = static_cast<Nz::UInt32>(index);

			indexMapper.Unmap();

			Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0);
			vertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size()));

			Nz::MeshRef mesh = Nz::Mesh::New();
			mesh->CreateStatic();

			Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(mesh);
			subMesh->Create(vertexBuffer);
			subMesh->SetIndexBuffer(indexBuffer);
			subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList);
			subMesh->SetMaterialIndex(0);
			subMesh->GenerateAABB();

			mesh->SetMaterialCount(1);
			mesh->AddSubMesh(subMesh);

			Nz::ModelRef model = Nz::Model::New();
			model->SetMesh(mesh);
			model->SetMaterial(0, GetCollisionMaterial());

			return model;
		}
		else
			return nullptr;
	}

	Nz::MaterialRef DebugSystem::GetAABBMaterial()
	{
		if (!m_aabbMaterial)
		{
			m_aabbMaterial = Nz::Material::New();
			m_aabbMaterial->EnableFaceCulling(false);
			m_aabbMaterial->EnableDepthBuffer(true);
			m_aabbMaterial->SetDiffuseColor(Nz::Color::Red);
			m_aabbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
		}

		return m_aabbMaterial;
	}

	Nz::MaterialRef DebugSystem::GetCollisionMaterial()
	{
		if (!m_collisionMaterial)
		{
			m_collisionMaterial = Nz::Material::New();
			m_collisionMaterial->EnableFaceCulling(false);
			m_collisionMaterial->EnableDepthBuffer(true);
			m_collisionMaterial->SetDiffuseColor(Nz::Color::Blue);
			m_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line);
		}

		return m_collisionMaterial;
	}

	Nz::MaterialRef DebugSystem::GetOBBMaterial()
	{
		if (!m_obbMaterial)
		{
			m_obbMaterial = Nz::Material::New();
			m_obbMaterial->EnableFaceCulling(false);
			m_obbMaterial->EnableDepthBuffer(true);
			m_obbMaterial->SetDiffuseColor(Nz::Color::Green);
			m_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line);
		}

		return m_obbMaterial;
	}

	SystemIndex DebugSystem::systemIndex;
}
<|endoftext|>


<commit_before>/* This file is part of Zanshin Todo.

   Copyright 2008-2010 Kevin Ottens <ervin@kde.org>
   Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "mainwindow.h"

#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KIcon>
#include <KDE/KLocale>
#include <KDE/KMenuBar>

#include <QtGui/QDockWidget>
#include <QtGui/QHeaderView>

#include "actionlisteditor.h"
#include "configdialog.h"
#include "globaldefs.h"
#include "sidebar.h"

MainWindow::MainWindow(ModelStack *models, QWidget *parent)
    : KXmlGuiWindow(parent)
{
    setupSideBar(models);
    setupCentralWidget(models);
    setupActions();

    setupGUI(ToolBar | Keys | Save | Create);

    restoreColumnsState();

    actionCollection()->action("project_mode")->trigger();
}

void MainWindow::setupCentralWidget(ModelStack *models)
{
    m_editor = new ActionListEditor(models,
                                    m_sidebar->projectSelection(),
                                    m_sidebar->categoriesSelection(),
                                    actionCollection(),
                                    this);
    setCentralWidget(m_editor);
}

void MainWindow::setupSideBar(ModelStack *models)
{
    m_sidebar = new SideBar(models, actionCollection(), this);

    QDockWidget *dock = new QDockWidget(this);
    dock->setObjectName("SideBar");
    dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);
    dock->setWidget(m_sidebar);
    addDockWidget(Qt::LeftDockWidgetArea, dock);
}

void MainWindow::setupActions()
{
    KActionCollection *ac = actionCollection();

    KAction *action = ac->addAction(KStandardAction::ShowMenubar);
    connect(action, SIGNAL(toggled(bool)),
            menuBar(), SLOT(setVisible(bool)));

    QActionGroup *modeGroup = new QActionGroup(this);
    modeGroup->setExclusive(true);

    action = ac->addAction("project_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Project View"));
    action->setIcon(KIcon("view-pim-tasks"));
    action->setShortcut(Qt::CTRL | Qt::Key_P);
    action->setCheckable(true);
    action->setData(Zanshin::ProjectMode);
    modeGroup->addAction(action);

    action = ac->addAction("categories_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Categories View"));
    action->setIcon(KIcon("view-pim-notes"));
    action->setShortcut(Qt::CTRL | Qt::Key_O);
    action->setCheckable(true);
    action->setData(Zanshin::CategoriesMode);
    modeGroup->addAction(action);

    ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog()));
    ac->addAction(KStandardAction::Quit, this, SLOT(close()));
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    saveColumnsState();
    KXmlGuiWindow::closeEvent(event);
}

void MainWindow::saveAutoSaveSettings()
{
    saveColumnsState();
    KXmlGuiWindow::saveAutoSaveSettings();
}

void MainWindow::saveColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->saveColumnsState(cg);
}

void MainWindow::restoreColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->restoreColumnsState(cg);
}

void MainWindow::onModeSwitch()
{
    KAction *action = static_cast<KAction*>(sender());
    m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());
    m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());
}

void MainWindow::showConfigDialog()
{
    ConfigDialog dialog(this);
    dialog.exec();
}
<commit_msg>Bring up the settings dialog on first run<commit_after>/* This file is part of Zanshin Todo.

   Copyright 2008-2010 Kevin Ottens <ervin@kde.org>
   Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "mainwindow.h"

#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KIcon>
#include <KDE/KLocale>
#include <KDE/KMenuBar>

#include <QtCore/QTimer>
#include <QtGui/QDockWidget>
#include <QtGui/QHeaderView>

#include "actionlisteditor.h"
#include "configdialog.h"
#include "globaldefs.h"
#include "sidebar.h"

MainWindow::MainWindow(ModelStack *models, QWidget *parent)
    : KXmlGuiWindow(parent)
{
    setupSideBar(models);
    setupCentralWidget(models);
    setupActions();

    setupGUI(ToolBar | Keys | Save | Create);

    restoreColumnsState();

    actionCollection()->action("project_mode")->trigger();

    KConfigGroup config(KGlobal::config(), "General");
    if (config.readEntry("firstRun", true)) {
        QTimer::singleShot(0, this, SLOT(showConfigDialog()));
        config.writeEntry("firstRun", false);
    }
}

void MainWindow::setupCentralWidget(ModelStack *models)
{
    m_editor = new ActionListEditor(models,
                                    m_sidebar->projectSelection(),
                                    m_sidebar->categoriesSelection(),
                                    actionCollection(),
                                    this);
    setCentralWidget(m_editor);
}

void MainWindow::setupSideBar(ModelStack *models)
{
    m_sidebar = new SideBar(models, actionCollection(), this);

    QDockWidget *dock = new QDockWidget(this);
    dock->setObjectName("SideBar");
    dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);
    dock->setWidget(m_sidebar);
    addDockWidget(Qt::LeftDockWidgetArea, dock);
}

void MainWindow::setupActions()
{
    KActionCollection *ac = actionCollection();

    KAction *action = ac->addAction(KStandardAction::ShowMenubar);
    connect(action, SIGNAL(toggled(bool)),
            menuBar(), SLOT(setVisible(bool)));

    QActionGroup *modeGroup = new QActionGroup(this);
    modeGroup->setExclusive(true);

    action = ac->addAction("project_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Project View"));
    action->setIcon(KIcon("view-pim-tasks"));
    action->setShortcut(Qt::CTRL | Qt::Key_P);
    action->setCheckable(true);
    action->setData(Zanshin::ProjectMode);
    modeGroup->addAction(action);

    action = ac->addAction("categories_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Categories View"));
    action->setIcon(KIcon("view-pim-notes"));
    action->setShortcut(Qt::CTRL | Qt::Key_O);
    action->setCheckable(true);
    action->setData(Zanshin::CategoriesMode);
    modeGroup->addAction(action);

    ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog()));
    ac->addAction(KStandardAction::Quit, this, SLOT(close()));
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    saveColumnsState();
    KXmlGuiWindow::closeEvent(event);
}

void MainWindow::saveAutoSaveSettings()
{
    saveColumnsState();
    KXmlGuiWindow::saveAutoSaveSettings();
}

void MainWindow::saveColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->saveColumnsState(cg);
}

void MainWindow::restoreColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->restoreColumnsState(cg);
}

void MainWindow::onModeSwitch()
{
    KAction *action = static_cast<KAction*>(sender());
    m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());
    m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());
}

void MainWindow::showConfigDialog()
{
    ConfigDialog dialog(this);
    dialog.exec();
}
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;
	int C = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){

				cout << Temp << endl << endl << endl << flush;
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ','){
				C++;
				mapArray[X][Y] = stoi(Temp.substr(F,i-F));
				cout << mapArray[X][Y] << "  " << flush;
				X++;
				F = i + 1;
			}
		}
		Y++;
		X = 0;
				cout << "C = " << C << flush;
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<commit_msg>Work in progress<commit_after>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;
	int C = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){

				cout << endl << endl << endl << flush;
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ','){
				C++;
				mapArray[X][Y] = stoi(Temp.substr(F,i-F));
				cout << mapArray[X][Y] << "  " << flush;
				X++;
				F = i + 1;
			}
		}
		Y++;
		X = 0;
		F = 0;
				cout << "\nC = " << C << flush;
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<|endoftext|>


<commit_before>/* This file is part of Zanshin Todo.

   Copyright 2008-2010 Kevin Ottens <ervin@kde.org>
   Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "mainwindow.h"

#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KIcon>
#include <KDE/KLocale>

#include <QtGui/QDockWidget>
#include <QtGui/QHeaderView>

#include "actionlisteditor.h"
#include "globaldefs.h"
#include "sidebar.h"

MainWindow::MainWindow(ModelStack *models, QWidget *parent)
    : KXmlGuiWindow(parent)
{
    setupSideBar(models);
    setupCentralWidget(models);
    setupActions();

    setupGUI(ToolBar | Keys | Save | Create);

    restoreColumnsState();

    actionCollection()->action("project_mode")->trigger();
}

void MainWindow::setupCentralWidget(ModelStack *models)
{
    m_editor = new ActionListEditor(models,
                                    m_sidebar->projectSelection(),
                                    m_sidebar->categoriesSelection(),
                                    actionCollection(),
                                    this);
    setCentralWidget(m_editor);
}

void MainWindow::setupSideBar(ModelStack *models)
{
    m_sidebar = new SideBar(models, actionCollection(), this);

    QDockWidget *dock = new QDockWidget(this);
    dock->setObjectName("SideBar");
    dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);
    dock->setWidget(m_sidebar);
    addDockWidget(Qt::LeftDockWidgetArea, dock);
}

void MainWindow::setupActions()
{
    KActionCollection *ac = actionCollection();

    QActionGroup *modeGroup = new QActionGroup(this);
    modeGroup->setExclusive(true);

    KAction *action = ac->addAction("project_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Project View"));
    action->setIcon(KIcon("view-pim-tasks"));
    action->setShortcut(Qt::CTRL | Qt::Key_P);
    action->setCheckable(true);
    action->setData(Zanshin::ProjectMode);
    modeGroup->addAction(action);

    action = ac->addAction("categories_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Categories View"));
    action->setIcon(KIcon("view-pim-notes"));
    action->setShortcut(Qt::CTRL | Qt::Key_O);
    action->setCheckable(true);
    action->setData(Zanshin::CategoriesMode);
    modeGroup->addAction(action);

    ac->addAction(KStandardAction::Quit, this, SLOT(close()));
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    saveColumnsState();
    KXmlGuiWindow::closeEvent(event);
}

void MainWindow::saveAutoSaveSettings()
{
    saveColumnsState();
    KXmlGuiWindow::saveAutoSaveSettings();
}

void MainWindow::saveColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->saveColumnsState(cg);
}

void MainWindow::restoreColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->restoreColumnsState(cg);
}

void MainWindow::onModeSwitch()
{
    KAction *action = static_cast<KAction*>(sender());
    m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());
    m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());
}
<commit_msg>Allow to hide the main menu.<commit_after>/* This file is part of Zanshin Todo.

   Copyright 2008-2010 Kevin Ottens <ervin@kde.org>
   Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program 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 General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "mainwindow.h"

#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KConfigGroup>
#include <KDE/KIcon>
#include <KDE/KLocale>
#include <KDE/KMenuBar>

#include <QtGui/QDockWidget>
#include <QtGui/QHeaderView>

#include "actionlisteditor.h"
#include "globaldefs.h"
#include "sidebar.h"

MainWindow::MainWindow(ModelStack *models, QWidget *parent)
    : KXmlGuiWindow(parent)
{
    setupSideBar(models);
    setupCentralWidget(models);
    setupActions();

    setupGUI(ToolBar | Keys | Save | Create);

    restoreColumnsState();

    actionCollection()->action("project_mode")->trigger();
}

void MainWindow::setupCentralWidget(ModelStack *models)
{
    m_editor = new ActionListEditor(models,
                                    m_sidebar->projectSelection(),
                                    m_sidebar->categoriesSelection(),
                                    actionCollection(),
                                    this);
    setCentralWidget(m_editor);
}

void MainWindow::setupSideBar(ModelStack *models)
{
    m_sidebar = new SideBar(models, actionCollection(), this);

    QDockWidget *dock = new QDockWidget(this);
    dock->setObjectName("SideBar");
    dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);
    dock->setWidget(m_sidebar);
    addDockWidget(Qt::LeftDockWidgetArea, dock);
}

void MainWindow::setupActions()
{
    KActionCollection *ac = actionCollection();

    KAction *action = ac->addAction(KStandardAction::ShowMenubar);
    connect(action, SIGNAL(toggled(bool)),
            menuBar(), SLOT(setVisible(bool)));

    QActionGroup *modeGroup = new QActionGroup(this);
    modeGroup->setExclusive(true);

    action = ac->addAction("project_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Project View"));
    action->setIcon(KIcon("view-pim-tasks"));
    action->setShortcut(Qt::CTRL | Qt::Key_P);
    action->setCheckable(true);
    action->setData(Zanshin::ProjectMode);
    modeGroup->addAction(action);

    action = ac->addAction("categories_mode", this, SLOT(onModeSwitch()));
    action->setText(i18n("Categories View"));
    action->setIcon(KIcon("view-pim-notes"));
    action->setShortcut(Qt::CTRL | Qt::Key_O);
    action->setCheckable(true);
    action->setData(Zanshin::CategoriesMode);
    modeGroup->addAction(action);

    ac->addAction(KStandardAction::Quit, this, SLOT(close()));
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    saveColumnsState();
    KXmlGuiWindow::closeEvent(event);
}

void MainWindow::saveAutoSaveSettings()
{
    saveColumnsState();
    KXmlGuiWindow::saveAutoSaveSettings();
}

void MainWindow::saveColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->saveColumnsState(cg);
}

void MainWindow::restoreColumnsState()
{
    KConfigGroup cg = autoSaveConfigGroup();
    m_editor->restoreColumnsState(cg);
}

void MainWindow::onModeSwitch()
{
    KAction *action = static_cast<KAction*>(sender());
    m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());
    m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());
}
<|endoftext|>