<commit_before>// text.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "text.h"

namespace dukat
{
	TextScene::TextScene(Game2* game2) : Scene2(game2)
	{
		auto layer = game->get_renderer()->create_layer("main", 1.0f);
		layer->stage = RenderStage::OVERLAY;

		auto settings = game->get_settings();

		// Set up default camera centered around origin
		auto window = game->get_window();
		auto camera = std::make_unique<Camera2>(game, Vector2((float)window->get_width(), (float)window->get_height()));
		camera->set_clip(settings.get_float("camera.nearclip"), settings.get_float("camera.farclip"));
		camera->refresh();
		game->get_renderer()->set_camera(std::move(camera));

		// Set up info text
		info_text = game->create_text_mesh();
		info_text->set_size(10.0f);
		std::stringstream ss;
		ss << "I sing the <#red>body electric</>," << std::endl
			<< "The <#yellow>armies</> of those I <#magenta>love</> engirth me and I engirth them," << std::endl
			<< "They will not let me off till I go with them, <#cyan>respond</> to them," << std::endl
			<< "And <#orange>discorrupt</> them, and charge them full with the <#blue>charge</> of the soul." << std::endl << std::endl
			<< "Was it <#purple>doubted</> that those who corrupt their own bodies <#green>conceal</> themselves ?" << std::endl
			<< "And if those who defile the <#tan>living</> are as bad as they who defile the <#brown>dead</> ?" << std::endl
			<< "And if the body does not do <#lightgrey>fully</> as much as the <#mediumgrey>soul</> ?" << std::endl
			<< "And if the body were not the <#darkgreen>soul</>, what is the <#darkgrey>soul</> ?" << std::endl;
		info_text->set_text(ss.str());
		info_text->transform.position = Vector3(-0.5f * (float)info_text->get_width(), -0.5f * (float)info_text->get_height(), 0.0f);
		info_text->transform.update();
		layer->add(info_text.get());

		// Set up debug layer
		auto debug_layer = game->get_renderer()->create_layer("debug", 1000.0f);
		debug_text = game->create_text_mesh();
		debug_text->set_size(12.0f);
		debug_text->transform.position = Vector3(-0.5f * (float)window->get_width(), -0.5f * (float)window->get_height(), 0.0f);
		debug_text->transform.update();
		debug_layer->add(debug_text.get());
		debug_layer->hide();

		game->get<TimerManager>()->create_timer(1.0f, [&]() {
			std::stringstream ss;
			auto window = game->get_window();
			auto cam = game->get_renderer()->get_camera();
			ss << "WIN: " << window->get_width() << "x" << window->get_height()
				<< " VIR: " << cam->transform.dimension.x << "x" << cam->transform.dimension.y
				<< " FPS: " << game->get_fps()
				<< " MESH: " << dukat::perfc.avg(dukat::PerformanceCounter::MESHES)
				<< " VERT: " << dukat::perfc.avg(dukat::PerformanceCounter::VERTICES) << std::endl;
			debug_text->set_text(ss.str());
		}, true);
	}
}

int main(int argc, char** argv)
{
	try
	{
		std::string config = "../assets/text.ini";
		if (argc > 1)
		{
			config = argv[1];
		}
		dukat::Settings settings(config);
		dukat::Game2 app(settings);
		app.add_scene("main", std::make_unique<dukat::TextScene>(&app));
		app.push_scene("main");
		return app.run();
	}
	catch (const std::exception& e)
	{
		dukat::log->error("Application failed with error: {}", e.what());
		return -1;
	}
	return 0;
}<commit_msg>Fixed alignment in text example<commit_after>// text.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "text.h"

namespace dukat
{
	TextScene::TextScene(Game2* game2) : Scene2(game2)
	{
		auto layer = game->get_renderer()->create_layer("main", 1.0f);
		layer->stage = RenderStage::OVERLAY;

		auto settings = game->get_settings();

		// Set up default camera centered around origin
		auto window = game->get_window();
		auto camera = std::make_unique<Camera2>(game, Vector2((float)window->get_width(), (float)window->get_height()));
		camera->set_clip(settings.get_float("camera.nearclip"), settings.get_float("camera.farclip"));
		camera->refresh();
		game->get_renderer()->set_camera(std::move(camera));

		// Set up info text
		info_text = game->create_text_mesh();
		info_text->align = TextMeshInstance::Center;
		info_text->set_size(10.0f);
		std::stringstream ss;
		ss << "I sing the <#red>body electric</>," << std::endl
			<< "The <#yellow>armies</> of those I <#magenta>love</> engirth me and I engirth them," << std::endl
			<< "They will not let me off till I go with them, <#cyan>respond</> to them," << std::endl
			<< "And <#orange>discorrupt</> them, and charge them full with the <#blue>charge</> of the soul." << std::endl << std::endl
			<< "Was it <#purple>doubted</> that those who corrupt their own bodies <#green>conceal</> themselves ?" << std::endl
			<< "And if those who defile the <#tan>living</> are as bad as they who defile the <#brown>dead</> ?" << std::endl
			<< "And if the body does not do <#lightgrey>fully</> as much as the <#mediumgrey>soul</> ?" << std::endl
			<< "And if the body were not the <#darkgreen>soul</>, what is the <#darkgrey>soul</> ?" << std::endl;
		info_text->set_text(ss.str());
		info_text->transform.position = Vector3(0.0f, -0.5f * (float)info_text->get_height(), 0.0f);
		info_text->update(0.0f);
		layer->add(info_text.get());

		// Set up debug layer
		auto debug_layer = game->get_renderer()->create_layer("debug", 1000.0f);
		debug_text = game->create_text_mesh();
		debug_text->set_size(12.0f);
		debug_text->transform.position = Vector3(-0.5f * (float)window->get_width(), -0.5f * (float)window->get_height(), 0.0f);
		debug_text->transform.update();
		debug_layer->add(debug_text.get());
		debug_layer->hide();

		game->get<TimerManager>()->create_timer(1.0f, [&]() {
			std::stringstream ss;
			auto window = game->get_window();
			auto cam = game->get_renderer()->get_camera();
			ss << "WIN: " << window->get_width() << "x" << window->get_height()
				<< " VIR: " << cam->transform.dimension.x << "x" << cam->transform.dimension.y
				<< " FPS: " << game->get_fps()
				<< " MESH: " << dukat::perfc.avg(dukat::PerformanceCounter::MESHES)
				<< " VERT: " << dukat::perfc.avg(dukat::PerformanceCounter::VERTICES) << std::endl;
			debug_text->set_text(ss.str());
		}, true);
	}
}

int main(int argc, char** argv)
{
	try
	{
		std::string config = "../assets/text.ini";
		if (argc > 1)
		{
			config = argv[1];
		}
		dukat::Settings settings(config);
		dukat::Game2 app(settings);
		app.add_scene("main", std::make_unique<dukat::TextScene>(&app));
		app.push_scene("main");
		return app.run();
	}
	catch (const std::exception& e)
	{
		dukat::log->error("Application failed with error: {}", e.what());
		return -1;
	}
	return 0;
}<|endoftext|>


<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>
* Changed: $Id$
*
* Version: $Revision$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief Tests for testing export functions.
*/

#include "test.h" // Brings in the GTest framework
#include "tigl.h"

#include "CTiglTriangularizer.h"
#include "CTiglExportCollada.h"
#include "CCPACSConfigurationManager.h"
#include "CCPACSConfiguration.h"
#include "CCPACSWing.h"

/******************************************************************************/

class tiglExport : public ::testing::Test
{
protected:
    static void SetUpTestCase()
    {
        const char* filename = "TestData/CPACS_21_D150.xml";
        ReturnCode tixiRet;
        TiglReturnCode tiglRet;

        tiglHandle = -1;
        tixiHandle = -1;

        tixiRet = tixiOpenDocument(filename, &tixiHandle);
        ASSERT_TRUE (tixiRet == SUCCESS);
        tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "D150_VAMP", &tiglHandle);
        ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    }

    static void TearDownTestCase()
    {
        ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglHandle) == TIGL_SUCCESS);
        ASSERT_TRUE(tixiCloseDocument(tixiHandle) == SUCCESS);
        tiglHandle = -1;
        tixiHandle = -1;
    }

    virtual void SetUp() {}
    virtual void TearDown() {}

    static TixiDocumentHandle           tixiHandle;
    static TiglCPACSConfigurationHandle tiglHandle;
};

TixiDocumentHandle tiglExport::tixiHandle = 0;
TiglCPACSConfigurationHandle tiglExport::tiglHandle = 0;

class tiglExportSimple : public ::testing::Test
{
protected:
    static void SetUpTestCase()
    {
        const char* filename = "TestData/simpletest.cpacs.xml";
        ReturnCode tixiRet;
        TiglReturnCode tiglRet;

        tiglSimpleHandle = -1;
        tixiSimpleHandle = -1;

        tixiRet = tixiOpenDocument(filename, &tixiSimpleHandle);
        ASSERT_TRUE (tixiRet == SUCCESS);
        tiglRet = tiglOpenCPACSConfiguration(tixiSimpleHandle, "", &tiglSimpleHandle);
        ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    }

    static void TearDownTestCase()
    {
        ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglSimpleHandle) == TIGL_SUCCESS);
        ASSERT_TRUE(tixiCloseDocument(tixiSimpleHandle) == SUCCESS);
        tiglSimpleHandle = -1;
        tixiSimpleHandle = -1;
    }

    virtual void SetUp() {}
    virtual void TearDown() {}

    static TixiDocumentHandle           tixiSimpleHandle;
    static TiglCPACSConfigurationHandle tiglSimpleHandle;
};

TixiDocumentHandle tiglExportSimple::tixiSimpleHandle = 0;
TiglCPACSConfigurationHandle tiglExportSimple::tiglSimpleHandle = 0;

class tiglExportRectangularWing : public ::testing::Test
{
protected:
    static void SetUpTestCase()
    {
        const char* filename = "TestData/simple_rectangle_compseg.xml";
        ReturnCode tixiRet;
        TiglReturnCode tiglRet;

        tiglRectangularWingHandle = -1;
        tixiRectangularWingHandle = -1;

        tixiRet = tixiOpenDocument(filename, &tixiRectangularWingHandle);
        ASSERT_TRUE (tixiRet == SUCCESS);
        tiglRet = tiglOpenCPACSConfiguration(tixiRectangularWingHandle, "", &tiglRectangularWingHandle);
        ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    }

    static void TearDownTestCase()
    {
        ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglRectangularWingHandle) == TIGL_SUCCESS);
        ASSERT_TRUE(tixiCloseDocument(tixiRectangularWingHandle) == SUCCESS);
        tiglRectangularWingHandle = -1;
        tixiRectangularWingHandle = -1;
    }

    virtual void SetUp() {}
    virtual void TearDown() {}

    static TixiDocumentHandle           tixiRectangularWingHandle;
    static TiglCPACSConfigurationHandle tiglRectangularWingHandle;
};

TixiDocumentHandle tiglExportRectangularWing::tixiRectangularWingHandle = 0;
TiglCPACSConfigurationHandle tiglExportRectangularWing::tiglRectangularWingHandle = 0;

/******************************************************************************/

//void tiglxEportMeshedWingVTK_small_example(void)
//{
//    const BRepPrimAPI_MakeCylinder cone(/* radius */ 2.0, /* height */ 8.0);
//    const CTiglExportVtk writer(config);
//    writer.ExportMeshedWingVTK
//}

/**
* Tests tiglWingGetProfileName with invalid CPACS handle.
*/
TEST_F(tiglExport, export_meshed_wing_success)
{
    const char* vtkWingFilename = "TestData/export/D150modelID_wing1.vtp";
    ASSERT_TRUE(tiglExportMeshedWingVTKByIndex(tiglHandle, 1, vtkWingFilename, 0.01) == TIGL_SUCCESS);
}

