<commit_before>/*
 * Copyright 2015 Cloudius Systems
 */

#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "tests/test-utils.hh"

struct conversation_state {
    service::storage_proxy proxy;
    cql3::query_processor qp;
    service::client_state client_state;
    service::query_state query_state;
    cql3::query_options& options;

    conversation_state(distributed<database>& db, const sstring& ks_name)
        : proxy(db)
        , qp(proxy, db)
        , client_state(service::client_state::for_internal_calls())
        , query_state(client_state)
        , options(cql3::query_options::DEFAULT)
    {
        client_state.set_keyspace(ks_name);
    }

    auto execute_cql(const sstring& text) {
        return qp.process(text, query_state, options);
    }
};

static const sstring ks_name = "ks";
static const sstring table_name = "cf";

static future<> require_column_has_value(distributed<database>& ddb, const sstring& ks_name, const sstring& table_name,
    std::vector<boost::any> pk, std::vector<boost::any> ck, const sstring& column_name, boost::any expected)
{
    auto& db = ddb.local();
    auto ks = db.find_keyspace(ks_name);
    assert(ks != nullptr);
    auto cf = ks->find_column_family(table_name);
    assert(cf != nullptr);
    auto schema = cf->_schema;
    auto pkey = schema->partition_key_type->serialize_value_deep(pk);
    auto dk = dht::global_partitioner().decorate_key(pkey);
    auto shard = db.shard_of(dk._token);
    return ddb.invoke_on(shard, [pkey = std::move(pkey),
                                 ck = std::move(ck),
                                 ks_name = std::move(ks_name),
                                 column_name = std::move(column_name),
                                 expected = std::move(expected),
                                 table_name = std::move(table_name)] (database& db) {
        auto ks = db.find_keyspace(ks_name);
        assert(ks != nullptr);
        auto cf = ks->find_column_family(table_name);
        assert(cf != nullptr);
        auto schema = cf->_schema;
        auto p = cf->find_partition(pkey);
        assert(p != nullptr);
        auto row = p->find_row(schema->clustering_key_type->serialize_value_deep(ck));
        assert(row != nullptr);
        auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
        assert(col_def != nullptr);
        auto i = row->find(col_def->id);
        if (i == row->end()) {
            assert(((void)"column not set", 0));
        }
        bytes actual;
        if (!col_def->type->is_multi_cell()) {
            auto cell = i->second.as_atomic_cell();
            assert(cell.is_live());
            actual = { cell.value().begin(), cell.value().end() };
        } else {
            auto cell = i->second.as_collection_mutation();
            auto type = dynamic_pointer_cast<collection_type_impl>(col_def->type);
            actual = type->to_value(type->deserialize_mutation_form(cell.data), 3);
        }
        assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
        row->find(col_def->id);
    });
}

SEASTAR_TEST_CASE(test_create_keyspace_statement) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    return db->start().then([state] {
        return state->execute_cql("create keyspace ks with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };").discard_result();
    }).finally([db] {
        return db->stop().finally([db] {});
    });
}

SEASTAR_TEST_CASE(test_insert_statement) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    // CQL: create table cf (p1 varchar, c1 int, r1 int, PRIMARY KEY (p1, c1));
    return db->start().then([db] {
        return db->invoke_on_all([] (database& db) {
            keyspace ks;
            auto cf_schema = make_lw_shared(schema(ks_name, table_name,
                {{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type));
            ks.column_families.emplace(table_name, column_family(cf_schema));
            db.keyspaces.emplace(ks_name, std::move(ks));
        });
    }).then([state, db] {
            return state->execute_cql("insert into cf (p1, c1, r1) values ('key1', 1, 100);").discard_result();
        }).then([state, db] {
            return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {1}, "r1", 100);
        }).then([state, db] {
            return state->execute_cql("update cf set r1 = 66 where p1 = 'key1' and c1 = 1;").discard_result();
        }).then([state, db] {
            return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {1}, "r1", 66);
        }).then([db] {
        return db->stop();
        }).then_wrapped([db] (future<> f) mutable {
        return make_ready_future<>();
    });
}

class rows_assertions {
    shared_ptr<transport::messages::result_message::rows> _rows;
public:
    rows_assertions(shared_ptr<transport::messages::result_message::rows> rows)
        : _rows(rows)
    { }

    rows_assertions with_size(size_t size) {
        auto row_count = _rows->rs().size();
        if (row_count != size) {
            BOOST_FAIL(sprint("Expected %d row(s) but got %d", size, row_count));
        }
        return {*this};
    }

    rows_assertions with_row(std::initializer_list<bytes_opt> values) {
        std::vector<bytes_opt> expected_row(values);
        for (auto&& row : _rows->rs().rows()) {
            if (row == expected_row) {
                return {*this};
            }
        }
        BOOST_FAIL("Expected row not found");
        return {*this};
    }
};

class result_msg_assertions {
    shared_ptr<transport::messages::result_message> _msg;
public:
    result_msg_assertions(shared_ptr<transport::messages::result_message> msg)
        : _msg(msg)
    { }

    rows_assertions is_rows() {
        auto rows = dynamic_pointer_cast<transport::messages::result_message::rows>(_msg);
        BOOST_REQUIRE(rows);
        return rows_assertions(rows);
    }
};

result_msg_assertions assert_that(shared_ptr<transport::messages::result_message> msg) {
    return result_msg_assertions(msg);
}

SEASTAR_TEST_CASE(test_select_statement) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    return db->start().then([db] {
        return db->invoke_on_all([] (database& db) {
            keyspace ks;
            // CQL: create table cf (p1 varchar, c1 int, c2 int, r1 int, PRIMARY KEY (p1, c1, c2));
            auto cf_schema = make_lw_shared(schema(ks_name, table_name,
                {{"p1", utf8_type}},
                {{"c1", int32_type}, {"c2", int32_type}},
                {{"r1", int32_type}},
                {},
                utf8_type));
            ks.column_families.emplace(table_name, column_family(cf_schema));
            db.keyspaces.emplace(ks_name, std::move(ks));
        });
    }).then([state] {
        return state->execute_cql("insert into cf (p1, c1, c2, r1) values ('key1', 1, 2, 3);").discard_result();
    }).then([state] {
        return state->execute_cql("insert into cf (p1, c1, c2, r1) values ('key2', 1, 2, 13);").discard_result();
    }).then([state] {
        return state->execute_cql("insert into cf (p1, c1, c2, r1) values ('key3', 1, 2, 23);").discard_result();
    }).then([state] {
        // Test wildcard
        return state->execute_cql("select * from cf where p1 = 'key1' and c2 = 2 and c1 = 1;").then([] (auto msg) {
            assert_that(msg).is_rows()
                .with_size(1)
                .with_row({
                     {utf8_type->decompose(sstring("key1"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(3)}
                 });
        });
    }).then([state] {
        // Test with only regular column
        return state->execute_cql("select r1 from cf where p1 = 'key1' and c2 = 2 and c1 = 1;").then([] (auto msg) {
            assert_that(msg).is_rows()
                .with_size(1)
                .with_row({
                     {int32_type->decompose(3)}
                 });
        });
    }).then([state] {
        // Test full partition range, singular clustering range
        return state->execute_cql("select * from cf where c1 = 1 and c2 = 2 allow filtering;").then([] (auto msg) {
            assert_that(msg).is_rows()
                .with_size(3)
                .with_row({
                     {utf8_type->decompose(sstring("key1"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(3)}})
                .with_row({
                     {utf8_type->decompose(sstring("key2"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(13)}})
                .with_row({
                     {utf8_type->decompose(sstring("key3"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(23)}
                 });
        });
    }).finally([db] {
        return db->stop().finally([db] {});
    });
}

SEASTAR_TEST_CASE(test_map_insert_update) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    // CQL: create table cf (p1 varchar primary key, map1 map<int, int>);
    return db->start().then([db] {
        return db->invoke_on_all([] (database& db) {
            keyspace ks;
            auto my_map_type = map_type_impl::get_instance(int32_type, int32_type, true);
            auto cf_schema = make_lw_shared(schema(ks_name, table_name,
                {{"p1", utf8_type}}, {}, {{"map1", my_map_type}}, {}, utf8_type));
            ks.column_families.emplace(table_name, column_family(cf_schema));
            db.keyspaces.emplace(ks_name, std::move(ks));
        });
    }).then([state, db] {
            return state->execute_cql("insert into cf (p1, map1) values ('key1', { 1001: 2001 });").discard_result();
        }).then([state, db] {
            return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {},
                    "map1", map_type_impl::native_type({{1001, 2001}}));
        }).then([state, db] {
            return state->execute_cql("update cf set map1[1002] = 2002 where p1 = 'key1';").discard_result();
        }).then([state, db] {
            return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {},
                    "map1", map_type_impl::native_type({{1001, 2001}, {1002, 2002}}));
        }).then([state, db] {
            // overwrite an element
            return state->execute_cql("update cf set map1[1001] = 3001 where p1 = 'key1';").discard_result();
        }).then([state, db] {
            return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {},
                    "map1", map_type_impl::native_type({{1001, 3001}, {1002, 2002}}));
        }).then([db] {
            return db->stop();
        }).then_wrapped([db] (future<> f) mutable {
            return make_ready_future<>();
    });
}
<commit_msg>tests: fix cql_query_test indentation<commit_after>/*
 * Copyright 2015 Cloudius Systems
 */

#include "cql3/query_processor.hh"
#include "cql3/query_options.hh"
#include "core/distributed.hh"
#include "tests/test-utils.hh"

struct conversation_state {
    service::storage_proxy proxy;
    cql3::query_processor qp;
    service::client_state client_state;
    service::query_state query_state;
    cql3::query_options& options;

    conversation_state(distributed<database>& db, const sstring& ks_name)
        : proxy(db)
        , qp(proxy, db)
        , client_state(service::client_state::for_internal_calls())
        , query_state(client_state)
        , options(cql3::query_options::DEFAULT)
    {
        client_state.set_keyspace(ks_name);
    }

    auto execute_cql(const sstring& text) {
        return qp.process(text, query_state, options);
    }
};

static const sstring ks_name = "ks";
static const sstring table_name = "cf";

static future<> require_column_has_value(distributed<database>& ddb, const sstring& ks_name, const sstring& table_name,
    std::vector<boost::any> pk, std::vector<boost::any> ck, const sstring& column_name, boost::any expected)
{
    auto& db = ddb.local();
    auto ks = db.find_keyspace(ks_name);
    assert(ks != nullptr);
    auto cf = ks->find_column_family(table_name);
    assert(cf != nullptr);
    auto schema = cf->_schema;
    auto pkey = schema->partition_key_type->serialize_value_deep(pk);
    auto dk = dht::global_partitioner().decorate_key(pkey);
    auto shard = db.shard_of(dk._token);
    return ddb.invoke_on(shard, [pkey = std::move(pkey),
                                 ck = std::move(ck),
                                 ks_name = std::move(ks_name),
                                 column_name = std::move(column_name),
                                 expected = std::move(expected),
                                 table_name = std::move(table_name)] (database& db) {
        auto ks = db.find_keyspace(ks_name);
        assert(ks != nullptr);
        auto cf = ks->find_column_family(table_name);
        assert(cf != nullptr);
        auto schema = cf->_schema;
        auto p = cf->find_partition(pkey);
        assert(p != nullptr);
        auto row = p->find_row(schema->clustering_key_type->serialize_value_deep(ck));
        assert(row != nullptr);
        auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));
        assert(col_def != nullptr);
        auto i = row->find(col_def->id);
        if (i == row->end()) {
            assert(((void)"column not set", 0));
        }
        bytes actual;
        if (!col_def->type->is_multi_cell()) {
            auto cell = i->second.as_atomic_cell();
            assert(cell.is_live());
            actual = { cell.value().begin(), cell.value().end() };
        } else {
            auto cell = i->second.as_collection_mutation();
            auto type = dynamic_pointer_cast<collection_type_impl>(col_def->type);
            actual = type->to_value(type->deserialize_mutation_form(cell.data), 3);
        }
        assert(col_def->type->equal(actual, col_def->type->decompose(expected)));
        row->find(col_def->id);
    });
}

SEASTAR_TEST_CASE(test_create_keyspace_statement) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    return db->start().then([state] {
        return state->execute_cql("create keyspace ks with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };").discard_result();
    }).finally([db] {
        return db->stop().finally([db] {});
    });
}

