<commit_before>#include <gtest/gtest.h>

#include <dsn/service_api_c.h>
#include <dsn/service_api_cpp.h>

#include "meta_service.h"
#include "server_state.h"
#include "meta_service_test_app.h"

dsn_message_t create_corresponding_receive(dsn_message_t request_msg)
{
    return dsn_msg_copy(request_msg, true);
}

class fake_receiver_meta_service: public dsn::replication::meta_service
{
public:
    fake_receiver_meta_service(): dsn::replication::meta_service() {}
    virtual ~fake_receiver_meta_service() {}
    virtual void reply_message(dsn_message_t request, dsn_message_t response) override
    {
        uint64_t ptr;
        dsn::unmarshall(request, ptr);
        reply_context* ctx = reinterpret_cast<reply_context*>(ptr);
        ctx->response = create_corresponding_receive(response);
        dsn_msg_add_ref(ctx->response);

        //release the response
        dsn_msg_add_ref(response);
        dsn_msg_release_ref(response);

        ctx->e.notify();
    }
};

#define fake_create_app(state, request_data) \
    fake_rpc_call(RPC_CM_CREATE_APP, \
        LPC_META_STATE_NORMAL, \
        state, \
        &dsn::replication::server_state::create_app, \
        request_data)

#define fake_drop_app(state, request_data) \
    fake_rpc_call(RPC_CM_DROP_APP, \
        LPC_META_STATE_NORMAL, \
        state, \
        &dsn::replication::server_state::drop_app, \
        request_data)

#define fake_wait_rpc(context, response_data) do {\
    context->e.wait();\
    ::dsn::unmarshall(context->response, response_data);\
    dsn_msg_release_ref(context->response);\
} while(0)

void meta_service_test_app::data_definition_op_test()
{
    std::shared_ptr<fake_receiver_meta_service> svc = std::make_shared<fake_receiver_meta_service>();
    dsn::error_code ec = svc->remote_storage_initialize();
    ASSERT_EQ(ec, dsn::ERR_OK);

    svc->_state->initialize(svc.get(), svc->_cluster_root+"/apps");
    ec = svc->_state->initialize_data_structure();
    ASSERT_EQ(ec, dsn::ERR_OK);

    svc->_started = true;

    std::shared_ptr<reply_context> result, result2, result3;
    dsn::replication::configuration_create_app_request create_request;
    dsn::replication::configuration_create_app_response create_response;

    //normal create app
    create_request.app_name = "test_app2";
    create_request.options.app_type = "simple_kv";
    create_request.options.partition_count = 10;
    create_request.options.replica_count = 3;
    create_request.options.success_if_exist = false;

    result = fake_create_app(svc->_state.get(), create_request);
    fake_wait_rpc(result, create_response);
    ASSERT_EQ(create_response.appid, 2);
    ASSERT_EQ(create_response.err, dsn::ERR_OK);
    //first wait the table to create
    ASSERT_TRUE(svc->_state->spin_wait_creating(30));

    //create a exist app, with success flags false
    result = fake_create_app(svc->_state.get(), create_request);
    fake_wait_rpc(result, create_response);
    ASSERT_TRUE(create_response.err==dsn::ERR_INVALID_PARAMETERS);

    //create same app with success flags true, but different params
    create_request.options.partition_count += 10;
    create_request.options.app_type = "rrdb";
    create_request.options.success_if_exist = true;
    result = fake_create_app(svc->_state.get(), create_request);
    fake_wait_rpc(result, create_response);
    ASSERT_EQ( create_response.err, dsn::ERR_INVALID_PARAMETERS);

    //drop current app
    dsn::replication::configuration_drop_app_request drop_request;
    dsn::replication::configuration_drop_app_response drop_response;
    drop_request.app_name = "test_app2";
    drop_request.options.success_if_not_exist = false;

    result = fake_drop_app(svc->_state.get(), drop_request);
    //a drop request immediately after the first request
    result2 = fake_drop_app(svc->_state.get(), drop_request);
    //try to create a app with same name when it is dropping
    result3 = fake_create_app(svc->_state.get(), create_request);

    result->e.wait();
    result2->e.wait();
    result3->e.wait();

    ::dsn::unmarshall(result->response, drop_response);
    dsn_msg_release_ref(result->response);
    ASSERT_EQ(drop_response.err, dsn::ERR_OK);

    ::dsn::unmarshall(result2->response, drop_response);
    dsn_msg_release_ref(result2->response);
    ASSERT_TRUE(drop_response.err == dsn::ERR_APP_NOT_EXIST || drop_response.err == dsn::ERR_BUSY_DROPPING);

    ::dsn::unmarshall(result3->response, create_response);
    dsn_msg_release_ref(result3->response);
    ASSERT_TRUE(create_response.err==dsn::ERR_BUSY_DROPPING || create_response.err == dsn::ERR_OK);

    int created_successfully = 2;
    //in case that the previous create request succeed
    if (create_response.err == dsn::ERR_OK)
    {
        created_successfully = 3;
        drop_request.options.success_if_not_exist = true;
        do {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            result = fake_drop_app(svc->_state.get(), drop_request);
            fake_wait_rpc(result, drop_response);
        } while (drop_response.err != dsn::ERR_OK);
    }

    //currently "test_app2" is dropped, let's drop it again
    drop_request.options.success_if_not_exist = false;
    result = fake_drop_app(svc->_state.get(), drop_request);
    fake_wait_rpc(result, drop_response);
    ASSERT_EQ(dsn::ERR_APP_NOT_EXIST, drop_response.err);

    //now let's recreating the app with the same name
    result = fake_create_app(svc->_state.get(), create_request);
    create_request.options.success_if_exist = true;
    result2 = fake_create_app(svc->_state.get(), create_request);

    result->e.wait();
    result2->e.wait();

    ::dsn::unmarshall(result->response, create_response);
    dsn_msg_release_ref(result->response);
    ASSERT_EQ(create_response.err, dsn::ERR_OK);
    ASSERT_EQ(create_response.appid, created_successfully+1);

    ::dsn::unmarshall(result2->response, create_response);
    dsn_msg_release_ref(result2->response);
    ASSERT_EQ(create_response.err, dsn::ERR_BUSY_CREATING);

    ASSERT_TRUE(svc->_state->spin_wait_creating(30));

    //finally list the apps
    dsn::replication::configuration_list_apps_request list_request;
    dsn::replication::configuration_list_apps_response list_response;

    list_request.status = dsn::app_status::AS_AVAILABLE;
    svc->_state->list_apps(list_request, list_response);
    ASSERT_EQ(list_response.err, dsn::ERR_OK);
    ASSERT_EQ(list_response.infos.size(), 2);

    for (dsn::app_info& info: list_response.infos) {
        if (info.app_id == created_successfully+1) {
            ASSERT_EQ(info.app_name, create_request.app_name);
            ASSERT_EQ(info.app_type, create_request.options.app_type);
            ASSERT_EQ(info.partition_count, create_request.options.partition_count);
            ASSERT_EQ(info.status, dsn::app_status::AS_AVAILABLE);
        }
    }
}
<commit_msg>- fix json encoding for missing int64 support - add clone_content parameter to dsn_msg_copy<commit_after>#include <gtest/gtest.h>

#include <dsn/service_api_c.h>
#include <dsn/service_api_cpp.h>

#include "meta_service.h"
#include "server_state.h"
#include "meta_service_test_app.h"

dsn_message_t create_corresponding_receive(dsn_message_t request_msg)
{
    return dsn_msg_copy(request_msg, true, true);
}

class fake_receiver_meta_service: public dsn::replication::meta_service
{
public:
    fake_receiver_meta_service(): dsn::replication::meta_service() {}
    virtual ~fake_receiver_meta_service() {}
    virtual void reply_message(dsn_message_t request, dsn_message_t response) override
    {
        uint64_t ptr;
        dsn::unmarshall(request, ptr);
        reply_context* ctx = reinterpret_cast<reply_context*>(ptr);
        ctx->response = create_corresponding_receive(response);
        dsn_msg_add_ref(ctx->response);

        //release the response
        dsn_msg_add_ref(response);
        dsn_msg_release_ref(response);

        ctx->e.notify();
    }
};

#define fake_create_app(state, request_data) \
    fake_rpc_call(RPC_CM_CREATE_APP, \
        LPC_META_STATE_NORMAL, \
        state, \
        &dsn::replication::server_state::create_app, \
        request_data)

#define fake_drop_app(state, request_data) \
    fake_rpc_call(RPC_CM_DROP_APP, \
        LPC_META_STATE_NORMAL, \
        state, \
        &dsn::replication::server_state::drop_app, \
        request_data)