/**
* Tests tiglWingGetProfileName with invalid CPACS handle.
*/
TEST_F(tiglExport, export_meshed_wing_simple_success)
{
    const char* vtkWingFilename = "TestData/export/D150modelID_wing1_simple.vtp";
    ASSERT_TRUE(tiglExportMeshedWingVTKSimpleByUID(tiglHandle, "D150_VAMP_W1", vtkWingFilename, 0.01) == TIGL_SUCCESS);
}

TEST_F(tiglExport, export_meshed_fuselage_success)
{
    const char* vtkFuselageFilename = "TestData/export/D150modelID_fuselage1.vtp";
    ASSERT_TRUE(tiglExportMeshedFuselageVTKSimpleByUID(tiglHandle, "D150_VAMP_FL1", vtkFuselageFilename, 0.03) == TIGL_SUCCESS);
}

TEST_F(tiglExport, export_fuselage_collada_success)
{
    const char* colladaFuselageFilename = "TestData/export/D150modelID_fuselage1.dae";
    ASSERT_TRUE(tiglExportFuselageColladaByUID(tiglHandle, "D150_VAMP_FL1", colladaFuselageFilename, 0.01) == TIGL_SUCCESS);
}

TEST_F(tiglExport, export_wing_collada_success)
{
    const char* colladaWing1Filename = "TestData/export/D150modelID_wing1.dae";
    ASSERT_TRUE(tiglExportWingColladaByUID(tiglHandle, "D150_VAMP_W1", colladaWing1Filename, 0.001) == TIGL_SUCCESS);
    const char* colladaWing2Filename = "TestData/export/D150modelID_wing2.dae";
    ASSERT_TRUE(tiglExportWingColladaByUID(tiglHandle, "D150_VAMP_HL1", colladaWing2Filename, 0.001) == TIGL_SUCCESS);
    const char* colladaWing3Filename = "TestData/export/D150modelID_wing3.dae";
    ASSERT_TRUE(tiglExportWingColladaByUID(tiglHandle, "D150_VAMP_SL1", colladaWing3Filename, 0.001) == TIGL_SUCCESS);
}

TEST_F(tiglExportSimple, export_wing_collada)
{
    tigl::CCPACSConfigurationManager & manager = tigl::CCPACSConfigurationManager::GetInstance();
    tigl::CCPACSConfiguration & config = manager.GetConfiguration(tiglSimpleHandle);
    tigl::CCPACSWing& wing = config.GetWing(1);

    tigl::CTiglTriangularizer t(wing.GetLoft()->Shape(), 0.001);

    TiglReturnCode ret = tigl::CTiglExportCollada::writeToDisc(t, "simple_wing", "TestData/export/simpletest_wing.dae");

    ASSERT_EQ(TIGL_SUCCESS, ret);
}

// check if face names were set correctly in the case with a trailing edge
TEST_F(tiglExportSimple, check_face_traits)
{
    tiglLogSetVerbosity(TILOG_ERROR);
    ASSERT_EQ(TIGL_SUCCESS, tiglExportIGES(tiglSimpleHandle,"TestData/export/simpletest.iges"));
    ASSERT_EQ(TIGL_SUCCESS, tiglExportFusedWingFuselageIGES(tiglSimpleHandle,"TestData/export/simpletest_fused.iges"));
}

// check if face names were set correctly in the case without a trailing edge
TEST_F(tiglExportRectangularWing, check_face_traits)
{
    tiglLogSetVerbosity(TILOG_ERROR);
    ASSERT_EQ(TIGL_SUCCESS, tiglExportIGES(tiglRectangularWingHandle,"TestData/export/rectangular_wing_test.iges"));
    ASSERT_EQ(TIGL_SUCCESS, tiglExportFusedWingFuselageIGES(tiglRectangularWingHandle,"TestData/export/rectangular_wing_test_fused.iges"));
}
<commit_msg>Removed error messages from tests<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>
* Changed: $Id$
*
* Version: $Revision$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief Tests for testing export functions.
*/

#include "test.h" // Brings in the GTest framework
#include "tigl.h"

#include "CTiglTriangularizer.h"
#include "CTiglExportCollada.h"
#include "CCPACSConfigurationManager.h"
#include "CCPACSConfiguration.h"
#include "CCPACSWing.h"

/******************************************************************************/

class tiglExport : public ::testing::Test
{
protected:
    static void SetUpTestCase()
    {
        const char* filename = "TestData/CPACS_21_D150.xml";
        ReturnCode tixiRet;
        TiglReturnCode tiglRet;

        tiglHandle = -1;
        tixiHandle = -1;

        tixiRet = tixiOpenDocument(filename, &tixiHandle);
        ASSERT_TRUE (tixiRet == SUCCESS);
        tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "D150_VAMP", &tiglHandle);
        ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    }

    static void TearDownTestCase()
    {
        ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglHandle) == TIGL_SUCCESS);
        ASSERT_TRUE(tixiCloseDocument(tixiHandle) == SUCCESS);
        tiglHandle = -1;
        tixiHandle = -1;
    }

    virtual void SetUp() {}
    virtual void TearDown() {}

    static TixiDocumentHandle           tixiHandle;
    static TiglCPACSConfigurationHandle tiglHandle;
};

TixiDocumentHandle tiglExport::tixiHandle = 0;
TiglCPACSConfigurationHandle tiglExport::tiglHandle = 0;

class tiglExportSimple : public ::testing::Test
{
protected:
    static void SetUpTestCase()
    {
        const char* filename = "TestData/simpletest.cpacs.xml";
        ReturnCode tixiRet;
        TiglReturnCode tiglRet;

        tiglSimpleHandle = -1;
        tixiSimpleHandle = -1;

        tixiRet = tixiOpenDocument(filename, &tixiSimpleHandle);
        ASSERT_TRUE (tixiRet == SUCCESS);
        tiglRet = tiglOpenCPACSConfiguration(tixiSimpleHandle, "", &tiglSimpleHandle);
        ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    }

    static void TearDownTestCase()
    {
        ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglSimpleHandle) == TIGL_SUCCESS);
        ASSERT_TRUE(tixiCloseDocument(tixiSimpleHandle) == SUCCESS);
        tiglSimpleHandle = -1;
        tixiSimpleHandle = -1;
    }

    virtual void SetUp() {}
    virtual void TearDown() {}

    static TixiDocumentHandle           tixiSimpleHandle;
    static TiglCPACSConfigurationHandle tiglSimpleHandle;
};

TixiDocumentHandle tiglExportSimple::tixiSimpleHandle = 0;
TiglCPACSConfigurationHandle tiglExportSimple::tiglSimpleHandle = 0;

class tiglExportRectangularWing : public ::testing::Test
{
protected:
    static void SetUpTestCase()
    {
        const char* filename = "TestData/simple_rectangle_compseg.xml";
        ReturnCode tixiRet;
        TiglReturnCode tiglRet;

        tiglRectangularWingHandle = -1;
        tixiRectangularWingHandle = -1;

        tixiRet = tixiOpenDocument(filename, &tixiRectangularWingHandle);
        ASSERT_TRUE (tixiRet == SUCCESS);
        tiglRet = tiglOpenCPACSConfiguration(tixiRectangularWingHandle, "", &tiglRectangularWingHandle);
        ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
    }

    static void TearDownTestCase()
    {
        ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglRectangularWingHandle) == TIGL_SUCCESS);
        ASSERT_TRUE(tixiCloseDocument(tixiRectangularWingHandle) == SUCCESS);
        tiglRectangularWingHandle = -1;
        tixiRectangularWingHandle = -1;
    }

    virtual void SetUp() {}
    virtual void TearDown() {}

    static TixiDocumentHandle           tixiRectangularWingHandle;
    static TiglCPACSConfigurationHandle tiglRectangularWingHandle;
};

TixiDocumentHandle tiglExportRectangularWing::tixiRectangularWingHandle = 0;
TiglCPACSConfigurationHandle tiglExportRectangularWing::tiglRectangularWingHandle = 0;

/******************************************************************************/

//void tiglxEportMeshedWingVTK_small_example(void)
//{
//    const BRepPrimAPI_MakeCylinder cone(/* radius */ 2.0, /* height */ 8.0);
//    const CTiglExportVtk writer(config);
//    writer.ExportMeshedWingVTK
//}

/**
* Tests tiglWingGetProfileName with invalid CPACS handle.
*/
TEST_F(tiglExport, export_meshed_wing_success)
{
    const char* vtkWingFilename = "TestData/export/D150modelID_wing1.vtp";
    ASSERT_TRUE(tiglExportMeshedWingVTKByIndex(tiglHandle, 1, vtkWingFilename, 0.01) == TIGL_SUCCESS);
}

/**
* Tests tiglWingGetProfileName with invalid CPACS handle.
*/
TEST_F(tiglExport, export_meshed_wing_simple_success)
{
    const char* vtkWingFilename = "TestData/export/D150modelID_wing1_simple.vtp";
    ASSERT_TRUE(tiglExportMeshedWingVTKSimpleByUID(tiglHandle, "D150_VAMP_W1", vtkWingFilename, 0.01) == TIGL_SUCCESS);
}

TEST_F(tiglExport, export_meshed_fuselage_success)
{
    const char* vtkFuselageFilename = "TestData/export/D150modelID_fuselage1.vtp";
    ASSERT_TRUE(tiglExportMeshedFuselageVTKSimpleByUID(tiglHandle, "D150_VAMP_FL1", vtkFuselageFilename, 0.03) == TIGL_SUCCESS);
}

TEST_F(tiglExport, export_fuselage_collada_success)
{
    const char* colladaFuselageFilename = "TestData/export/D150modelID_fuselage1.dae";
    ASSERT_TRUE(tiglExportFuselageColladaByUID(tiglHandle, "D150_VAMP_FL1", colladaFuselageFilename, 0.01) == TIGL_SUCCESS);
}

TEST_F(tiglExport, export_wing_collada_success)
{
    const char* colladaWing1Filename = "TestData/export/D150modelID_wing1.dae";
    ASSERT_TRUE(tiglExportWingColladaByUID(tiglHandle, "D150_VAMP_W1", colladaWing1Filename, 0.001) == TIGL_SUCCESS);
    const char* colladaWing2Filename = "TestData/export/D150modelID_wing2.dae";
    ASSERT_TRUE(tiglExportWingColladaByUID(tiglHandle, "D150_VAMP_HL1", colladaWing2Filename, 0.001) == TIGL_SUCCESS);
    const char* colladaWing3Filename = "TestData/export/D150modelID_wing3.dae";
    ASSERT_TRUE(tiglExportWingColladaByUID(tiglHandle, "D150_VAMP_SL1", colladaWing3Filename, 0.001) == TIGL_SUCCESS);
}

TEST_F(tiglExportSimple, export_wing_collada)
{
    tigl::CCPACSConfigurationManager & manager = tigl::CCPACSConfigurationManager::GetInstance();
    tigl::CCPACSConfiguration & config = manager.GetConfiguration(tiglSimpleHandle);
    tigl::CCPACSWing& wing = config.GetWing(1);

    tigl::CTiglTriangularizer t(wing.GetLoft()->Shape(), 0.001);

    TiglReturnCode ret = tigl::CTiglExportCollada::writeToDisc(t, "simple_wing", "TestData/export/simpletest_wing.dae");

    ASSERT_EQ(TIGL_SUCCESS, ret);
}

// check if face names were set correctly in the case with a trailing edge
TEST_F(tiglExportSimple, check_face_traits)
{
    ASSERT_EQ(TIGL_SUCCESS, tiglExportIGES(tiglSimpleHandle,"TestData/export/simpletest.iges"));
    ASSERT_EQ(TIGL_SUCCESS, tiglExportFusedWingFuselageIGES(tiglSimpleHandle,"TestData/export/simpletest_fused.iges"));
}