SEASTAR_TEST_CASE(test_insert_statement) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    // CQL: create table cf (p1 varchar, c1 int, r1 int, PRIMARY KEY (p1, c1));
    return db->start().then([db] {
        return db->invoke_on_all([] (database& db) {
            keyspace ks;
            auto cf_schema = make_lw_shared(schema(ks_name, table_name,
                {{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type));
            ks.column_families.emplace(table_name, column_family(cf_schema));
            db.keyspaces.emplace(ks_name, std::move(ks));
        });
    }).then([state, db] {
        return state->execute_cql("insert into cf (p1, c1, r1) values ('key1', 1, 100);").discard_result();
    }).then([state, db] {
        return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {1}, "r1", 100);
    }).then([state, db] {
        return state->execute_cql("update cf set r1 = 66 where p1 = 'key1' and c1 = 1;").discard_result();
    }).then([state, db] {
        return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {1}, "r1", 66);
    }).then([db] {
        return db->stop();
    }).then_wrapped([db] (future<> f) mutable {
        return make_ready_future<>();
    });
}

class rows_assertions {
    shared_ptr<transport::messages::result_message::rows> _rows;
public:
    rows_assertions(shared_ptr<transport::messages::result_message::rows> rows)
        : _rows(rows)
    { }

    rows_assertions with_size(size_t size) {
        auto row_count = _rows->rs().size();
        if (row_count != size) {
            BOOST_FAIL(sprint("Expected %d row(s) but got %d", size, row_count));
        }
        return {*this};
    }

    rows_assertions with_row(std::initializer_list<bytes_opt> values) {
        std::vector<bytes_opt> expected_row(values);
        for (auto&& row : _rows->rs().rows()) {
            if (row == expected_row) {
                return {*this};
            }
        }
        BOOST_FAIL("Expected row not found");
        return {*this};
    }
};

class result_msg_assertions {
    shared_ptr<transport::messages::result_message> _msg;
public:
    result_msg_assertions(shared_ptr<transport::messages::result_message> msg)
        : _msg(msg)
    { }

    rows_assertions is_rows() {
        auto rows = dynamic_pointer_cast<transport::messages::result_message::rows>(_msg);
        BOOST_REQUIRE(rows);
        return rows_assertions(rows);
    }
};

result_msg_assertions assert_that(shared_ptr<transport::messages::result_message> msg) {
    return result_msg_assertions(msg);
}