#define fake_wait_rpc(context, response_data) do {\
    context->e.wait();\
    ::dsn::unmarshall(context->response, response_data);\
    dsn_msg_release_ref(context->response);\
} while(0)

void meta_service_test_app::data_definition_op_test()
{
    std::shared_ptr<fake_receiver_meta_service> svc = std::make_shared<fake_receiver_meta_service>();
    dsn::error_code ec = svc->remote_storage_initialize();
    ASSERT_EQ(ec, dsn::ERR_OK);

    svc->_state->initialize(svc.get(), svc->_cluster_root+"/apps");
    ec = svc->_state->initialize_data_structure();
    ASSERT_EQ(ec, dsn::ERR_OK);

    svc->_started = true;

    std::shared_ptr<reply_context> result, result2, result3;
    dsn::replication::configuration_create_app_request create_request;
    dsn::replication::configuration_create_app_response create_response;

    //normal create app
    create_request.app_name = "test_app2";
    create_request.options.app_type = "simple_kv";
    create_request.options.partition_count = 10;
    create_request.options.replica_count = 3;
    create_request.options.success_if_exist = false;

    result = fake_create_app(svc->_state.get(), create_request);
    fake_wait_rpc(result, create_response);
    ASSERT_EQ(create_response.appid, 2);
    ASSERT_EQ(create_response.err, dsn::ERR_OK);
    //first wait the table to create
    ASSERT_TRUE(svc->_state->spin_wait_creating(30));

    //create a exist app, with success flags false
    result = fake_create_app(svc->_state.get(), create_request);
    fake_wait_rpc(result, create_response);
    ASSERT_TRUE(create_response.err==dsn::ERR_INVALID_PARAMETERS);

    //create same app with success flags true, but different params
    create_request.options.partition_count += 10;
    create_request.options.app_type = "rrdb";
    create_request.options.success_if_exist = true;
    result = fake_create_app(svc->_state.get(), create_request);
    fake_wait_rpc(result, create_response);
    ASSERT_EQ( create_response.err, dsn::ERR_INVALID_PARAMETERS);

    //drop current app
    dsn::replication::configuration_drop_app_request drop_request;
    dsn::replication::configuration_drop_app_response drop_response;
    drop_request.app_name = "test_app2";
    drop_request.options.success_if_not_exist = false;

    result = fake_drop_app(svc->_state.get(), drop_request);
    //a drop request immediately after the first request
    result2 = fake_drop_app(svc->_state.get(), drop_request);
    //try to create a app with same name when it is dropping
    result3 = fake_create_app(svc->_state.get(), create_request);

    result->e.wait();
    result2->e.wait();
    result3->e.wait();

    ::dsn::unmarshall(result->response, drop_response);
    dsn_msg_release_ref(result->response);
    ASSERT_EQ(drop_response.err, dsn::ERR_OK);

    ::dsn::unmarshall(result2->response, drop_response);
    dsn_msg_release_ref(result2->response);
    ASSERT_TRUE(drop_response.err == dsn::ERR_APP_NOT_EXIST || drop_response.err == dsn::ERR_BUSY_DROPPING);

    ::dsn::unmarshall(result3->response, create_response);
    dsn_msg_release_ref(result3->response);
    ASSERT_TRUE(create_response.err==dsn::ERR_BUSY_DROPPING || create_response.err == dsn::ERR_OK);

    int created_successfully = 2;
    //in case that the previous create request succeed
    if (create_response.err == dsn::ERR_OK)
    {
        created_successfully = 3;
        drop_request.options.success_if_not_exist = true;
        do {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            result = fake_drop_app(svc->_state.get(), drop_request);
            fake_wait_rpc(result, drop_response);
        } while (drop_response.err != dsn::ERR_OK);
    }

    //currently "test_app2" is dropped, let's drop it again
    drop_request.options.success_if_not_exist = false;
    result = fake_drop_app(svc->_state.get(), drop_request);
    fake_wait_rpc(result, drop_response);
    ASSERT_EQ(dsn::ERR_APP_NOT_EXIST, drop_response.err);

    //now let's recreating the app with the same name
    result = fake_create_app(svc->_state.get(), create_request);
    create_request.options.success_if_exist = true;
    result2 = fake_create_app(svc->_state.get(), create_request);

    result->e.wait();
    result2->e.wait();

    ::dsn::unmarshall(result->response, create_response);
    dsn_msg_release_ref(result->response);
    ASSERT_EQ(create_response.err, dsn::ERR_OK);
    ASSERT_EQ(create_response.appid, created_successfully+1);

    ::dsn::unmarshall(result2->response, create_response);
    dsn_msg_release_ref(result2->response);
    ASSERT_EQ(create_response.err, dsn::ERR_BUSY_CREATING);

    ASSERT_TRUE(svc->_state->spin_wait_creating(30));

    //finally list the apps
    dsn::replication::configuration_list_apps_request list_request;
    dsn::replication::configuration_list_apps_response list_response;

    list_request.status = dsn::app_status::AS_AVAILABLE;
    svc->_state->list_apps(list_request, list_response);
    ASSERT_EQ(list_response.err, dsn::ERR_OK);
    ASSERT_EQ(list_response.infos.size(), 2);

    for (dsn::app_info& info: list_response.infos) {
        if (info.app_id == created_successfully+1) {
            ASSERT_EQ(info.app_name, create_request.app_name);
            ASSERT_EQ(info.app_type, create_request.options.app_type);
            ASSERT_EQ(info.partition_count, create_request.options.partition_count);
            ASSERT_EQ(info.status, dsn::app_status::AS_AVAILABLE);
        }
    }
}
<|endoftext|>


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

#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/settings/systemsettings.h>
#include <inviwo/core/util/systemcapabilities.h>
#include <inviwo/core/util/formatconversion.h>

namespace inviwo {

SystemSettings::SystemSettings()
    : Settings("System Settings")
    , applicationUsageModeProperty_("applicationUsageMode", "Application usage mode")
    , txtEditorProperty_("txtEditor", "Use system text editor", true)
    , enablePortInformationProperty_("enablePortInformation", "Enable port information", true)
    , enablePortInspectorsProperty_("enablePortInspectors", "Enable port inspectors", false)
    , portInspectorSize_("portInspectorSize", "Port inspector size", 128, 1, 1024)
    , enablePickingProperty_("enablePicking", "Enable picking", true)
    , enableSoundProperty_("enableSound", "Enable sound", true)
    , useRAMPercentProperty_("useRAMPercent", "Max memory usage (%)", 50, 1, 100)
    , logStackTraceProperty_("logStackTraceProperty", "Error stack trace log", false)
    , btnAllocTestProperty_("allocTest", "Perform Allocation Test")
    , btnSysInfoProperty_("printSysInfo", "Print System Info")

    , glslSyntax_("glslSyntax", "GLSL Syntax Highlighting")
    , glslTextColor_("glslTextColor", "Text", ivec4(0xAA, 0xAA, 0xAA, 255), ivec4(0, 0, 0, 1),
                     ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                     PropertySemantics::Color)
    , glslBackgroundColor_("glslBackgroundColor", "Background", ivec4(0x4D, 0x4D, 0x4D, 255),
                           ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                           INVALID_OUTPUT, PropertySemantics::Color)
    , glslQualifierColor_("glslQualifierColor", "Qualifiers", ivec4(0x7D, 0xB4, 0xDF, 255),
                          ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                          INVALID_OUTPUT, PropertySemantics::Color)
    , glslBuiltinsColor_("glslBultinsColor", "Builtins", ivec4(0x1F, 0xF0, 0x7F, 255),
                         ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                         INVALID_OUTPUT, PropertySemantics::Color)
    , glslTypeColor_("glslTypeColor", "Types", ivec4(0x56, 0x9C, 0xD6, 255), ivec4(0, 0, 0, 1),
                     ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                     PropertySemantics::Color)
    , glslGlslBuiltinsColor_("glslGlslBultinsColor", "GLSL Builtins", ivec4(0xFF, 0x80, 0x00, 255),
                             ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                             INVALID_OUTPUT, PropertySemantics::Color)
    , glslCommentColor_("glslCommentColor", "Comments", ivec4(0x60, 0x8B, 0x4E, 255),
                        ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                        INVALID_OUTPUT, PropertySemantics::Color)
    , glslPreProcessorColor_("glslPreProcessorColor", "Pre Processor", ivec4(0x9B, 0x9B, 0x9B, 255),
                             ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                             INVALID_OUTPUT, PropertySemantics::Color)