// check if face names were set correctly in the case without a trailing edge
TEST_F(tiglExportRectangularWing, check_face_traits)
{
    ASSERT_EQ(TIGL_SUCCESS, tiglExportIGES(tiglRectangularWingHandle,"TestData/export/rectangular_wing_test.iges"));
    ASSERT_EQ(TIGL_SUCCESS, tiglExportFusedWingFuselageIGES(tiglRectangularWingHandle,"TestData/export/rectangular_wing_test_fused.iges"));
}
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2014 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include <gtest/gtest.h>

#include <QtTest/QSignalSpy>
#include <QtCore/QTimer>
#include <QtWebSockets/QWebSocket>

#include "joynr/IMessaging.h"
#include "joynr/system/RoutingTypes/WebSocketAddress.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/system/RoutingTypes/ChannelAddress.h"
#include "joynr/system/RoutingTypes/CommonApiDbusAddress.h"
#include "joynr/system/RoutingTypes/BrowserAddress.h"

#include "libjoynr/websocket/WebSocketMessagingStubFactory.h"
#include "libjoynr/websocket/WebSocketMessagingStub.h"

#include "utils/MockObjects.h"

using namespace ::testing;

namespace joynr {

class WebSocketMessagingStubFactoryTest : public testing::Test {
public:
    WebSocketMessagingStubFactoryTest() :
        webSocketServerAddress(joynr::system::RoutingTypes::WebSocketProtocol::WS, "localhost", 42, "path"),
        webSocketClientAddress("clientId"),
        channelAddress("channelId"),
        commonApiDbusAddress("domain", "serviceName", "participantId"),
        browserAddress("windowId")
    {
    }

    virtual void TearDown() {
    }

protected:
    ADD_LOGGER(WebSocketMessagingStubFactoryTest);
    joynr::system::RoutingTypes::WebSocketAddress webSocketServerAddress;
    joynr::system::RoutingTypes::WebSocketClientAddress webSocketClientAddress;
    joynr::system::RoutingTypes::ChannelAddress channelAddress;
    joynr::system::RoutingTypes::CommonApiDbusAddress commonApiDbusAddress;
    joynr::system::RoutingTypes::BrowserAddress browserAddress;
};

INIT_LOGGER(WebSocketMessagingStubFactoryTest);

TEST_F(WebSocketMessagingStubFactoryTest, canCreateWebSocketAddressses) {
    WebSocketMessagingStubFactory factory;

    EXPECT_TRUE(factory.canCreate(webSocketClientAddress));
    EXPECT_TRUE(factory.canCreate(webSocketServerAddress));
}

TEST_F(WebSocketMessagingStubFactoryTest, canOnlyCreateWebSocketAddressses) {
    WebSocketMessagingStubFactory factory;

    EXPECT_FALSE(factory.canCreate(channelAddress));
    EXPECT_FALSE(factory.canCreate(commonApiDbusAddress));
    EXPECT_FALSE(factory.canCreate(browserAddress));
}

TEST_F(WebSocketMessagingStubFactoryTest, createReturnsNullForUnknownClient) {
    WebSocketMessagingStubFactory factory;

    EXPECT_TRUE((factory.create(webSocketClientAddress)).get() == 0);
}

TEST_F(WebSocketMessagingStubFactoryTest, createReturnsMessagingStub) {
    WebSocketMessagingStubFactory factory;
    MockWebSocketClient* clientWebsocket = new MockWebSocketClient();
    QWebSocket* serverWebsocket = new QWebSocket();
    MockQWebSocketSendWrapper* wrapper = new MockQWebSocketSendWrapper(serverWebsocket);

    factory.addClient(new joynr::system::RoutingTypes::WebSocketClientAddress(webSocketClientAddress), clientWebsocket);
    factory.addServer(webSocketServerAddress, wrapper);
    EXPECT_TRUE(factory.create(webSocketClientAddress).get() != NULL);
    EXPECT_TRUE(factory.create(webSocketServerAddress).get() != NULL);

    // Terminate call is needed if context was created. This is normally done within the runtime
    clientWebsocket->terminate();
}

TEST_F(WebSocketMessagingStubFactoryTest, closedMessagingStubsAreRemoved) {
    WebSocketMessagingStubFactory factory;
    MockWebSocketClient* websocket = new MockWebSocketClient();

    factory.addClient(new joynr::system::RoutingTypes::WebSocketClientAddress(webSocketClientAddress), websocket);
    EXPECT_TRUE(factory.canCreate(webSocketClientAddress));
    std::shared_ptr<IMessaging> messagingStub(factory.create(webSocketClientAddress));
    std::shared_ptr<WebSocketMessagingStub> wsMessagingStub(std::dynamic_pointer_cast<WebSocketMessagingStub>(messagingStub));
    EXPECT_TRUE(messagingStub.get() != NULL);

    EXPECT_CALL(*websocket, dtorCalled());
    std::thread(&MockWebSocketClient::signalDisconnect, websocket).detach();

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    EXPECT_TRUE((factory.create(webSocketClientAddress)).get() == NULL);
}

TEST_F(WebSocketMessagingStubFactoryTest, removeClientRemovesMessagingStub) {
    WebSocketMessagingStubFactory factory;
    WebSocketClient* websocket = new MockWebSocketClient();

    factory.addClient(new joynr::system::RoutingTypes::WebSocketClientAddress(webSocketClientAddress), websocket);
    EXPECT_TRUE(factory.create(webSocketClientAddress).get() != nullptr);
    EXPECT_CALL(*static_cast<MockWebSocketClient*>(websocket), dtorCalled());
    factory.removeClient(webSocketClientAddress);
    EXPECT_TRUE((factory.create(webSocketClientAddress)).get() == nullptr);
}

TEST_F(WebSocketMessagingStubFactoryTest, convertWebSocketAddressToUrl) {
    joynr::system::RoutingTypes::WebSocketAddress wsAddress(
                joynr::system::RoutingTypes::WebSocketProtocol::WS,
                "localhost",
                42,
                "/some/path/"
    );
    Url expectedWsUrl("ws://localhost:42/some/path/");

    Url wsUrl(WebSocketMessagingStubFactory::convertWebSocketAddressToUrl(wsAddress));
    EXPECT_EQ(expectedWsUrl, wsUrl);

    joynr::system::RoutingTypes::WebSocketAddress wssAddress(
                joynr::system::RoutingTypes::WebSocketProtocol::WSS,
                "localhost",
                42,
                "/some/path"
    );
    Url expectedWssUrl("wss://localhost:42/some/path");

    Url wssUrl(WebSocketMessagingStubFactory::convertWebSocketAddressToUrl(wssAddress));
    EXPECT_EQ(expectedWssUrl, wssUrl);
}

} // namespace joynr
<commit_msg>[C++] replaced NULL by nullptr in WebSocketMessagingStubFactoryTest<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2014 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
#include <gtest/gtest.h>

#include <QtTest/QSignalSpy>
#include <QtCore/QTimer>
#include <QtWebSockets/QWebSocket>

#include "joynr/IMessaging.h"
#include "joynr/system/RoutingTypes/WebSocketAddress.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/system/RoutingTypes/ChannelAddress.h"
#include "joynr/system/RoutingTypes/CommonApiDbusAddress.h"
#include "joynr/system/RoutingTypes/BrowserAddress.h"

#include "libjoynr/websocket/WebSocketMessagingStubFactory.h"
#include "libjoynr/websocket/WebSocketMessagingStub.h"

#include "utils/MockObjects.h"

using namespace ::testing;

namespace joynr {

class WebSocketMessagingStubFactoryTest : public testing::Test {
public:
    WebSocketMessagingStubFactoryTest() :
        webSocketServerAddress(joynr::system::RoutingTypes::WebSocketProtocol::WS, "localhost", 42, "path"),
        webSocketClientAddress("clientId"),
        channelAddress("channelId"),
        commonApiDbusAddress("domain", "serviceName", "participantId"),
        browserAddress("windowId")
    {
    }

    virtual void TearDown() {
    }

protected:
    ADD_LOGGER(WebSocketMessagingStubFactoryTest);
    joynr::system::RoutingTypes::WebSocketAddress webSocketServerAddress;
    joynr::system::RoutingTypes::WebSocketClientAddress webSocketClientAddress;
    joynr::system::RoutingTypes::ChannelAddress channelAddress;
    joynr::system::RoutingTypes::CommonApiDbusAddress commonApiDbusAddress;
    joynr::system::RoutingTypes::BrowserAddress browserAddress;
};

INIT_LOGGER(WebSocketMessagingStubFactoryTest);

TEST_F(WebSocketMessagingStubFactoryTest, canCreateWebSocketAddressses) {
    WebSocketMessagingStubFactory factory;

    EXPECT_TRUE(factory.canCreate(webSocketClientAddress));
    EXPECT_TRUE(factory.canCreate(webSocketServerAddress));
}

TEST_F(WebSocketMessagingStubFactoryTest, canOnlyCreateWebSocketAddressses) {
    WebSocketMessagingStubFactory factory;

    EXPECT_FALSE(factory.canCreate(channelAddress));
    EXPECT_FALSE(factory.canCreate(commonApiDbusAddress));
    EXPECT_FALSE(factory.canCreate(browserAddress));
}

TEST_F(WebSocketMessagingStubFactoryTest, createReturnsNullForUnknownClient) {
    WebSocketMessagingStubFactory factory;

    EXPECT_TRUE((factory.create(webSocketClientAddress)).get() == 0);
}

TEST_F(WebSocketMessagingStubFactoryTest, createReturnsMessagingStub) {
    WebSocketMessagingStubFactory factory;
    MockWebSocketClient* clientWebsocket = new MockWebSocketClient();
    QWebSocket* serverWebsocket = new QWebSocket();
    MockQWebSocketSendWrapper* wrapper = new MockQWebSocketSendWrapper(serverWebsocket);

    factory.addClient(new joynr::system::RoutingTypes::WebSocketClientAddress(webSocketClientAddress), clientWebsocket);
    factory.addServer(webSocketServerAddress, wrapper);
    EXPECT_TRUE(factory.create(webSocketClientAddress).get() != nullptr);
    EXPECT_TRUE(factory.create(webSocketServerAddress).get() != nullptr);

    // Terminate call is needed if context was created. This is normally done within the runtime
    clientWebsocket->terminate();
}

TEST_F(WebSocketMessagingStubFactoryTest, closedMessagingStubsAreRemoved) {
    WebSocketMessagingStubFactory factory;
    MockWebSocketClient* websocket = new MockWebSocketClient();

    factory.addClient(new joynr::system::RoutingTypes::WebSocketClientAddress(webSocketClientAddress), websocket);
    EXPECT_TRUE(factory.canCreate(webSocketClientAddress));
    std::shared_ptr<IMessaging> messagingStub(factory.create(webSocketClientAddress));
    std::shared_ptr<WebSocketMessagingStub> wsMessagingStub(std::dynamic_pointer_cast<WebSocketMessagingStub>(messagingStub));
    EXPECT_TRUE(messagingStub.get() != nullptr);

    EXPECT_CALL(*websocket, dtorCalled());
    std::thread(&MockWebSocketClient::signalDisconnect, websocket).detach();

    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    EXPECT_TRUE((factory.create(webSocketClientAddress)).get() == nullptr);
}

TEST_F(WebSocketMessagingStubFactoryTest, removeClientRemovesMessagingStub) {
    WebSocketMessagingStubFactory factory;
    WebSocketClient* websocket = new MockWebSocketClient();

    factory.addClient(new joynr::system::RoutingTypes::WebSocketClientAddress(webSocketClientAddress), websocket);
    EXPECT_TRUE(factory.create(webSocketClientAddress).get() != nullptr);
    EXPECT_CALL(*static_cast<MockWebSocketClient*>(websocket), dtorCalled());
    factory.removeClient(webSocketClientAddress);
    EXPECT_TRUE((factory.create(webSocketClientAddress)).get() == nullptr);
}

TEST_F(WebSocketMessagingStubFactoryTest, convertWebSocketAddressToUrl) {
    joynr::system::RoutingTypes::WebSocketAddress wsAddress(
                joynr::system::RoutingTypes::WebSocketProtocol::WS,
                "localhost",
                42,
                "/some/path/"
    );
    Url expectedWsUrl("ws://localhost:42/some/path/");

    Url wsUrl(WebSocketMessagingStubFactory::convertWebSocketAddressToUrl(wsAddress));
    EXPECT_EQ(expectedWsUrl, wsUrl);

    joynr::system::RoutingTypes::WebSocketAddress wssAddress(
                joynr::system::RoutingTypes::WebSocketProtocol::WSS,
                "localhost",
                42,
                "/some/path"
    );
    Url expectedWssUrl("wss://localhost:42/some/path");

    Url wssUrl(WebSocketMessagingStubFactory::convertWebSocketAddressToUrl(wssAddress));
    EXPECT_EQ(expectedWssUrl, wssUrl);
}

} // namespace joynr
<|endoftext|>