SEASTAR_TEST_CASE(test_select_statement) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    return db->start().then([db] {
        return db->invoke_on_all([] (database& db) {
            keyspace ks;
            // CQL: create table cf (p1 varchar, c1 int, c2 int, r1 int, PRIMARY KEY (p1, c1, c2));
            auto cf_schema = make_lw_shared(schema(ks_name, table_name,
                {{"p1", utf8_type}},
                {{"c1", int32_type}, {"c2", int32_type}},
                {{"r1", int32_type}},
                {},
                utf8_type));
            ks.column_families.emplace(table_name, column_family(cf_schema));
            db.keyspaces.emplace(ks_name, std::move(ks));
        });
    }).then([state] {
        return state->execute_cql("insert into cf (p1, c1, c2, r1) values ('key1', 1, 2, 3);").discard_result();
    }).then([state] {
        return state->execute_cql("insert into cf (p1, c1, c2, r1) values ('key2', 1, 2, 13);").discard_result();
    }).then([state] {
        return state->execute_cql("insert into cf (p1, c1, c2, r1) values ('key3', 1, 2, 23);").discard_result();
    }).then([state] {
        // Test wildcard
        return state->execute_cql("select * from cf where p1 = 'key1' and c2 = 2 and c1 = 1;").then([] (auto msg) {
            assert_that(msg).is_rows()
                .with_size(1)
                .with_row({
                     {utf8_type->decompose(sstring("key1"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(3)}
                 });
        });
    }).then([state] {
        // Test with only regular column
        return state->execute_cql("select r1 from cf where p1 = 'key1' and c2 = 2 and c1 = 1;").then([] (auto msg) {
            assert_that(msg).is_rows()
                .with_size(1)
                .with_row({
                     {int32_type->decompose(3)}
                 });
        });
    }).then([state] {
        // Test full partition range, singular clustering range
        return state->execute_cql("select * from cf where c1 = 1 and c2 = 2 allow filtering;").then([] (auto msg) {
            assert_that(msg).is_rows()
                .with_size(3)
                .with_row({
                     {utf8_type->decompose(sstring("key1"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(3)}})
                .with_row({
                     {utf8_type->decompose(sstring("key2"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(13)}})
                .with_row({
                     {utf8_type->decompose(sstring("key3"))},
                     {int32_type->decompose(1)},
                     {int32_type->decompose(2)},
                     {int32_type->decompose(23)}
                 });
        });
    }).finally([db] {
        return db->stop().finally([db] {});
    });
}

SEASTAR_TEST_CASE(test_map_insert_update) {
    auto db = make_shared<distributed<database>>();
    auto state = make_shared<conversation_state>(*db, ks_name);

    // CQL: create table cf (p1 varchar primary key, map1 map<int, int>);
    return db->start().then([db] {
        return db->invoke_on_all([] (database& db) {
            keyspace ks;
            auto my_map_type = map_type_impl::get_instance(int32_type, int32_type, true);
            auto cf_schema = make_lw_shared(schema(ks_name, table_name,
                {{"p1", utf8_type}}, {}, {{"map1", my_map_type}}, {}, utf8_type));
            ks.column_families.emplace(table_name, column_family(cf_schema));
            db.keyspaces.emplace(ks_name, std::move(ks));
        });
    }).then([state, db] {
        return state->execute_cql("insert into cf (p1, map1) values ('key1', { 1001: 2001 });").discard_result();
    }).then([state, db] {
        return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {},
                "map1", map_type_impl::native_type({{1001, 2001}}));
    }).then([state, db] {
        return state->execute_cql("update cf set map1[1002] = 2002 where p1 = 'key1';").discard_result();
    }).then([state, db] {
        return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {},
                "map1", map_type_impl::native_type({{1001, 2001}, {1002, 2002}}));
    }).then([state, db] {
        // overwrite an element
        return state->execute_cql("update cf set map1[1001] = 3001 where p1 = 'key1';").discard_result();
    }).then([state, db] {
        return require_column_has_value(*db, ks_name, table_name, {sstring("key1")}, {},
                "map1", map_type_impl::native_type({{1001, 3001}, {1002, 2002}}));
    }).then([db] {
        return db->stop();
    }).then_wrapped([db] (future<> f) mutable {
        return make_ready_future<>();
    });
}
<|endoftext|>


<commit_before>
#include <QTextEdit>
#include <QScrollBar>
#include <QAbstractTextDocumentLayout>

#include "cmd.h"
#include "edith.h"
#include "form.h"
#include "pane.h"
#include "wd.h"
#include "../base/state.h"
#ifndef QT_NO_PRINTER
#ifdef QT50
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrinterInfo>
#include <QtPrintSupport/QPrintPreviewDialog>
#else
#include <QPrinter>
#include <QPrinterInfo>
#include <QPrintPreviewDialog>
#endif
#endif
// ---------------------------------------------------------------------
Edith::Edith(string n, string s, Form *f, Pane *p) : Child(n,s,f,p)
{
  type="edith";
  QTextEdit *w=new QTextEdit;
  widget=(QWidget*) w;
  QString qn=s2q(n);
  QStringList opt=qsplit(s);
  if (invalidopt(n,opt,"")) return;
  w->setObjectName(qn);
  childStyle(opt);
  w->setReadOnly(true);
}

// ---------------------------------------------------------------------
void Edith::cmd(string p,string v)
{
  QStringList opt=qsplit(v);
  if (p=="print") {
#ifndef QT_NO_PRINTER
    printPreview(config.Printer);
#endif
  } else if (p=="printpreview") {
#ifndef QT_NO_PRINTER
    QPrintPreviewDialog *dlg = new QPrintPreviewDialog(config.Printer, pform);
    dlg->setWindowTitle("Preview Document");
    QObject::connect(dlg,SIGNAL(paintRequested(QPrinter *)),this,SLOT(printPreview(QPrinter *)));
    dlg->exec();
    delete dlg;
    config.Printer->setPrintRange(QPrinter::AllPages);
#endif
  } else Child::set(p,v);
}

// ---------------------------------------------------------------------
string Edith::get(string p,string v)
{
  QTextEdit *w=(QTextEdit*) widget;
  string r;
  if (p=="property") {
    r+=string("readonly")+"\012"+ "scroll"+"\012"+ "select"+"\012"+ "text"+"\012"+ "wrap"+"\012";
    r+=Child::get(p,v);
  } else if (p=="text")
    r=q2s(w->toHtml());
  else if (p=="select"||p=="scroll") {
    QTextCursor c=w->textCursor();
    int b,e;
    b=c.selectionStart();
    e=c.selectionEnd();
    QScrollBar *vb=w->verticalScrollBar();
    if (p=="select")
      r=i2s(b)+" "+i2s(e);
    else
      r=i2s(vb->value());
  } else if (p=="readonly")
    r=i2s(w->isReadOnly());
  else if (p=="wrap")
    r=i2s(w->lineWrapMode());
  else
    r=Child::get(p,v);
  return r;
}

// ---------------------------------------------------------------------
void Edith::set(string p,string v)
{
  QTextEdit *w=(QTextEdit*) widget;
  QStringList opt=qsplit(v);
  QScrollBar *sb;

  int bgn,end,pos=0;

  if (p=="edit") {
    int s;
    if (opt.isEmpty())
      s=1;
    else
      s=c_strtoi(q2s(opt.at(0)));
    if (0==s) {
      if (!w->isReadOnly())  {
        QString t=w->toPlainText();
        w->setHtml(t);
        w->setReadOnly(1);
      }
    } else {
      if (w->isReadOnly()) {
        QString t=w->toHtml();
        w->setPlainText(t);
        w->setReadOnly(0);
      }
    }
  } else if (p=="text") {
    w->setHtml(s2q(remquotes(v)));
    w->setReadOnly(1);
  } else if (p=="select") {
    if (opt.isEmpty())
      w->selectAll();
    else {
      bgn=end=c_strtoi(q2s(opt.at(0)));
      if (opt.size()>1)
        end=c_strtoi(q2s(opt.at(1)));
      setselect(w,bgn,end);
    }
  } else if (p=="scroll") {
    if (opt.size()) {
      sb=w->verticalScrollBar();
      if (opt.at(0)=="min")
        pos=sb->minimum();
      else if (opt.at(0)=="max")
        pos=sb->maximum();
      else
        pos=c_strtoi(q2s(opt.at(0)));
      sb->setValue(pos);
    } else {
      error("set scroll requires additional parameters: " + id + " " + p);
      return;
    }
  } else if (p=="wrap") {
    w->setLineWrapMode((remquotes(v)!="0")?QTextEdit::WidgetWidth:QTextEdit::NoWrap);
  } else if (p=="find") {
    w->find(opt.at(0));
  } else Child::set(p,v);
}

// ---------------------------------------------------------------------
void Edith::setselect(QTextEdit *w, int bgn, int end)
{
  QTextCursor c = w->textCursor();
  c.setPosition(end,QTextCursor::MoveAnchor);
  c.setPosition(bgn,QTextCursor::KeepAnchor);
  w->setTextCursor(c);
}

// ---------------------------------------------------------------------
string Edith::state()
{
  QTextEdit *w=(QTextEdit*) widget;
  QTextCursor c=w->textCursor();
  int b,e;
  b=c.selectionStart();
  e=c.selectionEnd();
  QScrollBar *v=w->verticalScrollBar();
  string r;
  r+=spair(id,q2s(w->toHtml()));
  r+=spair(id+"_select",i2s(b)+" "+i2s(e));
  r+=spair(id+"_scroll",i2s(v->value()));
  return r;
}

#ifndef QT_NO_PRINTER
// ---------------------------------------------------------------------
void Edith::printPreview(QPrinter * printer)
{
  QTextEdit *w=(QTextEdit*) widget;
  QTextDocument *d=w->document()->clone();
#ifdef QT50
  d->documentLayout()->setPaintDevice((QPagedPaintDevice *)printer);
  d->setPageSize(QSizeF(printer->pageRect().size()));
  d->print((QPagedPaintDevice *)printer);
#else
  d->documentLayout()->setPaintDevice(printer);
  d->setPageSize(QSizeF(printer->pageRect().size()));
  d->print(printer);
#endif
  delete d;
}
#endif
<commit_msg>edith add baseurl<commit_after>
#include <QTextEdit>
#include <QScrollBar>
#include <QAbstractTextDocumentLayout>

#include "cmd.h"
#include "edith.h"
#include "form.h"
#include "pane.h"
#include "wd.h"
#include "../base/state.h"
#ifndef QT_NO_PRINTER
#ifdef QT50
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrinterInfo>
#include <QtPrintSupport/QPrintPreviewDialog>
#else
#include <QPrinter>
#include <QPrinterInfo>
#include <QPrintPreviewDialog>
#endif
#endif
// ---------------------------------------------------------------------
Edith::Edith(string n, string s, Form *f, Pane *p) : Child(n,s,f,p)
{
  type="edith";
  QTextEdit *w=new QTextEdit;
  widget=(QWidget*) w;
  QString qn=s2q(n);
  QStringList opt=qsplit(s);
  if (invalidopt(n,opt,"")) return;
  w->setObjectName(qn);
  childStyle(opt);
  w->setReadOnly(true);
}

// ---------------------------------------------------------------------
void Edith::cmd(string p,string v)
{
  QStringList opt=qsplit(v);
  if (p=="print") {
#ifndef QT_NO_PRINTER
    printPreview(config.Printer);
#endif
  } else if (p=="printpreview") {
#ifndef QT_NO_PRINTER
    QPrintPreviewDialog *dlg = new QPrintPreviewDialog(config.Printer, pform);
    dlg->setWindowTitle("Preview Document");
    QObject::connect(dlg,SIGNAL(paintRequested(QPrinter *)),this,SLOT(printPreview(QPrinter *)));
    dlg->exec();
    delete dlg;
    config.Printer->setPrintRange(QPrinter::AllPages);
#endif
  } else Child::set(p,v);
}

// ---------------------------------------------------------------------
string Edith::get(string p,string v)
{
  QTextEdit *w=(QTextEdit*) widget;
  string r;
  if (p=="property") {
    r+=string("readonly")+"\012"+ "scroll"+"\012"+ "select"+"\012"+ "text"+"\012"+ "wrap"+"\012";
    r+=Child::get(p,v);
  } else if (p=="text")
    r=q2s(w->toHtml());
  else if (p=="select"||p=="scroll") {
    QTextCursor c=w->textCursor();
    int b,e;
    b=c.selectionStart();
    e=c.selectionEnd();
    QScrollBar *vb=w->verticalScrollBar();
    if (p=="select")
      r=i2s(b)+" "+i2s(e);
    else
      r=i2s(vb->value());
  } else if (p=="readonly")
    r=i2s(w->isReadOnly());
  else if (p=="wrap")
    r=i2s(w->lineWrapMode());
  else
    r=Child::get(p,v);
  return r;
}

// ---------------------------------------------------------------------
void Edith::set(string p,string v)
{
  QTextEdit *w=(QTextEdit*) widget;
  QStringList opt=qsplit(v);
  QScrollBar *sb;

  int bgn,end,pos=0;

  if (p=="edit") {
    int s;
    if (opt.isEmpty())
      s=1;
    else
      s=c_strtoi(q2s(opt.at(0)));
    if (0==s) {
      if (!w->isReadOnly())  {
        QString t=w->toPlainText();
        w->setHtml(t);
        w->setReadOnly(1);
      }
    } else {
      if (w->isReadOnly()) {
        QString t=w->toHtml();
        w->setPlainText(t);
        w->setReadOnly(0);
      }
    }
  } else if (p=="text") {
    w->setHtml(s2q(remquotes(v)));
    w->setReadOnly(1);
  } else if (p=="select") {
    if (opt.isEmpty())
      w->selectAll();
    else {
      bgn=end=c_strtoi(q2s(opt.at(0)));
      if (opt.size()>1)
        end=c_strtoi(q2s(opt.at(1)));
      setselect(w,bgn,end);
    }
  } else if (p=="scroll") {
    if (opt.size()) {
      sb=w->verticalScrollBar();
      if (opt.at(0)=="min")
        pos=sb->minimum();
      else if (opt.at(0)=="max")
        pos=sb->maximum();
      else
        pos=c_strtoi(q2s(opt.at(0)));
      sb->setValue(pos);
    } else {
      error("set scroll requires additional parameters: " + id + " " + p);
      return;
    }
  } else if (p=="wrap") {
    w->setLineWrapMode((remquotes(v)!="0")?QTextEdit::WidgetWidth:QTextEdit::NoWrap);
  } else if (p=="find") {
    w->find(opt.at(0));
  } else if (p=="baseurl") {
    QString t = s2q(remquotes(v));
    QUrl baseUrl = QUrl(t);
    w->document()->setMetaInformation(QTextDocument::DocumentUrl, QUrl::fromLocalFile(baseUrl.toString()).toString());
  } else Child::set(p,v);
}

// ---------------------------------------------------------------------
void Edith::setselect(QTextEdit *w, int bgn, int end)
{
  QTextCursor c = w->textCursor();
  c.setPosition(end,QTextCursor::MoveAnchor);
  c.setPosition(bgn,QTextCursor::KeepAnchor);
  w->setTextCursor(c);
}

// ---------------------------------------------------------------------
string Edith::state()
{
  QTextEdit *w=(QTextEdit*) widget;
  QTextCursor c=w->textCursor();
  int b,e;
  b=c.selectionStart();
  e=c.selectionEnd();
  QScrollBar *v=w->verticalScrollBar();
  string r;
  r+=spair(id,q2s(w->toHtml()));
  r+=spair(id+"_select",i2s(b)+" "+i2s(e));
  r+=spair(id+"_scroll",i2s(v->value()));
  return r;
}

#ifndef QT_NO_PRINTER
// ---------------------------------------------------------------------
void Edith::printPreview(QPrinter * printer)
{
  QTextEdit *w=(QTextEdit*) widget;
  QTextDocument *d=w->document()->clone();
#ifdef QT50
  d->documentLayout()->setPaintDevice((QPagedPaintDevice *)printer);
  d->setPageSize(QSizeF(printer->pageRect().size()));
  d->print((QPagedPaintDevice *)printer);
#else
  d->documentLayout()->setPaintDevice(printer);
  d->setPageSize(QSizeF(printer->pageRect().size()));
  d->print(printer);
#endif
  delete d;
}
#endif
<|endoftext|>


<commit_before>#ifndef LUACPP_STATE_HPP
#define LUACPP_STATE_HPP

#include "luacpp/error.hpp"
#include <memory>
#include <silicium/config.hpp>
#include <silicium/memory_range.hpp>
#include <boost/system/error_code.hpp>
#include <boost/filesystem/path.hpp>

namespace lua
{
	struct lua_deleter
	{
		void operator()(lua_State *L) const BOOST_NOEXCEPT;
	};

	inline void lua_deleter::operator()(lua_State *L) const BOOST_NOEXCEPT
	{
		if (!L)
		{
			return;
		}
		lua_close(L);
	}

	typedef std::unique_ptr<lua_State, lua_deleter> state_ptr;

	state_ptr create_lua();

	inline state_ptr create_lua()
	{
		state_ptr lua(luaL_newstate());
		if (!lua)
		{
			throw std::bad_alloc();
		}
		return lua;
	}

	inline boost::system::error_code load_buffer(lua_State &L, Si::memory_range code, char const *name)
	{
		int rc = luaL_loadbuffer(&L, code.begin(), code.size(), name);
		if (rc != 0)
		{
			return boost::system::error_code(rc, get_lua_error_category());
		}
		return boost::system::error_code();
	}

	inline boost::system::error_code load_file(lua_State &L, boost::filesystem::path const &file)
	{
		int rc = luaL_loadfile(&L, file.c_str());
		if (rc != 0)
		{
			return boost::system::error_code(rc, get_lua_error_category());
		}
		return boost::system::error_code();
	}
}

#endif
<commit_msg>add debugging function print_stack<commit_after>#ifndef LUACPP_STATE_HPP
#define LUACPP_STATE_HPP

#include "luacpp/error.hpp"
#include <memory>
#include <silicium/config.hpp>
#include <silicium/memory_range.hpp>
#include <boost/system/error_code.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>

namespace lua
{
	struct lua_deleter
	{
		void operator()(lua_State *L) const BOOST_NOEXCEPT;
	};

	inline void lua_deleter::operator()(lua_State *L) const BOOST_NOEXCEPT
	{
		if (!L)
		{
			return;
		}
		lua_close(L);
	}

	typedef std::unique_ptr<lua_State, lua_deleter> state_ptr;

	state_ptr create_lua();

	inline state_ptr create_lua()
	{
		state_ptr lua(luaL_newstate());
		if (!lua)
		{
			throw std::bad_alloc();
		}
		return lua;
	}

	inline boost::system::error_code load_buffer(lua_State &L, Si::memory_range code, char const *name)
	{
		int rc = luaL_loadbuffer(&L, code.begin(), code.size(), name);
		if (rc != 0)
		{
			return boost::system::error_code(rc, get_lua_error_category());
		}
		return boost::system::error_code();
	}

	inline boost::system::error_code load_file(lua_State &L, boost::filesystem::path const &file)
	{
		int rc = luaL_loadfile(&L, file.c_str());
		if (rc != 0)
		{
			return boost::system::error_code(rc, get_lua_error_category());
		}
		return boost::system::error_code();
	}

	inline void print_stack(std::ostream &out, lua_State &L)
	{
		int size = lua_gettop(&L);
		out << "Size: " << size << '\n';
		for (int i = 1; i <= size; ++i)
		{
			out << "  " << i << ": " << lua_typename(&L, lua_type(&L, i)) << ' ';
			switch (lua_type(&L, i))
			{
			case LUA_TFUNCTION:
			case LUA_TUSERDATA:
			case LUA_TLIGHTUSERDATA:
				out << lua_topointer(&L, i);
				break;
			}
			out << '\n';
		}
	}
}

#endif
<|endoftext|>


<commit_before>#include "gb_sail.h"

GbSail::GbSail(uint8_t sensorPin, uint8_t sensorEnablePin,
               uint8_t motorPowerEnablePin, uint8_t motorIn1Pin,
               uint8_t motorIn2Pin, uint16_t min_sail_angle,
               uint16_t max_sail_angle, uint16_t trimRoutineMaxSeconds)
    : _sensorPin(sensorPin), _sensorEnablePin(sensorEnablePin),
      _mastGearSize(74), _sensorGearSize(36),
      _motorPowerEnablePin(motorPowerEnablePin), _motorIn1Pin(motorIn1Pin),
      _motorIn2Pin(motorIn2Pin), _min_sail_angle(min_sail_angle),
      _max_sail_angle(max_sail_angle),
      _trimRoutineMaxSeconds(trimRoutineMaxSeconds) {
  pinMode(_sensorPin, INPUT);
  pinMode(_sensorEnablePin, OUTPUT);
  pinMode(_motorPowerEnablePin, OUTPUT);
  digitalWrite(_motorPowerEnablePin, LOW);
  pinMode(_motorIn1Pin, OUTPUT);
  pinMode(_motorIn2Pin, OUTPUT);
}

// GbSail::GbTrimResult GbSail::Trim(uint16_t orderedSailPosition) {
//   unsigned long trimTimer;
//   uint16_t trimSeconds = 0;
//   uint16_t totalTrimSeconds = 0;
//   bool sailIsTrimming = true;
//
//   uint16_t sailPosition = GetSailPosition();
//   uint16_t tempSailPosition = sailPosition;
//   bool trimRoutineExceededMax = false;
//   bool sailNotMoving = false;
//
//   if ((abs(GetSailPosition() - orderedSailPosition)) > 4) { // sail out of
//   trim
//     trimTimer = millis(); // capture the time now
//     while (((sailPosition - orderedSailPosition) != 0) && sailIsTrimming) {
//
//       // Start rotating sail
//       if (sailPosition < orderedSailPosition) {
//         TurnCW();
//       } else {
//         TurnCCW();
//       }
//
//       // Every second, check if we're done, if we timed out or sail stopped
//       // moving
//       if ((unsigned long)(millis() - trimTimer) >= 1000) {
//         Serial.print(F("Check once per second: "));
//         Serial.println(trimTimer/1000);
//         trimTimer = millis(); // reset timer
//         totalTrimSeconds++;
//         if (totalTrimSeconds > _trimRoutineMaxSeconds) {
//           sailIsTrimming = false;
//           trimRoutineExceededMax = true;
//           Serial.println(F("trimRoutineExceededMax"));
//         }
//         sailPosition = GetSailPosition();
//         Serial.print(F("sailPosition = "));
//         Serial.print(sailPosition);
//         Serial.print(F(" | tempSailPosition = "));
//         Serial.println(tempSailPosition);
//         if (sailPosition == tempSailPosition) {
//           // sail hasn't moved in the last second
//           trimSeconds++;
//           if (trimSeconds > 10) { // sail hasn't moved in 10 seconds, bad!
//             sailIsTrimming = false;
//             sailNotMoving = true;
//             Serial.println(F("Sail not moving")); // what do we do? diags!
//           }
//         } else { // sail has moved
//           tempSailPosition = sailPosition;
//           trimSeconds = 0;
//           sailNotMoving = false;
//         }
//       }
//     }
//     Stop(); // sail is either in position or stuck
//   }
//   Serial.print(F("Done trimming. totalTrimSeconds = "));
//   Serial.println(totalTrimSeconds);
//
//   bool trimSuccess = (!sailNotMoving && !trimRoutineExceededMax);
//   GbTrimResult trimResult = {.success = trimSuccess,
//                              .sailNotMoving = sailNotMoving,
//                              .trimRoutineExceededMax =
//                              trimRoutineExceededMax};
//
//   return trimResult;
// }

GbSail::GbTrimResult GbSail::Trim(uint16_t orderedSailPosition) {

  uint32_t trimStartTime = millis();
  uint32_t sailMovingCheckTime = millis();
  bool sailIsTrimming = true;
  uint16_t sailPosition = GetSailPosition();
  Serial.print(F("Current position = "));
  Serial.println(sailPosition);
  uint16_t checkPosition = sailPosition;

  // Try to trim to the the ordered sail position
  while (!CloseEnough(sailPosition, orderedSailPosition) &&
         !TrimRoutineExceeded(trimStartTime) && sailIsTrimming) {
    TurnSailTowardsTarget(sailPosition, orderedSailPosition);
    sailPosition = GetSailPosition();
    if ((uint32_t)(millis() - sailMovingCheckTime) > 10000) {
      if (abs(sailPosition - checkPosition) < 2) {
        sailIsTrimming = false;
      } else {
        checkPosition = sailPosition;
        sailMovingCheckTime = millis();
      }
    }
  }
  Stop(); // sail is either in position or stuck
  GbTrimResult trimResult = {
      .success = CloseEnough(sailPosition, orderedSailPosition),
      .sailMoving = sailIsTrimming,
      .trimRoutineExceededMax = TrimRoutineExceeded(trimStartTime)};

  OutputTrimResults(trimResult);
  return trimResult;
}

void GbSail::OutputTrimResults(GbTrimResult trimResult) {
  Serial.print(F("Trim routine results: success = "));
  Serial.print(trimResult.success);
  Serial.print(F(" | sailMoving = "));
  Serial.print(trimResult.sailMoving);
  Serial.print(F(" | trimRoutineExceededMax = "));
  Serial.println(trimResult.trimRoutineExceededMax);
}

bool GbSail::CloseEnough(uint16_t sailPosition, uint16_t orderedSailPosition) {
  return abs(sailPosition - orderedSailPosition) < 2;
}

bool GbSail::TrimRoutineExceeded(uint32_t trimStartTime) {
  return ((trimStartTime / 1000) > _trimRoutineMaxSeconds);
}

void GbSail::TurnSailTowardsTarget(uint16_t sailPosition,
                                   uint16_t orderedSailPosition) {
  if (sailPosition < orderedSailPosition) {
    TurnCW();
  } else if (sailPosition > orderedSailPosition) {
    TurnCCW();
  } else {
    Stop();
  }
}

uint16_t GbSail::GetSailPosition() {
  uint16_t positionAnalogReading = GetPositionAnalogReading();
  float gearRatio = float(_mastGearSize) / _sensorGearSize;
  const uint8_t TURNS_IN_POT = 10;
  float readingRange = (float(gearRatio) / TURNS_IN_POT *
                        1023.0); // 1 mast turn = 1 * gearRatio pot turns
  const uint16_t CENTER_READING = 512;
  uint16_t minReading = int(CENTER_READING - (readingRange / 2.0));
  uint16_t maxReading = int(CENTER_READING + (readingRange / 2.0));
  uint16_t positionDegrees =
      map(positionAnalogReading, minReading, maxReading, 1, 359);
  return positionDegrees;
}

uint16_t GbSail::GetPositionAnalogReading() {
  digitalWrite(_sensorEnablePin, HIGH);
  uint16_t position;
  const uint8_t REPETITIONS = 10;
  uint16_t sum = 0;
  for (uint8_t i = 0; i < REPETITIONS; i++) {
    sum = sum + analogRead(_sensorPin);
    delay(1);
  }
  position = sum / REPETITIONS;
  return position;
}

void GbSail::TurnCW() {
  digitalWrite(_motorPowerEnablePin, LOW);
  digitalWrite(_motorIn1Pin, HIGH);
  digitalWrite(_motorIn2Pin, LOW);
}

void GbSail::TurnCCW() {
  digitalWrite(_motorPowerEnablePin, LOW);
  digitalWrite(_motorIn1Pin, LOW);
  digitalWrite(_motorIn2Pin, HIGH);
}

void GbSail::Stop() {
  Serial.println(F("Stopping the sail motor."));
  digitalWrite(_motorPowerEnablePin, HIGH);
  digitalWrite(_motorIn1Pin, LOW);
  digitalWrite(_motorIn2Pin, LOW);
}

bool GbSail::ValidOrders(uint16_t order) {
  if ((order > _max_sail_angle) || (order < _min_sail_angle)) {
    return false; // out-of-bouds
  } else {
    return true;
  }
}
<commit_msg>Remove old trim routine<commit_after>#include "gb_sail.h"

GbSail::GbSail(uint8_t sensorPin, uint8_t sensorEnablePin,
               uint8_t motorPowerEnablePin, uint8_t motorIn1Pin,
               uint8_t motorIn2Pin, uint16_t min_sail_angle,
               uint16_t max_sail_angle, uint16_t trimRoutineMaxSeconds)
    : _sensorPin(sensorPin), _sensorEnablePin(sensorEnablePin),
      _mastGearSize(74), _sensorGearSize(36),
      _motorPowerEnablePin(motorPowerEnablePin), _motorIn1Pin(motorIn1Pin),
      _motorIn2Pin(motorIn2Pin), _min_sail_angle(min_sail_angle),
      _max_sail_angle(max_sail_angle),
      _trimRoutineMaxSeconds(trimRoutineMaxSeconds) {
  pinMode(_sensorPin, INPUT);
  pinMode(_sensorEnablePin, OUTPUT);
  pinMode(_motorPowerEnablePin, OUTPUT);
  digitalWrite(_motorPowerEnablePin, LOW);
  pinMode(_motorIn1Pin, OUTPUT);
  pinMode(_motorIn2Pin, OUTPUT);
}

GbSail::GbTrimResult GbSail::Trim(uint16_t orderedSailPosition) {

  uint32_t trimStartTime = millis();
  uint32_t sailMovingCheckTime = millis();
  bool sailIsTrimming = true;
  uint16_t sailPosition = GetSailPosition();
  Serial.print(F("Current position = "));
  Serial.println(sailPosition);
  uint16_t checkPosition = sailPosition;

  // Try to trim to the the ordered sail position
  while (!CloseEnough(sailPosition, orderedSailPosition) &&
         !TrimRoutineExceeded(trimStartTime) && sailIsTrimming) {
    TurnSailTowardsTarget(sailPosition, orderedSailPosition);
    sailPosition = GetSailPosition();
    if ((uint32_t)(millis() - sailMovingCheckTime) > 10000) {
      if (abs(sailPosition - checkPosition) < 2) {
        sailIsTrimming = false;
      } else {
        checkPosition = sailPosition;
        sailMovingCheckTime = millis();
      }
    }
  }
  Stop(); // sail is either in position or stuck
  GbTrimResult trimResult = {
      .success = CloseEnough(sailPosition, orderedSailPosition),
      .sailMoving = sailIsTrimming,
      .trimRoutineExceededMax = TrimRoutineExceeded(trimStartTime)};

  OutputTrimResults(trimResult);
  return trimResult;
}

void GbSail::OutputTrimResults(GbTrimResult trimResult) {
  Serial.print(F("Trim routine results: success = "));
  Serial.print(trimResult.success);
  Serial.print(F(" | sailMoving = "));
  Serial.print(trimResult.sailMoving);
  Serial.print(F(" | trimRoutineExceededMax = "));
  Serial.println(trimResult.trimRoutineExceededMax);
}

bool GbSail::CloseEnough(uint16_t sailPosition, uint16_t orderedSailPosition) {
  return abs(sailPosition - orderedSailPosition) < 2;
}

bool GbSail::TrimRoutineExceeded(uint32_t trimStartTime) {
  return ((trimStartTime / 1000) > _trimRoutineMaxSeconds);
}

void GbSail::TurnSailTowardsTarget(uint16_t sailPosition,
                                   uint16_t orderedSailPosition) {
  if (sailPosition < orderedSailPosition) {
    TurnCW();
  } else if (sailPosition > orderedSailPosition) {
    TurnCCW();
  } else {
    Stop();
  }
}

uint16_t GbSail::GetSailPosition() {
  uint16_t positionAnalogReading = GetPositionAnalogReading();
  float gearRatio = float(_mastGearSize) / _sensorGearSize;
  const uint8_t TURNS_IN_POT = 10;
  float readingRange = (float(gearRatio) / TURNS_IN_POT *
                        1023.0); // 1 mast turn = 1 * gearRatio pot turns
  const uint16_t CENTER_READING = 512;
  uint16_t minReading = int(CENTER_READING - (readingRange / 2.0));
  uint16_t maxReading = int(CENTER_READING + (readingRange / 2.0));
  uint16_t positionDegrees =
      map(positionAnalogReading, minReading, maxReading, 1, 359);
  return positionDegrees;
}

uint16_t GbSail::GetPositionAnalogReading() {
  digitalWrite(_sensorEnablePin, HIGH);
  uint16_t position;
  const uint8_t REPETITIONS = 10;
  uint16_t sum = 0;
  for (uint8_t i = 0; i < REPETITIONS; i++) {
    sum = sum + analogRead(_sensorPin);
    delay(1);
  }
  position = sum / REPETITIONS;
  return position;
}

void GbSail::TurnCW() {
  digitalWrite(_motorPowerEnablePin, LOW);
  digitalWrite(_motorIn1Pin, HIGH);
  digitalWrite(_motorIn2Pin, LOW);
}

void GbSail::TurnCCW() {
  digitalWrite(_motorPowerEnablePin, LOW);
  digitalWrite(_motorIn1Pin, LOW);
  digitalWrite(_motorIn2Pin, HIGH);
}

void GbSail::Stop() {
  Serial.println(F("Stopping the sail motor."));
  digitalWrite(_motorPowerEnablePin, HIGH);
  digitalWrite(_motorIn1Pin, LOW);
  digitalWrite(_motorIn2Pin, LOW);
}

bool GbSail::ValidOrders(uint16_t order) {
  if ((order > _max_sail_angle) || (order < _min_sail_angle)) {
    return false; // out-of-bouds
  } else {
    return true;
  }
}
<|endoftext|>


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

#pragma hdrstop

#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
#include "languageoptions.hxx"
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <cjkoptions.hxx>
#endif
#ifndef _SVTOOLS_CTLOPTIONS_HXX
#include <ctloptions.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

// global ----------------------------------------------------------------------

namespace { struct ALMutex : public rtl::Static< ::osl::Mutex, ALMutex > {}; }

// class SvtLanguageOptions ----------------------------------------------------

SvtLanguageOptions::SvtLanguageOptions( sal_Bool _bDontLoad )
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    m_pCJKOptions = new SvtCJKOptions( _bDontLoad );
    m_pCTLOptions = new SvtCTLOptions( _bDontLoad );
    StartListening(*m_pCTLOptions);
}
//------------------------------------------------------------------------------
SvtLanguageOptions::~SvtLanguageOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    delete m_pCJKOptions;
    delete m_pCTLOptions;
}
//------------------------------------------------------------------------------
// CJK options -----------------------------------------------------------------
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCJKFontEnabled() const
{
    return m_pCJKOptions->IsCJKFontEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalTextEnabled() const
{
    return m_pCJKOptions->IsVerticalTextEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAsianTypographyEnabled() const
{
    return m_pCJKOptions->IsAsianTypographyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsJapaneseFindEnabled() const
{
    return m_pCJKOptions->IsJapaneseFindEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsRubyEnabled() const
{
    return m_pCJKOptions->IsRubyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsChangeCaseMapEnabled() const
{
    return m_pCJKOptions->IsChangeCaseMapEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsDoubleLinesEnabled() const
{
    return m_pCJKOptions->IsDoubleLinesEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsEmphasisMarksEnabled() const
{
    return m_pCJKOptions->IsEmphasisMarksEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalCallOutEnabled() const
{
    return m_pCJKOptions->IsVerticalCallOutEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetAll( sal_Bool _bSet )
{
    m_pCJKOptions->SetAll( _bSet );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAnyEnabled() const
{
    return m_pCJKOptions->IsAnyEnabled();
}
//------------------------------------------------------------------------------
// CTL options -----------------------------------------------------------------
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLFontEnabled( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLFontEnabled( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLFontEnabled() const
{
    return m_pCTLOptions->IsCTLFontEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLSequenceChecking( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLSequenceChecking( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLSequenceChecking() const
{
    return m_pCTLOptions->IsCTLSequenceChecking();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsReadOnly(SvtLanguageOptions::EOption eOption) const
{
    sal_Bool bReadOnly = sal_False;
    switch(eOption)
    {
        // cjk options
        case SvtLanguageOptions::E_CJKFONT          : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CJKFONT        ); break;
        case SvtLanguageOptions::E_VERTICALTEXT     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALTEXT   ); break;
        case SvtLanguageOptions::E_ASIANTYPOGRAPHY  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ASIANTYPOGRAPHY); break;
        case SvtLanguageOptions::E_JAPANESEFIND     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_JAPANESEFIND   ); break;
        case SvtLanguageOptions::E_RUBY             : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_RUBY           ); break;
        case SvtLanguageOptions::E_CHANGECASEMAP    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CHANGECASEMAP  ); break;
        case SvtLanguageOptions::E_DOUBLELINES      : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_DOUBLELINES    ); break;
        case SvtLanguageOptions::E_EMPHASISMARKS    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_EMPHASISMARKS  ); break;
        case SvtLanguageOptions::E_VERTICALCALLOUT  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALCALLOUT); break;
        case SvtLanguageOptions::E_ALLCJK           : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ALL            ); break;
        // ctl options
        case SvtLanguageOptions::E_CTLFONT              : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLFONT            ); break;
        case SvtLanguageOptions::E_CTLSEQUENCECHECKING  : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLSEQUENCECHECKING); break;
        case SvtLanguageOptions::E_CTLCURSORMOVEMENT    : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLCURSORMOVEMENT  ); break;
        case SvtLanguageOptions::E_CTLTEXTNUMERALS      : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLTEXTNUMERALS    ); break;
    }
    return bReadOnly;
}
/* -----------------30.04.2003 11:03-----------------

 --------------------------------------------------*/
void SvtLanguageOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    vos::OGuard aVclGuard( Application::GetSolarMutex() );
    Broadcast( rHint );
}

// -----------------------------------------------------------------------------
// returns for a language the scripttype
sal_uInt16 SvtLanguageOptions::GetScriptTypeOfLanguage( sal_uInt16 nLang )
{
    if( LANGUAGE_DONTKNOW == nLang )
        nLang = LANGUAGE_ENGLISH_US;
    else if( LANGUAGE_SYSTEM == nLang  )
        nLang = Application::GetSettings().GetLanguage();

    USHORT nScript;
    switch( nLang )
    {
        // CJK
        case LANGUAGE_CHINESE:
        case LANGUAGE_CHINESE_TRADITIONAL:
        case LANGUAGE_CHINESE_SIMPLIFIED:
        case LANGUAGE_CHINESE_HONGKONG:
        case LANGUAGE_CHINESE_SINGAPORE:
        case LANGUAGE_CHINESE_MACAU:
        case LANGUAGE_JAPANESE:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
            nScript = SCRIPTTYPE_ASIAN;
            break;

        // CTL
        case LANGUAGE_ARABIC:
        case LANGUAGE_ARABIC_SAUDI_ARABIA:
        case LANGUAGE_ARABIC_IRAQ:
        case LANGUAGE_ARABIC_EGYPT:
        case LANGUAGE_ARABIC_LIBYA:
        case LANGUAGE_ARABIC_ALGERIA:
        case LANGUAGE_ARABIC_MOROCCO:
        case LANGUAGE_ARABIC_TUNISIA:
        case LANGUAGE_ARABIC_OMAN:
        case LANGUAGE_ARABIC_YEMEN:
        case LANGUAGE_ARABIC_SYRIA:
        case LANGUAGE_ARABIC_JORDAN:
        case LANGUAGE_ARABIC_LEBANON:
        case LANGUAGE_ARABIC_KUWAIT:
        case LANGUAGE_ARABIC_UAE:
        case LANGUAGE_ARABIC_BAHRAIN:
        case LANGUAGE_ARABIC_QATAR:
        case LANGUAGE_HEBREW:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_VIETNAMESE: // not included in langtab.src?
            nScript = SCRIPTTYPE_COMPLEX;
            break;

// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_AFRIKAANS                  0x0436
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_ASSAMESE                   0x044D
#define LANGUAGE_AZERI                      0x002C
#define LANGUAGE_AZERI_LATIN                0x042C
#define LANGUAGE_AZERI_CYRILLIC             0x082C
#define LANGUAGE_BASQUE                     0x042D
#define LANGUAGE_BELARUSIAN                 0x0423
#define LANGUAGE_BENGALI                    0x0445
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KASHMIRI                   0x0460
#define LANGUAGE_KASHMIRI_INDIA             0x0860
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_LATVIAN                    0x0426
#define LANGUAGE_LITHUANIAN                 0x0427
#define LANGUAGE_LITHUANIAN_CLASSIC         0x0827
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_MALAY                      0x003E
#define LANGUAGE_MALAY_MALAYSIA             0x043E
#define LANGUAGE_MALAY_BRUNEI_DARUSSALAM    0x083E
#define LANGUAGE_MALAYALAM                  0x044C
#define LANGUAGE_MANIPURI                   0x0458
#define LANGUAGE_NEPALI                     0x0461
#define LANGUAGE_NEPALI_INDIA               0x0861
#define LANGUAGE_ORIYA                      0x0448
#define LANGUAGE_SANSKRIT                   0x044F
#define LANGUAGE_SERBIAN                    0x041A
#define LANGUAGE_SERBIAN_LATIN              0x081A
#define LANGUAGE_SERBIAN_CYRILLIC           0x0C1A
#define LANGUAGE_SINDHI                     0x0459
#define LANGUAGE_SWAHILI                    0x5041
#define LANGUAGE_TATAR                      0x0444
#define LANGUAGE_TURKISH                    0x041F
#define LANGUAGE_UKRAINIAN                  0x0422
#define LANGUAGE_UZBEK                      0x0043
#define LANGUAGE_UZBEK_LATIN                0x0443
#define LANGUAGE_UZBEK_CYRILLIC             0x0843
*/

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

#pragma hdrstop

#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
#include "languageoptions.hxx"
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <cjkoptions.hxx>
#endif
#ifndef _SVTOOLS_CTLOPTIONS_HXX
#include <ctloptions.hxx>
#endif
#ifndef _LANG_HXX
#include <tools/lang.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

// global ----------------------------------------------------------------------

namespace { struct ALMutex : public rtl::Static< ::osl::Mutex, ALMutex > {}; }

// class SvtLanguageOptions ----------------------------------------------------

SvtLanguageOptions::SvtLanguageOptions( sal_Bool _bDontLoad )
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    m_pCJKOptions = new SvtCJKOptions( _bDontLoad );
    m_pCTLOptions = new SvtCTLOptions( _bDontLoad );
    StartListening(*m_pCTLOptions);
}
//------------------------------------------------------------------------------
SvtLanguageOptions::~SvtLanguageOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( ALMutex::get() );

    delete m_pCJKOptions;
    delete m_pCTLOptions;
}
//------------------------------------------------------------------------------
// CJK options -----------------------------------------------------------------
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCJKFontEnabled() const
{
    return m_pCJKOptions->IsCJKFontEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalTextEnabled() const
{
    return m_pCJKOptions->IsVerticalTextEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAsianTypographyEnabled() const
{
    return m_pCJKOptions->IsAsianTypographyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsJapaneseFindEnabled() const
{
    return m_pCJKOptions->IsJapaneseFindEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsRubyEnabled() const
{
    return m_pCJKOptions->IsRubyEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsChangeCaseMapEnabled() const
{
    return m_pCJKOptions->IsChangeCaseMapEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsDoubleLinesEnabled() const
{
    return m_pCJKOptions->IsDoubleLinesEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsEmphasisMarksEnabled() const
{
    return m_pCJKOptions->IsEmphasisMarksEnabled();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsVerticalCallOutEnabled() const
{
    return m_pCJKOptions->IsVerticalCallOutEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetAll( sal_Bool _bSet )
{
    m_pCJKOptions->SetAll( _bSet );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsAnyEnabled() const
{
    return m_pCJKOptions->IsAnyEnabled();
}
//------------------------------------------------------------------------------
// CTL options -----------------------------------------------------------------
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLFontEnabled( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLFontEnabled( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLFontEnabled() const
{
    return m_pCTLOptions->IsCTLFontEnabled();
}
//------------------------------------------------------------------------------
void SvtLanguageOptions::SetCTLSequenceChecking( sal_Bool _bEnabled )
{
    m_pCTLOptions->SetCTLSequenceChecking( _bEnabled );
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsCTLSequenceChecking() const
{
    return m_pCTLOptions->IsCTLSequenceChecking();
}
//------------------------------------------------------------------------------
sal_Bool SvtLanguageOptions::IsReadOnly(SvtLanguageOptions::EOption eOption) const
{
    sal_Bool bReadOnly = sal_False;
    switch(eOption)
    {
        // cjk options
        case SvtLanguageOptions::E_CJKFONT          : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CJKFONT        ); break;
        case SvtLanguageOptions::E_VERTICALTEXT     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALTEXT   ); break;
        case SvtLanguageOptions::E_ASIANTYPOGRAPHY  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ASIANTYPOGRAPHY); break;
        case SvtLanguageOptions::E_JAPANESEFIND     : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_JAPANESEFIND   ); break;
        case SvtLanguageOptions::E_RUBY             : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_RUBY           ); break;
        case SvtLanguageOptions::E_CHANGECASEMAP    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_CHANGECASEMAP  ); break;
        case SvtLanguageOptions::E_DOUBLELINES      : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_DOUBLELINES    ); break;
        case SvtLanguageOptions::E_EMPHASISMARKS    : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_EMPHASISMARKS  ); break;
        case SvtLanguageOptions::E_VERTICALCALLOUT  : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_VERTICALCALLOUT); break;
        case SvtLanguageOptions::E_ALLCJK           : bReadOnly = m_pCJKOptions->IsReadOnly(SvtCJKOptions::E_ALL            ); break;
        // ctl options
        case SvtLanguageOptions::E_CTLFONT              : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLFONT            ); break;
        case SvtLanguageOptions::E_CTLSEQUENCECHECKING  : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLSEQUENCECHECKING); break;
        case SvtLanguageOptions::E_CTLCURSORMOVEMENT    : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLCURSORMOVEMENT  ); break;
        case SvtLanguageOptions::E_CTLTEXTNUMERALS      : bReadOnly = m_pCTLOptions->IsReadOnly(SvtCTLOptions::E_CTLTEXTNUMERALS    ); break;
    }
    return bReadOnly;
}
/* -----------------30.04.2003 11:03-----------------

 --------------------------------------------------*/
void SvtLanguageOptions::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    vos::OGuard aVclGuard( Application::GetSolarMutex() );
    Broadcast( rHint );
}

// -----------------------------------------------------------------------------
// returns for a language the scripttype
sal_uInt16 SvtLanguageOptions::GetScriptTypeOfLanguage( sal_uInt16 nLang )
{
    if( LANGUAGE_DONTKNOW == nLang )
        nLang = LANGUAGE_ENGLISH_US;
    else if( LANGUAGE_SYSTEM == nLang  )
        nLang = Application::GetSettings().GetLanguage();

    USHORT nScript;
    switch( nLang )
    {
        // CJK
        case LANGUAGE_CHINESE:
        case LANGUAGE_CHINESE_TRADITIONAL:
        case LANGUAGE_CHINESE_SIMPLIFIED:
        case LANGUAGE_CHINESE_HONGKONG:
        case LANGUAGE_CHINESE_SINGAPORE:
        case LANGUAGE_CHINESE_MACAU:
        case LANGUAGE_JAPANESE:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
        case LANGUAGE_USER_KOREAN_NORTH:
            nScript = SCRIPTTYPE_ASIAN;
            break;

        // CTL
        case LANGUAGE_ARABIC:
        case LANGUAGE_ARABIC_SAUDI_ARABIA:
        case LANGUAGE_ARABIC_IRAQ:
        case LANGUAGE_ARABIC_EGYPT:
        case LANGUAGE_ARABIC_LIBYA:
        case LANGUAGE_ARABIC_ALGERIA:
        case LANGUAGE_ARABIC_MOROCCO:
        case LANGUAGE_ARABIC_TUNISIA:
        case LANGUAGE_ARABIC_OMAN:
        case LANGUAGE_ARABIC_YEMEN:
        case LANGUAGE_ARABIC_SYRIA:
        case LANGUAGE_ARABIC_JORDAN:
        case LANGUAGE_ARABIC_LEBANON:
        case LANGUAGE_ARABIC_KUWAIT:
        case LANGUAGE_ARABIC_UAE:
        case LANGUAGE_ARABIC_BAHRAIN:
        case LANGUAGE_ARABIC_QATAR:
        case LANGUAGE_HEBREW:
        case LANGUAGE_MARATHI:
        case LANGUAGE_PUNJABI:
        case LANGUAGE_GUJARATI:
        case LANGUAGE_HINDI:
        case LANGUAGE_KANNADA:
        case LANGUAGE_TAMIL:
        case LANGUAGE_TELUGU:
        case LANGUAGE_THAI:
        case LANGUAGE_URDU:
        case LANGUAGE_URDU_PAKISTAN:
        case LANGUAGE_URDU_INDIA:
        case LANGUAGE_VIETNAMESE: // not included in langtab.src?
            nScript = SCRIPTTYPE_COMPLEX;
            break;

// currently not knowing scripttype - defaultet to LATIN:
/*
#define LANGUAGE_AFRIKAANS                  0x0436
#define LANGUAGE_ARMENIAN                   0x042B
#define LANGUAGE_ASSAMESE                   0x044D
#define LANGUAGE_AZERI                      0x002C
#define LANGUAGE_AZERI_LATIN                0x042C
#define LANGUAGE_AZERI_CYRILLIC             0x082C
#define LANGUAGE_BASQUE                     0x042D
#define LANGUAGE_BELARUSIAN                 0x0423
#define LANGUAGE_BENGALI                    0x0445
#define LANGUAGE_INDONESIAN                 0x0421
#define LANGUAGE_KASHMIRI                   0x0460
#define LANGUAGE_KASHMIRI_INDIA             0x0860
#define LANGUAGE_KAZAK                      0x043F
#define LANGUAGE_KONKANI                    0x0457
#define LANGUAGE_LATVIAN                    0x0426
#define LANGUAGE_LITHUANIAN                 0x0427
#define LANGUAGE_LITHUANIAN_CLASSIC         0x0827
#define LANGUAGE_MACEDONIAN                 0x042F
#define LANGUAGE_MALAY                      0x003E
#define LANGUAGE_MALAY_MALAYSIA             0x043E
#define LANGUAGE_MALAY_BRUNEI_DARUSSALAM    0x083E
#define LANGUAGE_MALAYALAM                  0x044C
#define LANGUAGE_MANIPURI                   0x0458
#define LANGUAGE_NEPALI                     0x0461
#define LANGUAGE_NEPALI_INDIA               0x0861
#define LANGUAGE_ORIYA                      0x0448
#define LANGUAGE_SANSKRIT                   0x044F
#define LANGUAGE_SERBIAN                    0x041A
#define LANGUAGE_SERBIAN_LATIN              0x081A
#define LANGUAGE_SERBIAN_CYRILLIC           0x0C1A
#define LANGUAGE_SINDHI                     0x0459
#define LANGUAGE_SWAHILI                    0x5041
#define LANGUAGE_TATAR                      0x0444
#define LANGUAGE_TURKISH                    0x041F
#define LANGUAGE_UKRAINIAN                  0x0422
#define LANGUAGE_UZBEK                      0x0043
#define LANGUAGE_UZBEK_LATIN                0x0443
#define LANGUAGE_UZBEK_CYRILLIC             0x0843
*/

    default:
        nScript = SCRIPTTYPE_LATIN;
        break;
    }
    return nScript;
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>// this library is public domain. enjoy!
// www.ladyada.net/learn/sensors/thermocouple

//#include <Wire.h>
#include <avr/pgmspace.h>
#include <WProgram.h>
#include <util/delay.h>
#include <stdlib.h>

#include "MAX6675.h"

MAX6675::MAX6675(int8_t SCLK, int8_t CS, int8_t MISO) {
  sclk = SCLK;
  cs = CS;
  miso = MISO;

  //define pin modes
  pinMode(cs, OUTPUT);
  pinMode(sclk, OUTPUT);
  pinMode(miso, INPUT);

  digitalWrite(cs, HIGH);
}

float MAX6675::readCelsius(void) {

  uint16_t v;

  digitalWrite(cs, LOW);
  delay(1);

  v = spiread();
  v <<= 8;
  v |= spiread();

  v >>= 3;

  digitalWrite(cs, HIGH);

  return v*0.25;
}

float MAX6675::readFarenheit(void) {
  return readCelsius() * 9.0/5.0 + 32;
}

byte MAX6675::spiread(void) {
  int i;
  byte d = 0;

  for (i=7; i>=0; i--)
  {
    digitalWrite(sclk, LOW);
    delay(1);
    if (digitalRead(miso)) {
      //set the bit to 0 no matter what
      d |= (1 << i);
    }

    digitalWrite(sclk, HIGH);
    delay(1);
  }

  return d;
}
<commit_msg>Turned delay()'s that use the millis() interrupt, into _delay_ms()'s that are 'hardcoded' so that this code can be called from an interrupt<commit_after>// this library is public domain. enjoy!
// www.ladyada.net/learn/sensors/thermocouple

//#include <Wire.h>
#include <avr/pgmspace.h>
#include <WProgram.h>
#include <util/delay.h>
#include <stdlib.h>

#include "MAX6675.h"

MAX6675::MAX6675(int8_t SCLK, int8_t CS, int8_t MISO) {
  sclk = SCLK;
  cs = CS;
  miso = MISO;

  //define pin modes
  pinMode(cs, OUTPUT);
  pinMode(sclk, OUTPUT);
  pinMode(miso, INPUT);

  digitalWrite(cs, HIGH);
}

float MAX6675::readCelsius(void) {

  uint16_t v;

  digitalWrite(cs, LOW);
  _delay_ms(1);

  v = spiread();
  v <<= 8;
  v |= spiread();

  v >>= 3;

  digitalWrite(cs, HIGH);

  return v*0.25;
}

float MAX6675::readFarenheit(void) {
  return readCelsius() * 9.0/5.0 + 32;
}

byte MAX6675::spiread(void) {
  int i;
  byte d = 0;

  for (i=7; i>=0; i--)
  {
    digitalWrite(sclk, LOW);
    _delay_ms(1);
    if (digitalRead(miso)) {
      //set the bit to 0 no matter what
      d |= (1 << i);
    }

    digitalWrite(sclk, HIGH);
    _delay_ms(1);
  }

  return d;
}
<|endoftext|>


<commit_before>// @(#)root/base:$Id$
// Author: Rene Brun   12/12/94

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TAttFill.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TVirtualX.h"
#include "TVirtualPadEditor.h"
#include "TColor.h"

ClassImp(TAttFill)

//______________________________________________________________________________
/* Begin_Html

Fill Area Attributes class

This class is used (in general by secondary inheritance)
by many other classes (graphics, histograms). It holds all the fill area
attributes.

Fill Area attributes

Fill Area attributes are:

Fill Area color.

Fill Area style.

Fill Area color

The fill area color is a color index (integer) pointing in the ROOT
color table.
The fill area color of any class inheriting from <tt>TAttFill</tt> can
be changed using the method <tt>SetFillColor</tt> and retrieved using the
method <tt>GetFillColor</tt>.
The following table shows the first 50 default colors.
End_Html
Begin_Macro(source)
{
   TCanvas *c = new TCanvas("c","Fill Area colors",0,0,500,200);
   c.DrawColorTable();
   return c;
}
End_Macro

Begin_Html

The ROOT Color Wheel.

The wheel contains the recommended 216 colors to be used in web applications.
The colors in the Color Wheel are created by TColor::CreateColorWheel.

Using this color set for your text, background or graphics will give your
application a consistent appearance across different platforms and browsers.

Colors are grouped by hue, the aspect most important in human perception
Touching color chips have the same hue, but with different brightness and vividness.

Colors of slightly different hues clash. If you intend to display
colors of the same hue together, you should pick them from the same group.

Each color chip is identified by a mnemonic (eg kYellow) and a number.
The keywords, kRed, kBlue, kYellow, kPink, etc are defined in the header file Rtypes.h
that is included in all ROOT other header files. We strongly recommend to use these keywords
in your code instead of hardcoded color numbers, eg:

   myObject.SetFillColor(kRed);
   myObject.SetFillColor(kYellow-10);
   myLine.SetLineColor(kMagenta+2);

End_Html
Begin_Macro(source)
{
   TColorWheel *w = new TColorWheel();
   w->Draw();
   return w->GetCanvas();
}
End_Macro

Begin_Html

Special case forcing black&white output.

If the current style fill area color is set to 0, then ROOT will force
a black&white output for all objects with a fill area defined and independently
of the object fill style.

Fill Area style

The fill area style defines the pattern used to fill a polygon.
The fill area style of any class inheriting from <tt>TAttFill</tt> can
be changed using the method <tt>SetFillStyle</tt> and retrieved using the
method <tt>GetFillStyle</tt>.

Conventions for fill styles:

  0    : hollow

  1001 : Solid

  2001 : hatch style

  3000+pattern_number (see below)

  For TPad only:

  4000 :the window is transparent.

  4000 to 4100 the window is 100% transparent to 100% opaque.

pattern_number can have any value from 1 to 25 (see table), or any
value from 100 to 999. For the latest the numbering convention is the following:

      pattern_number = ijk      (FillStyle = 3ijk)

      i (1-9) : specify the space between each hatch
                1 = 1/2mm  9 = 6mm

      j (0-9) : specify angle between 0 and 90 degrees
                0 = 0
                1 = 10
                2 = 20
                3 = 30
                4 = 45
                5 = Not drawn
                6 = 60
                7 = 70
                8 = 80
                9 = 90

      k (0-9) : specify angle between 90 and 180 degrees
                0 = 180
                1 = 170
                2 = 160
                3 = 150
                4 = 135
                5 = Not drawn
                6 = 120
                7 = 110
                8 = 100
                9 = 90

The following table shows the list of pattern styles.
The first table displays the 25 fixed patterns. They cannot be
customized unlike the hatches displayed in the second table which be
customized using:

 <tt>gStyle->SetHatchesSpacing()</tt> to define the spacing between hatches.

 <tt>gStyle->SetHatchesLineWidth()</tt> to define the hatches line width.

End_Html
Begin_Macro(source)
fillpatterns.C
End_Macro */

//______________________________________________________________________________
TAttFill::TAttFill()
{
   // AttFill default constructor.
   // Default fill attributes are taking from the current style

   if (!gStyle) return;
   fFillColor = gStyle->GetFillColor();
   fFillStyle = gStyle->GetFillStyle();
}

//______________________________________________________________________________
TAttFill::TAttFill(Color_t color, Style_t style)
{
   // AttFill normal constructor.
   // color Fill Color
   // style Fill Style

   fFillColor = color;
   fFillStyle = style;
}

//______________________________________________________________________________
TAttFill::~TAttFill()
{
   // AttFill destructor.
}

//______________________________________________________________________________
void TAttFill::Copy(TAttFill &attfill) const
{
   // Copy this fill attributes to a new TAttFill.

   attfill.fFillColor  = fFillColor;
   attfill.fFillStyle  = fFillStyle;
}

//______________________________________________________________________________
void TAttFill::Modify()
{
   // Change current fill area attributes if necessary.

   if (!gPad) return;
   if (!gPad->IsBatch()) {
      gVirtualX->SetFillColor(fFillColor);
      gVirtualX->SetFillStyle(fFillStyle);
   }

   gPad->SetAttFillPS(fFillColor,fFillStyle);
}

//______________________________________________________________________________
void TAttFill::ResetAttFill(Option_t *)
{
   // Reset this fill attributes to default values.

   fFillColor = 1;
   fFillStyle = 0;
}

//______________________________________________________________________________
void TAttFill::SaveFillAttributes(ostream &out, const char *name, Int_t coldef, Int_t stydef)
{
    // Save fill attributes as C++ statement(s) on output stream out

   if (fFillColor != coldef) {
      if (fFillColor > 228) {
         TColor::SaveColor(out, fFillColor);
         out<<"   "<<name<<"->SetFillColor(ci);" << endl;
      } else
         out<<"   "<<name<<"->SetFillColor("<<fFillColor<<");"<<endl;
   }
   if (fFillStyle != stydef) {
      out<<"   "<<name<<"->SetFillStyle("<<fFillStyle<<");"<<endl;
   }
}

//______________________________________________________________________________
void TAttFill::SetFillAttributes()
{
   // Invoke the DialogCanvas Fill attributes.

   TVirtualPadEditor::UpdateFillAttributes(fFillColor,fFillStyle);
}
<commit_msg>- Complete help<commit_after>// @(#)root/base:$Id$
// Author: Rene Brun   12/12/94

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "TAttFill.h"
#include "TVirtualPad.h"
#include "TStyle.h"
#include "TVirtualX.h"
#include "TVirtualPadEditor.h"
#include "TColor.h"

ClassImp(TAttFill)

//______________________________________________________________________________
/* Begin_Html

Fill Area Attributes class

This class is used (in general by secondary inheritance)
by many other classes (graphics, histograms). It holds all the fill area
attributes.

Fill Area attributes

Fill Area attributes are:

Fill Area color.

Fill Area style.

Fill Area color

The fill area color is a color index (integer) pointing in the ROOT
color table.
The fill area color of any class inheriting from <tt>TAttFill</tt> can
be changed using the method <tt>SetFillColor</tt> and retrieved using the
method <tt>GetFillColor</tt>.
The following table shows the first 50 default colors.
End_Html
Begin_Macro(source)
{
   TCanvas *c = new TCanvas("c","Fill Area colors",0,0,500,200);
   c.DrawColorTable();
   return c;
}
End_Macro

Begin_Html

The ROOT Color Wheel.

The wheel contains the recommended 216 colors to be used in web applications.
The colors in the Color Wheel are created by TColor::CreateColorWheel.

Using this color set for your text, background or graphics will give your
application a consistent appearance across different platforms and browsers.

Colors are grouped by hue, the aspect most important in human perception
Touching color chips have the same hue, but with different brightness and vividness.

Colors of slightly different hues clash. If you intend to display
colors of the same hue together, you should pick them from the same group.

Each color chip is identified by a mnemonic (eg kYellow) and a number.
The keywords, kRed, kBlue, kYellow, kPink, etc are defined in the header file Rtypes.h
that is included in all ROOT other header files. We strongly recommend to use these keywords
in your code instead of hardcoded color numbers, eg:

   myObject.SetFillColor(kRed);
   myObject.SetFillColor(kYellow-10);
   myLine.SetLineColor(kMagenta+2);

End_Html
Begin_Macro(source)
{
   TColorWheel *w = new TColorWheel();
   w->Draw();
   return w->GetCanvas();
}
End_Macro

Begin_Html

Special case forcing black&white output.

If the current style fill area color is set to 0, then ROOT will force
a black&white output for all objects with a fill area defined and independently
of the object fill style.

Fill Area style

The fill area style defines the pattern used to fill a polygon.
The fill area style of any class inheriting from <tt>TAttFill</tt> can
be changed using the method <tt>SetFillStyle</tt> and retrieved using the
method <tt>GetFillStyle</tt>.

Conventions for fill styles:

  0    : hollow

  1001 : Solid

  2001 : hatch style

  3000+pattern_number (see below)

  For TPad only:

  4000 :the window is transparent.

  4000 to 4100 the window is 100% transparent to 100% opaque.

      The pad transparency is visible in binary outputs files like gif, jpg, png etc ..
      but not in vector graphics output files like PS, PDF and SVG.

pattern_number can have any value from 1 to 25 (see table), or any
value from 100 to 999. For the latest the numbering convention is the following:

      pattern_number = ijk      (FillStyle = 3ijk)

      i (1-9) : specify the space between each hatch
                1 = 1/2mm  9 = 6mm

      j (0-9) : specify angle between 0 and 90 degrees
                0 = 0
                1 = 10
                2 = 20
                3 = 30
                4 = 45
                5 = Not drawn
                6 = 60
                7 = 70
                8 = 80
                9 = 90

      k (0-9) : specify angle between 90 and 180 degrees
                0 = 180
                1 = 170
                2 = 160
                3 = 150
                4 = 135
                5 = Not drawn
                6 = 120
                7 = 110
                8 = 100
                9 = 90

The following table shows the list of pattern styles.
The first table displays the 25 fixed patterns. They cannot be
customized unlike the hatches displayed in the second table which be
customized using:

 <tt>gStyle->SetHatchesSpacing()</tt> to define the spacing between hatches.

 <tt>gStyle->SetHatchesLineWidth()</tt> to define the hatches line width.

End_Html
Begin_Macro(source)
fillpatterns.C
End_Macro */

//______________________________________________________________________________
TAttFill::TAttFill()
{
   // AttFill default constructor.
   // Default fill attributes are taking from the current style

   if (!gStyle) return;
   fFillColor = gStyle->GetFillColor();
   fFillStyle = gStyle->GetFillStyle();
}

//______________________________________________________________________________
TAttFill::TAttFill(Color_t color, Style_t style)
{
   // AttFill normal constructor.
   // color Fill Color
   // style Fill Style

   fFillColor = color;
   fFillStyle = style;
}

//______________________________________________________________________________
TAttFill::~TAttFill()
{
   // AttFill destructor.
}

//______________________________________________________________________________
void TAttFill::Copy(TAttFill &attfill) const
{
   // Copy this fill attributes to a new TAttFill.

   attfill.fFillColor  = fFillColor;
   attfill.fFillStyle  = fFillStyle;
}

//______________________________________________________________________________
void TAttFill::Modify()
{
   // Change current fill area attributes if necessary.

   if (!gPad) return;
   if (!gPad->IsBatch()) {
      gVirtualX->SetFillColor(fFillColor);
      gVirtualX->SetFillStyle(fFillStyle);
   }

   gPad->SetAttFillPS(fFillColor,fFillStyle);
}

//______________________________________________________________________________
void TAttFill::ResetAttFill(Option_t *)
{
   // Reset this fill attributes to default values.

   fFillColor = 1;
   fFillStyle = 0;
}

//______________________________________________________________________________
void TAttFill::SaveFillAttributes(ostream &out, const char *name, Int_t coldef, Int_t stydef)
{
    // Save fill attributes as C++ statement(s) on output stream out

   if (fFillColor != coldef) {
      if (fFillColor > 228) {
         TColor::SaveColor(out, fFillColor);
         out<<"   "<<name<<"->SetFillColor(ci);" << endl;
      } else
         out<<"   "<<name<<"->SetFillColor("<<fFillColor<<");"<<endl;
   }
   if (fFillStyle != stydef) {
      out<<"   "<<name<<"->SetFillStyle("<<fFillStyle<<");"<<endl;
   }
}

//______________________________________________________________________________
void TAttFill::SetFillAttributes()
{
   // Invoke the DialogCanvas Fill attributes.

   TVirtualPadEditor::UpdateFillAttributes(fFillColor,fFillStyle);
}
<|endoftext|>