    , pythonSyntax_("pythonSyntax_", "Python Syntax Highlighting")
    , pyFontSize_("pyFontSize_" , "Font Size" , 11 , 1, 72)
    , pyBGColor_("pyBGColor", "Background", ivec4(0x88, 0x88, 0x88, 255), ivec4(0, 0, 0, 1),
                 ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                 PropertySemantics::Color)
    , pyTextColor_("pyTextColor", "Text", ivec4(0x11, 0x11, 0x11, 255), ivec4(0, 0, 0, 1),
                   ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                   PropertySemantics::Color)
    , pyTypeColor_("pyTypeColor", "Types", ivec4(0x14, 0x3C, 0xA6, 255), ivec4(0, 0, 0, 1),
                   ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                   PropertySemantics::Color)
    , pyCommentsColor_("pyCommentsColor", "Comments", ivec4(0x00, 0x66, 0x00, 255),
                       ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                       INVALID_OUTPUT, PropertySemantics::Color)

    , allocTest_(nullptr) {
    applicationUsageModeProperty_.addOption("applicationMode", "Application Mode", 0);
    applicationUsageModeProperty_.addOption("developerMode", "Developer Mode", 1);
    applicationUsageModeProperty_.setSelectedIndex(1);
    applicationUsageModeProperty_.setCurrentStateAsDefault();
    addProperty(applicationUsageModeProperty_);
    addProperty(txtEditorProperty_);
    addProperty(enablePortInformationProperty_);
    addProperty(enablePortInspectorsProperty_);
    addProperty(portInspectorSize_);
    addProperty(enablePickingProperty_);
    addProperty(enableSoundProperty_);
    addProperty(useRAMPercentProperty_);
    addProperty(logStackTraceProperty_);
    addProperty(pythonSyntax_);
    addProperty(glslSyntax_);

    glslSyntax_.addProperty(glslBackgroundColor_);
    glslSyntax_.addProperty(glslTextColor_);
    glslSyntax_.addProperty(glslCommentColor_);
    glslSyntax_.addProperty(glslTypeColor_);
    glslSyntax_.addProperty(glslQualifierColor_);
    glslSyntax_.addProperty(glslBuiltinsColor_);
    glslSyntax_.addProperty(glslGlslBuiltinsColor_);
    glslSyntax_.addProperty(glslPreProcessorColor_);

    pythonSyntax_.addProperty(pyFontSize_);
    pythonSyntax_.addProperty(pyBGColor_);
    pythonSyntax_.addProperty(pyTextColor_);
    pythonSyntax_.addProperty(pyCommentsColor_);
    pythonSyntax_.addProperty(pyTypeColor_);

    logStackTraceProperty_.onChange(this, &SystemSettings::logStacktraceCallback);
    // btnAllocTestProperty_.onChange(this, &SystemSettings::allocationTest);
    // addProperty(&btnAllocTestProperty_);
}

SystemSettings::~SystemSettings() {}

void SystemSettings::initialize() {
    InviwoCore* module = InviwoApplication::getPtr()->getModuleByType<InviwoCore>();
    if (module) {
        SystemCapabilities* sysInfo =
            getTypeFromVector<SystemCapabilities>(module->getCapabilities());
        if (sysInfo) {
            btnSysInfoProperty_.onChange(sysInfo, &SystemCapabilities::printInfo);
            addProperty(btnSysInfoProperty_);
        }
    }
}

void SystemSettings::deinitialize() {}

void SystemSettings::logStacktraceCallback() {
    LogCentral::getPtr()->setLogStacktrace(logStackTraceProperty_.get());
}

void SystemSettings::allocationTest() {
    InviwoCore* module = InviwoApplication::getPtr()->getModuleByType<InviwoCore>();
    if (!module) return;

    SystemCapabilities* sysInfo = getTypeFromVector<SystemCapabilities>(module->getCapabilities());

    if (sysInfo) {
        IntProperty* useRAMPercent =
            dynamic_cast<IntProperty*>(getPropertyByIdentifier("useRAMPercent"));
        glm::u64 memBytesAlloc = sysInfo->getAvailableMemory();  // In Bytes
        LogInfo("Maximum Available Memory is " << formatBytesToString(memBytesAlloc));
        memBytesAlloc /= 100;                   // 1% of total available memory
        memBytesAlloc *= useRAMPercent->get();  //?% of total available memory

        try {
            allocTest_ = new glm::u32[static_cast<glm::u32>(memBytesAlloc / 4)];
            LogInfo("Allocated " << formatBytesToString(memBytesAlloc) << ", which is "
                                 << useRAMPercent->get() << "% of available memory");
            delete allocTest_;
        } catch (std::bad_alloc&) {
            LogError("Failed allocation of " << formatBytesToString(memBytesAlloc) << ", which is "
                                             << useRAMPercent->get() << "% of available memory");
        }
    }
}

UsageMode SystemSettings::getApplicationUsageMode() const {
    return static_cast<UsageMode>(applicationUsageModeProperty_.get());
}

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

#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/settings/systemsettings.h>
#include <inviwo/core/util/systemcapabilities.h>
#include <inviwo/core/util/formatconversion.h>

namespace inviwo {

SystemSettings::SystemSettings()
    : Settings("System Settings")
    , applicationUsageModeProperty_("applicationUsageMode", "Application usage mode")
    , txtEditorProperty_("txtEditor", "Use system text editor", true)
    , enablePortInformationProperty_("enablePortInformation", "Enable port information", true)
    , enablePortInspectorsProperty_("enablePortInspectors", "Enable port inspectors", true)
    , portInspectorSize_("portInspectorSize", "Port inspector size", 128, 1, 1024)
    , enablePickingProperty_("enablePicking", "Enable picking", true)
    , enableSoundProperty_("enableSound", "Enable sound", true)
    , useRAMPercentProperty_("useRAMPercent", "Max memory usage (%)", 50, 1, 100)
    , logStackTraceProperty_("logStackTraceProperty", "Error stack trace log", false)
    , btnAllocTestProperty_("allocTest", "Perform Allocation Test")
    , btnSysInfoProperty_("printSysInfo", "Print System Info")

    , glslSyntax_("glslSyntax", "GLSL Syntax Highlighting")
    , glslTextColor_("glslTextColor", "Text", ivec4(0xAA, 0xAA, 0xAA, 255), ivec4(0, 0, 0, 1),
                     ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                     PropertySemantics::Color)
    , glslBackgroundColor_("glslBackgroundColor", "Background", ivec4(0x4D, 0x4D, 0x4D, 255),
                           ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                           INVALID_OUTPUT, PropertySemantics::Color)
    , glslQualifierColor_("glslQualifierColor", "Qualifiers", ivec4(0x7D, 0xB4, 0xDF, 255),
                          ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                          INVALID_OUTPUT, PropertySemantics::Color)
    , glslBuiltinsColor_("glslBultinsColor", "Builtins", ivec4(0x1F, 0xF0, 0x7F, 255),
                         ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                         INVALID_OUTPUT, PropertySemantics::Color)
    , glslTypeColor_("glslTypeColor", "Types", ivec4(0x56, 0x9C, 0xD6, 255), ivec4(0, 0, 0, 1),
                     ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                     PropertySemantics::Color)
    , glslGlslBuiltinsColor_("glslGlslBultinsColor", "GLSL Builtins", ivec4(0xFF, 0x80, 0x00, 255),
                             ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                             INVALID_OUTPUT, PropertySemantics::Color)
    , glslCommentColor_("glslCommentColor", "Comments", ivec4(0x60, 0x8B, 0x4E, 255),
                        ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                        INVALID_OUTPUT, PropertySemantics::Color)
    , glslPreProcessorColor_("glslPreProcessorColor", "Pre Processor", ivec4(0x9B, 0x9B, 0x9B, 255),
                             ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                             INVALID_OUTPUT, PropertySemantics::Color)

    , pythonSyntax_("pythonSyntax_", "Python Syntax Highlighting")
    , pyFontSize_("pyFontSize_" , "Font Size" , 11 , 1, 72)
    , pyBGColor_("pyBGColor", "Background", ivec4(0x88, 0x88, 0x88, 255), ivec4(0, 0, 0, 1),
                 ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                 PropertySemantics::Color)
    , pyTextColor_("pyTextColor", "Text", ivec4(0x11, 0x11, 0x11, 255), ivec4(0, 0, 0, 1),
                   ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                   PropertySemantics::Color)
    , pyTypeColor_("pyTypeColor", "Types", ivec4(0x14, 0x3C, 0xA6, 255), ivec4(0, 0, 0, 1),
                   ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1), INVALID_OUTPUT,
                   PropertySemantics::Color)
    , pyCommentsColor_("pyCommentsColor", "Comments", ivec4(0x00, 0x66, 0x00, 255),
                       ivec4(0, 0, 0, 1), ivec4(255, 255, 255, 1), ivec4(1, 1, 1, 1),
                       INVALID_OUTPUT, PropertySemantics::Color)