<commit_before>/**
 * \file
 * \brief PoolAllocator class header
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-10
 */

#ifndef INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
#define INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_

#include "distortos/allocators/AllocatorBase.hpp"

namespace distortos
{

namespace allocators
{

/**
 * \brief PoolAllocator class is a generic allocator which uses pool.
 *
 * \param T is the allocated type
 * \param PoolType is the type of pool used by allocator
 */

template<typename T, typename PoolType>
class PoolAllocator : public AllocatorBase<T>
{
public:

	/// alias of PoolType template parameter
	using Pool = PoolType;

	/// base of PoolAllocator
	using Base = AllocatorBase<T>;

	using typename Base::value_type;
	using typename Base::pointer;
	using typename Base::const_pointer;
	using typename Base::reference;
	using typename Base::const_reference;
	using typename Base::size_type;

	/**
	 * \brief Rebinds allocator to different type.
	 *
	 * \param U is the allocated type
	 */

	template<typename U>
	struct rebind
	{
		/// type of rebound allocator
		using other = PoolAllocator<U, Pool>;
	};

	/**
	 * \brief PoolAllocator's constructor
	 *
	 * \param [in] pool is a reference to pool used by allocator
	 */

	constexpr explicit PoolAllocator(Pool& pool) :
			pool_(pool)
	{

	}

	/**
	 * \brief PoolAllocator's copy constructor
	 *
	 * \param U is the allocated type
	 *
	 * \param [in] other is a reference to PoolAllocator which will be copied
	 */

	template<typename U>
	constexpr explicit PoolAllocator(const PoolAllocator<U, Pool>& other) :
			pool_(other.pool_)
	{

	}

	/**
	 * \brief Allocates raw storage.
	 *
	 * \param [in] size is the number of elements (each of size sizeof(value_type)) to be allocated
	 * \param [in] hint is the hint that may be used to improve locality
	 *
	 * \return pointer to allocated storage
	 */

	pointer allocate(size_type size, const void* = nullptr)
	{
		return static_cast<T*>(pool_.allocate(size * sizeof(T)));
	}

	/**
	 * \brief Deallocates raw storage.
	 *
	 * \param [in] storage is the pointer to deallocated storage
	 * \param [in] size is the number of elements (each of size sizeof(value_type)) to be deallocated
	 */

	void deallocate(pointer storage, size_type size)
	{
		pool_.deallocate(storage, size);
	}

private:

	/// reference to pool used by allocator
	Pool& pool_;

	template<typename U, typename OtherPoolType>
	friend class PoolAllocator;

	template<typename T1, typename T2, typename OtherPoolType>
	friend bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right);
};

/**
 * \brief PoolAllocator operator==
 *
 * \param T1 is the type allocated by left PoolAllocator
 * \param T2 is the type allocated by right PoolAllocator
 * \param OtherPoolType is the type of pool used by both allocators
 *
 * \param [in] left is a reference to left PoolAllocator
 * \param [in] right is a reference to right PoolAllocator
 *
 * \return true if the allocators are equal, false otherwise
 */

template<typename T1, typename T2, typename OtherPoolType>
inline bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
	return &left.pool_ == &right.pool_;
}

/**
 * \brief PoolAllocator operator!=
 *
 * \param T1 is the type allocated by left PoolAllocator
 * \param T2 is the type allocated by right PoolAllocator
 * \param OtherPoolType is the type of pool used by both allocators
 *
 * \param [in] left is a reference to left PoolAllocator
 * \param [in] right is a reference to right PoolAllocator
 *
 * \return true if the allocators are not equal, false otherwise
 */

template<typename T1, typename T2, typename OtherPoolType>
inline bool operator!=(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
	return !(left == right);
}

}	// namespace allocators

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
<commit_msg>PoolAllocator: a little bit of const-ness<commit_after>/**
 * \file
 * \brief PoolAllocator class header
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-11
 */

#ifndef INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
#define INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_

#include "distortos/allocators/AllocatorBase.hpp"

namespace distortos
{

namespace allocators
{

/**
 * \brief PoolAllocator class is a generic allocator which uses pool.
 *
 * \param T is the allocated type
 * \param PoolType is the type of pool used by allocator
 */

template<typename T, typename PoolType>
class PoolAllocator : public AllocatorBase<T>
{
public:

	/// alias of PoolType template parameter
	using Pool = PoolType;

	/// base of PoolAllocator
	using Base = AllocatorBase<T>;

	using typename Base::value_type;
	using typename Base::pointer;
	using typename Base::const_pointer;
	using typename Base::reference;
	using typename Base::const_reference;
	using typename Base::size_type;

	/**
	 * \brief Rebinds allocator to different type.
	 *
	 * \param U is the allocated type
	 */

	template<typename U>
	struct rebind
	{
		/// type of rebound allocator
		using other = PoolAllocator<U, Pool>;
	};

	/**
	 * \brief PoolAllocator's constructor
	 *
	 * \param [in] pool is a reference to pool used by allocator
	 */

	constexpr explicit PoolAllocator(Pool& pool) :
			pool_(pool)
	{

	}

	/**
	 * \brief PoolAllocator's copy constructor
	 *
	 * \param U is the allocated type
	 *
	 * \param [in] other is a reference to PoolAllocator which will be copied
	 */

	template<typename U>
	constexpr explicit PoolAllocator(const PoolAllocator<U, Pool>& other) :
			pool_(other.pool_)
	{

	}

	/**
	 * \brief Allocates raw storage.
	 *
	 * \param [in] size is the number of elements (each of size sizeof(value_type)) to be allocated
	 * \param [in] hint is the hint that may be used to improve locality
	 *
	 * \return pointer to allocated storage
	 */

	pointer allocate(const size_type size, const void* = nullptr)
	{
		return static_cast<T*>(pool_.allocate(size * sizeof(T)));
	}

	/**
	 * \brief Deallocates raw storage.
	 *
	 * \param [in] storage is the pointer to deallocated storage
	 * \param [in] size is the number of elements (each of size sizeof(value_type)) to be deallocated
	 */

	void deallocate(const pointer storage, const size_type size)
	{
		pool_.deallocate(storage, size);
	}

private:

	/// reference to pool used by allocator
	Pool& pool_;

	template<typename U, typename OtherPoolType>
	friend class PoolAllocator;

	template<typename T1, typename T2, typename OtherPoolType>
	friend bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right);
};

/**
 * \brief PoolAllocator operator==
 *
 * \param T1 is the type allocated by left PoolAllocator
 * \param T2 is the type allocated by right PoolAllocator
 * \param OtherPoolType is the type of pool used by both allocators
 *
 * \param [in] left is a reference to left PoolAllocator
 * \param [in] right is a reference to right PoolAllocator
 *
 * \return true if the allocators are equal, false otherwise
 */

template<typename T1, typename T2, typename OtherPoolType>
inline bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
	return &left.pool_ == &right.pool_;
}

/**
 * \brief PoolAllocator operator!=
 *
 * \param T1 is the type allocated by left PoolAllocator
 * \param T2 is the type allocated by right PoolAllocator
 * \param OtherPoolType is the type of pool used by both allocators
 *
 * \param [in] left is a reference to left PoolAllocator
 * \param [in] right is a reference to right PoolAllocator
 *
 * \return true if the allocators are not equal, false otherwise
 */

template<typename T1, typename T2, typename OtherPoolType>
inline bool operator!=(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
	return !(left == right);
}

}	// namespace allocators

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#ifdef GPR_ANDROID

#include <android/log.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

static android_LogPriority severity_to_log_priority(gpr_log_severity severity) {
  switch (severity) {
    case GPR_LOG_SEVERITY_DEBUG:
      return ANDROID_LOG_DEBUG;
    case GPR_LOG_SEVERITY_INFO:
      return ANDROID_LOG_INFO;
    case GPR_LOG_SEVERITY_ERROR:
      return ANDROID_LOG_ERROR;
  }
  return ANDROID_LOG_DEFAULT;
}

extern "C" void gpr_log(const char *file, int line, gpr_log_severity severity,
                        const char *format, ...) {
  char *message = NULL;
  va_list args;
  va_start(args, format);
  vasprintf(&message, format, args);
  va_end(args);
  gpr_log_message(file, line, severity, message);
  free(message);
}

extern "C" void gpr_default_log(gpr_log_func_args *args) {
  char *final_slash;
  const char *display_file;
  char *output = NULL;

  final_slash = strrchr(args->file, '/');
  if (final_slash == NULL)
    display_file = args->file;
  else
    display_file = final_slash + 1;

  asprintf(&output, "%s:%d] %s", display_file, args->line, args->message);

  __android_log_write(severity_to_log_priority(args->severity), "GRPC", output);

  /* allocated by asprintf => use free, not gpr_free */
  free(output);
}

#endif /* GPR_ANDROID */
<commit_msg>const required in log_android.cc<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <grpc/support/port_platform.h>

#ifdef GPR_ANDROID

#include <android/log.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

static android_LogPriority severity_to_log_priority(gpr_log_severity severity) {
  switch (severity) {
    case GPR_LOG_SEVERITY_DEBUG:
      return ANDROID_LOG_DEBUG;
    case GPR_LOG_SEVERITY_INFO:
      return ANDROID_LOG_INFO;
    case GPR_LOG_SEVERITY_ERROR:
      return ANDROID_LOG_ERROR;
  }
  return ANDROID_LOG_DEFAULT;
}

extern "C" void gpr_log(const char *file, int line, gpr_log_severity severity,
                        const char *format, ...) {
  char *message = NULL;
  va_list args;
  va_start(args, format);
  vasprintf(&message, format, args);
  va_end(args);
  gpr_log_message(file, line, severity, message);
  free(message);
}

extern "C" void gpr_default_log(gpr_log_func_args *args) {
  const char *final_slash;
  const char *display_file;
  char *output = NULL;

  final_slash = strrchr(args->file, '/');
  if (final_slash == NULL)
    display_file = args->file;
  else
    display_file = final_slash + 1;

  asprintf(&output, "%s:%d] %s", display_file, args->line, args->message);

  __android_log_write(severity_to_log_priority(args->severity), "GRPC", output);

  /* allocated by asprintf => use free, not gpr_free */
  free(output);
}

#endif /* GPR_ANDROID */
<|endoftext|>


<commit_before>#include "MeshCuboidParameters.h"

// -- Parameters -- //
//
DEFINE_bool(param_optimize_with_non_linear_constraints, true, "");
DEFINE_bool(param_optimize_training_cuboids, true, "");

DEFINE_int32(param_num_sample_point_neighbors, 8, "");
DEFINE_int32(param_min_num_cuboid_sample_points, 10, "");
DEFINE_int32(param_min_num_symmetric_point_pairs, 50, "");
DEFINE_int32(param_num_cuboid_surface_points, 1000, "");
DEFINE_int32(param_intra_cuboid_symmetry_axis, 0, "");
DEFINE_int32(param_eval_num_neighbor_range_samples, 1001, "");
DEFINE_int32(param_opt_max_iterations, 5, "");

DEFINE_double(param_min_sample_point_confidence, 0.7, "");
DEFINE_double(param_min_num_confidence_tol_sample_points, 0.5, "");
DEFINE_double(param_min_cuboid_bbox_size, 0.1, "");
DEFINE_double(param_min_cuboid_bbox_diag_length, 0.3, "");
DEFINE_double(param_sparse_neighbor_distance, 0.05, "");
DEFINE_double(param_cuboid_split_neighbor_distance, 0.2, "");
DEFINE_double(param_occlusion_test_neighbor_distance, 0.01, "");
DEFINE_double(param_eval_max_neighbor_distance, 0.1, "");
DEFINE_double(param_min_cuboid_overall_visibility, 0.8, "");
DEFINE_double(param_max_potential, 1.0E8, "");
DEFINE_double(param_dummy_potential, 1.0E4, "");
DEFINE_double(param_opt_single_energy_term_weight, 1.0E4, "");
DEFINE_double(param_opt_symmetry_energy_term_weight, 1.0E6, "");
DEFINE_double(param_part_assembly_window_size, 0.1, "");
DEFINE_double(param_part_assembly_voxel_size, 0.01, "");
DEFINE_double(param_part_assembly_voxel_variance, 0.01, "");

//DEFINE_double(param_sim_abs_attr_tol, 0.2, "");
//DEFINE_double(param_zero_tol, 1.0E-6, "");
//
// ---- //

// -- Experiments -- //
//
DEFINE_bool(run_ground_truth_cuboids, false, "");
DEFINE_bool(run_training, false, "");
DEFINE_bool(run_prediction, false, "");
DEFINE_bool(run_part_assembly, false, "");
DEFINE_bool(run_symmetry_detection, false, "");
DEFINE_string(mesh_filename, "", "");

DEFINE_string(data_root_path, "D:/Data/shape2pose/", "");
DEFINE_string(label_info_path, "data/0_body/assembly_chairs/", "");
DEFINE_string(mesh_path, "data/1_input/assembly_chairs/off/", "");
DEFINE_string(sample_path, "data/2_analysis/assembly_chairs/points/even1000/", "");
DEFINE_string(dense_sample_path, "data/2_analysis/assembly_chairs/points/random100000/", "");
DEFINE_string(mesh_label_path, "data/1_input/assembly_chairs/gt/", "");
DEFINE_string(sample_label_path, "data/4_experiments/exp1_assembly_chairs/1_prediction/", "");
DEFINE_string(output_dir, "output", "");
DEFINE_string(training_dir, "training", "");
DEFINE_string(part_assembly_dir, "part_assembly", "");
DEFINE_string(symmetry_detection_dir, "symmetry_detection", "");

DEFINE_string(label_info_filename, "regions.txt", "");
DEFINE_string(label_symmetry_info_filename, "regions_symmetry.txt", "");
DEFINE_string(symmetry_group_info_filename, "symmetry_groups.txt", "");
DEFINE_string(pose_filename, "pose.txt", "");
DEFINE_string(occlusion_pose_filename, "", "");
//DEFINE_string(occlusion_pose_filename, "occlusion_pose.txt", "");

DEFINE_string(single_feature_filename_prefix, "single_feature_", "");
DEFINE_string(pair_feature_filename_prefix, "pair_feature_", "");
DEFINE_string(single_stats_filename_prefix, "single_stats_", "");
DEFINE_string(pair_stats_filename_prefix, "pair_stats_", "");
DEFINE_string(feature_filename_prefix, "feature_", "");
DEFINE_string(transformation_filename_prefix, "transformation_", "");
DEFINE_string(joint_normal_relation_filename_prefix, "joint_normal_", "");
DEFINE_string(cond_normal_relation_filename_prefix, "conditional_normal_", "");
DEFINE_string(object_list_filename, "object_list.txt", "");

DEFINE_double(occlusion_test_radius, 0.01, "");
DEFINE_int32(random_view_seed, 20150416, "");

// To be removed.
//DEFINE_bool(use_symmetric_group_cuboids, false, "");
//
// ---- //<commit_msg>[WARNING] Occlusion test radius is changed to 0.1 (previously 0.01).<commit_after>#include "MeshCuboidParameters.h"

// -- Parameters -- //
//
DEFINE_bool(param_optimize_with_non_linear_constraints, true, "");
DEFINE_bool(param_optimize_training_cuboids, true, "");

DEFINE_int32(param_num_sample_point_neighbors, 8, "");
DEFINE_int32(param_min_num_cuboid_sample_points, 10, "");
DEFINE_int32(param_min_num_symmetric_point_pairs, 50, "");
DEFINE_int32(param_num_cuboid_surface_points, 1000, "");
DEFINE_int32(param_intra_cuboid_symmetry_axis, 0, "");
DEFINE_int32(param_eval_num_neighbor_range_samples, 1001, "");
DEFINE_int32(param_opt_max_iterations, 5, "");

DEFINE_double(param_min_sample_point_confidence, 0.7, "");
DEFINE_double(param_min_num_confidence_tol_sample_points, 0.5, "");
DEFINE_double(param_min_cuboid_bbox_size, 0.1, "");
DEFINE_double(param_min_cuboid_bbox_diag_length, 0.3, "");
DEFINE_double(param_sparse_neighbor_distance, 0.05, "");
DEFINE_double(param_cuboid_split_neighbor_distance, 0.2, "");
DEFINE_double(param_occlusion_test_neighbor_distance, 0.1, "");
DEFINE_double(param_eval_max_neighbor_distance, 0.1, "");
DEFINE_double(param_min_cuboid_overall_visibility, 0.8, "");
DEFINE_double(param_max_potential, 1.0E8, "");
DEFINE_double(param_dummy_potential, 1.0E4, "");
DEFINE_double(param_opt_single_energy_term_weight, 1.0E4, "");
DEFINE_double(param_opt_symmetry_energy_term_weight, 1.0E6, "");
DEFINE_double(param_part_assembly_window_size, 0.1, "");
DEFINE_double(param_part_assembly_voxel_size, 0.01, "");
DEFINE_double(param_part_assembly_voxel_variance, 0.01, "");

//DEFINE_double(param_sim_abs_attr_tol, 0.2, "");
//DEFINE_double(param_zero_tol, 1.0E-6, "");
//
// ---- //

// -- Experiments -- //
//
DEFINE_bool(run_ground_truth_cuboids, false, "");
DEFINE_bool(run_training, false, "");
DEFINE_bool(run_prediction, false, "");
DEFINE_bool(run_part_assembly, false, "");
DEFINE_bool(run_symmetry_detection, false, "");
DEFINE_string(mesh_filename, "", "");

DEFINE_string(data_root_path, "D:/Data/shape2pose/", "");
DEFINE_string(label_info_path, "data/0_body/assembly_chairs/", "");
DEFINE_string(mesh_path, "data/1_input/assembly_chairs/off/", "");
DEFINE_string(sample_path, "data/2_analysis/assembly_chairs/points/even1000/", "");
DEFINE_string(dense_sample_path, "data/2_analysis/assembly_chairs/points/random100000/", "");
DEFINE_string(mesh_label_path, "data/1_input/assembly_chairs/gt/", "");
DEFINE_string(sample_label_path, "data/4_experiments/exp1_assembly_chairs/1_prediction/", "");
DEFINE_string(output_dir, "output", "");
DEFINE_string(training_dir, "training", "");
DEFINE_string(part_assembly_dir, "part_assembly", "");
DEFINE_string(symmetry_detection_dir, "symmetry_detection", "");

DEFINE_string(label_info_filename, "regions.txt", "");
DEFINE_string(label_symmetry_info_filename, "regions_symmetry.txt", "");
DEFINE_string(symmetry_group_info_filename, "symmetry_groups.txt", "");
DEFINE_string(pose_filename, "pose.txt", "");
DEFINE_string(occlusion_pose_filename, "", "");
//DEFINE_string(occlusion_pose_filename, "occlusion_pose.txt", "");

DEFINE_string(single_feature_filename_prefix, "single_feature_", "");
DEFINE_string(pair_feature_filename_prefix, "pair_feature_", "");
DEFINE_string(single_stats_filename_prefix, "single_stats_", "");
DEFINE_string(pair_stats_filename_prefix, "pair_stats_", "");
DEFINE_string(feature_filename_prefix, "feature_", "");
DEFINE_string(transformation_filename_prefix, "transformation_", "");
DEFINE_string(joint_normal_relation_filename_prefix, "joint_normal_", "");
DEFINE_string(cond_normal_relation_filename_prefix, "conditional_normal_", "");
DEFINE_string(object_list_filename, "object_list.txt", "");

DEFINE_double(occlusion_test_radius, 0.01, "");
DEFINE_int32(random_view_seed, 20150416, "");

// To be removed.
//DEFINE_bool(use_symmetric_group_cuboids, false, "");
//
// ---- //<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <stdlib.h>
#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"

void print_alert(libtorrent::alert const* a)
{
	using namespace libtorrent;

	if (alert_cast<portmap_error_alert>(a))
	{
		printf("%s","\x1b[32m");
	}
	else if (alert_cast<portmap_alert>(a))
	{
		printf("%s","\x1b[33m");
	}

	printf("[%s] %s\n", time_now_string(), a->message().c_str());
	printf("%s", "\x1b[0m");
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 1)
	{
		fputs("usage: ./upnp_test\n", stderr);
		return 1;
	}

	session* s = new session;
	s->set_alert_mask(alert::port_mapping_notification);

	for (;;)
	{
		alert const* a = s->wait_for_alert(seconds(5));
		if (a == 0)
		{
			s->stop_upnp();
			break;
		}
		std::auto_ptr<alert> holder = s->pop_alert();
		print_alert(holder.get());
	}

	printf("\x1b[1m\n\n===================== done mapping. Now deleting mappings ========================\n\n\n\x1b[0m");

	for (;;)
	{
		alert const* a = s->wait_for_alert(seconds(5));
		if (a == 0) break;
		std::auto_ptr<alert> holder = s->pop_alert();
		print_alert(holder.get());
	}

	delete s;
	s = 0;

	return 0;
}

<commit_msg>update to upnp test<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <stdlib.h>
#include "libtorrent/session.hpp"
#include "libtorrent/alert_types.hpp"

void print_alert(libtorrent::alert const* a)
{
	using namespace libtorrent;

	if (alert_cast<portmap_error_alert>(a))
	{
		printf("%s","\x1b[32m");
	}
	else if (alert_cast<portmap_alert>(a))
	{
		printf("%s","\x1b[33m");
	}

	printf("[%s] %s\n", time_now_string(), a->message().c_str());
	printf("%s", "\x1b[0m");
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	if (argc != 1)
	{
		fputs("usage: ./upnp_test\n", stderr);
		return 1;
	}

	session s;
	s.set_alert_mask(alert::port_mapping_notification);

	for (;;)
	{
		alert const* a = s.wait_for_alert(seconds(5));
		if (a == 0)
		{
			s.stop_upnp();
			break;
		}
		std::auto_ptr<alert> holder = s.pop_alert();
		print_alert(holder.get());
	}

	printf("\x1b[1m\n\n===================== done mapping. Now deleting mappings ========================\n\n\n\x1b[0m");

	for (;;)
	{
		alert const* a = s.wait_for_alert(seconds(5));
		if (a == 0) break;
		std::auto_ptr<alert> holder = s.pop_alert();
		print_alert(holder.get());
	}

	return 0;
}

<|endoftext|>