    , allocTest_(nullptr) {
    applicationUsageModeProperty_.addOption("applicationMode", "Application Mode", 0);
    applicationUsageModeProperty_.addOption("developerMode", "Developer Mode", 1);
    applicationUsageModeProperty_.setSelectedIndex(1);
    applicationUsageModeProperty_.setCurrentStateAsDefault();
    addProperty(applicationUsageModeProperty_);
    addProperty(txtEditorProperty_);
    addProperty(enablePortInformationProperty_);
    addProperty(enablePortInspectorsProperty_);
    addProperty(portInspectorSize_);
    addProperty(enablePickingProperty_);
    addProperty(enableSoundProperty_);
    addProperty(useRAMPercentProperty_);
    addProperty(logStackTraceProperty_);
    addProperty(pythonSyntax_);
    addProperty(glslSyntax_);

    glslSyntax_.addProperty(glslBackgroundColor_);
    glslSyntax_.addProperty(glslTextColor_);
    glslSyntax_.addProperty(glslCommentColor_);
    glslSyntax_.addProperty(glslTypeColor_);
    glslSyntax_.addProperty(glslQualifierColor_);
    glslSyntax_.addProperty(glslBuiltinsColor_);
    glslSyntax_.addProperty(glslGlslBuiltinsColor_);
    glslSyntax_.addProperty(glslPreProcessorColor_);

    pythonSyntax_.addProperty(pyFontSize_);
    pythonSyntax_.addProperty(pyBGColor_);
    pythonSyntax_.addProperty(pyTextColor_);
    pythonSyntax_.addProperty(pyCommentsColor_);
    pythonSyntax_.addProperty(pyTypeColor_);

    logStackTraceProperty_.onChange(this, &SystemSettings::logStacktraceCallback);
    // btnAllocTestProperty_.onChange(this, &SystemSettings::allocationTest);
    // addProperty(&btnAllocTestProperty_);
}

SystemSettings::~SystemSettings() {}

void SystemSettings::initialize() {
    InviwoCore* module = InviwoApplication::getPtr()->getModuleByType<InviwoCore>();
    if (module) {
        SystemCapabilities* sysInfo =
            getTypeFromVector<SystemCapabilities>(module->getCapabilities());
        if (sysInfo) {
            btnSysInfoProperty_.onChange(sysInfo, &SystemCapabilities::printInfo);
            addProperty(btnSysInfoProperty_);
        }
    }
}

void SystemSettings::deinitialize() {}

void SystemSettings::logStacktraceCallback() {
    LogCentral::getPtr()->setLogStacktrace(logStackTraceProperty_.get());
}

void SystemSettings::allocationTest() {
    InviwoCore* module = InviwoApplication::getPtr()->getModuleByType<InviwoCore>();
    if (!module) return;

    SystemCapabilities* sysInfo = getTypeFromVector<SystemCapabilities>(module->getCapabilities());

    if (sysInfo) {
        IntProperty* useRAMPercent =
            dynamic_cast<IntProperty*>(getPropertyByIdentifier("useRAMPercent"));
        glm::u64 memBytesAlloc = sysInfo->getAvailableMemory();  // In Bytes
        LogInfo("Maximum Available Memory is " << formatBytesToString(memBytesAlloc));
        memBytesAlloc /= 100;                   // 1% of total available memory
        memBytesAlloc *= useRAMPercent->get();  //?% of total available memory

        try {
            allocTest_ = new glm::u32[static_cast<glm::u32>(memBytesAlloc / 4)];
            LogInfo("Allocated " << formatBytesToString(memBytesAlloc) << ", which is "
                                 << useRAMPercent->get() << "% of available memory");
            delete allocTest_;
        } catch (std::bad_alloc&) {
            LogError("Failed allocation of " << formatBytesToString(memBytesAlloc) << ", which is "
                                             << useRAMPercent->get() << "% of available memory");
        }
    }
}

UsageMode SystemSettings::getApplicationUsageMode() const {
    return static_cast<UsageMode>(applicationUsageModeProperty_.get());
}

}  // namespace
<|endoftext|>


<commit_before><commit_msg>Fix handle leak at shutdown.<commit_after><|endoftext|>


<commit_before>#include "nearbyclusters.h"

#include "../serverapi.h"

#include <QtCore/QDebug>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonParseError>
#include <QtCore/QJsonArray>

NearbyClusters::NearbyClusters(CashPointSqlModel *model)
    : CashPointRequest(model)
{
    registerStepHandlers({
                             STEP_HANDLER(fetchClusters)
                         });
}

NearbyClusters::~NearbyClusters()
{
    qDebug() << "destroyed " << this;
}

bool NearbyClusters::fromJson(const QJsonObject &json)
{
    const QJsonValue longitude = json["longitude"];
    const QJsonValue latitude  = json["latitude"];
    const QJsonValue radius    = json["radius"];
    const QJsonValue zoom      = json["zoom"];
    const QJsonValue filter    = json["filter"];

    if (!zoom.isDouble() || !radius.isDouble() ||
        !longitude.isDouble() || !latitude.isDouble() ||
        !(filter.isObject() || filter.isUndefined()) )
    {
        auto it = data.begin();
        while (it != data.end()) {
            it = data.erase(it);
        }
        return false;
    }

    data["longitude"] = longitude;
    data["latitude"] = latitude;
    data["radius"] = radius;
    data["zoom"] = qRound(zoom.toDouble());

    if (filter.isObject()) {
        data["filter"] = filter;
    }

    return true;
}

void NearbyClusters::fetchClusters(ServerApiPtr api, quint32 leftAttempts)
{
    qDebug() << "fetchClusters";

    if (data.isEmpty()) {
        return;
    }

    api->sendRequest("/nearby/clusters", data,
    [this, api, leftAttempts]
    (ServerApi::RequestStatusCode reqCode, ServerApi::HttpStatusCode httpCode, const QByteArray &data) {
        qDebug() << "callback " << this;
        if (!isRunning()) {
            if (isDisposing()) {
                deleteLater();
            }
            return;
        }
        const int step = 1;

        const QString errText = trUtf8("Cannot receive data of nearby clusters");
        if (reqCode == ServerApi::RSC_Timeout) {
            emitUpdate(leftAttempts - 1, step);
            return;
        }

        if (reqCode != ServerApi::RSC_Ok) {
            emitError(ServerApi::requestStatusCodeText(reqCode));
            emitStepFinished(*api, step, false, errText);
            return;
        }

        if (httpCode != ServerApi::HSC_Ok) {
            qWarning() << "Server request http code: " << httpCode;
            emitUpdate(leftAttempts - 1, step);
            return;
        }

        QJsonParseError err;
        const QJsonDocument json = QJsonDocument::fromJson(data, &err);
        if (err.error != QJsonParseError::NoError) {
            emitError("NearbyClusters: server response json parse error: " + err.errorString());
            emitStepFinished(*api, step, false, errText);
            return;
        }

        if (!json.isArray()) {
            emitError("NearbyClusters: response is not an array!");
            emitStepFinished(*api, step, false, errText);
            return;
        }

        mResponse = new CashPointResponse;

        const QJsonArray arr = json.array();
        const auto end = arr.end();
        for (auto it = arr.begin(); it != end; it++) {
            const QJsonValue &val = *it;
            if (!val.isObject()) {
                qDebug() << "expected json object in array";
                continue;
            }
            const QJsonObject obj = val.toObject();
            if (!obj["size"].isUndefined()) {
                mResponse->addClusterData(obj);
            } else {
                const int id = obj["id"].toInt();
                if (id > 0) {
                    mResponse->addCashPointData(obj);
                    mResponse->addVisiableCashpoint(id);
                }
            }
        }

        emitResponseReady(true);
        emitStepFinished(*api, step, true, trUtf8("List of nearby clusters received"));
    });
}
<commit_msg>[C|Client] Sending topLeft & bottomRight in NearbyCluster req to server<commit_after>#include "nearbyclusters.h"

#include "../serverapi.h"

#include <QtCore/QDebug>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonParseError>
#include <QtCore/QJsonArray>

NearbyClusters::NearbyClusters(CashPointSqlModel *model)
    : CashPointRequest(model)
{
    registerStepHandlers({
                             STEP_HANDLER(fetchClusters)
                         });
}

NearbyClusters::~NearbyClusters()
{
    qDebug() << "destroyed " << this;
}