<commit_before>/**
 * kmacctimap.cpp
 *
 * Copyright (c) 2000-2002 Michael Haeckel <haeckel@kde.org>
 *
 * This file is based on kmacctexppop.cpp by Don Sanders
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "kmacctimap.h"
using KMail::SieveConfig;

#include "broadcaststatus.h"
using KPIM::BroadcastStatus;
#include "kmfoldertree.h"
#include "kmfoldermgr.h"
#include "kmfolderimap.h"
#include "kmmainwin.h"
#include "folderstorage.h"
#include "imapjob.h"
using KMail::ImapJob;
using KMail::ImapAccountBase;
#include "progressmanager.h"
using KPIM::ProgressItem;
using KPIM::ProgressManager;
#include <kio/scheduler.h>
#include <kio/slave.h>
#include <kmessagebox.h>
#include <kdebug.h>

//-----------------------------------------------------------------------------
KMAcctImap::KMAcctImap(KMAcctMgr* aOwner, const QString& aAccountName, uint id):
  KMail::ImapAccountBase(aOwner, aAccountName, id),
  mCountRemainChecks( 0 )
{
  mFolder = 0;
  mNoopTimer.start( 60000 ); // // send a noop every minute
  mOpenFolders.setAutoDelete(true);
  connect(kmkernel->imapFolderMgr(), SIGNAL(changed()),
      this, SLOT(slotUpdateFolderList()));
  connect(&mErrorTimer, SIGNAL(timeout()), SLOT(slotResetConnectionError()));
}

//-----------------------------------------------------------------------------
KMAcctImap::~KMAcctImap()
{
  killAllJobs( true );
}

//-----------------------------------------------------------------------------
QString KMAcctImap::type() const
{
  return "imap";
}

//-----------------------------------------------------------------------------
void KMAcctImap::pseudoAssign( const KMAccount * a ) {
  killAllJobs( true );
  if (mFolder)
  {
    mFolder->setContentState(KMFolderImap::imapNoInformation);
    mFolder->setSubfolderState(KMFolderImap::imapNoInformation);
  }
  ImapAccountBase::pseudoAssign( a );
}

//-----------------------------------------------------------------------------
void KMAcctImap::setImapFolder(KMFolderImap *aFolder)
{
  mFolder = aFolder;
  mFolder->setImapPath(mPrefix);
}

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

bool KMAcctImap::handleError( int errorCode, const QString &errorMsg, KIO::Job* job, const QString& context, bool abortSync )
{
  /* TODO check where to handle this one better. */
  if ( errorCode == KIO::ERR_DOES_NOT_EXIST ) {
    // folder is gone, so reload the folderlist
    if ( mFolder )
      mFolder->listDirectory();
    return true;
  }
  return ImapAccountBase::handleError( errorCode, errorMsg, job, context, abortSync );
}