bool NearbyClusters::fromJson(const QJsonObject &json)
{
    const QJsonValue longitude = json["longitude"];
    const QJsonValue latitude  = json["latitude"];
    const QJsonValue radius    = json["radius"];
    const QJsonValue zoom      = json["zoom"];
    const QJsonValue filter    = json["filter"];

    const QJsonValue topLeft =   json["topLeft"];
    const QJsonValue botRight =  json["bottomRight"];

    if (!zoom.isDouble() || !radius.isDouble() ||
        !longitude.isDouble() || !latitude.isDouble() ||
        !(filter.isObject() || filter.isUndefined()) ||
        !(topLeft.isObject()) || !botRight.isObject() )
    {
        auto it = data.begin();
        while (it != data.end()) {
            it = data.erase(it);
        }
        return false;
    }

    data["longitude"] = longitude;
    data["latitude"] = latitude;
    data["radius"] = radius;
    data["zoom"] = qRound(zoom.toDouble());
    data["topLeft"] = topLeft;
    data["bottomRight"] = botRight;

    if (filter.isObject()) {
        data["filter"] = filter;
    }

    return true;
}

void NearbyClusters::fetchClusters(ServerApiPtr api, quint32 leftAttempts)
{
    qDebug() << "fetchClusters";

    if (data.isEmpty()) {
        return;
    }

    api->sendRequest("/nearby/clusters", data,
    [this, api, leftAttempts]
    (ServerApi::RequestStatusCode reqCode, ServerApi::HttpStatusCode httpCode, const QByteArray &data) {
        qDebug() << "callback " << this;
        if (!isRunning()) {
            if (isDisposing()) {
                deleteLater();
            }
            return;
        }
        const int step = 1;

        const QString errText = trUtf8("Cannot receive data of nearby clusters");
        if (reqCode == ServerApi::RSC_Timeout) {
            emitUpdate(leftAttempts - 1, step);
            return;
        }

        if (reqCode != ServerApi::RSC_Ok) {
            emitError(ServerApi::requestStatusCodeText(reqCode));
            emitStepFinished(*api, step, false, errText);
            return;
        }

        if (httpCode != ServerApi::HSC_Ok) {
            qWarning() << "Server request http code: " << httpCode;
            emitUpdate(leftAttempts - 1, step);
            return;
        }

        QJsonParseError err;
        const QJsonDocument json = QJsonDocument::fromJson(data, &err);
        if (err.error != QJsonParseError::NoError) {
            emitError("NearbyClusters: server response json parse error: " + err.errorString());
            emitStepFinished(*api, step, false, errText);
            return;
        }

        if (!json.isArray()) {
            emitError("NearbyClusters: response is not an array!");
            emitStepFinished(*api, step, false, errText);
            return;
        }

        mResponse = new CashPointResponse;

        const QJsonArray arr = json.array();
        const auto end = arr.end();
        for (auto it = arr.begin(); it != end; it++) {
            const QJsonValue &val = *it;
            if (!val.isObject()) {
                qDebug() << "expected json object in array";
                continue;
            }
            const QJsonObject obj = val.toObject();
            if (!obj["size"].isUndefined()) {
                mResponse->addClusterData(obj);
            } else {
                const int id = obj["id"].toInt();
                if (id > 0) {
                    mResponse->addCashPointData(obj);
                    mResponse->addVisiableCashpoint(id);
                }
            }
        }

        emitResponseReady(true);
        emitStepFinished(*api, step, true, trUtf8("List of nearby clusters received"));
    });
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/
#ifndef TIGHTDB_LANG_BIND_HELPER_HPP
#define TIGHTDB_LANG_BIND_HELPER_HPP

#include "table.hpp"
#include "table_view.hpp"
#include "group.hpp"

namespace tightdb {

/**
 * These functions are only to be used by language bindings to gain
 * access to certain otherwise private memebers.
 *
 * \note An application must never call these functions directly.
 *
 * All the get_*_ptr() functions in this class will return a Table
 * pointer where the reference count has already been incremented. The
 * application must make sure that the unbind_table_ref() function is
 * called to decrement the reference count when it no longer needs
 * access to that table.
 */
class LangBindHelper {
public:
    static Table* get_subtable_ptr(Table*, size_t column_ndx, size_t row_ndx);
    static const Table* get_subtable_ptr(const Table*, size_t column_ndx, size_t row_ndx);

    static Table* get_subtable_ptr(TableView*, size_t column_ndx, size_t row_ndx);
    static const Table* get_subtable_ptr(const TableView*, size_t column_ndx, size_t row_ndx);
    static const Table* get_subtable_ptr(const ConstTableView*, size_t column_ndx, size_t row_ndx);

    static Table* get_table_ptr(Group* grp, const char* name);
    static const Table* get_table_ptr(const Group* grp, const char* name);

    static void unbind_table_ref(const Table*);
};

// Implementation:

inline Table* LangBindHelper::get_subtable_ptr(Table* t, size_t column_ndx, size_t row_ndx)
{
    Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx);
    subtab->bind_ref();
    return subtab;
}

inline const Table* LangBindHelper::get_subtable_ptr(const Table* t, size_t column_ndx, size_t row_ndx)
{
    const Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx);
    subtab->bind_ref();
    return subtab;
}

inline Table* LangBindHelper::get_subtable_ptr(TableView* tv, size_t column_ndx, size_t row_ndx)
{
    return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx));
}

inline const Table* LangBindHelper::get_subtable_ptr(const TableView* tv, size_t column_ndx, size_t row_ndx)
{
    return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx));
}

inline const Table* LangBindHelper::get_subtable_ptr(const ConstTableView* tv, size_t column_ndx, size_t row_ndx)
{
    return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx));
}

inline Table* LangBindHelper::get_table_ptr(Group* grp, const char* name)
{
    Table* subtab = grp->get_table_ptr(name);
    subtab->bind_ref();
    return subtab;
}

inline const Table* LangBindHelper::get_table_ptr(const Group* grp, const char* name)
{
    const Table* subtab = grp->get_table_ptr(name);
    subtab->bind_ref();
    return subtab;
}

inline void LangBindHelper::unbind_table_ref(const Table* t)
{
   t->unbind_ref();
}

} // namespace tightdb

#endif // TIGHTDB_LANG_BIND_HELPER_HPP
<commit_msg>Added comment about order of unbinding.<commit_after>/*************************************************************************
 *
 * TIGHTDB CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] TightDB Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of TightDB Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to TightDB Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from TightDB Incorporated.
 *
 **************************************************************************/
#ifndef TIGHTDB_LANG_BIND_HELPER_HPP
#define TIGHTDB_LANG_BIND_HELPER_HPP

#include "table.hpp"
#include "table_view.hpp"
#include "group.hpp"

namespace tightdb {

/**
 * These functions are only to be used by language bindings to gain
 * access to certain otherwise private memebers.
 *
 * \note An application must never call these functions directly.
 *
 * All the get_*_ptr() functions in this class will return a Table
 * pointer where the reference count has already been incremented.
 *
 * The application must make sure that the unbind_table_ref() function is
 * called to decrement the reference count when it no longer needs
 * access to that table. The order of unbinding is important as you must
 * unbind subtables to a table before unbinding the table itself.
 *
 */
class LangBindHelper {
public:
    static Table* get_subtable_ptr(Table*, size_t column_ndx, size_t row_ndx);
    static const Table* get_subtable_ptr(const Table*, size_t column_ndx, size_t row_ndx);

    static Table* get_subtable_ptr(TableView*, size_t column_ndx, size_t row_ndx);
    static const Table* get_subtable_ptr(const TableView*, size_t column_ndx, size_t row_ndx);
    static const Table* get_subtable_ptr(const ConstTableView*, size_t column_ndx, size_t row_ndx);

    static Table* get_table_ptr(Group* grp, const char* name);
    static const Table* get_table_ptr(const Group* grp, const char* name);

    static void unbind_table_ref(const Table*);
};

// Implementation:

inline Table* LangBindHelper::get_subtable_ptr(Table* t, size_t column_ndx, size_t row_ndx)
{
    Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx);
    subtab->bind_ref();
    return subtab;
}

inline const Table* LangBindHelper::get_subtable_ptr(const Table* t, size_t column_ndx, size_t row_ndx)
{
    const Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx);
    subtab->bind_ref();
    return subtab;
}

inline Table* LangBindHelper::get_subtable_ptr(TableView* tv, size_t column_ndx, size_t row_ndx)
{
    return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx));
}

inline const Table* LangBindHelper::get_subtable_ptr(const TableView* tv, size_t column_ndx, size_t row_ndx)
{
    return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx));
}

inline const Table* LangBindHelper::get_subtable_ptr(const ConstTableView* tv, size_t column_ndx, size_t row_ndx)
{
    return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx));
}

inline Table* LangBindHelper::get_table_ptr(Group* grp, const char* name)
{
    Table* subtab = grp->get_table_ptr(name);
    subtab->bind_ref();
    return subtab;
}

inline const Table* LangBindHelper::get_table_ptr(const Group* grp, const char* name)
{
    const Table* subtab = grp->get_table_ptr(name);
    subtab->bind_ref();
    return subtab;
}