//-----------------------------------------------------------------------------
void KMAcctImap::killAllJobs( bool disconnectSlave )
{
  QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
  for ( ; it != mapJobData.end(); ++it)
  {
    QPtrList<KMMessage> msgList = (*it).msgList;
    QPtrList<KMMessage>::Iterator it2 = msgList.begin();
    for ( ; it2 != msgList.end(); ++it2 ) {
       KMMessage *msg = *it2;
       if ( msg->transferInProgress() ) {
          kdDebug(5006) << "KMAcctImap::killAllJobs - resetting mail" << endl;
          msg->setTransferInProgress( false );
       }
    }
    if ((*it).parent)
    {
      // clear folder state
      KMFolderImap *fld = static_cast<KMFolderImap*>((*it).parent->storage());
      fld->setCheckingValidity(false);
      fld->setContentState(KMFolderImap::imapNoInformation);
      fld->setSubfolderState(KMFolderImap::imapNoInformation);
      fld->sendFolderComplete(FALSE);
      fld->removeJobs();
    }
    if ( (*it).progressItem )
    {
      (*it).progressItem->setComplete();
    }
  }
  if (mSlave && mapJobData.begin() != mapJobData.end())
  {
    mSlave->kill();
    mSlave = 0;
  }
  // remove the jobs
  mapJobData.clear();
  KMAccount::deleteFolderJobs();
  // make sure that no new-mail-check is blocked
  if (mCountRemainChecks > 0)
  {
    checkDone( false, CheckOK ); // returned 0 new messages
    mCountRemainChecks = 0;
  }
  if ( disconnectSlave && slave() ) {
    KIO::Scheduler::disconnectSlave( slave() );
    mSlave = 0;
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForMessage( KMMessage* msg )
{
  if (!msg) return;
  QPtrListIterator<ImapJob> it( mJobList );
  while ( it.current() )
  {
    ImapJob *job = it.current();
    ++it;
    if ( job->msgList().first() == msg )
    {
      job->kill();
    }
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForFolder( KMFolder* folder )
{
  QPtrListIterator<ImapJob> it( mJobList );
  while ( it.current() )
  {
    ImapJob *job = it.current();
    ++it;
    if ( !job->msgList().isEmpty() && job->msgList().first()->parent() == folder )
    {
      job->kill();
    }
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::removeSlaveJobsForFolder( KMFolder* folder )
{
  // Make sure the folder is not referenced in any kio slave jobs
  QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
  while ( it != mapJobData.end() ) {
     QMap<KIO::Job*, jobData>::Iterator i = it;
     it++;
     if ( (*i).parent ) {
        if ( (*i).parent == folder ) {
           mapJobData.remove(i);
        }
     }
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::cancelMailCheck()
{
  // Make list of folders to reset, like in killAllJobs
  QValueList<KMFolderImap*> folderList;
  QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
  for (; it != mapJobData.end(); ++it) {
    if ( (*it).cancellable && (*it).parent ) {
      folderList << static_cast<KMFolderImap*>((*it).parent->storage());
    }
  }
  // Kill jobs
  // FIXME
  // ImapAccountBase::cancelMailCheck();
  killAllJobs( true );
  // emit folderComplete, this is important for
  // KMAccount::checkingMail() to be reset, in case we restart checking mail later.
  for( QValueList<KMFolderImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {
    KMFolderImap *fld = *it;
    fld->sendFolderComplete(FALSE);
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::processNewMail(bool interactive)
{
  kdDebug() << "processNewMail " << mCheckingSingleFolder << ",status="<<makeConnection()<<endl;
  if (!mFolder || !mFolder->folder() || !mFolder->folder()->child() ||
      makeConnection() == ImapAccountBase::Error)
  {
    mCountRemainChecks = 0;
    mCheckingSingleFolder = false;
    checkDone( false, CheckError );
    return;
  }
  // if necessary then initialize the list of folders which should be checked
  if( mMailCheckFolders.isEmpty() )
  {
    slotUpdateFolderList();
    // if no folders should be checked then the check is finished
    if( mMailCheckFolders.isEmpty() )
    {
      checkDone( false, CheckOK );
      mCheckingSingleFolder = false;
      return;
    }
  }
  // Ok, we're really checking, get a progress item;
  Q_ASSERT( !mMailCheckProgressItem );
  mMailCheckProgressItem =
    ProgressManager::createProgressItem(
        "MailCheckAccount" + name(),
        i18n("Checking account: " ) + name(),
        QString::null, // status
        true, // can be canceled
        useSSL() || useTLS() );

  mMailCheckProgressItem->setTotalItems( mMailCheckFolders.count() );
  connect ( mMailCheckProgressItem,
            SIGNAL( progressItemCanceled( KPIM::ProgressItem*) ),
            this,
            SLOT( slotMailCheckCanceled() ) );

  QValueList<QGuardedPtr<KMFolder> >::Iterator it;
  // first get the current count of unread-messages
  mCountRemainChecks = 0;
  mCountUnread = 0;
  mUnreadBeforeCheck.clear();
  for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); ++it)
  {
    KMFolder *folder = *it;
    if (folder && !folder->noContent())
    {
      mUnreadBeforeCheck[folder->idString()] = folder->countUnread();
    }
  }
  bool gotError = false;
  // then check for new mails
  for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); ++it)
  {
    KMFolder *folder = *it;
    if (folder && !folder->noContent())
    {
      KMFolderImap *imapFolder = static_cast<KMFolderImap*>(folder->storage());
      if (imapFolder->getContentState() != KMFolderImap::imapInProgress)
      {
        // connect the result-signals for new-mail-notification
        mCountRemainChecks++;
        if (imapFolder->isSelected()) {
          connect(imapFolder, SIGNAL(folderComplete(KMFolderImap*, bool)),
              this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
          imapFolder->getFolder();
        }
        else {
          connect(imapFolder, SIGNAL(numUnreadMsgsChanged(KMFolder*)),
              this, SLOT(postProcessNewMail(KMFolder*)));
          bool ok = imapFolder->processNewMail(interactive);
          if (!ok)
          {
            // there was an error so cancel
            mCountRemainChecks--;
            gotError = true;
            if ( mMailCheckProgressItem ) {
              mMailCheckProgressItem->incCompletedItems();
              mMailCheckProgressItem->updateProgress();
            }
          }
        }
      }
    }
  } // end for
  if ( gotError )
    slotUpdateFolderList();
  // for the case the account is down and all folders report errors
  if ( mCountRemainChecks == 0 )
  {
    mCountLastUnread = 0; // => mCountUnread - mCountLastUnread == new count
    ImapAccountBase::postProcessNewMail();
    mUnreadBeforeCheck.clear();
    mCheckingSingleFolder = false;
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::postProcessNewMail(KMFolderImap* folder, bool)
{
  disconnect(folder, SIGNAL(folderComplete(KMFolderImap*, bool)),
      this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
  postProcessNewMail(static_cast<KMFolder*>(folder->folder()));
}

void KMAcctImap::postProcessNewMail( KMFolder * folder )
{
  disconnect( folder->storage(), SIGNAL(numUnreadMsgsChanged(KMFolder*)),
              this, SLOT(postProcessNewMail(KMFolder*)) );

  if ( mMailCheckProgressItem ) {
    mMailCheckProgressItem->incCompletedItems();
    mMailCheckProgressItem->updateProgress();
    mMailCheckProgressItem->setStatus( folder->prettyURL() + i18n(" completed") );
  }
  mCountRemainChecks--;

  // count the unread messages
  const QString folderId = folder->idString();
  int newInFolder = folder->countUnread();
  if ( mUnreadBeforeCheck.find( folderId ) != mUnreadBeforeCheck.end() )
    newInFolder -= mUnreadBeforeCheck[folderId];
  if ( newInFolder > 0 ) {
    addToNewInFolder( folderId, newInFolder );
    mCountUnread += newInFolder;
  }
  if (mCountRemainChecks == 0)
  {
    // all checks are done
    mCountLastUnread = 0; // => mCountUnread - mCountLastUnread == new count
    // when we check only one folder (=selected) then do not display a summary
    // as the normal status message is better
    ImapAccountBase::postProcessNewMail( !mCheckingSingleFolder );
    mUnreadBeforeCheck.clear();
    mCheckingSingleFolder = false;
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::slotUpdateFolderList()
{
  if ( !mFolder || !mFolder->folder() || !mFolder->folder()->child() )
  {
    kdWarning(5006) << "KMAcctImap::slotUpdateFolderList return" << endl;
    return;
  }
  QStringList strList;
  mMailCheckFolders.clear();
  kmkernel->imapFolderMgr()->createFolderList(&strList, &mMailCheckFolders,
    mFolder->folder()->child(), QString::null, false);
  // the new list
  QValueList<QGuardedPtr<KMFolder> > includedFolders;
  // check for excluded folders
  QValueList<QGuardedPtr<KMFolder> >::Iterator it;
  for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); ++it)
  {
    KMFolderImap* folder = static_cast<KMFolderImap*>(((KMFolder*)(*it))->storage());
    if (folder->includeInMailCheck())
      includedFolders.append(*it);
  }
  mMailCheckFolders = includedFolders;
}

//-----------------------------------------------------------------------------
void KMAcctImap::listDirectory()
{
  mFolder->listDirectory();
}

//-----------------------------------------------------------------------------
void KMAcctImap::setPrefixHook() {
  if ( mFolder ) mFolder->setImapPath( prefix() );
}

//-----------------------------------------------------------------------------
void KMAcctImap::readConfig(KConfig& config)
{
  ImapAccountBase::readConfig( config );
}

//-----------------------------------------------------------------------------
void KMAcctImap::slotMailCheckCanceled()
{
  if( mMailCheckProgressItem )
    mMailCheckProgressItem->setComplete();
  cancelMailCheck();
}

//-----------------------------------------------------------------------------
FolderStorage* const KMAcctImap::rootFolder() const
{
  return mFolder;
}

ImapAccountBase::ConnectionState KMAcctImap::makeConnection()
{
  if ( mSlaveConnectionError )
  {
    mErrorTimer.start(100, true); // Clear error flag
    return Error;
  }
  return ImapAccountBase::makeConnection();
}

void KMAcctImap::slotResetConnectionError()
{
  mSlaveConnectionError = false;
  kdDebug(5006) << k_funcinfo << endl;
}

#include "kmacctimap.moc"
<commit_msg>Show a summary when a single folder is checked and the new message count did not change<commit_after>/**
 * kmacctimap.cpp
 *
 * Copyright (c) 2000-2002 Michael Haeckel <haeckel@kde.org>
 *
 * This file is based on kmacctexppop.cpp by Don Sanders
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "kmacctimap.h"
using KMail::SieveConfig;

#include "broadcaststatus.h"
using KPIM::BroadcastStatus;
#include "kmfoldertree.h"
#include "kmfoldermgr.h"
#include "kmfolderimap.h"
#include "kmmainwin.h"
#include "folderstorage.h"
#include "imapjob.h"
using KMail::ImapJob;
using KMail::ImapAccountBase;
#include "progressmanager.h"
using KPIM::ProgressItem;
using KPIM::ProgressManager;
#include <kio/scheduler.h>
#include <kio/slave.h>
#include <kmessagebox.h>
#include <kdebug.h>

//-----------------------------------------------------------------------------
KMAcctImap::KMAcctImap(KMAcctMgr* aOwner, const QString& aAccountName, uint id):
  KMail::ImapAccountBase(aOwner, aAccountName, id),
  mCountRemainChecks( 0 )
{
  mFolder = 0;
  mNoopTimer.start( 60000 ); // // send a noop every minute
  mOpenFolders.setAutoDelete(true);
  connect(kmkernel->imapFolderMgr(), SIGNAL(changed()),
      this, SLOT(slotUpdateFolderList()));
  connect(&mErrorTimer, SIGNAL(timeout()), SLOT(slotResetConnectionError()));
}

//-----------------------------------------------------------------------------
KMAcctImap::~KMAcctImap()
{
  killAllJobs( true );
}

//-----------------------------------------------------------------------------
QString KMAcctImap::type() const
{
  return "imap";
}

//-----------------------------------------------------------------------------
void KMAcctImap::pseudoAssign( const KMAccount * a ) {
  killAllJobs( true );
  if (mFolder)
  {
    mFolder->setContentState(KMFolderImap::imapNoInformation);
    mFolder->setSubfolderState(KMFolderImap::imapNoInformation);
  }
  ImapAccountBase::pseudoAssign( a );
}

//-----------------------------------------------------------------------------
void KMAcctImap::setImapFolder(KMFolderImap *aFolder)
{
  mFolder = aFolder;
  mFolder->setImapPath(mPrefix);
}

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

bool KMAcctImap::handleError( int errorCode, const QString &errorMsg, KIO::Job* job, const QString& context, bool abortSync )
{
  /* TODO check where to handle this one better. */
  if ( errorCode == KIO::ERR_DOES_NOT_EXIST ) {
    // folder is gone, so reload the folderlist
    if ( mFolder )
      mFolder->listDirectory();
    return true;
  }
  return ImapAccountBase::handleError( errorCode, errorMsg, job, context, abortSync );
}

//-----------------------------------------------------------------------------
void KMAcctImap::killAllJobs( bool disconnectSlave )
{
  QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
  for ( ; it != mapJobData.end(); ++it)
  {
    QPtrList<KMMessage> msgList = (*it).msgList;
    QPtrList<KMMessage>::Iterator it2 = msgList.begin();
    for ( ; it2 != msgList.end(); ++it2 ) {
       KMMessage *msg = *it2;
       if ( msg->transferInProgress() ) {
          kdDebug(5006) << "KMAcctImap::killAllJobs - resetting mail" << endl;
          msg->setTransferInProgress( false );
       }
    }
    if ((*it).parent)
    {
      // clear folder state
      KMFolderImap *fld = static_cast<KMFolderImap*>((*it).parent->storage());
      fld->setCheckingValidity(false);
      fld->setContentState(KMFolderImap::imapNoInformation);
      fld->setSubfolderState(KMFolderImap::imapNoInformation);
      fld->sendFolderComplete(FALSE);
      fld->removeJobs();
    }
    if ( (*it).progressItem )
    {
      (*it).progressItem->setComplete();
    }
  }
  if (mSlave && mapJobData.begin() != mapJobData.end())
  {
    mSlave->kill();
    mSlave = 0;
  }
  // remove the jobs
  mapJobData.clear();
  KMAccount::deleteFolderJobs();
  // make sure that no new-mail-check is blocked
  if (mCountRemainChecks > 0)
  {
    checkDone( false, CheckOK ); // returned 0 new messages
    mCountRemainChecks = 0;
  }
  if ( disconnectSlave && slave() ) {
    KIO::Scheduler::disconnectSlave( slave() );
    mSlave = 0;
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForMessage( KMMessage* msg )
{
  if (!msg) return;
  QPtrListIterator<ImapJob> it( mJobList );
  while ( it.current() )
  {
    ImapJob *job = it.current();
    ++it;
    if ( job->msgList().first() == msg )
    {
      job->kill();
    }
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::ignoreJobsForFolder( KMFolder* folder )
{
  QPtrListIterator<ImapJob> it( mJobList );
  while ( it.current() )
  {
    ImapJob *job = it.current();
    ++it;
    if ( !job->msgList().isEmpty() && job->msgList().first()->parent() == folder )
    {
      job->kill();
    }
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::removeSlaveJobsForFolder( KMFolder* folder )
{
  // Make sure the folder is not referenced in any kio slave jobs
  QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
  while ( it != mapJobData.end() ) {
     QMap<KIO::Job*, jobData>::Iterator i = it;
     it++;
     if ( (*i).parent ) {
        if ( (*i).parent == folder ) {
           mapJobData.remove(i);
        }
     }
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::cancelMailCheck()
{
  // Make list of folders to reset, like in killAllJobs
  QValueList<KMFolderImap*> folderList;
  QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();
  for (; it != mapJobData.end(); ++it) {
    if ( (*it).cancellable && (*it).parent ) {
      folderList << static_cast<KMFolderImap*>((*it).parent->storage());
    }
  }
  // Kill jobs
  // FIXME
  // ImapAccountBase::cancelMailCheck();
  killAllJobs( true );
  // emit folderComplete, this is important for
  // KMAccount::checkingMail() to be reset, in case we restart checking mail later.
  for( QValueList<KMFolderImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {
    KMFolderImap *fld = *it;
    fld->sendFolderComplete(FALSE);
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::processNewMail(bool interactive)
{
  kdDebug() << "processNewMail " << mCheckingSingleFolder << ",status="<<makeConnection()<<endl;
  if (!mFolder || !mFolder->folder() || !mFolder->folder()->child() ||
      makeConnection() == ImapAccountBase::Error)
  {
    mCountRemainChecks = 0;
    mCheckingSingleFolder = false;
    checkDone( false, CheckError );
    return;
  }
  // if necessary then initialize the list of folders which should be checked
  if( mMailCheckFolders.isEmpty() )
  {
    slotUpdateFolderList();
    // if no folders should be checked then the check is finished
    if( mMailCheckFolders.isEmpty() )
    {
      checkDone( false, CheckOK );
      mCheckingSingleFolder = false;
      return;
    }
  }
  // Ok, we're really checking, get a progress item;
  Q_ASSERT( !mMailCheckProgressItem );
  mMailCheckProgressItem =
    ProgressManager::createProgressItem(
        "MailCheckAccount" + name(),
        i18n("Checking account: " ) + name(),
        QString::null, // status
        true, // can be canceled
        useSSL() || useTLS() );

  mMailCheckProgressItem->setTotalItems( mMailCheckFolders.count() );
  connect ( mMailCheckProgressItem,
            SIGNAL( progressItemCanceled( KPIM::ProgressItem*) ),
            this,
            SLOT( slotMailCheckCanceled() ) );

  QValueList<QGuardedPtr<KMFolder> >::Iterator it;
  // first get the current count of unread-messages
  mCountRemainChecks = 0;
  mCountUnread = 0;
  mUnreadBeforeCheck.clear();
  for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); ++it)
  {
    KMFolder *folder = *it;
    if (folder && !folder->noContent())
    {
      mUnreadBeforeCheck[folder->idString()] = folder->countUnread();
    }
  }
  bool gotError = false;
  // then check for new mails
  for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); ++it)
  {
    KMFolder *folder = *it;
    if (folder && !folder->noContent())
    {
      KMFolderImap *imapFolder = static_cast<KMFolderImap*>(folder->storage());
      if (imapFolder->getContentState() != KMFolderImap::imapInProgress)
      {
        // connect the result-signals for new-mail-notification
        mCountRemainChecks++;
        if (imapFolder->isSelected()) {
          connect(imapFolder, SIGNAL(folderComplete(KMFolderImap*, bool)),
              this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
          imapFolder->getFolder();
        }
        else {
          connect(imapFolder, SIGNAL(numUnreadMsgsChanged(KMFolder*)),
              this, SLOT(postProcessNewMail(KMFolder*)));
          bool ok = imapFolder->processNewMail(interactive);
          if (!ok)
          {
            // there was an error so cancel
            mCountRemainChecks--;
            gotError = true;
            if ( mMailCheckProgressItem ) {
              mMailCheckProgressItem->incCompletedItems();
              mMailCheckProgressItem->updateProgress();
            }
          }
        }
      }
    }
  } // end for
  if ( gotError )
    slotUpdateFolderList();
  // for the case the account is down and all folders report errors
  if ( mCountRemainChecks == 0 )
  {
    mCountLastUnread = 0; // => mCountUnread - mCountLastUnread == new count
    ImapAccountBase::postProcessNewMail();
    mUnreadBeforeCheck.clear();
    mCheckingSingleFolder = false;
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::postProcessNewMail(KMFolderImap* folder, bool)
{
  disconnect(folder, SIGNAL(folderComplete(KMFolderImap*, bool)),
      this, SLOT(postProcessNewMail(KMFolderImap*, bool)));
  postProcessNewMail(static_cast<KMFolder*>(folder->folder()));
}

void KMAcctImap::postProcessNewMail( KMFolder * folder )
{
  disconnect( folder->storage(), SIGNAL(numUnreadMsgsChanged(KMFolder*)),
              this, SLOT(postProcessNewMail(KMFolder*)) );

  if ( mMailCheckProgressItem ) {
    mMailCheckProgressItem->incCompletedItems();
    mMailCheckProgressItem->updateProgress();
    mMailCheckProgressItem->setStatus( folder->prettyURL() + i18n(" completed") );
  }
  mCountRemainChecks--;

  // count the unread messages
  const QString folderId = folder->idString();
  int newInFolder = folder->countUnread();
  if ( mUnreadBeforeCheck.find( folderId ) != mUnreadBeforeCheck.end() )
    newInFolder -= mUnreadBeforeCheck[folderId];
  if ( newInFolder > 0 ) {
    addToNewInFolder( folderId, newInFolder );
    mCountUnread += newInFolder;
  }
  if (mCountRemainChecks == 0)
  {
    // all checks are done
    mCountLastUnread = 0; // => mCountUnread - mCountLastUnread == new count
    // when we check only one folder (=selected) and we have new mails
    // then do not display a summary as the normal status message is better
    bool showStatus = ( mCheckingSingleFolder && mCountUnread > 0 ) ? false : true;
    ImapAccountBase::postProcessNewMail( showStatus );
    mUnreadBeforeCheck.clear();
    mCheckingSingleFolder = false;
  }
}

//-----------------------------------------------------------------------------
void KMAcctImap::slotUpdateFolderList()
{
  if ( !mFolder || !mFolder->folder() || !mFolder->folder()->child() )
  {
    kdWarning(5006) << "KMAcctImap::slotUpdateFolderList return" << endl;
    return;
  }
  QStringList strList;
  mMailCheckFolders.clear();
  kmkernel->imapFolderMgr()->createFolderList(&strList, &mMailCheckFolders,
    mFolder->folder()->child(), QString::null, false);
  // the new list
  QValueList<QGuardedPtr<KMFolder> > includedFolders;
  // check for excluded folders
  QValueList<QGuardedPtr<KMFolder> >::Iterator it;
  for (it = mMailCheckFolders.begin(); it != mMailCheckFolders.end(); ++it)
  {
    KMFolderImap* folder = static_cast<KMFolderImap*>(((KMFolder*)(*it))->storage());
    if (folder->includeInMailCheck())
      includedFolders.append(*it);
  }
  mMailCheckFolders = includedFolders;
}

//-----------------------------------------------------------------------------
void KMAcctImap::listDirectory()
{
  mFolder->listDirectory();
}

//-----------------------------------------------------------------------------
void KMAcctImap::setPrefixHook() {
  if ( mFolder ) mFolder->setImapPath( prefix() );
}

//-----------------------------------------------------------------------------
void KMAcctImap::readConfig(KConfig& config)
{
  ImapAccountBase::readConfig( config );
}

//-----------------------------------------------------------------------------
void KMAcctImap::slotMailCheckCanceled()
{
  if( mMailCheckProgressItem )
    mMailCheckProgressItem->setComplete();
  cancelMailCheck();
}

//-----------------------------------------------------------------------------
FolderStorage* const KMAcctImap::rootFolder() const
{
  return mFolder;
}

ImapAccountBase::ConnectionState KMAcctImap::makeConnection()
{
  if ( mSlaveConnectionError )
  {
    mErrorTimer.start(100, true); // Clear error flag
    return Error;
  }
  return ImapAccountBase::makeConnection();
}

void KMAcctImap::slotResetConnectionError()
{
  mSlaveConnectionError = false;
  kdDebug(5006) << k_funcinfo << endl;
}

#include "kmacctimap.moc"
<|endoftext|>


<commit_before>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Globals, compile-time constants and runconfig abstractions.
  */

#include "thcrap.h"

json_t* run_cfg = NULL;

const char* PROJECT_NAME(void)
{
	return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
	return "thcrap";
}
DWORD PROJECT_VERSION(void)
{
	return 0x20190402;
}
const char* PROJECT_VERSION_STRING(void)
{
	static char ver_str[11] = {0};
	if(!ver_str[0]) {
		str_hexdate_format(ver_str, PROJECT_VERSION());
	}
	return ver_str;
}
json_t* runconfig_get(void)
{
	return run_cfg;
}
void runconfig_set(json_t *new_run_cfg)
{
	json_decref(run_cfg);
	run_cfg = json_incref(new_run_cfg);
}

const json_t *runconfig_title_get(void)
{
	const json_t *id = json_object_get(run_cfg, "game");
	const json_t *title = strings_get(json_string_value(id));
	if(!title) {
		title = json_object_get(run_cfg, "title");
	}
	return title ? title : (id ? id : NULL);
}
<commit_msg>Update version number<commit_after>/**
  * Touhou Community Reliant Automatic Patcher
  * Main DLL
  *
  * ----
  *
  * Globals, compile-time constants and runconfig abstractions.
  */

#include "thcrap.h"

json_t* run_cfg = NULL;

const char* PROJECT_NAME(void)
{
	return "Touhou Community Reliant Automatic Patcher";
}
const char* PROJECT_NAME_SHORT(void)
{
	return "thcrap";
}
DWORD PROJECT_VERSION(void)
{
	return 0x20190524;
}
const char* PROJECT_VERSION_STRING(void)
{
	static char ver_str[11] = {0};
	if(!ver_str[0]) {
		str_hexdate_format(ver_str, PROJECT_VERSION());
	}
	return ver_str;
}
json_t* runconfig_get(void)
{
	return run_cfg;
}
void runconfig_set(json_t *new_run_cfg)
{
	json_decref(run_cfg);
	run_cfg = json_incref(new_run_cfg);
}

const json_t *runconfig_title_get(void)
{
	const json_t *id = json_object_get(run_cfg, "game");
	const json_t *title = strings_get(json_string_value(id));
	if(!title) {
		title = json_object_get(run_cfg, "title");
	}
	return title ? title : (id ? id : NULL);
}
<|endoftext|>


<commit_before>#ifndef ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__
#define ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__

#include <algorithm>
#include <fstream>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>

#include <aleph/utilities/String.hh>

namespace aleph
{

namespace topology
{

namespace io
{

class EdgeListReader
{
public:

  bool readWeights() const noexcept { return _readWeights; }
  bool trimLines()   const noexcept { return _trimLines;   }

  void setReadWeights( bool value = true ) noexcept { _readWeights = value; }
  void setTrimLines( bool value = true )   noexcept { _trimLines = value; }

  template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
  {
    std::ifstream in( filename );
    if( !in )
      throw std::runtime_error( "Unable to read input file" );

    this->operator()( in, K );
  }

  template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K )
  {
    using namespace utilities;

    using Simplex           = typename SimplicialComplex::ValueType;
    using DataType          = typename Simplex::DataType;
    using VertexType        = typename Simplex::VertexType;

    std::string line;

    std::set<Simplex> vertices;
    std::vector<Simplex> edges;

    std::size_t lastID = 0;

    while( in )
    {
      std::getline( in, line );

      if( _trimLines )
        line = trim( line );

      // TODO: Make this configurable and permit splitting by different
      // tokens such as commas
      auto tokens = split( line );

      // Skip empty lines and comments
      if( line.empty() || std::find( _commentTokens.begin(), _commentTokens.end(), line.front() ) != _commentTokens.end() )
        continue;

      if( tokens.size() >= 2 )
      {
        VertexType u = VertexType();
        VertexType v = VertexType();

        // TODO: Make order of vertices & weights configurable?
        if( tokens[0].find_first_not_of( "0123456789" ) == std::string::npos )
        {
          u = convert<VertexType>( tokens[0] );
          v = convert<VertexType>( tokens[1] );
        }
        else
        {
          auto&& us = tokens[0];
          auto&& vs = tokens[1];

          if( _nodeLabels.find(us) == _nodeLabels.end() )
            _nodeLabels[us] = lastID++;

          if( _nodeLabels.find(vs) == _nodeLabels.end() )
            _nodeLabels[vs] = lastID++;

          u = static_cast<VertexType>( _nodeLabels.at(us) );
          v = static_cast<VertexType>( _nodeLabels.at(vs) );
        }

        DataType w = DataType();
        if( tokens.size() >= 3 && _readWeights )
          w = convert<DataType>( tokens[2] );

        edges.push_back( Simplex( { u, v }, w ) );

        vertices.insert( Simplex( u ) );
        vertices.insert( Simplex( v ) );
      }
      else
      {
        // TODO: Throw error?
      }
    }

    // Using a set has the advantage of ensuring that duplicate
    // simplices are deleted automatically. A duplicate simplex
    // is usually created by the input data set itself. It must
    // not be considered for any subsequent analysis.
    std::set<Simplex> simplices;

    simplices.insert( vertices.begin(), vertices.end() );
    simplices.insert( edges.begin(), edges.end() );

    K = SimplicialComplex( simplices.begin(), simplices.end() );
  }

private:
  std::vector<char> _commentTokens = { '#', '%', '\"', '*' };

  /**
    Optional set of node labels. These are read automatically in case an
    input data set does not use numeric labels. The idea is to map an ID
    in the form of a string to an index in corresponding graph.
  */

  std::map<std::string, std::size_t> _nodeLabels;

  bool _readWeights              = true;
  bool _trimLines                = true;
};

} // namespace io

} // namespace topology

} // namespace aleph

#endif
<commit_msg>Added missing header<commit_after>#ifndef ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__
#define ALEPH_TOPOLOGY_IO_EDGE_LISTS_HH__

#include <algorithm>
#include <fstream>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>

#include <aleph/utilities/String.hh>

namespace aleph
{

namespace topology
{

namespace io
{

class EdgeListReader
{
public:

  bool readWeights() const noexcept { return _readWeights; }
  bool trimLines()   const noexcept { return _trimLines;   }

  void setReadWeights( bool value = true ) noexcept { _readWeights = value; }
  void setTrimLines( bool value = true )   noexcept { _trimLines = value; }

  template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K )
  {
    std::ifstream in( filename );
    if( !in )
      throw std::runtime_error( "Unable to read input file" );

    this->operator()( in, K );
  }

  template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K )
  {
    using namespace utilities;

    using Simplex           = typename SimplicialComplex::ValueType;
    using DataType          = typename Simplex::DataType;
    using VertexType        = typename Simplex::VertexType;

    std::string line;

    std::set<Simplex> vertices;
    std::vector<Simplex> edges;

    std::size_t lastID = 0;

    while( in )
    {
      std::getline( in, line );

      if( _trimLines )
        line = trim( line );

      // TODO: Make this configurable and permit splitting by different
      // tokens such as commas
      auto tokens = split( line );

      // Skip empty lines and comments
      if( line.empty() || std::find( _commentTokens.begin(), _commentTokens.end(), line.front() ) != _commentTokens.end() )
        continue;

      if( tokens.size() >= 2 )
      {
        VertexType u = VertexType();
        VertexType v = VertexType();

        // TODO: Make order of vertices & weights configurable?
        if( tokens[0].find_first_not_of( "0123456789" ) == std::string::npos )
        {
          u = convert<VertexType>( tokens[0] );
          v = convert<VertexType>( tokens[1] );
        }
        else
        {
          auto&& us = tokens[0];
          auto&& vs = tokens[1];

          if( _nodeLabels.find(us) == _nodeLabels.end() )
            _nodeLabels[us] = lastID++;

          if( _nodeLabels.find(vs) == _nodeLabels.end() )
            _nodeLabels[vs] = lastID++;

          u = static_cast<VertexType>( _nodeLabels.at(us) );
          v = static_cast<VertexType>( _nodeLabels.at(vs) );
        }

        DataType w = DataType();
        if( tokens.size() >= 3 && _readWeights )
          w = convert<DataType>( tokens[2] );

        edges.push_back( Simplex( { u, v }, w ) );

        vertices.insert( Simplex( u ) );
        vertices.insert( Simplex( v ) );
      }
      else
      {
        // TODO: Throw error?
      }
    }

    // Using a set has the advantage of ensuring that duplicate
    // simplices are deleted automatically. A duplicate simplex
    // is usually created by the input data set itself. It must
    // not be considered for any subsequent analysis.
    std::set<Simplex> simplices;

    simplices.insert( vertices.begin(), vertices.end() );
    simplices.insert( edges.begin(), edges.end() );

    K = SimplicialComplex( simplices.begin(), simplices.end() );
  }

private:
  std::vector<char> _commentTokens = { '#', '%', '\"', '*' };

  /**
    Optional set of node labels. These are read automatically in case an
    input data set does not use numeric labels. The idea is to map an ID
    in the form of a string to an index in corresponding graph.
  */

  std::map<std::string, std::size_t> _nodeLabels;

  bool _readWeights              = true;
  bool _trimLines                = true;
};

} // namespace io

} // namespace topology

} // namespace aleph

#endif
<|endoftext|>