inline void LangBindHelper::unbind_table_ref(const Table* t)
{
   t->unbind_ref();
}

} // namespace tightdb

#endif // TIGHTDB_LANG_BIND_HELPER_HPP
<|endoftext|>


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

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

#ifdef _WIN32
#pragma comment(linker, "/subsystem:console")
#include <windows.h>
#include <vulkan.h>
#include <vk_wsi_swapchain.h>
#include <vk_wsi_device_swapchain.h>
#include <vk_debug_report_lunarg.h>
#define APP_NAME_STR_LEN 80
#else  // _WIN32
#include <xcb/xcb.h>
#include <vulkan/vulkan.h>
#include <vulkan/vk_wsi_swapchain.h>
#include <vulkan/vk_wsi_device_swapchain.h>
#include <vulkan/vk_debug_report_lunarg.h>
#endif // _WIN32

#define GET_INSTANCE_PROC_ADDR(inst, entrypoint)                         \
{                                                                        \
    info.fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \
    if (info.fp##entrypoint == NULL) {                                   \
        std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
        exit(-1);                                                        \
    }                                                                    \
}

#define GET_DEVICE_PROC_ADDR(dev, entrypoint)                           \
{                                                                       \
    info.fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint);   \
    if (info.fp##entrypoint == NULL) {                                   \
        std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
        exit(-1);                                                        \
    }                                                                    \
}

std::string get_base_data_dir();
std::string get_data_dir( std::string filename );

/*
 * structure to track all objects related to a texture.
 */
struct texture_object {
    VkSampler sampler;

    VkImage image;
    VkImageLayout imageLayout;

    VkDeviceMemory mem;
    VkImageView view;
    int32_t tex_width, tex_height;
};

typedef struct _swap_chain_buffers {
    VkImage image;
    VkCmdBuffer cmd;
    VkAttachmentView view;
} swap_chain_buffers;

/*
 * A layer can expose extensions, keep track of those
 * extensions here.
 */
typedef struct {
    VkLayerProperties properties;
    std::vector<VkExtensionProperties> extensions;
} layer_properties;

/*
 * Keep each of our swap chain buffers' image, command buffer and view in one spot
 */
typedef struct _SwapChainBuffers {
    VkImage image;
    VkCmdBuffer cmd;
    VkAttachmentView view;
} SwapChainBuffers;

/*
 * Structure for tracking information used / created / modified
 * by utility functions.
 */
struct sample_info {
#ifdef _WIN32
#define APP_NAME_STR_LEN 80
    HINSTANCE connection;        // hInstance - Windows Instance
    char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
    HWND        window;          // hWnd - window handle
#else  // _WIN32
    xcb_connection_t *connection;
    xcb_screen_t *screen;
    xcb_window_t window;
    xcb_intern_atom_reply_t *atom_wm_delete_window;
    VkPlatformHandleXcbWSI platform_handle_xcb;
#endif // _WIN32
    bool prepared;
    bool use_staging_buffer;

    std::vector<char *> instance_layer_names;
    std::vector<char *> instance_extension_names;
    std::vector<layer_properties> instance_layer_properties;
    std::vector<VkExtensionProperties> instance_extension_properties;
    VkInstance inst;

    std::vector<char *> device_layer_names;
    std::vector<char *> device_extension_names;
    std::vector<layer_properties> device_layer_properties;
    std::vector<VkExtensionProperties> device_extension_properties;
    VkPhysicalDevice gpu;
    VkDevice device;
    VkQueue queue;
    uint32_t graphics_queue_family_index;
    VkPhysicalDeviceProperties gpu_props;
    std::vector<VkPhysicalDeviceQueueProperties> queue_props;
    VkPhysicalDeviceMemoryProperties memory_properties;

    VkFramebuffer framebuffer;
    int width, height;
    VkFormat format;

    PFN_vkGetPhysicalDeviceSurfaceSupportWSI fpGetPhysicalDeviceSurfaceSupportWSI;
    PFN_vkGetSurfaceInfoWSI fpGetSurfaceInfoWSI;
    PFN_vkCreateSwapChainWSI fpCreateSwapChainWSI;
    PFN_vkDestroySwapChainWSI fpDestroySwapChainWSI;
    PFN_vkGetSwapChainInfoWSI fpGetSwapChainInfoWSI;
    PFN_vkAcquireNextImageWSI fpAcquireNextImageWSI;
    PFN_vkQueuePresentWSI fpQueuePresentWSI;
    VkSurfaceDescriptionWindowWSI surface_description;
    size_t swapChainImageCount;
    VkSwapChainWSI swap_chain;
    std::vector<swap_chain_buffers> buffers;

    VkCmdPool cmd_pool;

    struct {
        VkFormat format;

        VkImage image;
        VkDeviceMemory mem;
        VkAttachmentView view;
    } depth;

    std::vector<struct texture_object> textures;

    struct {
        VkBuffer buf;
        VkDeviceMemory mem;
        VkBufferView view;
        VkDescriptorInfo desc;
    } uniform_data;

    VkCmdBuffer cmd;  // Buffer for initialization commands
    VkPipelineLayout pipeline_layout;
    VkDescriptorSetLayout desc_layout;
    VkPipelineCache pipelineCache;
    VkRenderPass render_pass;
    VkPipeline pipeline;

    VkDynamicViewportState viewport;
    VkDynamicRasterState raster;
    VkDynamicColorBlendState color_blend;
    VkDynamicDepthStencilState depth_stencil;

    VkShaderModule vert_shader_module;
    VkShaderModule frag_shader_module;

    VkDescriptorPool desc_pool;
    VkDescriptorSet desc_set;

    std::vector<VkFramebuffer> framebuffers;

    PFN_vkDbgCreateMsgCallback dbgCreateMsgCallback;
    PFN_vkDbgDestroyMsgCallback dbgDestroyMsgCallback;
    PFN_vkDbgMsgCallback dbgBreakCallback;
    std::vector<VkDbgMsgCallback> msg_callbacks;

    uint32_t current_buffer;
    uint32_t queue_count;
};

VkResult memory_type_from_properties(struct sample_info &info, uint32_t typeBits, VkFlags properties, uint32_t *typeIndex);

void set_image_layout(
        struct sample_info &demo,
        VkImage image,
        VkImageAspect aspect,
        VkImageLayout old_image_layout,
        VkImageLayout new_image_layout);

bool read_ppm(char const*const filename, int *width, int *height, int rowPitch, char *dataPtr);
void extract_version(uint32_t version, uint32_t &major, uint32_t &minor, uint32_t &patch);
<commit_msg>Remove redundant struct type<commit_after>/*
 * Vulkan Samples Kit
 *
 * Copyright (C) 2015 LunarG, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

#ifdef _WIN32
#pragma comment(linker, "/subsystem:console")
#include <windows.h>
#include <vulkan.h>
#include <vk_wsi_swapchain.h>
#include <vk_wsi_device_swapchain.h>
#include <vk_debug_report_lunarg.h>
#define APP_NAME_STR_LEN 80
#else  // _WIN32
#include <xcb/xcb.h>
#include <vulkan/vulkan.h>
#include <vulkan/vk_wsi_swapchain.h>
#include <vulkan/vk_wsi_device_swapchain.h>
#include <vulkan/vk_debug_report_lunarg.h>
#endif // _WIN32

#define GET_INSTANCE_PROC_ADDR(inst, entrypoint)                         \
{                                                                        \
    info.fp##entrypoint = (PFN_vk##entrypoint) vkGetInstanceProcAddr(inst, "vk"#entrypoint); \
    if (info.fp##entrypoint == NULL) {                                   \
        std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
        exit(-1);                                                        \
    }                                                                    \
}

#define GET_DEVICE_PROC_ADDR(dev, entrypoint)                           \
{                                                                       \
    info.fp##entrypoint = (PFN_vk##entrypoint) vkGetDeviceProcAddr(dev, "vk"#entrypoint);   \
    if (info.fp##entrypoint == NULL) {                                   \
        std::cout << "vkGetDeviceProcAddr failed to find vk"#entrypoint; \
        exit(-1);                                                        \
    }                                                                    \
}

std::string get_base_data_dir();
std::string get_data_dir( std::string filename );

/*
 * structure to track all objects related to a texture.
 */
struct texture_object {
    VkSampler sampler;

    VkImage image;
    VkImageLayout imageLayout;

    VkDeviceMemory mem;
    VkImageView view;
    int32_t tex_width, tex_height;
};

/*
 * Keep each of our swap chain buffers' image, command buffer and view in one spot
 */
typedef struct _swap_chain_buffers {
    VkImage image;
    VkCmdBuffer cmd;
    VkAttachmentView view;
} swap_chain_buffers;

/*
 * A layer can expose extensions, keep track of those
 * extensions here.
 */
typedef struct {
    VkLayerProperties properties;
    std::vector<VkExtensionProperties> extensions;
} layer_properties;

/*
 * Structure for tracking information used / created / modified
 * by utility functions.
 */
struct sample_info {
#ifdef _WIN32
#define APP_NAME_STR_LEN 80
    HINSTANCE connection;        // hInstance - Windows Instance
    char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
    HWND        window;          // hWnd - window handle
#else  // _WIN32
    xcb_connection_t *connection;
    xcb_screen_t *screen;
    xcb_window_t window;
    xcb_intern_atom_reply_t *atom_wm_delete_window;
    VkPlatformHandleXcbWSI platform_handle_xcb;
#endif // _WIN32
    bool prepared;
    bool use_staging_buffer;

    std::vector<char *> instance_layer_names;
    std::vector<char *> instance_extension_names;
    std::vector<layer_properties> instance_layer_properties;
    std::vector<VkExtensionProperties> instance_extension_properties;
    VkInstance inst;

    std::vector<char *> device_layer_names;
    std::vector<char *> device_extension_names;
    std::vector<layer_properties> device_layer_properties;
    std::vector<VkExtensionProperties> device_extension_properties;
    VkPhysicalDevice gpu;
    VkDevice device;
    VkQueue queue;
    uint32_t graphics_queue_family_index;
    VkPhysicalDeviceProperties gpu_props;
    std::vector<VkPhysicalDeviceQueueProperties> queue_props;
    VkPhysicalDeviceMemoryProperties memory_properties;

    VkFramebuffer framebuffer;
    int width, height;
    VkFormat format;

    PFN_vkGetPhysicalDeviceSurfaceSupportWSI fpGetPhysicalDeviceSurfaceSupportWSI;
    PFN_vkGetSurfaceInfoWSI fpGetSurfaceInfoWSI;
    PFN_vkCreateSwapChainWSI fpCreateSwapChainWSI;
    PFN_vkDestroySwapChainWSI fpDestroySwapChainWSI;
    PFN_vkGetSwapChainInfoWSI fpGetSwapChainInfoWSI;
    PFN_vkAcquireNextImageWSI fpAcquireNextImageWSI;
    PFN_vkQueuePresentWSI fpQueuePresentWSI;
    VkSurfaceDescriptionWindowWSI surface_description;
    size_t swapChainImageCount;
    VkSwapChainWSI swap_chain;
    std::vector<swap_chain_buffers> buffers;

    VkCmdPool cmd_pool;

    struct {
        VkFormat format;

        VkImage image;
        VkDeviceMemory mem;
        VkAttachmentView view;
    } depth;

    std::vector<struct texture_object> textures;

    struct {
        VkBuffer buf;
        VkDeviceMemory mem;
        VkBufferView view;
        VkDescriptorInfo desc;
    } uniform_data;

    VkCmdBuffer cmd;  // Buffer for initialization commands
    VkPipelineLayout pipeline_layout;
    VkDescriptorSetLayout desc_layout;
    VkPipelineCache pipelineCache;
    VkRenderPass render_pass;
    VkPipeline pipeline;

    VkDynamicViewportState viewport;
    VkDynamicRasterState raster;
    VkDynamicColorBlendState color_blend;
    VkDynamicDepthStencilState depth_stencil;

    VkShaderModule vert_shader_module;
    VkShaderModule frag_shader_module;

    VkDescriptorPool desc_pool;
    VkDescriptorSet desc_set;

    std::vector<VkFramebuffer> framebuffers;

    PFN_vkDbgCreateMsgCallback dbgCreateMsgCallback;
    PFN_vkDbgDestroyMsgCallback dbgDestroyMsgCallback;
    PFN_vkDbgMsgCallback dbgBreakCallback;
    std::vector<VkDbgMsgCallback> msg_callbacks;

    uint32_t current_buffer;
    uint32_t queue_count;
};

VkResult memory_type_from_properties(struct sample_info &info, uint32_t typeBits, VkFlags properties, uint32_t *typeIndex);

void set_image_layout(
        struct sample_info &demo,
        VkImage image,
        VkImageAspect aspect,
        VkImageLayout old_image_layout,
        VkImageLayout new_image_layout);

bool read_ppm(char const*const filename, int *width, int *height, int rowPitch, char *dataPtr);
void extract_version(uint32_t version, uint32_t &major, uint32_t &minor, uint32_t &patch);
<|endoftext|>


<commit_before>// stdafx.cpp : source file that includes just the standard includes
// YorozuyaGS.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
<commit_msg>removed old comment<commit_after>#include "stdafx.h"
<|endoftext|>


<commit_before>//****************************************************************************
// Copyright © 2015 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2015-12-05.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "GetValueType.hpp"

#include <cstdint>

namespace Yson {

    namespace {
        int getDigit(char c);

        bool isHexDigit(char c);

        template<typename Predicate>
        ValueType_t getValueType(const char* first, const char* last,
                                 Predicate isDigit, ValueType_t type);

        ValueType_t getBinaryValueType(const char* first, const char* last);

        ValueType_t getOctalValueType(const char* first, const char* last);

        ValueType_t getHexadecimalValueType(const char* first,
                                            const char* last);

        ValueType_t getFloatingPointValueType(const char* first,
                                              const char* last);

        ValueType_t getNumberValueType(const char* first, const char* last);
    }

    ValueType_t getValueType(const char* first, const char* last)
    {
        if (first == last)
            return ValueType::INVALID;
        auto assumedType = ValueType_t(ValueType::UNKNOWN);
        if (*first == '-' || *first == '+')
        {
            if (++first == last)
                return ValueType::INVALID;
            assumedType = ValueType::INTEGER;
        }
        if (*first == '0')
        {
            if (++first == last)
                return ValueType::INTEGER;
            switch (*first)
            {
            case 'b':
                return getBinaryValueType(++first, last);
            case 'o':
                return getOctalValueType(++first, last);
            case 'x':
                return getHexadecimalValueType(++first, last);
            case '.':
            case 'e':
            case 'E':
                return getFloatingPointValueType(first, last);
            default:
                if (getDigit(*first) <= 9)
                {
                    if (++first == last)
                        return ValueType::INTEGER;
                    return getNumberValueType(first, last);
                }
                return ValueType::INVALID;
            }
        }
        else if (getDigit(*first) <= 9)
        {
            if (++first == last)
                return ValueType::INTEGER;
            return getNumberValueType(first, last);
        }

        if (last - first == 8 && std::equal(first, last, "infinity"))
            return ValueType::EXTENDED_FLOAT;
        if (last - first == 3 && std::equal(first, last, "NaN"))
            return ValueType::EXTENDED_FLOAT;

        if (assumedType != ValueType::UNKNOWN)
            return ValueType::INVALID;

        if (last - first == 4 && std::equal(first, last, "true"))
            return ValueType::TRUE_VALUE;
        if (last - first == 4 && std::equal(first, last, "null"))
            return ValueType::NULL_VALUE;
        if (last - first == 5 && std::equal(first, last, "false"))
            return ValueType::FALSE_VALUE;

        return ValueType::INVALID;
    }

    ValueType_t getValueType(const std::pair<const char*, const char*>& value)
    {
        return getValueType(value.first, value.second);
    }

    ValueType_t getValueType(const std::string& s)
    {
        return getValueType(s.data(), s.data() + s.size());
    }

    namespace {

        int getDigit(char c)
        {
            return uint8_t(c) ^ 0x30;
        }

        bool isHexDigit(char c)
        {
            return (getDigit(c) <= 9) ||
                   ('A' <= c && c <= 'F') ||
                   ('a' <= c && c <= 'f');
        }

        template<typename Predicate>
        ValueType_t getValueType(const char* first, const char* last,
                                 Predicate isDigit, ValueType_t type)
        {
            if (first == last)
                return ValueType::INVALID;
            while (isDigit(*first))
            {
                if (++first == last)
                    return type;
            }
            return ValueType::INVALID;
        }

        ValueType_t getBinaryValueType(const char* first, const char* last)
        {
            return getValueType(first, last,
                                [](char c) { return getDigit(c) <= 1; },
                                ValueType::BIN_INTEGER);
        }

        ValueType_t getOctalValueType(const char* first, const char* last)
        {
            return getValueType(first, last,
                                [](char c) { return getDigit(c) <= 7; },
                                ValueType::OCT_INTEGER);
        }

        ValueType_t getHexadecimalValueType(const char* first,
                                            const char* last)
        {
            return getValueType(first, last,
                                [](char c) { return isHexDigit(c); },
                                ValueType::HEX_INTEGER);
        }

        ValueType_t getFloatingPointValueType(const char* first,
                                              const char* last)
        {
            if (*first == '.')
            {
                if (++first == last)
                    return ValueType::FLOAT;
                while (getDigit(*first) <= 9)
                {
                    if (++first == last)
                        return ValueType::FLOAT;
                }
                if (*first != 'E' && *first != 'e')
                    return ValueType::INVALID;
            }

            ++first;
            if (*first == '+' || *first == '-')
            {
                if (++first == last)
                    return ValueType::INVALID;
            }
            while (getDigit(*first) <= 9)
            {
                if (++first == last)
                    return ValueType::FLOAT;
            }
            return ValueType::INVALID;
        }

        ValueType_t getNumberValueType(const char* first, const char* last)
        {
            while (getDigit(*first) <= 9)
            {
                if (++first == last)
                    return ValueType::INTEGER;
            }

            switch (*first)
            {
            case '.':
            case 'e':
            case 'E':
                return getFloatingPointValueType(first, last);
            default:
                return ValueType::INVALID;
            }
        }
    }
}
<commit_msg>Recognize hex, oct and binary values with uppercase prefixes.<commit_after>//****************************************************************************
// Copyright © 2015 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2015-12-05.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "GetValueType.hpp"

#include <cstdint>

namespace Yson {

    namespace {
        int getDigit(char c);

        bool isHexDigit(char c);

        template<typename Predicate>
        ValueType_t getValueType(const char* first, const char* last,
                                 Predicate isDigit, ValueType_t type);

        ValueType_t getBinaryValueType(const char* first, const char* last);

        ValueType_t getOctalValueType(const char* first, const char* last);

        ValueType_t getHexadecimalValueType(const char* first,
                                            const char* last);

        ValueType_t getFloatingPointValueType(const char* first,
                                              const char* last);

        ValueType_t getNumberValueType(const char* first, const char* last);
    }

    ValueType_t getValueType(const char* first, const char* last)
    {
        if (first == last)
            return ValueType::INVALID;
        auto assumedType = ValueType_t(ValueType::UNKNOWN);
        if (*first == '-' || *first == '+')
        {
            if (++first == last)
                return ValueType::INVALID;
            assumedType = ValueType::INTEGER;
        }
        if (*first == '0')
        {
            if (++first == last)
                return ValueType::INTEGER;
            switch (*first)
            {
            case 'b':
            case 'B':
                return getBinaryValueType(++first, last);
            case 'o':
            case 'O':
                return getOctalValueType(++first, last);
            case 'x':
            case 'X':
                return getHexadecimalValueType(++first, last);
            case '.':
            case 'e':
            case 'E':
                return getFloatingPointValueType(first, last);
            default:
                if (getDigit(*first) <= 9)
                {
                    if (++first == last)
                        return ValueType::INTEGER;
                    return getNumberValueType(first, last);
                }
                return ValueType::INVALID;
            }
        }
        else if (getDigit(*first) <= 9)
        {
            if (++first == last)
                return ValueType::INTEGER;
            return getNumberValueType(first, last);
        }

        if (last - first == 8 && std::equal(first, last, "infinity"))
            return ValueType::EXTENDED_FLOAT;
        if (last - first == 3 && std::equal(first, last, "NaN"))
            return ValueType::EXTENDED_FLOAT;

        if (assumedType != ValueType::UNKNOWN)
            return ValueType::INVALID;

        if (last - first == 4 && std::equal(first, last, "true"))
            return ValueType::TRUE_VALUE;
        if (last - first == 4 && std::equal(first, last, "null"))
            return ValueType::NULL_VALUE;
        if (last - first == 5 && std::equal(first, last, "false"))
            return ValueType::FALSE_VALUE;

        return ValueType::INVALID;
    }

    ValueType_t getValueType(const std::pair<const char*, const char*>& value)
    {
        return getValueType(value.first, value.second);
    }

    ValueType_t getValueType(const std::string& s)
    {
        return getValueType(s.data(), s.data() + s.size());
    }

    namespace {

        int getDigit(char c)
        {
            return uint8_t(c) ^ 0x30;
        }

        bool isHexDigit(char c)
        {
            return (getDigit(c) <= 9) ||
                   ('A' <= c && c <= 'F') ||
                   ('a' <= c && c <= 'f');
        }

        template<typename Predicate>
        ValueType_t getValueType(const char* first, const char* last,
                                 Predicate isDigit, ValueType_t type)
        {
            if (first == last)
                return ValueType::INVALID;
            while (isDigit(*first))
            {
                if (++first == last)
                    return type;
            }
            return ValueType::INVALID;
        }

        ValueType_t getBinaryValueType(const char* first, const char* last)
        {
            return getValueType(first, last,
                                [](char c) { return getDigit(c) <= 1; },
                                ValueType::BIN_INTEGER);
        }

        ValueType_t getOctalValueType(const char* first, const char* last)
        {
            return getValueType(first, last,
                                [](char c) { return getDigit(c) <= 7; },
                                ValueType::OCT_INTEGER);
        }

        ValueType_t getHexadecimalValueType(const char* first,
                                            const char* last)
        {
            return getValueType(first, last,
                                [](char c) { return isHexDigit(c); },
                                ValueType::HEX_INTEGER);
        }

        ValueType_t getFloatingPointValueType(const char* first,
                                              const char* last)
        {
            if (*first == '.')
            {
                if (++first == last)
                    return ValueType::FLOAT;
                while (getDigit(*first) <= 9)
                {
                    if (++first == last)
                        return ValueType::FLOAT;
                }
                if (*first != 'E' && *first != 'e')
                    return ValueType::INVALID;
            }

            ++first;
            if (*first == '+' || *first == '-')
            {
                if (++first == last)
                    return ValueType::INVALID;
            }
            while (getDigit(*first) <= 9)
            {
                if (++first == last)
                    return ValueType::FLOAT;
            }
            return ValueType::INVALID;
        }

        ValueType_t getNumberValueType(const char* first, const char* last)
        {
            while (getDigit(*first) <= 9)
            {
                if (++first == last)
                    return ValueType::INTEGER;
            }

            switch (*first)
            {
            case '.':
            case 'e':
            case 'E':
                return getFloatingPointValueType(first, last);
            default:
                return ValueType::INVALID;
            }
        }
    }
}
<|endoftext|>


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

#include "codemaker/options.hxx"

using namespace rtl;

Options::Options()
{
}

Options::~Options()
{

}

const OString& Options::getProgramName() const
{
    return m_program;
}

sal_Bool Options::isValid(const OString& option)
{
    return (m_options.count(option) > 0);
}

const OString Options::getOption(const OString& option)
    throw( IllegalArgument )
{
    if (m_options.count(option) > 0)
    {
        return m_options[option];
    } else
    {
        throw IllegalArgument("Option is not valid or currently not set.");
    }
}

const OptionMap& Options::getOptions()
{
    return m_options;
}

const OString Options::getInputFile(sal_uInt16 index)
    throw( IllegalArgument )
{
    if (index < m_inputFiles.size())
    {
        return m_inputFiles[index];
    } else
    {
        throw IllegalArgument("index is out of bound.");
    }
}

const StringVector& Options::getInputFiles()
{
    return m_inputFiles;
}

OString Options::getExtraInputFile(sal_uInt16 index) const
    throw( IllegalArgument )
{
    if (index < m_extra_input_files.size())
    {
        return m_extra_input_files[index];
    } else
    {
        throw IllegalArgument("index is out of bound.");
    }
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.5.8); FILE MERGED 2006/09/01 17:19:20 kaib 1.5.8.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: options.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:35:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_codemaker.hxx"

#include "codemaker/options.hxx"

using namespace rtl;

Options::Options()
{
}

Options::~Options()
{

}

const OString& Options::getProgramName() const
{
    return m_program;
}

sal_Bool Options::isValid(const OString& option)
{
    return (m_options.count(option) > 0);
}

const OString Options::getOption(const OString& option)
    throw( IllegalArgument )
{
    if (m_options.count(option) > 0)
    {
        return m_options[option];
    } else
    {
        throw IllegalArgument("Option is not valid or currently not set.");
    }
}

const OptionMap& Options::getOptions()
{
    return m_options;
}

const OString Options::getInputFile(sal_uInt16 index)
    throw( IllegalArgument )
{
    if (index < m_inputFiles.size())
    {
        return m_inputFiles[index];
    } else
    {
        throw IllegalArgument("index is out of bound.");
    }
}

const StringVector& Options::getInputFiles()
{
    return m_inputFiles;
}

OString Options::getExtraInputFile(sal_uInt16 index) const
    throw( IllegalArgument )
{
    if (index < m_extra_input_files.size())
    {
        return m_extra_input_files[index];
    } else
    {
        throw IllegalArgument("index is out of bound.");
    }
}

<|endoftext|>