From: Heeyong Song Date: Tue, 9 Feb 2021 01:15:48 +0000 (+0900) Subject: Merge branch 'devel/master' into tizen X-Git-Tag: accepted/tizen/unified/20210209.124355~2 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=4e39a7a1d48fbfc9b2cc00ed4adec47f421339be;hp=fa933b12bc3e373498b059ffe7487fe9c87ab648;p=platform%2Fcore%2Fuifw%2Fdali-adaptor.git Merge branch 'devel/master' into tizen Change-Id: I363fb4b12002eec1d24210123f15b2d707086f92 --- diff --git a/automated-tests/src/dali-adaptor-internal/utc-Dali-Internal-PixelBuffer.cpp b/automated-tests/src/dali-adaptor-internal/utc-Dali-Internal-PixelBuffer.cpp index dcc6a3a..a35f701 100644 --- a/automated-tests/src/dali-adaptor-internal/utc-Dali-Internal-PixelBuffer.cpp +++ b/automated-tests/src/dali-adaptor-internal/utc-Dali-Internal-PixelBuffer.cpp @@ -24,15 +24,14 @@ // Internal headers are allowed here -#include #include +#include using namespace Dali; using namespace Dali::Internal::Adaptor; namespace { - // resolution: 96*96, pixel format: LA88 const char* TEST_IMAGE_LA88 = TEST_IMAGE_DIR "/circle1-LA88.png"; @@ -184,14 +183,14 @@ int UtcDaliPixelManipulationLA88(void) Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromFile(TEST_IMAGE_LA88); DALI_TEST_CHECK(pixelBuffer); - unsigned int width = pixelBuffer.GetWidth(); + unsigned int width = pixelBuffer.GetWidth(); unsigned int height = pixelBuffer.GetHeight(); DALI_TEST_EQUALS(width, 96u, TEST_LOCATION); DALI_TEST_EQUALS(height, 96u, TEST_LOCATION); DALI_TEST_EQUALS(pixelBuffer.GetPixelFormat(), Pixel::LA88, TEST_LOCATION); unsigned char* pixel = pixelBuffer.GetBuffer(); - unsigned int value; + unsigned int value; value = Dali::Internal::Adaptor::ReadChannel(&pixel[0], Dali::Pixel::LA88, Dali::Internal::Adaptor::LUMINANCE); DALI_TEST_EQUALS(value, 0x0, TEST_LOCATION); @@ -201,7 +200,7 @@ int UtcDaliPixelManipulationLA88(void) // Get center pixel unsigned int stride = width * Pixel::GetBytesPerPixel(Dali::Pixel::LA88); unsigned int center = height / 2 * stride + width / 2 * Pixel::GetBytesPerPixel(Dali::Pixel::LA88); - value = Dali::Internal::Adaptor::ReadChannel(&pixel[center], Dali::Pixel::LA88, Dali::Internal::Adaptor::LUMINANCE); + value = Dali::Internal::Adaptor::ReadChannel(&pixel[center], Dali::Pixel::LA88, Dali::Internal::Adaptor::LUMINANCE); DALI_TEST_EQUALS(value, 0x0, TEST_LOCATION); value = Dali::Internal::Adaptor::ReadChannel(&pixel[center], Dali::Pixel::LA88, Dali::Internal::Adaptor::ALPHA); DALI_TEST_EQUALS(value, 0xFF, TEST_LOCATION); diff --git a/automated-tests/src/dali-adaptor/utc-Dali-Gl-Window.cpp b/automated-tests/src/dali-adaptor/utc-Dali-Gl-Window.cpp index 493cdf7..61c70fc 100644 --- a/automated-tests/src/dali-adaptor/utc-Dali-Gl-Window.cpp +++ b/automated-tests/src/dali-adaptor/utc-Dali-Gl-Window.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,11 @@ * */ +#include +#include #include #include #include -#include -#include - using namespace Dali; @@ -37,15 +36,15 @@ void utc_dali_glwindow_cleanup(void) int UtcDaliGlWindowConstructorP(void) { Dali::GlWindow window; - DALI_TEST_CHECK( !window ); + DALI_TEST_CHECK(!window); END_TEST; } int UtcDaliGlWindowCopyConstructorP(void) { Dali::GlWindow window; - Dali::GlWindow copy( window ); - DALI_TEST_CHECK( copy == window ); + Dali::GlWindow copy(window); + DALI_TEST_CHECK(copy == window); END_TEST; } @@ -53,8 +52,8 @@ int UtcDaliGlWindowCopyConstructorP(void) int UtcDaliGlWindowConstructorFromInternalPointerN(void) { Internal::Adaptor::GlWindow* internalWindow = NULL; - Dali::GlWindow window(internalWindow); - DALI_TEST_CHECK( !window ); + Dali::GlWindow window(internalWindow); + DALI_TEST_CHECK(!window); END_TEST; } @@ -62,10 +61,10 @@ int UtcDaliGlWindowConstructorFromInternalPointerN(void) int UtcDaliGlWindowAssignmentOperatorP(void) { const Dali::GlWindow window; - Dali::GlWindow copy; - DALI_TEST_CHECK( ! copy ); + Dali::GlWindow copy; + DALI_TEST_CHECK(!copy); copy = window; - DALI_TEST_CHECK( copy == window ); + DALI_TEST_CHECK(copy == window); END_TEST; } @@ -75,7 +74,7 @@ int UtcDaliGlWindowDestructorP(void) Dali::GlWindow* window = new Dali::GlWindow(); delete window; - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); END_TEST; } @@ -83,13 +82,13 @@ int UtcDaliGlWindowNew1(void) { try { - PositionSize windowPosition(0, 0, 10, 10); - Dali::GlWindow window = Dali::GlWindow::New( windowPosition, "test-window", "test-window-class", true ); - tet_result( TET_FAIL ); + PositionSize windowPosition(0, 0, 10, 10); + Dali::GlWindow window = Dali::GlWindow::New(windowPosition, "test-window", "test-window-class", true); + tet_result(TET_FAIL); } - catch ( DaliException& e ) + catch(DaliException& e) { - DALI_TEST_ASSERT( e, "Failed to create X window", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "Failed to create X window", TEST_LOCATION); } END_TEST; @@ -99,14 +98,14 @@ int UtcDaliGlWindowNew2(void) { try { - PositionSize windowPosition(20, 10, 10, 10); - Dali::GlWindow window = Dali::GlWindow::New( windowPosition, "test-window", "test-window-class", true ); + PositionSize windowPosition(20, 10, 10, 10); + Dali::GlWindow window = Dali::GlWindow::New(windowPosition, "test-window", "test-window-class", true); - tet_result( TET_FAIL ); + tet_result(TET_FAIL); } - catch ( DaliException& e ) + catch(DaliException& e) { - DALI_TEST_ASSERT( e, "Failed to create X window", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "Failed to create X window", TEST_LOCATION); } END_TEST; } @@ -116,13 +115,13 @@ int UtcDaliGlWindowSetEglConfigGles20(void) Dali::GlWindow window; try { - window.SetEglConfig( true, true, 0, Dali::GlWindow::GlesVersion::VERSION_2_0 ); + window.SetEglConfig(true, true, 0, Dali::GlWindow::GlesVersion::VERSION_2_0); - DALI_TEST_CHECK( false); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -132,13 +131,13 @@ int UtcDaliGlWindowSetEglConfigGles30(void) Dali::GlWindow window; try { - window.SetEglConfig( true, true, 0, Dali::GlWindow::GlesVersion::VERSION_3_0 ); + window.SetEglConfig(true, true, 0, Dali::GlWindow::GlesVersion::VERSION_3_0); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -151,11 +150,11 @@ int UtcDaliGlWindowRaise(void) { window.Raise(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -168,11 +167,11 @@ int UtcDaliGlWindowLower(void) { window.Lower(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -185,11 +184,11 @@ int UtcDaliGlWindowActivate(void) { window.Activate(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -202,11 +201,11 @@ int UtcDaliGlWindowShow(void) { window.Show(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -219,11 +218,11 @@ int UtcDaliGlWindowHide(void) { window.Hide(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -234,36 +233,36 @@ int UtcDaliGlWindowSetGetPositionSize(void) try { - PositionSize setPositionSize( 0, 0, 100, 100); - window.SetPositionSize( setPositionSize ); + PositionSize setPositionSize(0, 0, 100, 100); + window.SetPositionSize(setPositionSize); PositionSize getPositionSize = window.GetPositionSize(); - DALI_TEST_CHECK( setPositionSize == getPositionSize ); + DALI_TEST_CHECK(setPositionSize == getPositionSize); setPositionSize.x = 10; setPositionSize.y = 20; - window.SetPositionSize( setPositionSize ); + window.SetPositionSize(setPositionSize); getPositionSize = window.GetPositionSize(); - DALI_TEST_CHECK( setPositionSize == getPositionSize ); + DALI_TEST_CHECK(setPositionSize == getPositionSize); - setPositionSize.width = 50; + setPositionSize.width = 50; setPositionSize.height = 50; - window.SetPositionSize( setPositionSize ); + window.SetPositionSize(setPositionSize); getPositionSize = window.GetPositionSize(); - DALI_TEST_CHECK( setPositionSize == getPositionSize ); + DALI_TEST_CHECK(setPositionSize == getPositionSize); - setPositionSize.x = 0; - setPositionSize.y = 0; - setPositionSize.width = 100; + setPositionSize.x = 0; + setPositionSize.y = 0; + setPositionSize.width = 100; setPositionSize.height = 100; - window.SetPositionSize( setPositionSize ); + window.SetPositionSize(setPositionSize); getPositionSize = window.GetPositionSize(); - DALI_TEST_CHECK( setPositionSize == getPositionSize ); + DALI_TEST_CHECK(setPositionSize == getPositionSize); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -274,13 +273,13 @@ int UtcDaliGlWindowSetInputRegion(void) try { - window.SetInputRegion( Rect< int >( 0, 0, 100, 10 ) ); + window.SetInputRegion(Rect(0, 0, 100, 10)); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -292,13 +291,13 @@ int UtcDaliGlWindowOpaqueState(void) try { bool opaquestate = window.IsOpaqueState(); - DALI_TEST_CHECK( opaquestate == true ); + DALI_TEST_CHECK(opaquestate == true); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -309,22 +308,22 @@ int UtcDaliGlWindowSetAvailableOrientations(void) try { - Dali::Vector< Dali::WindowOrientation> orientations; - orientations.PushBack( Dali::WindowOrientation::PORTRAIT ); - orientations.PushBack( Dali::WindowOrientation::LANDSCAPE ); - orientations.PushBack( Dali::WindowOrientation::PORTRAIT_INVERSE ); - orientations.PushBack( Dali::WindowOrientation::LANDSCAPE_INVERSE ); - orientations.PushBack( Dali::WindowOrientation::NO_ORIENTATION_PREFERENCE ); - orientations.PushBack( Dali::WindowOrientation::PORTRAIT ); - orientations.PushBack( Dali::WindowOrientation::LANDSCAPE ); - orientations.PushBack( Dali::WindowOrientation::PORTRAIT_INVERSE ); + Dali::Vector orientations; + orientations.PushBack(Dali::WindowOrientation::PORTRAIT); + orientations.PushBack(Dali::WindowOrientation::LANDSCAPE); + orientations.PushBack(Dali::WindowOrientation::PORTRAIT_INVERSE); + orientations.PushBack(Dali::WindowOrientation::LANDSCAPE_INVERSE); + orientations.PushBack(Dali::WindowOrientation::NO_ORIENTATION_PREFERENCE); + orientations.PushBack(Dali::WindowOrientation::PORTRAIT); + orientations.PushBack(Dali::WindowOrientation::LANDSCAPE); + orientations.PushBack(Dali::WindowOrientation::PORTRAIT_INVERSE); window.SetAvailableOrientations(orientations); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -337,11 +336,11 @@ int UtcDaliGlWindowSetPreferredOrientation(void) { window.SetPreferredOrientation(Dali::WindowOrientation::PORTRAIT); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -354,11 +353,11 @@ int UtcDaliGlWindowSetPreferredOrientation1(void) { window.SetPreferredOrientation(Dali::WindowOrientation::NO_ORIENTATION_PREFERENCE); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -370,13 +369,13 @@ int UtcDaliWindowGetCurrentOrientation(void) try { Dali::WindowOrientation orientation = window.GetCurrentOrientation(); - DALI_TEST_CHECK( orientation == Dali::WindowOrientation::PORTRAIT ); + DALI_TEST_CHECK(orientation == Dali::WindowOrientation::PORTRAIT); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -402,13 +401,13 @@ int UtcDaliGlWindowRegisterGlCallback(void) try { - window.RegisterGlCallback( Dali::MakeCallback( glInit ), Dali::MakeCallback( glRenderFrame ), Dali::MakeCallback( glTerminate ) ); + window.RegisterGlCallback(Dali::MakeCallback(glInit), Dali::MakeCallback(glRenderFrame), Dali::MakeCallback(glTerminate)); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -419,14 +418,14 @@ int UtcDaliGlWindowRenderOnce(void) try { - window.RegisterGlCallback( Dali::MakeCallback( glInit ), Dali::MakeCallback( glRenderFrame ), Dali::MakeCallback( glTerminate ) ); + window.RegisterGlCallback(Dali::MakeCallback(glInit), Dali::MakeCallback(glRenderFrame), Dali::MakeCallback(glTerminate)); window.RenderOnce(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -439,11 +438,11 @@ int UtcDaliGlWindowGetSupportedAuxiliaryHintCount(void) { window.GetSupportedAuxiliaryHintCount(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -454,13 +453,13 @@ int UtcDaliGlWindowGetSupportedAuxiliaryHint(void) try { - window.GetSupportedAuxiliaryHint( 0 ); + window.GetSupportedAuxiliaryHint(0); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -471,13 +470,13 @@ int UtcDaliGlWindowAddAuxiliaryHint(void) try { - window.AddAuxiliaryHint( "stack_pop_to", "1" ); + window.AddAuxiliaryHint("stack_pop_to", "1"); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -488,13 +487,13 @@ int UtcDaliGlWindowRemoveAuxiliaryHint(void) try { - window.RemoveAuxiliaryHint( 0 ); + window.RemoveAuxiliaryHint(0); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -505,13 +504,13 @@ int UtcDaliGlWindowSetAuxiliaryHintValue(void) try { - window.SetAuxiliaryHintValue( 0, "0" ); + window.SetAuxiliaryHintValue(0, "0"); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -522,13 +521,13 @@ int UtcDaliGlWindowGetAuxiliaryHintValue(void) try { - window.GetAuxiliaryHintValue( 0 ); + window.GetAuxiliaryHintValue(0); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -539,13 +538,13 @@ int UtcDaliGlWindowGetAuxiliaryHintId(void) try { - window.GetAuxiliaryHintId( "0" ); + window.GetAuxiliaryHintId("0"); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -558,11 +557,11 @@ int UtcDaliGlWindowFocusChangeSignal(void) { window.FocusChangeSignal(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -575,11 +574,11 @@ int UtcDaliGlWindowResizeSignal(void) { window.ResizeSignal(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -592,11 +591,11 @@ int UtcDaliGlWindowKeyEventSignal(void) { window.KeyEventSignal(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -609,11 +608,11 @@ int UtcDaliGlWindowTouchedSignal(void) { window.TouchedSignal(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } @@ -626,11 +625,11 @@ int UtcDaliGlWindowVisibilityChangedSignal(void) { window.VisibilityChangedSignal(); - DALI_TEST_CHECK( false ); + DALI_TEST_CHECK(false); } - catch( ... ) + catch(...) { - DALI_TEST_CHECK( true ); + DALI_TEST_CHECK(true); } END_TEST; } diff --git a/automated-tests/src/dali-adaptor/utc-Dali-TextScript.cpp b/automated-tests/src/dali-adaptor/utc-Dali-TextScript.cpp index 484ab92..ad9d6de 100644 --- a/automated-tests/src/dali-adaptor/utc-Dali-TextScript.cpp +++ b/automated-tests/src/dali-adaptor/utc-Dali-TextScript.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,9 @@ void utc_dali_text_script_cleanup(void) namespace { -void GetCharacterScriptCheckRange(Character start, Character end, Script expectedScript, const char * location) +void GetCharacterScriptCheckRange(Character start, Character end, Script expectedScript, const char* location) { - for( auto character = start; character <= end; ++character ) + for(auto character = start; character <= end; ++character) { if(!IsCommonScript(character)) // Some characters are part of the common script and can be in the range { @@ -194,7 +194,6 @@ int UtcDaliGetCharacterScript(void) GetCharacterScriptCheckRange(0xA788, 0xA78A, NON_LATIN_LED, TEST_LOCATION); GetCharacterScriptCheckRange(0xA78B, 0xa7ff, LATIN, TEST_LOCATION); - GetCharacterScriptCheckRange(0xa960, 0xa97f, HANGUL, TEST_LOCATION); GetCharacterScriptCheckRange(0xa980, 0xa9fd, JAVANESE, TEST_LOCATION); GetCharacterScriptCheckRange(0xab00, 0xab2f, GEEZ, TEST_LOCATION); @@ -230,4 +229,3 @@ int UtcDaliGetCharacterScript(void) END_TEST; } - diff --git a/build/tizen/linker-test.cpp b/build/tizen/linker-test.cpp index 90f365a..4a9cf3c 100644 --- a/build/tizen/linker-test.cpp +++ b/build/tizen/linker-test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,14 @@ */ // EXTERNAL INCLUDES -#include -#include #include +#include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include using namespace Dali; @@ -34,13 +34,12 @@ using namespace Dali; class LinkerApp : public ConnectionTracker { public: - LinkerApp(Application &app) + LinkerApp(Application& app) { app.InitSignal().Connect(this, &LinkerApp::Create); } public: - void Create(Application& app) { } @@ -48,14 +47,13 @@ public: /*****************************************************************************/ -int -main(int argc, char **argv) +int main(int argc, char** argv) { try { Application app = Application::New(&argc, &argv); - LinkerApp linkerApp (app); + LinkerApp linkerApp(app); app.MainLoop(); } catch(...) diff --git a/dali/devel-api/adaptor-framework/accessibility-impl.cpp b/dali/devel-api/adaptor-framework/accessibility-impl.cpp index dcf1149..00f0615 100644 --- a/dali/devel-api/adaptor-framework/accessibility-impl.cpp +++ b/dali/devel-api/adaptor-framework/accessibility-impl.cpp @@ -26,9 +26,9 @@ #include // INTERNAL INCLUDES -#include #include #include +#include using namespace Dali::Accessibility; using namespace Dali; @@ -50,7 +50,7 @@ std::string Accessible::GetLocalizedRoleName() std::string Accessible::GetRoleName() { - switch( GetRole() ) + switch(GetRole()) { case Role::INVALID: { @@ -551,7 +551,7 @@ Dali::Actor Accessible::GetCurrentlyHighlightedActor() void Accessible::SetCurrentlyHighlightedActor(Dali::Actor actor) { - if (IsUp()) + if(IsUp()) { Bridge::GetCurrentBridge()->data->currentlyHighlightedActor = actor; } @@ -564,7 +564,7 @@ Dali::Actor Accessible::GetHighlightActor() void Accessible::SetHighlightActor(Dali::Actor actor) { - if (IsUp()) + if(IsUp()) { Bridge::GetCurrentBridge()->data->highlightActor = actor; } @@ -573,10 +573,10 @@ void Accessible::SetHighlightActor(Dali::Actor actor) void Bridge::ForceDown() { auto highlighted = Accessible::GetCurrentlyHighlightedActor(); - if( highlighted ) + if(highlighted) { - auto p = dynamic_cast< Component* >( Accessible::Get( highlighted ) ); - if( p ) + auto p = dynamic_cast(Accessible::Get(highlighted)); + if(p) { p->ClearHighlight(); } @@ -584,7 +584,7 @@ void Bridge::ForceDown() data = {}; } -void Bridge::SetIsOnRootLevel( Accessible* o ) +void Bridge::SetIsOnRootLevel(Accessible* o) { o->isOnRootLevel = true; } @@ -595,21 +595,23 @@ class NonControlAccessible : public virtual Accessible, public virtual Collectio { public: Dali::Actor actor; - bool root = false; + bool root = false; - NonControlAccessible( Dali::Actor actor, bool root ) : actor( actor ), root( root ) + NonControlAccessible(Dali::Actor actor, bool root) + : actor(actor), + root(root) { } - Dali::Rect<> GetExtents( Dali::Accessibility::CoordType ctype ) override + Dali::Rect<> GetExtents(Dali::Accessibility::CoordType ctype) override { - Vector2 screenPosition = actor.GetProperty( Actor::Property::SCREEN_POSITION ).Get< Vector2 >(); - Vector3 size = actor.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * actor.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_SCALE ); - bool positionUsesAnchorPoint = actor.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >(); - Vector3 anchorPointOffSet = size * ( positionUsesAnchorPoint ? actor.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) : AnchorPoint::TOP_LEFT ); - Vector2 position = Vector2( screenPosition.x - anchorPointOffSet.x, screenPosition.y - anchorPointOffSet.y ); + Vector2 screenPosition = actor.GetProperty(Actor::Property::SCREEN_POSITION).Get(); + Vector3 size = actor.GetCurrentProperty(Actor::Property::SIZE) * actor.GetCurrentProperty(Actor::Property::WORLD_SCALE); + bool positionUsesAnchorPoint = actor.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get(); + Vector3 anchorPointOffSet = size * (positionUsesAnchorPoint ? actor.GetCurrentProperty(Actor::Property::ANCHOR_POINT) : AnchorPoint::TOP_LEFT); + Vector2 position = Vector2(screenPosition.x - anchorPointOffSet.x, screenPosition.y - anchorPointOffSet.y); - return { position.x, position.y, size.x, size.y }; + return {position.x, position.y, size.x, size.y}; } Dali::Accessibility::ComponentLayer GetLayer() override { @@ -641,7 +643,7 @@ public: } std::string GetName() override { - return actor.GetProperty< std::string >( Dali::Actor::Property::NAME ); + return actor.GetProperty(Dali::Actor::Property::NAME); } std::string GetDescription() override { @@ -649,37 +651,37 @@ public: } Accessible* GetParent() override { - if( GetIsOnRootLevel() ) + if(GetIsOnRootLevel()) { auto b = GetBridgeData(); return b->bridge->GetApplication(); } - return Get( actor.GetParent() ); + return Get(actor.GetParent()); } size_t GetChildCount() override { - return static_cast< size_t >( actor.GetChildCount() ); + return static_cast(actor.GetChildCount()); } - Accessible* GetChildAtIndex( size_t index ) override + Accessible* GetChildAtIndex(size_t index) override { - auto s = static_cast< size_t >( actor.GetChildCount() ); - if( index >= s ) + auto s = static_cast(actor.GetChildCount()); + if(index >= s) { - throw std::domain_error{"invalid index " + std::to_string( index ) + " for object with " + std::to_string( s ) + " children"}; + throw std::domain_error{"invalid index " + std::to_string(index) + " for object with " + std::to_string(s) + " children"}; } - return Get( actor.GetChildAt( static_cast< unsigned int >( index ) ) ); + return Get(actor.GetChildAt(static_cast(index))); } size_t GetIndexInParent() override { auto parent = actor.GetParent(); - if( !parent ) + if(!parent) { return 0; } - auto size = static_cast< size_t >( parent.GetChildCount() ); - for( auto i = 0u; i < size; ++i ) + auto size = static_cast(parent.GetChildCount()); + for(auto i = 0u; i < size; ++i) { - if( parent.GetChildAt( i ) == actor ) + if(parent.GetChildAt(i) == actor) { return i; } @@ -693,17 +695,17 @@ public: States GetStates() override { States s; - if( root ) + if(root) { - s[State::ENABLED] = true; + s[State::ENABLED] = true; s[State::SENSITIVE] = true; - s[State::SHOWING] = true; - s[State::VISIBLE] = true; - s[State::ACTIVE] = true; + s[State::SHOWING] = true; + s[State::VISIBLE] = true; + s[State::ACTIVE] = true; } else { - auto t = GetParent()->GetStates(); + auto t = GetParent()->GetStates(); s[State::SHOWING] = t[State::SHOWING]; s[State::VISIBLE] = t[State::VISIBLE]; } @@ -712,11 +714,13 @@ public: Attributes GetAttributes() override { Dali::TypeInfo type; - actor.GetTypeInfo( type ); - return { {"t", type.GetName()}, }; + actor.GetTypeInfo(type); + return { + {"t", type.GetName()}, + }; } - bool DoGesture(const GestureInfo &gestureInfo) override + bool DoGesture(const GestureInfo& gestureInfo) override { return false; } @@ -727,12 +731,11 @@ public: } }; -using NonControlAccessiblesType = std::unordered_map< const Dali::RefObject*, std::unique_ptr< NonControlAccessible > >; +using NonControlAccessiblesType = std::unordered_map >; NonControlAccessiblesType nonControlAccessibles; -std::function< Accessible*( Dali::Actor ) > convertingFunctor = []( Dali::Actor ) -> Accessible* -{ +std::function convertingFunctor = [](Dali::Actor) -> Accessible* { return nullptr; }; @@ -744,32 +747,30 @@ void Accessible::SetObjectRegistry(ObjectRegistry registry) objectRegistry = registry; } -void Accessible::RegisterControlAccessibilityGetter( std::function< Accessible*( Dali::Actor ) > functor ) +void Accessible::RegisterControlAccessibilityGetter(std::function functor) { convertingFunctor = functor; } -Accessible* Accessible::Get( Dali::Actor actor, bool root ) +Accessible* Accessible::Get(Dali::Actor actor, bool root) { - if( !actor ) + if(!actor) { return nullptr; } - auto accessible = convertingFunctor( actor ); - if( !accessible ) + auto accessible = convertingFunctor(actor); + if(!accessible) { - if( nonControlAccessibles.empty() && objectRegistry ) + if(nonControlAccessibles.empty() && objectRegistry) { - objectRegistry.ObjectDestroyedSignal().Connect( []( const Dali::RefObject* obj ) - { - nonControlAccessibles.erase( obj ); - } - ); + objectRegistry.ObjectDestroyedSignal().Connect([](const Dali::RefObject* obj) { + nonControlAccessibles.erase(obj); + }); } - auto it = nonControlAccessibles.emplace( &actor.GetBaseObject(), nullptr ); - if( it.second ) + auto it = nonControlAccessibles.emplace(&actor.GetBaseObject(), nullptr); + if(it.second) { - it.first->second.reset( new NonControlAccessible( actor, root ) ); + it.first->second.reset(new NonControlAccessible(actor, root)); } accessible = it.first->second.get(); } diff --git a/dali/devel-api/adaptor-framework/accessibility-impl.h b/dali/devel-api/adaptor-framework/accessibility-impl.h index cb8b2a5..7b5d18c 100644 --- a/dali/devel-api/adaptor-framework/accessibility-impl.h +++ b/dali/devel-api/adaptor-framework/accessibility-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ATSPI_ACCESSIBILITY_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,11 +27,11 @@ #include #include #include +#include #include #include #include #include -#include //INTERNAL INCLUDES #include @@ -83,7 +83,7 @@ struct DALI_ADAPTOR_API Bridge * object as direct ancestor of application and therefore make it visible for * accessibility clients. */ - virtual void AddTopLevelWindow( Accessible* ) = 0; + virtual void AddTopLevelWindow(Accessible*) = 0; /** * @brief Removes top level window @@ -92,7 +92,7 @@ struct DALI_ADAPTOR_API Bridge * structure created from Actors objects. This method removes previously added * window from visible accessibility objects. */ - virtual void RemoveTopLevelWindow( Accessible* ) = 0; + virtual void RemoveTopLevelWindow(Accessible*) = 0; /** * @brief Adds popup window @@ -100,7 +100,7 @@ struct DALI_ADAPTOR_API Bridge * Hierarchy of objects visible for accessibility clients is based on tree-like * structure created from Actors objects. This method adds new popup to the tree. */ - virtual void AddPopup( Accessible* ) = 0; + virtual void AddPopup(Accessible*) = 0; /** * @brief Removes popup window @@ -109,12 +109,12 @@ struct DALI_ADAPTOR_API Bridge * structure created from Actors objects. This method removes previously added * popup window. */ - virtual void RemovePopup( Accessible* ) = 0; + virtual void RemovePopup(Accessible*) = 0; /** * @brief Set name of current application which will be visible on accessibility bus */ - virtual void SetApplicationName( std::string ) = 0; + virtual void SetApplicationName(std::string) = 0; /** * @brief Get object being root of accessibility tree @@ -130,7 +130,7 @@ struct DALI_ADAPTOR_API Bridge * * @return handler to accessibility object */ - virtual Accessible* FindByPath( const std::string& s) const = 0; + virtual Accessible* FindByPath(const std::string& s) const = 0; /** * @brief Show application on accessibility bus @@ -157,11 +157,11 @@ struct DALI_ADAPTOR_API Bridge */ virtual ForceUpResult ForceUp() { - if( data ) + if(data) { return ForceUpResult::ALREADY_UP; } - data = std::make_shared< Data >(); + data = std::make_shared(); data->bridge = this; return ForceUpResult::JUST_STARTED; } @@ -183,37 +183,37 @@ struct DALI_ADAPTOR_API Bridge /** * @brief Emits caret-moved event on at-spi bus. **/ - virtual void EmitCaretMoved( Accessible* obj, unsigned int cursorPosition ) = 0; + virtual void EmitCaretMoved(Accessible* obj, unsigned int cursorPosition) = 0; /** * @brief Emits active-descendant-changed event on at-spi bus. **/ - virtual void EmitActiveDescendantChanged( Accessible* obj, Accessible *child ) = 0; + virtual void EmitActiveDescendantChanged(Accessible* obj, Accessible* child) = 0; /** * @brief Emits text-changed event on at-spi bus. **/ - virtual void EmitTextChanged( Accessible* obj, TextChangedState state, unsigned int position, unsigned int length, const std::string &content ) = 0; + virtual void EmitTextChanged(Accessible* obj, TextChangedState state, unsigned int position, unsigned int length, const std::string& content) = 0; /** * @brief Emits state-changed event on at-spi bus. **/ - virtual void EmitStateChanged( Accessible* obj, State state, int val1, int val2 = 0 ) = 0; + virtual void EmitStateChanged(Accessible* obj, State state, int val1, int val2 = 0) = 0; /** * @brief Emits window event on at-spi bus. **/ - virtual void Emit( Accessible* obj, WindowEvent we, unsigned int detail1 = 0 ) = 0; + virtual void Emit(Accessible* obj, WindowEvent we, unsigned int detail1 = 0) = 0; /** * @brief Emits property-changed event on at-spi bus. **/ - virtual void Emit( Accessible* obj, ObjectPropertyChangeEvent event ) = 0; + virtual void Emit(Accessible* obj, ObjectPropertyChangeEvent event) = 0; /** * @brief Emits bounds-changed event on at-spi bus. **/ - virtual void EmitBoundsChanged( Accessible* obj, Rect<> rect ) = 0; + virtual void EmitBoundsChanged(Accessible* obj, Rect<> rect) = 0; /** * @brief Emits key event on at-spi bus. @@ -221,7 +221,7 @@ struct DALI_ADAPTOR_API Bridge * Screen-reader might receive this event and reply, that given keycode is consumed. In that case * further processing of the keycode should be ignored. **/ - virtual Consumed Emit( KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText ) = 0; + virtual Consumed Emit(KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText) = 0; /** * @brief Reads given text by screen reader @@ -234,7 +234,7 @@ struct DALI_ADAPTOR_API Bridge * Callback can be one of the following signals: * ReadingCancelled, ReadingStopped, ReadingSkipped */ - virtual void Say( const std::string& text, bool discardable, std::function callback ) = 0; + virtual void Say(const std::string& text, bool discardable, std::function callback) = 0; /** * @brief Force accessibility client to pause. @@ -264,12 +264,12 @@ struct DALI_ADAPTOR_API Bridge protected: struct Data { - std::unordered_set< Accessible* > knownObjects; - std::string busName; - Bridge* bridge = nullptr; - Actor highlightActor, currentlyHighlightedActor; + std::unordered_set knownObjects; + std::string busName; + Bridge* bridge = nullptr; + Actor highlightActor, currentlyHighlightedActor; }; - std::shared_ptr< Data > data; + std::shared_ptr data; friend class Accessible; /** @@ -279,7 +279,7 @@ protected: * might come and object will be identified by number id (it's memory address). * To avoid memory corruption number id is checked against set of known objects. **/ - void RegisterOnBridge( Accessible* ); + void RegisterOnBridge(Accessible*); /** * @brief Tells bridge, that given object is considered root (doesn't have any parents). @@ -287,7 +287,7 @@ protected: * All root objects will have the same parent - application object. Application object * is controlled by bridge and private. **/ - void SetIsOnRootLevel( Accessible* ); + void SetIsOnRootLevel(Accessible*); }; /** @@ -296,11 +296,11 @@ protected: */ inline bool IsUp() { - if( Bridge::GetCurrentBridge() == nullptr ) + if(Bridge::GetCurrentBridge() == nullptr) { return false; } - if( Bridge::GetCurrentBridge()->GetIsEnabled() == false ) + if(Bridge::GetCurrentBridge()->GetIsEnabled() == false) { return false; } @@ -324,7 +324,7 @@ public: * language to use. Word boundaries are returned as non-zero values in table breaks, which * must be of size at least length. **/ - void FindWordSeparationsUtf8( const utf8_t *s, size_t length, const char *language, char *breaks ); + void FindWordSeparationsUtf8(const utf8_t* s, size_t length, const char* language, char* breaks); /** * @brief Calculaties line boundaries in given utf8 text. @@ -333,22 +333,22 @@ public: * language to use. Line boundaries are returned as non-zero values in table breaks, which * must be of size at least length. **/ - void FindLineSeparationsUtf8( const utf8_t *s, size_t length, const char *language, char *breaks ); + void FindLineSeparationsUtf8(const utf8_t* s, size_t length, const char* language, char* breaks); /** * @brief Helper function for emiting active-descendant-changed event **/ - void EmitActiveDescendantChanged( Accessible* obj, Accessible *child ); + void EmitActiveDescendantChanged(Accessible* obj, Accessible* child); /** * @brief Helper function for emiting state-changed event **/ - void EmitStateChanged( State state, int newValue1, int newValue2 = 0 ); + void EmitStateChanged(State state, int newValue1, int newValue2 = 0); /** * @brief Helper function for emiting bounds-changed event **/ - void EmitBoundsChanged( Rect<> rect ); + void EmitBoundsChanged(Rect<> rect); /** * @brief Emit "showing" event. @@ -356,7 +356,7 @@ public: * * @param[in] showing flag pointing if object is showing */ - void EmitShowing( bool showing ); + void EmitShowing(bool showing); /** * @brief Emit "visible" event. @@ -364,7 +364,7 @@ public: * * @param[in] visible flag pointing if object is visible */ - void EmitVisible( bool visible ); + void EmitVisible(bool visible); /** * @brief Emit "highlighted" event. @@ -372,7 +372,7 @@ public: * * @param[in] set flag pointing if object is highlighted */ - void EmitHighlighted( bool set ); + void EmitHighlighted(bool set); /** * @brief Emit "focused" event. @@ -380,7 +380,7 @@ public: * * @param[in] set flag pointing if object is focused */ - void EmitFocused( bool set ); + void EmitFocused(bool set); /** * @brief Emit "text inserted" event @@ -389,7 +389,7 @@ public: * @param[in] length text length * @param[in] content inserted text */ - void EmitTextInserted( unsigned int position, unsigned int length, const std::string &content ); + void EmitTextInserted(unsigned int position, unsigned int length, const std::string& content); /** * @brief Emit "text deleted" event @@ -398,14 +398,14 @@ public: * @param[in] length text length * @param[in] content deleted text */ - void EmitTextDeleted( unsigned int position, unsigned int length, const std::string &content ); + void EmitTextDeleted(unsigned int position, unsigned int length, const std::string& content); /** * @brief Emit "caret moved" event * * @param[in] cursorPosition new caret position */ - void EmitTextCaretMoved( unsigned int cursorPosition ); + void EmitTextCaretMoved(unsigned int cursorPosition); /** * @brief Emit "highlighted" event @@ -413,13 +413,13 @@ public: * @param[in] we enumerated window event * @param[in] detail1 additional parameter which interpretation depends on chosen event */ - void Emit( WindowEvent we, unsigned int detail1 = 0 ); + void Emit(WindowEvent we, unsigned int detail1 = 0); /** * @brief Emits property-changed event * @param[in] event Property changed event **/ - void Emit( ObjectPropertyChangeEvent event ); + void Emit(ObjectPropertyChangeEvent event); /** * @brief Get accessibility name @@ -454,14 +454,14 @@ public: * * @return collection of accessibility objects */ - virtual std::vector< Accessible* > GetChildren(); + virtual std::vector GetChildren(); /** * @brief Get nth child * * @return accessibility object */ - virtual Accessible* GetChildAtIndex( size_t index ) = 0; + virtual Accessible* GetChildAtIndex(size_t index) = 0; /** * @brief Get index that current object has in its parent's children collection @@ -552,7 +552,7 @@ public: * * @see Dali::Accessibility::GestureInfo */ - virtual bool DoGesture(const GestureInfo &gestureInfo) = 0; + virtual bool DoGesture(const GestureInfo& gestureInfo) = 0; /** * @brief Re-emits selected states of an Accessibility Object @@ -560,7 +560,7 @@ public: * @param[in] states chosen states to re-emit * @param[in] doRecursive if true all children of the Accessibility Object will also re-emit the states */ - void NotifyAccessibilityStateChange( Dali::Accessibility::States states, bool doRecursive ); + void NotifyAccessibilityStateChange(Dali::Accessibility::States states, bool doRecursive); /** * @brief Get information about current object and all relations that connects @@ -577,18 +577,21 @@ public: * * @return collection of strings with implemented interfaces */ - std::vector< std::string > GetInterfaces(); + std::vector GetInterfaces(); /** * @brief Check if object is on root level */ - bool GetIsOnRootLevel() const { return isOnRootLevel; } + bool GetIsOnRootLevel() const + { + return isOnRootLevel; + } /** * @brief The method registers functor resposible for converting Actor into Accessible * @param functor returning Accessible handle from Actor object */ - static void RegisterControlAccessibilityGetter( std::function< Accessible*( Dali::Actor ) > functor); + static void RegisterControlAccessibilityGetter(std::function functor); /** * @brief Acquire Accessible object from Actor object @@ -598,28 +601,28 @@ public: * * @return handle to Accessible object */ - static Accessible* Get( Dali::Actor actor, bool root = false ); + static Accessible* Get(Dali::Actor actor, bool root = false); protected: Accessible(); - Accessible( const Accessible& ) = delete; - Accessible( Accessible&& ) = delete; - Accessible& operator=( const Accessible& ) = delete; - Accessible& operator=( Accessible&& ) = delete; - std::shared_ptr< Bridge::Data > GetBridgeData(); + Accessible(const Accessible&) = delete; + Accessible(Accessible&&) = delete; + Accessible& operator=(const Accessible&) = delete; + Accessible& operator=(Accessible&&) = delete; + std::shared_ptr GetBridgeData(); public: static Dali::Actor GetHighlightActor(); - static void SetHighlightActor(Dali::Actor actor); + static void SetHighlightActor(Dali::Actor actor); static Dali::Actor GetCurrentlyHighlightedActor(); - static void SetCurrentlyHighlightedActor(Dali::Actor); - static void SetObjectRegistry(ObjectRegistry registry); + static void SetCurrentlyHighlightedActor(Dali::Actor); + static void SetObjectRegistry(ObjectRegistry registry); private: friend class Bridge; - std::weak_ptr< Bridge::Data > bridgeData; - bool isOnRootLevel = false; + std::weak_ptr bridgeData; + bool isOnRootLevel = false; }; /** @@ -635,7 +638,7 @@ public: * * @return string with name of action */ - virtual std::string GetActionName( size_t index ) = 0; + virtual std::string GetActionName(size_t index) = 0; /** * @brief Get translated name of action with given index @@ -646,7 +649,7 @@ public: * * @note translation is not supported in this version */ - virtual std::string GetLocalizedActionName( size_t index ) = 0; + virtual std::string GetLocalizedActionName(size_t index) = 0; /** * @brief Get description of action with given index @@ -655,7 +658,7 @@ public: * * @return string with description of action */ - virtual std::string GetActionDescription( size_t index ) = 0; + virtual std::string GetActionDescription(size_t index) = 0; /** * @brief Get key code binded to action with given index @@ -664,7 +667,7 @@ public: * * @return string with key name */ - virtual std::string GetActionKeyBinding( size_t index ) = 0; + virtual std::string GetActionKeyBinding(size_t index) = 0; /** * @brief Get number of provided actions @@ -680,7 +683,7 @@ public: * * @return true on success, false otherwise */ - virtual bool DoAction( size_t index ) = 0; + virtual bool DoAction(size_t index) = 0; /** * @brief Perform an action with given name @@ -689,8 +692,7 @@ public: * * @return true on success, false otherwise */ - virtual bool DoAction( const std::string& name ) = 0; - + virtual bool DoAction(const std::string& name) = 0; }; /** @@ -719,7 +721,7 @@ public: * * @see Dali::Rect */ - virtual Rect<> GetExtents( CoordType ctype ) = 0; + virtual Rect<> GetExtents(CoordType ctype) = 0; /** * @brief Get layer current object is localized on @@ -791,7 +793,7 @@ public: * * @see Dali::Accessibility::Point */ - virtual Accessible* GetAccessibleAtPoint( Point p, CoordType ctype ); + virtual Accessible* GetAccessibleAtPoint(Point p, CoordType ctype); /** * @brief Check if current object contains given point @@ -803,7 +805,7 @@ public: * * @see Dali::Accessibility::Point */ - virtual bool Contains( Point p, CoordType ctype ); + virtual bool Contains(Point p, CoordType ctype); }; /** @@ -840,7 +842,7 @@ public: * * @return true if value could have been assigned, false otherwise */ - virtual bool SetCurrent( double val) = 0; + virtual bool SetCurrent(double val) = 0; /** * @brief Get the lowest increment that can be distinguished @@ -866,7 +868,7 @@ public: * * @return substring of stored text */ - virtual std::string GetText( size_t startOffset, size_t endOffset ) = 0; + virtual std::string GetText(size_t startOffset, size_t endOffset) = 0; /** * @brief Get number of all stored characters @@ -901,7 +903,7 @@ public: * * @see Dali::Accessibility::Range */ - virtual Range GetTextAtOffset( size_t offset, TextBoundary boundary ) = 0; + virtual Range GetTextAtOffset(size_t offset, TextBoundary boundary) = 0; /** * @brief Get selected text @@ -913,7 +915,7 @@ public: * * @see Dali::Accessibility::Range */ - virtual Range GetSelection( size_t selectionNum ) = 0; + virtual Range GetSelection(size_t selectionNum) = 0; /** * @brief Remove selection @@ -923,7 +925,7 @@ public: * * @return bool on success, false otherwise */ - virtual bool RemoveSelection( size_t selectionNum ) = 0; + virtual bool RemoveSelection(size_t selectionNum) = 0; /** * @brief Get selected text @@ -936,7 +938,7 @@ public: * * @return true on success, false otherwise */ - virtual bool SetSelection( size_t selectionNum, size_t startOffset, size_t endOffset ) = 0; + virtual bool SetSelection(size_t selectionNum, size_t startOffset, size_t endOffset) = 0; }; /** @@ -957,7 +959,7 @@ public: * * @return true on success, false otherwise */ - virtual bool CopyText( size_t startPosition, size_t endPosition ) = 0; + virtual bool CopyText(size_t startPosition, size_t endPosition) = 0; /** * @brief Cut text in range to system clipboard @@ -967,7 +969,7 @@ public: * * @return true on success, false otherwise */ - virtual bool CutText( size_t startPosition, size_t endPosition ) = 0; + virtual bool CutText(size_t startPosition, size_t endPosition) = 0; }; /** @@ -981,29 +983,62 @@ class DALI_ADAPTOR_API EmptyAccessibleWithAddress : public virtual Accessible { public: EmptyAccessibleWithAddress() = default; - EmptyAccessibleWithAddress( Address address ) : address( std::move( address ) ) {} + EmptyAccessibleWithAddress(Address address) + : address(std::move(address)) + { + } - void SetAddress( Address address ) { this->address = std::move( address ); } + void SetAddress(Address address) + { + this->address = std::move(address); + } - std::string GetName() override { return ""; } - std::string GetDescription() override { return ""; } - Accessible* GetParent() override { return nullptr; } - size_t GetChildCount() override { return 0; } - std::vector< Accessible* > GetChildren() override { return {}; } - Accessible* GetChildAtIndex( size_t index ) override + std::string GetName() override { - throw std::domain_error{"out of bounds index (" + std::to_string( index ) + ") - no children"}; + return ""; + } + std::string GetDescription() override + { + return ""; + } + Accessible* GetParent() override + { + return nullptr; + } + size_t GetChildCount() override + { + return 0; + } + std::vector GetChildren() override + { + return {}; + } + Accessible* GetChildAtIndex(size_t index) override + { + throw std::domain_error{"out of bounds index (" + std::to_string(index) + ") - no children"}; + } + size_t GetIndexInParent() override + { + return static_cast(-1); + } + Role GetRole() override + { + return {}; } - size_t GetIndexInParent() override { return static_cast< size_t >( -1 ); } - Role GetRole() override { return {}; } std::string GetRoleName() override; - States GetStates() override { return {}; } - Attributes GetAttributes() override { return {}; } + States GetStates() override + { + return {}; + } + Attributes GetAttributes() override + { + return {}; + } Address GetAddress() override { return address; } - bool DoGesture(const GestureInfo &gestureInfo) override + bool DoGesture(const GestureInfo& gestureInfo) override { return false; } @@ -1016,7 +1051,7 @@ private: Address address; }; -} -} +} // namespace Accessibility +} // namespace Dali #endif // DALI_INTERNAL_ATSPI_ACCESSIBILITY_IMPL_H diff --git a/dali/devel-api/adaptor-framework/accessibility.h b/dali/devel-api/adaptor-framework/accessibility.h index a6e373e..a8d0d35 100644 --- a/dali/devel-api/adaptor-framework/accessibility.h +++ b/dali/devel-api/adaptor-framework/accessibility.h @@ -1,7 +1,7 @@ #ifndef DALI_ATSPI_ACCESSIBILITY_H #define DALI_ATSPI_ACCESSIBILITY_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,20 +19,20 @@ // EXTERNAL INCLUDES +#include #include #include #include +#include #include #include +#include +#include #include +#include #include -#include #include #include -#include -#include -#include -#include // INTERNAL INCLUDES #include @@ -41,7 +41,6 @@ namespace Dali { namespace Accessibility { - /** * @brief Enumeration describing a relation between accessible objects * 1 to 0..N relation model is supported. By default relation is not symmetrical. @@ -49,29 +48,29 @@ namespace Accessibility */ enum class RelationType : uint32_t { - NULL_OF, ///< Null Relation. - LABEL_FOR, ///< Label For. - LABELLED_BY, ///< Labelled By. - CONTROLLER_FOR, ///< Controller For. - CONTROLLED_BY, ///< Controlled By. - MEMBER_OF, ///< Member Of. - TOOLTIP_FOR, ///< ToolTip For. - NODE_CHILD_OF, ///< Node Child Of. - NODE_PARENT_OF, ///< Node Parent Of. - EXTENDED, ///< Extended. - FLOWS_TO, ///< Flows To. - FLOWS_FROM, ///< Flows From. - SUBWINDOW_OF, ///< Sub Window Of. - EMBEDS, ///< Embeds. - EMBEDDED_BY, ///< Embedded By. - POPUP_FOR, ///< Popup For + NULL_OF, ///< Null Relation. + LABEL_FOR, ///< Label For. + LABELLED_BY, ///< Labelled By. + CONTROLLER_FOR, ///< Controller For. + CONTROLLED_BY, ///< Controlled By. + MEMBER_OF, ///< Member Of. + TOOLTIP_FOR, ///< ToolTip For. + NODE_CHILD_OF, ///< Node Child Of. + NODE_PARENT_OF, ///< Node Parent Of. + EXTENDED, ///< Extended. + FLOWS_TO, ///< Flows To. + FLOWS_FROM, ///< Flows From. + SUBWINDOW_OF, ///< Sub Window Of. + EMBEDS, ///< Embeds. + EMBEDDED_BY, ///< Embedded By. + POPUP_FOR, ///< Popup For PARENT_WINDOW_OF, ///< Parent Window Of. - DESCRIPTION_FOR, ///< Description For. - DESCRIBED_BY, ///< Described By. - DETAILS, ///< Details. - DETAILS_FOR, ///< Details For. - ERROR_MESSAGE, ///< Error Message. - ERROR_FOR, ///< Error For. + DESCRIPTION_FOR, ///< Description For. + DESCRIBED_BY, ///< Described By. + DETAILS, ///< Details. + DETAILS_FOR, ///< Details For. + ERROR_MESSAGE, ///< Error Message. + ERROR_FOR, ///< Error For. MAX_COUNT }; @@ -83,7 +82,7 @@ enum class RelationType : uint32_t enum class CoordType { SCREEN, ///< Screen. - WINDOW ///< Window. + WINDOW ///< Window. }; /** @@ -95,14 +94,14 @@ enum class CoordType */ enum class ComponentLayer { - INVALID, ///< Invalid. + INVALID, ///< Invalid. BACKGROUND, ///< Background. - CANVAS, ///< Canvas. - WIDGET, ///< Widget. - MDI, ///< MDI. - POPUP, ///< Popup. - OVERLAY, ///< Overlay. - WINDOW, ///< Window. + CANVAS, ///< Canvas. + WIDGET, ///< Widget. + MDI, ///< MDI. + POPUP, ///< Popup. + OVERLAY, ///< Overlay. + WINDOW, ///< Window. MAX_COUNT }; @@ -350,9 +349,9 @@ enum class WindowEvent enum class TextBoundary : uint32_t { CHARACTER, ///> Only one character is acquired. - WORD, ///> Not supported. - SENTENCE, ///> Not supported. - LINE, ///> Not supported. + WORD, ///> Not supported. + SENTENCE, ///> Not supported. + LINE, ///> Not supported. PARAGRAPH, ///> Not supported. MAX_COUNT }; @@ -434,10 +433,10 @@ enum class ReadingInfoType * @see Dali::Accessibility::Accessible::GetStates * @see Dali::Accessibility::Accessible::GetRoles */ -template < size_t I, typename S > +template class BitSets { - std::array< uint32_t, I > data; + std::array data; void _set() { @@ -448,72 +447,77 @@ class BitSets return true; } - template < typename T > static constexpr bool _accepts() + template + static constexpr bool _accepts() { - return std::is_enum< T >::value; + return std::is_enum::value; } - template < typename T, typename T2, typename ... ARGS > static constexpr bool _accepts() + template + static constexpr bool _accepts() { - return std::is_enum< T >::value && _accepts< T2, ARGS... >(); + return std::is_enum::value && _accepts(); } - template < typename T, typename ... ARGS > void _set(T t, ARGS ... args) + template + void _set(T t, ARGS... args) { (*this)[t] = true; _set(args...); } + public: BitSets() { - for( auto& u : data ) + for(auto& u : data) { u = 0; } } BitSets(const BitSets&) = default; - BitSets(BitSets&&) = default; + BitSets(BitSets&&) = default; - template < typename T, typename ... ARGS, typename std::enable_if< _accepts< T, ARGS... >() >::type * = nullptr >BitSets( T t, ARGS ... args ) + template()>::type* = nullptr> + BitSets(T t, ARGS... args) { - for( auto& u : data ) - u = 0; - _set( t, args... ); + for(auto& u : data) + u = 0; + _set(t, args...); } - explicit BitSets( std::array< uint32_t, I > d ) + explicit BitSets(std::array d) { - for( auto i = 0u; i < I; ++i ) + for(auto i = 0u; i < I; ++i) { data[i] = d[i]; } } - explicit BitSets( std::array< int32_t, I > d ) + explicit BitSets(std::array d) { - for( auto i = 0u; i < I; ++i ) + for(auto i = 0u; i < I; ++i) { - data[i] = static_cast( d[i] ); + data[i] = static_cast(d[i]); } } - BitSets& operator = (const BitSets&) = default; - BitSets& operator = (BitSets&&) = default; + BitSets& operator=(const BitSets&) = default; + BitSets& operator=(BitSets&&) = default; struct reference { - std::array< uint32_t, I >& data; - size_t pos; + std::array& data; + size_t pos; - reference& operator=( reference r ) + reference& operator=(reference r) { - (*this) = static_cast( r ); + (*this) = static_cast(r); return *this; } - reference& operator=( bool v ) + reference& operator=(bool v) { - if( v ) + if(v) { data[pos / 32] |= 1 << (pos & 31); } @@ -526,62 +530,62 @@ public: operator bool() const { - auto i = static_cast( pos ); + auto i = static_cast(pos); return (data[i / 32] & (1 << (i & 31))) != 0; } }; - reference operator[]( S index ) + reference operator[](S index) { - return { data, static_cast( index ) }; + return {data, static_cast(index)}; } - bool operator[]( S index ) const + bool operator[](S index) const { - auto i = static_cast( index ); - return ( data[i / 32] & ( 1 << (i & 31) ) ) != 0; + auto i = static_cast(index); + return (data[i / 32] & (1 << (i & 31))) != 0; } - std::array< uint32_t, I > GetRawData() const + std::array GetRawData() const { return data; } - BitSets operator|( BitSets b ) const + BitSets operator|(BitSets b) const { BitSets r; - for( auto i = 0u; i < I; ++i ) + for(auto i = 0u; i < I; ++i) { r.data[i] = data[i] | b.data[i]; } return r; } - BitSets operator^( BitSets b ) const + BitSets operator^(BitSets b) const { BitSets r; - for( auto i = 0u; i < I; ++i ) + for(auto i = 0u; i < I; ++i) { r.data[i] = data[i] ^ b.data[i]; } return r; } - BitSets operator&( BitSets b ) const + BitSets operator&(BitSets b) const { BitSets r; - for( auto i = 0u; i < I; ++i ) + for(auto i = 0u; i < I; ++i) { r.data[i] = data[i] & b.data[i]; } return r; } - bool operator==( BitSets b ) const + bool operator==(BitSets b) const { - for( auto i = 0u; i < I; ++i ) + for(auto i = 0u; i < I; ++i) { - if( data[i] != b.data[i] ) + if(data[i] != b.data[i]) { return false; } @@ -596,9 +600,9 @@ public: explicit operator bool() const { - for( auto& u : data ) + for(auto& u : data) { - if( u ) + if(u) { return true; } @@ -613,8 +617,8 @@ public: }; using ReadingInfoTypes = BitSets<1, ReadingInfoType>; -using States = BitSets< 2, State >; -using Attributes = std::unordered_map< std::string, std::string >; +using States = BitSets<2, State>; +using Attributes = std::unordered_map; /** * @brief Class representing unique object address on accessibility bus @@ -625,7 +629,7 @@ class DALI_ADAPTOR_API Address public: Address() = default; - Address( std::string bus, std::string path ) + Address(std::string bus, std::string path) : mBus(std::move(bus)), mPath(std::move(path)) { @@ -648,12 +652,12 @@ public: return mPath; } - bool operator == ( const Address& a ) const + bool operator==(const Address& a) const { return mBus == a.mBus && mPath == a.mPath; } - bool operator != ( const Address& a ) const + bool operator!=(const Address& a) const { return !(*this == a); } @@ -692,7 +696,7 @@ struct DALI_ADAPTOR_API Point Point() = default; - Point( int x, int y ) + Point(int x, int y) : x(x), y(y) { @@ -713,7 +717,7 @@ struct DALI_ADAPTOR_API Point */ struct DALI_ADAPTOR_API Size { - int width = 0; + int width = 0; int height = 0; Size() = default; @@ -724,12 +728,12 @@ struct DALI_ADAPTOR_API Size { } - bool operator==( Size p ) const + bool operator==(Size p) const { return width == p.width && height == p.height; } - bool operator!=( Size p ) const + bool operator!=(Size p) const { return !(*this == p); } @@ -742,8 +746,8 @@ struct DALI_ADAPTOR_API Size */ struct DALI_ADAPTOR_API Range { - int32_t startOffset = 0; - int32_t endOffset = 0; + int32_t startOffset = 0; + int32_t endOffset = 0; std::string content; Range() = default; @@ -785,13 +789,13 @@ struct DALI_ADAPTOR_API GestureInfo { } - Gesture type{}; - int32_t xBeg{}; - int32_t xEnd{}; - int32_t yBeg{}; - int32_t yEnd{}; + Gesture type{}; + int32_t xBeg{}; + int32_t xEnd{}; + int32_t yBeg{}; + int32_t yEnd{}; GestureState state{}; - uint32_t eventTime{}; + uint32_t eventTime{}; }; /** @@ -804,14 +808,14 @@ struct DALI_ADAPTOR_API GestureInfo */ struct DALI_ADAPTOR_API Relation { -Relation(RelationType relationType, std::vector
targets) -: relationType(relationType), - targets(targets) -{ -} + Relation(RelationType relationType, std::vector
targets) + : relationType(relationType), + targets(targets) + { + } -RelationType relationType; -std::vector
targets; + RelationType relationType; + std::vector
targets; }; } // namespace Accessibility diff --git a/dali/devel-api/adaptor-framework/atspi-accessibility.cpp b/dali/devel-api/adaptor-framework/atspi-accessibility.cpp index 575b8f7..1828477 100644 --- a/dali/devel-api/adaptor-framework/atspi-accessibility.cpp +++ b/dali/devel-api/adaptor-framework/atspi-accessibility.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,12 @@ * */ -#include #include +#include void Dali::AtspiAccessibility::Pause() { - if( auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge() ) + if(auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge()) { bridge->Pause(); } @@ -28,25 +28,25 @@ void Dali::AtspiAccessibility::Pause() void Dali::AtspiAccessibility::Resume() { - if( auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge() ) + if(auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge()) { bridge->Resume(); } } -void Dali::AtspiAccessibility::Say( const std::string& text, bool discardable, std::function callback ) +void Dali::AtspiAccessibility::Say(const std::string& text, bool discardable, std::function callback) { - if( auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge() ) + if(auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge()) { bridge->Say(text, discardable, callback); } } -int Dali::AtspiAccessibility::SetForcefully( bool turnOn ) +int Dali::AtspiAccessibility::SetForcefully(bool turnOn) { - if( turnOn ) + if(turnOn) { - if( auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge() ) + if(auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge()) { bridge->Initialize(); auto ret = bridge->ForceUp(); @@ -55,7 +55,7 @@ int Dali::AtspiAccessibility::SetForcefully( bool turnOn ) } else { - if( auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge() ) + if(auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge()) { bridge->ForceDown(); return 0; @@ -67,11 +67,11 @@ int Dali::AtspiAccessibility::SetForcefully( bool turnOn ) int Dali::AtspiAccessibility::GetStatus() { //0(ATSPI OFF, ScreenReader OFF), 1(ATSPI ON, ScreenReader OFF), 2 (ATSPI OFF, ScreenReader ON), 3(ATSPI ON, ScreenReader ON) - if( auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge() ) + if(auto bridge = Dali::Accessibility::Bridge::GetCurrentBridge()) { - if( bridge->GetScreenReaderEnabled() ) + if(bridge->GetScreenReaderEnabled()) { - if( bridge->GetIsEnabled() ) + if(bridge->GetIsEnabled()) { return 3; } @@ -82,7 +82,7 @@ int Dali::AtspiAccessibility::GetStatus() } else { - if( bridge->GetIsEnabled() ) + if(bridge->GetIsEnabled()) { return 1; } diff --git a/dali/devel-api/adaptor-framework/gl-window.cpp b/dali/devel-api/adaptor-framework/gl-window.cpp index bd85059..929e2a9 100644 --- a/dali/devel-api/adaptor-framework/gl-window.cpp +++ b/dali/devel-api/adaptor-framework/gl-window.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,27 +28,26 @@ namespace Dali { - GlWindow GlWindow::New() { - PositionSize positionSize( 0, 0, 0, 0 ); - return Dali::GlWindow::New( positionSize, "", "", false ); + PositionSize positionSize(0, 0, 0, 0); + return Dali::GlWindow::New(positionSize, "", "", false); } -GlWindow GlWindow::New(PositionSize positionSize, const std::string& name, const std::string& className, bool isTransparent ) +GlWindow GlWindow::New(PositionSize positionSize, const std::string& name, const std::string& className, bool isTransparent) { - GlWindow newWindow; - Internal::Adaptor::GlWindow* window = Internal::Adaptor::GlWindow::New( positionSize, name, className, isTransparent ); - newWindow = GlWindow(window); + GlWindow newWindow; + Internal::Adaptor::GlWindow* window = Internal::Adaptor::GlWindow::New(positionSize, name, className, isTransparent); + newWindow = GlWindow(window); const bool isAdaptorAvailable = Dali::Adaptor::IsAvailable(); - if( isAdaptorAvailable ) + if(isAdaptorAvailable) { - Dali::Adaptor& adaptor = Internal::Adaptor::Adaptor::Get(); + Dali::Adaptor& adaptor = Internal::Adaptor::Adaptor::Get(); Dali::WindowContainer windows = adaptor.GetWindows(); - if( !windows.empty() ) + if(!windows.empty()) { - window->SetChild( windows[0] ); + window->SetChild(windows[0]); } } return newWindow; @@ -70,9 +69,9 @@ GlWindow::GlWindow(GlWindow&& rhs) = default; GlWindow& GlWindow::operator=(GlWindow&& rhs) = default; -void GlWindow::SetEglConfig( bool depth, bool stencil, int msaa, GlesVersion version ) +void GlWindow::SetEglConfig(bool depth, bool stencil, int msaa, GlesVersion version) { - GetImplementation(*this).SetEglConfig( depth, stencil, msaa, version ); + GetImplementation(*this).SetEglConfig(depth, stencil, msaa, version); } void GlWindow::Raise() @@ -105,44 +104,44 @@ unsigned int GlWindow::GetSupportedAuxiliaryHintCount() const return GetImplementation(*this).GetSupportedAuxiliaryHintCount(); } -std::string GlWindow::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string GlWindow::GetSupportedAuxiliaryHint(unsigned int index) const { - return GetImplementation(*this).GetSupportedAuxiliaryHint( index ); + return GetImplementation(*this).GetSupportedAuxiliaryHint(index); } -unsigned int GlWindow::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int GlWindow::AddAuxiliaryHint(const std::string& hint, const std::string& value) { - return GetImplementation(*this).AddAuxiliaryHint( hint, value ); + return GetImplementation(*this).AddAuxiliaryHint(hint, value); } -bool GlWindow::RemoveAuxiliaryHint( unsigned int id ) +bool GlWindow::RemoveAuxiliaryHint(unsigned int id) { - return GetImplementation(*this).RemoveAuxiliaryHint( id ); + return GetImplementation(*this).RemoveAuxiliaryHint(id); } -bool GlWindow::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool GlWindow::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { - return GetImplementation(*this).SetAuxiliaryHintValue( id, value ); + return GetImplementation(*this).SetAuxiliaryHintValue(id, value); } -std::string GlWindow::GetAuxiliaryHintValue( unsigned int id ) const +std::string GlWindow::GetAuxiliaryHintValue(unsigned int id) const { - return GetImplementation(*this).GetAuxiliaryHintValue( id ); + return GetImplementation(*this).GetAuxiliaryHintValue(id); } -unsigned int GlWindow::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int GlWindow::GetAuxiliaryHintId(const std::string& hint) const { - return GetImplementation(*this).GetAuxiliaryHintId( hint ); + return GetImplementation(*this).GetAuxiliaryHintId(hint); } -void GlWindow::SetInputRegion( const Rect< int >& inputRegion ) +void GlWindow::SetInputRegion(const Rect& inputRegion) { - GetImplementation(*this).SetInputRegion( inputRegion ); + GetImplementation(*this).SetInputRegion(inputRegion); } -void GlWindow::SetOpaqueState( bool opaque ) +void GlWindow::SetOpaqueState(bool opaque) { - GetImplementation(*this).SetOpaqueState( opaque ); + GetImplementation(*this).SetOpaqueState(opaque); } bool GlWindow::IsOpaqueState() const @@ -150,9 +149,9 @@ bool GlWindow::IsOpaqueState() const return GetImplementation(*this).IsOpaqueState(); } -void GlWindow::SetPositionSize( PositionSize positionSize ) +void GlWindow::SetPositionSize(PositionSize positionSize) { - GetImplementation(*this).SetPositionSize( positionSize ); + GetImplementation(*this).SetPositionSize(positionSize); } PositionSize GlWindow::GetPositionSize() const @@ -162,22 +161,22 @@ PositionSize GlWindow::GetPositionSize() const WindowOrientation GlWindow::GetCurrentOrientation() const { - return GetImplementation( *this ).GetCurrentOrientation(); + return GetImplementation(*this).GetCurrentOrientation(); } -void GlWindow::SetAvailableOrientations( const Dali::Vector< WindowOrientation >& orientations ) +void GlWindow::SetAvailableOrientations(const Dali::Vector& orientations) { - GetImplementation( *this ).SetAvailableOrientations( orientations ); + GetImplementation(*this).SetAvailableOrientations(orientations); } -void GlWindow::SetPreferredOrientation( WindowOrientation orientation ) +void GlWindow::SetPreferredOrientation(WindowOrientation orientation) { - GetImplementation(*this).SetPreferredOrientation( orientation ); + GetImplementation(*this).SetPreferredOrientation(orientation); } -void GlWindow::RegisterGlCallback( CallbackBase* initCallback, CallbackBase* renderFrameCallback, CallbackBase* terminateCallback ) +void GlWindow::RegisterGlCallback(CallbackBase* initCallback, CallbackBase* renderFrameCallback, CallbackBase* terminateCallback) { - GetImplementation(*this).RegisterGlCallback( initCallback, renderFrameCallback, terminateCallback ); + GetImplementation(*this).RegisterGlCallback(initCallback, renderFrameCallback, terminateCallback); } void GlWindow::RenderOnce() @@ -185,9 +184,9 @@ void GlWindow::RenderOnce() GetImplementation(*this).RenderOnce(); } -void GlWindow::SetRenderingMode( RenderingMode mode ) +void GlWindow::SetRenderingMode(RenderingMode mode) { - GetImplementation(*this).SetRenderingMode( mode ); + GetImplementation(*this).SetRenderingMode(mode); } GlWindow::RenderingMode GlWindow::GetRenderingMode() const @@ -220,9 +219,9 @@ GlWindow::VisibilityChangedSignalType& GlWindow::VisibilityChangedSignal() return GetImplementation(*this).VisibilityChangedSignal(); } -GlWindow::GlWindow( Internal::Adaptor::GlWindow* window ) -: BaseHandle( window ) +GlWindow::GlWindow(Internal::Adaptor::GlWindow* window) +: BaseHandle(window) { } -}// Dali +} // namespace Dali diff --git a/dali/devel-api/adaptor-framework/gl-window.h b/dali/devel-api/adaptor-framework/gl-window.h index ccd51fa..72b5855 100644 --- a/dali/devel-api/adaptor-framework/gl-window.h +++ b/dali/devel-api/adaptor-framework/gl-window.h @@ -2,7 +2,7 @@ #define DALI_GL_WINDOW_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,15 +19,15 @@ */ // EXTERNAL INCLUDES -#include +#include #include #include #include #include -#include #include +#include #include -#include +#include // INTERNAL INCLUDES #include @@ -47,7 +47,7 @@ namespace Adaptor { class GlWindow; } -} +} // namespace DALI_INTERNAL class TouchEvent; class KeyEvent; @@ -63,17 +63,15 @@ class KeyEvent; class DALI_ADAPTOR_API GlWindow : public BaseHandle { public: + using WindowSize = Uint16Pair; - using WindowSize = Uint16Pair ; - - typedef Signal< void ( const KeyEvent& ) > KeyEventSignalType; ///< GlWindow Key Event signal type - typedef Signal< void ( const TouchEvent& ) > TouchEventSignalType; ///< GlWindow Touch Event signal type - typedef Signal< void ( GlWindow, bool ) > FocusChangeSignalType; ///< GlWindow Focus signal type - typedef Signal< void ( WindowSize ) > ResizeSignalType; ///< GlWindow resize signal type - typedef Signal< void ( GlWindow, bool ) > VisibilityChangedSignalType; ///< GlWindow visibility change signal type + typedef Signal KeyEventSignalType; ///< GlWindow Key Event signal type + typedef Signal TouchEventSignalType; ///< GlWindow Touch Event signal type + typedef Signal FocusChangeSignalType; ///< GlWindow Focus signal type + typedef Signal ResizeSignalType; ///< GlWindow resize signal type + typedef Signal VisibilityChangedSignalType; ///< GlWindow visibility change signal type public: - // Enumerations /** @@ -85,8 +83,8 @@ public: */ enum class GlesVersion { - VERSION_2_0 = 0, ///< GLES version 2.0 - VERSION_3_0, ///< GLES version 3.0 + VERSION_2_0 = 0, ///< GLES version 2.0 + VERSION_3_0, ///< GLES version 3.0 }; /** @@ -99,8 +97,8 @@ public: */ enum class RenderingMode { - CONTINUOUS, ///< continuous mode - ON_DEMAND ///< on demand by application + CONTINUOUS, ///< continuous mode + ON_DEMAND ///< on demand by application }; /** @@ -121,7 +119,7 @@ public: * @note This creates an extra GlWindow in addition to the default main GlWindow * @return A new GlWindow */ - static GlWindow New( PositionSize positionSize, const std::string& name, const std::string& className, bool isTransparent = false ); + static GlWindow New(PositionSize positionSize, const std::string& name, const std::string& className, bool isTransparent = false); /** * @brief Creates an uninitialized handle. @@ -155,7 +153,7 @@ public: */ GlWindow& operator=(const GlWindow& rhs); - /** + /** * @brief Move constructor. * * @param[in] rhs A reference to the moved handle @@ -179,7 +177,7 @@ public: * @param[in] version the GLES version * */ - void SetEglConfig( bool depth, bool stencil, int msaa, GlesVersion version ); + void SetEglConfig(bool depth, bool stencil, int msaa, GlesVersion version); /** * @brief Raises GlWindow to the top of GlWindow stack. @@ -216,7 +214,7 @@ public: * * @param[in] positionSize The new GlWindow position */ - void SetPositionSize( PositionSize positionSize ); + void SetPositionSize(PositionSize positionSize); /** * @brief Gets a position of the GlWindow. @@ -244,7 +242,7 @@ public: * @note The window auxiliary hint is the value which is used to decide which actions should be made available to the user by the window manager. * If you want to set specific hint to your window, then you should check whether it exists in the supported auxiliary hints. */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const; + std::string GetSupportedAuxiliaryHint(unsigned int index) const; /** * @brief Creates an auxiliary hint of the window. @@ -253,7 +251,7 @@ public: * @param[in] value The value string. * @return The ID of created auxiliary hint, or @c 0 on failure. */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ); + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value); /** * @brief Removes an auxiliary hint of the window. @@ -261,7 +259,7 @@ public: * @param[in] id The ID of the auxiliary hint. * @return True if no error occurred, false otherwise. */ - bool RemoveAuxiliaryHint( unsigned int id ); + bool RemoveAuxiliaryHint(unsigned int id); /** * @brief Changes a value of the auxiliary hint. @@ -270,7 +268,7 @@ public: * @param[in] value The value string to be set. * @return True if no error occurred, false otherwise. */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ); + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value); /** * @brief Gets a value of the auxiliary hint. @@ -278,7 +276,7 @@ public: * @param[in] id The auxiliary hint ID. * @return The string value of the auxiliary hint ID, or an empty string if none exists. */ - std::string GetAuxiliaryHintValue( unsigned int id ) const; + std::string GetAuxiliaryHintValue(unsigned int id) const; /** * @brief Gets a ID of the auxiliary hint string. @@ -286,14 +284,14 @@ public: * @param[in] hint The auxiliary hint string. * @return The ID of the auxiliary hint string, or @c 0 if none exists. */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const; + unsigned int GetAuxiliaryHintId(const std::string& hint) const; /** * @brief Sets a region to accept input events. * * @param[in] inputRegion The region to accept input events. */ - void SetInputRegion( const Rect< int >& inputRegion ); + void SetInputRegion(const Rect& inputRegion); /** * @brief Sets a transparent window's visual state to opaque. @@ -304,7 +302,7 @@ public: * @remarks This will have no effect on an opaque window. * It doesn't change transparent window to opaque window but lets the window manager know the visual state of the window. */ - void SetOpaqueState( bool opaque ); + void SetOpaqueState(bool opaque); /** * @brief Returns whether a transparent window's visual state is opaque or not. @@ -319,16 +317,16 @@ public: * * @return The current GlWindow rotation angle if previously set, or none */ - WindowOrientation GetCurrentOrientation() const; + WindowOrientation GetCurrentOrientation() const; - /** + /** * @brief Sets available orientations of the window. * * This API is for setting several orientations one time. * * @param[in] orientations The available orientations list to add */ - void SetAvailableOrientations( const Dali::Vector& orientations ); + void SetAvailableOrientations(const Dali::Vector& orientations); /** * @brief Sets a preferred orientation. @@ -338,7 +336,7 @@ public: * * @note To unset the preferred orientation, angle should be set NO_ORIENTATION_PREFERENCE. */ - void SetPreferredOrientation( WindowOrientation orientation ); + void SetPreferredOrientation(WindowOrientation orientation); /** * @brief Registers a GL callback function for application. @@ -367,7 +365,7 @@ public: * @endcode * This callback is called when GlWindow is deleted. */ - void RegisterGlCallback( CallbackBase* initCallback, CallbackBase* renderFrameCallback, CallbackBase* terminateCallback ); + void RegisterGlCallback(CallbackBase* initCallback, CallbackBase* renderFrameCallback, CallbackBase* terminateCallback); /** * @brief Renders once more even if GL render functions are not added to idler. @@ -384,7 +382,7 @@ public: * @note The default Rendering mode is continuous. * If OnDemand mode is set, it is rendered by RenderOnce() */ - void SetRenderingMode( RenderingMode mode ); + void SetRenderingMode(RenderingMode mode); /** * @brief Gets rendering mode. @@ -397,7 +395,6 @@ public: RenderingMode GetRenderingMode() const; public: // Signals - /** * @brief The user should connect to this signal to get a timing when GlWindow gains focus or loses focus. * @@ -474,7 +471,7 @@ public: // Not intended for application developers * @brief This constructor is used by Dali::Application::GetGlWindow(). * @param[in] GlWindow A pointer to the GlWindow */ - explicit DALI_INTERNAL GlWindow( Internal::Adaptor::GlWindow* GlWindow ); + explicit DALI_INTERNAL GlWindow(Internal::Adaptor::GlWindow* GlWindow); /// @endcond }; diff --git a/dali/devel-api/adaptor-framework/vector-image-renderer-plugin.h b/dali/devel-api/adaptor-framework/vector-image-renderer-plugin.h index 7e0f8f8..76d78f7 100644 --- a/dali/devel-api/adaptor-framework/vector-image-renderer-plugin.h +++ b/dali/devel-api/adaptor-framework/vector-image-renderer-plugin.h @@ -2,7 +2,7 @@ #define DALI_VECTOR_IMAGE_RENDERER_PLUGIN_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ namespace Dali { - /** * VectorImageRendererPlugin is an abstract interface, used by dali-adaptor to render a vector image(SVG). * A concrete implementation must be created for each platform and provided as a dynamic library which @@ -35,12 +34,16 @@ public: /** * @brief Constructor */ - VectorImageRendererPlugin() {} + VectorImageRendererPlugin() + { + } /** * @brief Destructor */ - virtual ~VectorImageRendererPlugin() {} + virtual ~VectorImageRendererPlugin() + { + } /** * @brief Load vector image data directly. @@ -56,7 +59,7 @@ public: * @param[in] buffer The target buffer * @return True if the rendering succeeds, false otherwise. */ - virtual bool Rasterize(Dali::Devel::PixelBuffer &buffer) = 0; + virtual bool Rasterize(Dali::Devel::PixelBuffer& buffer) = 0; /** * @brief Gets the default size of the file. @@ -64,7 +67,7 @@ public: * @param[out] width The default width of the file * @param[out] height The default height of the file */ - virtual void GetDefaultSize( uint32_t& width, uint32_t& height ) const = 0; + virtual void GetDefaultSize(uint32_t& width, uint32_t& height) const = 0; /** * @brief Function pointer called in adaptor to create a plugin instance. diff --git a/dali/devel-api/adaptor-framework/vector-image-renderer.cpp b/dali/devel-api/adaptor-framework/vector-image-renderer.cpp index fb51e62..f557cad 100644 --- a/dali/devel-api/adaptor-framework/vector-image-renderer.cpp +++ b/dali/devel-api/adaptor-framework/vector-image-renderer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,10 @@ namespace Dali { - VectorImageRenderer VectorImageRenderer::New() { Internal::Adaptor::VectorImageRendererPtr imageRenderer = Internal::Adaptor::VectorImageRenderer::New(); - return VectorImageRenderer( imageRenderer.Get() ); + return VectorImageRenderer(imageRenderer.Get()); } VectorImageRenderer::VectorImageRenderer() @@ -38,8 +37,8 @@ VectorImageRenderer::~VectorImageRenderer() { } -VectorImageRenderer::VectorImageRenderer( Internal::Adaptor::VectorImageRenderer* internal ) -: BaseHandle( internal ) +VectorImageRenderer::VectorImageRenderer(Internal::Adaptor::VectorImageRenderer* internal) +: BaseHandle(internal) { } @@ -53,9 +52,9 @@ bool VectorImageRenderer::Rasterize(Dali::Devel::PixelBuffer& buffer, float scal return GetImplementation(*this).Rasterize(buffer, scale); } -void VectorImageRenderer::GetDefaultSize( uint32_t& width, uint32_t& height ) const +void VectorImageRenderer::GetDefaultSize(uint32_t& width, uint32_t& height) const { - GetImplementation( *this ).GetDefaultSize( width, height ); + GetImplementation(*this).GetDefaultSize(width, height); } } // namespace Dali diff --git a/dali/devel-api/adaptor-framework/vector-image-renderer.h b/dali/devel-api/adaptor-framework/vector-image-renderer.h index bd82fa3..d2343d6 100644 --- a/dali/devel-api/adaptor-framework/vector-image-renderer.h +++ b/dali/devel-api/adaptor-framework/vector-image-renderer.h @@ -2,7 +2,7 @@ #define DALI_VECTOR_IMAGE_RENDERER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -32,13 +32,10 @@ namespace Dali * @{ */ -namespace Internal DALI_INTERNAL -{ -namespace Adaptor +namespace Internal::Adaptor { class VectorImageRenderer; -} -} +} // namespace Internal::Adaptor /** * @brief Used for rendering a vector image file (SVG) @@ -46,7 +43,6 @@ class VectorImageRenderer; class DALI_ADAPTOR_API VectorImageRenderer : public BaseHandle { public: - /** * @brief Creates an initialized handle to a new VectorImageRenderer. * @@ -70,7 +66,7 @@ public: * * @param[in] handle A reference to the copied handle */ - VectorImageRenderer( const VectorImageRenderer& handle ) = default; + VectorImageRenderer(const VectorImageRenderer& handle) = default; /** * @brief This assignment operator is required for (smart) pointer semantics. @@ -78,7 +74,7 @@ public: * @param[in] rhs A reference to the copied handle * @return A reference to this */ - VectorImageRenderer& operator=( const VectorImageRenderer& rhs ) = default; + VectorImageRenderer& operator=(const VectorImageRenderer& rhs) = default; /** * @brief Load vector image data directly. @@ -107,7 +103,6 @@ public: void GetDefaultSize(uint32_t& width, uint32_t& height) const; public: // Not intended for application developers - /// @cond internal /** * @brief The constructor. @@ -115,9 +110,8 @@ public: // Not intended for application developers * * @param[in] pointer A pointer to a newly allocated VectorImageRenderer */ - explicit DALI_INTERNAL VectorImageRenderer( Internal::Adaptor::VectorImageRenderer* internal ); + explicit DALI_INTERNAL VectorImageRenderer(Internal::Adaptor::VectorImageRenderer* internal); /// @endcond - }; /** diff --git a/dali/devel-api/adaptor-framework/web-engine-back-forward-list-item.h b/dali/devel-api/adaptor-framework/web-engine-back-forward-list-item.h old mode 100755 new mode 100644 index 6ab63de..c1b762e --- a/dali/devel-api/adaptor-framework/web-engine-back-forward-list-item.h +++ b/dali/devel-api/adaptor-framework/web-engine-back-forward-list-item.h @@ -23,15 +23,12 @@ namespace Dali { - /** * @brief A class WebBackForwardListItem for back forward list item of web engine. */ class WebEngineBackForwardListItem { - public: - /** * @brief Constructor. */ @@ -61,10 +58,8 @@ public: * @return The original URL of the item, otherwise "" in case of an error */ virtual std::string GetOriginalUrl() const = 0; - }; } // namespace Dali #endif // DALI_WEB_ENGINE_BACK_FORWARD_LIST_ITEM_H - diff --git a/dali/devel-api/adaptor-framework/web-engine-back-forward-list.h b/dali/devel-api/adaptor-framework/web-engine-back-forward-list.h old mode 100755 new mode 100644 index 26fd66a..cc0f82b --- a/dali/devel-api/adaptor-framework/web-engine-back-forward-list.h +++ b/dali/devel-api/adaptor-framework/web-engine-back-forward-list.h @@ -19,12 +19,11 @@ */ // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - class WebEngineBackForwardListItem; /** @@ -32,9 +31,7 @@ class WebEngineBackForwardListItem; */ class WebEngineBackForwardList { - public: - /** * @brief Constructor. */ @@ -56,7 +53,7 @@ public: * @param[in] index The index of the item * @return The item of back-forward list. */ - virtual WebEngineBackForwardListItem& GetItemAtIndex( uint32_t index ) const = 0; + virtual WebEngineBackForwardListItem& GetItemAtIndex(uint32_t index) const = 0; /** * @brief Returns the length of the back-forward list including the current @@ -65,7 +62,6 @@ public: * otherwise @c 0 in case of an error */ virtual uint32_t GetItemCount() const = 0; - }; } // namespace Dali diff --git a/dali/devel-api/adaptor-framework/web-engine-context.h b/dali/devel-api/adaptor-framework/web-engine-context.h old mode 100755 new mode 100644 index 752ac81..22a5b67 --- a/dali/devel-api/adaptor-framework/web-engine-context.h +++ b/dali/devel-api/adaptor-framework/web-engine-context.h @@ -2,7 +2,7 @@ #define DALI_WEB_ENGINE_CONTEXT_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,16 @@ */ // EXTERNAL INCLUDES +#include namespace Dali { - /** * @brief A class WebEngineContext for context of web engine. */ class WebEngineContext { - public: - /** * @brief Enumeration for cache model options. */ @@ -61,13 +59,13 @@ public: * @brief Requests to set the cache model. * @param[in] cacheModel The cache model */ - virtual void SetCacheModel( CacheModel cacheModel ) = 0; + virtual void SetCacheModel(CacheModel cacheModel) = 0; /** * @brief Sets the given proxy URI to network backend of specific context. * @param[in] uri The proxy URI to set */ - virtual void SetProxyUri( const std::string& uri ) = 0; + virtual void SetProxyUri(const std::string& uri) = 0; /** * @brief Sets a proxy auth credential to network backend of specific context. @@ -78,7 +76,7 @@ public: * @param[in] username username to set * @param[in] password password to set */ - virtual void SetDefaultProxyAuth( const std::string& username, const std::string& password ) = 0; + virtual void SetDefaultProxyAuth(const std::string& username, const std::string& password) = 0; /** * Adds CA certificates to persistent NSS certificate database @@ -88,7 +86,7 @@ public: * Directories are traversed recursively. * @param[in] certificatePath path to a CA certificate file(s), see above for details */ - virtual void SetCertificateFilePath( const std::string& certificatePath ) = 0; + virtual void SetCertificateFilePath(const std::string& certificatePath) = 0; /** * Requests for deleting all web databases. @@ -113,13 +111,12 @@ public: * By default the cache is disabled resulting in not storing network data on disk. * @param[in] cacheDisabled enable or disable cache */ - virtual void DisableCache( bool cacheDisabled ) = 0; + virtual void DisableCache(bool cacheDisabled) = 0; /** * @brief Requests to clear cache */ virtual void ClearCache() = 0; - }; } // namespace Dali diff --git a/dali/devel-api/adaptor-framework/web-engine-cookie-manager.h b/dali/devel-api/adaptor-framework/web-engine-cookie-manager.h old mode 100755 new mode 100644 index e053263..8400d35 --- a/dali/devel-api/adaptor-framework/web-engine-cookie-manager.h +++ b/dali/devel-api/adaptor-framework/web-engine-cookie-manager.h @@ -19,18 +19,16 @@ */ // EXTERNAL INCLUDES +#include namespace Dali { - /** * @brief A class WebEngineCookieManager to wrap ewk cookie manager. */ class WebEngineCookieManager { - public: - /** * @brief Enumeration for the cookies accept policies. */ @@ -67,7 +65,7 @@ public: * * @param[in] policy A #Dali::WebEngineCookieManager::CookieAcceptPolicy */ - virtual void SetCookieAcceptPolicy( CookieAcceptPolicy policy ) = 0; + virtual void SetCookieAcceptPolicy(CookieAcceptPolicy policy) = 0; /** * @brief Gets the cookie acceptance policy. @@ -92,8 +90,7 @@ public: * @param[in] path The path where to read/write Cookies * @param[in] storage The type of storage */ - virtual void SetPersistentStorage( const std::string& path, CookiePersistentStorage storage ) = 0; - + virtual void SetPersistentStorage(const std::string& path, CookiePersistentStorage storage) = 0; }; } // namespace Dali diff --git a/dali/devel-api/adaptor-framework/web-engine-plugin.h b/dali/devel-api/adaptor-framework/web-engine-plugin.h old mode 100755 new mode 100644 index 118446d..88500cc --- a/dali/devel-api/adaptor-framework/web-engine-plugin.h +++ b/dali/devel-api/adaptor-framework/web-engine-plugin.h @@ -2,7 +2,7 @@ #define DALI_WEB_ENGINE_PLUGIN_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ // EXTERNAL INCLUDES #include +#include #include #include @@ -43,12 +44,12 @@ public: /** * @brief WebEngine signal type related with page loading. */ - using WebEnginePageLoadSignalType = Signal< void( const std::string& ) >; + using WebEnginePageLoadSignalType = Signal; /** * @brief WebView signal type related with page loading error. */ - using WebEnginePageLoadErrorSignalType = Signal< void( const std::string&, int ) >; + using WebEnginePageLoadErrorSignalType = Signal; // forward declaration. enum class ScrollEdge; @@ -56,7 +57,7 @@ public: /** * @brief WebView signal type related with scroll edge reached. */ - using WebEngineScrollEdgeReachedSignalType = Signal< void( const ScrollEdge ) >; + using WebEngineScrollEdgeReachedSignalType = Signal; /** * @brief Enumeration for the scroll edge. @@ -97,7 +98,7 @@ public: * @param [in] argc The count of application arguments * @param [in] argv The string array of application arguments */ - virtual void Create( int width, int height, int argc, char** argv ) = 0; + virtual void Create(int width, int height, int argc, char** argv) = 0; /** * @brief Destroys WebEngine instance. @@ -187,12 +188,12 @@ public: /** * @brief Scrolls the webpage of view by deltaX and deltaY. */ - virtual void ScrollBy( int deltaX, int deltaY ) = 0; + virtual void ScrollBy(int deltaX, int deltaY) = 0; /** * @brief Scroll to the specified position of the given view. */ - virtual void SetScrollPosition( int x, int y ) = 0; + virtual void SetScrollPosition(int x, int y) = 0; /** * @brief Gets the current scroll position of the given view. @@ -291,7 +292,19 @@ public: /** * @brief Sets focus. */ - virtual void SetFocus( bool focused ) = 0; + virtual void SetFocus(bool focused) = 0; + + /** + * @brief Update display area. + * @param[in] displayArea The display area need be updated. + */ + virtual void UpdateDisplayArea(Dali::Rect displayArea) = 0; + + /** + * @brief Enable video hole. + * @param[in] enabled True if enabled, false othewise. + */ + virtual void EnableVideoHole(bool enabled) = 0; /** * @brief Connects to this signal to be notified when page loading is started. diff --git a/dali/devel-api/adaptor-framework/web-engine-settings.h b/dali/devel-api/adaptor-framework/web-engine-settings.h old mode 100755 new mode 100644 index 6da577e..d1d3cfc --- a/dali/devel-api/adaptor-framework/web-engine-settings.h +++ b/dali/devel-api/adaptor-framework/web-engine-settings.h @@ -22,15 +22,12 @@ namespace Dali { - /** * @brief A class WebEngineSettings for settings of web engine. */ class WebEngineSettings { - public: - /** * @brief Constructor. */ @@ -47,7 +44,7 @@ public: * @param[in] allowed if true, allow to run mixed contents, * otherwise not allow */ - virtual void AllowMixedContents( bool allowed ) = 0; + virtual void AllowMixedContents(bool allowed) = 0; /** * @brief Enable the spatial navigation or not. @@ -55,7 +52,7 @@ public: * @param[in] enabled if true, use spatial navigation, * otherwise to disable */ - virtual void EnableSpatialNavigation( bool enabled ) = 0; + virtual void EnableSpatialNavigation(bool enabled) = 0; /** * @brief Get the default font size. @@ -69,7 +66,7 @@ public: * * @param[in] size a new default font size to set */ - virtual void SetDefaultFontSize( uint32_t size ) = 0; + virtual void SetDefaultFontSize(uint32_t size) = 0; /** * @brief Enables/disables web security. @@ -77,7 +74,7 @@ public: * @param[in] enabled if true, to enable the web security * otherwise to disable */ - virtual void EnableWebSecurity( bool enabled ) = 0; + virtual void EnableWebSecurity(bool enabled) = 0; /** * @brief Allow/Disallow file access from external url @@ -85,7 +82,7 @@ public: * @param[in] allowed if true, to allow file access from external url * otherwise to disallow */ - virtual void AllowFileAccessFromExternalUrl( bool allowed ) = 0; + virtual void AllowFileAccessFromExternalUrl(bool allowed) = 0; /** * @brief Check if javascript is enabled or not. @@ -100,7 +97,7 @@ public: * @param[in] enabled if true, to enable javascript * otherwise to disable */ - virtual void EnableJavaScript( bool enabled ) = 0; + virtual void EnableJavaScript(bool enabled) = 0; /** * @brief Allow if the scripts can open new windows. @@ -108,7 +105,7 @@ public: * @param[in] allowed if true, the scripts can open new windows, * otherwise not */ - virtual void AllowScriptsOpenWindows( bool allowed ) = 0; + virtual void AllowScriptsOpenWindows(bool allowed) = 0; /** * @brief Check if images are loaded automatically or not. @@ -123,7 +120,7 @@ public: * @param[in] automatic if true, to load images automatically, * otherwise not */ - virtual void AllowImagesLoadAutomatically( bool automatic ) = 0; + virtual void AllowImagesLoadAutomatically(bool automatic) = 0; /** * @brief Get the default encoding name. @@ -137,8 +134,7 @@ public: * * @param[in] defaultTextEncodingName a default encoding name to set */ - virtual void SetDefaultTextEncodingName( const std::string& defaultTextEncodingName ) = 0; - + virtual void SetDefaultTextEncodingName(const std::string& defaultTextEncodingName) = 0; }; } // namespace Dali diff --git a/dali/devel-api/adaptor-framework/web-engine.cpp b/dali/devel-api/adaptor-framework/web-engine.cpp old mode 100755 new mode 100644 index e454f0d..e7701bd --- a/dali/devel-api/adaptor-framework/web-engine.cpp +++ b/dali/devel-api/adaptor-framework/web-engine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,9 +74,9 @@ void WebEngine::Create(int width, int height, const std::string& locale, const s GetImplementation(*this).Create(width, height, locale, timezoneId); } -void WebEngine::Create( int width, int height, int argc, char** argv ) +void WebEngine::Create(int width, int height, int argc, char** argv) { - GetImplementation( *this ).Create( width, height, argc, argv ); + GetImplementation(*this).Create(width, height, argc, argv); } void WebEngine::Destroy() @@ -91,22 +91,22 @@ NativeImageInterfacePtr WebEngine::GetNativeImageSource() Dali::WebEngineSettings& WebEngine::GetSettings() const { - return GetImplementation( *this ).GetSettings(); + return GetImplementation(*this).GetSettings(); } Dali::WebEngineContext& WebEngine::GetContext() const { - return GetImplementation( *this ).GetContext(); + return GetImplementation(*this).GetContext(); } Dali::WebEngineCookieManager& WebEngine::GetCookieManager() const { - return GetImplementation( *this ).GetCookieManager(); + return GetImplementation(*this).GetCookieManager(); } Dali::WebEngineBackForwardList& WebEngine::GetBackForwardList() const { - return GetImplementation( *this ).GetBackForwardList(); + return GetImplementation(*this).GetBackForwardList(); } void WebEngine::LoadUrl(const std::string& url) @@ -116,12 +116,12 @@ void WebEngine::LoadUrl(const std::string& url) std::string WebEngine::GetTitle() const { - return GetImplementation( *this ).GetTitle(); + return GetImplementation(*this).GetTitle(); } Dali::PixelData WebEngine::GetFavicon() const { - return GetImplementation( *this ).GetFavicon(); + return GetImplementation(*this).GetFavicon(); } const std::string& WebEngine::GetUrl() @@ -154,29 +154,29 @@ void WebEngine::Resume() GetImplementation(*this).Resume(); } -void WebEngine::ScrollBy( int deltaX, int deltaY ) +void WebEngine::ScrollBy(int deltaX, int deltaY) { - GetImplementation( *this ).ScrollBy( deltaX, deltaY ); + GetImplementation(*this).ScrollBy(deltaX, deltaY); } -void WebEngine::SetScrollPosition( int x, int y ) +void WebEngine::SetScrollPosition(int x, int y) { - GetImplementation( *this ).SetScrollPosition( x, y ); + GetImplementation(*this).SetScrollPosition(x, y); } Dali::Vector2 WebEngine::GetScrollPosition() const { - return GetImplementation( *this ).GetScrollPosition(); + return GetImplementation(*this).GetScrollPosition(); } Dali::Vector2 WebEngine::GetScrollSize() const { - return GetImplementation( *this ).GetScrollSize(); + return GetImplementation(*this).GetScrollSize(); } Dali::Vector2 WebEngine::GetContentSize() const { - return GetImplementation( *this ).GetContentSize(); + return GetImplementation(*this).GetContentSize(); } bool WebEngine::CanGoForward() @@ -211,7 +211,7 @@ void WebEngine::AddJavaScriptMessageHandler(const std::string& exposedObjectName void WebEngine::ClearAllTilesResources() { - GetImplementation( *this ).ClearAllTilesResources(); + GetImplementation(*this).ClearAllTilesResources(); } void WebEngine::ClearHistory() @@ -244,9 +244,19 @@ bool WebEngine::SendKeyEvent(const KeyEvent& event) return GetImplementation(*this).SendKeyEvent(event); } -void WebEngine::SetFocus( bool focused ) +void WebEngine::SetFocus(bool focused) { - GetImplementation( *this ).SetFocus( focused ); + GetImplementation(*this).SetFocus(focused); +} + +void WebEngine::UpdateDisplayArea(Dali::Rect displayArea) +{ + GetImplementation(*this).UpdateDisplayArea(displayArea); +} + +void WebEngine::EnableVideoHole(bool enabled) +{ + GetImplementation(*this).EnableVideoHole(enabled); } Dali::WebEnginePlugin::WebEnginePageLoadSignalType& WebEngine::PageLoadStartedSignal() @@ -266,7 +276,7 @@ Dali::WebEnginePlugin::WebEnginePageLoadErrorSignalType& WebEngine::PageLoadErro Dali::WebEnginePlugin::WebEngineScrollEdgeReachedSignalType& WebEngine::ScrollEdgeReachedSignal() { - return GetImplementation( *this ).ScrollEdgeReachedSignal(); + return GetImplementation(*this).ScrollEdgeReachedSignal(); } } // namespace Dali diff --git a/dali/devel-api/adaptor-framework/web-engine.h b/dali/devel-api/adaptor-framework/web-engine.h old mode 100755 new mode 100644 index 040a521..0a909b4 --- a/dali/devel-api/adaptor-framework/web-engine.h +++ b/dali/devel-api/adaptor-framework/web-engine.h @@ -2,7 +2,7 @@ #define DALI_WEB_ENGINE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,7 +104,7 @@ public: * @param [in] argc The count of application arguments * @param [in] argv The string array of application arguments */ - void Create( int width, int height, int argc, char** argv ); + void Create(int width, int height, int argc, char** argv); /** * @brief Destroys WebEngine instance. @@ -192,12 +192,12 @@ public: /** * @brief Scrolls the webpage of view by deltaX and deltaY. */ - void ScrollBy( int deltaX, int deltaY ); + void ScrollBy(int deltaX, int deltaY); /** * @brief Sets an absolute scroll of the given view. */ - void SetScrollPosition( int x, int y ); + void SetScrollPosition(int x, int y); /** * @brief Gets the current scroll position of the given view. @@ -295,8 +295,21 @@ public: /** * @brief Set focus. + * @param[in] focused True if web view is focused, false otherwise */ - void SetFocus( bool focused ); + void SetFocus(bool focused); + + /** + * @brief Update display area. + * @param[in] displayArea The area to display web page. + */ + void UpdateDisplayArea(Dali::Rect displayArea); + + /** + * @brief Enable video hole. + * @param[in] enabled True if video hole is enabled, false otherwise + */ + void EnableVideoHole(bool enabled); /** * @brief Connects to this signal to be notified when page loading is started. diff --git a/dali/devel-api/adaptor-framework/window-devel.cpp b/dali/devel-api/adaptor-framework/window-devel.cpp index e29e213..4cc29a8 100644 --- a/dali/devel-api/adaptor-framework/window-devel.cpp +++ b/dali/devel-api/adaptor-framework/window-devel.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,9 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include // INTERNAL INCLUDES #include diff --git a/dali/devel-api/adaptor-framework/window-devel.h b/dali/devel-api/adaptor-framework/window-devel.h index ea3577a..7895a23 100644 --- a/dali/devel-api/adaptor-framework/window-devel.h +++ b/dali/devel-api/adaptor-framework/window-devel.h @@ -2,7 +2,7 @@ #define DALI_WINDOW_DEVEL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ #include // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { @@ -35,7 +35,6 @@ class RenderTaskList; namespace DevelWindow { - typedef Signal EventProcessingFinishedSignalType; ///< Event Processing finished signal type typedef Signal KeyEventSignalType; ///< Key event signal type diff --git a/dali/devel-api/text-abstraction/script.cpp b/dali/devel-api/text-abstraction/script.cpp index 168109d..62dfaa9 100644 --- a/dali/devel-api/text-abstraction/script.cpp +++ b/dali/devel-api/text-abstraction/script.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +20,18 @@ namespace Dali { - namespace TextAbstraction { - namespace { -constexpr unsigned int WHITE_SPACE_THRESHOLD = 0x21; ///< All characters below 0x21 are considered white spaces. -constexpr unsigned int CHAR_LF = 0x000A; ///< NL Line feed, new line. -constexpr unsigned int CHAR_VT = 0x000B; ///< Vertical tab. -constexpr unsigned int CHAR_FF = 0x000C; ///< NP Form feed, new page. -constexpr unsigned int CHAR_CR = 0x000D; ///< Carriage return, new line. -constexpr unsigned int CHAR_NEL = 0x0085; ///< Next line. -constexpr unsigned int CHAR_LS = 0x2028; ///< Line separator. -constexpr unsigned int CHAR_PS = 0x2029; ///< Paragraph separator +constexpr unsigned int WHITE_SPACE_THRESHOLD = 0x21; ///< All characters below 0x21 are considered white spaces. +constexpr unsigned int CHAR_LF = 0x000A; ///< NL Line feed, new line. +constexpr unsigned int CHAR_VT = 0x000B; ///< Vertical tab. +constexpr unsigned int CHAR_FF = 0x000C; ///< NP Form feed, new page. +constexpr unsigned int CHAR_CR = 0x000D; ///< Carriage return, new line. +constexpr unsigned int CHAR_NEL = 0x0085; ///< Next line. +constexpr unsigned int CHAR_LS = 0x2028; ///< Line separator. +constexpr unsigned int CHAR_PS = 0x2029; ///< Paragraph separator constexpr unsigned int CHAR_ZWS = 0x200B; ///< Zero width space. constexpr unsigned int CHAR_ZWNJ = 0x200C; ///< Zero width non joiner. @@ -263,31 +261,30 @@ constexpr unsigned int CHAR_TS = 0x2009; ///< Thin Space. // 0x25aa // 0x262a - /// character <= 0x077f inline Script GetScriptTillArabicSupplement(Character character) { Script script = UNKNOWN; - if( ( 0x0030 <= character ) && ( character <= 0x0039 ) ) + if((0x0030 <= character) && (character <= 0x0039)) { script = ASCII_DIGITS; } - else if( character <= 0x007E ) + else if(character <= 0x007E) { - if( ( 0x0020 <= character ) && ( character <= 0x002F ) ) + if((0x0020 <= character) && (character <= 0x002F)) { script = ASCII_PS; } - else if( ( 0x003A <= character ) && ( character <= 0x0040 ) ) + else if((0x003A <= character) && (character <= 0x0040)) { script = ASCII_PS; } - else if( ( 0x005B <= character ) && ( character <= 0x0060 ) ) + else if((0x005B <= character) && (character <= 0x0060)) { script = ASCII_PS; } - else if( ( 0x007B <= character ) && ( character <= 0x007E ) ) + else if((0x007B <= character) && (character <= 0x007E)) { script = ASCII_PS; } @@ -296,19 +293,19 @@ inline Script GetScriptTillArabicSupplement(Character character) script = LATIN; } } - else if( ( 0x007F <= character ) && ( character <= 0x009F ) ) + else if((0x007F <= character) && (character <= 0x009F)) { // 0x007F is actually part of C0 Controls and Basic Latin. However, is the last and only control character of its block // and the following characters of the next block are consecutive. script = C1_CONTROLS; } - else if( ( 0x00A0 <= character ) && ( character <= 0x00BF ) ) + else if((0x00A0 <= character) && (character <= 0x00BF)) { - if( character == 0x00A9 ) + if(character == 0x00A9) { script = EMOJI; // 5. Uncategorized: copyright sign } - else if( character == 0x00AE ) + else if(character == 0x00AE) { script = EMOJI; // 5. Uncategorized: registered sign } @@ -317,17 +314,17 @@ inline Script GetScriptTillArabicSupplement(Character character) script = C1_PS; } } - else if( character == 0x00D7 ) + else if(character == 0x00D7) { script = C1_MATH; } - else if( character == 0x00F7 ) + else if(character == 0x00F7) { script = C1_MATH; } - else if( ( 0x00C0 <= character ) && ( character <= 0x02ff ) ) + else if((0x00C0 <= character) && (character <= 0x02ff)) { - if( ( 0x02B9 <= character ) && ( character <= 0x02BF ) ) + if((0x02B9 <= character) && (character <= 0x02BF)) { script = SML_P; } @@ -336,31 +333,31 @@ inline Script GetScriptTillArabicSupplement(Character character) script = LATIN; } } - else if( ( 0x0370 <= character ) && ( character <= 0x03ff ) ) + else if((0x0370 <= character) && (character <= 0x03ff)) { script = GREEK; } - else if( ( 0x0400 <= character ) && ( character <= 0x04ff ) ) + else if((0x0400 <= character) && (character <= 0x04ff)) { script = CYRILLIC; } - else if( ( 0x0500 <= character ) && ( character <= 0x052f ) ) + else if((0x0500 <= character) && (character <= 0x052f)) { script = CYRILLIC; } - else if( ( 0x0530 <= character ) && ( character <= 0x058f ) ) + else if((0x0530 <= character) && (character <= 0x058f)) { script = ARMENIAN; } - else if( ( 0x0591 <= character ) && ( character <= 0x05f4 ) ) + else if((0x0591 <= character) && (character <= 0x05f4)) { script = HEBREW; } - else if( ( 0x0600 <= character ) && ( character <= 0x06ff ) ) + else if((0x0600 <= character) && (character <= 0x06ff)) { script = ARABIC; } - else if( ( 0x0750 <= character ) && ( character <= 0x077f ) ) + else if((0x0750 <= character) && (character <= 0x077f)) { script = ARABIC; } @@ -373,21 +370,21 @@ inline Script GetScriptTillBengali(Character character) { Script script = UNKNOWN; - if( character <= 0x077f ) + if(character <= 0x077f) { script = GetScriptTillArabicSupplement(character); } else // > 0x077f { - if( ( 0x08A0 <= character ) && ( character <= 0x08ff ) ) + if((0x08A0 <= character) && (character <= 0x08ff)) { script = ARABIC; } - else if( ( 0x0900 <= character ) && ( character <= 0x097f ) ) + else if((0x0900 <= character) && (character <= 0x097f)) { script = DEVANAGARI; } - else if( ( 0x0980 <= character ) && ( character <= 0x09ff ) ) + else if((0x0980 <= character) && (character <= 0x09ff)) { script = BENGALI; } @@ -397,36 +394,36 @@ inline Script GetScriptTillBengali(Character character) } /// 0x09ff < character <= 0x0cff -inline Script GetScriptBetweenBengaliAndKannada( Character character ) +inline Script GetScriptBetweenBengaliAndKannada(Character character) { Script script = UNKNOWN; - if( character <= 0x0b7f ) + if(character <= 0x0b7f) { - if( ( 0x0a00 <= character ) && ( character <= 0x0a7f ) ) + if((0x0a00 <= character) && (character <= 0x0a7f)) { script = GURMUKHI; } - else if( ( 0x0a80 <= character ) && ( character <= 0x0aff ) ) + else if((0x0a80 <= character) && (character <= 0x0aff)) { script = GUJARATI; } - else if( ( 0x0b00 <= character ) && ( character <= 0x0b7f ) ) + else if((0x0b00 <= character) && (character <= 0x0b7f)) { script = ORIYA; } } else // > 0x0b7f { - if( ( 0x0b80 <= character ) && ( character <= 0x0bff ) ) + if((0x0b80 <= character) && (character <= 0x0bff)) { script = TAMIL; } - else if( ( 0x0c00 <= character ) && ( character <= 0x0c7f ) ) + else if((0x0c00 <= character) && (character <= 0x0c7f)) { script = TELUGU; } - else if( ( 0x0c80 <= character ) && ( character <= 0x0cff ) ) + else if((0x0c80 <= character) && (character <= 0x0cff)) { script = KANNADA; } @@ -440,85 +437,85 @@ inline Script GetScriptBetweenKannadaAndLatinExtendedAdditional(Character charac { Script script = UNKNOWN; - if( ( 0x0d00 <= character ) && ( character <= 0x0d7f ) ) + if((0x0d00 <= character) && (character <= 0x0d7f)) { script = MALAYALAM; } - else if( ( 0x0d80 <= character ) && ( character <= 0x0dff ) ) + else if((0x0d80 <= character) && (character <= 0x0dff)) { script = SINHALA; } - else if( ( 0x0e00 <= character ) && ( character <= 0x0e7f ) ) + else if((0x0e00 <= character) && (character <= 0x0e7f)) { script = THAI; } - else if( ( 0x0e80 <= character ) && ( character <= 0x0eff ) ) + else if((0x0e80 <= character) && (character <= 0x0eff)) { script = LAO; } - else if( ( 0x1000 <= character ) && ( character <= 0x109f ) ) + else if((0x1000 <= character) && (character <= 0x109f)) { script = BURMESE; } - else if( ( 0x10a0 <= character ) && ( character <= 0x10ff ) ) + else if((0x10a0 <= character) && (character <= 0x10ff)) { script = GEORGIAN; } - else if( ( 0x1100 <= character ) && ( character <= 0x11ff ) ) + else if((0x1100 <= character) && (character <= 0x11ff)) { script = HANGUL; } - else if( ( 0x1200 <= character ) && ( character <= 0x137f ) ) + else if((0x1200 <= character) && (character <= 0x137f)) { script = GEEZ; } - else if( ( 0x1380 <= character ) && ( character <= 0x139f ) ) + else if((0x1380 <= character) && (character <= 0x139f)) { script = GEEZ; } - else if( ( 0x1700 <= character ) && ( character <= 0x171f ) ) + else if((0x1700 <= character) && (character <= 0x171f)) { script = BAYBAYIN; } - else if( ( 0x1780 <= character ) && ( character <= 0x17ff ) ) + else if((0x1780 <= character) && (character <= 0x17ff)) { script = KHMER; } - else if( ( 0x19e0 <= character ) && ( character <= 0x19ff ) ) + else if((0x19e0 <= character) && (character <= 0x19ff)) { script = KHMER; } - else if( ( 0x1b80 <= character ) && ( character <= 0x1bbf ) ) + else if((0x1b80 <= character) && (character <= 0x1bbf)) { script = SUNDANESE; } - else if( ( 0x1c50 <= character ) && ( character <= 0x1c7f ) ) + else if((0x1c50 <= character) && (character <= 0x1c7f)) { script = OL_CHIKI; } - else if( ( 0x1cc0 <= character ) && ( character <= 0x1ccf ) ) + else if((0x1cc0 <= character) && (character <= 0x1ccf)) { script = SUNDANESE; } - else if( ( 0x1d00 <= character ) && ( character <= 0x1eff ) ) + else if((0x1d00 <= character) && (character <= 0x1eff)) { - if( ( 0x1D26 <= character ) && ( character <= 0x1D2B ) ) + if((0x1D26 <= character) && (character <= 0x1D2B)) { script = PHONETIC_U; } - else if( ( 0x1D5D <= character ) && ( character <= 0x1D61 ) ) + else if((0x1D5D <= character) && (character <= 0x1D61)) { script = PHONETIC_SS; } - else if( ( 0x1D66 <= character ) && ( character <= 0x1D6A ) ) + else if((0x1D66 <= character) && (character <= 0x1D6A)) { script = PHONETIC_SS; } - else if( character == 0x1D78 ) + else if(character == 0x1D78) { script = PHONETIC_SS; } - else if( character == 0x1DBF) + else if(character == 0x1DBF) { script = PHONETIC_SS; } @@ -536,25 +533,25 @@ inline Script GetScriptBetweenLatinExtendedAdditionalAndLatinExtendedC(Character { Script script = UNKNOWN; - if( ( 0x1f00 <= character ) && ( character <= 0x1fff ) ) + if((0x1f00 <= character) && (character <= 0x1fff)) { script = GREEK; } - else if( character == 0x203c ) + else if(character == 0x203c) { script = EMOJI; // 5. Uncategorized: double exclamation mark } - else if( character == 0x2049 ) + else if(character == 0x2049) { script = EMOJI; // 5. Uncategorized: exclamation question mark } - else if( ( 0x2070 <= character ) && ( character <= 0x209f ) ) + else if((0x2070 <= character) && (character <= 0x209f)) { - if( character == 0x2070 ) + if(character == 0x2070) { script = NUMERIC_SS; } - else if( ( 0x2074 <= character ) && ( character <= 0x207E ) ) + else if((0x2074 <= character) && (character <= 0x207E)) { script = NUMERIC_SS; } @@ -563,31 +560,31 @@ inline Script GetScriptBetweenLatinExtendedAdditionalAndLatinExtendedC(Character script = LATIN; } } - else if( character == 0x20e3 ) + else if(character == 0x20e3) { script = EMOJI; // 5. Uncategorized: combining enclosing keycap } - else if( character == 0x2122 ) + else if(character == 0x2122) { script = EMOJI; // 5. Uncategorized: trade mark sign } - else if( character == 0x2139 ) + else if(character == 0x2139) { script = EMOJI; // 5. Uncategorized: information source } - else if( ( 0x2100 <= character ) && ( character <= 0x2189 ) ) + else if((0x2100 <= character) && (character <= 0x2189)) { - if( ( 0x2100 <= character ) && ( character <= 0x214f ) ) + if((0x2100 <= character) && (character <= 0x214f)) { - if( ( 0x212A <= character ) && ( character <= 0x212B ) ) + if((0x212A <= character) && (character <= 0x212B)) { script = LATIN; } - else if( character == 0x2132 ) + else if(character == 0x2132) { script = LATIN; } - else if( character == 0x214E ) + else if(character == 0x214E) { script = LATIN; } @@ -596,11 +593,11 @@ inline Script GetScriptBetweenLatinExtendedAdditionalAndLatinExtendedC(Character script = LETTER_LIKE; } } - else if( ( 0x2150 <= character ) && ( character <= 0x215F ) ) + else if((0x2150 <= character) && (character <= 0x215F)) { script = FRACTIONS_NF; } - else if( character == 0x2189 ) + else if(character == 0x2189) { script = FRACTIONS_NF; } @@ -610,39 +607,39 @@ inline Script GetScriptBetweenLatinExtendedAdditionalAndLatinExtendedC(Character } } // Symbols - else if( ( 0x25cb == character ) || - ( 0x25cf == character ) || - ( 0x25a1 == character ) ) + else if((0x25cb == character) || + (0x25cf == character) || + (0x25a1 == character)) { script = SYMBOLS1; } - else if( 0x25a0 == character ) + else if(0x25a0 == character) { script = SYMBOLS2; } - else if( ( 0x2664 == character ) || - ( 0x2661 == character ) || - ( 0x2662 == character ) || - ( 0x2667 == character ) ) + else if((0x2664 == character) || + (0x2661 == character) || + (0x2662 == character) || + (0x2667 == character)) { script = SYMBOLS3; } - else if( ( 0x2606 == character ) || - ( 0x25aa == character ) ) + else if((0x2606 == character) || + (0x25aa == character)) { script = SYMBOLS4; } - else if( 0x262a == character ) + else if(0x262a == character) { script = SYMBOLS5; } // U+2194 5. Uncategorized: left right arrow // U+2B55 5. Uncategorized: heavy large circle - else if( ( 0x2194 <= character ) && ( character <= 0x2B55 ) ) + else if((0x2194 <= character) && (character <= 0x2B55)) { script = EMOJI; } - else if( ( 0x2c60 <= character ) && ( character <= 0x2c7f ) ) + else if((0x2c60 <= character) && (character <= 0x2c7f)) { script = LATIN; } @@ -655,7 +652,7 @@ inline Script GetScriptBetweenKannadaAndLatinExtendedC(Character character) { Script script = UNKNOWN; - if( character <= 0x1eff ) + if(character <= 0x1eff) { script = GetScriptBetweenKannadaAndLatinExtendedAdditional(character); } @@ -672,97 +669,97 @@ inline Script GetScriptBetweenLatinExtendedCAndLatinExtendedD(Character characte { Script script = UNKNOWN; - if( ( 0x2d00 <= character ) && ( character <= 0x2d2f ) ) + if((0x2d00 <= character) && (character <= 0x2d2f)) { script = GEORGIAN; } - else if( ( 0x2d80 <= character ) && ( character <= 0x2ddf ) ) + else if((0x2d80 <= character) && (character <= 0x2ddf)) { script = GEEZ; } - else if( ( 0x2de0 <= character ) && ( character <= 0x2dff ) ) + else if((0x2de0 <= character) && (character <= 0x2dff)) { script = CYRILLIC; } - else if( ( 0x2e80 <= character ) && ( character <= 0x2eff ) ) + else if((0x2e80 <= character) && (character <= 0x2eff)) { script = CJK; } - else if( ( 0x2f00 <= character ) && ( character <= 0x2fdf ) ) + else if((0x2f00 <= character) && (character <= 0x2fdf)) { script = CJK; } - else if( ( 0x3000 <= character ) && ( character <= 0x303f ) ) + else if((0x3000 <= character) && (character <= 0x303f)) { script = CJK; } - else if( ( 0x3040 <= character ) && ( character <= 0x309f ) ) + else if((0x3040 <= character) && (character <= 0x309f)) { script = HIRAGANA; } - else if( ( 0x30a0 <= character ) && ( character <= 0x30ff ) ) + else if((0x30a0 <= character) && (character <= 0x30ff)) { script = KATAKANA; } - else if( ( 0x3100 <= character ) && ( character <= 0x312f ) ) + else if((0x3100 <= character) && (character <= 0x312f)) { script = BOPOMOFO; } - else if( ( 0x3130 <= character ) && ( character <= 0x318f ) ) + else if((0x3130 <= character) && (character <= 0x318f)) { script = HANGUL; } - else if( ( 0x31a0 <= character ) && ( character <= 0x31bf ) ) + else if((0x31a0 <= character) && (character <= 0x31bf)) { script = BOPOMOFO; } - else if( ( 0x3200 <= character ) && ( character <= 0x32ff ) ) + else if((0x3200 <= character) && (character <= 0x32ff)) { script = CJK; } - else if( ( 0x3400 <= character ) && ( character <= 0x4dbf ) ) + else if((0x3400 <= character) && (character <= 0x4dbf)) { script = CJK; } - else if( ( 0x4e00 <= character ) && ( character <= 0x62ff ) ) + else if((0x4e00 <= character) && (character <= 0x62ff)) { script = CJK; } - else if( ( 0x6300 <= character ) && ( character <= 0x77ff ) ) + else if((0x6300 <= character) && (character <= 0x77ff)) { script = CJK; } - else if( ( 0x7800 <= character ) && ( character <= 0x8cff ) ) + else if((0x7800 <= character) && (character <= 0x8cff)) { script = CJK; } - else if( ( 0x8d00 <= character ) && ( character <= 0x9fff ) ) + else if((0x8d00 <= character) && (character <= 0x9fff)) { script = CJK; } - else if( ( 0xa640 <= character ) && ( character <= 0xa69f ) ) + else if((0xa640 <= character) && (character <= 0xa69f)) { script = CYRILLIC; } - else if( ( 0xa720 <= character ) && ( character <= 0xa7ff ) ) + else if((0xa720 <= character) && (character <= 0xa7ff)) { - if( character == 0xA720 ) + if(character == 0xA720) { script = PHONETIC_U; } - else if( character == 0xA721 ) + else if(character == 0xA721) { script = PHONETIC_U; } - else if( character == 0xA788 ) + else if(character == 0xA788) { script = NON_LATIN_LED; } - else if( character == 0xA789 ) + else if(character == 0xA789) { script = NON_LATIN_LED; } - else if( character == 0xA78A ) + else if(character == 0xA78A) { script = NON_LATIN_LED; } @@ -780,51 +777,51 @@ inline Script GetScriptBetweenLatinExtendedCAndArabicPresentationFormsA(Characte { Script script = GetScriptBetweenLatinExtendedCAndLatinExtendedD(character); - if( ( 0xa960 <= character ) && ( character <= 0xa97f ) ) + if((0xa960 <= character) && (character <= 0xa97f)) { script = HANGUL; } - else if( ( 0xa980 <= character ) && ( character <= 0xa9fd ) ) + else if((0xa980 <= character) && (character <= 0xa9fd)) { script = JAVANESE; } - else if( ( 0xab00 <= character ) && ( character <= 0xab2f ) ) + else if((0xab00 <= character) && (character <= 0xab2f)) { script = GEEZ; } - else if( ( 0xab30 <= character ) && ( character <= 0xab6f ) ) + else if((0xab30 <= character) && (character <= 0xab6f)) { script = LATIN; } - else if( ( 0xaae0 <= character ) && ( character <= 0xaaff ) ) + else if((0xaae0 <= character) && (character <= 0xaaff)) { script = MEITEI; } - else if( ( 0xabc0 <= character ) && ( character <= 0xabff ) ) + else if((0xabc0 <= character) && (character <= 0xabff)) { script = MEITEI; } - else if( ( 0xac00 <= character ) && ( character <= 0xd7af ) ) + else if((0xac00 <= character) && (character <= 0xd7af)) { script = HANGUL; } - else if( ( 0xd7b0 <= character ) && ( character <= 0xd7ff ) ) + else if((0xd7b0 <= character) && (character <= 0xd7ff)) { script = HANGUL; } - else if( ( 0xfb00 <= character ) && ( character <= 0xfb06 ) ) + else if((0xfb00 <= character) && (character <= 0xfb06)) { script = LATIN; } - else if( ( 0xfb13 <= character ) && ( character <= 0xfb17 ) ) + else if((0xfb13 <= character) && (character <= 0xfb17)) { script = ARMENIAN; } - else if( ( 0xfb1d <= character ) && ( character <= 0xfb4f ) ) + else if((0xfb1d <= character) && (character <= 0xfb4f)) { script = HEBREW; } - else if( ( 0xfb50 <= character ) && ( character <= 0xfdff ) ) + else if((0xfb50 <= character) && (character <= 0xfdff)) { script = ARABIC; } @@ -837,21 +834,21 @@ inline Script GetScriptAboveArabicPresentationFormsA(Character character) { Script script = UNKNOWN; - if( ( 0xfe70 <= character ) && ( character <= 0xfeff ) ) + if((0xfe70 <= character) && (character <= 0xfeff)) { script = ARABIC; } - else if( ( 0xff00 <= character ) && ( character <= 0xffef ) ) + else if((0xff00 <= character) && (character <= 0xffef)) { - if( ( 0xFF00 <= character ) && ( character <= 0xFF20 ) ) + if((0xFF00 <= character) && (character <= 0xFF20)) { script = HWFW_S; } - else if( ( 0xFF3B <= character ) && ( character <= 0xFF40 ) ) + else if((0xFF3B <= character) && (character <= 0xFF40)) { script = HWFW_S; } - else if( ( 0xFF5B <= character ) && ( character <= 0xFFEF ) ) + else if((0xFF5B <= character) && (character <= 0xFFEF)) { script = HWFW_S; } @@ -860,54 +857,54 @@ inline Script GetScriptAboveArabicPresentationFormsA(Character character) script = LATIN; } } - else if( ( 0x1ee00 <= character ) && ( character <= 0x1eeff ) ) + else if((0x1ee00 <= character) && (character <= 0x1eeff)) { script = ARABIC; } // U+1f170 4. Enclosed characters: negative squared latin capital letter A // U+1f6ff 6b. Additional transport and map symbols - else if( ( 0x1f170 <= character ) && ( character <= 0x1f6ff ) ) + else if((0x1f170 <= character) && (character <= 0x1f6ff)) { script = EMOJI; } // 7. Supplemental Symbols and Pictographs - else if( ( 0x1f900 <= character ) && ( character <= 0x1f9ff ) ) + else if((0x1f900 <= character) && (character <= 0x1f9ff)) { script = EMOJI; } - else if( ( 0x20000 <= character ) && ( character <= 0x215ff ) ) + else if((0x20000 <= character) && (character <= 0x215ff)) { script = CJK; } - else if( ( 0x21600 <= character ) && ( character <= 0x230ff ) ) + else if((0x21600 <= character) && (character <= 0x230ff)) { script = CJK; } - else if( ( 0x23100 <= character ) && ( character <= 0x245ff ) ) + else if((0x23100 <= character) && (character <= 0x245ff)) { script = CJK; } - else if( ( 0x24600 <= character ) && ( character <= 0x260ff ) ) + else if((0x24600 <= character) && (character <= 0x260ff)) { script = CJK; } - else if( ( 0x26100 <= character ) && ( character <= 0x275ff ) ) + else if((0x26100 <= character) && (character <= 0x275ff)) { script = CJK; } - else if( ( 0x27600 <= character ) && ( character <= 0x290ff ) ) + else if((0x27600 <= character) && (character <= 0x290ff)) { script = CJK; } - else if( ( 0x29100 <= character ) && ( character <= 0x2a6df ) ) + else if((0x29100 <= character) && (character <= 0x2a6df)) { script = CJK; } - else if( ( 0x2a700 <= character ) && ( character <= 0x2b73f ) ) + else if((0x2a700 <= character) && (character <= 0x2b73f)) { script = CJK; } - else if( ( 0x2b740 <= character ) && ( character <= 0x2b81f ) ) + else if((0x2b740 <= character) && (character <= 0x2b81f)) { script = CJK; } @@ -920,7 +917,7 @@ inline Script GetScriptAboveLatinExtendedC(Character character) { Script script = UNKNOWN; - if( character <= 0xfdff ) + if(character <= 0xfdff) { script = GetScriptBetweenLatinExtendedCAndArabicPresentationFormsA(character); } @@ -934,23 +931,23 @@ inline Script GetScriptAboveLatinExtendedC(Character character) } // namespace -bool IsRightToLeftScript( Script script ) +bool IsRightToLeftScript(Script script) { - return ( ( ARABIC == script ) || - ( HEBREW == script ) ); + return ((ARABIC == script) || + (HEBREW == script)); } -Script GetCharacterScript( Character character ) +Script GetCharacterScript(Character character) { Script script = UNKNOWN; - if( IsCommonScript( character ) ) + if(IsCommonScript(character)) { script = COMMON; } - else if( character <= 0x0cff ) + else if(character <= 0x0cff) { - if( character <= 0x09ff ) + if(character <= 0x09ff) { script = GetScriptTillBengali(character); } @@ -961,9 +958,9 @@ Script GetCharacterScript( Character character ) } else // > 0x0cff { - if( character <= 0x2c7f ) + if(character <= 0x2c7f) { - script = GetScriptBetweenKannadaAndLatinExtendedC(character); + script = GetScriptBetweenKannadaAndLatinExtendedC(character); } else // > 0x2c7f { diff --git a/dali/integration-api/adaptor-framework/scene-holder-impl.cpp b/dali/integration-api/adaptor-framework/scene-holder-impl.cpp index 2fb9af9..ec4be19 100644 --- a/dali/integration-api/adaptor-framework/scene-holder-impl.cpp +++ b/dali/integration-api/adaptor-framework/scene-holder-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -205,7 +205,7 @@ void SceneHolder::SetAdaptor(Dali::Adaptor& adaptor) // Create the scene PositionSize surfacePositionSize = mSurface->GetPositionSize(); - int orientation = mSurface->GetOrientation(); + int orientation = mSurface->GetOrientation(); mScene = Dali::Integration::Scene::New(Size(static_cast(surfacePositionSize.width), static_cast(surfacePositionSize.height)), orientation); Internal::Adaptor::Adaptor& adaptorImpl = Internal::Adaptor::Adaptor::GetImplementation(adaptor); diff --git a/dali/internal/accessibility/bridge/accessibility-common.h b/dali/internal/accessibility/bridge/accessibility-common.h index 7b5e5c8..cdb92e1 100644 --- a/dali/internal/accessibility/bridge/accessibility-common.h +++ b/dali/internal/accessibility/bridge/accessibility-common.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ATSPI_ACCESSIBILITY_COMMON_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,10 @@ #include // INTERNAL INCLUDES -#include #include -#include #include +#include +#include #define A11yDbusName "org.a11y.Bus" #define A11yDbusPath "/org/a11y/bus" @@ -100,7 +100,6 @@ enum class SortOrder : uint32_t namespace DBus { - class CurrentBridgePtr { static Dali::Accessibility::Bridge*& get() @@ -109,14 +108,14 @@ class CurrentBridgePtr return b; } Dali::Accessibility::Bridge* prev; - CurrentBridgePtr( const CurrentBridgePtr& ) = delete; - CurrentBridgePtr( CurrentBridgePtr&& ) = delete; - CurrentBridgePtr& operator=( const CurrentBridgePtr& ) = delete; - CurrentBridgePtr& operator=( CurrentBridgePtr&& ) = delete; + CurrentBridgePtr(const CurrentBridgePtr&) = delete; + CurrentBridgePtr(CurrentBridgePtr&&) = delete; + CurrentBridgePtr& operator=(const CurrentBridgePtr&) = delete; + CurrentBridgePtr& operator=(CurrentBridgePtr&&) = delete; public: - CurrentBridgePtr( Dali::Accessibility::Bridge* b ) - : prev( get() ) + CurrentBridgePtr(Dali::Accessibility::Bridge* b) + : prev(get()) { get() = b; } @@ -134,178 +133,179 @@ public: namespace detail { - -template < typename T > +template struct signature_accessible_impl : signature_helper> { - using subtype = std::pair< std::string, ObjectPath >; + using subtype = std::pair; static constexpr auto name_v = concat("AtspiAccessiblePtr"); - static constexpr auto sig_v = concat("(so)"); + static constexpr auto sig_v = concat("(so)"); /** * @brief Marshals value v as marshalled type into message */ - static void set( const DBusWrapper::MessageIterPtr& iter, T* t ) + static void set(const DBusWrapper::MessageIterPtr& iter, T* t) { - if( t ) + if(t) { auto v = t->GetAddress(); - signature< subtype >::set( iter, { v.GetBus(), ObjectPath{std::string{ ATSPI_PREFIX_PATH } +v.GetPath()} } ); + signature::set(iter, {v.GetBus(), ObjectPath{std::string{ATSPI_PREFIX_PATH} + v.GetPath()}}); } else { - signature< subtype >::set( iter, { "", ObjectPath{ ATSPI_NULL_PATH } } ); + signature::set(iter, {"", ObjectPath{ATSPI_NULL_PATH}}); } } /** * @brief Marshals value from marshalled type into variable v */ - static bool get( const DBusWrapper::MessageIterPtr& iter, T*& v ) + static bool get(const DBusWrapper::MessageIterPtr& iter, T*& v) { subtype tmp; - if( !signature< subtype >::get( iter, tmp ) ) + if(!signature::get(iter, tmp)) { return false; } - if( tmp.second.value == ATSPI_NULL_PATH ) + if(tmp.second.value == ATSPI_NULL_PATH) { v = nullptr; return true; } - if( tmp.second.value.substr( 0, strlen( ATSPI_PREFIX_PATH ) ) != ATSPI_PREFIX_PATH ) + if(tmp.second.value.substr(0, strlen(ATSPI_PREFIX_PATH)) != ATSPI_PREFIX_PATH) { return false; } auto b = CurrentBridgePtr::current(); - if( b->GetBusName() != tmp.first ) + if(b->GetBusName() != tmp.first) { return false; } - v = b->FindByPath( tmp.second.value.substr( strlen( ATSPI_PREFIX_PATH ) ) ); + v = b->FindByPath(tmp.second.value.substr(strlen(ATSPI_PREFIX_PATH))); return v != nullptr; } }; -template <> -struct signature< Dali::Accessibility::Accessible* > : public signature_accessible_impl< Dali::Accessibility::Accessible > +template<> +struct signature : public signature_accessible_impl { }; -template <> -struct signature< Dali::Accessibility::Address > : signature_helper> +template<> +struct signature : signature_helper> { - using subtype = std::pair< std::string, ObjectPath >; + using subtype = std::pair; static constexpr auto name_v = concat("AtspiAccessiblePtr"); - static constexpr auto sig_v = concat("(so)"); + static constexpr auto sig_v = concat("(so)"); /** * @brief Marshals value v as marshalled type into message */ - static void set( const DBusWrapper::MessageIterPtr& iter, const Dali::Accessibility::Address& v ) + static void set(const DBusWrapper::MessageIterPtr& iter, const Dali::Accessibility::Address& v) { - if( v ) + if(v) { - signature< subtype >::set( iter, { v.GetBus(), ObjectPath{ std::string{ ATSPI_PREFIX_PATH } + v.GetPath() } } ); + signature::set(iter, {v.GetBus(), ObjectPath{std::string{ATSPI_PREFIX_PATH} + v.GetPath()}}); } else { - signature< subtype >::set( iter, { v.GetBus(), ObjectPath{ ATSPI_NULL_PATH } } ); + signature::set(iter, {v.GetBus(), ObjectPath{ATSPI_NULL_PATH}}); } } /** * @brief Marshals value from marshalled type into variable v */ - static bool get( const DBusWrapper::MessageIterPtr& iter, Dali::Accessibility::Address& v ) + static bool get(const DBusWrapper::MessageIterPtr& iter, Dali::Accessibility::Address& v) { subtype tmp; - if( !signature< subtype >::get( iter, tmp ) ) + if(!signature::get(iter, tmp)) { return false; } - if( tmp.second.value == ATSPI_NULL_PATH ) + if(tmp.second.value == ATSPI_NULL_PATH) { v = {}; return true; } - if( tmp.second.value.substr( 0, strlen( ATSPI_PREFIX_PATH ) ) != ATSPI_PREFIX_PATH ) + if(tmp.second.value.substr(0, strlen(ATSPI_PREFIX_PATH)) != ATSPI_PREFIX_PATH) { return false; } - v = { std::move( tmp.first ), tmp.second.value.substr( strlen( ATSPI_PREFIX_PATH ) ) }; - return true; + v = {std::move(tmp.first), tmp.second.value.substr(strlen(ATSPI_PREFIX_PATH))}; + return true; } }; -template <> -struct signature< Dali::Accessibility::States > : signature_helper> +template<> +struct signature : signature_helper> { using subtype = std::array; static constexpr auto name_v = signature::name_v; - static constexpr auto sig_v = signature::sig_v; + static constexpr auto sig_v = signature::sig_v; /** * @brief Marshals value v as marshalled type into message */ - static void set( const DBusWrapper::MessageIterPtr& iter, const Dali::Accessibility::States& v ) + static void set(const DBusWrapper::MessageIterPtr& iter, const Dali::Accessibility::States& v) { - signature< subtype >::set( iter, v.GetRawData() ); + signature::set(iter, v.GetRawData()); } /** * @brief Marshals value from marshalled type into variable v */ - static bool get( const DBusWrapper::MessageIterPtr& iter, Dali::Accessibility::States& v ) + static bool get(const DBusWrapper::MessageIterPtr& iter, Dali::Accessibility::States& v) { subtype tmp; - if( !signature< subtype >::get( iter, tmp ) ) + if(!signature::get(iter, tmp)) { return false; } - v = Dali::Accessibility::States{ tmp }; + v = Dali::Accessibility::States{tmp}; return true; } }; -} -} +} // namespace detail +} // namespace DBus struct _Logger { - const char* file; - int line; + const char* file; + int line; std::ostringstream tmp; - _Logger( const char* f, int l ) - : file( f ), - line( l ){} + _Logger(const char* f, int l) + : file(f), + line(l) + { + } ~_Logger() { - Dali::Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%s:%d: %s", file, line, tmp.str().c_str() ); + Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d: %s", file, line, tmp.str().c_str()); } - template < typename T > - _Logger& operator<<( T&& t ) + template + _Logger& operator<<(T&& t) { - tmp << std::forward< T >( t ); + tmp << std::forward(t); return *this; } }; struct _LoggerEmpty { - template < typename T > - _LoggerEmpty& operator<<( T&& t ) + template + _LoggerEmpty& operator<<(T&& t) { return *this; } @@ -314,22 +314,22 @@ struct _LoggerEmpty struct _LoggerScope { const char* file; - int line; + int line; - _LoggerScope( const char* f, int l ) - : file( f ), - line( l ) + _LoggerScope(const char* f, int l) + : file(f), + line(l) { - Dali::Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%s:%d: +", file, line ); + Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d: +", file, line); } ~_LoggerScope() { - Dali::Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%s:%d: -", file, line ); + Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d: -", file, line); } }; -#define LOG() _Logger( __FILE__, __LINE__ ) -#define SCOPE() _LoggerScope _l##__LINE__( __FILE__, __LINE__ ) +#define LOG() _Logger(__FILE__, __LINE__) +#define SCOPE() _LoggerScope _l##__LINE__(__FILE__, __LINE__) #endif // DALI_INTERNAL_ATSPI_ACCESSIBILITY_COMMON_H diff --git a/dali/internal/accessibility/bridge/accessible.cpp b/dali/internal/accessibility/bridge/accessible.cpp index f23e33f..3a30b4b 100644 --- a/dali/internal/accessibility/bridge/accessible.cpp +++ b/dali/internal/accessibility/bridge/accessible.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,47 +15,47 @@ * */ - // CLASS HEADER +// CLASS HEADER - //INTERNAL INCLUDES +//INTERNAL INCLUDES #include -#include #include +#include using namespace Dali::Accessibility; -std::vector< std::string > Accessible::GetInterfaces() -{ - std::vector< std::string > tmp; - tmp.push_back(AtspiDbusInterfaceAccessible); - if (dynamic_cast(this)) - { - tmp.push_back(AtspiDbusInterfaceCollection); - } - if (dynamic_cast(this)) - { - tmp.push_back(AtspiDbusInterfaceText); - } - if (dynamic_cast(this)) - { - tmp.push_back(AtspiDbusInterfaceEditableText); - } - if (dynamic_cast(this)) - { - tmp.push_back(AtspiDbusInterfaceValue); - } - if (dynamic_cast(this)) - { - tmp.push_back(AtspiDbusInterfaceComponent); - } - if (auto d = dynamic_cast(this)) - { - if (d->GetActionCount() > 0) - { - tmp.push_back(AtspiDbusInterfaceAction); - } - } - return tmp; +std::vector Accessible::GetInterfaces() +{ + std::vector tmp; + tmp.push_back(AtspiDbusInterfaceAccessible); + if(dynamic_cast(this)) + { + tmp.push_back(AtspiDbusInterfaceCollection); + } + if(dynamic_cast(this)) + { + tmp.push_back(AtspiDbusInterfaceText); + } + if(dynamic_cast(this)) + { + tmp.push_back(AtspiDbusInterfaceEditableText); + } + if(dynamic_cast(this)) + { + tmp.push_back(AtspiDbusInterfaceValue); + } + if(dynamic_cast(this)) + { + tmp.push_back(AtspiDbusInterfaceComponent); + } + if(auto d = dynamic_cast(this)) + { + if(d->GetActionCount() > 0) + { + tmp.push_back(AtspiDbusInterfaceAction); + } + } + return tmp; } Accessible::Accessible() @@ -64,180 +64,184 @@ Accessible::Accessible() Accessible::~Accessible() { - auto b = bridgeData.lock(); - if (b) - b->knownObjects.erase(this); + auto b = bridgeData.lock(); + if(b) + b->knownObjects.erase(this); } void Accessible::EmitActiveDescendantChanged(Accessible* obj, Accessible* child) { - if (auto b = GetBridgeData()) - { - b->bridge->EmitActiveDescendantChanged(obj, child); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitActiveDescendantChanged(obj, child); + } } void Accessible::EmitStateChanged(State state, int newValue1, int newValue2) { - if (auto b = GetBridgeData()) - { - b->bridge->EmitStateChanged(this, state, newValue1, newValue2); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitStateChanged(this, state, newValue1, newValue2); + } } void Accessible::EmitShowing(bool showing) { - if (auto b = GetBridgeData()) - { - b->bridge->EmitStateChanged(this, State::SHOWING, showing ? 1 : 0, 0); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitStateChanged(this, State::SHOWING, showing ? 1 : 0, 0); + } } void Accessible::EmitVisible(bool visible) { - if (auto b = GetBridgeData()) - { - b->bridge->EmitStateChanged(this, State::VISIBLE, visible ? 1 : 0, 0); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitStateChanged(this, State::VISIBLE, visible ? 1 : 0, 0); + } } void Accessible::EmitHighlighted(bool set) { - if (auto b = GetBridgeData()) - { - b->bridge->EmitStateChanged(this, State::HIGHLIGHTED, set ? 1 : 0, 0); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitStateChanged(this, State::HIGHLIGHTED, set ? 1 : 0, 0); + } } void Accessible::EmitFocused(bool set) { - if (auto b = GetBridgeData()) { - b->bridge->EmitStateChanged(this, State::FOCUSED, set ? 1 : 0, 0); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitStateChanged(this, State::FOCUSED, set ? 1 : 0, 0); + } } void Accessible::EmitTextInserted(unsigned int position, unsigned int length, const std::string& content) { - if (auto b = GetBridgeData()) { - b->bridge->EmitTextChanged(this, TextChangedState::INSERTED, position, length, content); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitTextChanged(this, TextChangedState::INSERTED, position, length, content); + } } void Accessible::EmitTextDeleted(unsigned int position, unsigned int length, const std::string& content) { - if (auto b = GetBridgeData()) { - b->bridge->EmitTextChanged(this, TextChangedState::DELETED, position, length, content); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitTextChanged(this, TextChangedState::DELETED, position, length, content); + } } void Accessible::EmitTextCaretMoved(unsigned int cursorPosition) { - if (auto b = GetBridgeData()) { - b->bridge->EmitCaretMoved(this, cursorPosition); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitCaretMoved(this, cursorPosition); + } } void Accessible::Emit(WindowEvent we, unsigned int detail1) { - if (auto b = GetBridgeData()) - { - b->bridge->Emit(this, we, detail1); - } + if(auto b = GetBridgeData()) + { + b->bridge->Emit(this, we, detail1); + } } void Accessible::Emit(ObjectPropertyChangeEvent ev) { - if (auto b = GetBridgeData()) - { - b->bridge->Emit(this, ev); - } + if(auto b = GetBridgeData()) + { + b->bridge->Emit(this, ev); + } } void Accessible::EmitBoundsChanged(Rect<> rect) { - if (auto b = GetBridgeData()) - { - b->bridge->EmitBoundsChanged(this, rect); - } + if(auto b = GetBridgeData()) + { + b->bridge->EmitBoundsChanged(this, rect); + } } -std::vector< Accessible* > Accessible::GetChildren() +std::vector Accessible::GetChildren() { - std::vector< Accessible* > tmp(GetChildCount()); - for (auto i = 0u; i < tmp.size(); ++i) - { - tmp[i] = GetChildAtIndex(i); - } - return tmp; + std::vector tmp(GetChildCount()); + for(auto i = 0u; i < tmp.size(); ++i) + { + tmp[i] = GetChildAtIndex(i); + } + return tmp; } -std::shared_ptr< Bridge::Data > Accessible::GetBridgeData() +std::shared_ptr Accessible::GetBridgeData() { - auto b = bridgeData.lock(); - if (!b) - { - auto p = Bridge::GetCurrentBridge(); - b = p->data; - } - return b; + auto b = bridgeData.lock(); + if(!b) + { + auto p = Bridge::GetCurrentBridge(); + b = p->data; + } + return b; } Address Accessible::GetAddress() { - auto b = bridgeData.lock(); - if (!b) - { - b = GetBridgeData(); - if (b) - b->bridge->RegisterOnBridge(this); - } - std::ostringstream tmp; - tmp << this; - return { b ? b->busName : "", tmp.str() }; + auto b = bridgeData.lock(); + if(!b) + { + b = GetBridgeData(); + if(b) + b->bridge->RegisterOnBridge(this); + } + std::ostringstream tmp; + tmp << this; + return {b ? b->busName : "", tmp.str()}; } void Bridge::RegisterOnBridge(Accessible* obj) { - assert(!obj->bridgeData.lock() || obj->bridgeData.lock() == data); - if (!obj->bridgeData.lock()) - { - assert(data); - data->knownObjects.insert(obj); - obj->bridgeData = data; - } + assert(!obj->bridgeData.lock() || obj->bridgeData.lock() == data); + if(!obj->bridgeData.lock()) + { + assert(data); + data->knownObjects.insert(obj); + obj->bridgeData = data; + } } bool Accessible::IsProxy() { - return false; + return false; } Accessible* Accessible::GetDefaultLabel() { - return this; + return this; } void Accessible::NotifyAccessibilityStateChange(Dali::Accessibility::States states, bool doRecursive) { - if (auto b = GetBridgeData()) + if(auto b = GetBridgeData()) + { + auto s = GetStates() & states; + for(auto i = 0u; i < s.size(); i++) + { + auto index = static_cast(i); + if(s[index]) + b->bridge->EmitStateChanged(this, index, 1, 0); + } + if(doRecursive) { - auto s = GetStates() & states; - for (auto i = 0u; i < s.size(); i++) - { - auto index = static_cast(i); - if (s[index]) - b->bridge->EmitStateChanged(this, index, 1, 0); - } - if (doRecursive) - { - auto children = GetChildren(); - for (auto c : children) - c->NotifyAccessibilityStateChange(states, doRecursive); - } + auto children = GetChildren(); + for(auto c : children) + c->NotifyAccessibilityStateChange(states, doRecursive); } + } } void Accessible::FindWordSeparationsUtf8(const utf8_t* s, size_t length, const char* language, char* breaks) { - set_wordbreaks_utf8(s, length, language, breaks); + set_wordbreaks_utf8(s, length, language, breaks); } void Accessible::FindLineSeparationsUtf8(const utf8_t* s, size_t length, const char* language, char* breaks) { - set_linebreaks_utf8(s, length, language, breaks); + set_linebreaks_utf8(s, length, language, breaks); } diff --git a/dali/internal/accessibility/bridge/bridge-accessible.cpp b/dali/internal/accessibility/bridge/bridge-accessible.cpp index 03a6677..cd92a42 100644 --- a/dali/internal/accessibility/bridge/bridge-accessible.cpp +++ b/dali/internal/accessibility/bridge/bridge-accessible.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,33 +36,33 @@ BridgeAccessible::BridgeAccessible() void BridgeAccessible::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceAccessible}; - AddGetPropertyToInterface( desc, "ChildCount", &BridgeAccessible::GetChildCount ); - AddGetPropertyToInterface( desc, "Name", &BridgeAccessible::GetName ); - AddGetPropertyToInterface( desc, "Description", &BridgeAccessible::GetDescription ); - AddGetPropertyToInterface( desc, "Parent", &BridgeAccessible::GetParent ); - AddFunctionToInterface( desc, "GetRole", &BridgeAccessible::GetRole ); - AddFunctionToInterface( desc, "GetRoleName", &BridgeAccessible::GetRoleName ); - AddFunctionToInterface( desc, "GetLocalizedRoleName", &BridgeAccessible::GetLocalizedRoleName ); - AddFunctionToInterface( desc, "GetState", &BridgeAccessible::GetStates ); - AddFunctionToInterface( desc, "GetAttributes", &BridgeAccessible::GetAttributes ); - AddFunctionToInterface( desc, "GetInterfaces", &BridgeAccessible::GetInterfaces ); - AddFunctionToInterface( desc, "GetChildAtIndex", &BridgeAccessible::GetChildAtIndex ); - AddFunctionToInterface( desc, "GetChildren", &BridgeAccessible::GetChildren ); - AddFunctionToInterface( desc, "GetIndexInParent", &BridgeAccessible::GetIndexInParent ); - AddFunctionToInterface( desc, "GetNavigableAtPoint", &BridgeAccessible::GetNavigableAtPoint ); - AddFunctionToInterface( desc, "GetNeighbor", &BridgeAccessible::GetNeighbor ); - AddFunctionToInterface( desc, "GetDefaultLabelInfo", &BridgeAccessible::GetDefaultLabelInfo ); - AddFunctionToInterface( desc, "DoGesture", &BridgeAccessible::DoGesture ); - AddFunctionToInterface( desc, "GetReadingMaterial", &BridgeAccessible::GetReadingMaterial ); - AddFunctionToInterface( desc, "GetRelationSet", &BridgeAccessible::GetRelationSet ); - dbusServer.addInterface( "/", desc, true ); -} - -static bool AcceptObjectCheckRole( Component* obj ) -{ - if( !obj ) + AddGetPropertyToInterface(desc, "ChildCount", &BridgeAccessible::GetChildCount); + AddGetPropertyToInterface(desc, "Name", &BridgeAccessible::GetName); + AddGetPropertyToInterface(desc, "Description", &BridgeAccessible::GetDescription); + AddGetPropertyToInterface(desc, "Parent", &BridgeAccessible::GetParent); + AddFunctionToInterface(desc, "GetRole", &BridgeAccessible::GetRole); + AddFunctionToInterface(desc, "GetRoleName", &BridgeAccessible::GetRoleName); + AddFunctionToInterface(desc, "GetLocalizedRoleName", &BridgeAccessible::GetLocalizedRoleName); + AddFunctionToInterface(desc, "GetState", &BridgeAccessible::GetStates); + AddFunctionToInterface(desc, "GetAttributes", &BridgeAccessible::GetAttributes); + AddFunctionToInterface(desc, "GetInterfaces", &BridgeAccessible::GetInterfaces); + AddFunctionToInterface(desc, "GetChildAtIndex", &BridgeAccessible::GetChildAtIndex); + AddFunctionToInterface(desc, "GetChildren", &BridgeAccessible::GetChildren); + AddFunctionToInterface(desc, "GetIndexInParent", &BridgeAccessible::GetIndexInParent); + AddFunctionToInterface(desc, "GetNavigableAtPoint", &BridgeAccessible::GetNavigableAtPoint); + AddFunctionToInterface(desc, "GetNeighbor", &BridgeAccessible::GetNeighbor); + AddFunctionToInterface(desc, "GetDefaultLabelInfo", &BridgeAccessible::GetDefaultLabelInfo); + AddFunctionToInterface(desc, "DoGesture", &BridgeAccessible::DoGesture); + AddFunctionToInterface(desc, "GetReadingMaterial", &BridgeAccessible::GetReadingMaterial); + AddFunctionToInterface(desc, "GetRelationSet", &BridgeAccessible::GetRelationSet); + dbusServer.addInterface("/", desc, true); +} + +static bool AcceptObjectCheckRole(Component* obj) +{ + if(!obj) return false; - switch( obj->GetRole() ) + switch(obj->GetRole()) { case Role::APPLICATION: case Role::FILLER: @@ -98,83 +98,83 @@ static bool AcceptObjectCheckRole( Component* obj ) return true; } -static bool AcceptObjectCheckRelations( Component* obj) +static bool AcceptObjectCheckRelations(Component* obj) { auto r = obj->GetRelationSet(); - for (const auto& it : r) - if (it.relationType == RelationType::CONTROLLED_BY) + for(const auto& it : r) + if(it.relationType == RelationType::CONTROLLED_BY) return false; return true; } -static Component* GetScrollableParent( Accessible* obj ) +static Component* GetScrollableParent(Accessible* obj) { - while( obj ) + while(obj) { - obj = obj->GetParent(); - auto comp = dynamic_cast< Component* >( obj ); - if( comp && comp->IsScrollable() ) + obj = obj->GetParent(); + auto comp = dynamic_cast(obj); + if(comp && comp->IsScrollable()) return comp; } return nullptr; } -static bool ObjectIsItem( Component* obj ) +static bool ObjectIsItem(Component* obj) { - if( !obj ) + if(!obj) return false; auto role = obj->GetRole(); return role == Role::LIST_ITEM || role == Role::MENU_ITEM; } -static bool ObjectIsCollapsed( Component* obj ) +static bool ObjectIsCollapsed(Component* obj) { - if( !obj ) + if(!obj) return false; const auto states = obj->GetStates(); return states[State::EXPANDABLE] && !states[State::EXPANDED]; } -static bool OobjectIsZeroSize( Component* obj ) +static bool OobjectIsZeroSize(Component* obj) { - if( !obj ) + if(!obj) return false; - auto extents = obj->GetExtents( CoordType::WINDOW ); + auto extents = obj->GetExtents(CoordType::WINDOW); return extents.height == 0 || extents.width == 0; } -static bool AcceptObject( Component* obj ) +static bool AcceptObject(Component* obj) { - if( !obj ) + if(!obj) return false; const auto states = obj->GetStates(); - if( !states[State::VISIBLE] ) + if(!states[State::VISIBLE]) return false; - if( !AcceptObjectCheckRole( obj ) ) + if(!AcceptObjectCheckRole(obj)) return false; - if ( !AcceptObjectCheckRelations( obj ) ) + if(!AcceptObjectCheckRelations(obj)) return false; - if( !states[State::HIGHLIGHTABLE] ) + if(!states[State::HIGHLIGHTABLE]) return false; - if( GetScrollableParent( obj ) != nullptr ) + if(GetScrollableParent(obj) != nullptr) { - auto parent = dynamic_cast< Component* >( obj->GetParent() ); + auto parent = dynamic_cast(obj->GetParent()); - if( parent ) + if(parent) { - return !ObjectIsItem( obj ) || !ObjectIsCollapsed( parent ); + return !ObjectIsItem(obj) || !ObjectIsCollapsed(parent); } } else { - if( OobjectIsZeroSize( obj ) ) + if(OobjectIsZeroSize(obj)) { return false; } - if( !states[State::SHOWING] ) + if(!states[State::SHOWING]) { return false; } @@ -182,35 +182,35 @@ static bool AcceptObject( Component* obj ) return true; } -static bool AcceptObject( Accessible* obj ) +static bool AcceptObject(Accessible* obj) { - auto c = dynamic_cast< Component* >( obj ); - return AcceptObject( c ); + auto c = dynamic_cast(obj); + return AcceptObject(c); } -static std::string objDump( Component* obj ) +static std::string objDump(Component* obj) { - if ( !obj ) + if(!obj) return "nullptr"; std::ostringstream o; - auto e = obj->GetExtents( CoordType::SCREEN ); + auto e = obj->GetExtents(CoordType::SCREEN); o << "name: " << obj->GetName() << " extent: (" << e.x << ", " - << e.y << "), [" << e.width << ", " << e.height << "]"; + << e.y << "), [" << e.width << ", " << e.height << "]"; return o.str(); } -Component * BridgeAccessible::GetObjectInRelation( Accessible * obj, RelationType ralationType ) +Component* BridgeAccessible::GetObjectInRelation(Accessible* obj, RelationType ralationType) { - if ( !obj ) + if(!obj) return nullptr; - for ( auto &relation : obj->GetRelationSet() ) + for(auto& relation : obj->GetRelationSet()) { - if ( relation.relationType == ralationType ) + if(relation.relationType == ralationType) { - for ( auto &address : relation.targets ) + for(auto& address : relation.targets) { - auto component = dynamic_cast( Find( address ) ); - if ( component ) + auto component = dynamic_cast(Find(address)); + if(component) return component; } } @@ -218,39 +218,39 @@ Component * BridgeAccessible::GetObjectInRelation( Accessible * obj, RelationTyp return nullptr; } -static std::string makeIndent( unsigned int maxRecursionDepth ) +static std::string makeIndent(unsigned int maxRecursionDepth) { - return std::string( GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH - maxRecursionDepth, ' ' ); + return std::string(GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH - maxRecursionDepth, ' '); } -Component* BridgeAccessible::CalculateNavigableAccessibleAtPoint( Accessible* root, Point p, CoordType cType, unsigned int maxRecursionDepth ) +Component* BridgeAccessible::CalculateNavigableAccessibleAtPoint(Accessible* root, Point p, CoordType cType, unsigned int maxRecursionDepth) { - if( !root || maxRecursionDepth == 0 ) + if(!root || maxRecursionDepth == 0) return nullptr; - auto root_component = dynamic_cast< Component* >( root ); + auto root_component = dynamic_cast(root); LOG() << "CalculateNavigableAccessibleAtPoint: checking: " << makeIndent(maxRecursionDepth) << objDump(root_component); - if( root_component && !root_component->Contains( p, cType ) ) + if(root_component && !root_component->Contains(p, cType)) return nullptr; auto children = root->GetChildren(); - for( auto childIt = children.rbegin(); childIt != children.rend(); childIt++ ) + for(auto childIt = children.rbegin(); childIt != children.rend(); childIt++) { //check recursively all children first - auto result = CalculateNavigableAccessibleAtPoint( *childIt, p, cType, maxRecursionDepth - 1 ); - if( result ) + auto result = CalculateNavigableAccessibleAtPoint(*childIt, p, cType, maxRecursionDepth - 1); + if(result) return result; } - if( root_component ) + if(root_component) { //Found a candidate, all its children are already checked - auto controledBy = GetObjectInRelation( root_component, RelationType::CONTROLLED_BY ); - if ( !controledBy ) + auto controledBy = GetObjectInRelation(root_component, RelationType::CONTROLLED_BY); + if(!controledBy) controledBy = root_component; - if ( controledBy->IsProxy() || AcceptObject( controledBy ) ) + if(controledBy->IsProxy() || AcceptObject(controledBy)) { - LOG() << "CalculateNavigableAccessibleAtPoint: found: " << makeIndent(maxRecursionDepth) << objDump( root_component ); + LOG() << "CalculateNavigableAccessibleAtPoint: found: " << makeIndent(maxRecursionDepth) << objDump(root_component); return controledBy; } } @@ -259,102 +259,102 @@ Component* BridgeAccessible::CalculateNavigableAccessibleAtPoint( Accessible* ro BridgeAccessible::ReadingMaterialType BridgeAccessible::GetReadingMaterial() { - auto self = FindSelf(); - auto attributes = self->GetAttributes(); - auto name = self->GetName(); + auto self = FindSelf(); + auto attributes = self->GetAttributes(); + auto name = self->GetName(); std::string labeledByName = ""; - std::string textIfceName = ""; - auto role = static_cast< uint32_t >( self->GetRole() ); - auto states = self->GetStates(); - auto localizedName = self->GetLocalizedRoleName(); - auto childCount = static_cast< int32_t >( self->GetChildCount() ); + std::string textIfceName = ""; + auto role = static_cast(self->GetRole()); + auto states = self->GetStates(); + auto localizedName = self->GetLocalizedRoleName(); + auto childCount = static_cast(self->GetChildCount()); - double currentValue = 0.0; + double currentValue = 0.0; double minimumIncrement = 0.0; - double maximumValue = 0.0; - double minimumValue = 0.0; + double maximumValue = 0.0; + double minimumValue = 0.0; - auto *value = dynamic_cast(self); - if (value) + auto* value = dynamic_cast(self); + if(value) { - currentValue = value->GetCurrent(); + currentValue = value->GetCurrent(); minimumIncrement = value->GetMinimumIncrement(); - maximumValue = value->GetMaximum(); - minimumValue = value->GetMinimum(); + maximumValue = value->GetMaximum(); + minimumValue = value->GetMinimum(); } - auto description = self->GetDescription(); - auto indexInParent = static_cast< int32_t >( self->GetIndexInParent() ); - bool isSelectedInParent = false; - bool hasCheckBoxChild = false; + auto description = self->GetDescription(); + auto indexInParent = static_cast(self->GetIndexInParent()); + bool isSelectedInParent = false; + bool hasCheckBoxChild = false; int32_t firstSelectedChildIndex = -1; - int32_t selectedChildCount = 0; + int32_t selectedChildCount = 0; - for( auto i = 0u; i < static_cast< size_t >( childCount ); ++i ) + for(auto i = 0u; i < static_cast(childCount); ++i) { - auto q = self->GetChildAtIndex( i ); + auto q = self->GetChildAtIndex(i); auto s = q->GetStates(); - if( s[State::SELECTABLE] ) + if(s[State::SELECTABLE]) { - if( s[State::SELECTED] ) + if(s[State::SELECTED]) { ++selectedChildCount; - if( firstSelectedChildIndex < 0 ) - firstSelectedChildIndex = static_cast< int32_t >( i ); + if(firstSelectedChildIndex < 0) + firstSelectedChildIndex = static_cast(i); } } - if( q->GetRole() == Role::CHECK_BOX ) + if(q->GetRole() == Role::CHECK_BOX) hasCheckBoxChild = true; } - int32_t listChildrenCount = 0; - Accessible* parent = self->GetParent(); - auto parentStateSet = parent ? parent->GetStates() : States{}; - auto parentChildCount = parent ? static_cast< int32_t >( parent->GetChildCount() ) : 0; - auto parentRole = static_cast< uint32_t >( parent ? parent->GetRole() : Role{} ); + int32_t listChildrenCount = 0; + Accessible* parent = self->GetParent(); + auto parentStateSet = parent ? parent->GetStates() : States{}; + auto parentChildCount = parent ? static_cast(parent->GetChildCount()) : 0; + auto parentRole = static_cast(parent ? parent->GetRole() : Role{}); Accessible* describedByObject = nullptr; return { - attributes, - name, - labeledByName, - textIfceName, - role, - states, - localizedName, - childCount, - currentValue, - minimumIncrement, - maximumValue, - minimumValue, - description, - indexInParent, - isSelectedInParent, - hasCheckBoxChild, - listChildrenCount, - firstSelectedChildIndex, - parent, - parentStateSet, - parentChildCount, - parentRole, - selectedChildCount, - describedByObject}; -} - -DBus::ValueOrError< bool > BridgeAccessible::DoGesture( Dali::Accessibility::Gesture type, int32_t xBeg, int32_t xEnd, int32_t yBeg, int32_t yEnd, Dali::Accessibility::GestureState state, uint32_t eventTime ) -{ - return FindSelf()->DoGesture( Dali::Accessibility::GestureInfo {type, xBeg, xEnd, yBeg, yEnd, state, eventTime}); -} - -DBus::ValueOrError< Accessible*, uint8_t, Accessible* > BridgeAccessible::GetNavigableAtPoint( int32_t x, int32_t y, uint32_t coordType ) -{ - Accessible* deputy = nullptr; - auto accessible = FindSelf(); - auto cType = static_cast< CoordType >( coordType ); + attributes, + name, + labeledByName, + textIfceName, + role, + states, + localizedName, + childCount, + currentValue, + minimumIncrement, + maximumValue, + minimumValue, + description, + indexInParent, + isSelectedInParent, + hasCheckBoxChild, + listChildrenCount, + firstSelectedChildIndex, + parent, + parentStateSet, + parentChildCount, + parentRole, + selectedChildCount, + describedByObject}; +} + +DBus::ValueOrError BridgeAccessible::DoGesture(Dali::Accessibility::Gesture type, int32_t xBeg, int32_t xEnd, int32_t yBeg, int32_t yEnd, Dali::Accessibility::GestureState state, uint32_t eventTime) +{ + return FindSelf()->DoGesture(Dali::Accessibility::GestureInfo{type, xBeg, xEnd, yBeg, yEnd, state, eventTime}); +} + +DBus::ValueOrError BridgeAccessible::GetNavigableAtPoint(int32_t x, int32_t y, uint32_t coordType) +{ + Accessible* deputy = nullptr; + auto accessible = FindSelf(); + auto cType = static_cast(coordType); LOG() << "GetNavigableAtPoint: " << x << ", " << y << " type: " << coordType; - auto component = CalculateNavigableAccessibleAtPoint( accessible, {x, y}, cType, GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH ); - bool recurse = false; - if( component ) + auto component = CalculateNavigableAccessibleAtPoint(accessible, {x, y}, cType, GET_NAVIGABLE_AT_POINT_MAX_RECURSION_DEPTH); + bool recurse = false; + if(component) { recurse = component->IsProxy(); } @@ -362,16 +362,16 @@ DBus::ValueOrError< Accessible*, uint8_t, Accessible* > BridgeAccessible::GetNav return {component, recurse, deputy}; } -static bool CheckChainEndWithAttribute( Accessible* obj, unsigned char forward ) +static bool CheckChainEndWithAttribute(Accessible* obj, unsigned char forward) { - if( !obj ) + if(!obj) return false; auto attrs = obj->GetAttributes(); - for( auto& attr : attrs ) + for(auto& attr : attrs) { - if( attr.first == "relation_chain_end" ) + if(attr.first == "relation_chain_end") { - if( ( attr.second == "prev,end" && forward == 0 ) || ( attr.second == "next,end" && forward == 1 ) || attr.second == "prev,next,end" ) + if((attr.second == "prev,end" && forward == 0) || (attr.second == "next,end" && forward == 1) || attr.second == "prev,next,end") { return true; } @@ -380,7 +380,7 @@ static bool CheckChainEndWithAttribute( Accessible* obj, unsigned char forward ) return false; } -static Accessible* DeputyOfProxyInParentGet( Accessible* obj ) +static Accessible* DeputyOfProxyInParentGet(Accessible* obj) { return nullptr; } @@ -391,160 +391,165 @@ Accessible* BridgeAccessible::GetCurrentlyHighlighted() return nullptr; } -std::vector< Accessible* > BridgeAccessible::ValidChildrenGet( const std::vector< Accessible* >& children, Accessible* start, Accessible* root ) +std::vector BridgeAccessible::ValidChildrenGet(const std::vector& children, Accessible* start, Accessible* root) { return children; } -static bool DeputyIs( Accessible* obj ) +static bool DeputyIs(Accessible* obj) { //TODO: add deputy return false; } -static Accessible* ProxyInParentGet( Accessible* obj ) +static Accessible* ProxyInParentGet(Accessible* obj) { - if( !obj ) + if(!obj) return nullptr; auto children = obj->GetChildren(); - for( auto& child : children ) + for(auto& child : children) { - if( child->IsProxy() ) + if(child->IsProxy()) return child; } return nullptr; } -static bool ObjectRoleIsAcceptableWhenNavigatingNextPrev( Accessible* obj ) +static bool ObjectRoleIsAcceptableWhenNavigatingNextPrev(Accessible* obj) { - if( !obj ) + if(!obj) return false; auto role = obj->GetRole(); return role != Role::POPUP_MENU && role != Role::DIALOG; } -template < class T > +template struct CycleDetection { - CycleDetection( const T value ) : key( value ), currentSearchSize( 1 ), counter( 1 ) {} - bool check( const T value ) + CycleDetection(const T value) + : key(value), + currentSearchSize(1), + counter(1) { - if( key == value ) + } + bool check(const T value) + { + if(key == value) return true; - if( --counter == 0 ) + if(--counter == 0) { currentSearchSize <<= 1; - if( currentSearchSize == 0 ) + if(currentSearchSize == 0) return true; // UNDEFINED BEHAVIOR counter = currentSearchSize; - key = value; + key = value; } return false; } - T key; + T key; unsigned int currentSearchSize; unsigned int counter; }; -static Accessible* FindNonDefunctChild( const std::vector< Accessible* >& children, unsigned int currentIndex, unsigned char forward ) +static Accessible* FindNonDefunctChild(const std::vector& children, unsigned int currentIndex, unsigned char forward) { unsigned int childrenCount = children.size(); - for( ; currentIndex < childrenCount; forward ? ++currentIndex : --currentIndex ) + for(; currentIndex < childrenCount; forward ? ++currentIndex : --currentIndex) { Accessible* n = children[currentIndex]; - if( n && !n->GetStates()[State::DEFUNCT] ) + if(n && !n->GetStates()[State::DEFUNCT]) return n; } return nullptr; } -static Accessible* DirectionalDepthFirstSearchTryNonDefunctChild( Accessible* node, const std::vector< Accessible* >& children, unsigned char forward ) +static Accessible* DirectionalDepthFirstSearchTryNonDefunctChild(Accessible* node, const std::vector& children, unsigned char forward) { - if( !node ) + if(!node) return nullptr; auto childrenCount = children.size(); - if( childrenCount > 0 ) + if(childrenCount > 0) { - const bool isShowing = GetScrollableParent( node ) == nullptr ? node->GetStates()[State::SHOWING] : true; - if( isShowing ) + const bool isShowing = GetScrollableParent(node) == nullptr ? node->GetStates()[State::SHOWING] : true; + if(isShowing) { - return FindNonDefunctChild( children, forward ? 0 : childrenCount - 1, forward ); + return FindNonDefunctChild(children, forward ? 0 : childrenCount - 1, forward); } } return nullptr; } -Accessible* BridgeAccessible::GetNextNonDefunctSibling( Accessible* obj, Accessible* start, Accessible* root, unsigned char forward ) +Accessible* BridgeAccessible::GetNextNonDefunctSibling(Accessible* obj, Accessible* start, Accessible* root, unsigned char forward) { - if( !obj ) + if(!obj) return nullptr; auto parent = obj->GetParent(); - if( !parent ) + if(!parent) return nullptr; - auto children = ValidChildrenGet( parent->GetChildren(), start, root ); + auto children = ValidChildrenGet(parent->GetChildren(), start, root); unsigned int children_count = children.size(); - if( children_count == 0 ) + if(children_count == 0) { return nullptr; } unsigned int current = 0; - for( ; current < children_count && children[current] != obj; ++current ) + for(; current < children_count && children[current] != obj; ++current) ; - if( current >= children_count ) + if(current >= children_count) { return nullptr; } forward ? ++current : --current; - auto ret = FindNonDefunctChild( children, current, forward ); + auto ret = FindNonDefunctChild(children, current, forward); return ret; } -Accessible* BridgeAccessible::DirectionalDepthFirstSearchTryNonDefunctSibling( bool& all_children_visited, Accessible* node, Accessible* start, Accessible* root, unsigned char forward ) +Accessible* BridgeAccessible::DirectionalDepthFirstSearchTryNonDefunctSibling(bool& all_children_visited, Accessible* node, Accessible* start, Accessible* root, unsigned char forward) { - while( true ) + while(true) { - Accessible* sibling = GetNextNonDefunctSibling( node, start, root, forward ); - if( sibling ) + Accessible* sibling = GetNextNonDefunctSibling(node, start, root, forward); + if(sibling) { - node = sibling; + node = sibling; all_children_visited = false; break; } // walk up... node = node->GetParent(); - if( node == nullptr || node == root ) + if(node == nullptr || node == root) return nullptr; // in backward traversing stop the walk up on parent - if( !forward ) + if(!forward) break; } return node; } -Accessible* BridgeAccessible::CalculateNeighbor( Accessible* root, Accessible* start, unsigned char forward, BridgeAccessible::GetNeighborSearchMode search_mode ) +Accessible* BridgeAccessible::CalculateNeighbor(Accessible* root, Accessible* start, unsigned char forward, BridgeAccessible::GetNeighborSearchMode search_mode) { - if( start && CheckChainEndWithAttribute( start, forward ) ) + if(start && CheckChainEndWithAttribute(start, forward)) return start; - if( root && root->GetStates()[State::DEFUNCT] ) + if(root && root->GetStates()[State::DEFUNCT]) return NULL; - if( start && start->GetStates()[State::DEFUNCT] ) + if(start && start->GetStates()[State::DEFUNCT]) { - start = NULL; + start = NULL; forward = 1; } - if( search_mode == BridgeAccessible::GetNeighborSearchMode::recurseToOutside ) + if(search_mode == BridgeAccessible::GetNeighborSearchMode::recurseToOutside) { // This only works if we navigate backward, and it is not possible to // find in embedded process. In this case the deputy should be used */ - return DeputyOfProxyInParentGet( start ); + return DeputyOfProxyInParentGet(start); } Accessible* node = start ? start : root; - if( !node ) + if(!node) return nullptr; // initialization of all-children-visited flag for start node - we assume @@ -554,7 +559,7 @@ Accessible* BridgeAccessible::CalculateNeighbor( Accessible* root, Accessible* s // Regarding condtion (start != root): // The last object can be found only if all_children_visited is false. // The start is same with root, when looking for the last object. - bool all_children_visited = ( start != root ) && ( search_mode != BridgeAccessible::GetNeighborSearchMode::recurseFromRoot && !forward ); + bool all_children_visited = (start != root) && (search_mode != BridgeAccessible::GetNeighborSearchMode::recurseFromRoot && !forward); // true, if starting element should be ignored. this is only used in rare case of // recursive search failing to find an object. // consider tree, where element A on bus BUS_A has child B on bus BUS_B. when going "next" from @@ -563,96 +568,96 @@ Accessible* BridgeAccessible::CalculateNeighbor( Accessible* root, Accessible* s // if next object will be found there (on BUS_B), then search ends. but if not, then our caller will find it out // and will call us again with object A and flag search_mode set to NEIGHBOR_SEARCH_MODE_CONTINUE_AFTER_FAILED_RECURSING. // this flag means, that object A was already checked previously and we should skip it and its children. - bool force_next = ( search_mode == BridgeAccessible::GetNeighborSearchMode::continueAfterFailedRecursion ); + bool force_next = (search_mode == BridgeAccessible::GetNeighborSearchMode::continueAfterFailedRecursion); - CycleDetection< Accessible* > cycleDetection( node ); - while( node ) + CycleDetection cycleDetection(node); + while(node) { - if( node->GetStates()[State::DEFUNCT] ) + if(node->GetStates()[State::DEFUNCT]) return nullptr; // always accept proxy object from different world - if( !force_next && node->IsProxy() ) + if(!force_next && node->IsProxy()) return node; auto children = node->GetChildren(); - children = ValidChildrenGet( children, start, root ); + children = ValidChildrenGet(children, start, root); // do accept: // 1. not start node // 2. parent after all children in backward traversing // 3. Nodes with roles: ATSPI_ROLE_PAGE_TAB, ATSPI_ROLE_POPUP_MENU and ATSPI_ROLE_DIALOG, only when looking for first or last element. // Objects with those roles shouldnt be reachable, when navigating next / prev. - bool all_children_visited_or_moving_forward = ( children.size() == 0 || forward || all_children_visited ); - if( !force_next && node != start && all_children_visited_or_moving_forward && AcceptObject( node ) ) + bool all_children_visited_or_moving_forward = (children.size() == 0 || forward || all_children_visited); + if(!force_next && node != start && all_children_visited_or_moving_forward && AcceptObject(node)) { - if( start == NULL || ObjectRoleIsAcceptableWhenNavigatingNextPrev( node ) ) + if(start == NULL || ObjectRoleIsAcceptableWhenNavigatingNextPrev(node)) return node; } - Accessible* next_related_in_direction = !force_next ? GetObjectInRelation( node, forward ? RelationType::FLOWS_TO : RelationType::FLOWS_FROM ) : nullptr; + Accessible* next_related_in_direction = !force_next ? GetObjectInRelation(node, forward ? RelationType::FLOWS_TO : RelationType::FLOWS_FROM) : nullptr; // force_next means that the search_mode is NEIGHBOR_SEARCH_MODE_CONTINUE_AFTER_FAILED_RECURSING // in this case the node is elm_layout which is parent of proxy object. // There is an access object working for the proxy object, and the access // object could have relation information. This relation information should // be checked first before using the elm_layout as a node. - if( force_next && forward ) + if(force_next && forward) { - auto deputy = DeputyOfProxyInParentGet( node ); + auto deputy = DeputyOfProxyInParentGet(node); next_related_in_direction = - GetObjectInRelation( deputy, RelationType::FLOWS_TO ); + GetObjectInRelation(deputy, RelationType::FLOWS_TO); } - if( next_related_in_direction && start && start->GetStates()[State::DEFUNCT] ) + if(next_related_in_direction && start && start->GetStates()[State::DEFUNCT]) { next_related_in_direction = NULL; } unsigned char want_cycle_detection = 0; - if( next_related_in_direction ) + if(next_related_in_direction) { // Check next_related_in_direction is deputy object Accessible* parent; - if( !forward ) + if(!forward) { // If the prev object is deputy, then go to inside of its proxy first - if( DeputyIs( next_related_in_direction ) ) + if(DeputyIs(next_related_in_direction)) { - parent = next_related_in_direction->GetParent(); - next_related_in_direction = ProxyInParentGet( parent ); + parent = next_related_in_direction->GetParent(); + next_related_in_direction = ProxyInParentGet(parent); } } else { // If current object is deputy, and it has relation next object, // then do not use the relation next object, and use proxy first - if( DeputyIs( node ) ) + if(DeputyIs(node)) { - parent = node->GetParent(); - next_related_in_direction = ProxyInParentGet( parent ); + parent = node->GetParent(); + next_related_in_direction = ProxyInParentGet(parent); } } - node = next_related_in_direction; + node = next_related_in_direction; want_cycle_detection = 1; } else { - auto child = !force_next && !all_children_visited ? DirectionalDepthFirstSearchTryNonDefunctChild( node, children, forward ) : nullptr; - if( child ) + auto child = !force_next && !all_children_visited ? DirectionalDepthFirstSearchTryNonDefunctChild(node, children, forward) : nullptr; + if(child) { want_cycle_detection = 1; } else { - if( !force_next && node == root ) + if(!force_next && node == root) return NULL; all_children_visited = true; - child = DirectionalDepthFirstSearchTryNonDefunctSibling( all_children_visited, node, start, root, forward ); + child = DirectionalDepthFirstSearchTryNonDefunctSibling(all_children_visited, node, start, root, forward); } node = child; } force_next = 0; - if( want_cycle_detection && cycleDetection.check( node ) ) + if(want_cycle_detection && cycleDetection.check(node)) { return NULL; } @@ -660,14 +665,14 @@ Accessible* BridgeAccessible::CalculateNeighbor( Accessible* root, Accessible* s return NULL; } -DBus::ValueOrError< Accessible*, uint8_t > BridgeAccessible::GetNeighbor( std::string rootPath, int32_t direction, int32_t search_mode ) +DBus::ValueOrError BridgeAccessible::GetNeighbor(std::string rootPath, int32_t direction, int32_t search_mode) { - auto start = FindSelf(); - rootPath = StripPrefix( rootPath ); - auto root = !rootPath.empty() ? Find( rootPath ) : nullptr; - auto accessible = CalculateNeighbor( root, start, direction == 1, static_cast< GetNeighborSearchMode >( search_mode ) ); - unsigned char recurse = 0; - if( accessible ) + auto start = FindSelf(); + rootPath = StripPrefix(rootPath); + auto root = !rootPath.empty() ? Find(rootPath) : nullptr; + auto accessible = CalculateNeighbor(root, start, direction == 1, static_cast(search_mode)); + unsigned char recurse = 0; + if(accessible) { recurse = accessible->IsProxy(); } @@ -681,10 +686,10 @@ Accessible* BridgeAccessible::GetParent() // if you want more, then you need to change setApplicationRoot to // add/remove ApplicationRoot and make roots a vector. auto p = FindSelf()->GetParent(); - assert( p ); + assert(p); return p; } -DBus::ValueOrError< std::vector< Accessible* > > BridgeAccessible::GetChildren() +DBus::ValueOrError> BridgeAccessible::GetChildren() { return FindSelf()->GetChildren(); } @@ -692,31 +697,31 @@ std::string BridgeAccessible::GetDescription() { return FindSelf()->GetDescription(); } -DBus::ValueOrError< uint32_t > BridgeAccessible::GetRole() +DBus::ValueOrError BridgeAccessible::GetRole() { - return static_cast< unsigned int >( FindSelf()->GetRole() ); + return static_cast(FindSelf()->GetRole()); } -DBus::ValueOrError< std::string > BridgeAccessible::GetRoleName() +DBus::ValueOrError BridgeAccessible::GetRoleName() { return FindSelf()->GetRoleName(); } -DBus::ValueOrError< std::string > BridgeAccessible::GetLocalizedRoleName() +DBus::ValueOrError BridgeAccessible::GetLocalizedRoleName() { return FindSelf()->GetLocalizedRoleName(); } -DBus::ValueOrError< int32_t > BridgeAccessible::GetIndexInParent() +DBus::ValueOrError BridgeAccessible::GetIndexInParent() { return FindSelf()->GetIndexInParent(); } -DBus::ValueOrError< std::array< uint32_t, 2 > > BridgeAccessible::GetStates() +DBus::ValueOrError> BridgeAccessible::GetStates() { return FindSelf()->GetStates().GetRawData(); } -DBus::ValueOrError< std::unordered_map< std::string, std::string > > BridgeAccessible::GetAttributes() +DBus::ValueOrError> BridgeAccessible::GetAttributes() { return FindSelf()->GetAttributes(); } -DBus::ValueOrError< std::vector< std::string > > BridgeAccessible::GetInterfaces() +DBus::ValueOrError> BridgeAccessible::GetInterfaces() { return FindSelf()->GetInterfaces(); } @@ -724,11 +729,11 @@ int BridgeAccessible::GetChildCount() { return FindSelf()->GetChildCount(); } -DBus::ValueOrError< Accessible* > BridgeAccessible::GetChildAtIndex( int index ) +DBus::ValueOrError BridgeAccessible::GetChildAtIndex(int index) { - if( index < 0 ) - throw std::domain_error{"negative index (" + std::to_string( index ) + ")"}; - return FindSelf()->GetChildAtIndex( static_cast< size_t >( index ) ); + if(index < 0) + throw std::domain_error{"negative index (" + std::to_string(index) + ")"}; + return FindSelf()->GetChildAtIndex(static_cast(index)); } std::string BridgeAccessible::GetName() @@ -736,18 +741,18 @@ std::string BridgeAccessible::GetName() return FindSelf()->GetName(); } -DBus::ValueOrError< Accessible*, uint32_t , std::unordered_map< std::string, std::string > > BridgeAccessible::GetDefaultLabelInfo() +DBus::ValueOrError> BridgeAccessible::GetDefaultLabelInfo() { auto defaultLabel = FindSelf()->GetDefaultLabel(); - return {defaultLabel, static_cast< uint32_t >( defaultLabel->GetRole() ) , defaultLabel->GetAttributes()}; + return {defaultLabel, static_cast(defaultLabel->GetRole()), defaultLabel->GetAttributes()}; } -DBus::ValueOrError> BridgeAccessible::GetRelationSet() +DBus::ValueOrError> BridgeAccessible::GetRelationSet() { - auto relations = FindSelf()->GetRelationSet(); - std::vector< BridgeAccessible::Relation > ret; + auto relations = FindSelf()->GetRelationSet(); + std::vector ret; - for (auto &it : relations) + for(auto& it : relations) ret.emplace_back(Relation{static_cast(it.relationType), it.targets}); return ret; diff --git a/dali/internal/accessibility/bridge/bridge-accessible.h b/dali/internal/accessibility/bridge/bridge-accessible.h index 9abdd36..f4e62fc 100644 --- a/dali/internal/accessibility/bridge/bridge-accessible.h +++ b/dali/internal/accessibility/bridge/bridge-accessible.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_ACCESSIBLE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,69 +37,69 @@ protected: public: enum class GetNeighborSearchMode { - normal = 0, - recurseFromRoot = 1, + normal = 0, + recurseFromRoot = 1, continueAfterFailedRecursion = 2, - recurseToOutside = 3, + recurseToOutside = 3, }; - int GetChildCount(); - DBus::ValueOrError< Dali::Accessibility::Accessible* > GetChildAtIndex( int index ); - Dali::Accessibility::Accessible* GetParent(); - DBus::ValueOrError< std::vector< Dali::Accessibility::Accessible* > > GetChildren(); - std::string GetName(); - std::string GetDescription(); - DBus::ValueOrError< uint32_t > GetRole(); - DBus::ValueOrError< std::string > GetRoleName(); - DBus::ValueOrError< std::string > GetLocalizedRoleName(); - DBus::ValueOrError< int32_t > GetIndexInParent(); - DBus::ValueOrError< std::array< uint32_t, 2 > > GetStates(); - DBus::ValueOrError< std::unordered_map< std::string, std::string > > GetAttributes(); - DBus::ValueOrError< std::vector< std::string > > GetInterfaces(); - DBus::ValueOrError< Dali::Accessibility::Accessible*, uint8_t, Dali::Accessibility::Accessible* > GetNavigableAtPoint( int32_t x, int32_t y, uint32_t coordType ); - DBus::ValueOrError< Dali::Accessibility::Accessible*, uint8_t > GetNeighbor( std::string root_path, int32_t direction, int32_t search_mode ); - DBus::ValueOrError< Dali::Accessibility::Accessible*, uint32_t , std::unordered_map< std::string, std::string > > GetDefaultLabelInfo(); + int GetChildCount(); + DBus::ValueOrError GetChildAtIndex(int index); + Dali::Accessibility::Accessible* GetParent(); + DBus::ValueOrError> GetChildren(); + std::string GetName(); + std::string GetDescription(); + DBus::ValueOrError GetRole(); + DBus::ValueOrError GetRoleName(); + DBus::ValueOrError GetLocalizedRoleName(); + DBus::ValueOrError GetIndexInParent(); + DBus::ValueOrError> GetStates(); + DBus::ValueOrError> GetAttributes(); + DBus::ValueOrError> GetInterfaces(); + DBus::ValueOrError GetNavigableAtPoint(int32_t x, int32_t y, uint32_t coordType); + DBus::ValueOrError GetNeighbor(std::string root_path, int32_t direction, int32_t search_mode); + DBus::ValueOrError> GetDefaultLabelInfo(); using ReadingMaterialType = DBus::ValueOrError< - std::unordered_map< std::string, std::string >, // attributes - std::string, // name - std::string, // labeledByName - std::string, // textIfceName - uint32_t, - Dali::Accessibility::States, - std::string, // localized name - int32_t, // child count - double, // current value - double, // minimum increment - double, // maximum value - double, // minimum value - std::string, // description - int32_t, // index in parent - bool, // isSelectedInParent - bool, // hasCheckBoxChild - int32_t, // listChildrenCount - int32_t, // firstSelectedChildIndex - Dali::Accessibility::Accessible*, // parent - Dali::Accessibility::States, // parentStateSet - int32_t, // parentChildCount - uint32_t, // parentRole - int32_t, // selectedChildCount, - Dali::Accessibility::Accessible* // describedByObject - >; + std::unordered_map, // attributes + std::string, // name + std::string, // labeledByName + std::string, // textIfceName + uint32_t, + Dali::Accessibility::States, + std::string, // localized name + int32_t, // child count + double, // current value + double, // minimum increment + double, // maximum value + double, // minimum value + std::string, // description + int32_t, // index in parent + bool, // isSelectedInParent + bool, // hasCheckBoxChild + int32_t, // listChildrenCount + int32_t, // firstSelectedChildIndex + Dali::Accessibility::Accessible*, // parent + Dali::Accessibility::States, // parentStateSet + int32_t, // parentChildCount + uint32_t, // parentRole + int32_t, // selectedChildCount, + Dali::Accessibility::Accessible* // describedByObject + >; ReadingMaterialType GetReadingMaterial(); - DBus::ValueOrError< bool > DoGesture( Dali::Accessibility::Gesture type, int32_t xBeg, int32_t xEnd, int32_t yBeg, int32_t yEnd, Dali::Accessibility::GestureState state, uint32_t eventTime ); + DBus::ValueOrError DoGesture(Dali::Accessibility::Gesture type, int32_t xBeg, int32_t xEnd, int32_t yBeg, int32_t yEnd, Dali::Accessibility::GestureState state, uint32_t eventTime); - using Relation = std::tuple< uint32_t, std::vector< Dali::Accessibility::Address > >; - DBus::ValueOrError> GetRelationSet(); + using Relation = std::tuple>; + DBus::ValueOrError> GetRelationSet(); private: - Dali::Accessibility::Accessible* CalculateNeighbor( Dali::Accessibility::Accessible* root, Dali::Accessibility::Accessible* start, unsigned char forward, GetNeighborSearchMode search_mode ); - std::vector< Dali::Accessibility::Accessible* > ValidChildrenGet( const std::vector< Dali::Accessibility::Accessible* >& children, Dali::Accessibility::Accessible* start, Dali::Accessibility::Accessible* root ); - Dali::Accessibility::Accessible* GetCurrentlyHighlighted(); - Dali::Accessibility::Accessible* DirectionalDepthFirstSearchTryNonDefunctSibling( bool& all_children_visited, Dali::Accessibility::Accessible* node, Dali::Accessibility::Accessible* start, Dali::Accessibility::Accessible* root, unsigned char forward ); - Dali::Accessibility::Accessible* GetNextNonDefunctSibling( Dali::Accessibility::Accessible* obj, Dali::Accessibility::Accessible* start, Dali::Accessibility::Accessible* root, unsigned char forward ); - Dali::Accessibility::Component* CalculateNavigableAccessibleAtPoint( Dali::Accessibility::Accessible* root, Dali::Accessibility::Point p, Dali::Accessibility::CoordType cType, unsigned int maxRecursionDepth ); - Dali::Accessibility::Component * GetObjectInRelation(Dali::Accessibility::Accessible * obj, Dali::Accessibility::RelationType ralationType); + Dali::Accessibility::Accessible* CalculateNeighbor(Dali::Accessibility::Accessible* root, Dali::Accessibility::Accessible* start, unsigned char forward, GetNeighborSearchMode search_mode); + std::vector ValidChildrenGet(const std::vector& children, Dali::Accessibility::Accessible* start, Dali::Accessibility::Accessible* root); + Dali::Accessibility::Accessible* GetCurrentlyHighlighted(); + Dali::Accessibility::Accessible* DirectionalDepthFirstSearchTryNonDefunctSibling(bool& all_children_visited, Dali::Accessibility::Accessible* node, Dali::Accessibility::Accessible* start, Dali::Accessibility::Accessible* root, unsigned char forward); + Dali::Accessibility::Accessible* GetNextNonDefunctSibling(Dali::Accessibility::Accessible* obj, Dali::Accessibility::Accessible* start, Dali::Accessibility::Accessible* root, unsigned char forward); + Dali::Accessibility::Component* CalculateNavigableAccessibleAtPoint(Dali::Accessibility::Accessible* root, Dali::Accessibility::Point p, Dali::Accessibility::CoordType cType, unsigned int maxRecursionDepth); + Dali::Accessibility::Component* GetObjectInRelation(Dali::Accessibility::Accessible* obj, Dali::Accessibility::RelationType ralationType); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_ACCESSIBLE_H diff --git a/dali/internal/accessibility/bridge/bridge-action.cpp b/dali/internal/accessibility/bridge/bridge-action.cpp index 47c5eae..5f6189d 100644 --- a/dali/internal/accessibility/bridge/bridge-action.cpp +++ b/dali/internal/accessibility/bridge/bridge-action.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,67 +27,67 @@ void BridgeAction::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceAction}; - AddGetPropertyToInterface( desc, "NActions", &BridgeAction::GetActionCount ); + AddGetPropertyToInterface(desc, "NActions", &BridgeAction::GetActionCount); - AddFunctionToInterface( desc, "GetName", &BridgeAction::GetActionName ); - AddFunctionToInterface( desc, "GetLocalizedName", &BridgeAction::GetLocalizedActionName ); - AddFunctionToInterface( desc, "GetDescription", &BridgeAction::GetActionDescription ); - AddFunctionToInterface( desc, "GetKeyBinding", &BridgeAction::GetActionKeyBinding ); - AddFunctionToInterface( desc, "DoAction", &BridgeAction::DoAction ); - AddFunctionToInterface( desc, "DoActionName", &BridgeAction::DoActionName ); - dbusServer.addInterface( "/", desc, true ); + AddFunctionToInterface(desc, "GetName", &BridgeAction::GetActionName); + AddFunctionToInterface(desc, "GetLocalizedName", &BridgeAction::GetLocalizedActionName); + AddFunctionToInterface(desc, "GetDescription", &BridgeAction::GetActionDescription); + AddFunctionToInterface(desc, "GetKeyBinding", &BridgeAction::GetActionKeyBinding); + AddFunctionToInterface(desc, "DoAction", &BridgeAction::DoAction); + AddFunctionToInterface(desc, "DoActionName", &BridgeAction::DoActionName); + dbusServer.addInterface("/", desc, true); } Action* BridgeAction::FindSelf() const { auto s = BridgeBase::FindSelf(); - assert( s ); - auto s2 = dynamic_cast< Action* >( s ); - if( !s2 ) + assert(s); + auto s2 = dynamic_cast(s); + if(!s2) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Action interface"}; return s2; } -DBus::ValueOrError< std::string > BridgeAction::GetActionName( int32_t index ) +DBus::ValueOrError BridgeAction::GetActionName(int32_t index) { - return FindSelf()->GetActionName( index ); + return FindSelf()->GetActionName(index); } -DBus::ValueOrError< std::string > BridgeAction::GetLocalizedActionName( int32_t index ) +DBus::ValueOrError BridgeAction::GetLocalizedActionName(int32_t index) { - return FindSelf()->GetLocalizedActionName( index ); + return FindSelf()->GetLocalizedActionName(index); } -DBus::ValueOrError< std::string > BridgeAction::GetActionDescription( int32_t index ) +DBus::ValueOrError BridgeAction::GetActionDescription(int32_t index) { - return FindSelf()->GetActionDescription( index ); + return FindSelf()->GetActionDescription(index); } -DBus::ValueOrError< std::string > BridgeAction::GetActionKeyBinding( int32_t index ) +DBus::ValueOrError BridgeAction::GetActionKeyBinding(int32_t index) { - return FindSelf()->GetActionKeyBinding( index ); + return FindSelf()->GetActionKeyBinding(index); } -DBus::ValueOrError< int32_t > BridgeAction::GetActionCount() +DBus::ValueOrError BridgeAction::GetActionCount() { return FindSelf()->GetActionCount(); ; } -DBus::ValueOrError< bool > BridgeAction::DoAction( int32_t index ) +DBus::ValueOrError BridgeAction::DoAction(int32_t index) { - return FindSelf()->DoAction( index ); + return FindSelf()->DoAction(index); } -DBus::ValueOrError< bool > BridgeAction::DoActionName( std::string name ) +DBus::ValueOrError BridgeAction::DoActionName(std::string name) { auto self = FindSelf(); - auto cnt = self->GetActionCount(); - for( auto i = 0u; i < cnt; ++i ) + auto cnt = self->GetActionCount(); + for(auto i = 0u; i < cnt; ++i) { - if( self->GetActionName( i ) == name ) + if(self->GetActionName(i) == name) { - return self->DoAction( i ); + return self->DoAction(i); } } throw std::domain_error{"object " + self->GetAddress().ToString() + " doesn't have action '" + name + "'"}; diff --git a/dali/internal/accessibility/bridge/bridge-action.h b/dali/internal/accessibility/bridge/bridge-action.h index a47eb82..276d876 100644 --- a/dali/internal/accessibility/bridge/bridge-action.h +++ b/dali/internal/accessibility/bridge/bridge-action.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_ACTION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,13 +35,13 @@ protected: Dali::Accessibility::Action* FindSelf() const; public: - DBus::ValueOrError< std::string > GetActionName( int32_t index ); - DBus::ValueOrError< std::string > GetLocalizedActionName( int32_t index ); - DBus::ValueOrError< std::string > GetActionDescription( int32_t index ); - DBus::ValueOrError< std::string > GetActionKeyBinding( int32_t index ); - DBus::ValueOrError< int32_t > GetActionCount(); - DBus::ValueOrError< bool > DoAction( int32_t index ); - DBus::ValueOrError< bool > DoActionName( std::string name ); + DBus::ValueOrError GetActionName(int32_t index); + DBus::ValueOrError GetLocalizedActionName(int32_t index); + DBus::ValueOrError GetActionDescription(int32_t index); + DBus::ValueOrError GetActionKeyBinding(int32_t index); + DBus::ValueOrError GetActionCount(); + DBus::ValueOrError DoAction(int32_t index); + DBus::ValueOrError DoActionName(std::string name); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_ACTION_H diff --git a/dali/internal/accessibility/bridge/bridge-base.cpp b/dali/internal/accessibility/bridge/bridge-base.cpp index c8f01c6..9f1da75 100644 --- a/dali/internal/accessibility/bridge/bridge-base.cpp +++ b/dali/internal/accessibility/bridge/bridge-base.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,15 +38,15 @@ BridgeBase::BridgeBase() { } -void BridgeBase::addFilteredEvent( FilteredEvents kind, Dali::Accessibility::Accessible* obj, float delay, std::function functor ) +void BridgeBase::addFilteredEvent(FilteredEvents kind, Dali::Accessibility::Accessible* obj, float delay, std::function functor) { - if( delay < 0 ) + if(delay < 0) { delay = 0; } - auto it = filteredEvents.insert({ { kind, obj }, { static_cast(delay * 10), {} } }); - if (it.second) + auto it = filteredEvents.insert({{kind, obj}, {static_cast(delay * 10), {}}}); + if(it.second) { functor(); } @@ -55,7 +55,7 @@ void BridgeBase::addFilteredEvent( FilteredEvents kind, Dali::Accessibility::Acc it.first->second.second = std::move(functor); } - if (!tickTimer) + if(!tickTimer) { tickTimer = Dali::Timer::New(100); tickTimer.TickSignal().Connect(this, &BridgeBase::tickFilteredEvents); @@ -64,15 +64,15 @@ void BridgeBase::addFilteredEvent( FilteredEvents kind, Dali::Accessibility::Acc bool BridgeBase::tickFilteredEvents() { - for(auto it = filteredEvents.begin(); it != filteredEvents.end(); ) + for(auto it = filteredEvents.begin(); it != filteredEvents.end();) { - if (it->second.first) + if(it->second.first) { --it->second.first; } else { - if (it->second.second) + if(it->second.second) { it->second.second(); it->second.second = {}; @@ -90,31 +90,31 @@ bool BridgeBase::tickFilteredEvents() BridgeBase::ForceUpResult BridgeBase::ForceUp() { - if( Bridge::ForceUp() == ForceUpResult::ALREADY_UP ) + if(Bridge::ForceUp() == ForceUpResult::ALREADY_UP) { return ForceUpResult::ALREADY_UP; } auto proxy = DBus::DBusClient{dbusLocators::atspi::BUS, dbusLocators::atspi::OBJ_PATH, dbusLocators::atspi::BUS_INTERFACE, DBus::ConnectionType::SESSION}; - auto addr = proxy.method< std::string() >( dbusLocators::atspi::GET_ADDRESS ).call(); + auto addr = proxy.method(dbusLocators::atspi::GET_ADDRESS).call(); - if( !addr ) + if(!addr) { - throw std::domain_error{std::string( "failed at call '" ) + dbusLocators::atspi::GET_ADDRESS + "': " + addr.getError().message}; + throw std::domain_error{std::string("failed at call '") + dbusLocators::atspi::GET_ADDRESS + "': " + addr.getError().message}; } - con = DBusWrapper::Installed()->eldbus_address_connection_get_impl( std::get< 0 >( addr ) ); - data->busName = DBus::getConnectionName( con ); - dbusServer = { con }; + con = DBusWrapper::Installed()->eldbus_address_connection_get_impl(std::get<0>(addr)); + data->busName = DBus::getConnectionName(con); + dbusServer = {con}; { DBus::DBusInterfaceDescription desc{"org.a11y.atspi.Cache"}; - AddFunctionToInterface( desc, "GetItems", &BridgeBase::GetItems ); - dbusServer.addInterface( "/org/a11y/atspi/cache", desc ); + AddFunctionToInterface(desc, "GetItems", &BridgeBase::GetItems); + dbusServer.addInterface("/org/a11y/atspi/cache", desc); } { DBus::DBusInterfaceDescription desc{"org.a11y.atspi.Application"}; - AddGetSetPropertyToInterface( desc, "Id", &BridgeBase::IdGet, &BridgeBase::IdSet ); - dbusServer.addInterface( AtspiPath, desc ); + AddGetSetPropertyToInterface(desc, "Id", &BridgeBase::IdGet, &BridgeBase::IdSet); + dbusServer.addInterface(AtspiPath, desc); } return ForceUpResult::JUST_STARTED; @@ -124,7 +124,7 @@ void BridgeBase::ForceDown() { Bridge::ForceDown(); dbusServer = {}; - con = {}; + con = {}; } const std::string& BridgeBase::GetBusName() const @@ -133,64 +133,64 @@ const std::string& BridgeBase::GetBusName() const return data ? data->busName : empty; } -Accessible* BridgeBase::FindByPath( const std::string& name ) const +Accessible* BridgeBase::FindByPath(const std::string& name) const { try { - return Find( name ); + return Find(name); } - catch( std::domain_error& ) + catch(std::domain_error&) { return nullptr; } } -void BridgeBase::AddPopup( Accessible* obj ) +void BridgeBase::AddPopup(Accessible* obj) { - if( std::find( popups.begin(), popups.end(), obj ) != popups.end() ) + if(std::find(popups.begin(), popups.end(), obj) != popups.end()) { return; } - popups.push_back( obj ); - if (IsUp()) + popups.push_back(obj); + if(IsUp()) { - obj->Emit( WindowEvent::ACTIVATE, 0 ); + obj->Emit(WindowEvent::ACTIVATE, 0); } } -void BridgeBase::RemovePopup( Accessible* obj ) +void BridgeBase::RemovePopup(Accessible* obj) { - auto it = std::find( popups.begin(), popups.end(), obj ); - if( it == popups.end() ) + auto it = std::find(popups.begin(), popups.end(), obj); + if(it == popups.end()) { return; } - popups.erase( it ); - if (IsUp()) + popups.erase(it); + if(IsUp()) { - obj->Emit( WindowEvent::DEACTIVATE, 0 ); - if( popups.empty() ) + obj->Emit(WindowEvent::DEACTIVATE, 0); + if(popups.empty()) { - application.children.back()->Emit( WindowEvent::ACTIVATE, 0 ); + application.children.back()->Emit(WindowEvent::ACTIVATE, 0); } else { - popups.back()->Emit( WindowEvent::ACTIVATE, 0 ); + popups.back()->Emit(WindowEvent::ACTIVATE, 0); } } } -void BridgeBase::AddTopLevelWindow( Accessible* root ) +void BridgeBase::AddTopLevelWindow(Accessible* root) { - application.children.push_back( root ); - SetIsOnRootLevel( root ); + application.children.push_back(root); + SetIsOnRootLevel(root); } -void BridgeBase::RemoveTopLevelWindow( Accessible* root ) +void BridgeBase::RemoveTopLevelWindow(Accessible* root) { for(auto i = 0u; i < application.children.size(); ++i) { - if( application.children[i] == root ) + if(application.children[i] == root) { application.children.erase(application.children.begin() + i); break; @@ -198,58 +198,58 @@ void BridgeBase::RemoveTopLevelWindow( Accessible* root ) } } -std::string BridgeBase::StripPrefix( const std::string& path ) +std::string BridgeBase::StripPrefix(const std::string& path) { - auto size = strlen( AtspiPath ); - return path.substr( size + 1 ); + auto size = strlen(AtspiPath); + return path.substr(size + 1); } -Accessible* BridgeBase::Find( const std::string& path ) const +Accessible* BridgeBase::Find(const std::string& path) const { - if( path == "root" ) + if(path == "root") { return &application; } - void* p; - std::istringstream tmp{ path }; - if (! ( tmp >> p) ) + void* p; + std::istringstream tmp{path}; + if(!(tmp >> p)) { throw std::domain_error{"invalid path '" + path + "'"}; } - auto it = data->knownObjects.find( static_cast( p ) ); - if( it == data->knownObjects.end() ) + auto it = data->knownObjects.find(static_cast(p)); + if(it == data->knownObjects.end()) { throw std::domain_error{"unknown object '" + path + "'"}; } - return static_cast( p ); + return static_cast(p); } -Accessible* BridgeBase::Find( const Address& ptr ) const +Accessible* BridgeBase::Find(const Address& ptr) const { - assert( ptr.GetBus() == data->busName ); - return Find( ptr.GetPath() ); + assert(ptr.GetBus() == data->busName); + return Find(ptr.GetPath()); } Accessible* BridgeBase::FindSelf() const { - auto pth = DBus::DBusServer::getCurrentObjectPath(); - auto size = strlen( AtspiPath ); - if( pth.size() <= size ) + auto pth = DBus::DBusServer::getCurrentObjectPath(); + auto size = strlen(AtspiPath); + if(pth.size() <= size) { throw std::domain_error{"invalid path '" + pth + "'"}; } - if( pth.substr( 0, size ) != AtspiPath ) + if(pth.substr(0, size) != AtspiPath) { throw std::domain_error{"invalid path '" + pth + "'"}; } - if( pth[size] != '/' ) + if(pth[size] != '/') { throw std::domain_error{"invalid path '" + pth + "'"}; } - return Find( StripPrefix( pth ) ); + return Find(StripPrefix(pth)); } -void BridgeBase::IdSet( int id ) +void BridgeBase::IdSet(int id) { this->id = id; } @@ -259,39 +259,38 @@ int BridgeBase::IdGet() return this->id; } -auto BridgeBase::GetItems() -> DBus::ValueOrError< std::vector< CacheElementType > > +auto BridgeBase::GetItems() -> DBus::ValueOrError > { auto root = &application; - std::vector< CacheElementType > res; + std::vector res; - std::function< void(Accessible*) > proc = - [&]( Accessible* item ) - { - res.emplace_back( std::move( CreateCacheElement( root ) ) ); - for( auto i = 0u; i < item->GetChildCount(); ++i ) + std::function proc = + [&](Accessible* item) { + res.emplace_back(std::move(CreateCacheElement(root))); + for(auto i = 0u; i < item->GetChildCount(); ++i) { - proc( item->GetChildAtIndex( i ) ); + proc(item->GetChildAtIndex(i)); } }; return res; } -auto BridgeBase::CreateCacheElement( Accessible* item ) -> CacheElementType +auto BridgeBase::CreateCacheElement(Accessible* item) -> CacheElementType { - if( !item ) + if(!item) { return {}; } - auto root = &application; + auto root = &application; auto parent = item->GetParent(); - std::vector< Address > children; - for( auto i = 0u; i < item->GetChildCount(); ++i ) + std::vector
children; + for(auto i = 0u; i < item->GetChildCount(); ++i) { - children.emplace_back( item->GetChildAtIndex( i )->GetAddress() ); + children.emplace_back(item->GetChildAtIndex(i)->GetAddress()); } return std::make_tuple( @@ -303,7 +302,5 @@ auto BridgeBase::CreateCacheElement( Accessible* item ) -> CacheElementType item->GetName(), item->GetRole(), item->GetDescription(), - item->GetStates().GetRawData() - ); + item->GetStates().GetRawData()); } - diff --git a/dali/internal/accessibility/bridge/bridge-base.h b/dali/internal/accessibility/bridge/bridge-base.h index 5ba0ee0..e14f864 100644 --- a/dali/internal/accessibility/bridge/bridge-base.h +++ b/dali/internal/accessibility/bridge/bridge-base.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_BASE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ class AppAccessible : public virtual Dali::Accessibility::Accessible, public vir { public: Dali::Accessibility::EmptyAccessibleWithAddress parent; - std::vector< Dali::Accessibility::Accessible* > children; - std::string name; + std::vector children; + std::string name; std::string GetName() override { @@ -52,11 +52,11 @@ public: return children.size(); } - Dali::Accessibility::Accessible* GetChildAtIndex( size_t index ) override + Dali::Accessibility::Accessible* GetChildAtIndex(size_t index) override { auto s = children.size(); - if( index >= s ) - throw std::domain_error{"invalid index " + std::to_string( index ) + " for object with " + std::to_string( s ) + " children"}; + if(index >= s) + throw std::domain_error{"invalid index " + std::to_string(index) + " for object with " + std::to_string(s) + " children"}; return children[index]; } @@ -85,36 +85,38 @@ public: return children.empty() ? nullptr : children[0]; } - bool DoGesture(const Dali::Accessibility::GestureInfo &gestureInfo) override + bool DoGesture(const Dali::Accessibility::GestureInfo& gestureInfo) override { - return false; + return false; } std::vector GetRelationSet() override { - return {}; + return {}; } - Dali::Accessibility::Address GetAddress() override { - return { "", "root" }; + Dali::Accessibility::Address GetAddress() override + { + return {"", "root"}; } - }; - -enum class FilteredEvents { +enum class FilteredEvents +{ boundsChanged }; - -namespace std { - template <> struct hash> { - size_t operator () (std::pair v) const { - return (static_cast(v.first) * 131) ^ reinterpret_cast(v.second); - } - }; -} - +namespace std +{ +template<> +struct hash> +{ + size_t operator()(std::pair v) const + { + return (static_cast(v.first) * 131) ^ reinterpret_cast(v.second); + } +}; +} // namespace std class BridgeBase : public Dali::Accessibility::Bridge, public Dali::ConnectionTracker { @@ -123,172 +125,180 @@ class BridgeBase : public Dali::Accessibility::Bridge, public Dali::ConnectionTr bool tickFilteredEvents(); public: - void addFilteredEvent(FilteredEvents kind, Dali::Accessibility::Accessible* obj, float delay, std::function functor); const std::string& GetBusName() const override; - void AddTopLevelWindow( Dali::Accessibility::Accessible* window ) override; - void RemoveTopLevelWindow( Dali::Accessibility::Accessible* window ) override; - void AddPopup( Dali::Accessibility::Accessible* ) override; - void RemovePopup( Dali::Accessibility::Accessible* ) override; + void AddTopLevelWindow(Dali::Accessibility::Accessible* window) override; + void RemoveTopLevelWindow(Dali::Accessibility::Accessible* window) override; + void AddPopup(Dali::Accessibility::Accessible*) override; + void RemovePopup(Dali::Accessibility::Accessible*) override; Dali::Accessibility::Accessible* GetApplication() const override { return &application; } - template < typename SELF, typename... RET, typename... ARGS > + template void AddFunctionToInterface( - DBus::DBusInterfaceDescription& desc, const std::string& funcName, - DBus::ValueOrError< RET... > ( SELF::*funcPtr )( ARGS... ) ) + DBus::DBusInterfaceDescription& desc, const std::string& funcName, DBus::ValueOrError (SELF::*funcPtr)(ARGS...)) { - if ( auto self = dynamic_cast< SELF* >( this ) ) - desc.addMethod< DBus::ValueOrError< RET... >( ARGS... ) >( funcName, - [=]( ARGS... args ) -> DBus::ValueOrError< RET... > { - try - { - return ( self->*funcPtr )( std::move( args )... ); - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - } ); + if(auto self = dynamic_cast(this)) + desc.addMethod(ARGS...)>(funcName, + [=](ARGS... args) -> DBus::ValueOrError { + try + { + return (self->*funcPtr)(std::move(args)...); + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }); } - template < typename T, typename SELF > - void AddGetPropertyToInterface( DBus::DBusInterfaceDescription& desc, - const std::string& funcName, T ( SELF::*funcPtr )() ) + template + void AddGetPropertyToInterface(DBus::DBusInterfaceDescription& desc, + const std::string& funcName, + T (SELF::*funcPtr)()) { - if ( auto self = dynamic_cast< SELF* >( this ) ) - desc.addProperty< T >( funcName, - [=]() -> DBus::ValueOrError< T > { - try - { - return ( self->*funcPtr )(); - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - }, - {} ); + if(auto self = dynamic_cast(this)) + desc.addProperty(funcName, + [=]() -> DBus::ValueOrError { + try + { + return (self->*funcPtr)(); + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }, + {}); } - template < typename T, typename SELF > - void AddSetPropertyToInterface( DBus::DBusInterfaceDescription& desc, - const std::string& funcName, void ( SELF::*funcPtr )( T ) ) + template + void AddSetPropertyToInterface(DBus::DBusInterfaceDescription& desc, + const std::string& funcName, + void (SELF::*funcPtr)(T)) { - if ( auto self = dynamic_cast< SELF* >( this ) ) - desc.addProperty< T >( funcName, {}, - [=]( T t ) -> DBus::ValueOrError< void > { - try - { - ( self->*funcPtr )( std::move( t ) ); - return {}; - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - } ); + if(auto self = dynamic_cast(this)) + desc.addProperty(funcName, {}, [=](T t) -> DBus::ValueOrError { + try + { + (self->*funcPtr)(std::move(t)); + return {}; + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }); } - template < typename T, typename T1, typename SELF > - void AddGetSetPropertyToInterface( DBus::DBusInterfaceDescription& desc, - const std::string& funcName, T1 ( SELF::*funcPtrGet )(), DBus::ValueOrError< void > ( SELF::*funcPtrSet )( T ) ) + template + void AddGetSetPropertyToInterface(DBus::DBusInterfaceDescription& desc, + const std::string& funcName, + T1 (SELF::*funcPtrGet)(), + DBus::ValueOrError (SELF::*funcPtrSet)(T)) { - if ( auto self = dynamic_cast< SELF* >( this ) ) - desc.addProperty< T >( funcName, - [=]() -> DBus::ValueOrError< T > { - try - { - return ( self->*funcPtrGet )(); - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - }, - [=]( T t ) -> DBus::ValueOrError< void > { - try - { - ( self->*funcPtrSet )( std::move( t ) ); - return {}; - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - } ); + if(auto self = dynamic_cast(this)) + desc.addProperty( + funcName, + [=]() -> DBus::ValueOrError { + try + { + return (self->*funcPtrGet)(); + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }, + [=](T t) -> DBus::ValueOrError { + try + { + (self->*funcPtrSet)(std::move(t)); + return {}; + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }); } - template < typename T, typename T1, typename SELF > - void AddGetSetPropertyToInterface( DBus::DBusInterfaceDescription& desc, - const std::string& funcName, T1 ( SELF::*funcPtrGet )(), void ( SELF::*funcPtrSet )( T ) ) + template + void AddGetSetPropertyToInterface(DBus::DBusInterfaceDescription& desc, + const std::string& funcName, + T1 (SELF::*funcPtrGet)(), + void (SELF::*funcPtrSet)(T)) { - if ( auto self = dynamic_cast< SELF* >( this ) ) - desc.addProperty< T >( funcName, - [=]() -> DBus::ValueOrError< T > { - try - { - return ( self->*funcPtrGet )(); - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - }, - [=]( T t ) -> DBus::ValueOrError< void > { - try - { - ( self->*funcPtrSet )( std::move( t ) ); - return {}; - } - catch( std::domain_error& e ) - { - return DBus::Error{e.what()}; - } - } ); + if(auto self = dynamic_cast(this)) + desc.addProperty( + funcName, + [=]() -> DBus::ValueOrError { + try + { + return (self->*funcPtrGet)(); + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }, + [=](T t) -> DBus::ValueOrError { + try + { + (self->*funcPtrSet)(std::move(t)); + return {}; + } + catch(std::domain_error& e) + { + return DBus::Error{e.what()}; + } + }); } - static std::string StripPrefix( const std::string& path ); + static std::string StripPrefix(const std::string& path); - Dali::Accessibility::Accessible* Find( const std::string& path ) const; - Dali::Accessibility::Accessible* Find( const Dali::Accessibility::Address& ptr ) const; + Dali::Accessibility::Accessible* Find(const std::string& path) const; + Dali::Accessibility::Accessible* Find(const Dali::Accessibility::Address& ptr) const; Dali::Accessibility::Accessible* FindSelf() const; - Dali::Accessibility::Accessible* FindByPath( const std::string& name ) const override; - void SetApplicationName( std::string name ) override + Dali::Accessibility::Accessible* FindByPath(const std::string& name) const override; + void SetApplicationName(std::string name) override { - application.name = std::move( name ); + application.name = std::move(name); } protected: - mutable AppAccessible application; + mutable AppAccessible application; std::vector popups; + private: - void IdSet( int id ); - int IdGet(); + void IdSet(int id); + int IdGet(); using CacheElementType = std::tuple< - Dali::Accessibility::Address, Dali::Accessibility::Address, Dali::Accessibility::Address, - std::vector< Dali::Accessibility::Address >, - std::vector< std::string >, - std::string, - Dali::Accessibility::Role, - std::string, - std::array< uint32_t, 2 > >; - DBus::ValueOrError< std::vector< CacheElementType > > GetItems(); - CacheElementType CreateCacheElement( Dali::Accessibility::Accessible* item ); + Dali::Accessibility::Address, + Dali::Accessibility::Address, + Dali::Accessibility::Address, + std::vector, + std::vector, + std::string, + Dali::Accessibility::Role, + std::string, + std::array>; + DBus::ValueOrError> GetItems(); + CacheElementType CreateCacheElement(Dali::Accessibility::Accessible* item); protected: BridgeBase(); virtual ~BridgeBase(); ForceUpResult ForceUp() override; - void ForceDown() override; + void ForceDown() override; - DBus::DBusServer dbusServer; + DBus::DBusServer dbusServer; DBusWrapper::ConnectionPtr con; - int id = 0; + int id = 0; }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_BASE_H diff --git a/dali/internal/accessibility/bridge/bridge-collection.cpp b/dali/internal/accessibility/bridge/bridge-collection.cpp index 022a310..b2e0f06 100644 --- a/dali/internal/accessibility/bridge/bridge-collection.cpp +++ b/dali/internal/accessibility/bridge/bridge-collection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,16 +29,16 @@ using namespace Dali::Accessibility; void BridgeCollection::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceCollection}; - AddFunctionToInterface( desc, "GetMatches", &BridgeCollection::GetMatches ); - dbusServer.addInterface( "/", desc, true ); + AddFunctionToInterface(desc, "GetMatches", &BridgeCollection::GetMatches); + dbusServer.addInterface("/", desc, true); } Collection* BridgeCollection::FindSelf() const { auto s = BridgeBase::FindSelf(); - assert( s ); - auto s2 = dynamic_cast< Collection* >( s ); - if( !s2 ) + assert(s); + auto s2 = dynamic_cast(s); + if(!s2) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Collection interface"}; return s2; } @@ -63,9 +63,9 @@ struct BridgeCollection::Comparer FIRST_NOT_FOUND }; - static Mode ConvertToMatchType( int32_t mode ) + static Mode ConvertToMatchType(int32_t mode) { - switch( mode ) + switch(mode) { case ATSPI_Collection_MATCH_INVALID: { @@ -93,31 +93,38 @@ struct BridgeCollection::Comparer struct ComparerInterfaces { - std::unordered_set< std::string > object; - std::vector< std::string > requested; - Mode mode = Mode::INVALID; + std::unordered_set object; + std::vector requested; + Mode mode = Mode::INVALID; - ComparerInterfaces( MatchRule* rule ) : mode( ConvertToMatchType( std::get< Index::InterfacesMatchType >( *rule ) ) ) + ComparerInterfaces(MatchRule* rule) + : mode(ConvertToMatchType(std::get(*rule))) { - requested = {std::get< Index::Interfaces >( *rule ).begin(), std::get< Index::Interfaces >( *rule ).end()}; + requested = {std::get(*rule).begin(), std::get(*rule).end()}; } - void Update( Accessible* obj ) + void Update(Accessible* obj) { object.clear(); - for( auto& q : obj->GetInterfaces() ) - object.insert( std::move( q ) ); + for(auto& q : obj->GetInterfaces()) + object.insert(std::move(q)); } - bool RequestEmpty() const { return requested.empty(); } - bool ObjectEmpty() const { return object.empty(); } - bool Compare( CompareFuncExit exit ) + bool RequestEmpty() const + { + return requested.empty(); + } + bool ObjectEmpty() const + { + return object.empty(); + } + bool Compare(CompareFuncExit exit) { bool foundAny = false; - for( auto& iname : requested ) + for(auto& iname : requested) { - bool found = ( object.find( iname ) != object.end() ); - if( found ) + bool found = (object.find(iname) != object.end()); + if(found) foundAny = true; - if( found == ( exit == CompareFuncExit::FIRST_FOUND ) ) + if(found == (exit == CompareFuncExit::FIRST_FOUND)) return found; } return foundAny; @@ -125,29 +132,36 @@ struct BridgeCollection::Comparer }; struct ComparerAttributes { - std::unordered_map< std::string, std::string > requested, object; - Mode mode = Mode::INVALID; + std::unordered_map requested, object; + Mode mode = Mode::INVALID; - ComparerAttributes( MatchRule* rule ) : mode( ConvertToMatchType( std::get< Index::AttributesMatchType >( *rule ) ) ) + ComparerAttributes(MatchRule* rule) + : mode(ConvertToMatchType(std::get(*rule))) { - requested = std::get< Index::Attributes >( *rule ); + requested = std::get(*rule); } - void Update( Accessible* obj ) + void Update(Accessible* obj) { object = obj->GetAttributes(); } - bool RequestEmpty() const { return requested.empty(); } - bool ObjectEmpty() const { return object.empty(); } - bool Compare( CompareFuncExit exit ) + bool RequestEmpty() const + { + return requested.empty(); + } + bool ObjectEmpty() const + { + return object.empty(); + } + bool Compare(CompareFuncExit exit) { bool foundAny = false; - for( auto& iname : requested ) + for(auto& iname : requested) { - auto it = object.find( iname.first ); + auto it = object.find(iname.first); bool found = it != object.end() && iname.second == it->second; - if( found ) + if(found) foundAny = true; - if( found == ( exit == CompareFuncExit::FIRST_FOUND ) ) + if(found == (exit == CompareFuncExit::FIRST_FOUND)) { return found; } @@ -157,25 +171,32 @@ struct BridgeCollection::Comparer }; struct ComparerRoles { - using Roles = BitSets< 4, Role >; + using Roles = BitSets<4, Role>; Roles requested, object; - Mode mode = Mode::INVALID; + Mode mode = Mode::INVALID; - ComparerRoles( MatchRule* rule ) : mode( ConvertToMatchType( std::get< Index::RolesMatchType >( *rule ) ) ) + ComparerRoles(MatchRule* rule) + : mode(ConvertToMatchType(std::get(*rule))) { - requested = Roles{std::get< Index::Roles >( *rule )}; + requested = Roles{std::get(*rule)}; } - void Update( Accessible* obj ) + void Update(Accessible* obj) { - object = {}; + object = {}; object[obj->GetRole()] = true; - assert( object ); + assert(object); + } + bool RequestEmpty() const + { + return !requested; + } + bool ObjectEmpty() const + { + return !object; } - bool RequestEmpty() const { return !requested; } - bool ObjectEmpty() const { return !object; } - bool Compare( CompareFuncExit exit ) + bool Compare(CompareFuncExit exit) { - switch( mode ) + switch(mode) { case Mode::INVALID: { @@ -184,15 +205,15 @@ struct BridgeCollection::Comparer case Mode::EMPTY: case Mode::ALL: { - return requested == ( object & requested ); + return requested == (object & requested); } case Mode::ANY: { - return bool( object & requested ); + return bool(object & requested); } case Mode::NONE: { - return bool( object & requested ); + return bool(object & requested); } } return false; @@ -201,21 +222,28 @@ struct BridgeCollection::Comparer struct ComparerStates { States requested, object; - Mode mode = Mode::INVALID; + Mode mode = Mode::INVALID; - ComparerStates( MatchRule* rule ) : mode( ConvertToMatchType( std::get< Index::StatesMatchType >( *rule ) ) ) + ComparerStates(MatchRule* rule) + : mode(ConvertToMatchType(std::get(*rule))) { - requested = States{std::get< Index::States >( *rule )}; + requested = States{std::get(*rule)}; } - void Update( Accessible* obj ) + void Update(Accessible* obj) { object = obj->GetStates(); } - bool RequestEmpty() const { return !requested; } - bool ObjectEmpty() const { return !object; } - bool Compare( CompareFuncExit exit ) + bool RequestEmpty() const + { + return !requested; + } + bool ObjectEmpty() const { - switch( mode ) + return !object; + } + bool Compare(CompareFuncExit exit) + { + switch(mode) { case Mode::INVALID: { @@ -224,54 +252,54 @@ struct BridgeCollection::Comparer case Mode::EMPTY: case Mode::ALL: { - return requested == ( object & requested ); + return requested == (object & requested); } case Mode::ANY: { - return bool( object & requested ); + return bool(object & requested); } case Mode::NONE: { - return bool( object & requested ); + return bool(object & requested); } } return false; } }; - template < typename T > - bool compareFunc( T& cmp, Accessible* obj ) + template + bool compareFunc(T& cmp, Accessible* obj) { - if( cmp.mode == Mode::INVALID ) + if(cmp.mode == Mode::INVALID) return true; - cmp.Update( obj ); - switch( cmp.mode ) + cmp.Update(obj); + switch(cmp.mode) { case Mode::ANY: { - if( cmp.RequestEmpty() || cmp.ObjectEmpty() ) + if(cmp.RequestEmpty() || cmp.ObjectEmpty()) return false; break; } case Mode::ALL: { - if( cmp.RequestEmpty() ) + if(cmp.RequestEmpty()) return true; - if( cmp.ObjectEmpty() ) + if(cmp.ObjectEmpty()) return false; break; } case Mode::NONE: { - if( cmp.RequestEmpty() || cmp.ObjectEmpty() ) + if(cmp.RequestEmpty() || cmp.ObjectEmpty()) return true; break; } case Mode::EMPTY: { - if( cmp.RequestEmpty() && cmp.ObjectEmpty() ) + if(cmp.RequestEmpty() && cmp.ObjectEmpty()) return true; - if( cmp.RequestEmpty() || cmp.ObjectEmpty() ) + if(cmp.RequestEmpty() || cmp.ObjectEmpty()) return false; break; } @@ -281,24 +309,24 @@ struct BridgeCollection::Comparer } } - switch( cmp.mode ) + switch(cmp.mode) { case Mode::EMPTY: case Mode::ALL: { - if( !cmp.Compare( CompareFuncExit::FIRST_NOT_FOUND ) ) + if(!cmp.Compare(CompareFuncExit::FIRST_NOT_FOUND)) return false; break; } case Mode::ANY: { - if( cmp.Compare( CompareFuncExit::FIRST_FOUND ) ) + if(cmp.Compare(CompareFuncExit::FIRST_FOUND)) return true; break; } case Mode::NONE: { - if( cmp.Compare( CompareFuncExit::FIRST_FOUND ) ) + if(cmp.Compare(CompareFuncExit::FIRST_FOUND)) return false; break; } @@ -307,7 +335,7 @@ struct BridgeCollection::Comparer return true; } } - switch( cmp.mode ) + switch(cmp.mode) { case Mode::EMPTY: case Mode::ALL: @@ -329,40 +357,46 @@ struct BridgeCollection::Comparer ComparerInterfaces ci; ComparerAttributes ca; - ComparerRoles cr; - ComparerStates cs; + ComparerRoles cr; + ComparerStates cs; - Comparer( MatchRule* mr ) : ci( mr ), ca( mr ), cr( mr ), cs( mr ) {} + Comparer(MatchRule* mr) + : ci(mr), + ca(mr), + cr(mr), + cs(mr) + { + } - bool operator()( Accessible* obj ) + bool operator()(Accessible* obj) { - return compareFunc( ci, obj ) && - compareFunc( ca, obj ) && - compareFunc( cr, obj ) && - compareFunc( cs, obj ); + return compareFunc(ci, obj) && + compareFunc(ca, obj) && + compareFunc(cr, obj) && + compareFunc(cs, obj); } }; -void BridgeCollection::VisitNodes( Accessible* obj, std::vector< Accessible* >& result, Comparer& cmp, size_t maxCount ) +void BridgeCollection::VisitNodes(Accessible* obj, std::vector& result, Comparer& cmp, size_t maxCount) { - if( maxCount > 0 && result.size() >= maxCount ) + if(maxCount > 0 && result.size() >= maxCount) return; - if( cmp( obj ) ) - result.emplace_back( obj ); + if(cmp(obj)) + result.emplace_back(obj); - for( auto i = 0u; i < obj->GetChildCount(); ++i ) - VisitNodes( obj->GetChildAtIndex( i ), result, cmp, maxCount ); + for(auto i = 0u; i < obj->GetChildCount(); ++i) + VisitNodes(obj->GetChildAtIndex(i), result, cmp, maxCount); } -DBus::ValueOrError< std::vector< Accessible* > > BridgeCollection::GetMatches( MatchRule rule, uint32_t sortBy, int32_t count, bool traverse ) +DBus::ValueOrError > BridgeCollection::GetMatches(MatchRule rule, uint32_t sortBy, int32_t count, bool traverse) { - std::vector< Accessible* > res; - auto self = BridgeBase::FindSelf(); - auto matcher = Comparer{&rule}; - VisitNodes( self, res, matcher, count ); + std::vector res; + auto self = BridgeBase::FindSelf(); + auto matcher = Comparer{&rule}; + VisitNodes(self, res, matcher, count); - switch( static_cast< SortOrder >( sortBy ) ) + switch(static_cast(sortBy)) { case SortOrder::CANONICAL: { @@ -371,7 +405,7 @@ DBus::ValueOrError< std::vector< Accessible* > > BridgeCollection::GetMatches( M case SortOrder::REVERSE_CANONICAL: { - std::reverse( res.begin(), res.end() ); + std::reverse(res.begin(), res.end()); break; } diff --git a/dali/internal/accessibility/bridge/bridge-collection.h b/dali/internal/accessibility/bridge/bridge-collection.h index c4a279d..ad6153a 100644 --- a/dali/internal/accessibility/bridge/bridge-collection.h +++ b/dali/internal/accessibility/bridge/bridge-collection.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_COLLECTION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ class BridgeCollection : public virtual BridgeBase { private: struct Comparer; - static void VisitNodes( Dali::Accessibility::Accessible* obj, std::vector< Dali::Accessibility::Accessible* >& result, Comparer& cmp, size_t maxCount ); + static void VisitNodes(Dali::Accessibility::Accessible* obj, std::vector& result, Comparer& cmp, size_t maxCount); protected: BridgeCollection() = default; @@ -42,11 +42,15 @@ protected: public: using MatchRule = std::tuple< - std::array< int32_t, 2 >, int32_t, - std::unordered_map< std::string, std::string >, int32_t, - std::array< int32_t, 4 >, int32_t, - std::vector< std::string >, int32_t, - bool >; + std::array, + int32_t, + std::unordered_map, + int32_t, + std::array, + int32_t, + std::vector, + int32_t, + bool>; struct Index { enum @@ -62,7 +66,7 @@ public: }; }; - DBus::ValueOrError< std::vector< Dali::Accessibility::Accessible* > > GetMatches( MatchRule rule, uint32_t sortBy, int32_t count, bool traverse ); + DBus::ValueOrError > GetMatches(MatchRule rule, uint32_t sortBy, int32_t count, bool traverse); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_COLLECTION_H diff --git a/dali/internal/accessibility/bridge/bridge-component.cpp b/dali/internal/accessibility/bridge/bridge-component.cpp index 1e65ddc..bd85a23 100644 --- a/dali/internal/accessibility/bridge/bridge-component.cpp +++ b/dali/internal/accessibility/bridge/bridge-component.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,74 +32,74 @@ BridgeComponent::BridgeComponent() void BridgeComponent::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceComponent}; - AddFunctionToInterface( desc, "Contains", &BridgeComponent::Contains ); - AddFunctionToInterface( desc, "GetAccessibleAtPoint", &BridgeComponent::GetAccessibleAtPoint ); - AddFunctionToInterface( desc, "GetExtents", &BridgeComponent::GetExtents ); - AddFunctionToInterface( desc, "GetPosition", &BridgeComponent::GetPosition ); - AddFunctionToInterface( desc, "GetSize", &BridgeComponent::GetSize ); - AddFunctionToInterface( desc, "GetLayer", &BridgeComponent::GetLayer ); - AddFunctionToInterface( desc, "GetAlpha", &BridgeComponent::GetAlpha ); - AddFunctionToInterface( desc, "GetMDIZOrder", &BridgeComponent::GetMdiZOrder ); - AddFunctionToInterface( desc, "GrabHighlight", &BridgeComponent::GrabHighlight ); - AddFunctionToInterface( desc, "GrabFocus", &BridgeComponent::GrabFocus ); - AddFunctionToInterface( desc, "ClearHighlight", &BridgeComponent::ClearHighlight ); - dbusServer.addInterface( "/", desc, true ); + AddFunctionToInterface(desc, "Contains", &BridgeComponent::Contains); + AddFunctionToInterface(desc, "GetAccessibleAtPoint", &BridgeComponent::GetAccessibleAtPoint); + AddFunctionToInterface(desc, "GetExtents", &BridgeComponent::GetExtents); + AddFunctionToInterface(desc, "GetPosition", &BridgeComponent::GetPosition); + AddFunctionToInterface(desc, "GetSize", &BridgeComponent::GetSize); + AddFunctionToInterface(desc, "GetLayer", &BridgeComponent::GetLayer); + AddFunctionToInterface(desc, "GetAlpha", &BridgeComponent::GetAlpha); + AddFunctionToInterface(desc, "GetMDIZOrder", &BridgeComponent::GetMdiZOrder); + AddFunctionToInterface(desc, "GrabHighlight", &BridgeComponent::GrabHighlight); + AddFunctionToInterface(desc, "GrabFocus", &BridgeComponent::GrabFocus); + AddFunctionToInterface(desc, "ClearHighlight", &BridgeComponent::ClearHighlight); + dbusServer.addInterface("/", desc, true); } Component* BridgeComponent::FindSelf() const { auto s = BridgeBase::FindSelf(); - assert( s ); - auto s2 = dynamic_cast< Component* >( s ); - if( !s2 ) + assert(s); + auto s2 = dynamic_cast(s); + if(!s2) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Component interface"}; return s2; } -DBus::ValueOrError< bool > BridgeComponent::Contains( int32_t x, int32_t y, uint32_t coordType ) +DBus::ValueOrError BridgeComponent::Contains(int32_t x, int32_t y, uint32_t coordType) { - return FindSelf()->Contains( {x, y}, static_cast< CoordType >( coordType ) ); + return FindSelf()->Contains({x, y}, static_cast(coordType)); } -DBus::ValueOrError< Accessible* > BridgeComponent::GetAccessibleAtPoint( int32_t x, int32_t y, uint32_t coordType ) +DBus::ValueOrError BridgeComponent::GetAccessibleAtPoint(int32_t x, int32_t y, uint32_t coordType) { - return FindSelf()->GetAccessibleAtPoint( {x, y}, static_cast< CoordType >( coordType ) ); + return FindSelf()->GetAccessibleAtPoint({x, y}, static_cast(coordType)); } -DBus::ValueOrError< std::tuple< int32_t, int32_t, int32_t, int32_t > > BridgeComponent::GetExtents( uint32_t coordType ) +DBus::ValueOrError > BridgeComponent::GetExtents(uint32_t coordType) { - auto p = FindSelf()->GetExtents( static_cast< CoordType >( coordType ) ); - return std::tuple< int32_t, int32_t, int32_t, int32_t >{p.x, p.y, p.width, p.height}; + auto p = FindSelf()->GetExtents(static_cast(coordType)); + return std::tuple{p.x, p.y, p.width, p.height}; } -DBus::ValueOrError< int32_t, int32_t > BridgeComponent::GetPosition( uint32_t coordType ) +DBus::ValueOrError BridgeComponent::GetPosition(uint32_t coordType) { - auto p = FindSelf()->GetExtents( static_cast< CoordType >( coordType ) ); - return { static_cast(p.x), static_cast(p.y) }; + auto p = FindSelf()->GetExtents(static_cast(coordType)); + return {static_cast(p.x), static_cast(p.y)}; } -DBus::ValueOrError< int32_t, int32_t > BridgeComponent::GetSize( uint32_t coordType ) +DBus::ValueOrError BridgeComponent::GetSize(uint32_t coordType) { - auto p = FindSelf()->GetExtents( static_cast< CoordType >( coordType ) ); - return { static_cast(p.width), static_cast(p.height) }; + auto p = FindSelf()->GetExtents(static_cast(coordType)); + return {static_cast(p.width), static_cast(p.height)}; } -DBus::ValueOrError< ComponentLayer > BridgeComponent::GetLayer() +DBus::ValueOrError BridgeComponent::GetLayer() { return FindSelf()->GetLayer(); } -DBus::ValueOrError< double > BridgeComponent::GetAlpha() +DBus::ValueOrError BridgeComponent::GetAlpha() { return FindSelf()->GetAlpha(); } -DBus::ValueOrError< bool > BridgeComponent::GrabFocus() +DBus::ValueOrError BridgeComponent::GrabFocus() { return FindSelf()->GrabFocus(); } -DBus::ValueOrError< bool > BridgeComponent::GrabHighlight() +DBus::ValueOrError BridgeComponent::GrabHighlight() { return FindSelf()->GrabHighlight(); } -DBus::ValueOrError< bool > BridgeComponent::ClearHighlight() +DBus::ValueOrError BridgeComponent::ClearHighlight() { return FindSelf()->ClearHighlight(); } -DBus::ValueOrError< int16_t > BridgeComponent::GetMdiZOrder() +DBus::ValueOrError BridgeComponent::GetMdiZOrder() { return FindSelf()->GetMdiZOrder(); } diff --git a/dali/internal/accessibility/bridge/bridge-component.h b/dali/internal/accessibility/bridge/bridge-component.h index dcc8f49..f073148 100644 --- a/dali/internal/accessibility/bridge/bridge-component.h +++ b/dali/internal/accessibility/bridge/bridge-component.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_COMPONENT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,17 +38,17 @@ protected: Dali::Accessibility::Component* FindSelf() const; public: - DBus::ValueOrError< bool > Contains( int32_t x, int32_t y, uint32_t coordType ); - DBus::ValueOrError< Dali::Accessibility::Accessible* > GetAccessibleAtPoint( int32_t x, int32_t y, uint32_t coordType ); - DBus::ValueOrError< std::tuple< int32_t, int32_t, int32_t, int32_t > > GetExtents( uint32_t coordType ); - DBus::ValueOrError< int32_t, int32_t > GetPosition( uint32_t coordType ); - DBus::ValueOrError< int32_t, int32_t > GetSize( uint32_t coordType ); - DBus::ValueOrError< Dali::Accessibility::ComponentLayer > GetLayer(); - DBus::ValueOrError< double > GetAlpha(); - DBus::ValueOrError< bool > GrabFocus(); - DBus::ValueOrError< bool > GrabHighlight(); - DBus::ValueOrError< bool > ClearHighlight(); - DBus::ValueOrError< int16_t > GetMdiZOrder(); + DBus::ValueOrError Contains(int32_t x, int32_t y, uint32_t coordType); + DBus::ValueOrError GetAccessibleAtPoint(int32_t x, int32_t y, uint32_t coordType); + DBus::ValueOrError > GetExtents(uint32_t coordType); + DBus::ValueOrError GetPosition(uint32_t coordType); + DBus::ValueOrError GetSize(uint32_t coordType); + DBus::ValueOrError GetLayer(); + DBus::ValueOrError GetAlpha(); + DBus::ValueOrError GrabFocus(); + DBus::ValueOrError GrabHighlight(); + DBus::ValueOrError ClearHighlight(); + DBus::ValueOrError GetMdiZOrder(); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_COMPONENT_H diff --git a/dali/internal/accessibility/bridge/bridge-editable-text.cpp b/dali/internal/accessibility/bridge/bridge-editable-text.cpp index eb74e28..4d383ed 100644 --- a/dali/internal/accessibility/bridge/bridge-editable-text.cpp +++ b/dali/internal/accessibility/bridge/bridge-editable-text.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,33 +26,33 @@ using namespace Dali::Accessibility; void BridgeEditableText::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceEditableText}; - AddFunctionToInterface( desc, "CopyText", &BridgeEditableText::CopyText ); - AddFunctionToInterface( desc, "CutText", &BridgeEditableText::CutText ); - AddFunctionToInterface( desc, "PasteText", &BridgeEditableText::PasteText ); - dbusServer.addInterface( "/", desc, true ); + AddFunctionToInterface(desc, "CopyText", &BridgeEditableText::CopyText); + AddFunctionToInterface(desc, "CutText", &BridgeEditableText::CutText); + AddFunctionToInterface(desc, "PasteText", &BridgeEditableText::PasteText); + dbusServer.addInterface("/", desc, true); } EditableText* BridgeEditableText::FindSelf() const { auto s = BridgeBase::FindSelf(); - assert( s ); - auto s2 = dynamic_cast< EditableText* >( s ); - if( !s2 ) + assert(s); + auto s2 = dynamic_cast(s); + if(!s2) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Text interface"}; return s2; } -DBus::ValueOrError< bool > BridgeEditableText::CopyText( int32_t startPos, int32_t endPos ) +DBus::ValueOrError BridgeEditableText::CopyText(int32_t startPos, int32_t endPos) { - return FindSelf()->CopyText( startPos, endPos ); + return FindSelf()->CopyText(startPos, endPos); } -DBus::ValueOrError< bool > BridgeEditableText::CutText( int32_t startPos, int32_t endPos ) +DBus::ValueOrError BridgeEditableText::CutText(int32_t startPos, int32_t endPos) { - return FindSelf()->CutText( startPos, endPos ); + return FindSelf()->CutText(startPos, endPos); } -DBus::ValueOrError< bool > BridgeEditableText::PasteText( int32_t pos ) +DBus::ValueOrError BridgeEditableText::PasteText(int32_t pos) { // auto imfManager = Dali::Internal::Adaptor::ImfManager::Get(); // imfManager.SetCursorPosition( pos ); diff --git a/dali/internal/accessibility/bridge/bridge-editable-text.h b/dali/internal/accessibility/bridge/bridge-editable-text.h index e7d707b..9b4901f 100644 --- a/dali/internal/accessibility/bridge/bridge-editable-text.h +++ b/dali/internal/accessibility/bridge/bridge-editable-text.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_EDITABLE_TEXT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,9 +31,9 @@ protected: Dali::Accessibility::EditableText* FindSelf() const; public: - DBus::ValueOrError< bool > CopyText( int32_t startPos, int32_t endPos ); - DBus::ValueOrError< bool > CutText( int32_t startPos, int32_t endPos ); - DBus::ValueOrError< bool > PasteText( int32_t pos ); + DBus::ValueOrError CopyText(int32_t startPos, int32_t endPos); + DBus::ValueOrError CutText(int32_t startPos, int32_t endPos); + DBus::ValueOrError PasteText(int32_t pos); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_EDITABLE_TEXT_H diff --git a/dali/internal/accessibility/bridge/bridge-impl.cpp b/dali/internal/accessibility/bridge/bridge-impl.cpp index 91f68c8..f76a9b4 100644 --- a/dali/internal/accessibility/bridge/bridge-impl.cpp +++ b/dali/internal/accessibility/bridge/bridge-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,10 +27,10 @@ #include #include #include +#include #include -#include #include -#include +#include using namespace Dali::Accessibility; @@ -44,59 +44,55 @@ class BridgeImpl : public virtual BridgeBase, public BridgeText, public BridgeEditableText { - DBus::DBusClient listenOnAtspiEnabledSignalClient; - DBus::DBusClient registryClient, directReadingClient; - bool screenReaderEnabled = false; - bool isEnabled = false; - bool isShown = false; - std::unordered_map > directReadingCallbacks; - Dali::Actor highlightedActor; - std::function highlightClearAction; + DBus::DBusClient listenOnAtspiEnabledSignalClient; + DBus::DBusClient registryClient, directReadingClient; + bool screenReaderEnabled = false; + bool isEnabled = false; + bool isShown = false; + std::unordered_map> directReadingCallbacks; + Dali::Actor highlightedActor; + std::function highlightClearAction; public: BridgeImpl() { - listenOnAtspiEnabledSignalClient = DBus::DBusClient{ A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION }; + listenOnAtspiEnabledSignalClient = DBus::DBusClient{A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION}; - listenOnAtspiEnabledSignalClient.addPropertyChangedEvent< bool >( "ScreenReaderEnabled", [this]( bool res ) + listenOnAtspiEnabledSignalClient.addPropertyChangedEvent("ScreenReaderEnabled", [this](bool res) { + screenReaderEnabled = res; + if(screenReaderEnabled || isEnabled) { - screenReaderEnabled = res; - if( screenReaderEnabled || isEnabled ) - { - ForceUp(); - } - else - { - ForceDown(); - } + ForceUp(); } - ); + else + { + ForceDown(); + } + }); - listenOnAtspiEnabledSignalClient.addPropertyChangedEvent< bool >( "IsEnabled", [this]( bool res ) + listenOnAtspiEnabledSignalClient.addPropertyChangedEvent("IsEnabled", [this](bool res) { + isEnabled = res; + if(screenReaderEnabled || isEnabled) + { + ForceUp(); + } + else { - isEnabled = res; - if( screenReaderEnabled || isEnabled ) - { - ForceUp(); - } - else - { - ForceDown(); - } + ForceDown(); } - ); + }); } - Consumed Emit( KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText ) override + Consumed Emit(KeyEventType type, unsigned int keyCode, const std::string& keyName, unsigned int timeStamp, bool isText) override { - if (!IsUp()) + if(!IsUp()) { return Consumed::NO; } unsigned int evType = 0; - switch( type ) + switch(type) { case KeyEventType::KEY_PRESSED: { @@ -113,107 +109,104 @@ public: return Consumed::NO; } } - auto m = registryClient.method< bool( std::tuple< uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool > ) >( "NotifyListenersSync" ); - auto result = m.call( std::tuple< uint32_t, int32_t, int32_t, int32_t, int32_t, std::string, bool >{evType, 0, static_cast< int32_t >( keyCode ), 0, static_cast< int32_t >( timeStamp ), keyName, isText ? 1 : 0} ); - if( !result ) + auto m = registryClient.method)>("NotifyListenersSync"); + auto result = m.call(std::tuple{evType, 0, static_cast(keyCode), 0, static_cast(timeStamp), keyName, isText ? 1 : 0}); + if(!result) { LOG() << result.getError().message; return Consumed::NO; } - return std::get< 0 >( result ) ? Consumed::YES : Consumed::NO; + return std::get<0>(result) ? Consumed::YES : Consumed::NO; } void Pause() override { - if (!IsUp()) + if(!IsUp()) { return; } - directReadingClient.method< DBus::ValueOrError< void >( bool ) > ( "PauseResume" ).asyncCall( - []( DBus::ValueOrError< void > msg ) { - if (!msg) - { - LOG() << "Direct reading command failed (" << msg.getError().message << ")"; - } - }, - true); + directReadingClient.method(bool)>("PauseResume").asyncCall([](DBus::ValueOrError msg) { + if(!msg) + { + LOG() << "Direct reading command failed (" << msg.getError().message << ")"; + } + }, + true); } void Resume() override { - if (!IsUp()) + if(!IsUp()) { return; } - directReadingClient.method< DBus::ValueOrError< void >( bool ) > ( "PauseResume" ).asyncCall( - []( DBus::ValueOrError< void > msg) { - if (!msg) - { - LOG() << "Direct reading command failed (" << msg.getError().message << ")"; - } - }, - false); + directReadingClient.method(bool)>("PauseResume").asyncCall([](DBus::ValueOrError msg) { + if(!msg) + { + LOG() << "Direct reading command failed (" << msg.getError().message << ")"; + } + }, + false); } - void Say( const std::string& text, bool discardable, std::function< void(std::string) > callback ) override + void Say(const std::string& text, bool discardable, std::function callback) override { - if (!IsUp()) + if(!IsUp()) { return; } - directReadingClient.method< DBus::ValueOrError< std::string, bool, int32_t >( std::string, bool ) > ( "ReadCommand" ).asyncCall( - [=]( DBus::ValueOrError msg ) { - if ( !msg ) - { - LOG() << "Direct reading command failed (" << msg.getError().message << ")"; - } - else if( callback ) - { - directReadingCallbacks.emplace( std::get< 2 >( msg ), callback); - } - }, - text, - discardable); + directReadingClient.method(std::string, bool)>("ReadCommand").asyncCall([=](DBus::ValueOrError msg) { + if(!msg) + { + LOG() << "Direct reading command failed (" << msg.getError().message << ")"; + } + else if(callback) + { + directReadingCallbacks.emplace(std::get<2>(msg), callback); + } + }, + text, + discardable); } void ForceDown() override { - if (data) + if(data) { - if (data->currentlyHighlightedActor && data->highlightActor) + if(data->currentlyHighlightedActor && data->highlightActor) { data->currentlyHighlightedActor.Remove(data->highlightActor); } data->currentlyHighlightedActor = {}; - data->highlightActor = {}; + data->highlightActor = {}; } - highlightedActor = {}; + highlightedActor = {}; highlightClearAction = {}; BridgeAccessible::ForceDown(); - registryClient = {}; + registryClient = {}; directReadingClient = {}; directReadingCallbacks.clear(); } void Terminate() override { - if (data) + if(data) { data->currentlyHighlightedActor = {}; - data->highlightActor = {}; + data->highlightActor = {}; } ForceDown(); listenOnAtspiEnabledSignalClient = {}; - dbusServer = {}; - con = {}; + dbusServer = {}; + con = {}; } ForceUpResult ForceUp() override { - if( BridgeAccessible::ForceUp() == ForceUpResult::ALREADY_UP ) + if(BridgeAccessible::ForceUp() == ForceUpResult::ALREADY_UP) { return ForceUpResult::ALREADY_UP; } @@ -227,32 +220,30 @@ public: BridgeText::RegisterInterfaces(); BridgeEditableText::RegisterInterfaces(); - RegisterOnBridge( &application ); + RegisterOnBridge(&application); - registryClient = { AtspiDbusNameRegistry, AtspiDbusPathDec, AtspiDbusInterfaceDec, con }; - directReadingClient = DBus::DBusClient{ DirectReadingDBusName, DirectReadingDBusPath, DirectReadingDBusInterface, con }; - directReadingClient.addSignal< void(int32_t, std::string) >( "ReadingStateChanged", [=]( int32_t id, std::string readingState ) + registryClient = {AtspiDbusNameRegistry, AtspiDbusPathDec, AtspiDbusInterfaceDec, con}; + directReadingClient = DBus::DBusClient{DirectReadingDBusName, DirectReadingDBusPath, DirectReadingDBusInterface, con}; + directReadingClient.addSignal("ReadingStateChanged", [=](int32_t id, std::string readingState) { + auto it = directReadingCallbacks.find(id); + if(it != directReadingCallbacks.end()) { - auto it = directReadingCallbacks.find( id ); - if (it != directReadingCallbacks.end()) - { - it->second( readingState ); - if (readingState != "ReadingPaused" && readingState != "ReadingResumed" && readingState != "ReadingStarted") - directReadingCallbacks.erase( it ); - } + it->second(readingState); + if(readingState != "ReadingPaused" && readingState != "ReadingResumed" && readingState != "ReadingStarted") + directReadingCallbacks.erase(it); } - ); + }); - auto proxy = DBus::DBusClient{AtspiDbusNameRegistry, AtspiDbusPathRoot, AtspiDbusInterfaceSocket, con}; + auto proxy = DBus::DBusClient{AtspiDbusNameRegistry, AtspiDbusPathRoot, AtspiDbusInterfaceSocket, con}; Address root{"", "root"}; - auto res = proxy.method< Address( Address ) >( "Embed" ).call( root ); - if (!res) + auto res = proxy.method("Embed").call(root); + if(!res) { LOG() << "Call to Embed failed: " << res.getError().message; } - assert( res ); - application.parent.SetAddress( std::move( std::get< 0 >( res ) ) ); - if (isShown) + assert(res); + application.parent.SetAddress(std::move(std::get<0>(res))); + if(isShown) { EmitActivate(); } @@ -262,24 +253,24 @@ public: void EmitActivate() { auto win = application.getActiveWindow(); - if (win) + if(win) { - win->Emit( WindowEvent::ACTIVATE, 0 ); + win->Emit(WindowEvent::ACTIVATE, 0); } } void EmitDeactivate() { auto win = application.getActiveWindow(); - if (win) + if(win) { - win->Emit( WindowEvent::DEACTIVATE, 0 ); + win->Emit(WindowEvent::DEACTIVATE, 0); } } void ApplicationHidden() override { - if ( isShown && IsUp() ) + if(isShown && IsUp()) { EmitDeactivate(); } @@ -288,7 +279,7 @@ public: void ApplicationShown() override { - if ( !isShown && IsUp() ) + if(!isShown && IsUp()) { EmitActivate(); } @@ -298,17 +289,17 @@ public: void Initialize() override { auto req = DBus::DBusClient{A11yDbusName, A11yDbusPath, A11yDbusStatusInterface, DBus::ConnectionType::SESSION}; - auto p = req.property< bool >( "ScreenReaderEnabled" ).get(); - if( p ) + auto p = req.property("ScreenReaderEnabled").get(); + if(p) { - screenReaderEnabled = std::get< 0 >( p ); + screenReaderEnabled = std::get<0>(p); } - p = req.property< bool >( "IsEnabled" ).get(); - if( p ) + p = req.property("IsEnabled").get(); + if(p) { - isEnabled = std::get< 0 >( p ); + isEnabled = std::get<0>(p); } - if( screenReaderEnabled || isEnabled ) + if(screenReaderEnabled || isEnabled) { ForceUp(); } @@ -323,12 +314,10 @@ public: { return isEnabled; } - }; Bridge* Bridge::GetCurrentBridge() { - static BridgeImpl *bridge = new BridgeImpl; + static BridgeImpl* bridge = new BridgeImpl; return bridge; } - diff --git a/dali/internal/accessibility/bridge/bridge-object.cpp b/dali/internal/accessibility/bridge/bridge-object.cpp index 2a0d03e..e91f2e8 100644 --- a/dali/internal/accessibility/bridge/bridge-object.cpp +++ b/dali/internal/accessibility/bridge/bridge-object.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,35 +35,35 @@ void BridgeObject::RegisterInterfaces() // dbusServer.addInterface("/", desc, true); } -void BridgeObject::EmitActiveDescendantChanged( Accessible* obj, Accessible *child ) +void BridgeObject::EmitActiveDescendantChanged(Accessible* obj, Accessible* child) { - if (!IsUp()) return; + if(!IsUp()) return; auto index = child->GetIndexInParent(); - auto addr = obj->GetAddress(); - const auto prefixPath = "/org/a11y/atspi/accessible/"; - const auto nullPath = "/org/a11y/atspi/null"; + auto addr = obj->GetAddress(); + const auto prefixPath = "/org/a11y/atspi/accessible/"; + const auto nullPath = "/org/a11y/atspi/null"; std::string p; - if( addr ) + if(addr) p = prefixPath + addr.GetPath(); else p = nullPath; - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< Address >, Address >( - p, - AtspiDbusInterfaceEventObject, - "ActiveDescendantChanged", - "", - index, - 0, - { child->GetAddress() }, - {"", "root"} ); + dbusServer.emit2, Address>( + p, + AtspiDbusInterfaceEventObject, + "ActiveDescendantChanged", + "", + index, + 0, + {child->GetAddress()}, + {"", "root"}); } -void BridgeObject::Emit( Accessible* obj, Dali::Accessibility::ObjectPropertyChangeEvent ev ) +void BridgeObject::Emit(Accessible* obj, Dali::Accessibility::ObjectPropertyChangeEvent ev) { - if (!IsUp()) return; + if(!IsUp()) return; const char* name = nullptr; - switch( ev ) + switch(ev) { case ObjectPropertyChangeEvent::NAME: { @@ -91,31 +91,31 @@ void BridgeObject::Emit( Accessible* obj, Dali::Accessibility::ObjectPropertyCha break; } } - if( name ) + if(name) { - auto addr = obj->GetAddress(); + auto addr = obj->GetAddress(); std::string p; - if( addr ) + if(addr) p = ATSPI_PREFIX_PATH + addr.GetPath(); else p = ATSPI_NULL_PATH; - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< int >, Address >( - p, - AtspiDbusInterfaceEventObject, - "PropertyChange", - name, - 0, - 0, - {0}, - {"", "root"} ); + dbusServer.emit2, Address>( + p, + AtspiDbusInterfaceEventObject, + "PropertyChange", + name, + 0, + 0, + {0}, + {"", "root"}); } } -void BridgeObject::Emit( Accessible* obj, WindowEvent we, unsigned int detail1 ) +void BridgeObject::Emit(Accessible* obj, WindowEvent we, unsigned int detail1) { - if (!IsUp()) return; + if(!IsUp()) return; const char* name = nullptr; - switch( we ) + switch(we) { case WindowEvent::PROPERTY_CHANGE: { @@ -213,31 +213,31 @@ void BridgeObject::Emit( Accessible* obj, WindowEvent we, unsigned int detail1 ) break; } } - if( name ) + if(name) { - auto addr = obj->GetAddress(); + auto addr = obj->GetAddress(); std::string p; - if( addr ) + if(addr) p = ATSPI_PREFIX_PATH + addr.GetPath(); else p = ATSPI_NULL_PATH; - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< int >, Address >( - p, - AtspiDbusInterfaceEventWindow, - name, - "", - detail1, - 0, - {0}, - {"", "root"} ); + dbusServer.emit2, Address>( + p, + AtspiDbusInterfaceEventWindow, + name, + "", + detail1, + 0, + {0}, + {"", "root"}); } } -void BridgeObject::EmitStateChanged( Accessible* obj, State state, int newValue1, int newValue2 ) +void BridgeObject::EmitStateChanged(Accessible* obj, State state, int newValue1, int newValue2) { - if (!IsUp()) return; + if(!IsUp()) return; const char* stateName = nullptr; - switch( state ) + switch(state) { case State::INVALID: { @@ -474,40 +474,40 @@ void BridgeObject::EmitStateChanged( Accessible* obj, State state, int newValue1 break; } } - if( stateName ) + if(stateName) { - auto addr = obj->GetAddress(); + auto addr = obj->GetAddress(); std::string p; - if( addr ) + if(addr) p = ATSPI_PREFIX_PATH + addr.GetPath(); else p = ATSPI_NULL_PATH; - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< int >, Address >( - p, - AtspiDbusInterfaceEventObject, - "StateChanged", - stateName, - newValue1, - newValue2, - {0}, - {"", "root"} ); + dbusServer.emit2, Address>( + p, + AtspiDbusInterfaceEventObject, + "StateChanged", + stateName, + newValue1, + newValue2, + {0}, + {"", "root"}); } } -void BridgeObject::EmitBoundsChanged( Accessible* obj, Dali::Rect<> rect ) +void BridgeObject::EmitBoundsChanged(Accessible* obj, Dali::Rect<> rect) { - auto addr = obj->GetAddress(); - const auto prefixPath = "/org/a11y/atspi/accessible/"; - const auto nullPath = "/org/a11y/atspi/null"; + auto addr = obj->GetAddress(); + const auto prefixPath = "/org/a11y/atspi/accessible/"; + const auto nullPath = "/org/a11y/atspi/null"; std::string p; - if( addr ) + if(addr) p = prefixPath + addr.GetPath(); else p = nullPath; - DBus::EldbusVariant< std::tuple > tmp { - std::tuple{ rect.x, rect.y, rect.width, rect.height } }; + DBus::EldbusVariant > tmp{ + std::tuple{rect.x, rect.y, rect.width, rect.height}}; addFilteredEvent(FilteredEvents::boundsChanged, obj, 1.0f, [=]() { - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< std::tuple >, Address >( + dbusServer.emit2 >, Address>( p, AtspiDbusInterfaceEventObject, "BoundsChanged", @@ -515,15 +515,15 @@ void BridgeObject::EmitBoundsChanged( Accessible* obj, Dali::Rect<> rect ) 0, 0, tmp, - {"", "root"} ); + {"", "root"}); }); } -void BridgeObject::EmitCaretMoved( Accessible* obj, unsigned int cursorPosition ) +void BridgeObject::EmitCaretMoved(Accessible* obj, unsigned int cursorPosition) { - auto addr = obj->GetAddress(); - std::string p = addr ? ATSPI_PREFIX_PATH + addr.GetPath() : ATSPI_NULL_PATH; - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< int >, Address >( + auto addr = obj->GetAddress(); + std::string p = addr ? ATSPI_PREFIX_PATH + addr.GetPath() : ATSPI_NULL_PATH; + dbusServer.emit2, Address>( p, AtspiDbusInterfaceEventObject, "TextCaretMoved", @@ -531,13 +531,13 @@ void BridgeObject::EmitCaretMoved( Accessible* obj, unsigned int cursorPosition cursorPosition, 0, {0}, - {"", "root"} ); + {"", "root"}); } -void BridgeObject::EmitTextChanged( Accessible* obj, TextChangedState state, unsigned int position, unsigned int length, const std::string &content ) +void BridgeObject::EmitTextChanged(Accessible* obj, TextChangedState state, unsigned int position, unsigned int length, const std::string& content) { const char* stateName = nullptr; - switch( state ) + switch(state) { case TextChangedState::INSERTED: { @@ -554,18 +554,18 @@ void BridgeObject::EmitTextChanged( Accessible* obj, TextChangedState state, uns break; } } - if( stateName ) + if(stateName) { - auto addr = obj->GetAddress(); - std::string p = addr ? ATSPI_PREFIX_PATH + addr.GetPath() : ATSPI_NULL_PATH; - dbusServer.emit2< std::string, int, int, DBus::EldbusVariant< std::string >, Address >( - p, - AtspiDbusInterfaceEventObject, - "TextChanged", - stateName, - position, - length, - {content}, - {"", "root"} ); + auto addr = obj->GetAddress(); + std::string p = addr ? ATSPI_PREFIX_PATH + addr.GetPath() : ATSPI_NULL_PATH; + dbusServer.emit2, Address>( + p, + AtspiDbusInterfaceEventObject, + "TextChanged", + stateName, + position, + length, + {content}, + {"", "root"}); } } diff --git a/dali/internal/accessibility/bridge/bridge-object.h b/dali/internal/accessibility/bridge/bridge-object.h index 18fa86b..51abe03 100644 --- a/dali/internal/accessibility/bridge/bridge-object.h +++ b/dali/internal/accessibility/bridge/bridge-object.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_OBJECT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,28 +37,28 @@ protected: DBus::DBusInterfaceDescription::SignalId stateChanged; - void EmitActiveDescendantChanged( Dali::Accessibility::Accessible* obj, Dali::Accessibility::Accessible *child ) override; - void EmitCaretMoved( Dali::Accessibility::Accessible* obj, unsigned int cursorPosition ) override; - void EmitTextChanged( Dali::Accessibility::Accessible* obj, Dali::Accessibility::TextChangedState state, unsigned int position, unsigned int length, const std::string &content ) override; - void EmitStateChanged( Dali::Accessibility::Accessible* obj, Dali::Accessibility::State state, int val1, int val2 ) override; - void Emit( Dali::Accessibility::Accessible* obj, Dali::Accessibility::WindowEvent we, unsigned int detail1 ) override; - void Emit( Dali::Accessibility::Accessible* obj, Dali::Accessibility::ObjectPropertyChangeEvent we ) override; - void EmitBoundsChanged( Dali::Accessibility::Accessible* obj, Dali::Rect<> rect ) override; + void EmitActiveDescendantChanged(Dali::Accessibility::Accessible* obj, Dali::Accessibility::Accessible* child) override; + void EmitCaretMoved(Dali::Accessibility::Accessible* obj, unsigned int cursorPosition) override; + void EmitTextChanged(Dali::Accessibility::Accessible* obj, Dali::Accessibility::TextChangedState state, unsigned int position, unsigned int length, const std::string& content) override; + void EmitStateChanged(Dali::Accessibility::Accessible* obj, Dali::Accessibility::State state, int val1, int val2) override; + void Emit(Dali::Accessibility::Accessible* obj, Dali::Accessibility::WindowEvent we, unsigned int detail1) override; + void Emit(Dali::Accessibility::Accessible* obj, Dali::Accessibility::ObjectPropertyChangeEvent we) override; + void EmitBoundsChanged(Dali::Accessibility::Accessible* obj, Dali::Rect<> rect) override; public: - int GetChildCount(); - DBus::ValueOrError< Dali::Accessibility::Accessible* > GetChildAtIndex( int index ); - Dali::Accessibility::Accessible* GetParent(); - DBus::ValueOrError< std::vector< Dali::Accessibility::Accessible* > > GetChildren(); - std::string GetName(); - std::string GetDescription(); - DBus::ValueOrError< uint32_t > GetRole(); - DBus::ValueOrError< std::string > GetRoleName(); - DBus::ValueOrError< std::string > GetLocalizedRoleName(); - DBus::ValueOrError< int32_t > GetIndexInParent(); - DBus::ValueOrError< std::array< uint32_t, 2 > > GetStates(); - DBus::ValueOrError< std::unordered_map< std::string, std::string > > GetAttributes(); - DBus::ValueOrError< std::vector< std::string > > GetInterfaces(); + int GetChildCount(); + DBus::ValueOrError GetChildAtIndex(int index); + Dali::Accessibility::Accessible* GetParent(); + DBus::ValueOrError > GetChildren(); + std::string GetName(); + std::string GetDescription(); + DBus::ValueOrError GetRole(); + DBus::ValueOrError GetRoleName(); + DBus::ValueOrError GetLocalizedRoleName(); + DBus::ValueOrError GetIndexInParent(); + DBus::ValueOrError > GetStates(); + DBus::ValueOrError > GetAttributes(); + DBus::ValueOrError > GetInterfaces(); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_OBJECT_H diff --git a/dali/internal/accessibility/bridge/bridge-text.cpp b/dali/internal/accessibility/bridge/bridge-text.cpp index 0c3ed82..8bcd277 100644 --- a/dali/internal/accessibility/bridge/bridge-text.cpp +++ b/dali/internal/accessibility/bridge/bridge-text.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,65 +26,65 @@ using namespace Dali::Accessibility; void BridgeText::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceText}; - AddFunctionToInterface( desc, "GetText", &BridgeText::GetText ); - AddGetPropertyToInterface( desc, "CharacterCount", &BridgeText::GetCharacterCount ); - AddGetPropertyToInterface( desc, "CaretOffset", &BridgeText::GetCaretOffset ); - AddFunctionToInterface( desc, "SetCaretOffset", &BridgeText::SetCaretOffset ); - AddFunctionToInterface( desc, "GetTextAtOffset", &BridgeText::GetTextAtOffset ); - AddFunctionToInterface( desc, "GetSelection", &BridgeText::GetSelection ); - AddFunctionToInterface( desc, "SetSelection", &BridgeText::SetSelection ); - AddFunctionToInterface( desc, "RemoveSelection", &BridgeText::RemoveSelection ); - dbusServer.addInterface( "/", desc, true ); + AddFunctionToInterface(desc, "GetText", &BridgeText::GetText); + AddGetPropertyToInterface(desc, "CharacterCount", &BridgeText::GetCharacterCount); + AddGetPropertyToInterface(desc, "CaretOffset", &BridgeText::GetCaretOffset); + AddFunctionToInterface(desc, "SetCaretOffset", &BridgeText::SetCaretOffset); + AddFunctionToInterface(desc, "GetTextAtOffset", &BridgeText::GetTextAtOffset); + AddFunctionToInterface(desc, "GetSelection", &BridgeText::GetSelection); + AddFunctionToInterface(desc, "SetSelection", &BridgeText::SetSelection); + AddFunctionToInterface(desc, "RemoveSelection", &BridgeText::RemoveSelection); + dbusServer.addInterface("/", desc, true); } Text* BridgeText::FindSelf() const { auto s = BridgeBase::FindSelf(); - assert( s ); - auto s2 = dynamic_cast< Text* >( s ); - if( !s2 ) + assert(s); + auto s2 = dynamic_cast(s); + if(!s2) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Text interface"}; return s2; } -DBus::ValueOrError< std::string > BridgeText::GetText( int startOffset, int endOffset ) +DBus::ValueOrError BridgeText::GetText(int startOffset, int endOffset) { - return FindSelf()->GetText( startOffset, endOffset ); + return FindSelf()->GetText(startOffset, endOffset); } -DBus::ValueOrError< int32_t > BridgeText::GetCharacterCount() +DBus::ValueOrError BridgeText::GetCharacterCount() { return FindSelf()->GetCharacterCount(); } -DBus::ValueOrError< int32_t > BridgeText::GetCaretOffset() +DBus::ValueOrError BridgeText::GetCaretOffset() { return FindSelf()->GetCaretOffset(); } -DBus::ValueOrError< bool > BridgeText::SetCaretOffset( int32_t offset ) +DBus::ValueOrError BridgeText::SetCaretOffset(int32_t offset) { return FindSelf()->SetCaretOffset(offset); } -DBus::ValueOrError< std::string, int, int > BridgeText::GetTextAtOffset( int32_t offset, uint32_t boundary ) +DBus::ValueOrError BridgeText::GetTextAtOffset(int32_t offset, uint32_t boundary) { - auto r = FindSelf()->GetTextAtOffset( offset, static_cast< TextBoundary >( boundary ) ); - return {r.content, static_cast< int >( r.startOffset ), static_cast< int >( r.endOffset )}; + auto r = FindSelf()->GetTextAtOffset(offset, static_cast(boundary)); + return {r.content, static_cast(r.startOffset), static_cast(r.endOffset)}; } -DBus::ValueOrError< int, int > BridgeText::GetSelection( int32_t selectionNum ) +DBus::ValueOrError BridgeText::GetSelection(int32_t selectionNum) { - auto r = FindSelf()->GetSelection( selectionNum ); - return {static_cast< int >( r.startOffset ), static_cast< int >( r.endOffset )}; + auto r = FindSelf()->GetSelection(selectionNum); + return {static_cast(r.startOffset), static_cast(r.endOffset)}; } -DBus::ValueOrError< bool > BridgeText::RemoveSelection( int32_t selectionNum ) +DBus::ValueOrError BridgeText::RemoveSelection(int32_t selectionNum) { - return FindSelf()->RemoveSelection( selectionNum ); + return FindSelf()->RemoveSelection(selectionNum); } -DBus::ValueOrError< bool > BridgeText::SetSelection( int32_t selectionNum, int32_t startOffset, int32_t endOffset ) +DBus::ValueOrError BridgeText::SetSelection(int32_t selectionNum, int32_t startOffset, int32_t endOffset) { - return FindSelf()->SetSelection( selectionNum, startOffset, endOffset ); + return FindSelf()->SetSelection(selectionNum, startOffset, endOffset); } diff --git a/dali/internal/accessibility/bridge/bridge-text.h b/dali/internal/accessibility/bridge/bridge-text.h index f8661a7..7618b28 100644 --- a/dali/internal/accessibility/bridge/bridge-text.h +++ b/dali/internal/accessibility/bridge/bridge-text.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_TEXT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,14 +31,14 @@ protected: Dali::Accessibility::Text* FindSelf() const; public: - DBus::ValueOrError< std::string > GetText( int startOffset, int endOffset ); - DBus::ValueOrError< int32_t > GetCharacterCount(); - DBus::ValueOrError< int32_t > GetCaretOffset(); - DBus::ValueOrError< bool > SetCaretOffset( int32_t offset ); - DBus::ValueOrError< std::string, int, int > GetTextAtOffset( int32_t offset, uint32_t boundary ); - DBus::ValueOrError< int, int > GetSelection( int32_t selectionNum ); - DBus::ValueOrError< bool > RemoveSelection( int32_t selectionNum ); - DBus::ValueOrError< bool > SetSelection( int32_t selectionNum, int32_t startOffset, int32_t endOffset ); + DBus::ValueOrError GetText(int startOffset, int endOffset); + DBus::ValueOrError GetCharacterCount(); + DBus::ValueOrError GetCaretOffset(); + DBus::ValueOrError SetCaretOffset(int32_t offset); + DBus::ValueOrError GetTextAtOffset(int32_t offset, uint32_t boundary); + DBus::ValueOrError GetSelection(int32_t selectionNum); + DBus::ValueOrError RemoveSelection(int32_t selectionNum); + DBus::ValueOrError SetSelection(int32_t selectionNum, int32_t startOffset, int32_t endOffset); }; #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_TEXT_H diff --git a/dali/internal/accessibility/bridge/bridge-value.cpp b/dali/internal/accessibility/bridge/bridge-value.cpp index aa1a34c..ee2fc50 100644 --- a/dali/internal/accessibility/bridge/bridge-value.cpp +++ b/dali/internal/accessibility/bridge/bridge-value.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,19 +30,19 @@ BridgeValue::BridgeValue() void BridgeValue::RegisterInterfaces() { DBus::DBusInterfaceDescription desc{AtspiDbusInterfaceValue}; - AddGetSetPropertyToInterface( desc, "CurrentValue", &BridgeValue::GetCurrentValue, &BridgeValue::SetCurrentValue ); - AddGetPropertyToInterface( desc, "MaximumValue", &BridgeValue::GetMaximumValue ); - AddGetPropertyToInterface( desc, "MinimumIncrement", &BridgeValue::GetMinimumIncrement ); - AddGetPropertyToInterface( desc, "MinimumValue", &BridgeValue::GetMinimumValue ); - dbusServer.addInterface( "/", desc, true ); + AddGetSetPropertyToInterface(desc, "CurrentValue", &BridgeValue::GetCurrentValue, &BridgeValue::SetCurrentValue); + AddGetPropertyToInterface(desc, "MaximumValue", &BridgeValue::GetMaximumValue); + AddGetPropertyToInterface(desc, "MinimumIncrement", &BridgeValue::GetMinimumIncrement); + AddGetPropertyToInterface(desc, "MinimumValue", &BridgeValue::GetMinimumValue); + dbusServer.addInterface("/", desc, true); } Value* BridgeValue::FindSelf() const { auto s = BridgeBase::FindSelf(); - assert( s ); - auto s2 = dynamic_cast< Value* >( s ); - if( !s2 ) + assert(s); + auto s2 = dynamic_cast(s); + if(!s2) throw std::domain_error{"object " + s->GetAddress().ToString() + " doesn't have Value interface"}; return s2; } @@ -50,9 +50,9 @@ double BridgeValue::GetCurrentValue() { return FindSelf()->GetCurrent(); } -void BridgeValue::SetCurrentValue( double new_value ) +void BridgeValue::SetCurrentValue(double new_value) { - FindSelf()->SetCurrent( new_value ); + FindSelf()->SetCurrent(new_value); } double BridgeValue::GetMaximumValue() { diff --git a/dali/internal/accessibility/bridge/bridge-value.h b/dali/internal/accessibility/bridge/bridge-value.h index 0fb921f..470a6f7 100644 --- a/dali/internal/accessibility/bridge/bridge-value.h +++ b/dali/internal/accessibility/bridge/bridge-value.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_BRIDGE_VALUE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ protected: public: double GetCurrentValue(); - void SetCurrentValue( double new_value ); + void SetCurrentValue(double new_value); double GetMaximumValue(); double GetMinimumIncrement(); double GetMinimumValue(); diff --git a/dali/internal/accessibility/bridge/component.cpp b/dali/internal/accessibility/bridge/component.cpp index 73334a1..7e85d56 100644 --- a/dali/internal/accessibility/bridge/component.cpp +++ b/dali/internal/accessibility/bridge/component.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,19 +25,19 @@ using namespace Dali::Accessibility; -bool Component::Contains( Point p, CoordType ctype ) +bool Component::Contains(Point p, CoordType ctype) { - auto extents = GetExtents( ctype ); + auto extents = GetExtents(ctype); return p.x >= extents.x && p.y >= extents.y && p.x <= extents.x + extents.width && p.y <= extents.y + extents.height; } -Accessible* Component::GetAccessibleAtPoint( Point p, CoordType ctype ) +Accessible* Component::GetAccessibleAtPoint(Point p, CoordType ctype) { auto children = GetChildren(); - for( auto childIt = children.rbegin(); childIt != children.rend(); childIt++ ) + for(auto childIt = children.rbegin(); childIt != children.rend(); childIt++) { - auto component = dynamic_cast< Component* >( *childIt ); - if( component && component->Contains( p, ctype ) ) + auto component = dynamic_cast(*childIt); + if(component && component->Contains(p, ctype)) { return component; } diff --git a/dali/internal/accessibility/bridge/dbus-locators.h b/dali/internal/accessibility/bridge/dbus-locators.h index 1bfb8ec..d617e4d 100644 --- a/dali/internal/accessibility/bridge/dbus-locators.h +++ b/dali/internal/accessibility/bridge/dbus-locators.h @@ -21,78 +21,78 @@ namespace dbusLocators { namespace callmgr { -static constexpr const char* BUS = "org.tizen.callmgr"; -static constexpr const char* OBJ_PATH = "/org/tizen/callmgr"; +static constexpr const char* BUS = "org.tizen.callmgr"; +static constexpr const char* OBJ_PATH = "/org/tizen/callmgr"; static constexpr const char* INTERFACE = "org.tizen.callmgr"; -} +} // namespace callmgr namespace accessibilityEMod { -static constexpr const char* BUS = "org.enlightenment.wm-screen-reader"; -static constexpr const char* OBJ_PATH = "/org/tizen/GestureNavigation"; +static constexpr const char* BUS = "org.enlightenment.wm-screen-reader"; +static constexpr const char* OBJ_PATH = "/org/tizen/GestureNavigation"; static constexpr const char* INTERFACE = "org.tizen.GestureNavigation"; static constexpr const char* ACCESSORIES_SP_ENABLED = "AccessoriesSwitchProviderEnabled"; -static constexpr const char* KEY_DOWN_SIGNAL = "KeyDown"; -static constexpr const char* KEY_UP_SIGNAL = "KeyUp"; +static constexpr const char* KEY_DOWN_SIGNAL = "KeyDown"; +static constexpr const char* KEY_UP_SIGNAL = "KeyUp"; static constexpr const char* SCREEN_SP_ENABLED = "ScreenSwitchProviderEnabled"; static constexpr const char* MOUSE_DOWN_SIGNAL = "MouseDown"; -static constexpr const char* MOUSE_UP_SIGNAL = "MouseUp"; +static constexpr const char* MOUSE_UP_SIGNAL = "MouseUp"; static constexpr const char* BACK_BUTTON_INTERCEPTION_ENABLED = "BackButtonInterceptionEnabled"; -static constexpr const char* BACK_BUTTON_DOWN_SIGNAL = "BackButtonDown"; -static constexpr const char* BACK_BUTTON_UP_SIGNAL = "BackButtonUp"; -} +static constexpr const char* BACK_BUTTON_DOWN_SIGNAL = "BackButtonDown"; +static constexpr const char* BACK_BUTTON_UP_SIGNAL = "BackButtonUp"; +} // namespace accessibilityEMod namespace freeDesktop { -static constexpr const char* BUS = "org.freedesktop.DBus"; -static constexpr const char* OBJ_PATH = "/org/freedesktop/DBus"; -static constexpr const char* INTERFACE = "org.freedesktop.DBus"; -static constexpr const char* PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"; +static constexpr const char* BUS = "org.freedesktop.DBus"; +static constexpr const char* OBJ_PATH = "/org/freedesktop/DBus"; +static constexpr const char* INTERFACE = "org.freedesktop.DBus"; +static constexpr const char* PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"; static constexpr const char* GET_CONNECTION_UNIX_PROCESS_ID = "GetConnectionUnixProcessID"; -static constexpr const char* SET = "Set"; -static constexpr const char* GET = "Get"; -} +static constexpr const char* SET = "Set"; +static constexpr const char* GET = "Get"; +} // namespace freeDesktop namespace windowManager { -static constexpr const char* BUS = "org.enlightenment.wm"; -static constexpr const char* OBJ_PATH = "/org/enlightenment/wm"; -static constexpr const char* INTERFACE = "org.enlightenment.wm.proc"; +static constexpr const char* BUS = "org.enlightenment.wm"; +static constexpr const char* OBJ_PATH = "/org/enlightenment/wm"; +static constexpr const char* INTERFACE = "org.enlightenment.wm.proc"; static constexpr const char* GET_VISIBLE_WIN_INFO = "GetVisibleWinInfo"; -static constexpr const char* GET_FOCUS_PROC = "GetFocusProc"; -} +static constexpr const char* GET_FOCUS_PROC = "GetFocusProc"; +} // namespace windowManager namespace atspi { -static constexpr const char* BUS = "org.a11y.Bus"; -static constexpr const char* OBJ_PATH = "/org/a11y/bus"; -static constexpr const char* BUS_INTERFACE = "org.a11y.Bus"; +static constexpr const char* BUS = "org.a11y.Bus"; +static constexpr const char* OBJ_PATH = "/org/a11y/bus"; +static constexpr const char* BUS_INTERFACE = "org.a11y.Bus"; static constexpr const char* STATUS_INTERFACE = "org.a11y.Status"; -static constexpr const char* GET_ADDRESS = "GetAddress"; -static constexpr const char* IS_ENABLED = "IsEnabled"; -static constexpr const char* GET_ATTRIBUTES = "GetAttributes"; -static constexpr const char* DO_ACTION_NAME = "DoActionName"; -static constexpr const char* PARENT = "Parent"; -static constexpr const char* GET_MATCHES = "GetMatches"; -static constexpr const char* GET_INDEX_IN_PARENT = "GetIndexInParent"; -static constexpr const char* SELECT_CHILD = "SelectChild"; -static constexpr const char* NAME = "Name"; -static constexpr const char* GET_ROLE = "GetRole"; -static constexpr const char* CHILD_COUNT = "ChildCount"; -static constexpr const char* GET_CHILD_AT_INDEX = "GetChildAtIndex"; -static constexpr const char* GET_STATE = "GetState"; -static constexpr const char* GET_RELATION_SET = "GetRelationSet"; -static constexpr const char* GET_EXTENTS = "GetExtents"; -static constexpr const char* CURRENT_VALUE = "CurrentValue"; -static constexpr const char* MAXIMUM_VALUE = "MaximumValue"; -static constexpr const char* MINIMUM_VALUE = "MinimumValue"; -static constexpr const char* GET_INTERFACES = "GetInterfaces"; +static constexpr const char* GET_ADDRESS = "GetAddress"; +static constexpr const char* IS_ENABLED = "IsEnabled"; +static constexpr const char* GET_ATTRIBUTES = "GetAttributes"; +static constexpr const char* DO_ACTION_NAME = "DoActionName"; +static constexpr const char* PARENT = "Parent"; +static constexpr const char* GET_MATCHES = "GetMatches"; +static constexpr const char* GET_INDEX_IN_PARENT = "GetIndexInParent"; +static constexpr const char* SELECT_CHILD = "SelectChild"; +static constexpr const char* NAME = "Name"; +static constexpr const char* GET_ROLE = "GetRole"; +static constexpr const char* CHILD_COUNT = "ChildCount"; +static constexpr const char* GET_CHILD_AT_INDEX = "GetChildAtIndex"; +static constexpr const char* GET_STATE = "GetState"; +static constexpr const char* GET_RELATION_SET = "GetRelationSet"; +static constexpr const char* GET_EXTENTS = "GetExtents"; +static constexpr const char* CURRENT_VALUE = "CurrentValue"; +static constexpr const char* MAXIMUM_VALUE = "MaximumValue"; +static constexpr const char* MINIMUM_VALUE = "MinimumValue"; +static constexpr const char* GET_INTERFACES = "GetInterfaces"; static constexpr const char* GET_NAVIGABLE_AT_POINT = "GetNavigableAtPoint"; -} -} +} // namespace atspi +} // namespace dbusLocators #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_DBUS_LOCATORS_H diff --git a/dali/internal/accessibility/bridge/dbus-tizen.cpp b/dali/internal/accessibility/bridge/dbus-tizen.cpp index 4d236d6..cc2a45c 100644 --- a/dali/internal/accessibility/bridge/dbus-tizen.cpp +++ b/dali/internal/accessibility/bridge/dbus-tizen.cpp @@ -15,16 +15,16 @@ */ // CLASS HEADER -#include #include +#include // EXTERNAL INCLUDES -#include #include #include +#include -#include #include +#include // INTERNAL INCLUDES #include @@ -33,137 +33,140 @@ #undef EINA_FALSE #undef EINA_TRUE -#define EINA_TRUE static_cast< Eina_Bool >( 1 ) -#define EINA_FALSE static_cast< Eina_Bool >( 0 ) +#define EINA_TRUE static_cast(1) +#define EINA_FALSE static_cast(0) //#define DBUS_DEBUG(...) do { DBus::debugPrint(__FILE__, __LINE__, __VA_ARGS__); } while (0) -std::atomic< unsigned int > DBus::detail::CallId::LastId{0}; -static std::function< void( const char*, size_t ) > debugPrinter; -static std::mutex debugLock; +std::atomic DBus::detail::CallId::LastId{0}; +static std::function debugPrinter; +static std::mutex debugLock; -thread_local std::string DBus::DBusServer::currentObjectPath; +thread_local std::string DBus::DBusServer::currentObjectPath; thread_local DBusWrapper::ConnectionPtr DBus::DBusServer::currentConnection; -void DBus::setDebugPrinter( std::function< void( const char*, size_t ) > printer ) +void DBus::setDebugPrinter(std::function printer) { - std::lock_guard< std::mutex > lock( debugLock ); - debugPrinter = std::move( printer ); + std::lock_guard lock(debugLock); + debugPrinter = std::move(printer); } -void DBus::debugPrint( const char* file, size_t line, const char* format, ... ) +void DBus::debugPrint(const char* file, size_t line, const char* format, ...) { - std::function< void( const char*, size_t ) > debugPrintFunc; + std::function debugPrintFunc; { - std::lock_guard< std::mutex > lock( debugLock ); - if( !debugPrinter ) + std::lock_guard lock(debugLock); + if(!debugPrinter) return; debugPrintFunc = debugPrinter; } - std::vector< char > buf( 4096 ); - int offset; - while( true ) + std::vector buf(4096); + int offset; + while(true) { - offset = snprintf( buf.data(), buf.size(), "%s:%u: ", file, static_cast< unsigned int >( line ) ); - if( offset < 0 ) + offset = snprintf(buf.data(), buf.size(), "%s:%u: ", file, static_cast(line)); + if(offset < 0) return; - if( static_cast< size_t >( offset ) < buf.size() ) + if(static_cast(offset) < buf.size()) break; - buf.resize( offset + 1 ); + buf.resize(offset + 1); } - while( true ) + while(true) { va_list args; - va_start( args, format ); - int z = vsnprintf( buf.data() + offset, buf.size() - offset, format, args ); - va_end( args ); - if( z < 0 ) + va_start(args, format); + int z = vsnprintf(buf.data() + offset, buf.size() - offset, format, args); + va_end(args); + if(z < 0) return; - bool done = static_cast< size_t >( z ) + static_cast< size_t >( offset ) < buf.size(); - buf.resize( static_cast< size_t >( z ) + static_cast< size_t >( offset ) ); - if( done ) + bool done = static_cast(z) + static_cast(offset) < buf.size(); + buf.resize(static_cast(z) + static_cast(offset)); + if(done) break; } - debugPrintFunc( buf.data(), buf.size() ); + debugPrintFunc(buf.data(), buf.size()); } -DBusWrapper::ConnectionPtr DBus::getDBusConnectionByName( const std::string& name ) +DBusWrapper::ConnectionPtr DBus::getDBusConnectionByName(const std::string& name) { - return DBUS_W->eldbus_address_connection_get_impl( name ); + return DBUS_W->eldbus_address_connection_get_impl(name); } -DBusWrapper::ConnectionPtr DBus::getDBusConnectionByType( ConnectionType connectionType ) +DBusWrapper::ConnectionPtr DBus::getDBusConnectionByType(ConnectionType connectionType) { return DBUS_W->eldbus_connection_get_impl(connectionType); } -DBus::DBusClient::DBusClient( std::string busName, std::string pathName, std::string interfaceName, ConnectionType tp ) : DBusClient( std::move( busName ), std::move( pathName ), std::move( interfaceName ), getDBusConnectionByType( tp ) ) +DBus::DBusClient::DBusClient(std::string busName, std::string pathName, std::string interfaceName, ConnectionType tp) +: DBusClient(std::move(busName), std::move(pathName), std::move(interfaceName), getDBusConnectionByType(tp)) { } -DBus::DBusClient::DBusClient( std::string busName, std::string pathName, std::string interfaceName, const DBusWrapper::ConnectionPtr &conn ) +DBus::DBusClient::DBusClient(std::string busName, std::string pathName, std::string interfaceName, const DBusWrapper::ConnectionPtr& conn) { - if( !conn ) - connectionState->connection = getDBusConnectionByType( ConnectionType::SESSION ); + if(!conn) + connectionState->connection = getDBusConnectionByType(ConnectionType::SESSION); else connectionState->connection = conn; std::ostringstream o; - o << "bus = " << busName << " path = " << pathName << " connection = " << DBUS_W->eldbus_connection_unique_name_get_impl( connectionState->connection ); + o << "bus = " << busName << " path = " << pathName << " connection = " << DBUS_W->eldbus_connection_unique_name_get_impl(connectionState->connection); info = o.str(); - connectionState->object = DBUS_W->eldbus_object_get_impl( connectionState->connection, busName.c_str(), pathName.c_str() ); - if( connectionState->object ) + connectionState->object = DBUS_W->eldbus_object_get_impl(connectionState->connection, busName.c_str(), pathName.c_str()); + if(connectionState->object) { - connectionState->proxy = DBUS_W->eldbus_proxy_get_impl( connectionState->object, interfaceName ); - if( interfaceName != DBUS_INTERFACE_PROPERTIES ) + connectionState->proxy = DBUS_W->eldbus_proxy_get_impl(connectionState->object, interfaceName); + if(interfaceName != DBUS_INTERFACE_PROPERTIES) { - connectionState->propertiesProxy = DBUS_W->eldbus_proxy_get_impl( connectionState->object, DBUS_INTERFACE_PROPERTIES ); + connectionState->propertiesProxy = DBUS_W->eldbus_proxy_get_impl(connectionState->object, DBUS_INTERFACE_PROPERTIES); } else { - connectionState->propertiesProxy = DBUS_W->eldbus_proxy_copy_impl( connectionState->proxy ); + connectionState->propertiesProxy = DBUS_W->eldbus_proxy_copy_impl(connectionState->proxy); } } - connectionInfo = std::make_shared< ConnectionInfo >(); - connectionInfo->busName = std::move( busName ); - connectionInfo->pathName = std::move( pathName ); - connectionInfo->interfaceName = std::move( interfaceName ); + connectionInfo = std::make_shared(); + connectionInfo->busName = std::move(busName); + connectionInfo->pathName = std::move(pathName); + connectionInfo->interfaceName = std::move(interfaceName); } -DBus::DBusServer::DBusServer( ConnectionType tp ) : DBus::DBusServer( DBus::getDBusConnectionByType( tp ) ) +DBus::DBusServer::DBusServer(ConnectionType tp) +: DBus::DBusServer(DBus::getDBusConnectionByType(tp)) { } -DBus::DBusServer::DBusServer( const DBusWrapper::ConnectionPtr &conn ) +DBus::DBusServer::DBusServer(const DBusWrapper::ConnectionPtr& conn) { - if( !conn ) - connection = getDBusConnectionByType( ConnectionType::SESSION ); + if(!conn) + connection = getDBusConnectionByType(ConnectionType::SESSION); else connection = conn; } -DBus::DBusInterfaceDescription::DBusInterfaceDescription( std::string interfaceName ) : interfaceName( std::move( interfaceName ) ) +DBus::DBusInterfaceDescription::DBusInterfaceDescription(std::string interfaceName) +: interfaceName(std::move(interfaceName)) { } -void DBus::DBusServer::addInterface( const std::string& pathName, DBusInterfaceDescription& dscr, bool fallback ) +void DBus::DBusServer::addInterface(const std::string& pathName, DBusInterfaceDescription& dscr, bool fallback) { - DBUS_W->add_interface_impl( fallback, pathName, connection, destructorObject->destructors, dscr.interfaceName, dscr.methods, dscr.properties, dscr.signals ); + DBUS_W->add_interface_impl(fallback, pathName, connection, destructorObject->destructors, dscr.interfaceName, dscr.methods, dscr.properties, dscr.signals); } std::string DBus::DBusServer::getBusName() const { - return getConnectionName( connection ); + return getConnectionName(connection); } -std::string DBus::getConnectionName( const DBusWrapper::ConnectionPtr &c ) +std::string DBus::getConnectionName(const DBusWrapper::ConnectionPtr& c) { - return DBUS_W->eldbus_connection_unique_name_get_impl( c ); + return DBUS_W->eldbus_connection_unique_name_get_impl(c); } -bool DBus::DBusClient::getFromEinaValue(const _Eina_Value *v, void *dst) +bool DBus::DBusClient::getFromEinaValue(const _Eina_Value* v, void* dst) { return eina_value_get(const_cast(v), dst); } @@ -182,35 +185,49 @@ struct DefaultDBusWrapper : public DBusWrapper { } - #define DEFINE_GS(name, eldbus_name, unref_call) \ - static eldbus_name *get(const std::shared_ptr &a) { \ - return static_cast(a.get())->Value; \ - } \ - static eldbus_name *release(const std::shared_ptr &a) { \ - auto z = static_cast(a.get())->Value; \ - static_cast(a.get())->Value = nullptr; \ - return z; \ - } \ - template static std::shared_ptr create(const eldbus_name *v, ARGS && ... args) { \ - return std::make_shared(const_cast(v), std::forward(args)...); \ - } - - #define DEFINE_TYPE(name, eldbus_name, unref_call) \ - struct name ## Impl : public name { \ - eldbus_name *Value = nullptr; \ - bool EraseOnExit = false; \ - name ## Impl(eldbus_name *Value, bool EraseOnExit = false) : Value(Value), EraseOnExit(EraseOnExit) { } \ - ~name ## Impl() { \ - if (EraseOnExit && Value) { unref_call; } \ - } \ - }; \ +#define DEFINE_GS(name, eldbus_name, unref_call) \ + static eldbus_name* get(const std::shared_ptr& a) \ + { \ + return static_cast(a.get())->Value; \ + } \ + static eldbus_name* release(const std::shared_ptr& a) \ + { \ + auto z = static_cast(a.get())->Value; \ + static_cast(a.get())->Value = nullptr; \ + return z; \ + } \ + template \ + static std::shared_ptr create(const eldbus_name* v, ARGS&&... args) \ + { \ + return std::make_shared(const_cast(v), std::forward(args)...); \ + } + +#define DEFINE_TYPE(name, eldbus_name, unref_call) \ + struct name##Impl : public name \ + { \ + eldbus_name* Value = nullptr; \ + bool EraseOnExit = false; \ + name##Impl(eldbus_name* Value, bool EraseOnExit = false): Value(Value), \ + EraseOnExit(EraseOnExit) \ + { \ + } \ + ~name##Impl() \ + { \ + if(EraseOnExit && Value) \ + { \ + unref_call; \ + } \ + } \ + }; \ DEFINE_GS(name, eldbus_name, unref_call) struct ConnectionImpl : public Connection { - Eldbus_Connection *Value = nullptr; - bool EraseOnExit = false; - ConnectionImpl(Eldbus_Connection *Value, bool EraseOnExit = false) : Value(Value), EraseOnExit(EraseOnExit) + Eldbus_Connection* Value = nullptr; + bool EraseOnExit = false; + ConnectionImpl(Eldbus_Connection* Value, bool EraseOnExit = false) + : Value(Value), + EraseOnExit(EraseOnExit) { ecore_event_init(); eldbus_init(); @@ -218,9 +235,9 @@ struct DefaultDBusWrapper : public DBusWrapper ~ConnectionImpl() { - if (EraseOnExit && Value) + if(EraseOnExit && Value) { - eldbus_connection_unref( Value ); + eldbus_connection_unref(Value); } eldbus_shutdown(); ecore_event_shutdown(); @@ -230,14 +247,17 @@ struct DefaultDBusWrapper : public DBusWrapper struct MessageIterImpl : public MessageIter { Eldbus_Message_Iter *Value = nullptr, *Parent = nullptr; - bool EraseOnExit = false; - MessageIterImpl(Eldbus_Message_Iter *Value, Eldbus_Message_Iter *Parent, bool EraseOnExit = false) : Value(Value), Parent(Parent), EraseOnExit(EraseOnExit) + bool EraseOnExit = false; + MessageIterImpl(Eldbus_Message_Iter* Value, Eldbus_Message_Iter* Parent, bool EraseOnExit = false) + : Value(Value), + Parent(Parent), + EraseOnExit(EraseOnExit) { } ~MessageIterImpl() { - if (EraseOnExit && Value && Parent) + if(EraseOnExit && Value && Parent) { eldbus_message_iter_container_close(Parent, Value); } @@ -246,14 +266,14 @@ struct DefaultDBusWrapper : public DBusWrapper DEFINE_GS(Connection, Eldbus_Connection, ) DEFINE_GS(MessageIter, Eldbus_Message_Iter, ) - DEFINE_TYPE(Message, Eldbus_Message, eldbus_message_unref( Value )) + DEFINE_TYPE(Message, Eldbus_Message, eldbus_message_unref(Value)) DEFINE_TYPE(Proxy, Eldbus_Proxy, ) - DEFINE_TYPE(Object, Eldbus_Object, eldbus_object_unref( Value )) + DEFINE_TYPE(Object, Eldbus_Object, eldbus_object_unref(Value)) DEFINE_TYPE(Pending, Eldbus_Pending, ) DEFINE_TYPE(EventPropertyChanged, Eldbus_Proxy_Event_Property_Changed, ) - #undef DEFINE_TYPE +#undef DEFINE_TYPE - std::shared_ptr eldbus_address_connection_get_impl(const std::string &addr) override + std::shared_ptr eldbus_address_connection_get_impl(const std::string& addr) override { eldbus_init(); auto p = eldbus_address_connection_get(addr.c_str()); @@ -262,14 +282,17 @@ struct DefaultDBusWrapper : public DBusWrapper return w; } -#define eldbus_message_iter_arguments_append_impl_basic(type, sig) \ - void eldbus_message_iter_arguments_append_impl(const MessageIterPtr &it, type src) override { \ - eldbus_message_iter_arguments_append( get(it), #sig, src ); \ - } \ - bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr &it, type &dst) override { \ - return eldbus_message_iter_get_and_next( get(it), (#sig)[0], &dst ); \ +#define eldbus_message_iter_arguments_append_impl_basic(type, sig) \ + void eldbus_message_iter_arguments_append_impl(const MessageIterPtr& it, type src) override \ + { \ + eldbus_message_iter_arguments_append(get(it), #sig, src); \ + } \ + bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr& it, type& dst) override \ + { \ + return eldbus_message_iter_get_and_next(get(it), (#sig)[0], &dst); \ } + // clang-format off eldbus_message_iter_arguments_append_impl_basic(uint8_t, y) eldbus_message_iter_arguments_append_impl_basic(uint16_t, q) eldbus_message_iter_arguments_append_impl_basic(uint32_t, u) @@ -278,34 +301,35 @@ struct DefaultDBusWrapper : public DBusWrapper eldbus_message_iter_arguments_append_impl_basic(int32_t, i) eldbus_message_iter_arguments_append_impl_basic(int64_t, x) eldbus_message_iter_arguments_append_impl_basic(double, d) + // clang-format on #undef eldbus_message_iter_arguments_append_impl_basic - void eldbus_message_iter_arguments_append_impl(const MessageIterPtr &it, bool src) override + void eldbus_message_iter_arguments_append_impl(const MessageIterPtr& it, bool src) override { - eldbus_message_iter_arguments_append( get(it), "b", src ? 1 : 0 ); + eldbus_message_iter_arguments_append(get(it), "b", src ? 1 : 0); } - bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr &it, bool &dst) override + bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr& it, bool& dst) override { unsigned char q; - auto z = eldbus_message_iter_get_and_next( get(it), 'b', &q ); - dst = q != 0; + auto z = eldbus_message_iter_get_and_next(get(it), 'b', &q); + dst = q != 0; return z; } - void eldbus_message_iter_arguments_append_impl(const MessageIterPtr &it, const std::string &src) override + void eldbus_message_iter_arguments_append_impl(const MessageIterPtr& it, const std::string& src) override { - eldbus_message_iter_arguments_append( get(it), "s", src.c_str() ); + eldbus_message_iter_arguments_append(get(it), "s", src.c_str()); } - bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr &it, std::string &dst) override + bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr& it, std::string& dst) override { - auto iter = get(it); + auto iter = get(it); const char* q; - if( !eldbus_message_iter_get_and_next( iter, 's', &q ) ) + if(!eldbus_message_iter_get_and_next(iter, 's', &q)) { - if( !eldbus_message_iter_get_and_next( iter, 'o', &q ) ) + if(!eldbus_message_iter_get_and_next(iter, 'o', &q)) { return false; } @@ -314,15 +338,15 @@ struct DefaultDBusWrapper : public DBusWrapper return true; } - void eldbus_message_iter_arguments_append_impl(const MessageIterPtr &it, const ObjectPath &src) override + void eldbus_message_iter_arguments_append_impl(const MessageIterPtr& it, const ObjectPath& src) override { - eldbus_message_iter_arguments_append( get(it), "o", src.value.c_str() ); + eldbus_message_iter_arguments_append(get(it), "o", src.value.c_str()); } - bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr &it, ObjectPath &dst) override + bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr& it, ObjectPath& dst) override { const char* q; - if( !eldbus_message_iter_get_and_next( get(it), 'o', &q ) ) + if(!eldbus_message_iter_get_and_next(get(it), 'o', &q)) { return false; } @@ -330,41 +354,41 @@ struct DefaultDBusWrapper : public DBusWrapper return true; } - MessageIterPtr eldbus_message_iter_container_new_impl(const MessageIterPtr &it, int type, const std::string &sig) override + MessageIterPtr eldbus_message_iter_container_new_impl(const MessageIterPtr& it, int type, const std::string& sig) override { - auto z = eldbus_message_iter_container_new( get(it), type, !sig.empty() ? sig.c_str() : NULL ); + auto z = eldbus_message_iter_container_new(get(it), type, !sig.empty() ? sig.c_str() : NULL); return create(z, get(it), true); } - MessageIterPtr eldbus_message_iter_get_and_next_by_type_impl(const MessageIterPtr &it, int type) override + MessageIterPtr eldbus_message_iter_get_and_next_by_type_impl(const MessageIterPtr& it, int type) override { Eldbus_Message_Iter* entry; - if (!eldbus_message_iter_get_and_next( get(it), type, &entry ) ) + if(!eldbus_message_iter_get_and_next(get(it), type, &entry)) { return {}; } return create(entry, get(it), false); } - MessageIterPtr eldbus_message_iter_get_impl(const MessagePtr &msg, bool) override + MessageIterPtr eldbus_message_iter_get_impl(const MessagePtr& msg, bool) override { return create(eldbus_message_iter_get(get(msg)), nullptr, false); } - MessagePtr eldbus_proxy_method_call_new_impl(const ProxyPtr &proxy, const std::string &funcName) + MessagePtr eldbus_proxy_method_call_new_impl(const ProxyPtr& proxy, const std::string& funcName) { - return create(eldbus_proxy_method_call_new( get(proxy), funcName.c_str() ) ); + return create(eldbus_proxy_method_call_new(get(proxy), funcName.c_str())); } - MessagePtr eldbus_proxy_send_and_block_impl(const ProxyPtr &proxy, const MessagePtr &msg) override + MessagePtr eldbus_proxy_send_and_block_impl(const ProxyPtr& proxy, const MessagePtr& msg) override { - return create(eldbus_proxy_send_and_block(get(proxy), release(msg), ELDBUS_CALL_TIMEOUT) ); + return create(eldbus_proxy_send_and_block(get(proxy), release(msg), ELDBUS_CALL_TIMEOUT)); } - bool eldbus_message_error_get_impl(const MessagePtr &msg, std::string &name, std::string &text) override + bool eldbus_message_error_get_impl(const MessagePtr& msg, std::string& name, std::string& text) override { const char *errname, *errmsg; - if( eldbus_message_error_get( get(msg), &errname, &errmsg ) ) + if(eldbus_message_error_get(get(msg), &errname, &errmsg)) { name = errname; text = errmsg; @@ -373,36 +397,36 @@ struct DefaultDBusWrapper : public DBusWrapper return false; } - std::string eldbus_message_signature_get_impl(const MessagePtr &msg) override + std::string eldbus_message_signature_get_impl(const MessagePtr& msg) override { return eldbus_message_signature_get(get(msg)); } - static void callAsyncCb( void* data, const Eldbus_Message *msg, Eldbus_Pending *pending ) + static void callAsyncCb(void* data, const Eldbus_Message* msg, Eldbus_Pending* pending) { - auto d = static_cast< SendCallback* >( data ); - (*d)( create(msg, false) ); + auto d = static_cast(data); + (*d)(create(msg, false)); } - static void pendingFreeCb( void* data, const void* ) + static void pendingFreeCb(void* data, const void*) { - auto d = static_cast< SendCallback* >( data ); + auto d = static_cast(data); delete d; } - static void listenerCallbackFree( void* data, const void* ) + static void listenerCallbackFree(void* data, const void*) { - auto d = static_cast< std::function< void( const Eldbus_Message* msg ) >* >( data ); + auto d = static_cast*>(data); delete d; } - PendingPtr eldbus_proxy_send_impl(const ProxyPtr &proxy, const MessagePtr &msg, const SendCallback &callback) override + PendingPtr eldbus_proxy_send_impl(const ProxyPtr& proxy, const MessagePtr& msg, const SendCallback& callback) override { - auto cb = new SendCallback{ callback }; - auto pending = eldbus_proxy_send( get(proxy), release(msg), callAsyncCb, cb, ELDBUS_CALL_TIMEOUT ); - if( pending ) + auto cb = new SendCallback{callback}; + auto pending = eldbus_proxy_send(get(proxy), release(msg), callAsyncCb, cb, ELDBUS_CALL_TIMEOUT); + if(pending) { - eldbus_pending_free_cb_add( pending, pendingFreeCb, cb ); + eldbus_pending_free_cb_add(pending, pendingFreeCb, cb); } else { @@ -411,72 +435,69 @@ struct DefaultDBusWrapper : public DBusWrapper return create(pending, false); } - std::string eldbus_proxy_interface_get_impl(const ProxyPtr &proxy) override + std::string eldbus_proxy_interface_get_impl(const ProxyPtr& proxy) override { - return eldbus_proxy_interface_get( get(proxy) ); + return eldbus_proxy_interface_get(get(proxy)); } - static void listenerCallback( void* data, const Eldbus_Message* msg ) + static void listenerCallback(void* data, const Eldbus_Message* msg) { - auto p = static_cast< std::function< void( const Eldbus_Message* msg ) >* >( data ); - ( *p )( msg ); + auto p = static_cast*>(data); + (*p)(msg); } - void eldbus_proxy_signal_handler_add_impl(const ProxyPtr &proxy, const std::string &member, const std::function &cb) override + void eldbus_proxy_signal_handler_add_impl(const ProxyPtr& proxy, const std::string& member, const std::function& cb) override { - auto tmp = new std::function< void( const Eldbus_Message* msg ) > - { - [cb](const Eldbus_Message* msg) - { + auto tmp = new std::function{ + [cb](const Eldbus_Message* msg) { cb(create(msg, false)); - } - }; - auto handler = eldbus_proxy_signal_handler_add( get(proxy), member.c_str(), listenerCallback, tmp ); - if( handler ) + }}; + auto handler = eldbus_proxy_signal_handler_add(get(proxy), member.c_str(), listenerCallback, tmp); + if(handler) { - eldbus_proxy_free_cb_add( get(proxy), listenerCallbackFree, tmp ); - } + eldbus_proxy_free_cb_add(get(proxy), listenerCallbackFree, tmp); + } else { delete tmp; - } + } } - std::string eldbus_message_iter_signature_get_impl(const MessageIterPtr &iter) override + std::string eldbus_message_iter_signature_get_impl(const MessageIterPtr& iter) override { - return eldbus_message_iter_signature_get( get(iter) ); + return eldbus_message_iter_signature_get(get(iter)); } - MessagePtr eldbus_message_method_return_new_impl( const MessagePtr &msg) override + MessagePtr eldbus_message_method_return_new_impl(const MessagePtr& msg) override { - return create(eldbus_message_method_return_new( get(msg) ) ); + return create(eldbus_message_method_return_new(get(msg))); } - MessagePtr eldbus_message_error_new_impl( const MessagePtr &msg, const std::string &err, const std::string &txt ) override + MessagePtr eldbus_message_error_new_impl(const MessagePtr& msg, const std::string& err, const std::string& txt) override { - return create(eldbus_message_error_new( get(msg), err.c_str(), txt.c_str() ) ); + return create(eldbus_message_error_new(get(msg), err.c_str(), txt.c_str())); } - PendingPtr eldbus_connection_send_impl(const ConnectionPtr &conn, const MessagePtr &msg) override + PendingPtr eldbus_connection_send_impl(const ConnectionPtr& conn, const MessagePtr& msg) override { - return create(eldbus_connection_send( get(conn), get(msg), NULL, NULL, -1 ) ); + return create(eldbus_connection_send(get(conn), get(msg), NULL, NULL, -1)); } - MessagePtr eldbus_message_signal_new_impl(const std::string &path, const std::string &iface, const std::string &name) override + MessagePtr eldbus_message_signal_new_impl(const std::string& path, const std::string& iface, const std::string& name) override { - return create(eldbus_message_signal_new( path.c_str(), iface.c_str(), name.c_str() ) ); + return create(eldbus_message_signal_new(path.c_str(), iface.c_str(), name.c_str())); } - MessagePtr eldbus_message_ref_impl(const MessagePtr &msg) override + MessagePtr eldbus_message_ref_impl(const MessagePtr& msg) override { - return create(eldbus_message_ref( get(msg) ), true ); + return create(eldbus_message_ref(get(msg)), true); } ConnectionPtr eldbus_connection_get_impl(ConnectionType type) override { Eldbus_Connection_Type eldbusType = ELDBUS_CONNECTION_TYPE_SYSTEM; - switch( type ) + switch(type) { case ConnectionType::SYSTEM: { @@ -491,91 +512,90 @@ struct DefaultDBusWrapper : public DBusWrapper } eldbus_init(); - auto p = eldbus_connection_get( eldbusType ); + auto p = eldbus_connection_get(eldbusType); auto w = create(p, true); eldbus_shutdown(); return w; } - std::string eldbus_connection_unique_name_get_impl(const ConnectionPtr &conn) override + std::string eldbus_connection_unique_name_get_impl(const ConnectionPtr& conn) override { - return eldbus_connection_unique_name_get( get(conn) ); + return eldbus_connection_unique_name_get(get(conn)); } - ObjectPtr eldbus_object_get_impl( const ConnectionPtr &conn, const std::string &bus, const std::string &path ) override + ObjectPtr eldbus_object_get_impl(const ConnectionPtr& conn, const std::string& bus, const std::string& path) override { - return create(eldbus_object_get(get(conn), bus.c_str(), path.c_str() ), true ); + return create(eldbus_object_get(get(conn), bus.c_str(), path.c_str()), true); } - ProxyPtr eldbus_proxy_get_impl( const ObjectPtr &obj, const std::string &interface ) override + ProxyPtr eldbus_proxy_get_impl(const ObjectPtr& obj, const std::string& interface) override { - return create(eldbus_proxy_get(get(obj), interface.c_str() ), false ); + return create(eldbus_proxy_get(get(obj), interface.c_str()), false); } - ProxyPtr eldbus_proxy_copy_impl( const ProxyPtr &ptr) override + ProxyPtr eldbus_proxy_copy_impl(const ProxyPtr& ptr) override { - return create(get(ptr), false ); + return create(get(ptr), false); } struct Implementation { - Eldbus_Service_Interface_Desc dsc; - std::vector< std::vector< Eldbus_Arg_Info > > argsInfos; - std::vector< Eldbus_Method > methods; - std::vector< Eldbus_Signal > signals; - std::vector< Eldbus_Property > properties; + Eldbus_Service_Interface_Desc dsc; + std::vector> argsInfos; + std::vector methods; + std::vector signals; + std::vector properties; - std::unordered_map< std::string, DBusWrapper::MethodInfo > methodsMap; - std::unordered_map< std::string, DBusWrapper::PropertyInfo > propertiesMap; - std::unordered_map< unsigned int, DBusWrapper::SignalInfo > signalsMap; + std::unordered_map methodsMap; + std::unordered_map propertiesMap; + std::unordered_map signalsMap; DBusWrapper::ConnectionWeakPtr connection; }; - static std::unordered_map< const Eldbus_Service_Interface*, std::unique_ptr< Implementation > > globalEntries; - static std::mutex globalEntriesMutex; + static std::unordered_map> globalEntries; + static std::mutex globalEntriesMutex; #undef EINA_FALSE #undef EINA_TRUE #define EINA_FALSE static_cast(0) #define EINA_TRUE static_cast(1) - static Eina_Bool property_get_callback( const Eldbus_Service_Interface* iface, const char* propertyName, Eldbus_Message_Iter* iter, - const Eldbus_Message* message, Eldbus_Message** error ) + static Eina_Bool property_get_callback(const Eldbus_Service_Interface* iface, const char* propertyName, Eldbus_Message_Iter* iter, const Eldbus_Message* message, Eldbus_Message** error) { Implementation* impl = nullptr; { - std::lock_guard< std::mutex > lock( globalEntriesMutex ); - auto it = globalEntries.find( iface ); - if( it != globalEntries.end() ) + std::lock_guard lock(globalEntriesMutex); + auto it = globalEntries.find(iface); + if(it != globalEntries.end()) { impl = it->second.get(); } } - if( !impl ) + if(!impl) { return EINA_FALSE; } - auto it = impl->propertiesMap.find( propertyName ); - if( it == impl->propertiesMap.end() || !it->second.getCallback ) + auto it = impl->propertiesMap.find(propertyName); + if(it == impl->propertiesMap.end() || !it->second.getCallback) { return EINA_FALSE; } auto connection = impl->connection.lock(); - if( !connection ) + if(!connection) { return EINA_FALSE; } - DBus::DBusServer::CurrentObjectSetter currentObjectSetter( connection, eldbus_message_path_get( message ) ); - auto reply = it->second.getCallback( create(message, false), create(iter, nullptr, false) ); - if( !reply.empty() ) + DBus::DBusServer::CurrentObjectSetter currentObjectSetter(connection, eldbus_message_path_get(message)); + auto reply = it->second.getCallback(create(message, false), create(iter, nullptr, false)); + if(!reply.empty()) { - if( error ) + if(error) { - *error = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", reply.c_str() ); + *error = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", reply.c_str()); } return EINA_FALSE; } @@ -583,226 +603,221 @@ struct DefaultDBusWrapper : public DBusWrapper return EINA_TRUE; } - static Eldbus_Message* property_set_callback( const Eldbus_Service_Interface* iface, const char* propertyName, Eldbus_Message_Iter* iter, - const Eldbus_Message* message ) + static Eldbus_Message* property_set_callback(const Eldbus_Service_Interface* iface, const char* propertyName, Eldbus_Message_Iter* iter, const Eldbus_Message* message) { Implementation* impl = nullptr; { - std::lock_guard< std::mutex > lock( globalEntriesMutex ); - auto it = globalEntries.find( iface ); - if( it != globalEntries.end() ) + std::lock_guard lock(globalEntriesMutex); + auto it = globalEntries.find(iface); + if(it != globalEntries.end()) { impl = it->second.get(); } } - if( !impl ) + if(!impl) { - auto ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", "Unknown interface" ); + auto ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", "Unknown interface"); return ret; } - auto it = impl->propertiesMap.find( propertyName ); - if( it == impl->propertiesMap.end() || !it->second.setCallback ) + auto it = impl->propertiesMap.find(propertyName); + if(it == impl->propertiesMap.end() || !it->second.setCallback) { - auto ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", "Unknown setter" ); + auto ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", "Unknown setter"); return ret; } auto connection = impl->connection.lock(); - if( !connection ) + if(!connection) { - auto ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", "Connection lost" ); + auto ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", "Connection lost"); return ret; } - DBus::DBusServer::CurrentObjectSetter currentObjectSetter( connection, eldbus_message_path_get( message ) ); - auto reply = it->second.setCallback( create(message, false), create(iter, nullptr, false) ); + DBus::DBusServer::CurrentObjectSetter currentObjectSetter(connection, eldbus_message_path_get(message)); + auto reply = it->second.setCallback(create(message, false), create(iter, nullptr, false)); Eldbus_Message* ret = nullptr; - if( !reply.empty() ) + if(!reply.empty()) { - ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", reply.c_str() ); + ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", reply.c_str()); } else { - ret = eldbus_message_method_return_new( message ); + ret = eldbus_message_method_return_new(message); } return ret; } - static Eldbus_Message* method_callback( const Eldbus_Service_Interface* iface, const Eldbus_Message* message ) + static Eldbus_Message* method_callback(const Eldbus_Service_Interface* iface, const Eldbus_Message* message) { Implementation* impl = nullptr; { - std::lock_guard< std::mutex > lock( globalEntriesMutex ); - auto it = globalEntries.find( iface ); - if( it != globalEntries.end() ) + std::lock_guard lock(globalEntriesMutex); + auto it = globalEntries.find(iface); + if(it != globalEntries.end()) impl = it->second.get(); } - if( !impl ) + if(!impl) { - auto ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", "Unknown interface" ); + auto ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", "Unknown interface"); return ret; } - std::string memberName = eldbus_message_member_get( message ); - auto it = impl->methodsMap.find( memberName ); - if( it == impl->methodsMap.end() ) + std::string memberName = eldbus_message_member_get(message); + auto it = impl->methodsMap.find(memberName); + if(it == impl->methodsMap.end()) { - auto ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", "Unknown method" ); + auto ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", "Unknown method"); return ret; } auto connection = impl->connection.lock(); - if( !connection ) + if(!connection) { - auto ret = eldbus_message_error_new( message, "org.freedesktop.DBus.Error.Failed", "Connection lost" ); + auto ret = eldbus_message_error_new(message, "org.freedesktop.DBus.Error.Failed", "Connection lost"); return ret; } - DBus::DBusServer::CurrentObjectSetter currentObjectSetter( connection, eldbus_message_path_get( message ) ); - auto reply = it->second.callback( create(message) ); + DBus::DBusServer::CurrentObjectSetter currentObjectSetter(connection, eldbus_message_path_get(message)); + auto reply = it->second.callback(create(message)); return release(reply); } - void add_interface_impl( bool fallback, const std::string& pathName, - const ConnectionPtr &connection, - std::vector> &destructors, - const std::string& interfaceName, - std::vector< MethodInfo >& dscrMethods, - std::vector< PropertyInfo >& dscrProperties, - std::vector< SignalInfo >& dscrSignals ) override - { - std::vector< Eldbus_Method > methods; - std::vector< Eldbus_Signal > signals; - std::vector< Eldbus_Property > properties; - std::vector< std::vector< Eldbus_Arg_Info > > argsInfos; - std::unordered_map< std::string, DBus::DBusInterfaceDescription::MethodInfo > methodsMap; - std::unordered_map< std::string, DBus::DBusInterfaceDescription::PropertyInfo > propertiesMap; - std::unordered_map< unsigned int, DBus::DBusInterfaceDescription::SignalInfo > signalsMap; - - DBUS_DEBUG( "interface %s path %s on bus %s", interfaceName.c_str(), pathName.c_str(), DBus::getConnectionName( connection ).c_str() ); - auto makeArgInfo = [&](const std::vector> &input) { + void add_interface_impl(bool fallback, + const std::string& pathName, + const ConnectionPtr& connection, + std::vector>& destructors, + const std::string& interfaceName, + std::vector& dscrMethods, + std::vector& dscrProperties, + std::vector& dscrSignals) override + { + std::vector methods; + std::vector signals; + std::vector properties; + std::vector> argsInfos; + std::unordered_map methodsMap; + std::unordered_map propertiesMap; + std::unordered_map signalsMap; + + DBUS_DEBUG("interface %s path %s on bus %s", interfaceName.c_str(), pathName.c_str(), DBus::getConnectionName(connection).c_str()); + auto makeArgInfo = [&](const std::vector>& input) { argsInfos.push_back({}); - auto &dst = argsInfos.back(); - for(auto &s : input) + auto& dst = argsInfos.back(); + for(auto& s : input) { auto a = Strings.add(s.first); auto b = Strings.add(s.second); - dst.push_back({ a, b }); + dst.push_back({a, b}); } - dst.push_back({ nullptr, nullptr }); + dst.push_back({nullptr, nullptr}); return dst.data(); }; - for( auto& ee : dscrMethods ) + for(auto& ee : dscrMethods) { auto key = ee.memberName; - DBUS_DEBUG( "adding method %s", ee.memberName.c_str() ); - for( auto& r : ee.in ) + DBUS_DEBUG("adding method %s", ee.memberName.c_str()); + for(auto& r : ee.in) { - DBUS_DEBUG( "in %s '%s'", r.first.c_str(), r.second.c_str() ); + DBUS_DEBUG("in %s '%s'", r.first.c_str(), r.second.c_str()); } - for( auto& r : ee.out ) + for(auto& r : ee.out) { - DBUS_DEBUG( "out %s '%s'", r.first.c_str(), r.second.c_str() ); + DBUS_DEBUG("out %s '%s'", r.first.c_str(), r.second.c_str()); } - auto& e = ( methodsMap[key] = std::move( ee ) ); - methods.push_back( {} ); - auto& m = methods.back(); + auto& e = (methodsMap[key] = std::move(ee)); + methods.push_back({}); + auto& m = methods.back(); m.member = e.memberName.c_str(); - m.in = makeArgInfo(e.in); - m.out = makeArgInfo(e.out); - m.cb = method_callback; - m.flags = 0; + m.in = makeArgInfo(e.in); + m.out = makeArgInfo(e.out); + m.cb = method_callback; + m.flags = 0; } - for( auto& ee : dscrProperties ) + for(auto& ee : dscrProperties) { auto key = ee.memberName; - DBUS_DEBUG( "adding property %s", ee.memberName.c_str() ); - auto& e = ( propertiesMap[key] = std::move( ee ) ); - properties.push_back( {} ); - auto& m = properties.back(); - m.name = e.memberName.c_str(); - m.type = e.typeSignature.c_str(); + DBUS_DEBUG("adding property %s", ee.memberName.c_str()); + auto& e = (propertiesMap[key] = std::move(ee)); + properties.push_back({}); + auto& m = properties.back(); + m.name = e.memberName.c_str(); + m.type = e.typeSignature.c_str(); m.get_func = e.getCallback ? property_get_callback : nullptr; m.set_func = e.setCallback ? property_set_callback : nullptr; - m.flags = 0; + m.flags = 0; } dscrMethods.clear(); dscrProperties.clear(); dscrSignals.clear(); - methods.push_back( {nullptr, nullptr, nullptr, nullptr, 0} ); - signals.push_back( {nullptr, nullptr, 0} ); - properties.push_back( {nullptr, nullptr, nullptr, nullptr, 0} ); - - auto impl = std::unique_ptr< Implementation >( new Implementation{ - {interfaceName.c_str(), - methods.data(), - signals.data(), - properties.data(), - nullptr, - nullptr}, - std::move( argsInfos ), - std::move( methods ), - std::move( signals ), - std::move( properties ), - std::move( methodsMap ), - std::move( propertiesMap ), - std::move( signalsMap ), - connection} ); - - { - std::lock_guard< std::mutex > lock( globalEntriesMutex ); - auto v = fallback ? eldbus_service_interface_fallback_register( get(connection), pathName.c_str(), &impl->dsc ) : eldbus_service_interface_register( get(connection), pathName.c_str(), &impl->dsc ); - assert( v ); - globalEntries[v] = std::move( impl ); - DBUS_DEBUG( "registering interface %p (%d)", v, fallback ? 1 : 0 ); - destructors.push_back([=]() + methods.push_back({nullptr, nullptr, nullptr, nullptr, 0}); + signals.push_back({nullptr, nullptr, 0}); + properties.push_back({nullptr, nullptr, nullptr, nullptr, 0}); + + auto impl = std::unique_ptr(new Implementation{ + {interfaceName.c_str(), + methods.data(), + signals.data(), + properties.data(), + nullptr, + nullptr}, + std::move(argsInfos), + std::move(methods), + std::move(signals), + std::move(properties), + std::move(methodsMap), + std::move(propertiesMap), + std::move(signalsMap), + connection}); + + { + std::lock_guard lock(globalEntriesMutex); + auto v = fallback ? eldbus_service_interface_fallback_register(get(connection), pathName.c_str(), &impl->dsc) : eldbus_service_interface_register(get(connection), pathName.c_str(), &impl->dsc); + assert(v); + globalEntries[v] = std::move(impl); + DBUS_DEBUG("registering interface %p (%d)", v, fallback ? 1 : 0); + destructors.push_back([=]() { + DBUS_DEBUG("unregistering interface %p", v); { - DBUS_DEBUG( "unregistering interface %p", v ); - { - std::lock_guard< std::mutex > lock( globalEntriesMutex ); - globalEntries.erase( v ); - } - eldbus_service_interface_unregister( v ); + std::lock_guard lock(globalEntriesMutex); + globalEntries.erase(v); } - ); + eldbus_service_interface_unregister(v); + }); } } - static void listenerEventChangedCallback( void* data, Eldbus_Proxy* proxy EINA_UNUSED, void* event ) + static void listenerEventChangedCallback(void* data, Eldbus_Proxy* proxy EINA_UNUSED, void* event) { - auto p = static_cast< std::function< void( Eldbus_Proxy_Event_Property_Changed* ) >* >( data ); - ( *p )( static_cast< Eldbus_Proxy_Event_Property_Changed* >( event ) ); + auto p = static_cast*>(data); + (*p)(static_cast(event)); } - static void ProxyEventCallbackDelCb( void* data, const void *obj ) + static void ProxyEventCallbackDelCb(void* data, const void* obj) { - auto d = static_cast< std::function< void( Eldbus_Proxy_Event_Property_Changed* ) >* >( data ); + auto d = static_cast*>(data); delete d; } - void add_property_changed_event_listener_impl( const ProxyPtr &proxy, const std::string &interface, const std::string &name, std::function< void( const Eina_Value * ) > cb) override + void add_property_changed_event_listener_impl(const ProxyPtr& proxy, const std::string& interface, const std::string& name, std::function cb) override { - auto callbackLambdaPtr = new std::function< void( Eldbus_Proxy_Event_Property_Changed *epc ) > - { - [cb, name, interface]( Eldbus_Proxy_Event_Property_Changed *ev ) - { - const char* ifc = eldbus_proxy_interface_get( ev->proxy ); - if( ev->name && ev->name == name && ifc && interface == ifc ) + auto callbackLambdaPtr = new std::function{ + [cb, name, interface](Eldbus_Proxy_Event_Property_Changed* ev) { + const char* ifc = eldbus_proxy_interface_get(ev->proxy); + if(ev->name && ev->name == name && ifc && interface == ifc) { cb(ev->value); } - } - }; + }}; auto p = get(proxy); - eldbus_proxy_event_callback_add( p, ELDBUS_PROXY_EVENT_PROPERTY_CHANGED, listenerEventChangedCallback, callbackLambdaPtr ); - eldbus_proxy_free_cb_add( p, ProxyEventCallbackDelCb, callbackLambdaPtr ); + eldbus_proxy_event_callback_add(p, ELDBUS_PROXY_EVENT_PROPERTY_CHANGED, listenerEventChangedCallback, callbackLambdaPtr); + eldbus_proxy_free_cb_add(p, ProxyEventCallbackDelCb, callbackLambdaPtr); } }; -std::unordered_map< const Eldbus_Service_Interface*, std::unique_ptr< DefaultDBusWrapper::Implementation > > DefaultDBusWrapper::globalEntries; -std::mutex DefaultDBusWrapper::globalEntriesMutex; +std::unordered_map> DefaultDBusWrapper::globalEntries; +std::mutex DefaultDBusWrapper::globalEntriesMutex; -DBusWrapper *DBusWrapper::Installed() +DBusWrapper* DBusWrapper::Installed() { - if (!InstalledWrapper) + if(!InstalledWrapper) { InstalledWrapper.reset(new DefaultDBusWrapper); } diff --git a/dali/internal/accessibility/bridge/dbus.h b/dali/internal/accessibility/bridge/dbus.h index f2afcb0..c983902 100644 --- a/dali/internal/accessibility/bridge/dbus.h +++ b/dali/internal/accessibility/bridge/dbus.h @@ -36,8 +36,8 @@ #include // INTERNAL INCLUDES -#include #include +#include #define ATSPI_PREFIX_PATH "/org/a11y/atspi/accessible/" #define ATSPI_NULL_PATH "/org/a11y/atspi/null" @@ -60,65 +60,71 @@ struct DALI_ADAPTOR_API DBusWrapper }; #define DEFINE_TYPE(name, eldbus_name, unref_call) \ - struct name { virtual ~name() = default; }; \ - using name ## Ptr = std::shared_ptr; \ - using name ## WeakPtr = std::weak_ptr; \ + struct name \ + { \ + virtual ~name() = default; \ + }; \ + using name##Ptr = std::shared_ptr; \ + using name##WeakPtr = std::weak_ptr; DEFINE_TYPE(Connection, Eldbus_Connection, ) - DEFINE_TYPE(MessageIter, Eldbus_Message_Iter, eldbus_message_iter_container_close(Value)) - DEFINE_TYPE(Message, Eldbus_Message, eldbus_message_unref(Value)) - DEFINE_TYPE(Proxy, Eldbus_Proxy, eldbus_proxy_unref(Value)) - DEFINE_TYPE(Object, Eldbus_Object, eldbus_object_unref(Value)) - DEFINE_TYPE(Pending, Eldbus_Pending, ) - DEFINE_TYPE(EventPropertyChanged, Eldbus_Proxy_Event_Property_Changed, ) + DEFINE_TYPE(MessageIter, Eldbus_Message_Iter, eldbus_message_iter_container_close(Value)) + DEFINE_TYPE(Message, Eldbus_Message, eldbus_message_unref(Value)) + DEFINE_TYPE(Proxy, Eldbus_Proxy, eldbus_proxy_unref(Value)) + DEFINE_TYPE(Object, Eldbus_Object, eldbus_object_unref(Value)) + DEFINE_TYPE(Pending, Eldbus_Pending, ) + DEFINE_TYPE(EventPropertyChanged, Eldbus_Proxy_Event_Property_Changed, ) #undef DEFINE_TYPE - virtual ConnectionPtr eldbus_address_connection_get_impl(const std::string& addr) = 0; + virtual ConnectionPtr eldbus_address_connection_get_impl(const std::string& addr) = 0; -#define eldbus_message_iter_arguments_append_impl_basic_impl(type_set, type_get, sig) \ - virtual void eldbus_message_iter_arguments_append_impl(const MessageIterPtr &it, type_set src) = 0; \ - virtual bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr &it, type_get &dst) = 0; +#define eldbus_message_iter_arguments_append_impl_basic_impl(type_set, type_get, sig) \ + virtual void eldbus_message_iter_arguments_append_impl(const MessageIterPtr& it, type_set src) = 0; \ + virtual bool eldbus_message_iter_get_and_next_impl(const MessageIterPtr& it, type_get& dst) = 0; #define eldbus_message_iter_arguments_append_impl_basic(type, sig) \ eldbus_message_iter_arguments_append_impl_basic_impl(type, type, sig) + // clang-format off eldbus_message_iter_arguments_append_impl_basic(uint8_t, y) - eldbus_message_iter_arguments_append_impl_basic(uint16_t, q) - eldbus_message_iter_arguments_append_impl_basic(uint32_t, u) - eldbus_message_iter_arguments_append_impl_basic(uint64_t, t) - eldbus_message_iter_arguments_append_impl_basic(int16_t, n) - eldbus_message_iter_arguments_append_impl_basic(int32_t, i) - eldbus_message_iter_arguments_append_impl_basic(int64_t, x) - eldbus_message_iter_arguments_append_impl_basic(double, d) - eldbus_message_iter_arguments_append_impl_basic(bool, b) - eldbus_message_iter_arguments_append_impl_basic_impl(const std::string&, std::string, s) - eldbus_message_iter_arguments_append_impl_basic_impl(const ObjectPath&, ObjectPath, o) + eldbus_message_iter_arguments_append_impl_basic(uint16_t, q) + eldbus_message_iter_arguments_append_impl_basic(uint32_t, u) + eldbus_message_iter_arguments_append_impl_basic(uint64_t, t) + eldbus_message_iter_arguments_append_impl_basic(int16_t, n) + eldbus_message_iter_arguments_append_impl_basic(int32_t, i) + eldbus_message_iter_arguments_append_impl_basic(int64_t, x) + eldbus_message_iter_arguments_append_impl_basic(double, d) + eldbus_message_iter_arguments_append_impl_basic(bool, b) + eldbus_message_iter_arguments_append_impl_basic_impl(const std::string&, std::string, s) + eldbus_message_iter_arguments_append_impl_basic_impl(const ObjectPath&, ObjectPath, o) #undef eldbus_message_iter_arguments_append_impl_basic #undef eldbus_message_iter_arguments_append_impl_basic_impl - virtual MessageIterPtr eldbus_message_iter_container_new_impl(const MessageIterPtr& it, int type, const std::string& sig) = 0; - virtual MessageIterPtr eldbus_message_iter_get_and_next_by_type_impl(const MessageIterPtr& it, int type) = 0; - virtual MessageIterPtr eldbus_message_iter_get_impl(const MessagePtr& it, bool write) = 0; - virtual MessagePtr eldbus_proxy_method_call_new_impl(const ProxyPtr& proxy, const std::string& funcName) = 0; - virtual MessagePtr eldbus_proxy_send_and_block_impl(const ProxyPtr& proxy, const MessagePtr& msg) = 0; - virtual bool eldbus_message_error_get_impl(const MessagePtr& msg, std::string& name, std::string& text) = 0; - virtual std::string eldbus_message_signature_get_impl(const MessagePtr& msg) = 0; - - using SendCallback = std::function; - virtual PendingPtr eldbus_proxy_send_impl(const ProxyPtr& proxy, const MessagePtr& msg, const SendCallback& callback) = 0; - virtual std::string eldbus_proxy_interface_get_impl(const ProxyPtr&) = 0; - virtual void eldbus_proxy_signal_handler_add_impl(const ProxyPtr& proxy, const std::string& member, const std::function& cb) = 0; - virtual std::string eldbus_message_iter_signature_get_impl(const MessageIterPtr& iter) = 0; - virtual MessagePtr eldbus_message_method_return_new_impl(const MessagePtr& msg) = 0; - virtual MessagePtr eldbus_message_error_new_impl(const MessagePtr& msg, const std::string& err, const std::string& txt) = 0; - virtual PendingPtr eldbus_connection_send_impl(const ConnectionPtr& conn, const MessagePtr& msg) = 0; - virtual MessagePtr eldbus_message_signal_new_impl(const std::string& path, const std::string& iface, const std::string& name) = 0; - virtual MessagePtr eldbus_message_ref_impl(const MessagePtr& msg) = 0; - virtual ConnectionPtr eldbus_connection_get_impl(ConnectionType type) = 0; - virtual std::string eldbus_connection_unique_name_get_impl(const ConnectionPtr& conn) = 0; - virtual ObjectPtr eldbus_object_get_impl(const ConnectionPtr& conn, const std::string& bus, const std::string& path) = 0; - virtual ProxyPtr eldbus_proxy_get_impl(const ObjectPtr& obj, const std::string& interface) = 0; - virtual ProxyPtr eldbus_proxy_copy_impl(const ProxyPtr& ptr) = 0; + virtual MessageIterPtr eldbus_message_iter_container_new_impl(const MessageIterPtr& it, int type, const std::string& sig) = 0; + virtual MessageIterPtr eldbus_message_iter_get_and_next_by_type_impl(const MessageIterPtr& it, int type) = 0; + virtual MessageIterPtr eldbus_message_iter_get_impl(const MessagePtr& it, bool write) = 0; + virtual MessagePtr eldbus_proxy_method_call_new_impl(const ProxyPtr& proxy, const std::string& funcName) = 0; + virtual MessagePtr eldbus_proxy_send_and_block_impl(const ProxyPtr& proxy, const MessagePtr& msg) = 0; + virtual bool eldbus_message_error_get_impl(const MessagePtr& msg, std::string& name, std::string& text) = 0; + virtual std::string eldbus_message_signature_get_impl(const MessagePtr& msg) = 0; + // clang-format on + + using SendCallback = std::function; + + virtual PendingPtr eldbus_proxy_send_impl(const ProxyPtr& proxy, const MessagePtr& msg, const SendCallback& callback) = 0; + virtual std::string eldbus_proxy_interface_get_impl(const ProxyPtr&) = 0; + virtual void eldbus_proxy_signal_handler_add_impl(const ProxyPtr& proxy, const std::string& member, const std::function& cb) = 0; + virtual std::string eldbus_message_iter_signature_get_impl(const MessageIterPtr& iter) = 0; + virtual MessagePtr eldbus_message_method_return_new_impl(const MessagePtr& msg) = 0; + virtual MessagePtr eldbus_message_error_new_impl(const MessagePtr& msg, const std::string& err, const std::string& txt) = 0; + virtual PendingPtr eldbus_connection_send_impl(const ConnectionPtr& conn, const MessagePtr& msg) = 0; + virtual MessagePtr eldbus_message_signal_new_impl(const std::string& path, const std::string& iface, const std::string& name) = 0; + virtual MessagePtr eldbus_message_ref_impl(const MessagePtr& msg) = 0; + virtual ConnectionPtr eldbus_connection_get_impl(ConnectionType type) = 0; + virtual std::string eldbus_connection_unique_name_get_impl(const ConnectionPtr& conn) = 0; + virtual ObjectPtr eldbus_object_get_impl(const ConnectionPtr& conn, const std::string& bus, const std::string& path) = 0; + virtual ProxyPtr eldbus_proxy_get_impl(const ObjectPtr& obj, const std::string& interface) = 0; + virtual ProxyPtr eldbus_proxy_copy_impl(const ProxyPtr& ptr) = 0; class StringStorage { @@ -130,12 +136,12 @@ struct DALI_ADAPTOR_API DBusWrapper free(p); } }; - std::vector< std::unique_ptr< char, char_ptr_deleter > > storage; + std::vector> storage; const char* add(const char* txt) { auto ptr = strdup(txt); - storage.push_back(std::unique_ptr< char, char_ptr_deleter >(ptr)); + storage.push_back(std::unique_ptr(ptr)); return storage.back().get(); } const char* add(const std::string& txt) @@ -146,128 +152,263 @@ struct DALI_ADAPTOR_API DBusWrapper struct CallId { - static std::atomic< unsigned int > LastId; - unsigned int id = ++LastId; + static std::atomic LastId; + unsigned int id = ++LastId; }; struct MethodInfo { - CallId id; - std::string memberName; - std::vector< std::pair > in, out; // _Eldbus_Arg_Info - std::function< DBusWrapper::MessagePtr(const DBusWrapper::MessagePtr & msg) > callback; + CallId id; + std::string memberName; + std::vector> in, out; // _Eldbus_Arg_Info + std::function callback; }; struct SignalInfo { - CallId id; - std::string memberName; - std::vector< std::pair > args; - unsigned int uniqueId; + CallId id; + std::string memberName; + std::vector> args; + unsigned int uniqueId; }; struct PropertyInfo { - CallId setterId, getterId; - std::string memberName, typeSignature; - std::function< std::string(const DBusWrapper::MessagePtr & src, const DBusWrapper::MessageIterPtr & dst) > getCallback, setCallback; + CallId setterId, getterId; + std::string memberName, typeSignature; + std::function getCallback, setCallback; }; struct SignalId { CallId id; SignalId() = default; - SignalId(CallId id) : id(id) {} + SignalId(CallId id) + : id(id) + { + } }; - virtual void add_interface_impl(bool fallback, const std::string& pathName, - const ConnectionPtr& connection, - std::vector>& destructors, - const std::string& interfaceName, - std::vector< MethodInfo >& dscrMethods, - std::vector< PropertyInfo >& dscrProperties, - std::vector< SignalInfo >& dscrSignals) = 0; - virtual void add_property_changed_event_listener_impl(const ProxyPtr& proxy, const std::string& interface, const std::string& name, std::function< void(const _Eina_Value*) > cb) = 0; + virtual void add_interface_impl(bool fallback, const std::string& pathName, const ConnectionPtr& connection, std::vector>& destructors, const std::string& interfaceName, std::vector& dscrMethods, std::vector& dscrProperties, std::vector& dscrSignals) = 0; + virtual void add_property_changed_event_listener_impl(const ProxyPtr& proxy, const std::string& interface, const std::string& name, std::function cb) = 0; static DBusWrapper* Installed(); - static void Install(std::unique_ptr); + static void Install(std::unique_ptr); StringStorage Strings; }; -namespace detail { - enum class MethodType { - Method, Getter, Setter - }; +namespace detail +{ +enum class MethodType +{ + Method, + Getter, + Setter +}; } -namespace std { - template <> struct hash> { - size_t operator () (const std::tuple& a) const { - auto a1 = std::hash()(std::get<0>(a)); - auto a2 = std::hash()(std::get<1>(a)); - auto a3 = std::hash()(std::get<2>(a)); - size_t v = a1; - v = (v * 11400714819323198485llu) + a2; - v = (v * 11400714819323198485llu) + a3; - return v; - } +namespace std +{ +template<> +struct hash> +{ + size_t operator()(const std::tuple& a) const + { + auto a1 = std::hash()(std::get<0>(a)); + auto a2 = std::hash()(std::get<1>(a)); + auto a3 = std::hash()(std::get<2>(a)); + size_t v = a1; + v = (v * 11400714819323198485llu) + a2; + v = (v * 11400714819323198485llu) + a3; + return v; + } +}; +template<> +struct hash> +{ + size_t operator()(const std::tuple& a) const + { + auto a1 = std::hash()(std::get<0>(a)); + auto a2 = std::hash()(std::get<1>(a)); + auto a3 = std::hash()(std::get<2>(a)); + auto a4 = static_cast(std::get<3>(a)); + size_t v = a1; + v = (v * 11400714819323198485llu) + a2; + v = (v * 11400714819323198485llu) + a3; + v = (v * 11400714819323198485llu) + a4; + return v; + } +}; +template<> +struct hash> +{ + size_t operator()(const std::tuple& a) const + { + auto a1 = std::hash()(std::get<0>(a)); + auto a2 = std::hash()(std::get<1>(a)); + auto a3 = std::get<2>(a); + size_t v = a1; + v = (v * 11400714819323198485llu) + a2; + v = (v * 11400714819323198485llu) + a3; + return v; + } +}; +} // namespace std + +namespace detail +{ +template +struct DBusSigImpl +{ + enum + { + value = 0, + end = 0 }; - template <> struct hash> { - size_t operator () (const std::tuple& a) const { - auto a1 = std::hash()(std::get<0>(a)); - auto a2 = std::hash()(std::get<1>(a)); - auto a3 = std::hash()(std::get<2>(a)); - auto a4 = static_cast(std::get<3>(a)); - size_t v = a1; - v = (v * 11400714819323198485llu) + a2; - v = (v * 11400714819323198485llu) + a3; - v = (v * 11400714819323198485llu) + a4; - return v; - } +}; +template +struct DBusSig +{ + enum + { + value = DBusSigImpl::type>::value, + end = DBusSigImpl::type>::end }; - template <> struct hash> { - size_t operator () (const std::tuple& a) const { - auto a1 = std::hash()(std::get<0>(a)); - auto a2 = std::hash()(std::get<1>(a)); - auto a3 = std::get<2>(a); - size_t v = a1; - v = (v * 11400714819323198485llu) + a2; - v = (v * 11400714819323198485llu) + a3; - return v; - } +}; +template +struct IndexFromTypeTupleImpl +{ + enum + { + value = std::is_same::type>::type, Q>::value ? I : IndexFromTypeTupleImpl::value }; -} - -namespace detail { - template struct DBusSigImpl { enum { value = 0, end = 0 }; }; - template struct DBusSig { enum { value = DBusSigImpl::type>::value, end = DBusSigImpl::type>::end }; }; - template struct IndexFromTypeTupleImpl { - enum { value = std::is_same::type>::type, Q>::value ? I : IndexFromTypeTupleImpl::value }; +}; +template +struct IndexFromTypeTupleImpl +{ + enum + { + value = S }; - template struct IndexFromTypeTupleImpl { enum { value = S }; }; - template struct IndexFromTypeTuple { - enum { value = IndexFromTypeTupleImpl::type, 0, std::tuple_size::value>::value }; +}; +template +struct IndexFromTypeTuple +{ + enum + { + value = IndexFromTypeTupleImpl::type, 0, std::tuple_size::value>::value }; - template struct Encoder; - template struct EncoderTuple; -} - -namespace detail { - template <> struct DBusSigImpl { enum { value = 'y', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'q', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'u', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 't', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'n', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'i', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'x', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'd', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'b', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 's', end = 0 }; }; - template <> struct DBusSigImpl { enum { value = 'o', end = 0 }; }; -} +}; +template +struct Encoder; +template +struct EncoderTuple; +} // namespace detail +namespace detail +{ +template<> +struct DBusSigImpl +{ + enum + { + value = 'y', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'q', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'u', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 't', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'n', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'i', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'x', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'd', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'b', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 's', + end = 0 + }; +}; +template<> +struct DBusSigImpl +{ + enum + { + value = 'o', + end = 0 + }; +}; +} // namespace detail -#define DBUS_DEBUG( ... ) \ - do \ - { \ - DBus::debugPrint( __FILE__, __LINE__, __VA_ARGS__ ); \ - } while( 0 ) +#define DBUS_DEBUG(...) \ + do \ + { \ + DBus::debugPrint(__FILE__, __LINE__, __VA_ARGS__); \ + } while(0) #define DBUS_W DBusWrapper::Installed() @@ -312,42 +453,41 @@ namespace detail { */ namespace DBus { +class DBusServer; +class DBusClient; +class DBusInterfaceDescription; - class DBusServer; - class DBusClient; - class DBusInterfaceDescription; - - /** +/** * @brief Formats debug message and calls debug printer (if any) with it */ - void debugPrint(const char* file, size_t line, const char* format, ...); +void debugPrint(const char* file, size_t line, const char* format, ...); - /** +/** * @brief Sets debug printer callback, which will be called with debug messages * * Callback will be called in various moments of DBus activity. First value passed to callback * is pointer to text, second it's length. Text is ended with 0 (not counted towards it's size), * user can safely printf it. */ - void setDebugPrinter(std::function< void(const char*, size_t) >); - - struct Error - { - std::string message; +void setDebugPrinter(std::function); - Error() = default; - Error(std::string msg) : message(std::move(msg)) - { - assert(!message.empty()); - } - }; +struct Error +{ + std::string message; - struct Success + Error() = default; + Error(std::string msg) + : message(std::move(msg)) { - }; + assert(!message.empty()); + } +}; +struct Success +{ +}; - /** +/** * @brief Value representing data, that came from DBUS or error message * * Object of this class either helds series of values (of types ARGS...) @@ -361,165 +501,175 @@ namespace DBus * Both mean the same - ValueOrError containing no real data and being a marker, * wherever operation successed or failed and containing possible error message. */ - template < typename... ARGS > - class ValueOrError - { - public: - /** +template +class ValueOrError +{ +public: + /** * @brief Empty constructor. Valid only, if all ARGS types are default constructible. */ - ValueOrError() = default; + ValueOrError() = default; - /** + /** * @brief Value constructor. * * This will be initialized as success with passed in values. */ - ValueOrError(ARGS... t) : value(std::move(t)...) {} + ValueOrError(ARGS... t) + : value(std::move(t)...) + { + } - /** + /** * @brief Alternative Value constructor. * * This will be initialized as success with passed in values. */ - ValueOrError(std::tuple< ARGS... > t) : value(std::move(t)) {} + ValueOrError(std::tuple t) + : value(std::move(t)) + { + } - /** + /** * @brief Error constructor. This will be initialized as failure with given error message. */ - ValueOrError(Error e) : error(std::move(e)) - { - assert(!error.message.empty()); - } + ValueOrError(Error e) + : error(std::move(e)) + { + assert(!error.message.empty()); + } - /** + /** * @brief bool operator. * * Returns true, if operation was successful (getValues member is callable), or false * when operation failed (getError is callable). */ - explicit operator bool() const - { - return error.message.empty(); - } + explicit operator bool() const + { + return error.message.empty(); + } - /** + /** * @brief Returns error message object. * * Returns object containing error message associated with the failed operation. * Only callable, if operation actually failed, otherwise will assert. */ - const Error& getError() const - { - return error; - } + const Error& getError() const + { + return error; + } - /** + /** * @brief Returns modifiable tuple of held data. * * Returns reference to the internal tuple containing held data. * User can modify (or move) data safely. * Only callable, if operation actually successed, otherwise will assert. */ - std::tuple< ARGS... >& getValues() - { - assert(*this); - return value; - } + std::tuple& getValues() + { + assert(*this); + return value; + } - /** + /** * @brief Returns const tuple of held data. * * Returns const reference to the internal tuple containing held data. * Only callable, if operation actually successed, otherwise will assert. */ - const std::tuple< ARGS... >& getValues() const - { - assert(*this); - return value; - } - - protected: - std::tuple< ARGS... > value; - Error error; - - }; + const std::tuple& getValues() const + { + assert(*this); + return value; + } +protected: + std::tuple value; + Error error; +}; - template <> - class ValueOrError<> +template<> +class ValueOrError<> +{ +public: + ValueOrError() = default; + ValueOrError(std::tuple<> t) { - public: - ValueOrError() = default; - ValueOrError(std::tuple<> t) {} - ValueOrError(Error e) : error(std::move(e)) - { - assert(!error.message.empty()); - } + } + ValueOrError(Error e) + : error(std::move(e)) + { + assert(!error.message.empty()); + } - explicit operator bool() const - { - return error.message.empty(); - } - const Error& getError() const - { - return error; - } - std::tuple<>& getValues() - { - assert(*this); - static std::tuple<> t; - return t; - } - std::tuple<> getValues() const - { - assert(*this); - return {}; - } + explicit operator bool() const + { + return error.message.empty(); + } + const Error& getError() const + { + return error; + } + std::tuple<>& getValues() + { + assert(*this); + static std::tuple<> t; + return t; + } + std::tuple<> getValues() const + { + assert(*this); + return {}; + } - protected: - Error error; - }; +protected: + Error error; +}; - template <> - class ValueOrError< void > +template<> +class ValueOrError +{ +public: + ValueOrError() = default; + ValueOrError(Success) { - public: - ValueOrError() = default; - ValueOrError(Success) {} - ValueOrError(Error e) : error(std::move(e)) - { - assert(!error.message.empty()); - } - - explicit operator bool() const - { - return error.message.empty(); - } - const Error& getError() const - { - return error; - } - std::tuple<>& getValues() - { - assert(*this); - static std::tuple<> t; - return t; - } - std::tuple<> getValues() const - { - assert(*this); - return {}; - } + } + ValueOrError(Error e) + : error(std::move(e)) + { + assert(!error.message.empty()); + } - protected: - Error error; - }; + explicit operator bool() const + { + return error.message.empty(); + } + const Error& getError() const + { + return error; + } + std::tuple<>& getValues() + { + assert(*this); + static std::tuple<> t; + return t; + } + std::tuple<> getValues() const + { + assert(*this); + return {}; + } - using ObjectPath = ObjectPath; +protected: + Error error; +}; +using ObjectPath = ObjectPath; - /** +/** * @brief Class used to marshall DBUS's variant type * * Minimalistic class, that allows user to specify DBUS variant type @@ -528,630 +678,636 @@ namespace DBus * as return data in variant. So for example user can't specify method call, which on return * expects DBUS variant holding either string or int. */ - template < typename A > - struct EldbusVariant - { - A value; - }; +template +struct EldbusVariant +{ + A value; +}; - /** +/** * @brief Namespace for private, internal functions and classes */ - namespace detail - { - inline namespace strings { - template - using char_array = std::array; - - constexpr char *xcopy_n(const char *src, size_t n, char *dst) - { - for (std::size_t i = 0; i < n; ++i) - dst[i] = src[i]; +namespace detail +{ +inline namespace strings +{ +template +using char_array = std::array; - return dst + n; - } +constexpr char* xcopy_n(const char* src, size_t n, char* dst) +{ + for(std::size_t i = 0; i < n; ++i) + dst[i] = src[i]; - template - constexpr std::size_t xlen(const char (&)[N]) - { - return N - 1; - } + return dst + n; +} - template - constexpr std::size_t xlen(const char_array &) - { - return N - 1; - } +template +constexpr std::size_t xlen(const char (&)[N]) +{ + return N - 1; +} - template - constexpr auto concat(const Args &... args) - { - char_array<(1U + ... + xlen(args))> arr{}; - char *ptr = arr.data(); +template +constexpr std::size_t xlen(const char_array&) +{ + return N - 1; +} - if constexpr (!arr.empty()) - ((ptr = xcopy_n(std::data(args), xlen(args), ptr)), ...); +template +constexpr auto concat(const Args&... args) +{ + char_array<(1U + ... + xlen(args))> arr{}; + char* ptr = arr.data(); - return arr; - } + if constexpr(!arr.empty()) + ((ptr = xcopy_n(std::data(args), xlen(args), ptr)), ...); - template - struct to_chars { - static constexpr const char value[] = {('0' + static_cast(Digits))..., '\0'}; + return arr; +} - static_assert((true && ... && (Digits < 10))); - }; +template +struct to_chars +{ + static constexpr const char value[] = {('0' + static_cast(Digits))..., '\0'}; - template - struct to_chars_helper : to_chars_helper {}; + static_assert((true && ... && (Digits < 10))); +}; - template - struct to_chars_helper<0, Digits...> : to_chars {}; +template +struct to_chars_helper : to_chars_helper +{ +}; - template - using to_string = to_chars_helper; - } +template +struct to_chars_helper<0, Digits...> : to_chars +{ +}; - template < typename T, typename = void > - struct signature; - template < typename... ARGS > - struct signature< std::tuple< ARGS... > >; - template < typename A, typename B > - struct signature< std::pair< A, B > >; - template < typename A > - struct signature< std::vector< A > >; - template < typename A, size_t N > - struct signature< std::array< A, N > >; - template < typename A, typename B > - struct signature< std::unordered_map< A, B > >; - template < typename A, typename B > - struct signature< std::map< A, B > >; - - template - struct signature_helper - { - /** +template +using to_string = to_chars_helper; +} // namespace strings + +template +struct signature; +template +struct signature>; +template +struct signature>; +template +struct signature>; +template +struct signature>; +template +struct signature>; +template +struct signature>; + +template +struct signature_helper +{ + /** * @brief Returns name of type marshalled, for informative purposes */ - static constexpr std::string_view name() - { - return {T::name_v.data()}; - } + static constexpr std::string_view name() + { + return {T::name_v.data()}; + } - /** + /** * @brief Returns DBUS' signature of type marshalled */ - static constexpr std::string_view sig() - { - return {T::sig_v.data()}; - } - }; + static constexpr std::string_view sig() + { + return {T::sig_v.data()}; + } +}; - /** +/** * @brief Signature class for marshalling uint8 type. */ - template <> - struct signature< uint8_t > : signature_helper> - { - static constexpr auto name_v = concat("uint8_t"); - static constexpr auto sig_v = concat("y"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("uint8_t"); + static constexpr auto sig_v = concat("y"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, uint8_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, uint8_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, uint8_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, uint8_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling uint16 type. */ - template <> - struct signature< uint16_t > : signature_helper> - { - static constexpr auto name_v = concat("uint16_t"); - static constexpr auto sig_v = concat("q"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("uint16_t"); + static constexpr auto sig_v = concat("q"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, uint16_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, uint16_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, uint16_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, uint16_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling uint32 type. */ - template <> - struct signature< uint32_t > : signature_helper> - { - static constexpr auto name_v = concat("uint32_t"); - static constexpr auto sig_v = concat("u"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("uint32_t"); + static constexpr auto sig_v = concat("u"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, uint32_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, uint32_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, uint32_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, uint32_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling uint64 type. */ - template <> - struct signature< uint64_t > : signature_helper> - { - static constexpr auto name_v = concat("uint64_t"); - static constexpr auto sig_v = concat("t"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("uint64_t"); + static constexpr auto sig_v = concat("t"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, uint64_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, uint64_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, uint64_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, uint64_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling int16 type. */ - template <> - struct signature< int16_t > : signature_helper> - { - static constexpr auto name_v = concat("int16_t"); - static constexpr auto sig_v = concat("n"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("int16_t"); + static constexpr auto sig_v = concat("n"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, int16_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, int16_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, int16_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, int16_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling int32 type. */ - template <> - struct signature< int32_t > : signature_helper> - { - static constexpr auto name_v = concat("int32_t"); - static constexpr auto sig_v = concat("i"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("int32_t"); + static constexpr auto sig_v = concat("i"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, int32_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, int32_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, int32_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, int32_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling int64 type. */ - template <> - struct signature< int64_t > : signature_helper> - { - static constexpr auto name_v = concat("int64_t"); - static constexpr auto sig_v = concat("x"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("int64_t"); + static constexpr auto sig_v = concat("x"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, int64_t v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, int64_t v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, int64_t& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, int64_t& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - /** +/** * @brief Signature class for marshalling double type. */ - template <> - struct signature< double > : signature_helper> - { - static constexpr auto name_v = concat("double"); - static constexpr auto sig_v = concat("d"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("double"); + static constexpr auto sig_v = concat("d"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, double v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, double v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, double& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } + static bool get(const DBusWrapper::MessageIterPtr& iter, double& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, float& v2) - { - double v = 0; - auto r = DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - v2 = static_cast(v); - return r; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, float& v2) + { + double v = 0; + auto r = DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + v2 = static_cast(v); + return r; + } +}; - /** +/** * @brief Signature class for marshalling float type. */ - template <> - struct signature< float > : signature_helper> - { - static constexpr auto name_v = concat("float"); - static constexpr auto sig_v = concat("d"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("float"); + static constexpr auto sig_v = concat("d"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, float v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, float v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, double& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } + static bool get(const DBusWrapper::MessageIterPtr& iter, double& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, float& v2) - { - double v = 0; - auto r = DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - v2 = static_cast(v); - return r; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, float& v2) + { + double v = 0; + auto r = DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + v2 = static_cast(v); + return r; + } +}; - /** +/** * @brief Signature class for marshalling boolean type. */ - template <> - struct signature< bool > : signature_helper> - { - static constexpr auto name_v = concat("bool"); - static constexpr auto sig_v = concat("b"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("bool"); + static constexpr auto sig_v = concat("b"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, bool v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, bool v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, bool& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, bool& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - template < typename T > - struct signature, void>> : signature_helper> - { - static constexpr auto name_v = concat("enum"); - static constexpr auto sig_v = signature::type>::sig_v; +template +struct signature, void>> : signature_helper> +{ + static constexpr auto name_v = concat("enum"); + static constexpr auto sig_v = signature::type>::sig_v; - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, T v) - { - signature::type>::set(iter, static_cast(v)); - } + static void set(const DBusWrapper::MessageIterPtr& iter, T v) + { + signature::type>::set(iter, static_cast(v)); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, T& v) - { - typename std::underlying_type::type q = 0; - if (!signature::type>::get(iter, q)) - return false; + static bool get(const DBusWrapper::MessageIterPtr& iter, T& v) + { + typename std::underlying_type::type q = 0; + if(!signature::type>::get(iter, q)) + return false; - v = static_cast(q); - return true; - } - }; + v = static_cast(q); + return true; + } +}; - /** +/** * @brief Signature class for marshalling string type. * * Both (const) char * and std::string types are accepted as value to send. * Only std::string is accepted as value to receive. */ - template <> - struct signature< std::string > : signature_helper> - { - static constexpr auto name_v = concat("string"); - static constexpr auto sig_v = concat("s"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("string"); + static constexpr auto sig_v = concat("s"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::string& v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::string& v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::string& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::string& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } +}; - template <> - struct signature< ObjectPath > : signature_helper> - { - static constexpr auto name_v = concat("path"); - static constexpr auto sig_v = concat("o"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("path"); + static constexpr auto sig_v = concat("o"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::string& v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, ObjectPath{ v }); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::string& v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, ObjectPath{v}); + } - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const ObjectPath& v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const ObjectPath& v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const char* v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, ObjectPath{ v }); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const char* v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, ObjectPath{v}); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, ObjectPath& v) - { - return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); - } + static bool get(const DBusWrapper::MessageIterPtr& iter, ObjectPath& v) + { + return DBUS_W->eldbus_message_iter_get_and_next_impl(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::string& v) - { - ObjectPath q; - if (!DBUS_W->eldbus_message_iter_get_and_next_impl(iter, q)) return false; - v = std::move(q.value); - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::string& v) + { + ObjectPath q; + if(!DBUS_W->eldbus_message_iter_get_and_next_impl(iter, q)) return false; + v = std::move(q.value); + return true; + } +}; - /** +/** * @brief Signature class for marshalling (const) char * type. * * Both (const) char * and std::string types are accepted as value to send. * You can't use (const) char * variable type to receive value. */ - template <> - struct signature< char* > : signature_helper> - { - static constexpr auto name_v = concat("string"); - static constexpr auto sig_v = concat("s"); +template<> +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("string"); + static constexpr auto sig_v = concat("s"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::string& v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::string& v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, v); + } - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const char* v) - { - DBUS_W->eldbus_message_iter_arguments_append_impl(iter, std::string{ v }); - } - }; - - template < size_t INDEX, typename A, typename... ARGS > - struct signature_tuple_element_type_helper - { - using type = typename signature_tuple_element_type_helper< INDEX - 1, ARGS... >::type; - }; + static void set(const DBusWrapper::MessageIterPtr& iter, const char* v) + { + DBUS_W->eldbus_message_iter_arguments_append_impl(iter, std::string{v}); + } +}; - template < typename A, typename... ARGS > - struct signature_tuple_element_type_helper< 0, A, ARGS... > - { - using type = A; - }; +template +struct signature_tuple_element_type_helper +{ + using type = typename signature_tuple_element_type_helper::type; +}; - /** +template +struct signature_tuple_element_type_helper<0, A, ARGS...> +{ + using type = A; +}; + +/** * @brief Helper class to marshall tuples * * This class marshals all elements of the tuple value starting at the index INDEX * and incrementing. This class recursively calls itself with increasing INDEX value * until INDEX is equal to SIZE, where recursive calling ends. */ - template < size_t INDEX, size_t SIZE, typename... ARGS > - struct signature_tuple_helper : signature_helper> - { - using current_type = typename signature_tuple_element_type_helper< INDEX, ARGS... >::type; +template +struct signature_tuple_helper : signature_helper> +{ + using current_type = typename signature_tuple_element_type_helper::type; - static constexpr auto name_v = concat(signature::name_v, ", ", signature_tuple_helper::name_v); - static constexpr auto sig_v = concat(signature::sig_v, signature_tuple_helper::sig_v); + static constexpr auto name_v = concat(signature::name_v, ", ", signature_tuple_helper::name_v); + static constexpr auto sig_v = concat(signature::sig_v, signature_tuple_helper::sig_v); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::tuple< ARGS... >& args) - { - signature< current_type >::set(iter, std::get< INDEX >(args)); - signature_tuple_helper< INDEX + 1, SIZE, ARGS... >::set(iter, args); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::tuple& args) + { + signature::set(iter, std::get(args)); + signature_tuple_helper::set(iter, args); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::tuple< ARGS... >& args) - { - return signature< current_type >::get(iter, std::get< INDEX >(args)) && - signature_tuple_helper< INDEX + 1, SIZE, ARGS... >::get(iter, args); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::tuple& args) + { + return signature::get(iter, std::get(args)) && + signature_tuple_helper::get(iter, args); + } +}; - /** +/** * @brief Helper class to marshall tuples * * This class marks end of the tuple marshalling. Members of this class are called * when INDEX value is equal to SIZE. */ - template < size_t SIZE, typename... ARGS > - struct signature_tuple_helper< SIZE, SIZE, ARGS... > : signature_helper> - { - static constexpr auto name_v = concat(""); - static constexpr auto sig_v = concat(""); +template +struct signature_tuple_helper : signature_helper> +{ + static constexpr auto name_v = concat(""); + static constexpr auto sig_v = concat(""); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::tuple< ARGS... >& args) - { - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::tuple& args) + { + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::tuple< ARGS... >& args) - { - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::tuple& args) + { + return true; + } +}; - /** +/** * @brief Signature class for marshalling tuple of values * * This class marshalls tuple of values. This represents * DBUS struct typle, encoded with character 'r' */ - template < typename... ARGS > - struct signature< std::tuple< ARGS... > > : signature_helper>> - { - static constexpr auto name_v = concat("tuple<", signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::name_v, ">"); - static constexpr auto sig_v = concat("(", signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::sig_v, ")"); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("tuple<", signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::name_v, ">"); + static constexpr auto sig_v = concat("(", signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::sig_v, ")"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::tuple< ARGS... >& args) - { - auto entry = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'r', ""); - signature_tuple_helper< 0, sizeof...(ARGS), ARGS... >::set(entry, args); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::tuple& args) + { + auto entry = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'r', ""); + signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::set(entry, args); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::tuple< ARGS... >& args) - { - auto entry = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'r'); - if (!entry) return false; - return signature_tuple_helper< 0, sizeof...(ARGS), ARGS... >::get(entry, args); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::tuple& args) + { + auto entry = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'r'); + if(!entry) return false; + return signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::get(entry, args); + } +}; - /** +/** * @brief Signature class for marshalling ValueOrError template type * * ValueOrError template type is used to marshall list of values passed to @@ -1162,241 +1318,242 @@ namespace DBus * or * \code{.cpp} ValueOrError>> \endcode */ - template < typename... ARGS > - struct signature< ValueOrError< ARGS... > > : signature_helper>> - { - static constexpr auto name_v = concat("ValueOrError<", signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::name_v, ">"); - static constexpr auto sig_v = signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::sig_v; +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("ValueOrError<", signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::name_v, ">"); + static constexpr auto sig_v = signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::sig_v; - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const ValueOrError< ARGS... >& args) - { - signature_tuple_helper< 0, sizeof...(ARGS), ARGS... >::set(iter, args.getValues()); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const ValueOrError& args) + { + signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::set(iter, args.getValues()); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, ValueOrError< ARGS... >& args) - { - return signature_tuple_helper< 0, sizeof...(ARGS), ARGS... >::get(iter, args.getValues()); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, ValueOrError& args) + { + return signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::get(iter, args.getValues()); + } +}; - /** +/** * @brief Signature class for marshalling ValueOrError type */ - template <> - struct signature< ValueOrError< void > > : signature_helper>> - { - static constexpr auto name_v = concat("ValueOrError"); - static constexpr auto sig_v = concat(""); +template<> +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("ValueOrError"); + static constexpr auto sig_v = concat(""); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const ValueOrError< void >& args) - { - } + static void set(const DBusWrapper::MessageIterPtr& iter, const ValueOrError& args) + { + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, ValueOrError< void >& args) - { - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, ValueOrError& args) + { + return true; + } +}; - /** +/** * @brief Signature class for marshalling ValueOrError<> type */ - template <> - struct signature< ValueOrError<> > : signature_helper>> - { - static constexpr auto name_v = concat("ValueOrError<>"); - static constexpr auto sig_v = concat(""); +template<> +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("ValueOrError<>"); + static constexpr auto sig_v = concat(""); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const ValueOrError<>& args) - { - } + static void set(const DBusWrapper::MessageIterPtr& iter, const ValueOrError<>& args) + { + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, ValueOrError<>& args) - { - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, ValueOrError<>& args) + { + return true; + } +}; - /** +/** * @brief Signature class for marshalling pair of types */ - template < typename A, typename B > - struct signature< std::pair< A, B > > : signature_helper>> - { - static constexpr auto name_v = concat("pair<", signature_tuple_helper<0, 2, A, B>::name_v, ">"); - static constexpr auto sig_v = concat("(", signature_tuple_helper<0, 2, A, B>::sig_v, ")"); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("pair<", signature_tuple_helper<0, 2, A, B>::name_v, ">"); + static constexpr auto sig_v = concat("(", signature_tuple_helper<0, 2, A, B>::sig_v, ")"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::pair< A, B >& ab, bool dictionary = false) - { - auto entry = DBUS_W->eldbus_message_iter_container_new_impl(iter, dictionary ? 'e' : 'r', ""); - signature_tuple_helper< 0, 2, A, B >::set(entry, ab); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::pair& ab, bool dictionary = false) + { + auto entry = DBUS_W->eldbus_message_iter_container_new_impl(iter, dictionary ? 'e' : 'r', ""); + signature_tuple_helper<0, 2, A, B>::set(entry, ab); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::pair< A, B >& ab) - { - auto entry = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'r'); - if (!entry) { - entry = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, '{'); - if (!entry) return false; - } + static bool get(const DBusWrapper::MessageIterPtr& iter, std::pair& ab) + { + auto entry = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'r'); + if(!entry) + { + entry = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, '{'); + if(!entry) return false; + } - std::tuple< A, B > ab_tmp; - auto z = signature_tuple_helper< 0, 2, A, B >::get(entry, ab_tmp); - if (z) - { - ab.first = std::move(std::get< 0 >(ab_tmp)); - ab.second = std::move(std::get< 1 >(ab_tmp)); - } - return z; - } - }; + std::tuple ab_tmp; + auto z = signature_tuple_helper<0, 2, A, B>::get(entry, ab_tmp); + if(z) + { + ab.first = std::move(std::get<0>(ab_tmp)); + ab.second = std::move(std::get<1>(ab_tmp)); + } + return z; + } +}; - /** +/** * @brief Signature class for marshalling std::vector template type * * This marshals container's content as DBUS a ascii character type code. */ - template < typename A > - struct signature< std::vector< A > > : signature_helper>> - { - static constexpr auto name_v = concat("vector<", signature::name_v, ">"); - static constexpr auto sig_v = concat("a", signature::sig_v); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("vector<", signature::name_v, ">"); + static constexpr auto sig_v = concat("a", signature::sig_v); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::vector< A >& v) - { - auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', std::string{signature< A >::sig()}); - assert(lst); - for (auto& a : v) - { - signature< A >::set(lst, a); - } - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::vector& v) + { + auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', std::string{signature::sig()}); + assert(lst); + for(auto& a : v) + { + signature::set(lst, a); + } + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::vector< A >& v) - { - auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); - if (!s) return false; - v.clear(); - A a; - while (signature< A >::get(s, a)) - v.push_back(std::move(a)); - - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::vector& v) + { + auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); + if(!s) return false; + v.clear(); + A a; + while(signature::get(s, a)) + v.push_back(std::move(a)); + + return true; + } +}; - /** +/** * @brief Signature class for marshalling std::array template type * * This marshals container's content as DBUS a ascii character type code. */ - template < typename A, size_t N > - struct signature< std::array< A, N > > : signature_helper>> - { - static constexpr auto name_v = concat("array<", signature::name_v, ", ", to_string::value, ">"); - static constexpr auto sig_v = concat("a", signature::sig_v); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("array<", signature::name_v, ", ", to_string::value, ">"); + static constexpr auto sig_v = concat("a", signature::sig_v); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::array< A, N >& v) - { - auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', std::string{signature< A >::sig()}); - assert(lst); - for (auto& a : v) - { - signature< A >::set(lst, a); - } - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::array& v) + { + auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', std::string{signature::sig()}); + assert(lst); + for(auto& a : v) + { + signature::set(lst, a); + } + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::array< A, N >& v) - { - auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); - if (!s) - return false; - for (auto& a : v) - { - if (!signature< A >::get(s, a)) - return false; - } - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::array& v) + { + auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); + if(!s) + return false; + for(auto& a : v) + { + if(!signature::get(s, a)) + return false; + } + return true; + } +}; - /** +/** * @brief Signature class for marshalling EldbusVariant type * * This marshals variant's content as DBUS v ascii character type code. */ - template < typename A > - struct signature< EldbusVariant< A > > : signature_helper>> - { - static constexpr auto name_v = concat("variant<", signature::name_v, ">"); - static constexpr auto sig_v = concat("v"); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("variant<", signature::name_v, ">"); + static constexpr auto sig_v = concat("v"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const EldbusVariant< A >& v) - { - set(iter, v.value); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const EldbusVariant& v) + { + set(iter, v.value); + } - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) - { - auto var = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'v', std::string{signature< A >::sig()}); - signature< A >::set(var, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) + { + auto var = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'v', std::string{signature::sig()}); + signature::set(var, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, EldbusVariant< A >& v) - { - auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'v'); - if (!s) - return false; - return signature< A >::get(s, v.value); - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, EldbusVariant& v) + { + auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'v'); + if(!s) + return false; + return signature::get(s, v.value); + } +}; - /** +/** * @brief Signature class for marshalling std::unordered_map template type * * This marshals container's content as DBUS {} ascii character type code. @@ -1406,43 +1563,43 @@ namespace DBus * User can receive such values as std::vector of std::pair values. * Order of such values is unspecified. */ - template < typename A, typename B > - struct signature< std::unordered_map< A, B > > : signature_helper>> - { - static constexpr auto name_v = concat("unordered_map<", signature::name_v, ", ", signature::name_v, ">"); - static constexpr auto sig_v = concat("a{", signature_tuple_helper<0, 2, A, B>::sig_v, "}"); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("unordered_map<", signature::name_v, ", ", signature::name_v, ">"); + static constexpr auto sig_v = concat("a{", signature_tuple_helper<0, 2, A, B>::sig_v, "}"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::unordered_map< A, B >& v) - { - auto sig = "{" + std::string{signature_tuple_helper< 0, 2, A, B >::sig()} + "}"; - auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', sig); - assert(lst); - for (auto& a : v) - { - signature< std::pair< A, B > >::set(lst, a, true); - } - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::unordered_map& v) + { + auto sig = "{" + std::string{signature_tuple_helper<0, 2, A, B>::sig()} + "}"; + auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', sig); + assert(lst); + for(auto& a : v) + { + signature>::set(lst, a, true); + } + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::unordered_map< A, B >& v) - { - auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); - v.clear(); - if (!s) - return false; - std::pair< A, B > a; - while (signature< std::pair< A, B > >::get(s, a)) - v.insert(std::move(a)); - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::unordered_map& v) + { + auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); + v.clear(); + if(!s) + return false; + std::pair a; + while(signature>::get(s, a)) + v.insert(std::move(a)); + return true; + } +}; - /** +/** * @brief Signature class for marshalling std::unordered_map template type * * This marshals container's content as DBUS {} ascii character type code. @@ -1452,432 +1609,428 @@ namespace DBus * User can receive such values as std::vector of std::pair values. * Order of such values is unspecified. */ - template < typename A, typename B > - struct signature< std::map< A, B > > : signature_helper>> - { - static constexpr auto name_v = concat("map<", signature::name_v, ", ", signature::name_v, ">"); - static constexpr auto sig_v = concat("a{", signature_tuple_helper<0, 2, A, B>::sig_v, "}"); +template +struct signature> : signature_helper>> +{ + static constexpr auto name_v = concat("map<", signature::name_v, ", ", signature::name_v, ">"); + static constexpr auto sig_v = concat("a{", signature_tuple_helper<0, 2, A, B>::sig_v, "}"); - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const std::map< A, B >& v) - { - auto sig = "{" + std::string{signature_tuple_helper< 0, 2, A, B >::sig()} + "}"; - auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', sig); - assert(lst); - for (auto& a : v) - { - signature< std::pair< A, B > >::set(lst, a, true); - } - } + static void set(const DBusWrapper::MessageIterPtr& iter, const std::map& v) + { + auto sig = "{" + std::string{signature_tuple_helper<0, 2, A, B>::sig()} + "}"; + auto lst = DBUS_W->eldbus_message_iter_container_new_impl(iter, 'a', sig); + assert(lst); + for(auto& a : v) + { + signature>::set(lst, a, true); + } + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static bool get(const DBusWrapper::MessageIterPtr& iter, std::map< A, B >& v) - { - auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); - if (!s) - return false; - std::pair< A, B > a; - while (signature< std::pair< A, B > >::get(s, a)) - v.insert(std::move(a)); - return true; - } - }; + static bool get(const DBusWrapper::MessageIterPtr& iter, std::map& v) + { + auto s = DBUS_W->eldbus_message_iter_get_and_next_by_type_impl(iter, 'a'); + if(!s) + return false; + std::pair a; + while(signature>::get(s, a)) + v.insert(std::move(a)); + return true; + } +}; - /** +/** * @brief Signature helper class for marshalling const reference types */ - template < typename A > - struct signature< const A& > : signature_helper> - { - static constexpr auto name_v = concat("const ", signature::name_v, "&"); - static constexpr auto sig_v = signature::sig_v; +template +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("const ", signature::name_v, "&"); + static constexpr auto sig_v = signature::sig_v; - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) - { - signature< A >::set(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) + { + signature::set(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static void get(const DBusWrapper::MessageIterPtr& iter, A& v) - { - signature< A >::get(iter, v); - } - }; + static void get(const DBusWrapper::MessageIterPtr& iter, A& v) + { + signature::get(iter, v); + } +}; - /** +/** * @brief Signature helper class for marshalling reference types */ - template < typename A > - struct signature< A& > : signature_helper> - { - static constexpr auto name_v = concat(signature::name_v, "&"); - static constexpr auto sig_v = signature::sig_v; +template +struct signature : signature_helper> +{ + static constexpr auto name_v = concat(signature::name_v, "&"); + static constexpr auto sig_v = signature::sig_v; - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) - { - signature< A >::set(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) + { + signature::set(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static void get(const DBusWrapper::MessageIterPtr& iter, A& v) - { - signature< A >::get(iter, v); - } - }; + static void get(const DBusWrapper::MessageIterPtr& iter, A& v) + { + signature::get(iter, v); + } +}; - /** +/** * @brief Signature helper class for marshalling const types */ - template < typename A > - struct signature< const A > : signature_helper> - { - static constexpr auto name_v = concat("const ", signature::name_v); - static constexpr auto sig_v = signature::sig_v; +template +struct signature : signature_helper> +{ + static constexpr auto name_v = concat("const ", signature::name_v); + static constexpr auto sig_v = signature::sig_v; - /** + /** * @brief Marshals value v as marshalled type into message */ - static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) - { - signature< A >::set(iter, v); - } + static void set(const DBusWrapper::MessageIterPtr& iter, const A& v) + { + signature::set(iter, v); + } - /** + /** * @brief Marshals value from marshalled type into variable v */ - static void get(const DBusWrapper::MessageIterPtr& iter, A& v) - { - signature< A >::get(iter, v); - } - }; + static void get(const DBusWrapper::MessageIterPtr& iter, A& v) + { + signature::get(iter, v); + } +}; - using CallId = DBusWrapper::CallId; +using CallId = DBusWrapper::CallId; - template < typename ValueType > - ValueType unpackValues(CallId callId, const DBusWrapper::MessagePtr& msg) - { - static const std::string sig{signature< ValueType >::sig().data()}; +template +ValueType unpackValues(CallId callId, const DBusWrapper::MessagePtr& msg) +{ + static const std::string sig{signature::sig().data()}; - auto iter = DBUS_W->eldbus_message_iter_get_impl(msg, false); - ValueType r; + auto iter = DBUS_W->eldbus_message_iter_get_impl(msg, false); + ValueType r; - if (iter) - { - if (!signature< ValueType >::get(iter, r)) - { - DBUS_DEBUG("ValueType is %s", signature< ValueType >::name().data()); - r = Error{ "call " + std::to_string(callId.id) + ": failed to unpack values, got signature '" + - DBUS_W->eldbus_message_signature_get_impl(msg) + "', expected '" + sig + "'" }; - } - } - else - { - r = Error{ "call " + std::to_string(callId.id) + ": failed to get iterator" }; - } - return r; + if(iter) + { + if(!signature::get(iter, r)) + { + DBUS_DEBUG("ValueType is %s", signature::name().data()); + r = Error{"call " + std::to_string(callId.id) + ": failed to unpack values, got signature '" + + DBUS_W->eldbus_message_signature_get_impl(msg) + "', expected '" + sig + "'"}; } + } + else + { + r = Error{"call " + std::to_string(callId.id) + ": failed to get iterator"}; + } + return r; +} - inline void packValues_helper(const DBusWrapper::MessageIterPtr&) {} +inline void packValues_helper(const DBusWrapper::MessageIterPtr&) +{ +} - template < typename A, typename... ARGS > - void packValues_helper(const DBusWrapper::MessageIterPtr& iter, A&& a, ARGS&&... r) - { - signature< A >::set(iter, std::forward< A >(a)); - packValues_helper(iter, std::forward< ARGS >(r)...); - } +template +void packValues_helper(const DBusWrapper::MessageIterPtr& iter, A&& a, ARGS&&... r) +{ + signature::set(iter, std::forward(a)); + packValues_helper(iter, std::forward(r)...); +} - template < typename... ARGS > - void packValues(CallId callId, const DBusWrapper::MessagePtr& msg, ARGS&&... r) - { - auto iter = DBUS_W->eldbus_message_iter_get_impl(msg, true); - packValues_helper(iter, std::forward< ARGS >(r)...); - } +template +void packValues(CallId callId, const DBusWrapper::MessagePtr& msg, ARGS&&... r) +{ + auto iter = DBUS_W->eldbus_message_iter_get_impl(msg, true); + packValues_helper(iter, std::forward(r)...); +} - struct ConnectionState - { - DBusWrapper::ConnectionPtr connection; - DBusWrapper::ObjectPtr object; - DBusWrapper::ProxyPtr proxy, propertiesProxy; - }; +struct ConnectionState +{ + DBusWrapper::ConnectionPtr connection; + DBusWrapper::ObjectPtr object; + DBusWrapper::ProxyPtr proxy, propertiesProxy; +}; - template < typename RETTYPE, typename... ARGS > - RETTYPE call(CallId callId, const ConnectionState& connectionState, bool property, const std::string& funcName, const ARGS&... args) - { - const auto& proxy = property ? connectionState.propertiesProxy : connectionState.proxy; - if (!proxy) - { - DBUS_DEBUG("call %d: not initialized", callId.id); - return Error{ "not initialized" }; - } +template +RETTYPE call(CallId callId, const ConnectionState& connectionState, bool property, const std::string& funcName, const ARGS&... args) +{ + const auto& proxy = property ? connectionState.propertiesProxy : connectionState.proxy; + if(!proxy) + { + DBUS_DEBUG("call %d: not initialized", callId.id); + return Error{"not initialized"}; + } - DBUS_DEBUG("call %d: calling '%s'", callId.id, funcName.c_str()); - auto msg = DBUS_W->eldbus_proxy_method_call_new_impl(proxy, funcName); - if (!msg) - { - DBUS_DEBUG("call %d: failed", callId.id); - return Error{ "failed to create message" }; - } + DBUS_DEBUG("call %d: calling '%s'", callId.id, funcName.c_str()); + auto msg = DBUS_W->eldbus_proxy_method_call_new_impl(proxy, funcName); + if(!msg) + { + DBUS_DEBUG("call %d: failed", callId.id); + return Error{"failed to create message"}; + } - detail::packValues(callId, msg, args...); - auto reply = DBUS_W->eldbus_proxy_send_and_block_impl(proxy, msg); - DBUS_DEBUG("call %d: calling '%s' done", callId.id, funcName.c_str()); - if (!reply) - { - DBUS_DEBUG("call %d: failed", callId.id); - return Error{ "eldbus returned null as reply" }; - } - std::string errname, errmsg; - if (DBUS_W->eldbus_message_error_get_impl(reply, errname, errmsg)) - { - DBUS_DEBUG("call %d: %s: %s", callId.id, errname.c_str(), errmsg.c_str()); - return Error{ errname + ": " + errmsg }; - } - DBUS_DEBUG("call %d: got reply with signature '%s'", callId.id, - DBUS_W->eldbus_message_signature_get_impl(reply).c_str()); - return detail::unpackValues< RETTYPE >(callId, reply); - } + detail::packValues(callId, msg, args...); + auto reply = DBUS_W->eldbus_proxy_send_and_block_impl(proxy, msg); + DBUS_DEBUG("call %d: calling '%s' done", callId.id, funcName.c_str()); + if(!reply) + { + DBUS_DEBUG("call %d: failed", callId.id); + return Error{"eldbus returned null as reply"}; + } + std::string errname, errmsg; + if(DBUS_W->eldbus_message_error_get_impl(reply, errname, errmsg)) + { + DBUS_DEBUG("call %d: %s: %s", callId.id, errname.c_str(), errmsg.c_str()); + return Error{errname + ": " + errmsg}; + } + DBUS_DEBUG("call %d: got reply with signature '%s'", callId.id, DBUS_W->eldbus_message_signature_get_impl(reply).c_str()); + return detail::unpackValues(callId, reply); +} - template < typename RETTYPE, typename... ARGS > - void asyncCall(CallId callId, const ConnectionState& connectionState, - bool property, const std::string& funcName, - std::function< void(RETTYPE) > callback, const ARGS&... args) - { - const auto& proxy = property ? connectionState.propertiesProxy : connectionState.proxy; - if (!proxy) - { - DBUS_DEBUG("call %d: not initialized", callId.id); - callback(Error{ "not initialized" }); - return; - } +template +void asyncCall(CallId callId, const ConnectionState& connectionState, bool property, const std::string& funcName, std::function callback, const ARGS&... args) +{ + const auto& proxy = property ? connectionState.propertiesProxy : connectionState.proxy; + if(!proxy) + { + DBUS_DEBUG("call %d: not initialized", callId.id); + callback(Error{"not initialized"}); + return; + } - auto msg = DBUS_W->eldbus_proxy_method_call_new_impl(proxy, funcName); - if (!msg) - { - DBUS_DEBUG("call %d: failed", callId.id); - callback(Error{ "failed to create message" }); - return; - } + auto msg = DBUS_W->eldbus_proxy_method_call_new_impl(proxy, funcName); + if(!msg) + { + DBUS_DEBUG("call %d: failed", callId.id); + callback(Error{"failed to create message"}); + return; + } - detail::packValues(callId, msg, args...); - auto pending = DBUS_W->eldbus_proxy_send_impl(proxy, msg, [callback, callId, proxy](const DBusWrapper::MessagePtr& reply) { - DBUS_DEBUG("call %d: calling done", callId.id); - if (!reply) - { - DBUS_DEBUG("call %d: failed", callId.id); - callback(Error{ "eldbus returned null as reply" }); - } - else - { - std::string errname, errmsg; - if (DBUS_W->eldbus_message_error_get_impl(reply, errname, errmsg)) - { - DBUS_DEBUG("call %d: %s: %s", callId.id, errname.c_str(), errmsg.c_str()); - callback(Error{ errname + ": " + errmsg }); - } - else - { - DBUS_DEBUG("call %d: got reply with signature '%s'", callId.id, - DBUS_W->eldbus_message_signature_get_impl(reply).c_str()); - callback(detail::unpackValues< RETTYPE >(callId, reply)); - } - } - } - ); - if (pending) + detail::packValues(callId, msg, args...); + auto pending = DBUS_W->eldbus_proxy_send_impl(proxy, msg, [callback, callId, proxy](const DBusWrapper::MessagePtr& reply) { + DBUS_DEBUG("call %d: calling done", callId.id); + if(!reply) + { + DBUS_DEBUG("call %d: failed", callId.id); + callback(Error{"eldbus returned null as reply"}); + } + else + { + std::string errname, errmsg; + if(DBUS_W->eldbus_message_error_get_impl(reply, errname, errmsg)) { - DBUS_DEBUG("call %d: call sent", callId.id); + DBUS_DEBUG("call %d: %s: %s", callId.id, errname.c_str(), errmsg.c_str()); + callback(Error{errname + ": " + errmsg}); } else { - DBUS_DEBUG("call %d: failed to send call", callId.id); - callback(Error{ "failed to send call" }); + DBUS_DEBUG("call %d: got reply with signature '%s'", callId.id, DBUS_W->eldbus_message_signature_get_impl(reply).c_str()); + callback(detail::unpackValues(callId, reply)); } } + }); + if(pending) + { + DBUS_DEBUG("call %d: call sent", callId.id); + } + else + { + DBUS_DEBUG("call %d: failed to send call", callId.id); + callback(Error{"failed to send call"}); + } +} - inline void displayDebugCallInfo(CallId callId, const std::string& funcName, const std::string& info, const std::string& interfaceName) - { - DBUS_DEBUG("call %d: %s iname = %s fname = %s", callId.id, info.c_str(), interfaceName.c_str(), funcName.c_str()); - } - - inline void displayDebugCallInfoSignal(CallId callId, const std::string& funcName, const std::string& info, const std::string& interfaceName) - { - DBUS_DEBUG("call %d: %s signal iname = %s fname = %s", callId.id, info.c_str(), interfaceName.c_str(), funcName.c_str()); - } +inline void displayDebugCallInfo(CallId callId, const std::string& funcName, const std::string& info, const std::string& interfaceName) +{ + DBUS_DEBUG("call %d: %s iname = %s fname = %s", callId.id, info.c_str(), interfaceName.c_str(), funcName.c_str()); +} - inline void displayDebugCallInfoProperty(CallId callId, const std::string& funcName, std::string info, const std::string& interfaceName, - const std::string& propertyName) - { - DBUS_DEBUG("call %d: %s iname = %s pname = %s", callId.id, info.c_str(), interfaceName.c_str(), propertyName.c_str()); - } +inline void displayDebugCallInfoSignal(CallId callId, const std::string& funcName, const std::string& info, const std::string& interfaceName) +{ + DBUS_DEBUG("call %d: %s signal iname = %s fname = %s", callId.id, info.c_str(), interfaceName.c_str(), funcName.c_str()); +} - using StringStorage = DBusWrapper::StringStorage; +inline void displayDebugCallInfoProperty(CallId callId, const std::string& funcName, std::string info, const std::string& interfaceName, const std::string& propertyName) +{ + DBUS_DEBUG("call %d: %s iname = %s pname = %s", callId.id, info.c_str(), interfaceName.c_str(), propertyName.c_str()); +} - template < typename A, typename... ARGS > - struct EldbusArgGenerator_Helper - { - static void add(std::vector< std::pair >& r) - { - auto s = r.size(); - auto sig = std::string{signature< A >::sig()}; - assert(!sig.empty()); - auto name = "p" + std::to_string(s + 1); - r.push_back({ std::move(sig), std::move(name) }); - EldbusArgGenerator_Helper::add(r); - } - }; +using StringStorage = DBusWrapper::StringStorage; - template <> - struct EldbusArgGenerator_Helper< void > - { - static void add(std::vector< std::pair >&) - { - } - }; +template +struct EldbusArgGenerator_Helper +{ + static void add(std::vector>& r) + { + auto s = r.size(); + auto sig = std::string{signature::sig()}; + assert(!sig.empty()); + auto name = "p" + std::to_string(s + 1); + r.push_back({std::move(sig), std::move(name)}); + EldbusArgGenerator_Helper::add(r); + } +}; - template <> - struct EldbusArgGenerator_Helper< ValueOrError< void >, void > - { - static void add(std::vector< std::pair >&) - { - } - }; - template <> - struct EldbusArgGenerator_Helper< ValueOrError<>, void > - { - static void add(std::vector< std::pair >&) - { - } - }; +template<> +struct EldbusArgGenerator_Helper +{ + static void add(std::vector>&) + { + } +}; - template < typename... ARGS > - struct EldbusArgGenerator_Helper< std::tuple< ARGS... > > - { - static void add(std::vector< std::pair >& r) - { - EldbusArgGenerator_Helper< ARGS..., void >::add(r); - } - }; +template<> +struct EldbusArgGenerator_Helper, void> +{ + static void add(std::vector>&) + { + } +}; +template<> +struct EldbusArgGenerator_Helper, void> +{ + static void add(std::vector>&) + { + } +}; - template < typename RetType > - struct dbus_interface_return_type_traits - { - using type = ValueOrError< RetType >; - }; +template +struct EldbusArgGenerator_Helper> +{ + static void add(std::vector>& r) + { + EldbusArgGenerator_Helper::add(r); + } +}; - template < typename... ARGS > - struct dbus_interface_return_type_traits< ValueOrError< ARGS... > > - { - using type = ValueOrError< ARGS... >; - }; +template +struct dbus_interface_return_type_traits +{ + using type = ValueOrError; +}; - template < typename T > - struct dbus_interface_traits; - template < typename RetType, typename... ARGS > - struct dbus_interface_traits< RetType(ARGS...) > - { - using Ret = typename dbus_interface_return_type_traits< RetType >::type; - using SyncCB = std::function< Ret(ARGS...) >; - using AsyncCB = std::function< void(std::function< void(Ret) >, ARGS...) >; - using VEArgs = ValueOrError< ARGS... >; - }; +template +struct dbus_interface_return_type_traits> +{ + using type = ValueOrError; +}; - template < typename T > - struct EldbusArgGenerator_Args; - template < typename RetType, typename... ARGS > - struct EldbusArgGenerator_Args< RetType(ARGS...) > - { - static std::string name() - { - return std::string{signature_tuple_helper< 0, sizeof...(ARGS), ARGS... >::name()}; - } - static std::vector< std::pair > get() - { - std::vector< std::pair > tmp; - EldbusArgGenerator_Helper< ARGS..., void >::add(tmp); - return tmp; - } - }; +template +struct dbus_interface_traits; +template +struct dbus_interface_traits +{ + using Ret = typename dbus_interface_return_type_traits::type; + using SyncCB = std::function; + using AsyncCB = std::function, ARGS...)>; + using VEArgs = ValueOrError; +}; - template < typename T > - struct EldbusArgGenerator_ReturnType; - template < typename RetType, typename... ARGS > - struct EldbusArgGenerator_ReturnType< RetType(ARGS...) > - { - static std::string name() - { - return std::string{signature< RetType >::name()}; - } - static std::vector< std::pair > get() - { - std::vector< std::pair > tmp; - EldbusArgGenerator_Helper< RetType, void >::add(tmp); - return tmp; - } - }; +template +struct EldbusArgGenerator_Args; +template +struct EldbusArgGenerator_Args +{ + static std::string name() + { + return std::string{signature_tuple_helper<0, sizeof...(ARGS), ARGS...>::name()}; + } + static std::vector> get() + { + std::vector> tmp; + EldbusArgGenerator_Helper::add(tmp); + return tmp; + } +}; - template < typename T > - struct EldbusArgGenerator_ReturnType; - template < typename... ARGS > - struct EldbusArgGenerator_ReturnType< void(ARGS...) > - { - static std::string name() - { - return ""; - } - static std::vector< std::pair > get() - { - return {}; - } - }; +template +struct EldbusArgGenerator_ReturnType; +template +struct EldbusArgGenerator_ReturnType +{ + static std::string name() + { + return std::string{signature::name()}; + } + static std::vector> get() + { + std::vector> tmp; + EldbusArgGenerator_Helper::add(tmp); + return tmp; + } +}; +template +struct EldbusArgGenerator_ReturnType; +template +struct EldbusArgGenerator_ReturnType +{ + static std::string name() + { + return ""; + } + static std::vector> get() + { + return {}; } +}; - using ConnectionType = DBusWrapper::ConnectionType; +} // namespace detail - /** +using ConnectionType = DBusWrapper::ConnectionType; + +/** * @brief Class representing client's end of DBUS connection * * Allows calling (synchronous and asynchronous) methods on selected interface * Allows (synchronous and asynchronous) setting / getting properties. * Allows registering signals. - */ - class DBusClient - { - struct ConnectionInfo - { - std::string interfaceName, busName, pathName; - }; - public: - /** + */ +class DBusClient +{ + struct ConnectionInfo + { + std::string interfaceName, busName, pathName; + }; + +public: + /** * @brief Default constructor, creates non-connected object. */ - DBusClient() = default; + DBusClient() = default; - /** + /** * @brief Connects to dbus choosen by tp, using given arguments * * @param bus_name name of the bus to connect to * @param path_name object's path * @param interface_name interface name */ - DBusClient(std::string busName_, std::string pathName_, std::string interfaceName_, - ConnectionType tp); + DBusClient(std::string busName_, std::string pathName_, std::string interfaceName_, ConnectionType tp); - /** + /** * @brief Connects to dbus using connection conn * * @param bus_name name of the bus to connect to @@ -1885,34 +2038,33 @@ namespace DBus * @param interface_name interface name * @param conn connection object from getDBusConnectionByType call */ - DBusClient(std::string busName_, std::string pathName_, std::string interfaceName_, - const DBusWrapper::ConnectionPtr& conn = {}); + DBusClient(std::string busName_, std::string pathName_, std::string interfaceName_, const DBusWrapper::ConnectionPtr& conn = {}); - /** + /** * @brief Destructor object. * * All signals added will be disconnected. * All asynchronous calls will be cancelled, their callback's will be called * with failure message. */ - ~DBusClient() = default; - DBusClient(const DBusClient&) = delete; - DBusClient(DBusClient&&) = default; + ~DBusClient() = default; + DBusClient(const DBusClient&) = delete; + DBusClient(DBusClient&&) = default; - DBusClient& operator=(DBusClient&&) = default; - DBusClient& operator=(const DBusClient&) = delete; + DBusClient& operator=(DBusClient&&) = default; + DBusClient& operator=(const DBusClient&) = delete; - /** + /** * @brief bool operator * * Returns true, if object is connected to DBUS */ - explicit operator bool() const - { - return bool(connectionState->proxy); - } + explicit operator bool() const + { + return bool(connectionState->proxy); + } - /** + /** * @brief Helper class for calling a method * * Template type T defines both arguments sent to the method @@ -1922,16 +2074,16 @@ namespace DBus * defines method, which takes two arguments (two floats) and return * single value of type int. */ - template < typename T > - struct Method - { - using RetType = typename detail::dbus_interface_traits< T >::Ret; - const detail::ConnectionState& connectionState; - std::string funcName; - std::string info; - std::shared_ptr< ConnectionInfo > connectionInfo; + template + struct Method + { + using RetType = typename detail::dbus_interface_traits::Ret; + const detail::ConnectionState& connectionState; + std::string funcName; + std::string info; + std::shared_ptr connectionInfo; - /** + /** * @brief Executes synchronous call on DBUS's method * * The function returns ValueOrError<...> object, which @@ -1939,15 +2091,15 @@ namespace DBus * * @param args arguments to pass to the method */ - template < typename... ARGS > - RetType call(const ARGS&... args) - { - detail::CallId callId; - detail::displayDebugCallInfo(callId, funcName, info, connectionInfo->interfaceName); - return detail::call< RetType >(callId, connectionState, false, funcName, args...); - } + template + RetType call(const ARGS&... args) + { + detail::CallId callId; + detail::displayDebugCallInfo(callId, funcName, info, connectionInfo->interfaceName); + return detail::call(callId, connectionState, false, funcName, args...); + } - /** + /** * @brief Executes asynchronous call on DBUS's method * * The function calls callback with either received values or error message. @@ -1955,151 +2107,150 @@ namespace DBus * @param callback callback functor, which will be called with return value(s) or error message * @param args arguments to pass to the method */ - template < typename... ARGS > - void asyncCall(std::function< void(RetType) > callback, const ARGS&... args) - { - detail::CallId callId; - detail::displayDebugCallInfo(callId, funcName, info, connectionInfo->interfaceName); - detail::asyncCall< RetType >(callId, connectionState, false, funcName, std::move(callback), args...); - } - }; + template + void asyncCall(std::function callback, const ARGS&... args) + { + detail::CallId callId; + detail::displayDebugCallInfo(callId, funcName, info, connectionInfo->interfaceName); + detail::asyncCall(callId, connectionState, false, funcName, std::move(callback), args...); + } + }; - /** + /** * @brief Helper class for calling a property * * Template type T defines type of the value hidden under property. * Note, that library automatically wraps both sent and received value into * DBUS's wrapper type. */ - template < typename T > - struct Property - { - using RetType = typename detail::dbus_interface_return_type_traits< T >::type; - using VariantRetType = typename detail::dbus_interface_return_type_traits< EldbusVariant< T > >::type; - const detail::ConnectionState& connectionState; - std::string propName; - std::string info; - std::shared_ptr< ConnectionInfo > connectionInfo; - - /** + template + struct Property + { + using RetType = typename detail::dbus_interface_return_type_traits::type; + using VariantRetType = typename detail::dbus_interface_return_type_traits>::type; + const detail::ConnectionState& connectionState; + std::string propName; + std::string info; + std::shared_ptr connectionInfo; + + /** * @brief executes synchronous get on property * * The function returns ValueOrError<...> object, which * contains either received values or error message. */ - RetType get() - { - detail::CallId callId; - detail::displayDebugCallInfoProperty(callId, "Get", info, connectionInfo->interfaceName, propName); - auto z = detail::call< VariantRetType >(callId, connectionState, true, "Get", connectionInfo->interfaceName, propName); - if (!z) - return z.getError(); - return { std::get< 0 >(z.getValues()).value }; - } + RetType get() + { + detail::CallId callId; + detail::displayDebugCallInfoProperty(callId, "Get", info, connectionInfo->interfaceName, propName); + auto z = detail::call(callId, connectionState, true, "Get", connectionInfo->interfaceName, propName); + if(!z) + return z.getError(); + return {std::get<0>(z.getValues()).value}; + } - /** + /** * @brief executes asynchronous get on property * * The function calls callback with either received values or error message. * * @param callback callback functor, which will be called with return value(s) or error message */ - void asyncGet(std::function< void(RetType) > callback) - { - detail::CallId callId; - detail::displayDebugCallInfoProperty(callId, "Get", info, connectionInfo->interfaceName, propName); - auto cc = [callback](VariantRetType reply) { - if (reply) - callback(std::move(std::get< 0 >(reply.getValues()).value)); - else - callback(reply.getError()); - }; - detail::asyncCall< VariantRetType >(callId, connectionState, true, "Get", std::move(cc), connectionInfo->interfaceName, propName); - } + void asyncGet(std::function callback) + { + detail::CallId callId; + detail::displayDebugCallInfoProperty(callId, "Get", info, connectionInfo->interfaceName, propName); + auto cc = [callback](VariantRetType reply) { + if(reply) + callback(std::move(std::get<0>(reply.getValues()).value)); + else + callback(reply.getError()); + }; + detail::asyncCall(callId, connectionState, true, "Get", std::move(cc), connectionInfo->interfaceName, propName); + } - /** + /** * @brief executes synchronous set on property * * The function returns ValueOrError object, with * possible error message. */ - ValueOrError< void > set(const T& r) - { - detail::CallId callId; - detail::displayDebugCallInfoProperty(callId, "Set", info, connectionInfo->interfaceName, propName); - EldbusVariant< T > variantValue{ std::move(r) }; - return detail::call< ValueOrError< void > >(callId, connectionState, true, "Set", connectionInfo->interfaceName, propName, variantValue); - } + ValueOrError set(const T& r) + { + detail::CallId callId; + detail::displayDebugCallInfoProperty(callId, "Set", info, connectionInfo->interfaceName, propName); + EldbusVariant variantValue{std::move(r)}; + return detail::call>(callId, connectionState, true, "Set", connectionInfo->interfaceName, propName, variantValue); + } - /** + /** * @brief executes asynchronous get on property * * The function calls callback with either received values or error message. * * @param callback callback functor, which will be called with return value(s) or error message */ - void asyncSet(std::function< void(ValueOrError< void >) > callback, const T& r) - { - detail::CallId callId; - detail::displayDebugCallInfoProperty(callId, "Set", info, connectionInfo->interfaceName, propName); - EldbusVariant< T > variantValue{ std::move(r) }; - detail::asyncCall< ValueOrError< void > >(callId, connectionState, true, "Set", std::move(callback), connectionInfo->interfaceName, propName, variantValue); - } - }; + void asyncSet(std::function)> callback, const T& r) + { + detail::CallId callId; + detail::displayDebugCallInfoProperty(callId, "Set", info, connectionInfo->interfaceName, propName); + EldbusVariant variantValue{std::move(r)}; + detail::asyncCall>(callId, connectionState, true, "Set", std::move(callback), connectionInfo->interfaceName, propName, variantValue); + } + }; - /** + /** * @brief Constructs Property<...> object for calling properties * * The function constructs and returns proxy object for calling property. * * @param propName property name to set and / or query */ - template < typename PropertyType > - Property< PropertyType > property(std::string propName) - { - return Property< PropertyType >{*connectionState, std::move(propName), info, connectionInfo}; - } + template + Property property(std::string propName) + { + return Property{*connectionState, std::move(propName), info, connectionInfo}; + } - /** + /** * @brief Constructs Method<...> object for calling methods * * The function constructs and returns proxy object for calling method. * * @param funcName function name to call */ - template < typename MethodType > - Method< MethodType > method(std::string funcName) - { - return Method< MethodType >{*connectionState, std::move(funcName), info, connectionInfo}; - } + template + Method method(std::string funcName) + { + return Method{*connectionState, std::move(funcName), info, connectionInfo}; + } - /** + /** * @brief Registers notification callback, when property has changed * * The callback will be called with new value, when property's value has changed. * Note, that template type V must match expected type, otherwise undefined behavior will occur, * there's no check for this. */ - template < typename V > - void addPropertyChangedEvent(std::string propertyName, std::function< void(V) > callback) - { - detail::CallId callId; - detail::displayDebugCallInfoSignal(callId, propertyName, info, connectionInfo->interfaceName); - DBUS_DEBUG("call %d: adding property", callId.id); - auto& cI = this->connectionInfo; - DBUS_W->add_property_changed_event_listener_impl(connectionState->proxy, cI->interfaceName, propertyName, - [callback](const _Eina_Value* newValue) { - V val = 0; - if (!getFromEinaValue(newValue, &val)) - { - DBUS_DEBUG("unable to get property's value"); - return; - } - callback(val); - }); - } + template + void addPropertyChangedEvent(std::string propertyName, std::function callback) + { + detail::CallId callId; + detail::displayDebugCallInfoSignal(callId, propertyName, info, connectionInfo->interfaceName); + DBUS_DEBUG("call %d: adding property", callId.id); + auto& cI = this->connectionInfo; + DBUS_W->add_property_changed_event_listener_impl(connectionState->proxy, cI->interfaceName, propertyName, [callback](const _Eina_Value* newValue) { + V val = 0; + if(!getFromEinaValue(newValue, &val)) + { + DBUS_DEBUG("unable to get property's value"); + return; + } + callback(val); + }); + } - /** + /** * @brief Registers callback on the DBUS' signal * * The function registers callback signalName. When signal comes, callback will be called. @@ -2109,69 +2260,68 @@ namespace DBus * @param signalName name of the signal to register * @param callback callback to call */ - template < typename SignalType > - void addSignal(std::string signalName, std::function< SignalType > callback) - { - detail::CallId callId; - detail::displayDebugCallInfoSignal(callId, signalName, info, connectionInfo->interfaceName); - DBUS_W->eldbus_proxy_signal_handler_add_impl(connectionState->proxy, signalName, - [callId, callback, signalName](const DBusWrapper::MessagePtr& msg) -> void { - std::string errname, aux; - if (DBUS_W->eldbus_message_error_get_impl(msg, errname, aux)) - { - DBUS_DEBUG("call %d: Eldbus error: %s %s", callId.id, errname.c_str(), aux.c_str()); - return; - } - DBUS_DEBUG("call %d: received signal with signature '%s'", callId.id, DBUS_W->eldbus_message_signature_get_impl(msg).c_str()); - using ParamsType = typename detail::dbus_interface_traits< SignalType >::VEArgs; - auto params = detail::unpackValues< ParamsType >(callId, msg); - if (!params) - { - DBUS_DEBUG("call %d: failed: %s", callId.id, params.getError().message.c_str()); - return; - } - try - { - std::apply(callback, params.getValues()); - } - catch (const Dali::DaliException &e) - { - DBUS_DEBUG("unhandled exception"); - assert(0); - } - }); - } + template + void addSignal(std::string signalName, std::function callback) + { + detail::CallId callId; + detail::displayDebugCallInfoSignal(callId, signalName, info, connectionInfo->interfaceName); + DBUS_W->eldbus_proxy_signal_handler_add_impl(connectionState->proxy, signalName, [callId, callback, signalName](const DBusWrapper::MessagePtr& msg) -> void { + std::string errname, aux; + if(DBUS_W->eldbus_message_error_get_impl(msg, errname, aux)) + { + DBUS_DEBUG("call %d: Eldbus error: %s %s", callId.id, errname.c_str(), aux.c_str()); + return; + } + DBUS_DEBUG("call %d: received signal with signature '%s'", callId.id, DBUS_W->eldbus_message_signature_get_impl(msg).c_str()); + using ParamsType = typename detail::dbus_interface_traits::VEArgs; + auto params = detail::unpackValues(callId, msg); + if(!params) + { + DBUS_DEBUG("call %d: failed: %s", callId.id, params.getError().message.c_str()); + return; + } + try + { + std::apply(callback, params.getValues()); + } + catch(const Dali::DaliException& e) + { + DBUS_DEBUG("unhandled exception"); + assert(0); + } + }); + } - private: - std::unique_ptr connectionState{ new detail::ConnectionState }; - std::string info; - std::shared_ptr< ConnectionInfo > connectionInfo; +private: + std::unique_ptr connectionState{new detail::ConnectionState}; + std::string info; + std::shared_ptr connectionInfo; - static bool getFromEinaValue(const _Eina_Value* v, void* dst); - }; + static bool getFromEinaValue(const _Eina_Value* v, void* dst); +}; - /** +/** * @brief Helper class describing DBUS's server interface * */ - class DBusInterfaceDescription - { - friend class DBusServer; +class DBusInterfaceDescription +{ + friend class DBusServer; - public: - using MethodInfo = DBusWrapper::MethodInfo; - using SignalInfo = DBusWrapper::SignalInfo; - using PropertyInfo = DBusWrapper::PropertyInfo; - using SignalId = DBusWrapper::SignalId; +public: + using MethodInfo = DBusWrapper::MethodInfo; + using SignalInfo = DBusWrapper::SignalInfo; + using PropertyInfo = DBusWrapper::PropertyInfo; + using SignalId = DBusWrapper::SignalId; - /** + /** * @brief Creates empty interface description with given name * * @param interfaceName name of the interface */ - DBusInterfaceDescription(std::string interfaceName); + DBusInterfaceDescription(std::string interfaceName); - /** + /** * @brief adds new, synchronous method to the interface * * When method memberName is called on DBUS, callback functor will be called @@ -2189,24 +2339,22 @@ namespace DBus * @param memberName name of the method * @param callback functor, which will be called */ - template < typename T > - void addMethod(const std::string& memberName, typename detail::dbus_interface_traits< T >::SyncCB callback) - { - detail::CallId callId; - MethodInfo mi; - methods.push_back(std::move(mi)); - auto& z = methods.back(); - z.in = detail::EldbusArgGenerator_Args< T >::get(); - z.out = detail::EldbusArgGenerator_ReturnType< T >::get(); - z.memberName = memberName; - DBUS_DEBUG("call %d: method %s, in %s, out %s", callId.id, memberName.c_str(), - detail::EldbusArgGenerator_Args< T >::name().c_str(), - detail::EldbusArgGenerator_ReturnType< T >::name().c_str()); - z.callback = construct< T >(callId, callback); - z.id = callId; - } + template + void addMethod(const std::string& memberName, typename detail::dbus_interface_traits::SyncCB callback) + { + detail::CallId callId; + MethodInfo mi; + methods.push_back(std::move(mi)); + auto& z = methods.back(); + z.in = detail::EldbusArgGenerator_Args::get(); + z.out = detail::EldbusArgGenerator_ReturnType::get(); + z.memberName = memberName; + DBUS_DEBUG("call %d: method %s, in %s, out %s", callId.id, memberName.c_str(), detail::EldbusArgGenerator_Args::name().c_str(), detail::EldbusArgGenerator_ReturnType::name().c_str()); + z.callback = construct(callId, callback); + z.id = callId; + } - /** + /** * @brief adds new, synchronous property to the interface * * When property memberName is called on DBUS, respective callback functor will be called @@ -2222,218 +2370,217 @@ namespace DBus * @param getter functor, which will be called when property is being read * @param setter functor, which will be called when property is being set */ - template < typename T > - void addProperty(const std::string& memberName, std::function< ValueOrError< T >() > getter, std::function< ValueOrError< void >(T) > setter) - { - properties.push_back({}); - auto& z = properties.back(); - z.memberName = memberName; - z.typeSignature = detail::signature< T >::sig(); - if (getter) - { - detail::CallId getterId; - z.getterId = getterId; - DBUS_DEBUG("call %d: property %s (get) type %s", getterId.id, memberName.c_str(), detail::signature< T >::name().data()); - z.getCallback = [=](const DBusWrapper::MessagePtr& src, const DBusWrapper::MessageIterPtr& dst) -> std::string { + template + void addProperty(const std::string& memberName, std::function()> getter, std::function(T)> setter) + { + properties.push_back({}); + auto& z = properties.back(); + z.memberName = memberName; + z.typeSignature = detail::signature::sig(); + if(getter) + { + detail::CallId getterId; + z.getterId = getterId; + DBUS_DEBUG("call %d: property %s (get) type %s", getterId.id, memberName.c_str(), detail::signature::name().data()); + z.getCallback = [=](const DBusWrapper::MessagePtr& src, const DBusWrapper::MessageIterPtr& dst) -> std::string { + try + { + auto v = std::apply(getter, std::tuple<>{}); + if(v) + { + detail::signature::set(dst, std::get<0>(v.getValues())); + DBUS_DEBUG("call %d: success", getterId.id); + return ""; + } + DBUS_DEBUG("call %d: failed: %s", getterId.id, v.getError().message.c_str()); + return v.getError().message; + } + catch(std::exception& e) + { + return std::string("unhandled exception (") + e.what() + ")"; + } + catch(const Dali::DaliException& e) + { + return std::string("unhandled exception (") + e.condition + ")"; + } + }; + } + if(setter) + { + detail::CallId setterId; + z.setterId = setterId; + DBUS_DEBUG("call %d: property %s (set) type %s", setterId.id, memberName.c_str(), detail::signature::name().data()); + z.setCallback = [=](const DBusWrapper::MessagePtr& src, const DBusWrapper::MessageIterPtr& src_iter) -> std::string { + std::tuple value; + auto src_signature = DBUS_W->eldbus_message_iter_signature_get_impl(src_iter); + if(detail::signature::get(src_iter, std::get<0>(value))) + { try { - auto v = std::apply(getter, std::tuple<>{}); - if (v) + auto v = std::apply(setter, std::move(value)); + if(v) { - detail::signature< T >::set(dst, std::get< 0 >(v.getValues())); - DBUS_DEBUG("call %d: success", getterId.id); + DBUS_DEBUG("call %d: success", setterId.id); return ""; } - DBUS_DEBUG("call %d: failed: %s", getterId.id, v.getError().message.c_str()); + DBUS_DEBUG("call %d: failed: %s", setterId.id, v.getError().message.c_str()); return v.getError().message; } - catch (std::exception & e) + catch(std::exception& e) { return std::string("unhandled exception (") + e.what() + ")"; } - catch (const Dali::DaliException &e) + catch(const Dali::DaliException& e) { return std::string("unhandled exception (") + e.condition + ")"; } - }; - } - if (setter) - { - detail::CallId setterId; - z.setterId = setterId; - DBUS_DEBUG("call %d: property %s (set) type %s", setterId.id, memberName.c_str(), detail::signature< T >::name().data()); - z.setCallback = [=](const DBusWrapper::MessagePtr& src, const DBusWrapper::MessageIterPtr& src_iter) -> std::string { - std::tuple< T > value; - auto src_signature = DBUS_W->eldbus_message_iter_signature_get_impl(src_iter); - if (detail::signature< T >::get(src_iter, std::get< 0 >(value))) - { - try - { - auto v = std::apply(setter, std::move(value)); - if (v) - { - DBUS_DEBUG("call %d: success", setterId.id); - return ""; - } - DBUS_DEBUG("call %d: failed: %s", setterId.id, v.getError().message.c_str()); - return v.getError().message; - } - catch (std::exception & e) - { - return std::string("unhandled exception (") + e.what() + ")"; - } - catch (const Dali::DaliException &e) - { - return std::string("unhandled exception (") + e.condition + ")"; - } - } - DBUS_DEBUG("call %d: failed to unpack values, got signature '%s', expected '%s'", setterId.id, - src_signature.c_str(), detail::signature< T >::sig().data()); - return "call " + std::to_string(setterId.id) + ": failed to unpack values, got signature '" + - src_signature + "', expected '" + std::string{detail::signature< T >::sig()} + "'"; - }; - } + } + DBUS_DEBUG("call %d: failed to unpack values, got signature '%s', expected '%s'", setterId.id, src_signature.c_str(), detail::signature::sig().data()); + return "call " + std::to_string(setterId.id) + ": failed to unpack values, got signature '" + + src_signature + "', expected '" + std::string{detail::signature::sig()} + "'"; + }; } + } - /** + /** * @brief adds new signal to the interface * * Template types ARGS defines values, which will be emited with the signal * * @param memberName name of the method */ - template < typename... ARGS > - SignalId addSignal(const std::string& memberName) - { - detail::CallId callId; - signals.push_back({}); - auto& z = signals.back(); - z.memberName = memberName; - z.args = detail::EldbusArgGenerator_Args< void(ARGS...) >::get(DBUS_W->Strings); - z.id = callId; - DBUS_DEBUG("call %d: signal %s", callId.id, memberName.c_str()); - return SignalId{ callId }; - } + template + SignalId addSignal(const std::string& memberName) + { + detail::CallId callId; + signals.push_back({}); + auto& z = signals.back(); + z.memberName = memberName; + z.args = detail::EldbusArgGenerator_Args::get(DBUS_W->Strings); + z.id = callId; + DBUS_DEBUG("call %d: signal %s", callId.id, memberName.c_str()); + return SignalId{callId}; + } - private: - std::vector< MethodInfo > methods; - std::vector< PropertyInfo > properties; - std::vector< SignalInfo > signals; - std::string interfaceName; +private: + std::vector methods; + std::vector properties; + std::vector signals; + std::string interfaceName; - template < typename T > - std::function< DBusWrapper::MessagePtr(const DBusWrapper::MessagePtr & msg) > construct(detail::CallId callId, - typename detail::dbus_interface_traits< T >::SyncCB callback) - { - using VEArgs = typename detail::dbus_interface_traits< T >::VEArgs; - return [=](const DBusWrapper::MessagePtr& msg) -> DBusWrapper::MessagePtr { - DBUS_DEBUG("call %d: entering", callId.id); - DBusWrapper::MessagePtr ret = {}; - auto args = detail::unpackValues< VEArgs >(callId, msg); - if (args) + template + std::function construct(detail::CallId callId, + typename detail::dbus_interface_traits::SyncCB callback) + { + using VEArgs = typename detail::dbus_interface_traits::VEArgs; + return [=](const DBusWrapper::MessagePtr& msg) -> DBusWrapper::MessagePtr { + DBUS_DEBUG("call %d: entering", callId.id); + DBusWrapper::MessagePtr ret = {}; + auto args = detail::unpackValues(callId, msg); + if(args) + { + try { - try - { - auto v = std::apply(callback, std::move(args.getValues())); - if (v) - { - DBUS_DEBUG("call %d: success", callId.id); - ret = DBUS_W->eldbus_message_method_return_new_impl(msg); - detail::packValues(callId, ret, v); - } - else - { - DBUS_DEBUG("call %d: failed: %s", callId.id, v.getError().message.c_str()); - ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.Failed", v.getError().message); - } - } - catch (std::exception & e) + auto v = std::apply(callback, std::move(args.getValues())); + if(v) { - auto txt = std::string("unhandled exception (") + e.what() + ")"; - DBUS_DEBUG("call %d: failed: %s", callId.id, txt.c_str()); - ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.Failed", txt); + DBUS_DEBUG("call %d: success", callId.id); + ret = DBUS_W->eldbus_message_method_return_new_impl(msg); + detail::packValues(callId, ret, v); } - catch (const Dali::DaliException &e) + else { - auto txt = std::string("unhandled exception (") + e.condition + ")"; - DBUS_DEBUG("call %d: failed: %s", callId.id, txt.c_str()); - ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.Failed", txt); + DBUS_DEBUG("call %d: failed: %s", callId.id, v.getError().message.c_str()); + ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.Failed", v.getError().message); } } - else + catch(std::exception& e) { - std::ostringstream err; - err << "expected signature '" << detail::signature< VEArgs >::sig() << "', got '" << DBUS_W->eldbus_message_signature_get_impl(msg) << "'"; - auto str = err.str(); - DBUS_DEBUG("call %d: failed: %s", callId.id, str.c_str()); - ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.InvalidArgs", str); + auto txt = std::string("unhandled exception (") + e.what() + ")"; + DBUS_DEBUG("call %d: failed: %s", callId.id, txt.c_str()); + ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.Failed", txt); } - return ret; - }; - } - }; + catch(const Dali::DaliException& e) + { + auto txt = std::string("unhandled exception (") + e.condition + ")"; + DBUS_DEBUG("call %d: failed: %s", callId.id, txt.c_str()); + ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.Failed", txt); + } + } + else + { + std::ostringstream err; + err << "expected signature '" << detail::signature::sig() << "', got '" << DBUS_W->eldbus_message_signature_get_impl(msg) << "'"; + auto str = err.str(); + DBUS_DEBUG("call %d: failed: %s", callId.id, str.c_str()); + ret = DBUS_W->eldbus_message_error_new_impl(msg, "org.freedesktop.DBus.Error.InvalidArgs", str); + } + return ret; + }; + } +}; - /** +/** * @brief Class representing server's end of DBUS connection * * Allows listening (synchronously and asynchronously) on methods on selected interface * Allows listening (synchronously and asynchronously) on setting / getting properties. * Allows emiting signals. */ - class DBusServer - { - public: - /** +class DBusServer +{ +public: + /** * @brief Constructs non-connected dbus server. */ - DBusServer() = default; + DBusServer() = default; - /** + /** * @brief Constructs dbus server on either system or user dbus connection. */ - DBusServer(ConnectionType tp); + DBusServer(ConnectionType tp); - /** + /** * @brief Constructs dbus server on connection from getDBusConnectionByType */ - DBusServer(const DBusWrapper::ConnectionPtr& conn); + DBusServer(const DBusWrapper::ConnectionPtr& conn); - /** + /** * @brief Destructor * * Destructor will properly destroy everything. Destructor will cancel * pending replies. */ - ~DBusServer() = default; + ~DBusServer() = default; - DBusServer(const DBusServer&) = delete; - DBusServer(DBusServer&&) = default; + DBusServer(const DBusServer&) = delete; + DBusServer(DBusServer&&) = default; - DBusServer& operator=(DBusServer&&) = default; - DBusServer& operator=(const DBusServer&) = delete; + DBusServer& operator=(DBusServer&&) = default; + DBusServer& operator=(const DBusServer&) = delete; - /** + /** * @brief Registers interface on given path name * * @param pathName path object to register interface on. * @param dscr * @param fallback */ - void addInterface(const std::string& pathName, DBusInterfaceDescription& dscr, bool fallback = false); + void addInterface(const std::string& pathName, DBusInterfaceDescription& dscr, bool fallback = false); - /** + /** * @brief Gets bus name of the current connection (must be connected) */ - std::string getBusName() const; + std::string getBusName() const; - /** + /** * @brief Returns connection object for this dbus server object * * @return connection object */ - DBusWrapper::ConnectionPtr getConnection(); + DBusWrapper::ConnectionPtr getConnection(); - /** + /** * @brief Emits signal * * Emits signal based only on data passed to the function @@ -2441,17 +2588,16 @@ namespace DBus * @param signal identifier of the signal * @param args values to emit */ - template < typename... ARGS > - void emit2(const std::string& path, const std::string& interfaceName, - const std::string& signalName, const ARGS&... args) - { - auto msg = DBUS_W->eldbus_message_signal_new_impl(path, interfaceName, signalName); - detail::CallId id; - detail::packValues(id, msg, args...); - DBUS_W->eldbus_connection_send_impl(connection, msg); - } + template + void emit2(const std::string& path, const std::string& interfaceName, const std::string& signalName, const ARGS&... args) + { + auto msg = DBUS_W->eldbus_message_signal_new_impl(path, interfaceName, signalName); + detail::CallId id; + detail::packValues(id, msg, args...); + DBUS_W->eldbus_connection_send_impl(connection, msg); + } - /** + /** * @brief Returns current object path, when handling call to property / method * * User can call this function from inside callback used to handle property / method calls. @@ -2472,9 +2618,12 @@ namespace DBus * }; * \endcode */ - static std::string getCurrentObjectPath() { return currentObjectPath; } + static std::string getCurrentObjectPath() + { + return currentObjectPath; + } - /** + /** * @brief Returns current connection object, when handling call to property / method * * User can call this function from inside callback used to handle property / method calls. @@ -2495,61 +2644,65 @@ namespace DBus * }; * \endcode */ - static const DBusWrapper::ConnectionPtr& getCurrentConnection() { return currentConnection; } + static const DBusWrapper::ConnectionPtr& getCurrentConnection() + { + return currentConnection; + } - /// \cond - class CurrentObjectSetter + /// \cond + class CurrentObjectSetter + { + public: + CurrentObjectSetter(DBusWrapper::ConnectionPtr con, std::string path) { - public: - CurrentObjectSetter(DBusWrapper::ConnectionPtr con, std::string path) - { - currentObjectPath = std::move(path); - currentConnection = std::move(con); - } - ~CurrentObjectSetter() - { - currentObjectPath = ""; - currentConnection = {}; - } - CurrentObjectSetter(const CurrentObjectSetter&) = delete; - CurrentObjectSetter(CurrentObjectSetter&&) = delete; - void operator=(const CurrentObjectSetter&) = delete; - void operator=(CurrentObjectSetter&&) = delete; - }; - - private: - DBusWrapper::ConnectionPtr connection; - struct DestructorObject { - std::vector> destructors; - ~DestructorObject() { - for (auto& a : destructors) a(); - } - }; - - std::unique_ptr destructorObject{ new DestructorObject() }; - static thread_local std::string currentObjectPath; - static thread_local DBusWrapper::ConnectionPtr currentConnection; + currentObjectPath = std::move(path); + currentConnection = std::move(con); + } + ~CurrentObjectSetter() + { + currentObjectPath = ""; + currentConnection = {}; + } + CurrentObjectSetter(const CurrentObjectSetter&) = delete; + CurrentObjectSetter(CurrentObjectSetter&&) = delete; + void operator=(const CurrentObjectSetter&) = delete; + void operator=(CurrentObjectSetter&&) = delete; + }; +private: + DBusWrapper::ConnectionPtr connection; + struct DestructorObject + { + std::vector> destructors; + ~DestructorObject() + { + for(auto& a : destructors) a(); + } }; - DBusWrapper::ConnectionPtr getDBusConnectionByType(ConnectionType tp); - DBusWrapper::ConnectionPtr getDBusConnectionByName(const std::string& name); - std::string getConnectionName(const DBusWrapper::ConnectionPtr&); -} + std::unique_ptr destructorObject{new DestructorObject()}; + static thread_local std::string currentObjectPath; + static thread_local DBusWrapper::ConnectionPtr currentConnection; +}; + +DBusWrapper::ConnectionPtr getDBusConnectionByType(ConnectionType tp); +DBusWrapper::ConnectionPtr getDBusConnectionByName(const std::string& name); +std::string getConnectionName(const DBusWrapper::ConnectionPtr&); +} // namespace DBus namespace std { - template < size_t INDEX, typename... ARGS > - inline auto get(DBus::ValueOrError< ARGS... >& v) -> decltype(std::get< INDEX >(v.getValues()))& - { - return std::get< INDEX >(v.getValues()); - } +template +inline auto get(DBus::ValueOrError& v) -> decltype(std::get(v.getValues()))& +{ + return std::get(v.getValues()); +} - template < size_t INDEX, typename... ARGS > - inline auto get(const DBus::ValueOrError< ARGS... >& v) -> decltype(std::get< INDEX >(v.getValues())) - { - return std::get< INDEX >(v.getValues()); - } +template +inline auto get(const DBus::ValueOrError& v) -> decltype(std::get(v.getValues())) +{ + return std::get(v.getValues()); } +} // namespace std #endif // DALI_INTERNAL_ACCESSIBILITY_BRIDGE_DBUS_H diff --git a/dali/internal/accessibility/bridge/dummy-atspi.cpp b/dali/internal/accessibility/bridge/dummy-atspi.cpp index 252628c..695cb9d 100644 --- a/dali/internal/accessibility/bridge/dummy-atspi.cpp +++ b/dali/internal/accessibility/bridge/dummy-atspi.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,12 +15,13 @@ * */ -#include #include +#include -namespace Dali { -namespace { - +namespace Dali +{ +namespace +{ struct DummyBridge : Dali::Accessibility::Bridge { const std::string& GetBusName() const override @@ -29,19 +30,19 @@ struct DummyBridge : Dali::Accessibility::Bridge return name; } - void AddTopLevelWindow(Accessibility::Accessible *) override + void AddTopLevelWindow(Accessibility::Accessible*) override { } - void RemoveTopLevelWindow(Accessibility::Accessible *) override + void RemoveTopLevelWindow(Accessibility::Accessible*) override { } - void AddPopup(Accessibility::Accessible *) override + void AddPopup(Accessibility::Accessible*) override { } - void RemovePopup(Accessibility::Accessible *) override + void RemovePopup(Accessibility::Accessible*) override { } @@ -49,12 +50,12 @@ struct DummyBridge : Dali::Accessibility::Bridge { } - Accessibility::Accessible *GetApplication() const override + Accessibility::Accessible* GetApplication() const override { return nullptr; } - Accessibility::Accessible *FindByPath(const std::string& s) const override + Accessibility::Accessible* FindByPath(const std::string& s) const override { return nullptr; } @@ -84,31 +85,31 @@ struct DummyBridge : Dali::Accessibility::Bridge { } - void EmitCaretMoved(Accessibility::Accessible *obj, unsigned int cursorPosition) override + void EmitCaretMoved(Accessibility::Accessible* obj, unsigned int cursorPosition) override { } - void EmitActiveDescendantChanged(Accessibility::Accessible *obj, Accessibility::Accessible *child) override + void EmitActiveDescendantChanged(Accessibility::Accessible* obj, Accessibility::Accessible* child) override { } - void EmitTextChanged(Accessibility::Accessible *obj, Accessibility::TextChangedState state, unsigned int position, unsigned int length, const std::string &content) override + void EmitTextChanged(Accessibility::Accessible* obj, Accessibility::TextChangedState state, unsigned int position, unsigned int length, const std::string& content) override { } - void EmitStateChanged(Accessibility::Accessible *obj, Accessibility::State state, int val1, int val2) override + void EmitStateChanged(Accessibility::Accessible* obj, Accessibility::State state, int val1, int val2) override { } - void Emit(Accessibility::Accessible *obj, Accessibility::WindowEvent we, unsigned int detail1) override + void Emit(Accessibility::Accessible* obj, Accessibility::WindowEvent we, unsigned int detail1) override { } - void Emit(Accessibility::Accessible *obj, Accessibility::ObjectPropertyChangeEvent event) override + void Emit(Accessibility::Accessible* obj, Accessibility::ObjectPropertyChangeEvent event) override { } - void EmitBoundsChanged(Accessibility::Accessible *obj, Rect<> rect) override + void EmitBoundsChanged(Accessibility::Accessible* obj, Rect<> rect) override { } @@ -117,7 +118,7 @@ struct DummyBridge : Dali::Accessibility::Bridge return Accessibility::Consumed::YES; } - void Say( const std::string& text, bool discardable, std::function callback ) override + void Say(const std::string& text, bool discardable, std::function callback) override { } @@ -152,12 +153,12 @@ Accessibility::Accessible::~Accessible() { } -std::vector Accessibility::Accessible::GetChildren() +std::vector Accessibility::Accessible::GetChildren() { return {}; } -Accessibility::Accessible *Accessibility::Accessible::GetDefaultLabel() +Accessibility::Accessible* Accessibility::Accessible::GetDefaultLabel() { return nullptr; } @@ -167,7 +168,7 @@ Accessibility::Address Accessibility::Accessible::GetAddress() return {}; } -std::shared_ptr< Accessibility::Bridge::Data > Accessibility::Accessible::GetBridgeData() +std::shared_ptr Accessibility::Accessible::GetBridgeData() { return {}; } @@ -187,12 +188,12 @@ bool Accessibility::Component::Contains(Point p, CoordType ctype) return false; } -Accessibility::Accessible *Accessibility::Component::GetAccessibleAtPoint(Accessibility::Point p, Accessibility::CoordType ctype) +Accessibility::Accessible* Accessibility::Component::GetAccessibleAtPoint(Accessibility::Point p, Accessibility::CoordType ctype) { return nullptr; } -Accessibility::Bridge *Accessibility::Bridge::GetCurrentBridge() +Accessibility::Bridge* Accessibility::Bridge::GetCurrentBridge() { return &dummyBridge; } @@ -225,11 +226,11 @@ void Accessibility::Accessible::EmitVisible(bool visible) { } -void Accessibility::Accessible::EmitTextInserted(unsigned int position, unsigned int length, const std::string &content) +void Accessibility::Accessible::EmitTextInserted(unsigned int position, unsigned int length, const std::string& content) { } -void Accessibility::Accessible::EmitTextDeleted(unsigned int position, unsigned int length, const std::string &content) +void Accessibility::Accessible::EmitTextDeleted(unsigned int position, unsigned int length, const std::string& content) { } @@ -237,15 +238,15 @@ void Accessibility::Accessible::EmitTextCaretMoved(unsigned int cursorPosition) { } -void Accessibility::Accessible::EmitActiveDescendantChanged(Accessibility::Accessible* obj, Accessibility::Accessible *child) +void Accessibility::Accessible::EmitActiveDescendantChanged(Accessibility::Accessible* obj, Accessibility::Accessible* child) { } -void Accessibility::Accessible::FindWordSeparationsUtf8(const utf8_t *s, size_t length, const char *language, char *breaks) +void Accessibility::Accessible::FindWordSeparationsUtf8(const utf8_t* s, size_t length, const char* language, char* breaks) { } -void Accessibility::Accessible::FindLineSeparationsUtf8(const utf8_t *s, size_t length, const char *language, char *breaks) +void Accessibility::Accessible::FindLineSeparationsUtf8(const utf8_t* s, size_t length, const char* language, char* breaks) { } diff --git a/dali/internal/accessibility/common/tts-player-factory.cpp b/dali/internal/accessibility/common/tts-player-factory.cpp index 1e4c884..1e2e151 100644 --- a/dali/internal/accessibility/common/tts-player-factory.cpp +++ b/dali/internal/accessibility/common/tts-player-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class TtsPlayer; @@ -33,14 +31,15 @@ namespace TtsPlayerFactory * @return dummy implementation of Tts Player */ __attribute__((weak)) -std::unique_ptr New(Dali::TtsPlayer::Mode mode) +std::unique_ptr +New(Dali::TtsPlayer::Mode mode) { return std::unique_ptr(new Internal::Adaptor::TtsPlayer()); } -} +} // namespace TtsPlayerFactory -} +} // namespace Adaptor -} +} // namespace Internal -} \ No newline at end of file +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/accessibility/common/tts-player-factory.h b/dali/internal/accessibility/common/tts-player-factory.h index aac8e85..abe1bbc 100644 --- a/dali/internal/accessibility/common/tts-player-factory.h +++ b/dali/internal/accessibility/common/tts-player-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_FACTORY_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,16 +23,13 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class TtsPlayer; namespace TtsPlayerFactory { - /** * Factory function that ought to be overriden by platform implementation. * @return @@ -41,7 +38,7 @@ std::unique_ptr New(Dali::TtsPlayer::Mode mode); } // namespace TtsPlayerFactory -} // namespaceAdaptor +} // namespace Adaptor } // namespace Internal diff --git a/dali/internal/accessibility/common/tts-player-impl.cpp b/dali/internal/accessibility/common/tts-player-impl.cpp index 16a6b4a..a6bd587 100644 --- a/dali/internal/accessibility/common/tts-player-impl.cpp +++ b/dali/internal/accessibility/common/tts-player-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,40 +15,33 @@ * */ -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - Dali::TtsPlayer TtsPlayer::New(Dali::TtsPlayer::Mode mode) { return Dali::TtsPlayer(TtsPlayerFactory::New(mode).release()); } -void TtsPlayer::Play(const std::string &text) +void TtsPlayer::Play(const std::string& text) { - } void TtsPlayer::Stop() { - } void TtsPlayer::Pause() { - } void TtsPlayer::Resume() { - } Dali::TtsPlayer::State TtsPlayer::GetState() @@ -62,6 +55,6 @@ Dali::TtsPlayer::StateChangedSignalType& TtsPlayer::StateChangedSignal() return signal; } -} -} -} \ No newline at end of file +} // namespace Adaptor +} // namespace Internal +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/accessibility/common/tts-player-impl.h b/dali/internal/accessibility/common/tts-player-impl.h index 0f7d93d..53ecda7 100644 --- a/dali/internal/accessibility/common/tts-player-impl.h +++ b/dali/internal/accessibility/common/tts-player-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_COMMON_TTS_PLAYER_IMPL_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,21 +27,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Text-to-speech player */ class TtsPlayer : public Dali::BaseObject { - public: - /** * Create a TtsPlayer with the given mode. * This should only be called once by the Adaptor class for each given mode. @@ -89,7 +84,7 @@ public: inline Internal::Adaptor::TtsPlayer& GetImplementation(Dali::TtsPlayer& player) { - DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" ); + DALI_ASSERT_ALWAYS(player && "TtsPlayer handle is empty"); BaseObject& handle = player.GetBaseObject(); @@ -98,7 +93,7 @@ inline Internal::Adaptor::TtsPlayer& GetImplementation(Dali::TtsPlayer& player) inline const Internal::Adaptor::TtsPlayer& GetImplementation(const Dali::TtsPlayer& player) { - DALI_ASSERT_ALWAYS( player && "TtsPlayer handle is empty" ); + DALI_ASSERT_ALWAYS(player && "TtsPlayer handle is empty"); const BaseObject& handle = player.GetBaseObject(); diff --git a/dali/internal/accessibility/generic/tts-player-factory-generic.cpp b/dali/internal/accessibility/generic/tts-player-factory-generic.cpp index ac70139..85e4713 100644 --- a/dali/internal/accessibility/generic/tts-player-factory-generic.cpp +++ b/dali/internal/accessibility/generic/tts-player-factory-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,16 +20,13 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class TtsPlayer; namespace TtsPlayerFactory { - std::unique_ptr New(Dali::TtsPlayer::Mode mode) { return TtsPlayerGeneric::New(mode); diff --git a/dali/internal/accessibility/generic/tts-player-impl-generic.cpp b/dali/internal/accessibility/generic/tts-player-impl-generic.cpp index 5200af5..db540a7 100644 --- a/dali/internal/accessibility/generic/tts-player-impl-generic.cpp +++ b/dali/internal/accessibility/generic/tts-player-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,10 @@ #include namespace Dali { - namespace Internal { - namespace Adaptor { - #if defined(DEBUG_ENABLED) Debug::Filter* TtsPlayerGeneric::gLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_TTS_PLAYER"); #endif diff --git a/dali/internal/accessibility/generic/tts-player-impl-generic.h b/dali/internal/accessibility/generic/tts-player-impl-generic.h index 257350f..007edf2 100644 --- a/dali/internal/accessibility/generic/tts-player-impl-generic.h +++ b/dali/internal/accessibility/generic/tts-player-impl-generic.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_GENERIC_TTS_PLAYER_IMPL_GENERIC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ // EXTERNAL INCLUDES -#include #include +#include #include #include @@ -32,21 +32,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Text-to-speech player */ class TtsPlayerGeneric : public Dali::Internal::Adaptor::TtsPlayer { - public: - /** * Create a TtsPlayer with the given mode. * This should only be called once by the Adaptor class for each given mode. @@ -97,7 +92,6 @@ public: ~TtsPlayerGeneric() override; private: - Dali::TtsPlayer::StateChangedSignalType mStateChangedSignal; ///< Signal emitted when the TTS state changes (non-functional, for interface compatibility). #if defined(DEBUG_ENABLED) diff --git a/dali/internal/accessibility/tizen-wayland/tts-player-factory-tizen.cpp b/dali/internal/accessibility/tizen-wayland/tts-player-factory-tizen.cpp index 6287f4d..1c4a4c1 100644 --- a/dali/internal/accessibility/tizen-wayland/tts-player-factory-tizen.cpp +++ b/dali/internal/accessibility/tizen-wayland/tts-player-factory-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,25 +20,22 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class TtsPlayer; namespace TtsPlayerFactory { - std::unique_ptr New(Dali::TtsPlayer::Mode mode) { return TtsPlayerTizen::New(mode); } -} +} // namespace TtsPlayerFactory -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.cpp b/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.cpp index b18a74e..20f1670 100644 --- a/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.cpp +++ b/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,27 +23,22 @@ #include - namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { - /** * Helper function to convert Tizen-specific TTS state to external state. * @param state The Tizen TTS state. * @return The external TTS state. */ -Dali::TtsPlayer::State InternalToExternalState( tts_state_e state ) +Dali::TtsPlayer::State InternalToExternalState(tts_state_e state) { - switch( state ) + switch(state) { case TTS_STATE_CREATED: { @@ -94,14 +89,14 @@ TtsPlayerTizen::~TtsPlayerTizen() // Unset the callback funtion for TTS state change int retVal = tts_unset_state_changed_cb(mTtsHandle); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } // Destroy the TTS handle and disconnects the daemon retVal = tts_destroy(mTtsHandle); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } @@ -112,7 +107,7 @@ void TtsPlayerTizen::Initialize() // Create the TTS handle int retVal = tts_create(&mTtsHandle); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } @@ -120,26 +115,26 @@ void TtsPlayerTizen::Initialize() { // Set the callback funtion for TTS state change retVal = tts_set_state_changed_cb(mTtsHandle, &StateChangedCallback, this); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } // Check tts mode tts_mode_e ttsMode = TTS_MODE_DEFAULT; - switch (mTtsMode) + switch(mTtsMode) { case Dali::TtsPlayer::DEFAULT: ttsMode = TTS_MODE_DEFAULT; - break; + break; case Dali::TtsPlayer::NOTIFICATION: ttsMode = TTS_MODE_NOTIFICATION; - break; + break; case Dali::TtsPlayer::SCREEN_READER: ttsMode = TTS_MODE_SCREEN_READER; - break; + break; default: - break; + break; } // Set mode @@ -192,7 +187,7 @@ void TtsPlayerTizen::Stop() { // Check the current TTS state tts_state_e state; - int retVal = tts_get_state(mTtsHandle, &state); + int retVal = tts_get_state(mTtsHandle, &state); if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); @@ -201,7 +196,7 @@ void TtsPlayerTizen::Stop() { // If it is playing or paused, stop playing and clear the queue retVal = tts_stop(mTtsHandle); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } @@ -215,7 +210,7 @@ void TtsPlayerTizen::Pause() { // Check the current TTS state tts_state_e state; - int retVal = tts_get_state(mTtsHandle, &state); + int retVal = tts_get_state(mTtsHandle, &state); if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); @@ -224,7 +219,7 @@ void TtsPlayerTizen::Pause() { // If the player is playing, pause it. retVal = tts_pause(mTtsHandle); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } @@ -238,7 +233,7 @@ void TtsPlayerTizen::Resume() { // Check the current TTS state tts_state_e state; - int retVal = tts_get_state(mTtsHandle, &state); + int retVal = tts_get_state(mTtsHandle, &state); if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); @@ -247,7 +242,7 @@ void TtsPlayerTizen::Resume() { // If the player is paused, resume it. retVal = tts_play(mTtsHandle); - if( retVal != TTS_ERROR_NONE ) + if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } @@ -263,14 +258,14 @@ Dali::TtsPlayer::State TtsPlayerTizen::GetState() { // Check the current TTS state tts_state_e state; - int retVal = tts_get_state(mTtsHandle, &state); + int retVal = tts_get_state(mTtsHandle, &state); if(retVal != TTS_ERROR_NONE) { LogErrorCode(static_cast(retVal)); } else { - ttsState = InternalToExternalState( state ); + ttsState = InternalToExternalState(state); } } @@ -282,22 +277,22 @@ Dali::TtsPlayer::StateChangedSignalType& TtsPlayerTizen::StateChangedSignal() return mStateChangedSignal; } -void TtsPlayerTizen::EmitStateChangedSignal( tts_state_e previous, tts_state_e current ) +void TtsPlayerTizen::EmitStateChangedSignal(tts_state_e previous, tts_state_e current) { // Convert the previous and current states to external states and emit them as a signal. - if( !mStateChangedSignal.Empty() ) + if(!mStateChangedSignal.Empty()) { - mStateChangedSignal.Emit( InternalToExternalState( previous ), InternalToExternalState( current ) ); + mStateChangedSignal.Emit(InternalToExternalState(previous), InternalToExternalState(current)); } } -void TtsPlayerTizen::StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void *userData) +void TtsPlayerTizen::StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void* userData) { // Get the implementation (this is a static function). TtsPlayerTizen* obj = static_cast(userData); // Emit the signal. - obj->EmitStateChangedSignal( previous, current ); + obj->EmitStateChangedSignal(previous, current); if(!obj->mInitialized && current == TTS_STATE_READY) { @@ -316,7 +311,7 @@ void TtsPlayerTizen::LogErrorCode(tts_error_e reason) { std::string error_string; - switch (reason) + switch(reason) { case TTS_ERROR_NONE: { diff --git a/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.h b/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.h index 7ae8d18..73e7213 100644 --- a/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.h +++ b/dali/internal/accessibility/tizen-wayland/tts-player-impl-tizen.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ACCESSIBILITY_TIZEN_TTS_PLAYER_IMPL_TIZEN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,33 +20,28 @@ // EXTERNAL INCLUDES #include -#include #include +#include #include #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Text-to-speech player */ class TtsPlayerTizen : public Dali::Internal::Adaptor::TtsPlayer { - public: - /** * Create a TtsPlayer with the given mode. * This should only be called once by the Adaptor class for each given mode. @@ -91,7 +86,6 @@ public: ~TtsPlayerTizen() override; private: - /** * Private Constructor; see also TtsPlayer::New() * @param mode the mode of tts-player @@ -114,7 +108,7 @@ private: * @param[in] previous The previous state * @param[in] current The current state */ - void EmitStateChangedSignal( tts_state_e previous, tts_state_e current ); + void EmitStateChangedSignal(tts_state_e previous, tts_state_e current); /** * Called when the state of TTS is changed. @@ -124,7 +118,7 @@ private: * @param[in] current A current state * @param[in] userData The user data passed from the callback registration function. */ - static void StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void *userData); + static void StateChangedCallback(tts_h tts, tts_state_e previous, tts_state_e current, void* userData); // Undefined TtsPlayerTizen(const TtsPlayerTizen&); @@ -133,12 +127,11 @@ private: TtsPlayerTizen& operator=(TtsPlayerTizen&); private: - Dali::TtsPlayer::StateChangedSignalType mStateChangedSignal; ///< Signal emitted when the TTS state changes - bool mInitialized; ///< Whether the TTS player is initialised successfully or not - std::string mUnplayedString; ///< The text that can not be played because tts engine is not yet initialized - tts_h mTtsHandle; ///< The handle of TTS - int mUtteranceId; ///< The utterance ID + bool mInitialized; ///< Whether the TTS player is initialised successfully or not + std::string mUnplayedString; ///< The text that can not be played because tts engine is not yet initialized + tts_h mTtsHandle; ///< The handle of TTS + int mUtteranceId; ///< The utterance ID Dali::TtsPlayer::Mode mTtsMode; ///< The current mode of tts engine diff --git a/dali/internal/adaptor-framework/android/file-loader-impl-android.cpp b/dali/internal/adaptor-framework/android/file-loader-impl-android.cpp index 06abd6a..5b08b03 100644 --- a/dali/internal/adaptor-framework/android/file-loader-impl-android.cpp +++ b/dali/internal/adaptor-framework/android/file-loader-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ #include // EXTERNAL INCLUDES +#include #include -#include #include -#include +#include // INTERNAL INCLUDES #include @@ -29,25 +29,22 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali::FileLoader::FileType fileType) { std::streampos size; - return Dali::Internal::Adaptor::ReadFile( filename, size, memblock, fileType); + return Dali::Internal::Adaptor::ReadFile(filename, size, memblock, fileType); } int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali::FileLoader::FileType fileType) { std::streampos size; - return Dali::Internal::Adaptor::ReadFile( filename, size, memblock, fileType); + return Dali::Internal::Adaptor::ReadFile(filename, size, memblock, fileType); } inline bool hasPrefix(const std::string& prefix, const std::string& path) @@ -60,7 +57,7 @@ inline std::string ConvertToAssetsInternalPath(const std::string& path, int offs std::string internalPath = std::string(path.c_str() + offset); int i = 0; - while ((i = internalPath.find("//", i)) != std::string::npos) + while((i = internalPath.find("//", i)) != std::string::npos) { internalPath.replace(i, 2, "/"); } @@ -71,63 +68,63 @@ inline std::string ConvertToAssetsInternalPath(const std::string& path, int offs template int ReadFile(const std::string& filename, std::streampos& fileSize, Dali::Vector& memblock, Dali::FileLoader::FileType fileType) { - int errorCode = 0; - int length = 0; - char mode[3] = { 'r', 0, 0 }; + int errorCode = 0; + int length = 0; + char mode[3] = {'r', 0, 0}; - if( fileType == Dali::FileLoader::BINARY ) + if(fileType == Dali::FileLoader::BINARY) { mode[1] = 'b'; } - else if( fileType != Dali::FileLoader::TEXT ) + else if(fileType != Dali::FileLoader::TEXT) { return errorCode; } const std::string assetsPrefix = "assets/"; - if( hasPrefix( assetsPrefix, filename ) ) + if(hasPrefix(assetsPrefix, filename)) { - std::string internalPath = ConvertToAssetsInternalPath( filename, assetsPrefix.length() ); + std::string internalPath = ConvertToAssetsInternalPath(filename, assetsPrefix.length()); AAssetManager* assetManager = Dali::Integration::AndroidFramework::Get().GetApplicationAssets(); - AAsset* asset = AAssetManager_open( assetManager, internalPath.c_str(), AASSET_MODE_BUFFER ); - if( asset ) + AAsset* asset = AAssetManager_open(assetManager, internalPath.c_str(), AASSET_MODE_BUFFER); + if(asset) { - length = AAsset_getLength( asset ); - memblock.Resize( length + 1 ); // 1 for extra zero at the end + length = AAsset_getLength(asset); + memblock.Resize(length + 1); // 1 for extra zero at the end char* buffer = reinterpret_cast(memblock.Begin()); - errorCode = ( AAsset_read( asset, buffer, length ) != length ) ? 0 : 1; - fileSize = length; + errorCode = (AAsset_read(asset, buffer, length) != length) ? 0 : 1; + fileSize = length; - AAsset_close( asset ); + AAsset_close(asset); } else { - DALI_LOG_ERROR( "Asset not found %s\n", internalPath.c_str() ); + DALI_LOG_ERROR("Asset not found %s\n", internalPath.c_str()); } } else { - FILE* file = fopen( filename.c_str(), mode ); - if( file ) + FILE* file = fopen(filename.c_str(), mode); + if(file) { - fseek( file, 0, SEEK_END ); - length = ftell( file ); + fseek(file, 0, SEEK_END); + length = ftell(file); //Dali::Vector.Resize would lead to calling PushBack for each byte, waste of CPU resource - memblock.ResizeUninitialized( length + 1 ); + memblock.ResizeUninitialized(length + 1); //put last byte as 0, in case this is a text file without null-terminator memblock[length] = 0; char* buffer = reinterpret_cast(memblock.Begin()); - fseek( file, 0, SEEK_SET ); - errorCode = ( fread( buffer, 1, length, file ) != length ) ? 0 : 1; - fileSize = length; + fseek(file, 0, SEEK_SET); + errorCode = (fread(buffer, 1, length, file) != length) ? 0 : 1; + fileSize = length; - fclose( file ); + fclose(file); } else { - DALI_LOG_ERROR( "File not found %s\n", filename.c_str() ); + DALI_LOG_ERROR("File not found %s\n", filename.c_str()); } } @@ -139,41 +136,41 @@ std::streampos GetFileSize(const std::string& filename) std::streampos size = 0; const std::string assetsPrefix = "assets/"; - if( hasPrefix( assetsPrefix, filename ) ) + if(hasPrefix(assetsPrefix, filename)) { - std::string internalPath = ConvertToAssetsInternalPath( filename, assetsPrefix.length() ); + std::string internalPath = ConvertToAssetsInternalPath(filename, assetsPrefix.length()); AAssetManager* assetManager = Dali::Integration::AndroidFramework::Get().GetApplicationAssets(); - AAsset* asset = AAssetManager_open( assetManager, internalPath.c_str(), AASSET_MODE_BUFFER ); - if( asset ) + AAsset* asset = AAssetManager_open(assetManager, internalPath.c_str(), AASSET_MODE_BUFFER); + if(asset) { - size = AAsset_getLength( asset ); - AAsset_close( asset ); + size = AAsset_getLength(asset); + AAsset_close(asset); } else { - DALI_LOG_ERROR( "Asset not found %s\n", internalPath.c_str() ); + DALI_LOG_ERROR("Asset not found %s\n", internalPath.c_str()); } } else { - FILE* file = fopen( filename.c_str(), "r" ); - if( file ) + FILE* file = fopen(filename.c_str(), "r"); + if(file) { - fseek( file, 0, SEEK_END ); - size = ftell( file ); - fclose( file ); + fseek(file, 0, SEEK_END); + size = ftell(file); + fclose(file); } else { - DALI_LOG_ERROR( "File not found %s\n", filename.c_str() ); + DALI_LOG_ERROR("File not found %s\n", filename.c_str()); } } return size; } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/adaptor-framework/android/file-stream-impl-android.cpp b/dali/internal/adaptor-framework/android/file-stream-impl-android.cpp index 3c85454..a03091c 100644 --- a/dali/internal/adaptor-framework/android/file-stream-impl-android.cpp +++ b/dali/internal/adaptor-framework/android/file-stream-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,9 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include +#include // INTERNAL INCLUDES #include @@ -28,34 +28,33 @@ namespace Dali { - FileStream::Impl::Impl(const std::string& filename, uint8_t mode) -: mFileName( filename ), - mMode( mode ), - mBuffer( nullptr ), - mDataSize( 0 ), - mFile( nullptr ) +: mFileName(filename), + mMode(mode), + mBuffer(nullptr), + mDataSize(0), + mFile(nullptr) { - DALI_ASSERT_DEBUG( !filename.empty() && "Can't open a empty filename." ); - DALI_ASSERT_DEBUG( mode != 0 && "No mode is undefined behaviour" ); + DALI_ASSERT_DEBUG(!filename.empty() && "Can't open a empty filename."); + DALI_ASSERT_DEBUG(mode != 0 && "No mode is undefined behaviour"); } FileStream::Impl::Impl(uint8_t* buffer, size_t dataSize, uint8_t mode) -: mMode( mode ), - mBuffer( buffer ), - mDataSize( dataSize ), - mFile( nullptr ) +: mMode(mode), + mBuffer(buffer), + mDataSize(dataSize), + mFile(nullptr) { - DALI_ASSERT_DEBUG( buffer != 0 && "Can't open file on null buffer." ); - DALI_ASSERT_DEBUG( dataSize > 0 && "Pointless to open file on empty buffer." ); - DALI_ASSERT_DEBUG( mode != 0 && "No mode is undefined behaviour." ); + DALI_ASSERT_DEBUG(buffer != 0 && "Can't open file on null buffer."); + DALI_ASSERT_DEBUG(dataSize > 0 && "Pointless to open file on empty buffer."); + DALI_ASSERT_DEBUG(mode != 0 && "No mode is undefined behaviour."); } FileStream::Impl::Impl(Dali::Vector& buffer, size_t dataSize, uint8_t mode) -: mMode( mode ), - mBuffer( nullptr ), - mDataSize( dataSize ), - mFile( nullptr ) +: mMode(mode), + mBuffer(nullptr), + mDataSize(dataSize), + mFile(nullptr) { // Resize the buffer to ensure any null that gets written by // fmemopen is written past the end of any data that is written to the buffer. @@ -64,28 +63,28 @@ FileStream::Impl::Impl(Dali::Vector& buffer, size_t dataSize, uint8_t m // null if binary mode is specified). ++mDataSize; - buffer.Resize( mDataSize ); + buffer.Resize(mDataSize); mBuffer = &buffer[0]; - DALI_ASSERT_DEBUG( mBuffer != nullptr && "Can't open file on null buffer." ); - DALI_ASSERT_DEBUG( dataSize > 0 && "Pointless to open file on empty buffer." ); - DALI_ASSERT_DEBUG( mode != 0 && "No mode is undefined behaviour." ); + DALI_ASSERT_DEBUG(mBuffer != nullptr && "Can't open file on null buffer."); + DALI_ASSERT_DEBUG(dataSize > 0 && "Pointless to open file on empty buffer."); + DALI_ASSERT_DEBUG(mode != 0 && "No mode is undefined behaviour."); } FileStream::Impl::~Impl() { - if( mFile ) + if(mFile) { - const int closeFailed = fclose( mFile ); - if( closeFailed ) + const int closeFailed = fclose(mFile); + if(closeFailed) { - DALI_LOG_WARNING( "File close failed for FILE: \"%p\".\n", static_cast( mFile ) ); + DALI_LOG_WARNING("File close failed for FILE: \"%p\".\n", static_cast(mFile)); } mFile = nullptr; } - if( mFileStream.is_open() ) + if(mFileStream.is_open()) { mFileStream.close(); } @@ -93,83 +92,87 @@ FileStream::Impl::~Impl() std::iostream& FileStream::Impl::GetStream() { - if( mFile ) + if(mFile) { // return empty stream if FILE stream is open to avoid simultaneous access to the same file return mFileStream; } - if( mFileStream.is_open() ) + if(mFileStream.is_open()) { return mFileStream; } - if( mBufferStream.rdbuf()->in_avail() ) + if(mBufferStream.rdbuf()->in_avail()) { return mBufferStream; } int openMode = 0; - if( mMode & Dali::FileStream::APPEND ) + if(mMode & Dali::FileStream::APPEND) { - openMode |= ( std::ios::out | std::ios::app ); + openMode |= (std::ios::out | std::ios::app); } - else if( mMode & Dali::FileStream::WRITE ) + else if(mMode & Dali::FileStream::WRITE) { - openMode |= ( std::ios::out | std::ios::ate ); + openMode |= (std::ios::out | std::ios::ate); } - if( mMode & Dali::FileStream::READ ) + if(mMode & Dali::FileStream::READ) { openMode |= std::ios::in; } - if( mMode & Dali::FileStream::BINARY ) + if(mMode & Dali::FileStream::BINARY) { openMode |= std::ios::binary; } - if( !mFileName.empty() ) + if(!mFileName.empty()) { // TODO: it works only with text files, we need custom stream buffer implementation for binary and to avoid buffer copy - if( !( mMode & Dali::FileStream::WRITE ) && !( mMode & Dali::FileStream::APPEND ) && !( mMode & Dali::FileStream::BINARY ) ) + if(!(mMode & Dali::FileStream::WRITE) && !(mMode & Dali::FileStream::APPEND) && !(mMode & Dali::FileStream::BINARY)) { std::streampos fileSize; - if( ReadFile( mFileName, fileSize, mFileBuffer, Dali::FileLoader::TEXT ) ) + if(ReadFile(mFileName, fileSize, mFileBuffer, Dali::FileLoader::TEXT)) { - mBuffer = reinterpret_cast( &mFileBuffer[0] ); + mBuffer = reinterpret_cast(&mFileBuffer[0]); mDataSize = fileSize; - mBufferStream.str( std::string ( &mFileBuffer[0], fileSize ) ); - if( !mBufferStream.rdbuf()->in_avail() ) + mBufferStream.str(std::string(&mFileBuffer[0], fileSize)); + if(!mBufferStream.rdbuf()->in_avail()) { - DALI_LOG_ERROR( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%d\".\n", - static_cast( mBuffer ), static_cast( mDataSize ), static_cast( openMode ) ); + DALI_LOG_ERROR("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%d\".\n", + static_cast(mBuffer), + static_cast(mDataSize), + static_cast(openMode)); } return mBufferStream; } else { - DALI_LOG_ERROR( "stream open failed for: \"%s\", in mode: \"%d\".\n", mFileName.c_str(), static_cast( openMode ) ); + DALI_LOG_ERROR("stream open failed for: \"%s\", in mode: \"%d\".\n", mFileName.c_str(), static_cast(openMode)); } } else { - mFileStream.open( mFileName, static_cast( openMode ) ); - if( !mFileStream.is_open() ) + mFileStream.open(mFileName, static_cast(openMode)); + if(!mFileStream.is_open()) { - DALI_LOG_ERROR( "stream open failed for: \"%s\", in mode: \"%d\".\n", mFileName.c_str(), static_cast( openMode ) ); + DALI_LOG_ERROR("stream open failed for: \"%s\", in mode: \"%d\".\n", mFileName.c_str(), static_cast(openMode)); } } return mFileStream; } - else if( mBuffer ) + else if(mBuffer) { - mBufferStream.rdbuf()->pubsetbuf( reinterpret_cast( mBuffer ), mDataSize ); - if( !mBufferStream.rdbuf()->in_avail() ) + mBufferStream.rdbuf()->pubsetbuf(reinterpret_cast(mBuffer), mDataSize); + if(!mBufferStream.rdbuf()->in_avail()) { - DALI_LOG_ERROR( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%d\".\n", - static_cast( mBuffer ), static_cast( mDataSize ), static_cast( openMode ) ); + DALI_LOG_ERROR("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%d\".\n", + static_cast(mBuffer), + static_cast(mDataSize), + static_cast(openMode)); } } @@ -178,25 +181,25 @@ std::iostream& FileStream::Impl::GetStream() FILE* FileStream::Impl::GetFile() { - if( mFileStream.is_open() || mBufferStream.rdbuf()->in_avail() ) + if(mFileStream.is_open() || mBufferStream.rdbuf()->in_avail()) { // return empty FILE stream if the stream is open to avoid simultaneous access to the same file return nullptr; } - if( mFile ) + if(mFile) { return mFile; } - char openMode[16] = { 0 }; - int i = 0; + char openMode[16] = {0}; + int i = 0; - if( mMode & Dali::FileStream::APPEND ) + if(mMode & Dali::FileStream::APPEND) { openMode[i++] = 'a'; } - else if( mMode & Dali::FileStream::WRITE ) + else if(mMode & Dali::FileStream::WRITE) { openMode[i++] = 'w'; } @@ -205,54 +208,58 @@ FILE* FileStream::Impl::GetFile() openMode[i++] = 'r'; } - if( mMode & Dali::FileStream::BINARY ) + if(mMode & Dali::FileStream::BINARY) { openMode[i++] = 'b'; } openMode[i++] = 0; - if( !mFileName.empty() ) + if(!mFileName.empty()) { - if ( !( mMode & Dali::FileStream::WRITE ) && !( mMode & Dali::FileStream::APPEND ) ) + if(!(mMode & Dali::FileStream::WRITE) && !(mMode & Dali::FileStream::APPEND)) { std::streampos fileSize; - if ( ReadFile( mFileName, fileSize, mFileBuffer, ( mMode & Dali::FileStream::BINARY ) ? Dali::FileLoader::BINARY : Dali::FileLoader::TEXT ) ) + if(ReadFile(mFileName, fileSize, mFileBuffer, (mMode & Dali::FileStream::BINARY) ? Dali::FileLoader::BINARY : Dali::FileLoader::TEXT)) { - mBuffer = reinterpret_cast( &mFileBuffer[0] ); + mBuffer = reinterpret_cast(&mFileBuffer[0]); mDataSize = fileSize; - mFile = fmemopen( mBuffer, mDataSize, openMode ); - if( !mFile ) + mFile = fmemopen(mBuffer, mDataSize, openMode); + if(!mFile) { - DALI_LOG_ERROR( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", - static_cast( mBuffer ), static_cast( mDataSize ), openMode ); + DALI_LOG_ERROR("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", + static_cast(mBuffer), + static_cast(mDataSize), + openMode); } } else { - DALI_LOG_ERROR( "read file failed for: \"%s\", in mode: \"%s\".\n", mFileName.c_str(), openMode ); + DALI_LOG_ERROR("read file failed for: \"%s\", in mode: \"%s\".\n", mFileName.c_str(), openMode); } } else { - mFile = fopen( mFileName.c_str(), openMode ); - if( !mFile ) + mFile = fopen(mFileName.c_str(), openMode); + if(!mFile) { - DALI_LOG_ERROR( "file open failed for: \"%s\", in mode: \"%s\".\n", mFileName.c_str(), openMode ); + DALI_LOG_ERROR("file open failed for: \"%s\", in mode: \"%s\".\n", mFileName.c_str(), openMode); } } } - else if( mBuffer ) + else if(mBuffer) { - mFile = fmemopen( mBuffer, mDataSize, openMode ); - if( !mFile ) + mFile = fmemopen(mBuffer, mDataSize, openMode); + if(!mFile) { - DALI_LOG_ERROR( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", - static_cast( mBuffer ), static_cast( mDataSize ), openMode ); + DALI_LOG_ERROR("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", + static_cast(mBuffer), + static_cast(mDataSize), + openMode); } } return mFile; } -} // Dali +} // namespace Dali diff --git a/dali/internal/adaptor-framework/common/file-loader-impl.h b/dali/internal/adaptor-framework/common/file-loader-impl.h index 96199a1..23910e4 100644 --- a/dali/internal/adaptor-framework/common/file-loader-impl.h +++ b/dali/internal/adaptor-framework/common/file-loader-impl.h @@ -2,7 +2,7 @@ #define DALI_FILE_LOADER_IMPL_GENERIC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali::FileLoader::FileType fileType = Dali::FileLoader::BINARY); int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali::FileLoader::FileType fileType = Dali::FileLoader::BINARY); @@ -40,9 +37,9 @@ int ReadFile(const std::string& filename, std::streampos& fileSize, Dali::Vector std::streampos GetFileSize(const std::string& filename); -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali #endif // DALI_FILE_LOADER_IMPL_GENERIC_H diff --git a/dali/internal/adaptor-framework/common/file-stream-impl.h b/dali/internal/adaptor-framework/common/file-stream-impl.h index 8b4e3ae..63177e4 100644 --- a/dali/internal/adaptor-framework/common/file-stream-impl.h +++ b/dali/internal/adaptor-framework/common/file-stream-impl.h @@ -2,7 +2,7 @@ #define DALI_FILE_STREAM_IMPL_GENERIC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ namespace Dali { - class FileStream::Impl { public: @@ -44,16 +43,16 @@ public: private: std::string mFileName; - uint8_t mMode; - uint8_t* mBuffer; // external buffer, not owned - size_t mDataSize; + uint8_t mMode; + uint8_t* mBuffer; // external buffer, not owned + size_t mDataSize; Dali::Vector mFileBuffer; // for internal usage only - FILE* mFile; - std::fstream mFileStream; - std::stringstream mBufferStream; + FILE* mFile; + std::fstream mFileStream; + std::stringstream mBufferStream; }; -} // Dali +} // namespace Dali #endif // DALI_FILE_STREAM_IMPL_GENERIC_H diff --git a/dali/internal/adaptor-framework/generic/file-loader-impl-generic.cpp b/dali/internal/adaptor-framework/generic/file-loader-impl-generic.cpp index 0baa2bf..10580e9 100644 --- a/dali/internal/adaptor-framework/generic/file-loader-impl-generic.cpp +++ b/dali/internal/adaptor-framework/generic/file-loader-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,18 +25,15 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali::FileLoader::FileType fileType) { std::streampos size; - return Dali::Internal::Adaptor::ReadFile( filename, size, memblock, fileType); + return Dali::Internal::Adaptor::ReadFile(filename, size, memblock, fileType); } int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali::FileLoader::FileType fileType) @@ -49,30 +46,30 @@ int ReadFile(const std::string& filename, Dali::Vector& memblock, Dali: template int ReadFile(const std::string& filename, std::streampos& fileSize, Dali::Vector& memblock, Dali::FileLoader::FileType fileType) { - int errorCode = 0; - std::ifstream * file; + int errorCode = 0; + std::ifstream* file; - if( fileType == Dali::FileLoader::BINARY ) + if(fileType == Dali::FileLoader::BINARY) { - file = new std::ifstream (filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate); + file = new std::ifstream(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate); } - else if( fileType == Dali::FileLoader::TEXT ) + else if(fileType == Dali::FileLoader::TEXT) { - file = new std::ifstream (filename.c_str(), std::ios::in|std::ios::ate); + file = new std::ifstream(filename.c_str(), std::ios::in | std::ios::ate); } else { return errorCode; } - if( file->is_open() ) + if(file->is_open()) { fileSize = file->tellg(); - memblock.Resize( fileSize ); + memblock.Resize(fileSize); - file->seekg (0, std::ios::beg); - file->read( reinterpret_cast(memblock.Begin()), fileSize ); + file->seekg(0, std::ios::beg); + file->read(reinterpret_cast(memblock.Begin()), fileSize); file->close(); delete file; @@ -82,7 +79,7 @@ int ReadFile(const std::string& filename, std::streampos& fileSize, Dali::Vector else { char buf[512]; - DALI_LOG_ERROR( "file open failed for: \"%s\", error : %s\n", filename.c_str(), strerror_r( errno, buf, 512 ) ); + DALI_LOG_ERROR("file open failed for: \"%s\", error : %s\n", filename.c_str(), strerror_r(errno, buf, 512)); } return errorCode; @@ -92,8 +89,8 @@ std::streampos GetFileSize(const std::string& filename) { std::streampos size = 0; - std::ifstream file( filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate ); - if( file.is_open() ) + std::ifstream file(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate); + if(file.is_open()) { size = file.tellg(); file.close(); @@ -102,8 +99,8 @@ std::streampos GetFileSize(const std::string& filename) return size; } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/adaptor-framework/generic/file-stream-impl-generic.cpp b/dali/internal/adaptor-framework/generic/file-stream-impl-generic.cpp index 98bdb96..8af04d2 100644 --- a/dali/internal/adaptor-framework/generic/file-stream-impl-generic.cpp +++ b/dali/internal/adaptor-framework/generic/file-stream-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,34 +25,33 @@ namespace Dali { - FileStream::Impl::Impl(const std::string& filename, uint8_t mode) -: mFileName( filename ), - mMode( mode ), - mBuffer( nullptr ), - mDataSize( 0 ), - mFile( nullptr ) +: mFileName(filename), + mMode(mode), + mBuffer(nullptr), + mDataSize(0), + mFile(nullptr) { - DALI_ASSERT_DEBUG( !filename.empty() && "Can't open a empty filename." ); - DALI_ASSERT_DEBUG( mode != 0 && "No mode is undefined behaviour" ); + DALI_ASSERT_DEBUG(!filename.empty() && "Can't open a empty filename."); + DALI_ASSERT_DEBUG(mode != 0 && "No mode is undefined behaviour"); } FileStream::Impl::Impl(uint8_t* buffer, size_t dataSize, uint8_t mode) -: mMode( mode ), - mBuffer( buffer ), - mDataSize( dataSize ), - mFile( nullptr ) +: mMode(mode), + mBuffer(buffer), + mDataSize(dataSize), + mFile(nullptr) { - DALI_ASSERT_DEBUG( buffer != 0 && "Can't open file on null buffer." ); - DALI_ASSERT_DEBUG( dataSize > 0 && "Pointless to open file on empty buffer." ); - DALI_ASSERT_DEBUG( mode != 0 && "No mode is undefined behaviour." ); + DALI_ASSERT_DEBUG(buffer != 0 && "Can't open file on null buffer."); + DALI_ASSERT_DEBUG(dataSize > 0 && "Pointless to open file on empty buffer."); + DALI_ASSERT_DEBUG(mode != 0 && "No mode is undefined behaviour."); } FileStream::Impl::Impl(Dali::Vector& vector, size_t dataSize, uint8_t mode) -: mMode( mode ), - mBuffer( nullptr ), - mDataSize( dataSize ), - mFile( nullptr ) +: mMode(mode), + mBuffer(nullptr), + mDataSize(dataSize), + mFile(nullptr) { // Resize the buffer to ensure any null that gets written by // fmemopen is written past the end of any data that is written to the buffer. @@ -61,28 +60,28 @@ FileStream::Impl::Impl(Dali::Vector& vector, size_t dataSize, uint8_t m // null if binary mode is specified). ++mDataSize; - vector.Resize( mDataSize ); + vector.Resize(mDataSize); mBuffer = &vector[0]; - DALI_ASSERT_DEBUG( mBuffer != nullptr && "Can't open file on null buffer." ); - DALI_ASSERT_DEBUG( dataSize > 0 && "Pointless to open file on empty buffer." ); - DALI_ASSERT_DEBUG( mode != 0 && "No mode is undefined behaviour." ); + DALI_ASSERT_DEBUG(mBuffer != nullptr && "Can't open file on null buffer."); + DALI_ASSERT_DEBUG(dataSize > 0 && "Pointless to open file on empty buffer."); + DALI_ASSERT_DEBUG(mode != 0 && "No mode is undefined behaviour."); } FileStream::Impl::~Impl() { - if( mFile ) + if(mFile) { - const int closeFailed = fclose( mFile ); - if( closeFailed ) + const int closeFailed = fclose(mFile); + if(closeFailed) { - DALI_LOG_WARNING( "File close failed for FILE: \"%p\".\n", static_cast( mFile ) ); + DALI_LOG_WARNING("File close failed for FILE: \"%p\".\n", static_cast(mFile)); } mFile = nullptr; } - if( mFileStream.is_open() ) + if(mFileStream.is_open()) { mFileStream.close(); } @@ -90,59 +89,61 @@ FileStream::Impl::~Impl() std::iostream& FileStream::Impl::GetStream() { - if( mFile ) + if(mFile) { // return empty stream if FILE stream is open to avoid simultaneous access to the same file return mFileStream; } - if( mFileStream.is_open() ) + if(mFileStream.is_open()) { return mFileStream; } - if( mBufferStream.rdbuf()->in_avail() ) + if(mBufferStream.rdbuf()->in_avail()) { return mBufferStream; } int openMode = 0; - if( mMode & Dali::FileStream::APPEND ) + if(mMode & Dali::FileStream::APPEND) { - openMode |= ( std::ios::out | std::ios::app ); + openMode |= (std::ios::out | std::ios::app); } - else if( mMode & Dali::FileStream::WRITE ) + else if(mMode & Dali::FileStream::WRITE) { - openMode |= ( std::ios::out | std::ios::ate ); + openMode |= (std::ios::out | std::ios::ate); } - if( mMode & Dali::FileStream::READ ) + if(mMode & Dali::FileStream::READ) { openMode |= std::ios::in; } - if( mMode & Dali::FileStream::BINARY ) + if(mMode & Dali::FileStream::BINARY) { openMode |= std::ios::binary; } - if( !mFileName.empty() ) + if(!mFileName.empty()) { - mFileStream.open( mFileName, static_cast( openMode ) ); - if( !mFileStream.is_open() ) + mFileStream.open(mFileName, static_cast(openMode)); + if(!mFileStream.is_open()) { - DALI_LOG_WARNING( "stream open failed for: \"%s\", in mode: \"%d\".\n", mFileName.c_str(), openMode ); + DALI_LOG_WARNING("stream open failed for: \"%s\", in mode: \"%d\".\n", mFileName.c_str(), openMode); } return mFileStream; } - else if( mBuffer ) + else if(mBuffer) { - mBufferStream.rdbuf()->pubsetbuf( reinterpret_cast( mBuffer ), mDataSize ); - if( !mBufferStream.rdbuf()->in_avail() ) + mBufferStream.rdbuf()->pubsetbuf(reinterpret_cast(mBuffer), mDataSize); + if(!mBufferStream.rdbuf()->in_avail()) { - DALI_LOG_WARNING( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%d\".\n", - static_cast( mBuffer ), static_cast( mDataSize ), openMode ); + DALI_LOG_WARNING("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%d\".\n", + static_cast(mBuffer), + static_cast(mDataSize), + openMode); } } @@ -151,25 +152,25 @@ std::iostream& FileStream::Impl::GetStream() FILE* FileStream::Impl::GetFile() { - if( mFileStream.is_open() || mBufferStream.rdbuf()->in_avail() ) + if(mFileStream.is_open() || mBufferStream.rdbuf()->in_avail()) { // return empty FILE stream if the stream is open to avoid simultaneous access to the same file return nullptr; } - if( mFile ) + if(mFile) { return mFile; } - char openMode[16] = { 0 }; - int i = 0; + char openMode[16] = {0}; + int i = 0; - if( mMode & Dali::FileStream::APPEND ) + if(mMode & Dali::FileStream::APPEND) { openMode[i++] = 'a'; } - else if( mMode & Dali::FileStream::WRITE ) + else if(mMode & Dali::FileStream::WRITE) { openMode[i++] = 'w'; } @@ -178,36 +179,38 @@ FILE* FileStream::Impl::GetFile() openMode[i++] = 'r'; } - if( mMode & Dali::FileStream::BINARY ) + if(mMode & Dali::FileStream::BINARY) { openMode[i++] = 'b'; } openMode[i++] = 0; - if( !mFileName.empty() ) + if(!mFileName.empty()) { - mFile = fopen( mFileName.c_str(), openMode ); - if( !mFile ) + mFile = fopen(mFileName.c_str(), openMode); + if(!mFile) { char buf[512]; - DALI_LOG_ERROR( "file open failed for: \"%s\", in mode: \"%s\".\n", mFileName.c_str(), openMode ); - DALI_LOG_ERROR( "file open failed error : %s\n", strerror_r( errno, buf, 512 ) ); + DALI_LOG_ERROR("file open failed for: \"%s\", in mode: \"%s\".\n", mFileName.c_str(), openMode); + DALI_LOG_ERROR("file open failed error : %s\n", strerror_r(errno, buf, 512)); } } - else if( mBuffer ) + else if(mBuffer) { - mFile = fmemopen( mBuffer, mDataSize, openMode ); - if( !mFile ) + mFile = fmemopen(mBuffer, mDataSize, openMode); + if(!mFile) { char buf[512]; - DALI_LOG_ERROR( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", - static_cast( mBuffer ), static_cast( mDataSize ), openMode ); - DALI_LOG_ERROR( "file open failed error : %s\n", strerror_r( errno, buf, 512 ) ); + DALI_LOG_ERROR("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", + static_cast(mBuffer), + static_cast(mDataSize), + openMode); + DALI_LOG_ERROR("file open failed error : %s\n", strerror_r(errno, buf, 512)); } } return mFile; } -} // Dali +} // namespace Dali diff --git a/dali/internal/adaptor/android/android-framework-impl.cpp b/dali/internal/adaptor/android/android-framework-impl.cpp index c83265e..4a90531 100644 --- a/dali/internal/adaptor/android/android-framework-impl.cpp +++ b/dali/internal/adaptor/android/android-framework-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { AndroidFramework* gAndroidFramework = nullptr; // raw specific pointer to allow AndroidFramework::Get @@ -35,20 +32,20 @@ AndroidFramework* gAndroidFramework = nullptr; // raw specific pointer to allow Dali::Integration::AndroidFramework& AndroidFramework::New() { Dali::Integration::AndroidFramework* androidFramework = new Dali::Integration::AndroidFramework; - AndroidFramework* impl = new AndroidFramework( androidFramework ); - androidFramework->mImpl = impl; + AndroidFramework* impl = new AndroidFramework(androidFramework); + androidFramework->mImpl = impl; return *androidFramework; } void AndroidFramework::Delete() { - DALI_ASSERT_ALWAYS( gAndroidFramework != nullptr && "Cannot delete already deleted AndroidFramework." ); + DALI_ASSERT_ALWAYS(gAndroidFramework != nullptr && "Cannot delete already deleted AndroidFramework."); delete gAndroidFramework->mAndroidFramework; gAndroidFramework = nullptr; } -void AndroidFramework::SetNativeApplication( android_app* application ) +void AndroidFramework::SetNativeApplication(android_app* application) { mNativeApplication = application; } @@ -58,7 +55,7 @@ android_app* AndroidFramework::GetNativeApplication() const return mNativeApplication; } -void AndroidFramework::SetJVM( JavaVM* jvm ) +void AndroidFramework::SetJVM(JavaVM* jvm) { mJVM = jvm; } @@ -68,7 +65,7 @@ JavaVM* AndroidFramework::GetJVM() const return mJVM; } -void AndroidFramework::SetApplicationAssets( AAssetManager* assets ) +void AndroidFramework::SetApplicationAssets(AAssetManager* assets) { mAssets = assets; } @@ -78,7 +75,7 @@ AAssetManager* AndroidFramework::GetApplicationAssets() const return mAssets; } -void AndroidFramework::SetInternalDataPath( const std::string& path ) +void AndroidFramework::SetInternalDataPath(const std::string& path) { mInternalDataPath = path; } @@ -88,7 +85,7 @@ std::string AndroidFramework::GetInternalDataPath() const return mInternalDataPath; } -void AndroidFramework::SetApplicationConfiguration( AConfiguration* configuration ) +void AndroidFramework::SetApplicationConfiguration(AConfiguration* configuration) { mConfiguration = configuration; } @@ -98,7 +95,7 @@ AConfiguration* AndroidFramework::GetApplicationConfiguration() const return mConfiguration; } -void AndroidFramework::SetApplicationWindow( ANativeWindow* window ) +void AndroidFramework::SetApplicationWindow(ANativeWindow* window) { mWindow = window; } @@ -110,46 +107,46 @@ ANativeWindow* AndroidFramework::GetApplicationWindow() const void AndroidFramework::OnTerminate() { - mFramework->AppStatusHandler( APP_DESTROYED, nullptr ); + mFramework->AppStatusHandler(APP_DESTROYED, nullptr); } void AndroidFramework::OnPause() { - mFramework->AppStatusHandler( APP_PAUSE, nullptr ); + mFramework->AppStatusHandler(APP_PAUSE, nullptr); } void AndroidFramework::OnResume() { - mFramework->AppStatusHandler( APP_RESUME, nullptr ); + mFramework->AppStatusHandler(APP_RESUME, nullptr); } -void AndroidFramework::OnWindowCreated( ANativeWindow* window ) +void AndroidFramework::OnWindowCreated(ANativeWindow* window) { - mFramework->AppStatusHandler( APP_WINDOW_CREATED, window ); + mFramework->AppStatusHandler(APP_WINDOW_CREATED, window); } -void AndroidFramework::OnWindowDestroyed( ANativeWindow* window ) +void AndroidFramework::OnWindowDestroyed(ANativeWindow* window) { - mFramework->AppStatusHandler( APP_WINDOW_DESTROYED, window ); + mFramework->AppStatusHandler(APP_WINDOW_DESTROYED, window); } Dali::Integration::AndroidFramework& AndroidFramework::Get() { - DALI_ASSERT_ALWAYS( gAndroidFramework != nullptr && "AndroidFramework not instantiated" ); + DALI_ASSERT_ALWAYS(gAndroidFramework != nullptr && "AndroidFramework not instantiated"); return *gAndroidFramework->mAndroidFramework; } -AndroidFramework::AndroidFramework( Dali::Integration::AndroidFramework* androidFramework ) - : mAndroidFramework( androidFramework ), - mFramework( nullptr ), - mNativeApplication( nullptr ), - mWindow( nullptr ), - mAssets( nullptr ), - mConfiguration( nullptr ), - mJVM( nullptr ) +AndroidFramework::AndroidFramework(Dali::Integration::AndroidFramework* androidFramework) +: mAndroidFramework(androidFramework), + mFramework(nullptr), + mNativeApplication(nullptr), + mWindow(nullptr), + mAssets(nullptr), + mConfiguration(nullptr), + mJVM(nullptr) { - DALI_ASSERT_ALWAYS( gAndroidFramework == nullptr && "Cannot create more than one AndroidFramework." ); + DALI_ASSERT_ALWAYS(gAndroidFramework == nullptr && "Cannot create more than one AndroidFramework."); gAndroidFramework = this; } diff --git a/dali/internal/adaptor/android/android-framework-impl.h b/dali/internal/adaptor/android/android-framework-impl.h index 9bec4ce..8dae6be 100644 --- a/dali/internal/adaptor/android/android-framework-impl.h +++ b/dali/internal/adaptor/android/android-framework-impl.h @@ -2,7 +2,7 @@ #define DALI_INTEGRATION_ANDROID_FRAMEWORK_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,13 +26,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /// Android application events enum { @@ -67,7 +64,7 @@ public: /** * @copydoc Dali::Integration::AndroidFramework::SetNativeApplication() */ - void SetNativeApplication( android_app* application ); + void SetNativeApplication(android_app* application); /** * @copydoc Dali::Integration::AndroidFramework::GetNativeApplication() @@ -77,7 +74,7 @@ public: /** * @copydoc Dali::Integration::AndroidFramework::SetJVM() */ - void SetJVM( JavaVM* jvm ); + void SetJVM(JavaVM* jvm); /** * @copydoc Dali::Integration::AndroidFramework::GetJVM() @@ -87,7 +84,7 @@ public: /** * @copydoc Dali::Integration::AndroidFramework::SetApplicationAssets() */ - void SetApplicationAssets( AAssetManager* assets ); + void SetApplicationAssets(AAssetManager* assets); /** * @copydoc Dali::Integration::AndroidFramework::GetApplicationAssets() @@ -97,7 +94,7 @@ public: /** * copydoc Dali::Integration::AndroidFramework::SetInternalDataPath() */ - void SetInternalDataPath( const std::string& path ); + void SetInternalDataPath(const std::string& path); /** * copydoc Dali::Integration::AndroidFramework::GetInternalDataPath() @@ -107,7 +104,7 @@ public: /** * @copydoc Dali::Integration::AndroidFramework::SetApplicationConfiguration() */ - void SetApplicationConfiguration( AConfiguration* configuration ); + void SetApplicationConfiguration(AConfiguration* configuration); /** * @copydoc Dali::Integration::AndroidFramework::GetApplicationConfiguration() @@ -117,7 +114,7 @@ public: /** * @copydoc Dali::Integration::AndroidFramework::SetApplicationWindow() */ - void SetApplicationWindow( ANativeWindow* window ); + void SetApplicationWindow(ANativeWindow* window); /** * @copydoc Dali::Integration::AndroidFramework::GetApplicationWindow() @@ -142,12 +139,12 @@ public: /** * @copydoc Dali::Integration::AndroidFramework::OnWindowCreated() */ - void OnWindowCreated( ANativeWindow* window ); + void OnWindowCreated(ANativeWindow* window); /** * @copydoc Dali::Integration::AndroidFramework::OnWindowDestroyed() */ - void OnWindowDestroyed( ANativeWindow* window ); + void OnWindowDestroyed(ANativeWindow* window); /** * @copydoc Dali::Integration::AndroidFramework::Get() @@ -157,14 +154,20 @@ public: /** * @brief Sets an internal framework. */ - void SetFramework( Framework* framework ) { mFramework = framework; } + void SetFramework(Framework* framework) + { + mFramework = framework; + } /** * @brief Gets an internal framework. * * @return a pointer to the internal framework */ - Framework* GetFramework() { return mFramework; } + Framework* GetFramework() + { + return mFramework; + } /** * Virtual destructor. @@ -172,33 +175,38 @@ public: virtual ~AndroidFramework(); // Not copyable or movable - AndroidFramework( const AndroidFramework& ) = delete; ///< Deleted copy constructor - AndroidFramework( AndroidFramework&& ) = delete; ///< Deleted move constructor - AndroidFramework& operator=( const AndroidFramework& ) = delete; ///< Deleted copy assignment operator - AndroidFramework& operator=( AndroidFramework&& ) = delete; ///< Deleted move assignment operator + AndroidFramework(const AndroidFramework&) = delete; ///< Deleted copy constructor + AndroidFramework(AndroidFramework&&) = delete; ///< Deleted move constructor + AndroidFramework& operator=(const AndroidFramework&) = delete; ///< Deleted copy assignment operator + AndroidFramework& operator=(AndroidFramework&&) = delete; ///< Deleted move assignment operator private: - AndroidFramework( Dali::Integration::AndroidFramework* androidFramework ); + AndroidFramework(Dali::Integration::AndroidFramework* androidFramework); Dali::Integration::AndroidFramework* mAndroidFramework; - Framework* mFramework; + Framework* mFramework; - android_app* mNativeApplication; - ANativeWindow* mWindow; - AAssetManager* mAssets; - std::string mInternalDataPath; + android_app* mNativeApplication; + ANativeWindow* mWindow; + AAssetManager* mAssets; + std::string mInternalDataPath; AConfiguration* mConfiguration; - JavaVM* mJVM; + JavaVM* mJVM; public: - static AndroidFramework& GetImplementation( Dali::Integration::AndroidFramework& androidFramework ) { return *androidFramework.mImpl; } - static Framework& GetFramework( Dali::Integration::AndroidFramework& androidFramework ) { return *androidFramework.mImpl->mFramework; } + static AndroidFramework& GetImplementation(Dali::Integration::AndroidFramework& androidFramework) + { + return *androidFramework.mImpl; + } + static Framework& GetFramework(Dali::Integration::AndroidFramework& androidFramework) + { + return *androidFramework.mImpl->mFramework; + } }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTEGRATION_ANDROID_FRAMEWORK_IMPL_H - diff --git a/dali/internal/adaptor/android/framework-android.cpp b/dali/internal/adaptor/android/framework-android.cpp index a6a3549..0f93208 100644 --- a/dali/internal/adaptor/android/framework-android.cpp +++ b/dali/internal/adaptor/android/framework-android.cpp @@ -19,55 +19,51 @@ #include // EXTERNAL INCLUDES +#include #include #include #include -#include -#include +#include +#include #include #include -#include -#include +#include #include #include -#include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - // Copied from x server static unsigned int GetCurrentMilliSeconds(void) { struct timeval tv; - struct timespec tp; + struct timespec tp; static clockid_t clockid; - if (!clockid) + if(!clockid) { #ifdef CLOCK_MONOTONIC_COARSE - if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 && - (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0) + if(clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 && + (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0) { clockid = CLOCK_MONOTONIC_COARSE; } else #endif - if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) + if(clock_gettime(CLOCK_MONOTONIC, &tp) == 0) { clockid = CLOCK_MONOTONIC; } @@ -76,7 +72,7 @@ static unsigned int GetCurrentMilliSeconds(void) clockid = ~0L; } } - if (clockid != ~0L && clock_gettime(clockid, &tp) == 0) + if(clockid != ~0L && clock_gettime(clockid, &tp) == 0) { return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L); } @@ -103,7 +99,7 @@ void RemoveAllConstraints(Dali::Actor actor) /// Removes constraints from all actors in all windows. void RemoveAllConstraints(const Dali::WindowContainer& windows) { - for( auto& window : windows ) + for(auto& window : windows) { RemoveAllConstraints(window.GetRootLayer()); } @@ -116,30 +112,29 @@ void RemoveAllConstraints(const Dali::WindowContainer& windows) */ struct Framework::Impl { - struct IdleCallback { - int timestamp; - int timeout; - int id; + int timestamp; + int timeout; + int id; void* data; - bool ( *callback )( void *data ); + bool (*callback)(void* data); - IdleCallback( int timeout, int id, void* data, bool ( *callback )( void *data ) ) - : timestamp( GetCurrentMilliSeconds() + timeout ), - timeout( timeout ), - id ( id ), - data( data ), - callback( callback ) + IdleCallback(int timeout, int id, void* data, bool (*callback)(void* data)) + : timestamp(GetCurrentMilliSeconds() + timeout), + timeout(timeout), + id(id), + data(data), + callback(callback) { } bool operator()() { - return callback( data ); + return callback(data); } - bool operator<( const IdleCallback& rhs ) const + bool operator<(const IdleCallback& rhs) const { return timestamp > rhs.timestamp; } @@ -147,24 +142,23 @@ struct Framework::Impl // Constructor - Impl( Framework* framework ) - : mAbortCallBack( nullptr ), - mCallbackManager( CallbackManager::New() ), - mLanguage( "NOT_SUPPORTED" ), - mRegion( "NOT_SUPPORTED" ), - mFinishRequested( false ), - mIdleId( 0 ), - mIdleReadPipe( -1 ), - mIdleWritePipe( -1 ) - + Impl(Framework* framework) + : mAbortCallBack(nullptr), + mCallbackManager(CallbackManager::New()), + mLanguage("NOT_SUPPORTED"), + mRegion("NOT_SUPPORTED"), + mFinishRequested(false), + mIdleId(0), + mIdleReadPipe(-1), + mIdleWritePipe(-1) { - AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( framework ); + AndroidFramework::GetImplementation(AndroidFramework::Get()).SetFramework(framework); } ~Impl() { - AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( nullptr ); + AndroidFramework::GetImplementation(AndroidFramework::Get()).SetFramework(nullptr); delete mAbortCallBack; mAbortCallBack = nullptr; @@ -190,72 +184,72 @@ struct Framework::Impl { // Dequeue the pipe int8_t msg = -1; - read( mIdleReadPipe, &msg, sizeof( msg ) ); + read(mIdleReadPipe, &msg, sizeof(msg)); unsigned int ts = GetCurrentMilliSeconds(); - if ( !mIdleCallbacks.empty() ) + if(!mIdleCallbacks.empty()) { IdleCallback callback = mIdleCallbacks.top(); - if( callback.timestamp <= ts ) + if(callback.timestamp <= ts) { mIdleCallbacks.pop(); // Callback wasn't removed - if( mRemovedIdleCallbacks.find( callback.id ) == mRemovedIdleCallbacks.end() ) + if(mRemovedIdleCallbacks.find(callback.id) == mRemovedIdleCallbacks.end()) { - if ( callback() ) // keep the callback + if(callback()) // keep the callback { - AddIdle( callback.timeout, callback.data, callback.callback, callback.id ); + AddIdle(callback.timeout, callback.data, callback.callback, callback.id); } } // Callback cane be also removed during the callback call - auto i = mRemovedIdleCallbacks.find( callback.id ); - if( i != mRemovedIdleCallbacks.end() ) + auto i = mRemovedIdleCallbacks.find(callback.id); + if(i != mRemovedIdleCallbacks.end()) { - mRemovedIdleCallbacks.erase( i ); + mRemovedIdleCallbacks.erase(i); } } } - if( mIdleCallbacks.empty() ) + if(mIdleCallbacks.empty()) { mRemovedIdleCallbacks.clear(); } } - unsigned int AddIdle( int timeout, void* data, bool ( *callback )( void *data ) , unsigned int existingId = 0 ) + unsigned int AddIdle(int timeout, void* data, bool (*callback)(void* data), unsigned int existingId = 0) { unsigned int chosenId; - if (existingId) + if(existingId) { chosenId = existingId; } else { ++mIdleId; - if( mIdleId == 0 ) + if(mIdleId == 0) { ++mIdleId; } chosenId = mIdleId; } - mIdleCallbacks.push( IdleCallback( timeout, chosenId, data, callback ) ); + mIdleCallbacks.push(IdleCallback(timeout, chosenId, data, callback)); // To wake up the idle pipe and to trigger OnIdle int8_t msg = 1; - write( mIdleWritePipe, &msg, sizeof( msg ) ); + write(mIdleWritePipe, &msg, sizeof(msg)); return chosenId; } - void RemoveIdle( unsigned int id ) + void RemoveIdle(unsigned int id) { - if( id != 0 ) + if(id != 0) { - mRemovedIdleCallbacks.insert( id ); + mRemovedIdleCallbacks.insert(id); } } @@ -263,13 +257,13 @@ struct Framework::Impl { int timeout = -1; - if( !mIdleCallbacks.empty() ) + if(!mIdleCallbacks.empty()) { IdleCallback idleTimeout = mIdleCallbacks.top(); - timeout = idleTimeout.timestamp - GetCurrentMilliSeconds(); - if( timeout < 0 ) + timeout = idleTimeout.timestamp - GetCurrentMilliSeconds(); + if(timeout < 0) { - timeout = 0; + timeout = 0; } } @@ -277,92 +271,92 @@ struct Framework::Impl } // Data - CallbackBase* mAbortCallBack; + CallbackBase* mAbortCallBack; CallbackManager* mCallbackManager; - std::string mLanguage; - std::string mRegion; - bool mFinishRequested; + std::string mLanguage; + std::string mRegion; + bool mFinishRequested; - int mIdleReadPipe; - int mIdleWritePipe; - unsigned int mIdleId; + int mIdleReadPipe; + int mIdleWritePipe; + unsigned int mIdleId; std::priority_queue mIdleCallbacks; - std::unordered_set mRemovedIdleCallbacks; + std::unordered_set mRemovedIdleCallbacks; // Static methods /** * Called by the native activity loop when the application APP_CMD_INIT_WINDOW event is processed. */ - static void NativeWindowCreated( Framework* framework, ANativeWindow* window ) + static void NativeWindowCreated(Framework* framework, ANativeWindow* window) { - if( framework ) + if(framework) { - framework->AppStatusHandler( APP_WINDOW_CREATED, window ); + framework->AppStatusHandler(APP_WINDOW_CREATED, window); } } /** * Called by the native activity loop when the application APP_CMD_DESTROY event is processed. */ - static void NativeWindowDestroyed( Framework* framework, ANativeWindow* window ) + static void NativeWindowDestroyed(Framework* framework, ANativeWindow* window) { - if( framework ) + if(framework) { - framework->AppStatusHandler( APP_WINDOW_DESTROYED, window ); + framework->AppStatusHandler(APP_WINDOW_DESTROYED, window); } } /** * Called by the native activity loop when the application APP_CMD_INIT_WINDOW event is processed. */ - static void NativeAppPaused( Framework* framework ) + static void NativeAppPaused(Framework* framework) { - if( framework ) + if(framework) { - framework->AppStatusHandler( APP_PAUSE, nullptr ); + framework->AppStatusHandler(APP_PAUSE, nullptr); } } /** * Called by the native activity loop when the application APP_CMD_TERM_WINDOW event is processed. */ - static void NativeAppResumed( Framework* framework ) + static void NativeAppResumed(Framework* framework) { - if( framework ) + if(framework) { - framework->AppStatusHandler( APP_RESUME, nullptr ); + framework->AppStatusHandler(APP_RESUME, nullptr); } } /** * Called by the native activity loop when the application input touch event is processed. */ - static void NativeAppTouchEvent( Framework* framework, Dali::TouchPoint& touchPoint, int64_t timeStamp ) + static void NativeAppTouchEvent(Framework* framework, Dali::TouchPoint& touchPoint, int64_t timeStamp) { - Dali::Adaptor::Get().FeedTouchPoint( touchPoint, timeStamp ); + Dali::Adaptor::Get().FeedTouchPoint(touchPoint, timeStamp); } /** * Called by the native activity loop when the application input key event is processed. */ - static void NativeAppKeyEvent( Framework* framework, Dali::KeyEvent& keyEvent ) + static void NativeAppKeyEvent(Framework* framework, Dali::KeyEvent& keyEvent) { - Dali::Adaptor::Get().FeedKeyEvent( keyEvent ); + Dali::Adaptor::Get().FeedKeyEvent(keyEvent); } /** * Called by the native activity loop when the application APP_CMD_DESTROY event is processed. */ - static void NativeAppDestroyed( Framework* framework ) + static void NativeAppDestroyed(Framework* framework) { - if( framework ) + if(framework) { - framework->AppStatusHandler( APP_DESTROYED, nullptr ); + framework->AppStatusHandler(APP_DESTROYED, nullptr); } } -/* + /* Order of events: APP_CMD_START @@ -379,8 +373,8 @@ struct Framework::Impl static void HandleAppCmd(struct android_app* app, int32_t cmd) { - Framework* framework = AndroidFramework::GetImplementation( AndroidFramework::Get() ).GetFramework(); - switch( cmd ) + Framework* framework = AndroidFramework::GetImplementation(AndroidFramework::Get()).GetFramework(); + switch(cmd) { case APP_CMD_SAVE_STATE: break; @@ -394,124 +388,124 @@ struct Framework::Impl break; case APP_CMD_INIT_WINDOW: // The window is being shown, get it ready. - AndroidFramework::Get().SetApplicationWindow( app->window ); - Dali::Internal::Adaptor::Framework::Impl::NativeWindowCreated( framework, app->window ); - Dali::Internal::Adaptor::Framework::Impl::NativeAppResumed( framework ); + AndroidFramework::Get().SetApplicationWindow(app->window); + Dali::Internal::Adaptor::Framework::Impl::NativeWindowCreated(framework, app->window); + Dali::Internal::Adaptor::Framework::Impl::NativeAppResumed(framework); break; case APP_CMD_TERM_WINDOW: // The window is being hidden or closed, clean it up. - AndroidFramework::Get().SetApplicationWindow( nullptr ); - Dali::Internal::Adaptor::Framework::Impl::NativeAppPaused( framework ); - Dali::Internal::Adaptor::Framework::Impl::NativeWindowDestroyed( framework, app->window ); + AndroidFramework::Get().SetApplicationWindow(nullptr); + Dali::Internal::Adaptor::Framework::Impl::NativeAppPaused(framework); + Dali::Internal::Adaptor::Framework::Impl::NativeWindowDestroyed(framework, app->window); break; case APP_CMD_GAINED_FOCUS: break; case APP_CMD_LOST_FOCUS: break; case APP_CMD_DESTROY: - Dali::Internal::Adaptor::Framework::Impl::NativeAppPaused( framework ); - Dali::Internal::Adaptor::Framework::Impl::NativeAppDestroyed( framework ); + Dali::Internal::Adaptor::Framework::Impl::NativeAppPaused(framework); + Dali::Internal::Adaptor::Framework::Impl::NativeAppDestroyed(framework); break; } } static int32_t HandleAppInput(struct android_app* app, AInputEvent* event) { - Framework* framework = AndroidFramework::GetImplementation( AndroidFramework::Get() ).GetFramework(); + Framework* framework = AndroidFramework::GetImplementation(AndroidFramework::Get()).GetFramework(); - if( AInputEvent_getType( event ) == AINPUT_EVENT_TYPE_MOTION ) + if(AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { - int32_t deviceId = AInputEvent_getDeviceId( event ); - float x = AMotionEvent_getX( event, 0 ); - float y = AMotionEvent_getY( event, 0 ); - Dali::PointState::Type state = Dali::PointState::DOWN; - int32_t action = AMotionEvent_getAction( event ); - int64_t timeStamp = AMotionEvent_getEventTime( event ); + int32_t deviceId = AInputEvent_getDeviceId(event); + float x = AMotionEvent_getX(event, 0); + float y = AMotionEvent_getY(event, 0); + Dali::PointState::Type state = Dali::PointState::DOWN; + int32_t action = AMotionEvent_getAction(event); + int64_t timeStamp = AMotionEvent_getEventTime(event); - switch ( action & AMOTION_EVENT_ACTION_MASK ) + switch(action & AMOTION_EVENT_ACTION_MASK) { - case AMOTION_EVENT_ACTION_DOWN: - break; - case AMOTION_EVENT_ACTION_UP: - state = Dali::PointState::UP; - break; - case AMOTION_EVENT_ACTION_MOVE: - state = Dali::PointState::MOTION; - break; - case AMOTION_EVENT_ACTION_CANCEL: - state = Dali::PointState::INTERRUPTED; - break; - case AMOTION_EVENT_ACTION_OUTSIDE: - state = Dali::PointState::LEAVE; - break; + case AMOTION_EVENT_ACTION_DOWN: + break; + case AMOTION_EVENT_ACTION_UP: + state = Dali::PointState::UP; + break; + case AMOTION_EVENT_ACTION_MOVE: + state = Dali::PointState::MOTION; + break; + case AMOTION_EVENT_ACTION_CANCEL: + state = Dali::PointState::INTERRUPTED; + break; + case AMOTION_EVENT_ACTION_OUTSIDE: + state = Dali::PointState::LEAVE; + break; } - Dali::TouchPoint point( deviceId, state, x, y ); - Dali::Internal::Adaptor::Framework::Impl::NativeAppTouchEvent( framework, point, timeStamp ); + Dali::TouchPoint point(deviceId, state, x, y); + Dali::Internal::Adaptor::Framework::Impl::NativeAppTouchEvent(framework, point, timeStamp); return 1; } - else if ( AInputEvent_getType( event ) == AINPUT_EVENT_TYPE_KEY ) + else if(AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) { - int32_t deviceId = AInputEvent_getDeviceId( event ); - int32_t keyCode = AKeyEvent_getKeyCode( event ); - int32_t action = AKeyEvent_getAction( event ); - int64_t timeStamp = AKeyEvent_getEventTime( event ); + int32_t deviceId = AInputEvent_getDeviceId(event); + int32_t keyCode = AKeyEvent_getKeyCode(event); + int32_t action = AKeyEvent_getAction(event); + int64_t timeStamp = AKeyEvent_getEventTime(event); Dali::KeyEvent::State state = Dali::KeyEvent::DOWN; - switch ( action ) + switch(action) { - case AKEY_EVENT_ACTION_DOWN: - break; - case AKEY_EVENT_ACTION_UP: - state = Dali::KeyEvent::UP; - break; + case AKEY_EVENT_ACTION_DOWN: + break; + case AKEY_EVENT_ACTION_UP: + state = Dali::KeyEvent::UP; + break; } std::string keyName = ""; - switch( keyCode ) + switch(keyCode) { - case 4: - keyName = "XF86Back"; - break; - default: - break; + case 4: + keyName = "XF86Back"; + break; + default: + break; } - Dali::KeyEvent keyEvent = Dali::DevelKeyEvent::New( keyName, "", "", keyCode, 0, timeStamp, state, "", "", Device::Class::NONE, Device::Subclass::NONE ); - Dali::Internal::Adaptor::Framework::Impl::NativeAppKeyEvent( framework, keyEvent ); + Dali::KeyEvent keyEvent = Dali::DevelKeyEvent::New(keyName, "", "", keyCode, 0, timeStamp, state, "", "", Device::Class::NONE, Device::Subclass::NONE); + Dali::Internal::Adaptor::Framework::Impl::NativeAppKeyEvent(framework, keyEvent); return 1; } return 0; } - static void HandleAppIdle(struct android_app* app, struct android_poll_source* source) { - Framework* framework = AndroidFramework::GetImplementation( AndroidFramework::Get() ).GetFramework(); - if( framework && framework->mImpl ) + static void HandleAppIdle(struct android_app* app, struct android_poll_source* source) + { + Framework* framework = AndroidFramework::GetImplementation(AndroidFramework::Get()).GetFramework(); + if(framework && framework->mImpl) { framework->mImpl->OnIdle(); } } - }; -Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type ) -: mObserver( observer ), - mInitialised( false ), +Framework::Framework(Framework::Observer& observer, int* argc, char*** argv, Type type) +: mObserver(observer), + mInitialised(false), mPaused(false), - mRunning( false ), - mArgc( argc ), - mArgv( argv ), - mBundleName( "" ), - mBundleId( "" ), - mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ), - mImpl( NULL ) + mRunning(false), + mArgc(argc), + mArgv(argv), + mBundleName(""), + mBundleId(""), + mAbortHandler(MakeCallback(this, &Framework::AbortCallback)), + mImpl(NULL) { - mImpl = new Impl( this ); + mImpl = new Impl(this); } Framework::~Framework() { - if( mRunning ) + if(mRunning) { Quit(); } @@ -523,26 +517,30 @@ Framework::~Framework() void Framework::Run() { struct android_app* app = AndroidFramework::Get().GetNativeApplication(); - app->onAppCmd = Framework::Impl::HandleAppCmd; - app->onInputEvent = Framework::Impl::HandleAppInput; + app->onAppCmd = Framework::Impl::HandleAppCmd; + app->onInputEvent = Framework::Impl::HandleAppInput; struct android_poll_source* source; - struct android_poll_source idlePollSource; - idlePollSource.id = LOOPER_ID_USER; - idlePollSource.app = app; + struct android_poll_source idlePollSource; + idlePollSource.id = LOOPER_ID_USER; + idlePollSource.app = app; idlePollSource.process = Impl::HandleAppIdle; int idlePipe[2]; - if( pipe( idlePipe ) ) + if(pipe(idlePipe)) { - DALI_LOG_ERROR( "Failed to open idle pipe\n" ); + DALI_LOG_ERROR("Failed to open idle pipe\n"); return; } - mImpl->mIdleReadPipe = idlePipe[0]; + mImpl->mIdleReadPipe = idlePipe[0]; mImpl->mIdleWritePipe = idlePipe[1]; - ALooper_addFd( app->looper, - idlePipe[0], LOOPER_ID_USER, ALOOPER_EVENT_INPUT, NULL, &idlePollSource ); + ALooper_addFd(app->looper, + idlePipe[0], + LOOPER_ID_USER, + ALOOPER_EVENT_INPUT, + NULL, + &idlePollSource); mRunning = true; @@ -550,44 +548,44 @@ void Framework::Run() int events; int idleTimeout = -1; - while( true ) + while(true) { - if ( mImpl ) + if(mImpl) { idleTimeout = mImpl->GetIdleTimeout(); } - int id = ALooper_pollAll( idleTimeout, NULL, &events, (void**)&source ); + int id = ALooper_pollAll(idleTimeout, NULL, &events, (void**)&source); // Process the error. - if( id == ALOOPER_POLL_ERROR ) + if(id == ALOOPER_POLL_ERROR) { - DALI_LOG_ERROR( "ALooper error\n" ); - Quit(); - std::abort(); + DALI_LOG_ERROR("ALooper error\n"); + Quit(); + std::abort(); } // Process the timeout, trigger OnIdle. - if( id == ALOOPER_POLL_TIMEOUT ) + if(id == ALOOPER_POLL_TIMEOUT) { int8_t msg = 1; - write( mImpl->mIdleWritePipe, &msg, sizeof( msg ) ); + write(mImpl->mIdleWritePipe, &msg, sizeof(msg)); } // Process the application event. - if( id >= 0 && source != NULL ) + if(id >= 0 && source != NULL) { - source->process( app, source ); + source->process(app, source); } // Check if we are exiting. - if( app->destroyRequested ) + if(app->destroyRequested) { break; } } - while (!mImpl->mIdleCallbacks.empty()) + while(!mImpl->mIdleCallbacks.empty()) { mImpl->mIdleCallbacks.pop(); } @@ -595,42 +593,42 @@ void Framework::Run() mImpl->mRemovedIdleCallbacks.clear(); mImpl->mIdleId = 0; - ALooper_removeFd( app->looper, idlePipe[0] ); - if ( mImpl ) + ALooper_removeFd(app->looper, idlePipe[0]); + if(mImpl) { - mImpl->mIdleReadPipe = -1; + mImpl->mIdleReadPipe = -1; mImpl->mIdleWritePipe = -1; } - close( idlePipe[0] ); - close( idlePipe[1] ); + close(idlePipe[0]); + close(idlePipe[1]); mRunning = false; } -unsigned int Framework::AddIdle( int timeout, void* data, bool ( *callback )( void *data ) ) +unsigned int Framework::AddIdle(int timeout, void* data, bool (*callback)(void* data)) { - if( mImpl ) + if(mImpl) { - return mImpl->AddIdle( timeout, data, callback ); + return mImpl->AddIdle(timeout, data, callback); } return -1; } -void Framework::RemoveIdle( unsigned int id ) +void Framework::RemoveIdle(unsigned int id) { - if( mImpl ) + if(mImpl) { - mImpl->RemoveIdle( id ); + mImpl->RemoveIdle(id); } } void Framework::Quit() { struct android_app* app = AndroidFramework::Get().GetNativeApplication(); - if( app && !app->destroyRequested && !mImpl->mFinishRequested ) + if(app && !app->destroyRequested && !mImpl->mFinishRequested) { mImpl->mFinishRequested = true; - ANativeActivity_finish( app->activity ); + ANativeActivity_finish(app->activity); } } @@ -639,7 +637,7 @@ bool Framework::IsMainLoopRunning() return mRunning; } -void Framework::AddAbortCallback( CallbackBase* callback ) +void Framework::AddAbortCallback(CallbackBase* callback) { mImpl->mAbortCallBack = callback; } @@ -674,12 +672,12 @@ void Framework::SetBundleId(const std::string& id) mBundleId = id; } -void Framework::AbortCallback( ) +void Framework::AbortCallback() { // if an abort call back has been installed run it. - if( mImpl->mAbortCallBack ) + if(mImpl->mAbortCallBack) { - CallbackBase::Execute( *mImpl->mAbortCallBack ); + CallbackBase::Execute(*mImpl->mAbortCallBack); } else { @@ -690,17 +688,17 @@ void Framework::AbortCallback( ) bool Framework::AppStatusHandler(int type, void* data) { Dali::Adaptor* adaptor = nullptr; - switch (type) + switch(type) { case APP_WINDOW_CREATED: { - if( !mInitialised ) + if(!mInitialised) { mObserver.OnInit(); mInitialised = true; } - mObserver.OnSurfaceCreated( data ); + mObserver.OnSurfaceCreated(data); break; } @@ -720,7 +718,7 @@ bool Framework::AppStatusHandler(int type, void* data) case APP_WINDOW_DESTROYED: { - mObserver.OnSurfaceDestroyed( data ); + mObserver.OnSurfaceDestroyed(data); break; } diff --git a/dali/internal/adaptor/androidjni/framework-androidjni.cpp b/dali/internal/adaptor/androidjni/framework-androidjni.cpp index c411174..6fc0f63 100644 --- a/dali/internal/adaptor/androidjni/framework-androidjni.cpp +++ b/dali/internal/adaptor/androidjni/framework-androidjni.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,28 +19,25 @@ #include // EXTERNAL INCLUDES -#include +#include #include #include +#include #include -#include // INTERNAL INCLUDES -#include #include +#include #include using namespace Dali; namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Impl to hide android data members */ @@ -48,18 +45,18 @@ struct Framework::Impl { // Constructor - Impl( Framework* framework ) - : mAbortCallBack( nullptr ), - mCallbackManager( CallbackManager::New() ), - mLanguage( "NOT_SUPPORTED" ), - mRegion( "NOT_SUPPORTED" ) + Impl(Framework* framework) + : mAbortCallBack(nullptr), + mCallbackManager(CallbackManager::New()), + mLanguage("NOT_SUPPORTED"), + mRegion("NOT_SUPPORTED") { - AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( framework ); + AndroidFramework::GetImplementation(AndroidFramework::Get()).SetFramework(framework); } ~Impl() { - AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( nullptr ); + AndroidFramework::GetImplementation(AndroidFramework::Get()).SetFramework(nullptr); delete mAbortCallBack; mAbortCallBack = nullptr; @@ -81,30 +78,30 @@ struct Framework::Impl return mRegion; } - CallbackBase* mAbortCallBack; + CallbackBase* mAbortCallBack; CallbackManager* mCallbackManager; - std::string mLanguage; - std::string mRegion; + std::string mLanguage; + std::string mRegion; }; -Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type ) -: mObserver( observer ), - mInitialised( false ), - mPaused( false ), - mRunning( false ), - mArgc( argc ), - mArgv( argv ), - mBundleName( "" ), - mBundleId( "" ), - mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ), - mImpl( NULL ) +Framework::Framework(Framework::Observer& observer, int* argc, char*** argv, Type type) +: mObserver(observer), + mInitialised(false), + mPaused(false), + mRunning(false), + mArgc(argc), + mArgv(argv), + mBundleName(""), + mBundleId(""), + mAbortHandler(MakeCallback(this, &Framework::AbortCallback)), + mImpl(NULL) { - mImpl = new Impl( this ); + mImpl = new Impl(this); } Framework::~Framework() { - if( mRunning ) + if(mRunning) { Quit(); } @@ -115,63 +112,63 @@ Framework::~Framework() void Framework::Run() { - AndroidFramework::GetImplementation( AndroidFramework::Get() ).SetFramework( this ); + AndroidFramework::GetImplementation(AndroidFramework::Get()).SetFramework(this); mRunning = true; } -unsigned int Framework::AddIdle( int timeout, void* data, bool ( *callback )( void *data ) ) +unsigned int Framework::AddIdle(int timeout, void* data, bool (*callback)(void* data)) { - JNIEnv *env = nullptr; + JNIEnv* env = nullptr; JavaVM* javaVM = AndroidFramework::Get().GetJVM(); - if( javaVM == nullptr || javaVM->GetEnv( reinterpret_cast( &env ), JNI_VERSION_1_6 ) != JNI_OK ) + if(javaVM == nullptr || javaVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { DALI_LOG_ERROR("Couldn't get JNI env."); return -1; } - jclass clazz = env->FindClass( "com/sec/daliview/DaliView" ); - if ( !clazz ) + jclass clazz = env->FindClass("com/sec/daliview/DaliView"); + if(!clazz) { DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView."); return -1; } - jmethodID addIdle = env->GetStaticMethodID( clazz, "addIdle", "(JJJ)I" ); - if (!addIdle) + jmethodID addIdle = env->GetStaticMethodID(clazz, "addIdle", "(JJJ)I"); + if(!addIdle) { DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.addIdle."); return -1; } - jint id = env->CallStaticIntMethod( clazz, addIdle, reinterpret_cast( callback ), reinterpret_cast( data ), static_cast( timeout ) ); - return static_cast( id ); + jint id = env->CallStaticIntMethod(clazz, addIdle, reinterpret_cast(callback), reinterpret_cast(data), static_cast(timeout)); + return static_cast(id); } -void Framework::RemoveIdle( unsigned int id ) +void Framework::RemoveIdle(unsigned int id) { - JNIEnv *env = nullptr; + JNIEnv* env = nullptr; JavaVM* javaVM = AndroidFramework::Get().GetJVM(); - if( javaVM == nullptr || javaVM->GetEnv( reinterpret_cast( &env ), JNI_VERSION_1_6 ) != JNI_OK ) + if(javaVM == nullptr || javaVM->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { DALI_LOG_ERROR("Couldn't get JNI env."); return; } - jclass clazz = env->FindClass( "com/sec/daliview/DaliView" ); - if( !clazz ) + jclass clazz = env->FindClass("com/sec/daliview/DaliView"); + if(!clazz) { DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView."); return; } - jmethodID removeIdle = env->GetStaticMethodID( clazz, "removeIdle", "(I)V" ); - if( !removeIdle ) + jmethodID removeIdle = env->GetStaticMethodID(clazz, "removeIdle", "(I)V"); + if(!removeIdle) { DALI_LOG_ERROR("Couldn't find com.sec.daliview.DaliView.removeIdle."); return; } - env->CallStaticVoidMethod( clazz, removeIdle, static_cast( id ) ); + env->CallStaticVoidMethod(clazz, removeIdle, static_cast(id)); } void Framework::Quit() @@ -184,7 +181,7 @@ bool Framework::IsMainLoopRunning() return mRunning; } -void Framework::AddAbortCallback( CallbackBase* callback ) +void Framework::AddAbortCallback(CallbackBase* callback) { mImpl->mAbortCallBack = callback; } @@ -219,12 +216,12 @@ void Framework::SetBundleId(const std::string& id) mBundleId = id; } -void Framework::AbortCallback( ) +void Framework::AbortCallback() { // if an abort call back has been installed run it. - if (mImpl->mAbortCallBack) + if(mImpl->mAbortCallBack) { - CallbackBase::Execute( *mImpl->mAbortCallBack ); + CallbackBase::Execute(*mImpl->mAbortCallBack); } else { @@ -235,20 +232,20 @@ void Framework::AbortCallback( ) bool Framework::AppStatusHandler(int type, void* data) { Dali::Adaptor* adaptor = nullptr; - switch (type) + switch(type) { case APP_WINDOW_CREATED: - if( !mInitialised ) + if(!mInitialised) { mObserver.OnInit(); mInitialised = true; } - mObserver.OnSurfaceCreated( data ); + mObserver.OnSurfaceCreated(data); break; case APP_WINDOW_DESTROYED: - mObserver.OnSurfaceDestroyed( data ); + mObserver.OnSurfaceDestroyed(data); break; case APP_RESET: @@ -273,8 +270,8 @@ bool Framework::AppStatusHandler(int type, void* data) case APP_DESTROYED: mObserver.OnTerminate(); - mRunning = false; - mPaused = false; + mRunning = false; + mPaused = false; mInitialised = false; break; diff --git a/dali/internal/adaptor/common/adaptor-impl.h b/dali/internal/adaptor/common/adaptor-impl.h index 5590aa0..7992342 100644 --- a/dali/internal/adaptor/common/adaptor-impl.h +++ b/dali/internal/adaptor/common/adaptor-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,19 +19,18 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include #include -#include +#include // INTERNAL INCLUDES -#include #include -#include #include #include #include +#include #include #include #include @@ -42,12 +41,12 @@ #include #include #include +#include #include namespace Dali { - class RenderSurfaceInterface; namespace Accessibility @@ -61,11 +60,10 @@ class Core; class GlAbstraction; class Processor; class AddOnManager; -} +} // namespace Integration namespace Internal { - namespace Adaptor { class DisplayConnection; @@ -95,11 +93,10 @@ class Adaptor : public Integration::RenderController, public WindowVisibilityObserver { public: - - using AdaptorSignalType = Dali::Adaptor::AdaptorSignalType; + using AdaptorSignalType = Dali::Adaptor::AdaptorSignalType; using WindowCreatedSignalType = Dali::Adaptor::WindowCreatedSignalType; - using SurfaceSize = Uint16Pair; ///< Surface size type + using SurfaceSize = Uint16Pair; ///< Surface size type /** * Creates a New Adaptor @@ -110,18 +107,18 @@ public: * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created. * @param[in] threadMode The thread mode */ - static Dali::Adaptor* New( Dali::Integration::SceneHolder window, - Dali::RenderSurfaceInterface* surface, - EnvironmentOptions* environmentOptions, - ThreadMode threadMode ); + static Dali::Adaptor* New(Dali::Integration::SceneHolder window, + Dali::RenderSurfaceInterface* surface, + EnvironmentOptions* environmentOptions, + ThreadMode threadMode); /** * Creates a New Adaptor * @param[in] window The window handle * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created. */ - static Dali::Adaptor* New( Dali::Integration::SceneHolder window, - EnvironmentOptions* environmentOptions ); + static Dali::Adaptor* New(Dali::Integration::SceneHolder window, + EnvironmentOptions* environmentOptions); /** * Creates a New Adaptor @@ -133,11 +130,11 @@ public: * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created. * @param[in] threadMode The thread mode */ - static Dali::Adaptor* New( GraphicsFactory& graphicsFactory, - Dali::Integration::SceneHolder window, - Dali::RenderSurfaceInterface* surface, - EnvironmentOptions* environmentOptions, - ThreadMode threadMode ); + static Dali::Adaptor* New(GraphicsFactory& graphicsFactory, + Dali::Integration::SceneHolder window, + Dali::RenderSurfaceInterface* surface, + EnvironmentOptions* environmentOptions, + ThreadMode threadMode); /** * Creates a New Adaptor @@ -145,15 +142,15 @@ public: * @param[in] window The window handle * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created. */ - static Dali::Adaptor* New( GraphicsFactory& graphicsFactory, - Dali::Integration::SceneHolder window, - EnvironmentOptions* environmentOptions ); + static Dali::Adaptor* New(GraphicsFactory& graphicsFactory, + Dali::Integration::SceneHolder window, + EnvironmentOptions* environmentOptions); /** * 2-step initialisation, this should be called after creating an adaptor instance. * @param[in] graphicsFactory A factory that creates the graphics interface */ - void Initialize( GraphicsFactory& graphicsFactory ); + void Initialize(GraphicsFactory& graphicsFactory); /** * Virtual destructor. @@ -211,22 +208,22 @@ public: // AdaptorInternalServices implementation /** * @copydoc Dali::EventFeeder::FeedTouchPoint() */ - virtual void FeedTouchPoint( TouchPoint& point, int timeStamp ); + virtual void FeedTouchPoint(TouchPoint& point, int timeStamp); /** * @copydoc Dali::EventFeeder::FeedWheelEvent() */ - virtual void FeedWheelEvent( Dali::WheelEvent& wheelEvent ); + virtual void FeedWheelEvent(Dali::WheelEvent& wheelEvent); /** * @copydoc Dali::EventFeeder::FeedKeyEvent() */ - virtual void FeedKeyEvent( Dali::KeyEvent& keyEvent ); + virtual void FeedKeyEvent(Dali::KeyEvent& keyEvent); /** * @copydoc Dali::Adaptor::ReplaceSurface() */ - virtual void ReplaceSurface( Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& surface ); + virtual void ReplaceSurface(Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& surface); /** * @copydoc Dali::Adaptor::GetSurface() @@ -248,31 +245,31 @@ public: // AdaptorInternalServices implementation /** * @copydoc Dali::Adaptor::AddIdle() */ - virtual bool AddIdle( CallbackBase* callback, bool hasReturnValue, bool forceAdd ); + virtual bool AddIdle(CallbackBase* callback, bool hasReturnValue, bool forceAdd); /** * Adds a new Window instance to the Adaptor * @param[in] childWindow The child window instance */ - virtual bool AddWindow( Dali::Integration::SceneHolder childWindow ); + virtual bool AddWindow(Dali::Integration::SceneHolder childWindow); /** * Removes an existing Window instance from the Adaptor * @param[in] window The Window instance */ - virtual bool RemoveWindow( Dali::Integration::SceneHolder* childWindow ); + virtual bool RemoveWindow(Dali::Integration::SceneHolder* childWindow); /** * Removes an existing Window instance from the Adaptor * @param[in] windowName The Window name * @note If two Windows have the same name, the first one that matches will be removed */ - virtual bool RemoveWindow( std::string childWindowName ); + virtual bool RemoveWindow(std::string childWindowName); /** * @copydoc Dali::Adaptor::RemoveIdle() */ - virtual void RemoveIdle( CallbackBase* callback ); + virtual void RemoveIdle(CallbackBase* callback); /** * @copydoc Dali::Adaptor::ProcessIdle() @@ -282,19 +279,19 @@ public: // AdaptorInternalServices implementation /** * Sets a pre-render callback. */ - void SetPreRenderCallback( CallbackBase* callback ); + void SetPreRenderCallback(CallbackBase* callback); /** * Removes an existing Window instance from the Adaptor * @param[in] childWindow The Window instance */ - bool RemoveWindow( Dali::Internal::Adaptor::SceneHolder* childWindow ); + bool RemoveWindow(Dali::Internal::Adaptor::SceneHolder* childWindow); /** * @brief Deletes the rendering surface * @param[in] surface to delete */ - void DeleteSurface( Dali::RenderSurfaceInterface& surface ); + void DeleteSurface(Dali::RenderSurfaceInterface& surface); /** * @brief Retrieve the window that the given actor is added to. @@ -302,7 +299,7 @@ public: // AdaptorInternalServices implementation * @param[in] actor The actor * @return The window the actor is added to or a null pointer if the actor is not added to any widnow. */ - Dali::Internal::Adaptor::SceneHolder* GetWindow( Dali::Actor& actor ); + Dali::Internal::Adaptor::SceneHolder* GetWindow(Dali::Actor& actor); /** * @copydoc Dali::Adaptor::GetWindows() @@ -320,7 +317,6 @@ public: // AdaptorInternalServices implementation Dali::ObjectRegistry GetObjectRegistry() const; public: - /** * @return the Core instance */ @@ -329,7 +325,7 @@ public: /** * @copydoc Dali::Adaptor::SetRenderRefreshRate() */ - void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender ); + void SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender); /** * Return the PlatformAbstraction. @@ -356,7 +352,7 @@ public: * @param[in] actor The actor * @return native window handle */ - Any GetNativeWindowHandle( Dali::Actor actor ); + Any GetNativeWindowHandle(Dali::Actor actor); /** * Get the native display associated with the graphics backend @@ -372,20 +368,19 @@ public: void SetUseRemoteSurface(bool useRemoteSurface); public: - /** * Adds an adaptor observer so that we can observe the adaptor's lifetime events. * @param[in] observer The observer. * @note Observers should remove themselves when they are destroyed. */ - void AddObserver( LifeCycleObserver& observer ); + void AddObserver(LifeCycleObserver& observer); /** * Removes the observer from the adaptor. * @param[in] observer The observer to remove. * @note Observers should remove themselves when they are destroyed. */ - void RemoveObserver( LifeCycleObserver& observer ); + void RemoveObserver(LifeCycleObserver& observer); /** * Emits the Notification event to the Dali core. @@ -410,29 +405,29 @@ public: /** * Gets AppId of current application */ - void GetAppId( std::string& appId ); + void GetAppId(std::string& appId); /** * Gets path for resource storage. * @param[out] path Path for resource storage */ - void GetResourceStoragePath( std::string& path ); + void GetResourceStoragePath(std::string& path); /** * @copydoc Dali::Adaptor::SurfaceResizePrepare */ - void SurfaceResizePrepare( Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize ); + void SurfaceResizePrepare(Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize); /** * @copydoc Dali::Adaptor::SurfaceResizeComplete */ - void SurfaceResizeComplete( Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize ); + void SurfaceResizeComplete(Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize); /** * Sets layout direction of root by system language * @param[in] locale System locale */ - void SetRootLayoutDirection( std::string locale ); + void SetRootLayoutDirection(std::string locale); /** * @copydoc Dali::Adaptor::RenderOnce @@ -447,20 +442,19 @@ public: /** * @copydoc Dali::Adaptor::RegisterProcessor */ - void RegisterProcessor( Integration::Processor& processor ); + void RegisterProcessor(Integration::Processor& processor); /** * @coydoc Dali::Adaptor::UnregisterProcessor */ - void UnregisterProcessor( Integration::Processor& processor ); + void UnregisterProcessor(Integration::Processor& processor); /** * Check MultipleWindow is supported */ bool IsMultipleWindowSupported() const; -public: //AdaptorInternalServices - +public: //AdaptorInternalServices /** * @copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetPlatformAbstractionInterface() */ @@ -509,10 +503,9 @@ public: //AdaptorInternalServices /** * copydoc Dali::Internal::Adaptor::AdaptorInternalServices::GetWindowContainerInterface() */ - void GetWindowContainerInterface( WindowContainer& windows ) override; + void GetWindowContainerInterface(WindowContainer& windows) override; public: // Signals - /** * @copydoc Dali::Adaptor::SignalResized */ @@ -538,33 +531,29 @@ public: // Signals } public: // From Dali::Internal::Adaptor::CoreEventInterface - /** * @copydoc Dali::Internal::Adaptor:CoreEventInterface:::ProcessCoreEvents() */ void ProcessCoreEvents() override; private: // From Dali::Internal::Adaptor::CoreEventInterface - /** * @copydoc Dali::Internal::Adaptor::CoreEventInterface::QueueCoreEvent() */ void QueueCoreEvent(const Dali::Integration::Event& event) override; private: // From Dali::Integration::RenderController - /** * @copydoc Dali::Integration::RenderController::RequestUpdate() */ - void RequestUpdate( bool forceUpdate ) override; + void RequestUpdate(bool forceUpdate) override; /** * @copydoc Dali::Integration::RenderController::RequestProcessEventsOnIdle() */ - void RequestProcessEventsOnIdle( bool forceProcess ) override; + void RequestProcessEventsOnIdle(bool forceProcess) override; public: // From Dali::Internal::Adaptor::WindowVisibilityObserver - /** * Called when the window becomes fully or partially visible. */ @@ -576,25 +565,22 @@ public: // From Dali::Internal::Adaptor::WindowVisibilityObserver void OnWindowHidden() override; private: // From Dali::Internal::Adaptor::DamageObserver - /** * @copydoc Dali::Internal::Adaptor::DamageObserver::OnDamaged() */ - void OnDamaged( const DamageArea& area ) override; + void OnDamaged(const DamageArea& area) override; private: - // Undefined Adaptor(const Adaptor&) = delete; Adaptor& operator=(Adaptor&) = delete; private: - /** * Assigns the render surface to the adaptor * */ - void SetSurface(Dali::RenderSurfaceInterface *surface); + void SetSurface(Dali::RenderSurfaceInterface* surface); /** * called after surface is created @@ -626,15 +612,14 @@ private: * @endcode * This callback will be called repeatedly as long as it returns true. A return of 0 deletes this callback. */ - bool AddIdleEnterer( CallbackBase* callback, bool forceAdd ); + bool AddIdleEnterer(CallbackBase* callback, bool forceAdd); /** * Removes a previously added the idle enterer callback. */ - void RemoveIdleEnterer( CallbackBase* callback ); + void RemoveIdleEnterer(CallbackBase* callback); private: - /** * Constructor * @param[in] window window handle @@ -645,10 +630,9 @@ private: * @param[in] environmentOptions A pointer to the environment options. If NULL then one is created. * @param[in] threadMode The ThreadMode of the Adaptor */ - Adaptor( Dali::Integration::SceneHolder window, Dali::Adaptor& adaptor, Dali::RenderSurfaceInterface* surface, EnvironmentOptions* environmentOptions, ThreadMode threadMode ); + Adaptor(Dali::Integration::SceneHolder window, Dali::Adaptor& adaptor, Dali::RenderSurfaceInterface* surface, EnvironmentOptions* environmentOptions, ThreadMode threadMode); private: // Types - enum State { READY, ///< Initial state before Adaptor::Start is called. @@ -661,63 +645,65 @@ private: // Types // There is no weak handle for BaseHandle in DALi, but we can't ref count the window here, // so we have to store the raw pointer. - using WindowContainer = std::vector; + using WindowContainer = std::vector; using ObserverContainer = std::vector; -private: // Data - - AdaptorSignalType mResizedSignal; ///< Resized signal. - AdaptorSignalType mLanguageChangedSignal; ///< Language changed signal. - WindowCreatedSignalType mWindowCreatedSignal; ///< Window created signal. - - Dali::Adaptor& mAdaptor; ///< Reference to public adaptor instance. - State mState; ///< Current state of the adaptor - Dali::Integration::Core* mCore; ///< Dali Core - ThreadController* mThreadController; ///< Controls the threads - - std::unique_ptr< GraphicsInterface > mGraphics; ///< Graphics interface - Dali::DisplayConnection* mDisplayConnection; ///< Display connection - WindowContainer mWindows; ///< A container of all the Windows that are currently created - - std::unique_ptr mConfigurationManager; ///< Configuration manager - - TizenPlatform::TizenPlatformAbstraction* mPlatformAbstraction; ///< Platform abstraction - - CallbackManager* mCallbackManager; ///< Used to install callbacks - bool mNotificationOnIdleInstalled; ///< whether the idle handler is installed to send an notification event - TriggerEventInterface* mNotificationTrigger; ///< Notification event trigger - FeedbackPluginProxy* mDaliFeedbackPlugin; ///< Used to access feedback support - FeedbackController* mFeedbackController; ///< Plays feedback effects for Dali-Toolkit UI Controls. - Dali::TtsPlayer mTtsPlayers[Dali::TtsPlayer::MODE_NUM]; ///< Provides TTS support - ObserverContainer mObservers; ///< A list of adaptor observer pointers - EnvironmentOptions* mEnvironmentOptions; ///< environment options - PerformanceInterface* mPerformanceInterface; ///< Performance interface - KernelTrace mKernelTracer; ///< Kernel tracer - SystemTrace mSystemTracer; ///< System tracer - ObjectProfiler* mObjectProfiler; ///< Tracks object lifetime for profiling - SocketFactory mSocketFactory; ///< Socket factory - ThreadMode mThreadMode; ///< The thread mode - const bool mEnvironmentOptionsOwned:1; ///< Whether we own the EnvironmentOptions (and thus, need to delete it) - bool mUseRemoteSurface:1; ///< whether the remoteSurface is used or not - Dali::LayoutDirection::Type mRootLayoutDirection; ///< LayoutDirection of window - - std::unique_ptr mAddOnManager; ///< Pointer to the addon manager +private: // Data + AdaptorSignalType mResizedSignal; ///< Resized signal. + AdaptorSignalType mLanguageChangedSignal; ///< Language changed signal. + WindowCreatedSignalType mWindowCreatedSignal; ///< Window created signal. + + Dali::Adaptor& mAdaptor; ///< Reference to public adaptor instance. + State mState; ///< Current state of the adaptor + Dali::Integration::Core* mCore; ///< Dali Core + ThreadController* mThreadController; ///< Controls the threads + + std::unique_ptr mGraphics; ///< Graphics interface + Dali::DisplayConnection* mDisplayConnection; ///< Display connection + WindowContainer mWindows; ///< A container of all the Windows that are currently created + + std::unique_ptr mConfigurationManager; ///< Configuration manager + + TizenPlatform::TizenPlatformAbstraction* mPlatformAbstraction; ///< Platform abstraction + + CallbackManager* mCallbackManager; ///< Used to install callbacks + bool mNotificationOnIdleInstalled; ///< whether the idle handler is installed to send an notification event + TriggerEventInterface* mNotificationTrigger; ///< Notification event trigger + FeedbackPluginProxy* mDaliFeedbackPlugin; ///< Used to access feedback support + FeedbackController* mFeedbackController; ///< Plays feedback effects for Dali-Toolkit UI Controls. + Dali::TtsPlayer mTtsPlayers[Dali::TtsPlayer::MODE_NUM]; ///< Provides TTS support + ObserverContainer mObservers; ///< A list of adaptor observer pointers + EnvironmentOptions* mEnvironmentOptions; ///< environment options + PerformanceInterface* mPerformanceInterface; ///< Performance interface + KernelTrace mKernelTracer; ///< Kernel tracer + SystemTrace mSystemTracer; ///< System tracer + ObjectProfiler* mObjectProfiler; ///< Tracks object lifetime for profiling + SocketFactory mSocketFactory; ///< Socket factory + ThreadMode mThreadMode; ///< The thread mode + const bool mEnvironmentOptionsOwned : 1; ///< Whether we own the EnvironmentOptions (and thus, need to delete it) + bool mUseRemoteSurface : 1; ///< whether the remoteSurface is used or not + Dali::LayoutDirection::Type mRootLayoutDirection; ///< LayoutDirection of window + + std::unique_ptr mAddOnManager; ///< Pointer to the addon manager class AccessibilityObserver : public ConnectionTracker { public: - void OnAccessibleKeyEvent( const Dali::KeyEvent& event ); + void OnAccessibleKeyEvent(const Dali::KeyEvent& event); }; AccessibilityObserver accessibilityObserver; public: - inline static Adaptor& GetImplementation(Dali::Adaptor& adaptor) { return *adaptor.mImpl; } + inline static Adaptor& GetImplementation(Dali::Adaptor& adaptor) + { + return *adaptor.mImpl; + } }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_IMPL_H diff --git a/dali/internal/adaptor/common/adaptor-internal-services.h b/dali/internal/adaptor/common/adaptor-internal-services.h index ab88729..1b6f8f4 100644 --- a/dali/internal/adaptor/common/adaptor-internal-services.h +++ b/dali/internal/adaptor/common/adaptor-internal-services.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,13 +34,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class SceneHolder; using WindowContainer = std::vector; @@ -52,9 +49,7 @@ using WindowContainer = std::vector; */ class AdaptorInternalServices { - public: - /** * @return core */ @@ -113,35 +108,30 @@ public: * Used to access the list of windows from the Render thread * @param[out] windows The list of created windows */ - virtual void GetWindowContainerInterface( WindowContainer& windows ) = 0; + virtual void GetWindowContainerInterface(WindowContainer& windows) = 0; protected: - /** * constructor */ - AdaptorInternalServices() - { - }; + AdaptorInternalServices(){}; /** * virtual destructor */ - virtual ~AdaptorInternalServices() - { - }; + virtual ~AdaptorInternalServices(){}; // Undefined copy constructor. - AdaptorInternalServices( const AdaptorInternalServices& ) = delete; + AdaptorInternalServices(const AdaptorInternalServices&) = delete; // Undefined assignment operator. - AdaptorInternalServices& operator=( const AdaptorInternalServices& ) = delete; + AdaptorInternalServices& operator=(const AdaptorInternalServices&) = delete; }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_INTERNAL_SERVICES_H diff --git a/dali/internal/adaptor/common/adaptor.cpp b/dali/internal/adaptor/common/adaptor.cpp index a32657c..31af12b 100644 --- a/dali/internal/adaptor/common/adaptor.cpp +++ b/dali/internal/adaptor/common/adaptor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,45 +19,44 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include #include #include #include -#include #include +#include namespace Dali { - -Adaptor& Adaptor::New( Window window ) +Adaptor& Adaptor::New(Window window) { - Internal::Adaptor::SceneHolder* sceneHolder = &Dali::GetImplementation( window ); - Adaptor* adaptor = Internal::Adaptor::Adaptor::New( Dali::Integration::SceneHolder( sceneHolder ), NULL ); + Internal::Adaptor::SceneHolder* sceneHolder = &Dali::GetImplementation(window); + Adaptor* adaptor = Internal::Adaptor::Adaptor::New(Dali::Integration::SceneHolder(sceneHolder), NULL); return *adaptor; } -Adaptor& Adaptor::New( Window window, const Dali::RenderSurfaceInterface& surface ) +Adaptor& Adaptor::New(Window window, const Dali::RenderSurfaceInterface& surface) { - Internal::Adaptor::SceneHolder* sceneHolder = &Dali::GetImplementation( window ); - Dali::RenderSurfaceInterface* pSurface = const_cast(&surface); - Adaptor* adaptor = Internal::Adaptor::Adaptor::New( Dali::Integration::SceneHolder( sceneHolder ), pSurface, NULL, Dali::Internal::Adaptor::ThreadMode::NORMAL ); + Internal::Adaptor::SceneHolder* sceneHolder = &Dali::GetImplementation(window); + Dali::RenderSurfaceInterface* pSurface = const_cast(&surface); + Adaptor* adaptor = Internal::Adaptor::Adaptor::New(Dali::Integration::SceneHolder(sceneHolder), pSurface, NULL, Dali::Internal::Adaptor::ThreadMode::NORMAL); return *adaptor; } -Adaptor& Adaptor::New( Dali::Integration::SceneHolder window ) +Adaptor& Adaptor::New(Dali::Integration::SceneHolder window) { - Adaptor* adaptor = Internal::Adaptor::Adaptor::New( window, NULL ); + Adaptor* adaptor = Internal::Adaptor::Adaptor::New(window, NULL); return *adaptor; } -Adaptor& Adaptor::New( Dali::Integration::SceneHolder window, const Dali::RenderSurfaceInterface& surface ) +Adaptor& Adaptor::New(Dali::Integration::SceneHolder window, const Dali::RenderSurfaceInterface& surface) { - Dali::RenderSurfaceInterface* pSurface = const_cast(&surface); - Adaptor* adaptor = Internal::Adaptor::Adaptor::New( window, pSurface, NULL, Dali::Internal::Adaptor::ThreadMode::NORMAL ); + Dali::RenderSurfaceInterface* pSurface = const_cast(&surface); + Adaptor* adaptor = Internal::Adaptor::Adaptor::New(window, pSurface, NULL, Dali::Internal::Adaptor::ThreadMode::NORMAL); return *adaptor; } @@ -86,39 +85,39 @@ void Adaptor::Stop() mImpl->Stop(); } -bool Adaptor::AddIdle( CallbackBase* callback, bool hasReturnValue ) +bool Adaptor::AddIdle(CallbackBase* callback, bool hasReturnValue) { - DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" ); - return mImpl->AddIdle( callback, hasReturnValue, false ); + DALI_ASSERT_ALWAYS(IsAvailable() && "Adaptor not instantiated"); + return mImpl->AddIdle(callback, hasReturnValue, false); } -bool Adaptor::AddWindow( Dali::Integration::SceneHolder childWindow ) +bool Adaptor::AddWindow(Dali::Integration::SceneHolder childWindow) { - DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" ); - return mImpl->AddWindow( childWindow ); + DALI_ASSERT_ALWAYS(IsAvailable() && "Adaptor not instantiated"); + return mImpl->AddWindow(childWindow); } -void Adaptor::RemoveIdle( CallbackBase* callback ) +void Adaptor::RemoveIdle(CallbackBase* callback) { - DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" ); - mImpl->RemoveIdle( callback ); + DALI_ASSERT_ALWAYS(IsAvailable() && "Adaptor not instantiated"); + mImpl->RemoveIdle(callback); } void Adaptor::ProcessIdle() { - DALI_ASSERT_ALWAYS( IsAvailable() && "Adaptor not instantiated" ); + DALI_ASSERT_ALWAYS(IsAvailable() && "Adaptor not instantiated"); mImpl->ProcessIdle(); } -void Adaptor::ReplaceSurface( Window window, Dali::RenderSurfaceInterface& surface ) +void Adaptor::ReplaceSurface(Window window, Dali::RenderSurfaceInterface& surface) { - Internal::Adaptor::SceneHolder* sceneHolder = &Dali::GetImplementation( window ); - mImpl->ReplaceSurface( Dali::Integration::SceneHolder( sceneHolder ), surface ); + Internal::Adaptor::SceneHolder* sceneHolder = &Dali::GetImplementation(window); + mImpl->ReplaceSurface(Dali::Integration::SceneHolder(sceneHolder), surface); } -void Adaptor::ReplaceSurface( Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& surface ) +void Adaptor::ReplaceSurface(Dali::Integration::SceneHolder window, Dali::RenderSurfaceInterface& surface) { - mImpl->ReplaceSurface( window, surface ); + mImpl->ReplaceSurface(window, surface); } Adaptor::AdaptorSignalType& Adaptor::ResizedSignal() @@ -146,9 +145,9 @@ Any Adaptor::GetNativeWindowHandle() return mImpl->GetNativeWindowHandle(); } -Any Adaptor::GetNativeWindowHandle( Actor actor ) +Any Adaptor::GetNativeWindowHandle(Actor actor) { - return mImpl->GetNativeWindowHandle( actor ); + return mImpl->GetNativeWindowHandle(actor); } Any Adaptor::GetGraphicsDisplay() @@ -161,14 +160,14 @@ void Adaptor::ReleaseSurfaceLock() mImpl->ReleaseSurfaceLock(); } -void Adaptor::SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender ) +void Adaptor::SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender) { - mImpl->SetRenderRefreshRate( numberOfVSyncsPerRender ); + mImpl->SetRenderRefreshRate(numberOfVSyncsPerRender); } -void Adaptor::SetPreRenderCallback( CallbackBase* callback ) +void Adaptor::SetPreRenderCallback(CallbackBase* callback) { - mImpl->SetPreRenderCallback( callback ); + mImpl->SetPreRenderCallback(callback); } Adaptor& Adaptor::Get() @@ -191,17 +190,17 @@ void Adaptor::NotifyLanguageChanged() mImpl->NotifyLanguageChanged(); } -void Adaptor::FeedTouchPoint( TouchPoint& point, int timeStamp ) +void Adaptor::FeedTouchPoint(TouchPoint& point, int timeStamp) { mImpl->FeedTouchPoint(point, timeStamp); } -void Adaptor::FeedWheelEvent( WheelEvent& wheelEvent ) +void Adaptor::FeedWheelEvent(WheelEvent& wheelEvent) { mImpl->FeedWheelEvent(wheelEvent); } -void Adaptor::FeedKeyEvent( KeyEvent& keyEvent ) +void Adaptor::FeedKeyEvent(KeyEvent& keyEvent) { mImpl->FeedKeyEvent(keyEvent); } @@ -211,14 +210,14 @@ void Adaptor::SceneCreated() mImpl->SceneCreated(); } -void Adaptor::SurfaceResizePrepare( Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize ) +void Adaptor::SurfaceResizePrepare(Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize) { - mImpl->SurfaceResizePrepare( surface, surfaceSize ); + mImpl->SurfaceResizePrepare(surface, surfaceSize); } -void Adaptor::SurfaceResizeComplete( Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize ) +void Adaptor::SurfaceResizeComplete(Dali::RenderSurfaceInterface* surface, SurfaceSize surfaceSize) { - mImpl->SurfaceResizeComplete( surface, surfaceSize ); + mImpl->SurfaceResizeComplete(surface, surfaceSize); } void Adaptor::RenderOnce() @@ -231,14 +230,14 @@ const LogFactoryInterface& Adaptor::GetLogFactory() return mImpl->GetLogFactory(); } -void Adaptor::RegisterProcessor( Integration::Processor& processor ) +void Adaptor::RegisterProcessor(Integration::Processor& processor) { - mImpl->RegisterProcessor( processor ); + mImpl->RegisterProcessor(processor); } -void Adaptor::UnregisterProcessor( Integration::Processor& processor ) +void Adaptor::UnregisterProcessor(Integration::Processor& processor) { - mImpl->UnregisterProcessor( processor ); + mImpl->UnregisterProcessor(processor); } Dali::WindowContainer Adaptor::GetWindows() const @@ -267,7 +266,7 @@ void Adaptor::OnWindowHidden() } Adaptor::Adaptor() -: mImpl( NULL ) +: mImpl(NULL) { } diff --git a/dali/internal/adaptor/common/application-impl.h b/dali/internal/adaptor/common/application-impl.h index 4d3a4eb..1cd9563 100644 --- a/dali/internal/adaptor/common/application-impl.h +++ b/dali/internal/adaptor/common/application-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_APPLICATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,12 +23,12 @@ #include // INTERNAL INCLUDES -#include #include +#include +#include #include #include -#include namespace Dali { @@ -37,21 +37,18 @@ class Window; namespace Internal { - namespace Adaptor { - namespace Launchpad { - /** * @brief Launchpad is used to improve application launch performance. * When an application is pre-initialized, so files are preloaded, some functions are initialized and a window is made in advance. */ enum State { - NONE, ///< The default state - PRE_INITIALIZED ///< Application is pre-initialized. + NONE, ///< The default state + PRE_INITIALIZED ///< Application is pre-initialized. }; } // namespace Launchpad @@ -70,12 +67,11 @@ typedef IntrusivePtr ApplicationPtr; class Application : public BaseObject, public Framework::Observer { public: - typedef Dali::Application::LowBatterySignalType LowBatterySignalType; - typedef Dali::Application::LowMemorySignalType LowMemorySignalType; - typedef Dali::Application::AppSignalType AppSignalType; + typedef Dali::Application::LowMemorySignalType LowMemorySignalType; + typedef Dali::Application::AppSignalType AppSignalType; typedef Dali::Application::AppControlSignalType AppControlSignalType; - typedef Dali::Application::WINDOW_MODE WINDOW_MODE; + typedef Dali::Application::WINDOW_MODE WINDOW_MODE; /** * Create a new application @@ -86,16 +82,14 @@ public: * @param[in] positionSize A position and a size of the window * @param[in] applicationType A member of Dali::Framework::Type */ - static ApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet, - WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType ); + static ApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet, WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType); /** * @copydoc Dali::DevelApplication::PreInitialize() */ - static void PreInitialize( int* argc, char** argv[] ); + static void PreInitialize(int* argc, char** argv[]); public: - /** * @copydoc Dali::Application::MainLoop() */ @@ -114,7 +108,7 @@ public: /** * @copydoc Dali::Application::AddIdle() */ - bool AddIdle( CallbackBase* callback, bool hasReturnValue ); + bool AddIdle(CallbackBase* callback, bool hasReturnValue); /** * @copydoc Dali::Application::GetAdaptor(); @@ -159,7 +153,6 @@ public: static ApplicationPtr GetPreInitializedApplication(); public: // From Framework::Observer - /** * Called when the framework is initialised. */ @@ -184,7 +177,7 @@ public: // From Framework::Observer * Called when the framework received AppControlSignal. * @param[in] The bundle data of AppControl event. */ - void OnAppControl(void *data) override; + void OnAppControl(void* data) override; /** * Called when the framework informs the application that it should reset itself. @@ -204,31 +197,30 @@ public: // From Framework::Observer /** * Called when the framework informs the application that the battery level of the device is low. */ - void OnBatteryLow( Dali::DeviceStatus::Battery::Status status ) override; + void OnBatteryLow(Dali::DeviceStatus::Battery::Status status) override; /** * Called when the framework informs the application that the memory level of the device is low. */ - void OnMemoryLow( Dali::DeviceStatus::Memory::Status status ) override; + void OnMemoryLow(Dali::DeviceStatus::Memory::Status status) override; /** * Called when the framework informs the application that the platform surface is created. */ - void OnSurfaceCreated( Any newSurface ) override; + void OnSurfaceCreated(Any newSurface) override; /** * Called when the framework informs the application that the platform surface is destroyed. */ - void OnSurfaceDestroyed( Any newSurface ) override; + void OnSurfaceDestroyed(Any newSurface) override; public: - /** * Sets a user defined theme file. * This should be called before initialization. * @param[in] stylesheet The path to user defined theme file */ - void SetStyleSheet( const std::string& stylesheet ); + void SetStyleSheet(const std::string& stylesheet); /** * Sets a command line options. @@ -236,62 +228,90 @@ public: * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list */ - void SetCommandLineOptions( int* argc, char **argv[] ); - -public: // Signals + void SetCommandLineOptions(int* argc, char** argv[]); +public: // Signals /** * @copydoc Dali::Application::InitSignal() */ - Dali::Application::AppSignalType& InitSignal() { return mInitSignal; } + Dali::Application::AppSignalType& InitSignal() + { + return mInitSignal; + } /** * @copydoc Dali::Application::TerminateSignal() */ - Dali::Application::AppSignalType& TerminateSignal() { return mTerminateSignal; } + Dali::Application::AppSignalType& TerminateSignal() + { + return mTerminateSignal; + } /** * @copydoc Dali::Application::PauseSignal() */ - Dali::Application::AppSignalType& PauseSignal() { return mPauseSignal; } + Dali::Application::AppSignalType& PauseSignal() + { + return mPauseSignal; + } /** * @copydoc Dali::Application::ResumeSignal() */ - Dali::Application::AppSignalType& ResumeSignal() { return mResumeSignal; } + Dali::Application::AppSignalType& ResumeSignal() + { + return mResumeSignal; + } /** * @copydoc Dali::Application::ResetSignal() */ - Dali::Application::AppSignalType& ResetSignal() { return mResetSignal; } + Dali::Application::AppSignalType& ResetSignal() + { + return mResetSignal; + } /** * @copydoc Dali::Application::AppControlSignal() */ - Dali::Application::AppControlSignalType& AppControlSignal() { return mAppControlSignal; } + Dali::Application::AppControlSignalType& AppControlSignal() + { + return mAppControlSignal; + } /** * @copydoc Dali::Application::LanguageChangedSignal() */ - Dali::Application::AppSignalType& LanguageChangedSignal() { return mLanguageChangedSignal; } + Dali::Application::AppSignalType& LanguageChangedSignal() + { + return mLanguageChangedSignal; + } /** * @copydoc Dali::Application::RegionChangedSignal() */ - Dali::Application::AppSignalType& RegionChangedSignal() { return mRegionChangedSignal; } + Dali::Application::AppSignalType& RegionChangedSignal() + { + return mRegionChangedSignal; + } /** * @copydoc Dali::Application::LowBatterySignal() */ - Dali::Application::LowBatterySignalType& LowBatterySignal() { return mLowBatterySignal; } + Dali::Application::LowBatterySignalType& LowBatterySignal() + { + return mLowBatterySignal; + } /** * @copydoc Dali::Application:::LowMemorySignal() */ - Dali::Application::LowMemorySignalType& LowMemorySignal() { return mLowMemorySignal; } + Dali::Application::LowMemorySignalType& LowMemorySignal() + { + return mLowMemorySignal; + } protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments @@ -301,8 +321,7 @@ protected: * @param[in] positionSize A position and a size of the window * @param[in] applicationType A member of Dali::Framework::Type */ - Application( int* argc, char **argv[], const std::string& stylesheet, - WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType ); + Application(int* argc, char** argv[], const std::string& stylesheet, WINDOW_MODE windowMode, const PositionSize& positionSize, Framework::Type applicationType); /** * Destructor @@ -334,41 +353,40 @@ protected: void QuitFromMainLoop(); private: - - AppSignalType mInitSignal; - AppSignalType mTerminateSignal; - AppSignalType mPauseSignal; - AppSignalType mResumeSignal; - AppSignalType mResetSignal; - AppControlSignalType mAppControlSignal; - AppSignalType mLanguageChangedSignal; - AppSignalType mRegionChangedSignal; - LowBatterySignalType mLowBatterySignal; - LowMemorySignalType mLowMemorySignal; - - EventLoop* mEventLoop; - Framework* mFramework; - - CommandLineOptions* mCommandLineOptions; - - Dali::Internal::Adaptor::AdaptorBuilder* mAdaptorBuilder; ///< The adaptor builder + AppSignalType mInitSignal; + AppSignalType mTerminateSignal; + AppSignalType mPauseSignal; + AppSignalType mResumeSignal; + AppSignalType mResetSignal; + AppControlSignalType mAppControlSignal; + AppSignalType mLanguageChangedSignal; + AppSignalType mRegionChangedSignal; + LowBatterySignalType mLowBatterySignal; + LowMemorySignalType mLowMemorySignal; + + EventLoop* mEventLoop; + Framework* mFramework; + + CommandLineOptions* mCommandLineOptions; + + Dali::Internal::Adaptor::AdaptorBuilder* mAdaptorBuilder; ///< The adaptor builder Dali::Adaptor* mAdaptor; // The Main Window is that window created by the Application during initial startup // (previously this was the only window) - Dali::Window mMainWindow; ///< Main Window instance - Dali::Application::WINDOW_MODE mMainWindowMode; ///< Window mode of the main window - std::string mMainWindowName; ///< Name of the main window as obtained from environment options + Dali::Window mMainWindow; ///< Main Window instance + Dali::Application::WINDOW_MODE mMainWindowMode; ///< Window mode of the main window + std::string mMainWindowName; ///< Name of the main window as obtained from environment options - std::string mStylesheet; - EnvironmentOptions mEnvironmentOptions; - PositionSize mWindowPositionSize; - Launchpad::State mLaunchpadState; - bool mUseRemoteSurface; + std::string mStylesheet; + EnvironmentOptions mEnvironmentOptions; + PositionSize mWindowPositionSize; + Launchpad::State mLaunchpadState; + bool mUseRemoteSurface; - SlotDelegate< Application > mSlotDelegate; + SlotDelegate mSlotDelegate; - static ApplicationPtr gPreInitializedApplication; + static ApplicationPtr gPreInitializedApplication; }; inline Application& GetImplementation(Dali::Application& application) @@ -389,7 +407,6 @@ inline const Application& GetImplementation(const Dali::Application& application return static_cast(handle); } - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/adaptor/common/combined-update-render-controller-debug.h b/dali/internal/adaptor/common/combined-update-render-controller-debug.h old mode 100755 new mode 100644 index 91f9f76..2ebebb6 --- a/dali/internal/adaptor/common/combined-update-render-controller-debug.h +++ b/dali/internal/adaptor/common/combined-update-render-controller-debug.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_DEBUG_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { // Uncomment next line for FULL logging of the ThreadSynchronization class in release mode @@ -42,42 +39,48 @@ namespace #define ENABLE_UPDATE_RENDER_THREAD_LOGGING #define ENABLE_EVENT_LOGGING -#define DEBUG_LEVEL_COUNTER Debug::Verbose -#define DEBUG_LEVEL_UPDATE_RENDER Debug::General -#define DEBUG_LEVEL_EVENT Debug::Concise +#define DEBUG_LEVEL_COUNTER Debug::Verbose +#define DEBUG_LEVEL_UPDATE_RENDER Debug::General +#define DEBUG_LEVEL_EVENT Debug::Concise -Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_THREAD_SYNC" ); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_THREAD_SYNC"); #define LOG_THREAD_SYNC(level, color, format, ...) \ - DALI_LOG_INFO( gLogFilter, level, "%s" format "%s\n", color, ## __VA_ARGS__, COLOR_CLEAR ) + DALI_LOG_INFO(gLogFilter, level, "%s" format "%s\n", color, ##__VA_ARGS__, COLOR_CLEAR) -#define LOG_THREAD_SYNC_TRACE(color) \ - Dali::Integration::Log::TraceObj debugTraceObj( gLogFilter, "%s%s%s", color, __FUNCTION__, COLOR_CLEAR ); \ - if( ! gLogFilter->IsTraceEnabled() ) { LOG_THREAD_SYNC( Debug::Concise, color, "%s", __FUNCTION__ ); } +#define LOG_THREAD_SYNC_TRACE(color) \ + Dali::Integration::Log::TraceObj debugTraceObj(gLogFilter, "%s%s%s", color, __FUNCTION__, COLOR_CLEAR); \ + if(!gLogFilter->IsTraceEnabled()) \ + { \ + LOG_THREAD_SYNC(Debug::Concise, color, "%s", __FUNCTION__); \ + } -#define LOG_THREAD_SYNC_TRACE_FMT(color, format, ...) \ - Dali::Integration::Log::TraceObj debugTraceObj( gLogFilter, "%s%s: " format "%s", color, __FUNCTION__, ## __VA_ARGS__, COLOR_CLEAR ); \ - if( ! gLogFilter->IsTraceEnabled() ) { LOG_THREAD_SYNC( Debug::Concise, color, "%s: " format, __FUNCTION__, ## __VA_ARGS__ ); } +#define LOG_THREAD_SYNC_TRACE_FMT(color, format, ...) \ + Dali::Integration::Log::TraceObj debugTraceObj(gLogFilter, "%s%s: " format "%s", color, __FUNCTION__, ##__VA_ARGS__, COLOR_CLEAR); \ + if(!gLogFilter->IsTraceEnabled()) \ + { \ + LOG_THREAD_SYNC(Debug::Concise, color, "%s: " format, __FUNCTION__, ##__VA_ARGS__); \ + } -#elif defined( RELEASE_BUILD_LOGGING ) +#elif defined(RELEASE_BUILD_LOGGING) #define ENABLE_LOG_IN_COLOR #define ENABLE_COUNTER_LOGGING #define ENABLE_UPDATE_RENDER_THREAD_LOGGING #define ENABLE_EVENT_LOGGING -#define DEBUG_LEVEL_COUNTER 0 -#define DEBUG_LEVEL_UPDATE_RENDER 0 -#define DEBUG_LEVEL_EVENT 0 +#define DEBUG_LEVEL_COUNTER 0 +#define DEBUG_LEVEL_UPDATE_RENDER 0 +#define DEBUG_LEVEL_EVENT 0 #define LOG_THREAD_SYNC(level, color, format, ...) \ - Dali::Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%s" format "%s\n", color, ## __VA_ARGS__, COLOR_CLEAR ) + Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s" format "%s\n", color, ##__VA_ARGS__, COLOR_CLEAR) #define LOG_THREAD_SYNC_TRACE(color) \ - Dali::Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%s%s%s\n", color, __FUNCTION__, COLOR_CLEAR ) + Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s%s%s\n", color, __FUNCTION__, COLOR_CLEAR) #define LOG_THREAD_SYNC_TRACE_FMT(color, format, ...) \ - Dali::Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, "%s%s: " format "%s\n", color, __FUNCTION__, ## __VA_ARGS__, COLOR_CLEAR ) + Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s%s: " format "%s\n", color, __FUNCTION__, ##__VA_ARGS__, COLOR_CLEAR) #else @@ -88,11 +91,11 @@ Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TH #endif // DEBUG_ENABLED #ifdef ENABLE_LOG_IN_COLOR -#define COLOR_YELLOW "\033[33m" -#define COLOR_LIGHT_RED "\033[91m" -#define COLOR_LIGHT_YELLOW "\033[93m" -#define COLOR_WHITE "\033[97m" -#define COLOR_CLEAR "\033[0m" +#define COLOR_YELLOW "\033[33m" +#define COLOR_LIGHT_RED "\033[91m" +#define COLOR_LIGHT_YELLOW "\033[93m" +#define COLOR_WHITE "\033[97m" +#define COLOR_CLEAR "\033[0m" #else #define COLOR_YELLOW #define COLOR_LIGHT_RED @@ -102,17 +105,17 @@ Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TH #endif #ifdef ENABLE_COUNTER_LOGGING -#define LOG_COUNTER_EVENT(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_COUNTER, COLOR_LIGHT_RED, "%s: " format, __FUNCTION__, ## __VA_ARGS__) -#define LOG_COUNTER_UPDATE_RENDER(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_COUNTER, COLOR_LIGHT_YELLOW, "%s: " format, __FUNCTION__, ## __VA_ARGS__) +#define LOG_COUNTER_EVENT(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_COUNTER, COLOR_LIGHT_RED, "%s: " format, __FUNCTION__, ##__VA_ARGS__) +#define LOG_COUNTER_UPDATE_RENDER(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_COUNTER, COLOR_LIGHT_YELLOW, "%s: " format, __FUNCTION__, ##__VA_ARGS__) #else #define LOG_COUNTER_EVENT(format, ...) #define LOG_COUNTER_UPDATE_RENDER(format, ...) #endif #ifdef ENABLE_UPDATE_RENDER_THREAD_LOGGING -#define LOG_UPDATE_RENDER(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_UPDATE_RENDER, COLOR_YELLOW, "%s: " format, __FUNCTION__, ## __VA_ARGS__) -#define LOG_UPDATE_RENDER_TRACE LOG_THREAD_SYNC_TRACE(COLOR_YELLOW) -#define LOG_UPDATE_RENDER_TRACE_FMT(format, ...) LOG_THREAD_SYNC_TRACE_FMT(COLOR_YELLOW, format, ## __VA_ARGS__) +#define LOG_UPDATE_RENDER(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_UPDATE_RENDER, COLOR_YELLOW, "%s: " format, __FUNCTION__, ##__VA_ARGS__) +#define LOG_UPDATE_RENDER_TRACE LOG_THREAD_SYNC_TRACE(COLOR_YELLOW) +#define LOG_UPDATE_RENDER_TRACE_FMT(format, ...) LOG_THREAD_SYNC_TRACE_FMT(COLOR_YELLOW, format, ##__VA_ARGS__) #else #define LOG_UPDATE_RENDER(format, ...) #define LOG_UPDATE_RENDER_TRACE @@ -120,9 +123,9 @@ Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TH #endif #ifdef ENABLE_EVENT_LOGGING -#define LOG_EVENT(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_EVENT, COLOR_WHITE, "%s: " format, __FUNCTION__, ## __VA_ARGS__) -#define LOG_EVENT_TRACE LOG_THREAD_SYNC_TRACE(COLOR_WHITE) -#define LOG_EVENT_TRACE_FMT(format, ...) LOG_THREAD_SYNC_TRACE_FMT(COLOR_WHITE, format, ## __VA_ARGS__) +#define LOG_EVENT(format, ...) LOG_THREAD_SYNC(DEBUG_LEVEL_EVENT, COLOR_WHITE, "%s: " format, __FUNCTION__, ##__VA_ARGS__) +#define LOG_EVENT_TRACE LOG_THREAD_SYNC_TRACE(COLOR_WHITE) +#define LOG_EVENT_TRACE_FMT(format, ...) LOG_THREAD_SYNC_TRACE_FMT(COLOR_WHITE, format, ##__VA_ARGS__) #else #define LOG_EVENT(format, ...) #define LOG_EVENT_TRACE diff --git a/dali/internal/adaptor/common/combined-update-render-controller.h b/dali/internal/adaptor/common/combined-update-render-controller.h index 612967f..7127d66 100644 --- a/dali/internal/adaptor/common/combined-update-render-controller.h +++ b/dali/internal/adaptor/common/combined-update-render-controller.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ */ // EXTERNAL INCLUDES -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include // INTERNAL INCLUDES #include @@ -37,16 +37,13 @@ namespace Dali { - class RenderSurfaceInterface; class TriggerEventInterface; namespace Internal { - namespace Adaptor { - class AdaptorInternalServices; class EnvironmentOptions; @@ -77,11 +74,10 @@ class CombinedUpdateRenderController : public ThreadControllerInterface, public ThreadSynchronizationInterface { public: - /** * Constructor */ - CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode ); + CombinedUpdateRenderController(AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode); /** * Non virtual destructor. Not intended as base class. @@ -121,17 +117,17 @@ public: /** * @copydoc ThreadControllerInterface::RequestUpdateOnce() */ - void RequestUpdateOnce( UpdateMode updateMode ) override; + void RequestUpdateOnce(UpdateMode updateMode) override; /** * @copydoc ThreadControllerInterface::ReplaceSurface() */ - void ReplaceSurface( Dali::RenderSurfaceInterface* surface ) override; + void ReplaceSurface(Dali::RenderSurfaceInterface* surface) override; /** * @copydoc ThreadControllerInterface::DeleteSurface() */ - void DeleteSurface( Dali::RenderSurfaceInterface* surface ) override; + void DeleteSurface(Dali::RenderSurfaceInterface* surface) override; /** * @copydoc ThreadControllerInterface::ResizeSurface() @@ -146,25 +142,24 @@ public: /** * @copydoc ThreadControllerInterface::SetRenderRefreshRate() */ - void SetRenderRefreshRate( unsigned int numberOfFramesPerRender ) override; + void SetRenderRefreshRate(unsigned int numberOfFramesPerRender) override; /** * @copydoc ThreadControllerInterface::SetPreRenderCallback */ - void SetPreRenderCallback( CallbackBase* callback ) override; + void SetPreRenderCallback(CallbackBase* callback) override; /** * @copydoc ThreadControllerInterface::AddSurface() */ - void AddSurface( Dali::RenderSurfaceInterface* surface ) override; + void AddSurface(Dali::RenderSurfaceInterface* surface) override; private: - // Undefined copy constructor. - CombinedUpdateRenderController( const CombinedUpdateRenderController& ); + CombinedUpdateRenderController(const CombinedUpdateRenderController&); // Undefined assignment operator. - CombinedUpdateRenderController& operator=( const CombinedUpdateRenderController& ); + CombinedUpdateRenderController& operator=(const CombinedUpdateRenderController&); ///////////////////////////////////////////////////////////////////////////////////////////////// // EventThread @@ -172,8 +167,8 @@ private: enum AnimationProgression { - USE_ELAPSED_TIME, ///< Animation progression using elapsed time - NONE ///< No animation progression + USE_ELAPSED_TIME, ///< Animation progression using elapsed time + NONE ///< No animation progression }; /** @@ -184,7 +179,7 @@ private: * @param[in] animationProgression Whether to progress animation using time elapsed since the last frame. * @param[in] updateMode The update mode (i.e. either update & render or skip rendering) */ - inline void RunUpdateRenderThread( int numberOfCycles, AnimationProgression animationProgression, UpdateMode updateMode ); + inline void RunUpdateRenderThread(int numberOfCycles, AnimationProgression animationProgression, UpdateMode updateMode); /** * Pauses the Update/Render Thread. @@ -233,7 +228,7 @@ private: * @param[out] timeToSleepUntil The time remaining in nanoseconds to keep the thread sleeping before resuming. * @return false, if the thread should stop. */ - bool UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil ); + bool UpdateRenderReady(bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil); /** * Checks to see if the surface needs to be replaced. @@ -276,9 +271,9 @@ private: * Helper for the thread calling the entry function * @param[in] This A pointer to the current object */ - static void* InternalUpdateRenderThreadEntryFunc( void* This ) + static void* InternalUpdateRenderThreadEntryFunc(void* This) { - ( static_cast( This ) )->UpdateRenderThread(); + (static_cast(This))->UpdateRenderThread(); return NULL; } @@ -302,7 +297,7 @@ private: * Helper to add a performance marker to the performance server (if it's active) * @param[in] type performance marker type */ - void AddPerformanceMarker( PerformanceInterface::MarkerType type ); + void AddPerformanceMarker(PerformanceInterface::MarkerType type); ///////////////////////////////////////////////////////////////////////////////////////////////// // POST RENDERING - ThreadSynchronizationInterface overrides @@ -332,61 +327,60 @@ private: void PostRenderWaitForCompletion() override; private: + FpsTracker mFpsTracker; ///< Object that tracks the FPS + UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required. - FpsTracker mFpsTracker; ///< Object that tracks the FPS - UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required. - - Semaphore<> mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface. - ConditionalWait mGraphicsInitializeWait; ///< Used by the render thread to ensure the graphics has been initialised. - Semaphore<> mSurfaceSemaphore; ///< Used by the event thread to ensure the surface has been deleted or replaced. + Semaphore<> mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface. + ConditionalWait mGraphicsInitializeWait; ///< Used by the render thread to ensure the graphics has been initialised. + Semaphore<> mSurfaceSemaphore; ///< Used by the event thread to ensure the surface has been deleted or replaced. - ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread. + ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread. - AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface - PerformanceInterface* mPerformanceInterface; ///< The performance logging interface - Integration::Core& mCore; ///< Dali core reference - const EnvironmentOptions& mEnvironmentOptions; ///< Environment options - TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger - TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates - CallbackBase* mPreRenderCallback; ///< Used by Update/Render thread when PreRender is about to be called on graphics. + AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface + PerformanceInterface* mPerformanceInterface; ///< The performance logging interface + Integration::Core& mCore; ///< Dali core reference + const EnvironmentOptions& mEnvironmentOptions; ///< Environment options + TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger + TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates + CallbackBase* mPreRenderCallback; ///< Used by Update/Render thread when PreRender is about to be called on graphics. - pthread_t* mUpdateRenderThread; ///< The Update/Render thread. + pthread_t* mUpdateRenderThread; ///< The Update/Render thread. - float mDefaultFrameDelta; ///< Default time delta between each frame (used for animations). Not protected by lock, but written to rarely so not worth adding a lock when reading. + float mDefaultFrameDelta; ///< Default time delta between each frame (used for animations). Not protected by lock, but written to rarely so not worth adding a lock when reading. // TODO: mDefaultFrameDurationMilliseconds is defined as uint64_t, the only place where it is used, it is converted to an unsigned int!!! - uint64_t mDefaultFrameDurationMilliseconds; ///< Default duration of a frame (used for predicting the time of the next frame). Not protected by lock, but written to rarely so not worth adding a lock when reading. - uint64_t mDefaultFrameDurationNanoseconds; ///< Default duration of a frame (used for sleeping if not enough time elapsed). Not protected by lock, but written to rarely so not worth adding a lock when reading. - uint64_t mDefaultHalfFrameNanoseconds; ///< Is half of mDefaultFrameDurationNanoseconds. Using a member variable avoids having to do the calculation every frame. Not protected by lock, but written to rarely so not worth adding a lock when reading. + uint64_t mDefaultFrameDurationMilliseconds; ///< Default duration of a frame (used for predicting the time of the next frame). Not protected by lock, but written to rarely so not worth adding a lock when reading. + uint64_t mDefaultFrameDurationNanoseconds; ///< Default duration of a frame (used for sleeping if not enough time elapsed). Not protected by lock, but written to rarely so not worth adding a lock when reading. + uint64_t mDefaultHalfFrameNanoseconds; ///< Is half of mDefaultFrameDurationNanoseconds. Using a member variable avoids having to do the calculation every frame. Not protected by lock, but written to rarely so not worth adding a lock when reading. - unsigned int mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early. - unsigned int mRunning; ///< Read and set on the event-thread only to state whether we are running. + unsigned int mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early. + unsigned int mRunning; ///< Read and set on the event-thread only to state whether we are running. - ThreadMode mThreadMode; ///< Whether the thread runs continuously or runs when it is requested. + ThreadMode mThreadMode; ///< Whether the thread runs continuously or runs when it is requested. // // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write // - volatile int mUpdateRenderRunCount; ///< The number of times Update/Render cycle should run. If -1, then will run continuously (set by the event-thread, read by v-sync-thread). - volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread). - volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread). - volatile unsigned int mPendingRequestUpdate; ///< Is set as soon as an RequestUpdate is made and unset when the next update happens (set by the event-thread and update-render thread, read by the update-render-thread). - ///< Ensures we do not go to sleep if we have not processed the most recent update-request. + volatile int mUpdateRenderRunCount; ///< The number of times Update/Render cycle should run. If -1, then will run continuously (set by the event-thread, read by v-sync-thread). + volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread). + volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread). + volatile unsigned int mPendingRequestUpdate; ///< Is set as soon as an RequestUpdate is made and unset when the next update happens (set by the event-thread and update-render thread, read by the update-render-thread). + ///< Ensures we do not go to sleep if we have not processed the most recent update-request. - volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread). + volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread). - Dali::RenderSurfaceInterface* volatile mNewSurface; ///< Will be set to the new-surface if requested (set by the event-thread, read & cleared by the update-render thread). - Dali::RenderSurfaceInterface* volatile mDeletedSurface; ///< Will be set to the deleted surface if requested (set by the event-thread, read & cleared by the update-render thread). + Dali::RenderSurfaceInterface* volatile mNewSurface; ///< Will be set to the new-surface if requested (set by the event-thread, read & cleared by the update-render thread). + Dali::RenderSurfaceInterface* volatile mDeletedSurface; ///< Will be set to the deleted surface if requested (set by the event-thread, read & cleared by the update-render thread). - volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread). - volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread). - volatile unsigned int mForceClear; ///< Will be set to clear forcibly + volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread). + volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread). + volatile unsigned int mForceClear; ///< Will be set to clear forcibly - volatile unsigned int mUploadWithoutRendering; ///< Will be set to upload the resource only (with no rendering) + volatile unsigned int mUploadWithoutRendering; ///< Will be set to upload the resource only (with no rendering) - volatile unsigned int mFirstFrameAfterResume; ///< Will be set to check the first frame after resume (for log) + volatile unsigned int mFirstFrameAfterResume; ///< Will be set to check the first frame after resume (for log) - std::vector> mDamagedRects; ///< Keeps collected damaged render items rects for one render pass + std::vector> mDamagedRects; ///< Keeps collected damaged render items rects for one render pass }; } // namespace Adaptor diff --git a/dali/internal/adaptor/common/framework.h b/dali/internal/adaptor/common/framework.h index e4b172b..5ab74ac 100644 --- a/dali/internal/adaptor/common/framework.h +++ b/dali/internal/adaptor/common/framework.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_FRAMEWORK_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include #ifdef APPCORE_WATCH_AVAILABLE #include #endif @@ -34,13 +34,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * The Framework class is ideally placed to provide key API required by Applications. * @@ -52,13 +49,12 @@ namespace Adaptor class Framework { public: - enum Type { - NORMAL, ///< normal appFramework - WATCH, ///< watch appFramework - WIDGET, ///< widget appFramework - COMPONENT ///< component appFramework + NORMAL, ///< normal appFramework + WATCH, ///< watch appFramework + WIDGET, ///< widget appFramework + COMPONENT ///< component appFramework }; /** @@ -67,95 +63,126 @@ public: class Observer { public: - /** * Invoked when the application is to be initialised. */ - virtual void OnInit() {} + virtual void OnInit() + { + } /** * Invoked when the application is to be terminated. */ - virtual void OnTerminate() {} + virtual void OnTerminate() + { + } /** * Invoked when the application is to be paused. */ - virtual void OnPause() {} + virtual void OnPause() + { + } /** * Invoked when the application is to be resumed. */ - virtual void OnResume() {} + virtual void OnResume() + { + } /** * Invoked when the application is to be reset. */ - virtual void OnReset() {} + virtual void OnReset() + { + } /** * Invoked when the AppControl message is received. * @param[in] The bundle data of AppControl message. */ - virtual void OnAppControl(void *) {} + virtual void OnAppControl(void*) + { + } #ifdef APPCORE_WATCH_AVAILABLE /** * Invoked at every second */ - virtual void OnTimeTick(WatchTime&) {} + virtual void OnTimeTick(WatchTime&) + { + } /** * Invoked at every second in ambient mode */ - virtual void OnAmbientTick(WatchTime&) {} + virtual void OnAmbientTick(WatchTime&) + { + } /** * Invoked when the device enters or exits ambient mode */ - virtual void OnAmbientChanged(bool ambient) {} + virtual void OnAmbientChanged(bool ambient) + { + } #endif /** * Invoked when the language of the device is changed. */ - virtual void OnLanguageChanged() {} + virtual void OnLanguageChanged() + { + } /** * Invoked when the region is changed. */ - virtual void OnRegionChanged() {} + virtual void OnRegionChanged() + { + } /** * Invoked when the battery level of the device is low. */ - virtual void OnBatteryLow( Dali::DeviceStatus::Battery::Status status ) {} + virtual void OnBatteryLow(Dali::DeviceStatus::Battery::Status status) + { + } /** * Invoked when the memory level of the device is low. */ - virtual void OnMemoryLow( Dali::DeviceStatus::Memory::Status status ) {} + virtual void OnMemoryLow(Dali::DeviceStatus::Memory::Status status) + { + } /** * Invoked when the platform surface is created. */ - virtual void OnSurfaceCreated( Any newSurface ) {} + virtual void OnSurfaceCreated(Any newSurface) + { + } /** * Invoked when the platform surface is destroyed. */ - virtual void OnSurfaceDestroyed( Any newSurface ) {} + virtual void OnSurfaceDestroyed(Any newSurface) + { + } #ifdef COMPONENT_APPLICATION_SUPPORT /** * Invoked when the component application is created. */ - virtual Any OnCreate() { return nullptr; } + virtual Any OnCreate() + { + return nullptr; + } #endif }; public: - /** * Constructor * @param[in] observer The observer of the Framework. @@ -163,7 +190,7 @@ public: * @param[in] argv A pointer the the argument list. * @param[in] type The type of application */ - Framework( Observer& observer, int* argc, char ***argv, Type type = NORMAL ); + Framework(Observer& observer, int* argc, char*** argv, Type type = NORMAL); /** * Destructor @@ -171,7 +198,6 @@ public: ~Framework(); public: - /** * Runs the main loop of framework */ @@ -194,7 +220,7 @@ public: * @note Only one callback can be registered. The last callback to be set will be called on abort. * @note The ownership of callback is passed onto this class. */ - void AddAbortCallback( CallbackBase* callback ); + void AddAbortCallback(CallbackBase* callback); /** * Gets bundle name which was passed in app_reset callback. @@ -212,13 +238,12 @@ public: * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list */ - void SetCommandLineOptions( int* argc, char **argv[] ) + void SetCommandLineOptions(int* argc, char** argv[]) { mArgc = argc; mArgv = argv; } - /** * Gets the path at which application resources are stored. */ @@ -232,12 +257,12 @@ public: /** * Sets system language. */ - void SetLanguage( const std::string& language ); + void SetLanguage(const std::string& language); /** * Sets system region. */ - void SetRegion( const std::string& region ); + void SetRegion(const std::string& region); /** * Gets system language. @@ -263,22 +288,20 @@ public: * @param[in] callback The callback. * @return The callback id. */ - unsigned int AddIdle( int timeout, void* data, bool ( *callback )( void *data ) ); + unsigned int AddIdle(int timeout, void* data, bool (*callback)(void* data)); /** * Called by the adaptor when an idle callback is removed. * @param[in] id The callback id. */ - void RemoveIdle( unsigned int id ); + void RemoveIdle(unsigned int id); private: - // Undefined Framework(const Framework&); Framework& operator=(Framework&); private: - /** * Called when the application is created. */ @@ -305,18 +328,17 @@ private: void InitThreads(); private: - Observer& mObserver; - bool mInitialised; - bool mPaused; - bool mRunning; - int* mArgc; - char*** mArgv; - std::string mBundleName; - std::string mBundleId; - AbortHandler mAbortHandler; + Observer& mObserver; + bool mInitialised; + bool mPaused; + bool mRunning; + int* mArgc; + char*** mArgv; + std::string mBundleName; + std::string mBundleId; + AbortHandler mAbortHandler; private: // impl members - struct Impl; Impl* mImpl; }; diff --git a/dali/internal/adaptor/common/lifecycle-controller-impl.cpp b/dali/internal/adaptor/common/lifecycle-controller-impl.cpp index bfdd275..f932d75 100644 --- a/dali/internal/adaptor/common/lifecycle-controller-impl.cpp +++ b/dali/internal/adaptor/common/lifecycle-controller-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,36 +22,33 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - Dali::LifecycleController LifecycleController::Get() { Dali::LifecycleController lifecycleController; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::LifecycleController ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::LifecycleController)); if(handle) { // If so, downcast the handle - lifecycleController = Dali::LifecycleController( dynamic_cast< LifecycleController* >( handle.GetObjectPtr() ) ); + lifecycleController = Dali::LifecycleController(dynamic_cast(handle.GetObjectPtr())); } else { - lifecycleController = Dali::LifecycleController( new LifecycleController() ); - service.Register( typeid( lifecycleController ), lifecycleController ); + lifecycleController = Dali::LifecycleController(new LifecycleController()); + service.Register(typeid(lifecycleController), lifecycleController); } } @@ -73,7 +70,7 @@ Dali::LifecycleController::LifecycleSignalType& LifecycleController::InitSignal( void LifecycleController::EmitInitSignal() { - if( !mInitSignal.Empty() ) + if(!mInitSignal.Empty()) { mInitSignal.Emit(); } @@ -86,7 +83,7 @@ Dali::LifecycleController::LifecycleSignalType& LifecycleController::TerminateSi void LifecycleController::EmitTerminateSignal() { - if( !mTerminateSignal.Empty() ) + if(!mTerminateSignal.Empty()) { mTerminateSignal.Emit(); } @@ -99,7 +96,7 @@ Dali::LifecycleController::LifecycleSignalType& LifecycleController::PauseSignal void LifecycleController::EmitPauseSignal() { - if( !mPauseSignal.Empty() ) + if(!mPauseSignal.Empty()) { mPauseSignal.Emit(); } @@ -112,7 +109,7 @@ Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResumeSigna void LifecycleController::EmitResumeSignal() { - if( !mResumeSignal.Empty() ) + if(!mResumeSignal.Empty()) { mResumeSignal.Emit(); } @@ -125,7 +122,7 @@ Dali::LifecycleController::LifecycleSignalType& LifecycleController::ResetSignal void LifecycleController::EmitResetSignal() { - if( !mResetSignal.Empty() ) + if(!mResetSignal.Empty()) { mResetSignal.Emit(); } @@ -138,38 +135,38 @@ Dali::LifecycleController::LifecycleSignalType& LifecycleController::LanguageCha void LifecycleController::EmitLanguageChangedSignal() { - if( !mLanguageChangedSignal.Empty() ) + if(!mLanguageChangedSignal.Empty()) { mLanguageChangedSignal.Emit(); } } -void LifecycleController::OnInit( Dali::Application& app ) +void LifecycleController::OnInit(Dali::Application& app) { EmitInitSignal(); } -void LifecycleController::OnTerminate( Dali::Application& app ) +void LifecycleController::OnTerminate(Dali::Application& app) { EmitTerminateSignal(); } -void LifecycleController::OnPause( Dali::Application& app ) +void LifecycleController::OnPause(Dali::Application& app) { EmitPauseSignal(); } -void LifecycleController::OnResume( Dali::Application& app ) +void LifecycleController::OnResume(Dali::Application& app) { EmitResumeSignal(); } -void LifecycleController::OnReset( Dali::Application& app ) +void LifecycleController::OnReset(Dali::Application& app) { EmitResetSignal(); } -void LifecycleController::OnLanguageChanged( Dali::Application& app ) +void LifecycleController::OnLanguageChanged(Dali::Application& app) { EmitLanguageChangedSignal(); } diff --git a/dali/internal/adaptor/common/lifecycle-controller-impl.h b/dali/internal/adaptor/common/lifecycle-controller-impl.h index f63c0c2..f72ddb7 100644 --- a/dali/internal/adaptor/common/lifecycle-controller-impl.h +++ b/dali/internal/adaptor/common/lifecycle-controller-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_LIFECYCLE_CONTROLLER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -28,22 +28,18 @@ namespace Dali { - class Adaptor; namespace Internal { - namespace Adaptor { - /** * This provides signals that are emitted according the lifecylce of the program. */ class LifecycleController : public BaseObject, public ConnectionTracker { public: - // Creation & Destruction /** @@ -90,58 +86,55 @@ public: Dali::LifecycleController::LifecycleSignalType& LanguageChangedSignal(); public: - /** * Called when the framework is initialised. * * @param[in] app The application instance */ - void OnInit( Dali::Application& app ); + void OnInit(Dali::Application& app); /** * Called when the framework is terminated. * * @param[in] app The application instance */ - void OnTerminate( Dali::Application& app ); + void OnTerminate(Dali::Application& app); /** * Called when the framework is paused. * * @param[in] app The application instance */ - void OnPause( Dali::Application& app ); + void OnPause(Dali::Application& app); /** * Called when the framework resumes from a paused state. * * @param[in] app The application instance */ - void OnResume( Dali::Application& app ); + void OnResume(Dali::Application& app); /** * Called when the framework informs the application that it should reset itself. * * @param[in] app The application instance */ - void OnReset( Dali::Application& app ); + void OnReset(Dali::Application& app); /** * Called when the framework informs the application that the language of the device has changed. * * @param[in] app The application instance */ - void OnLanguageChanged( Dali::Application& app ); + void OnLanguageChanged(Dali::Application& app); protected: - /** * Virtual Destructor. */ ~LifecycleController() override; private: - /** * Emit the init signal. */ @@ -173,7 +166,6 @@ private: void EmitLanguageChangedSignal(); private: - // Signals Dali::LifecycleController::LifecycleSignalType mInitSignal; Dali::LifecycleController::LifecycleSignalType mTerminateSignal; @@ -181,7 +173,6 @@ private: Dali::LifecycleController::LifecycleSignalType mResumeSignal; Dali::LifecycleController::LifecycleSignalType mResetSignal; Dali::LifecycleController::LifecycleSignalType mLanguageChangedSignal; - }; } // namespace Adaptor diff --git a/dali/internal/adaptor/common/lifecycle-observer.h b/dali/internal/adaptor/common/lifecycle-observer.h index d84ac8c..f4344e6 100644 --- a/dali/internal/adaptor/common/lifecycle-observer.h +++ b/dali/internal/adaptor/common/lifecycle-observer.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_BASE_LIFECYCLE_OBSERVER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Adaptor life cycle observer */ @@ -61,7 +58,6 @@ public: virtual void OnDestroy() = 0; protected: - /** * Constructor */ @@ -77,21 +73,17 @@ protected: } private: - // Undefined copy constructor. - LifeCycleObserver( const LifeCycleObserver& ); + LifeCycleObserver(const LifeCycleObserver&); // Undefined assignment operator. - LifeCycleObserver& operator=( const LifeCycleObserver& ); - + LifeCycleObserver& operator=(const LifeCycleObserver&); }; - +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_BASE_LIFECYCLE_OBSERVER_H diff --git a/dali/internal/adaptor/common/thread-controller-interface.h b/dali/internal/adaptor/common/thread-controller-interface.h index efeb819..1ab348a 100644 --- a/dali/internal/adaptor/common/thread-controller-interface.h +++ b/dali/internal/adaptor/common/thread-controller-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_THREAD_CONTROLLER_INTERFACE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,26 +22,23 @@ namespace Dali { - class RenderSurfaceInterface; namespace Internal { - namespace Adaptor { - enum class UpdateMode { - NORMAL, ///< Update and render - SKIP_RENDER, ///< Update and resource upload but no rendering - FORCE_RENDER ///< Force update and render + NORMAL, ///< Update and render + SKIP_RENDER, ///< Update and resource upload but no rendering + FORCE_RENDER ///< Force update and render }; enum class ThreadMode { - NORMAL, ///< The thread runs continuously - RUN_IF_REQUESTED ///< The threads runs when it is requested + NORMAL, ///< The thread runs continuously + RUN_IF_REQUESTED ///< The threads runs when it is requested }; /** @@ -50,11 +47,12 @@ enum class ThreadMode class ThreadControllerInterface { public: - /** * Virtual destructor. Not intended as base class. */ - virtual ~ThreadControllerInterface() { } + virtual ~ThreadControllerInterface() + { + } /** * Initializes the thread controller @@ -91,19 +89,19 @@ public: * If Adaptor is paused, we do one update/render and return to pause * @param updateMode The update mode (i.e. i.e. either update & render or skip rendering) */ - virtual void RequestUpdateOnce( UpdateMode updateMode ) = 0; + virtual void RequestUpdateOnce(UpdateMode updateMode) = 0; /** * Replaces the surface. * @param surface new surface */ - virtual void ReplaceSurface( Dali::RenderSurfaceInterface* surface ) = 0; + virtual void ReplaceSurface(Dali::RenderSurfaceInterface* surface) = 0; /** * Deletes the surface. * @param[in] surface The surface to be deleted */ - virtual void DeleteSurface( Dali::RenderSurfaceInterface* surface ) = 0; + virtual void DeleteSurface(Dali::RenderSurfaceInterface* surface) = 0; /** * Resize the surface. @@ -118,33 +116,33 @@ public: /** * @copydoc Dali::Adaptor::SetRenderRefreshRate() */ - virtual void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender ) = 0; + virtual void SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender) = 0; /** * @copydoc Dali::Adaptor::SetPreRenderCallback() */ - virtual void SetPreRenderCallback( CallbackBase* callback ) = 0; + virtual void SetPreRenderCallback(CallbackBase* callback) = 0; /** * @brief Adds the new surface. * @param surface new surface */ - virtual void AddSurface( Dali::RenderSurfaceInterface* surface ) = 0; + virtual void AddSurface(Dali::RenderSurfaceInterface* surface) = 0; protected: - /** * Constructor */ - ThreadControllerInterface() { } + ThreadControllerInterface() + { + } private: - // Undefined copy constructor. - ThreadControllerInterface( const ThreadControllerInterface& ); + ThreadControllerInterface(const ThreadControllerInterface&); // Undefined assignment operator. - ThreadControllerInterface& operator=( const ThreadControllerInterface& ); + ThreadControllerInterface& operator=(const ThreadControllerInterface&); }; } // namespace Adaptor diff --git a/dali/internal/adaptor/common/threading-mode.h b/dali/internal/adaptor/common/threading-mode.h index d113c3a..c0f21a0 100644 --- a/dali/internal/adaptor/common/threading-mode.h +++ b/dali/internal/adaptor/common/threading-mode.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_THREADING_MODE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,25 +20,22 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - struct ThreadingMode { enum Type { - COMBINED_UPDATE_RENDER = 1, ///< Three threads: Event, V-Sync & a Joint Update/Render thread. + COMBINED_UPDATE_RENDER = 1, ///< Three threads: Event, V-Sync & a Joint Update/Render thread. }; }; -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_THREADING_MODE_H diff --git a/dali/internal/adaptor/generic/adaptor-impl-generic.cpp b/dali/internal/adaptor/generic/adaptor-impl-generic.cpp index 2a983ee..9693b0b 100644 --- a/dali/internal/adaptor/generic/adaptor-impl-generic.cpp +++ b/dali/internal/adaptor/generic/adaptor-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,24 +20,21 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - std::string Adaptor::GetApplicationPackageName() { return ""; } -void Adaptor::GetDataStoragePath( std::string& path) +void Adaptor::GetDataStoragePath(std::string& path) { path = ""; } -void Adaptor::GetAppId( std::string& appId ) +void Adaptor::GetAppId(std::string& appId) { appId = ""; } diff --git a/dali/internal/adaptor/tizen-wayland/adaptor-impl-tizen.cpp b/dali/internal/adaptor/tizen-wayland/adaptor-impl-tizen.cpp old mode 100755 new mode 100644 index cff3073..a0150ec --- a/dali/internal/adaptor/tizen-wayland/adaptor-impl-tizen.cpp +++ b/dali/internal/adaptor/tizen-wayland/adaptor-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,53 +37,49 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - -static void OnSystemLanguageChanged( system_settings_key_e key, void* data ) +static void OnSystemLanguageChanged(system_settings_key_e key, void* data) { char* locale = NULL; - if( system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale ) != SYSTEM_SETTINGS_ERROR_NONE || - locale == NULL ) + if(system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale) != SYSTEM_SETTINGS_ERROR_NONE || + locale == NULL) { - DALI_LOG_ERROR( "DALI OnSystemLanguageChanged failed " ); + DALI_LOG_ERROR("DALI OnSystemLanguageChanged failed "); return; } - Adaptor* adaptor = static_cast< Adaptor* >( data ); - if( adaptor != NULL ) + Adaptor* adaptor = static_cast(data); + if(adaptor != NULL) { - adaptor->SetRootLayoutDirection( locale ); + adaptor->SetRootLayoutDirection(locale); } - free( locale ); + free(locale); } -} // namesapce +} // namespace std::string Adaptor::GetApplicationPackageName() { char appname[4096] = {0}; - int pid = getpid(); - aul_app_get_pkgname_bypid( pid, appname, sizeof( appname ) ); + int pid = getpid(); + aul_app_get_pkgname_bypid(pid, appname, sizeof(appname)); return appname; } -void Adaptor::GetResourceStoragePath( std::string& path ) +void Adaptor::GetResourceStoragePath(std::string& path) { #ifdef USE_APPFW - char *pathInt = app_get_resource_path(); - if ( pathInt ) + char* pathInt = app_get_resource_path(); + if(pathInt) { path = pathInt; - free( pathInt ); + free(pathInt); } else { @@ -92,32 +88,31 @@ void Adaptor::GetResourceStoragePath( std::string& path ) #endif } -void Adaptor::GetDataStoragePath( std::string& path ) +void Adaptor::GetDataStoragePath(std::string& path) { #ifdef USE_APPFW - char *pathInt = app_get_data_path(); - if ( pathInt ) + char* pathInt = app_get_data_path(); + if(pathInt) { path = pathInt; - free( pathInt ); + free(pathInt); } else { path = ""; } #endif - } -void Adaptor::GetAppId( std::string& appId ) +void Adaptor::GetAppId(std::string& appId) { #ifdef USE_APPFW - char *id; + char* id; app_get_id(&id); - if ( id ) + if(id) { appId = id; - free( id ); + free(id); } else { @@ -129,48 +124,47 @@ void Adaptor::GetAppId( std::string& appId ) void Adaptor::SurfaceInitialized() { #ifdef APPCORE_WATCH_AVAILABLE - if ( !mUseRemoteSurface ) + if(!mUseRemoteSurface) { return; } - char *appId; + char* appId; app_get_id(&appId); // Use strdup() in app_get_id(), so need to free memory - if( appId ) + if(appId) { #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Window* ecoreWlWindow = AnyCast< Ecore_Wl2_Window* >( mWindows.front()->GetNativeHandle() ); - screen_connector_provider_remote_enable( appId, ecore_wl2_window_surface_get( ecoreWlWindow ) ); + Ecore_Wl2_Window* ecoreWlWindow = AnyCast(mWindows.front()->GetNativeHandle()); + screen_connector_provider_remote_enable(appId, ecore_wl2_window_surface_get(ecoreWlWindow)); #else - Ecore_Wl_Window* ecoreWlWindow = AnyCast< Ecore_Wl_Window* >( mWindows.front()->GetNativeHandle() ); - screen_connector_provider_remote_enable( appId, ecore_wl_window_surface_get( ecoreWlWindow ) ); + Ecore_Wl_Window* ecoreWlWindow = AnyCast(mWindows.front()->GetNativeHandle()); + screen_connector_provider_remote_enable(appId, ecore_wl_window_surface_get(ecoreWlWindow)); #endif - free( appId ); + free(appId); } #endif } void Adaptor::SetupSystemInformation() { - if( system_settings_add_changed_cb( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, OnSystemLanguageChanged, this ) != SYSTEM_SETTINGS_ERROR_NONE ) + if(system_settings_add_changed_cb(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, OnSystemLanguageChanged, this) != SYSTEM_SETTINGS_ERROR_NONE) { - DALI_LOG_ERROR( "DALI system_settings_add_changed_cb failed.\n" ); + DALI_LOG_ERROR("DALI system_settings_add_changed_cb failed.\n"); return; } char* locale = NULL; - if( system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale ) != SYSTEM_SETTINGS_ERROR_NONE || - locale == NULL ) + if(system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale) != SYSTEM_SETTINGS_ERROR_NONE || + locale == NULL) { - DALI_LOG_ERROR( "DALI OnSystemLanguageChanged failed " ); + DALI_LOG_ERROR("DALI OnSystemLanguageChanged failed "); return; } - SetRootLayoutDirection( locale ); - - free( locale ); + SetRootLayoutDirection(locale); + free(locale); } } // namespace Adaptor diff --git a/dali/internal/adaptor/tizen-wayland/component-application-impl.cpp b/dali/internal/adaptor/tizen-wayland/component-application-impl.cpp index bf3855c..e5bb71a 100644 --- a/dali/internal/adaptor/tizen-wayland/component-application-impl.cpp +++ b/dali/internal/adaptor/tizen-wayland/component-application-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,23 +20,21 @@ namespace Dali { - namespace Internal { - namespace Adaptor { ComponentApplicationPtr ComponentApplication::New( - int* argc, - char **argv[], - const std::string& stylesheet, + int* argc, + char** argv[], + const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode) { - ComponentApplicationPtr application ( new ComponentApplication (argc, argv, stylesheet, windowMode ) ); + ComponentApplicationPtr application(new ComponentApplication(argc, argv, stylesheet, windowMode)); return application; } -ComponentApplication::ComponentApplication( int* argc, char** argv[], const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode ) +ComponentApplication::ComponentApplication(int* argc, char** argv[], const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode) : Application(argc, argv, stylesheet, windowMode, PositionSize(), Framework::COMPONENT) { } diff --git a/dali/internal/adaptor/tizen-wayland/component-application-impl.h b/dali/internal/adaptor/tizen-wayland/component-application-impl.h index bf726ff..b84104b 100644 --- a/dali/internal/adaptor/tizen-wayland/component-application-impl.h +++ b/dali/internal/adaptor/tizen-wayland/component-application-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_COMPONENT_APPLICATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,10 +28,8 @@ class Adaptor; namespace Internal { - namespace Adaptor { - class ComponentApplication; typedef IntrusivePtr ComponentApplicationPtr; @@ -52,17 +50,17 @@ public: * @param[in] windowMode A member of WINDOW_MODE * @return A handle to the ComponentApplication */ - static ComponentApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode ); + static ComponentApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet, WINDOW_MODE windowMode); /** * @brief The default constructor. */ - ComponentApplication( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode ); + ComponentApplication(int* argc, char** argv[], const std::string& stylesheet, WINDOW_MODE windowMode); /** * @brief Undefined copy constructor. */ - ComponentApplication( const ComponentApplication& ) = default; + ComponentApplication(const ComponentApplication&) = default; /** * @brief Destructor @@ -72,16 +70,16 @@ public: /** *@brief Undefined assignment operator. */ - ComponentApplication& operator=( const ComponentApplication& ) = delete; + ComponentApplication& operator=(const ComponentApplication&) = delete; -public: // From Framework::Observer +public: // From Framework::Observer /** * Called when the framework is Component Application Created. */ Any OnCreate() override; public: - CreateSignal mCreateSignal; + CreateSignal mCreateSignal; }; inline ComponentApplication& GetImplementation(Dali::ComponentApplication& application) @@ -102,7 +100,6 @@ inline const ComponentApplication& GetImplementation(const Dali::ComponentApplic return static_cast(handle); } - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/adaptor/tizen-wayland/component-application.cpp b/dali/internal/adaptor/tizen-wayland/component-application.cpp index c1e0761..a04f8a3 100644 --- a/dali/internal/adaptor/tizen-wayland/component-application.cpp +++ b/dali/internal/adaptor/tizen-wayland/component-application.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,20 +23,19 @@ namespace Dali { - ComponentApplication ComponentApplication::New() { - return New( NULL, NULL ); + return New(NULL, NULL); } -ComponentApplication ComponentApplication::New( int* argc, char **argv[] ) +ComponentApplication ComponentApplication::New(int* argc, char** argv[]) { - return New( argc, argv, "" ); + return New(argc, argv, ""); } -ComponentApplication ComponentApplication::New( int* argc, char **argv[], const std::string& stylesheet ) +ComponentApplication ComponentApplication::New(int* argc, char** argv[], const std::string& stylesheet) { - Internal::Adaptor::ComponentApplicationPtr internal = Internal::Adaptor::ComponentApplication::New( argc, argv, stylesheet, TRANSPARENT ); + Internal::Adaptor::ComponentApplicationPtr internal = Internal::Adaptor::ComponentApplication::New(argc, argv, stylesheet, TRANSPARENT); return ComponentApplication(internal.Get()); } diff --git a/dali/internal/adaptor/tizen-wayland/dali-ecore-wayland.h b/dali/internal/adaptor/tizen-wayland/dali-ecore-wayland.h index 6eb6038..6820d6c 100644 --- a/dali/internal/adaptor/tizen-wayland/dali-ecore-wayland.h +++ b/dali/internal/adaptor/tizen-wayland/dali-ecore-wayland.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_TIZEN_WAYLAND_DALI_ECORE_WAYLAND_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_ADAPTOR_TIZEN_WAYLAND_DALI_ECORE_WAYLAND_H */ diff --git a/dali/internal/adaptor/tizen-wayland/dali-ecore-wl2.h b/dali/internal/adaptor/tizen-wayland/dali-ecore-wl2.h index c733e31..eeb5398 100644 --- a/dali/internal/adaptor/tizen-wayland/dali-ecore-wl2.h +++ b/dali/internal/adaptor/tizen-wayland/dali-ecore-wl2.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_TIZEN_WAYLAND_DALI_ECORE_WL2_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_ADAPTOR_TIZEN_WAYLAND_DALI_ECORE_WL2_H */ diff --git a/dali/internal/adaptor/tizen-wayland/framework-tizen.cpp b/dali/internal/adaptor/tizen-wayland/framework-tizen.cpp index 1301b71..7cb27c2 100644 --- a/dali/internal/adaptor/tizen-wayland/framework-tizen.cpp +++ b/dali/internal/adaptor/tizen-wayland/framework-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,15 +19,15 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include +#include #include #include +#include #include #include -#include #include // CONDITIONAL INCLUDES #ifdef APPCORE_WATCH_AVAILABLE @@ -37,7 +37,7 @@ #include #endif // DALI_ELDBUS_AVAILABLE -#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED +#if defined(TIZEN_PLATFORM_CONFIG_SUPPORTED) && TIZEN_PLATFORM_CONFIG_SUPPORTED #include #endif // TIZEN_PLATFORM_CONFIG_SUPPORTED @@ -52,24 +52,21 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) -Integration::Log::Filter* gDBusLogging = Integration::Log::Filter::New( Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DBUS" ); +Integration::Log::Filter* gDBusLogging = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_ADAPTOR_EVENTS_DBUS"); #endif bool IsWidgetFeatureEnabled() { - static bool feature = false; + static bool feature = false; static bool retrieved = false; - int ret; + int ret; if(retrieved == true) { @@ -91,7 +88,6 @@ bool IsWidgetFeatureEnabled() namespace AppCore { - typedef enum { LOW_MEMORY, //< The low memory event @@ -104,66 +100,66 @@ typedef enum } AppEventType; static int AppEventConverter[APPCORE_BASE_EVENT_MAX] = -{ - [LOW_MEMORY] = APPCORE_BASE_EVENT_LOW_MEMORY, - [LOW_BATTERY] = APPCORE_BASE_EVENT_LOW_BATTERY, - [LANGUAGE_CHANGED] = APPCORE_BASE_EVENT_LANG_CHANGE, - [DEVICE_ORIENTATION_CHANGED] = APPCORE_BASE_EVENT_DEVICE_ORIENTATION_CHANGED, - [REGION_FORMAT_CHANGED] = APPCORE_BASE_EVENT_REGION_CHANGE, - [SUSPENDED_STATE_CHANGED] = APPCORE_BASE_EVENT_SUSPENDED_STATE_CHANGE, + { + [LOW_MEMORY] = APPCORE_BASE_EVENT_LOW_MEMORY, + [LOW_BATTERY] = APPCORE_BASE_EVENT_LOW_BATTERY, + [LANGUAGE_CHANGED] = APPCORE_BASE_EVENT_LANG_CHANGE, + [DEVICE_ORIENTATION_CHANGED] = APPCORE_BASE_EVENT_DEVICE_ORIENTATION_CHANGED, + [REGION_FORMAT_CHANGED] = APPCORE_BASE_EVENT_REGION_CHANGE, + [SUSPENDED_STATE_CHANGED] = APPCORE_BASE_EVENT_SUSPENDED_STATE_CHANGE, }; struct AppEventInfo { AppEventType type; - void *value; + void* value; }; -typedef struct AppEventInfo *AppEventInfoPtr; +typedef struct AppEventInfo* AppEventInfoPtr; -typedef void (*AppEventCallback)(AppEventInfoPtr eventInfo, void *userData); +typedef void (*AppEventCallback)(AppEventInfoPtr eventInfo, void* userData); struct AppEventHandler { - AppEventType type; + AppEventType type; AppEventCallback cb; - void *data; - void *raw; + void* data; + void* raw; }; -typedef struct AppEventHandler *AppEventHandlerPtr; +typedef struct AppEventHandler* AppEventHandlerPtr; -int EventCallback(void *event, void *data) +int EventCallback(void* event, void* data) { AppEventHandlerPtr handler = static_cast(data); struct AppEventInfo appEvent; - appEvent.type = handler->type; + appEvent.type = handler->type; appEvent.value = event; - if (handler->cb) + if(handler->cb) handler->cb(&appEvent, handler->data); return 0; } -int AppAddEventHandler(AppEventHandlerPtr *eventHandler, AppEventType eventType, AppEventCallback callback, void *userData) +int AppAddEventHandler(AppEventHandlerPtr* eventHandler, AppEventType eventType, AppEventCallback callback, void* userData) { AppEventHandlerPtr handler; - handler = static_cast( calloc(1, sizeof(struct AppEventHandler)) ); - if (!handler) + handler = static_cast(calloc(1, sizeof(struct AppEventHandler))); + if(!handler) { - DALI_LOG_ERROR( "failed to create handler" ); + DALI_LOG_ERROR("failed to create handler"); return TIZEN_ERROR_UNKNOWN; } else { handler->type = eventType; - handler->cb = callback; + handler->cb = callback; handler->data = userData; - handler->raw = appcore_base_add_event( static_cast(AppEventConverter[static_cast(eventType)]), EventCallback, handler); + handler->raw = appcore_base_add_event(static_cast(AppEventConverter[static_cast(eventType)]), EventCallback, handler); *eventHandler = handler; @@ -171,47 +167,48 @@ int AppAddEventHandler(AppEventHandlerPtr *eventHandler, AppEventType eventType, } } -} // namespace Appcore +} // namespace AppCore /** * Impl to hide EFL data members */ struct Framework::Impl { -// Constructor - Impl(void* data, Type type ) - : mAbortCallBack( NULL ), - mCallbackManager( NULL ) + // Constructor + Impl(void* data, Type type) + : mAbortCallBack(NULL), + mCallbackManager(NULL) #ifdef APPCORE_WATCH_AVAILABLE - , mWatchCallback() + , + mWatchCallback() #endif { mFramework = static_cast(data); #ifndef APPCORE_WATCH_AVAILABLE - if ( type == WATCH ) + if(type == WATCH) { - throw Dali::DaliException( "", "Watch Application is not supported." ); + throw Dali::DaliException("", "Watch Application is not supported."); } #endif mApplicationType = type; mCallbackManager = CallbackManager::New(); - char* region = nullptr; + char* region = nullptr; char* language = nullptr; - system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_COUNTRY, ®ion ); - system_settings_get_value_string( SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &language ); + system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_COUNTRY, ®ion); + system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &language); - if (region != nullptr) + if(region != nullptr) { - mRegion = std::string( region ); - free( region ); + mRegion = std::string(region); + free(region); } - if ( language != nullptr) + if(language != nullptr) { - mLanguage = std::string( language ); - free( language ); + mLanguage = std::string(language); + free(language); } } @@ -228,7 +225,7 @@ struct Framework::Impl int AppMain() { int ret; - switch ( mApplicationType ) + switch(mApplicationType) { case NORMAL: { @@ -258,7 +255,7 @@ struct Framework::Impl void AppExit() { - switch ( mApplicationType ) + switch(mApplicationType) { case NORMAL: { @@ -285,12 +282,12 @@ struct Framework::Impl } } - void SetLanguage( const std::string& language ) + void SetLanguage(const std::string& language) { mLanguage = language; } - void SetRegion( const std::string& region ) + void SetRegion(const std::string& region) { mRegion = region; } @@ -306,56 +303,56 @@ struct Framework::Impl } // Data - Type mApplicationType; - CallbackBase* mAbortCallBack; - CallbackManager *mCallbackManager; - std::string mLanguage; - std::string mRegion; + Type mApplicationType; + CallbackBase* mAbortCallBack; + CallbackManager* mCallbackManager; + std::string mLanguage; + std::string mRegion; - Framework* mFramework; + Framework* mFramework; AppCore::AppEventHandlerPtr handlers[5]; #ifdef APPCORE_WATCH_AVAILABLE watch_app_lifecycle_callback_s mWatchCallback; - app_event_handler_h watchHandlers[5]; + app_event_handler_h watchHandlers[5]; #endif - static int AppCreate(void *data) + static int AppCreate(void* data) { appcore_ui_base_on_create(); - return static_cast( static_cast(data)->Create() ); + return static_cast(static_cast(data)->Create()); } - static int AppTerminate(void *data) + static int AppTerminate(void* data) { appcore_ui_base_on_terminate(); - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnTerminate(); return 0; } - static int AppPause(void *data) + static int AppPause(void* data) { appcore_ui_base_on_pause(); - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnPause(); return 0; } - static int AppResume(void *data) + static int AppResume(void* data) { appcore_ui_base_on_resume(); - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnResume(); return 0; } - static void ProcessBundle(Framework* framework, bundle *bundleData) + static void ProcessBundle(Framework* framework, bundle* bundleData) { if(bundleData == NULL) { @@ -381,29 +378,29 @@ struct Framework::Impl * Called by AppCore when the application is launched from another module (e.g. homescreen). * @param[in] b the bundle data which the launcher module sent */ - static int AppControl(bundle* bundleData, void *data) + static int AppControl(bundle* bundleData, void* data) { app_control_h appControl = NULL; appcore_ui_base_on_control(bundleData); - if (bundleData) + if(bundleData) { - if (app_control_create_event(bundleData, &appControl) != TIZEN_ERROR_NONE) + if(app_control_create_event(bundleData, &appControl) != TIZEN_ERROR_NONE) { DALI_LOG_ERROR("Failed to create an app_control handle"); } } else { - if (app_control_create(&appControl) != TIZEN_ERROR_NONE) + if(app_control_create(&appControl) != TIZEN_ERROR_NONE) { DALI_LOG_ERROR("Failed to create an app_control handle"); } } Framework* framework = static_cast(data); - Observer *observer = &framework->mObserver; + Observer* observer = &framework->mObserver; ProcessBundle(framework, bundleData); @@ -415,13 +412,13 @@ struct Framework::Impl return 0; } - static void AppInit(int argc, char **argv, void *data) + static void AppInit(int argc, char** argv, void* data) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" ecore_init(); - ecore_app_args_set( argc, (const char **)argv ); + ecore_app_args_set(argc, (const char**)argv); #pragma GCC diagnostic pop } @@ -437,60 +434,60 @@ struct Framework::Impl } } - static void AppRun(void *data) + static void AppRun(void* data) { ecore_main_loop_begin(); } - static void AppExit(void *data) + static void AppExit(void* data) { ecore_main_loop_quit(); } - static void AppLanguageChanged(AppCore::AppEventInfoPtr event, void *data) + static void AppLanguageChanged(AppCore::AppEventInfoPtr event, void* data) { Framework* framework = static_cast(data); - Observer *observer = &framework->mObserver; + Observer* observer = &framework->mObserver; - if( event && event->value ) + if(event && event->value) { - framework->SetLanguage( std::string( static_cast(event->value) ) ); + framework->SetLanguage(std::string(static_cast(event->value))); observer->OnLanguageChanged(); } else { - DALI_LOG_ERROR( "NULL pointer in Language changed event\n" ); + DALI_LOG_ERROR("NULL pointer in Language changed event\n"); } } - static void AppDeviceRotated(AppCore::AppEventInfoPtr event_info, void *data) + static void AppDeviceRotated(AppCore::AppEventInfoPtr event_info, void* data) { } - static void AppRegionChanged(AppCore::AppEventInfoPtr event, void *data) + static void AppRegionChanged(AppCore::AppEventInfoPtr event, void* data) { Framework* framework = static_cast(data); - Observer *observer = &framework->mObserver; + Observer* observer = &framework->mObserver; - if( event && event->value ) + if(event && event->value) { - framework->SetRegion( std::string( static_cast(event->value) ) ); + framework->SetRegion(std::string(static_cast(event->value))); observer->OnRegionChanged(); } else { - DALI_LOG_ERROR( "NULL pointer in Region changed event\n" ); + DALI_LOG_ERROR("NULL pointer in Region changed event\n"); } } - static void AppBatteryLow(AppCore::AppEventInfoPtr event, void *data) + static void AppBatteryLow(AppCore::AppEventInfoPtr event, void* data) { - Observer *observer = &static_cast(data)->mObserver; - int status = *static_cast(event->value); - Dali::DeviceStatus::Battery::Status result = Dali::DeviceStatus::Battery::NORMAL; + Observer* observer = &static_cast(data)->mObserver; + int status = *static_cast(event->value); + Dali::DeviceStatus::Battery::Status result = Dali::DeviceStatus::Battery::NORMAL; // convert to dali battery status - switch( status ) + switch(status) { case 1: { @@ -502,20 +499,20 @@ struct Framework::Impl result = Dali::DeviceStatus::Battery::CRITICALLY_LOW; break; } - default : + default: break; } observer->OnBatteryLow(result); } - static void AppMemoryLow(AppCore::AppEventInfoPtr event, void *data) + static void AppMemoryLow(AppCore::AppEventInfoPtr event, void* data) { - Observer *observer = &static_cast(data)->mObserver; - int status = *static_cast(event->value); - Dali::DeviceStatus::Memory::Status result = Dali::DeviceStatus::Memory::NORMAL; + Observer* observer = &static_cast(data)->mObserver; + int status = *static_cast(event->value); + Dali::DeviceStatus::Memory::Status result = Dali::DeviceStatus::Memory::NORMAL; // convert to dali memmory status - switch( status ) + switch(status) { case 1: { @@ -532,13 +529,12 @@ struct Framework::Impl result = Dali::DeviceStatus::Memory::CRITICALLY_LOW; break; } - default : + default: break; } observer->OnMemoryLow(result); } - int AppNormalMain() { int ret; @@ -552,23 +548,19 @@ struct Framework::Impl appcore_ui_base_ops ops = appcore_ui_base_get_default_ops(); /* override methods */ - ops.base.create = AppCreate; - ops.base.control = AppControl; + ops.base.create = AppCreate; + ops.base.control = AppControl; ops.base.terminate = AppTerminate; - ops.pause = AppPause; - ops.resume = AppResume; - ops.base.init = AppInit; - ops.base.finish = AppFinish; - ops.base.run = AppRun; - ops.base.exit = AppExit; - - ret = appcore_ui_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework, APPCORE_UI_BASE_HINT_WINDOW_GROUP_CONTROL | - APPCORE_UI_BASE_HINT_WINDOW_STACK_CONTROL | - APPCORE_UI_BASE_HINT_BG_LAUNCH_CONTROL | - APPCORE_UI_BASE_HINT_HW_ACC_CONTROL | - APPCORE_UI_BASE_HINT_WINDOW_AUTO_CONTROL ); - - if (ret != TIZEN_ERROR_NONE) + ops.pause = AppPause; + ops.resume = AppResume; + ops.base.init = AppInit; + ops.base.finish = AppFinish; + ops.base.run = AppRun; + ops.base.exit = AppExit; + + ret = appcore_ui_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework, APPCORE_UI_BASE_HINT_WINDOW_GROUP_CONTROL | APPCORE_UI_BASE_HINT_WINDOW_STACK_CONTROL | APPCORE_UI_BASE_HINT_BG_LAUNCH_CONTROL | APPCORE_UI_BASE_HINT_HW_ACC_CONTROL | APPCORE_UI_BASE_HINT_WINDOW_AUTO_CONTROL); + + if(ret != TIZEN_ERROR_NONE) return ret; appcore_ui_base_fini(); @@ -586,15 +578,15 @@ struct Framework::Impl widget_base_exit(); } - static int WidgetAppCreate( void *data ) + static int WidgetAppCreate(void* data) { widget_base_on_create(); - return static_cast( static_cast(data)->Create() ); + return static_cast(static_cast(data)->Create()); } - static int WidgetAppTerminate( void *data ) + static int WidgetAppTerminate(void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnTerminate(); widget_base_on_terminate(); @@ -603,7 +595,7 @@ struct Framework::Impl int AppWidgetMain() { - if( !IsWidgetFeatureEnabled() ) + if(!IsWidgetFeatureEnabled()) { DALI_LOG_ERROR("widget feature is not supported"); return 0; @@ -618,12 +610,12 @@ struct Framework::Impl widget_base_ops ops = widget_base_get_default_ops(); /* override methods */ - ops.create = WidgetAppCreate; + ops.create = WidgetAppCreate; ops.terminate = WidgetAppTerminate; - ops.init = AppInit; - ops.finish = AppFinish; - ops.run = AppRun; - ops.exit = AppExit; + ops.init = AppInit; + ops.finish = AppFinish; + ops.run = AppRun; + ops.exit = AppExit; int result = widget_base_init(ops, *mFramework->mArgc, *mFramework->mArgv, mFramework); @@ -633,39 +625,39 @@ struct Framework::Impl } #ifdef APPCORE_WATCH_AVAILABLE - static bool WatchAppCreate(int width, int height, void *data) + static bool WatchAppCreate(int width, int height, void* data) { return static_cast(data)->Create(); } - static void WatchAppTimeTick(watch_time_h time, void *data) + static void WatchAppTimeTick(watch_time_h time, void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; WatchTime curTime(time); observer->OnTimeTick(curTime); } - static void WatchAppAmbientTick(watch_time_h time, void *data) + static void WatchAppAmbientTick(watch_time_h time, void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; WatchTime curTime(time); observer->OnAmbientTick(curTime); } - static void WatchAppAmbientChanged(bool ambient, void *data) + static void WatchAppAmbientChanged(bool ambient, void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnAmbientChanged(ambient); } - static void WatchAppControl(app_control_h app_control, void *data) + static void WatchAppControl(app_control_h app_control, void* data) { - Framework* framework = static_cast(data); - Observer *observer = &framework->mObserver; - bundle *bundleData = NULL; + Framework* framework = static_cast(data); + Observer* observer = &framework->mObserver; + bundle* bundleData = NULL; app_control_to_bundle(app_control, &bundleData); ProcessBundle(framework, bundleData); @@ -674,23 +666,23 @@ struct Framework::Impl observer->OnAppControl(app_control); } - static void WatchAppTerminate(void *data) + static void WatchAppTerminate(void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnTerminate(); } - static void WatchAppPause(void *data) + static void WatchAppPause(void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnPause(); } - static void WatchAppResume(void *data) + static void WatchAppResume(void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnResume(); } @@ -702,13 +694,13 @@ struct Framework::Impl int ret = true; #ifdef APPCORE_WATCH_AVAILABLE - mWatchCallback.create = WatchAppCreate; - mWatchCallback.app_control = WatchAppControl; - mWatchCallback.terminate = WatchAppTerminate; - mWatchCallback.pause = WatchAppPause; - mWatchCallback.resume = WatchAppResume; - mWatchCallback.time_tick = WatchAppTimeTick; - mWatchCallback.ambient_tick = WatchAppAmbientTick; + mWatchCallback.create = WatchAppCreate; + mWatchCallback.app_control = WatchAppControl; + mWatchCallback.terminate = WatchAppTerminate; + mWatchCallback.pause = WatchAppPause; + mWatchCallback.resume = WatchAppResume; + mWatchCallback.time_tick = WatchAppTimeTick; + mWatchCallback.ambient_tick = WatchAppAmbientTick; mWatchCallback.ambient_changed = WatchAppAmbientChanged; AppCore::AppAddEventHandler(&handlers[AppCore::LOW_BATTERY], AppCore::LOW_BATTERY, AppBatteryLow, mFramework); @@ -735,32 +727,33 @@ struct Framework::Impl /*Crate component_based_app_base_lifecycle_callback*/ component_based_app_base_lifecycle_callback_s callback; - callback.init = AppInit; - callback.run = AppRun; - callback.exit = AppExit; - callback.create = ComponentAppCreate; + callback.init = AppInit; + callback.run = AppRun; + callback.exit = AppExit; + callback.create = ComponentAppCreate; callback.terminate = ComponentAppTerminate; - callback.fini = ComponentAppFinish; + callback.fini = ComponentAppFinish; - return component_based_app_base_main(*mFramework->mArgc, *mFramework->mArgv, &callback, mFramework);; + return component_based_app_base_main(*mFramework->mArgc, *mFramework->mArgv, &callback, mFramework); + ; } - static void* ComponentAppCreate( void *data ) + static void* ComponentAppCreate(void* data) { Framework* framework = static_cast(data); - Observer *observer = &framework->mObserver; + Observer* observer = &framework->mObserver; observer->OnInit(); - return Dali::AnyCast( observer->OnCreate() ); + return Dali::AnyCast(observer->OnCreate()); } - static void ComponentAppTerminate( void *data ) + static void ComponentAppTerminate(void* data) { - Observer *observer = &static_cast(data)->mObserver; + Observer* observer = &static_cast(data)->mObserver; observer->OnTerminate(); } - static void ComponentAppFinish( void *data ) + static void ComponentAppFinish(void* data) { ecore_shutdown(); @@ -780,13 +773,13 @@ struct Framework::Impl private: // Undefined - Impl( const Impl& impl ); + Impl(const Impl& impl); // Undefined - Impl& operator=( const Impl& impl ); + Impl& operator=(const Impl& impl); }; -Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type ) +Framework::Framework(Framework::Observer& observer, int* argc, char*** argv, Type type) : mObserver(observer), mInitialised(false), mPaused(false), @@ -795,19 +788,19 @@ Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Ty mArgv(argv), mBundleName(""), mBundleId(""), - mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ), + mAbortHandler(MakeCallback(this, &Framework::AbortCallback)), mImpl(NULL) { bool featureFlag = true; - system_info_get_platform_bool( "tizen.org/feature/opengles.version.2_0", &featureFlag ); + system_info_get_platform_bool("tizen.org/feature/opengles.version.2_0", &featureFlag); - if( featureFlag == false ) + if(featureFlag == false) { - set_last_result( TIZEN_ERROR_NOT_SUPPORTED ); + set_last_result(TIZEN_ERROR_NOT_SUPPORTED); } #ifdef DALI_ELDBUS_AVAILABLE // Initialize ElDBus. - DALI_LOG_INFO( gDBusLogging, Debug::General, "Starting DBus Initialization\n" ); + DALI_LOG_INFO(gDBusLogging, Debug::General, "Starting DBus Initialization\n"); eldbus_init(); #endif InitThreads(); @@ -817,14 +810,14 @@ Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Ty Framework::~Framework() { - if (mRunning) + if(mRunning) { Quit(); } #ifdef DALI_ELDBUS_AVAILABLE // Shutdown ELDBus. - DALI_LOG_INFO( gDBusLogging, Debug::General, "Shutting down DBus\n" ); + DALI_LOG_INFO(gDBusLogging, Debug::General, "Shutting down DBus\n"); eldbus_shutdown(); #endif @@ -844,7 +837,7 @@ void Framework::Run() int ret; ret = mImpl->AppMain(); - if (ret != APP_ERROR_NONE) + if(ret != APP_ERROR_NONE) { DALI_LOG_ERROR("Framework::Run(), ui_app_main() is failed. err = %d\n", ret); } @@ -861,7 +854,7 @@ bool Framework::IsMainLoopRunning() return mRunning; } -void Framework::AddAbortCallback( CallbackBase* callback ) +void Framework::AddAbortCallback(CallbackBase* callback) { mImpl->mAbortCallBack = callback; } @@ -884,9 +877,9 @@ std::string Framework::GetBundleId() const std::string Framework::GetResourcePath() { std::string resourcePath = ""; -#if defined( TIZEN_PLATFORM_CONFIG_SUPPORTED ) && TIZEN_PLATFORM_CONFIG_SUPPORTED +#if defined(TIZEN_PLATFORM_CONFIG_SUPPORTED) && TIZEN_PLATFORM_CONFIG_SUPPORTED char* app_rsc_path = app_get_resource_path(); - if (app_rsc_path) + if(app_rsc_path) { resourcePath = app_rsc_path; free(app_rsc_path); @@ -895,15 +888,15 @@ std::string Framework::GetResourcePath() // "DALI_APPLICATION_PACKAGE" is used to get the already configured Application package path. const char* environmentVariable = "DALI_APPLICATION_PACKAGE"; - char* value = getenv( environmentVariable ); - if ( value != NULL ) + char* value = getenv(environmentVariable); + if(value != NULL) { resourcePath = value; } - if( resourcePath.back() != '/' ) + if(resourcePath.back() != '/') { - resourcePath+="/"; + resourcePath += "/"; } #endif //TIZEN_PLATFORM_CONFIG_SUPPORTED @@ -914,8 +907,8 @@ std::string Framework::GetResourcePath() std::string Framework::GetDataPath() { std::string result; - char* dataPath = app_get_data_path(); - if( dataPath ) + char* dataPath = app_get_data_path(); + if(dataPath) { result = dataPath; free(dataPath); @@ -928,12 +921,12 @@ void Framework::SetBundleId(const std::string& id) mBundleId = id; } -void Framework::AbortCallback( ) +void Framework::AbortCallback() { // if an abort call back has been installed run it. - if (mImpl->mAbortCallBack) + if(mImpl->mAbortCallBack) { - CallbackBase::Execute( *mImpl->mAbortCallBack ); + CallbackBase::Execute(*mImpl->mAbortCallBack); } else { @@ -945,14 +938,14 @@ void Framework::InitThreads() { } -void Framework::SetLanguage( const std::string& language ) +void Framework::SetLanguage(const std::string& language) { - mImpl->SetLanguage( language ); + mImpl->SetLanguage(language); } -void Framework::SetRegion( const std::string& region ) +void Framework::SetRegion(const std::string& region) { - mImpl->SetRegion( region ); + mImpl->SetRegion(region); } std::string Framework::GetLanguage() const diff --git a/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.cpp b/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.cpp index f937172..4a03a7e 100644 --- a/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.cpp +++ b/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,38 +24,34 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - unsigned int GetEnvWatchRenderRefreshRate() { - const char* envVariable = std::getenv( DALI_WATCH_REFRESH_RATE ); + const char* envVariable = std::getenv(DALI_WATCH_REFRESH_RATE); - return envVariable ? std::atoi( envVariable ) : 2u; // Default 30 fps + return envVariable ? std::atoi(envVariable) : 2u; // Default 30 fps } } // unnamed namespace WatchApplicationPtr WatchApplication::New( - int* argc, - char **argv[], - const std::string& stylesheet, + int* argc, + char** argv[], + const std::string& stylesheet, Dali::WatchApplication::WINDOW_MODE windowMode) { - WatchApplicationPtr watch ( new WatchApplication (argc, argv, stylesheet, windowMode ) ); + WatchApplicationPtr watch(new WatchApplication(argc, argv, stylesheet, windowMode)); return watch; } -WatchApplication::WatchApplication( int* argc, char** argv[], const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode ) +WatchApplication::WatchApplication(int* argc, char** argv[], const std::string& stylesheet, Dali::Application::WINDOW_MODE windowMode) : Application(argc, argv, stylesheet, windowMode, PositionSize(), Framework::WATCH), - mState( UNINITIALIZED ) + mState(UNINITIALIZED) { } @@ -67,7 +63,7 @@ void WatchApplication::OnInit() { Application::OnInit(); - Dali::Adaptor::Get().SetRenderRefreshRate( GetEnvWatchRenderRefreshRate() ); + Dali::Adaptor::Get().SetRenderRefreshRate(GetEnvWatchRenderRefreshRate()); mState = INITIALIZED; } @@ -96,35 +92,35 @@ void WatchApplication::OnPause() void WatchApplication::OnTimeTick(WatchTime& time) { Dali::WatchApplication watch(this); - mTickSignal.Emit( watch, time ); + mTickSignal.Emit(watch, time); if(mState == PAUSED) { // This is a pre-resume scenario. All rendering engine of tizen SHOULD forcely update once at this time. - Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() ).RequestUpdateOnce(); + Internal::Adaptor::Adaptor::GetImplementation(GetAdaptor()).RequestUpdateOnce(); } // A watch application will queue messages to update the UI in the signal emitted above // Process these immediately to avoid a blinking issue where the old time is briefly visible - CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() ); + CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation(GetAdaptor()); eventInterface.ProcessCoreEvents(); } void WatchApplication::OnAmbientTick(WatchTime& time) { Dali::WatchApplication watch(this); - mAmbientTickSignal.Emit( watch, time ); + mAmbientTickSignal.Emit(watch, time); // A watch application will queue messages to update the UI in the signal emitted above // Process these immediately to avoid a blinking issue where the old time is briefly visible - CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation( GetAdaptor() ); + CoreEventInterface& eventInterface = Internal::Adaptor::Adaptor::GetImplementation(GetAdaptor()); eventInterface.ProcessCoreEvents(); } void WatchApplication::OnAmbientChanged(bool ambient) { Dali::WatchApplication watch(this); - mAmbientChangeSignal.Emit( watch, ambient ); + mAmbientChangeSignal.Emit(watch, ambient); } } // namespace Adaptor diff --git a/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.h b/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.h index 2117e16..dbae797 100644 --- a/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.h +++ b/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WATCH_APPLICATION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -28,10 +28,8 @@ class Adaptor; namespace Internal { - namespace Adaptor { - class WatchApplication; typedef IntrusivePtr WatchApplicationPtr; @@ -60,7 +58,7 @@ public: * @param[in] stylesheet The path to user defined theme file * @param[in] windowMode A member of Dali::Watch::WINDOW_MODE */ - static WatchApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode ); + static WatchApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet, WINDOW_MODE windowMode); /** * Private Constructor @@ -69,7 +67,7 @@ public: * @param[in] stylesheet The path to user defined theme file * @param[in] windowMode A member of Dali::Watch::WINDOW_MODE */ - WatchApplication( int* argc, char **argv[], const std::string& stylesheet, WINDOW_MODE windowMode ); + WatchApplication(int* argc, char** argv[], const std::string& stylesheet, WINDOW_MODE windowMode); /** * Destructor @@ -112,22 +110,20 @@ public: void OnAmbientChanged(bool ambient); private: - // @brief Undefined copy constructor. - WatchApplication( const WatchApplication& ); + WatchApplication(const WatchApplication&); // @brief Undefined assignment operator. - WatchApplication& operator=( const WatchApplication& ); + WatchApplication& operator=(const WatchApplication&); public: - // Signals - WatchTimeSignal mTickSignal; - WatchTimeSignal mAmbientTickSignal; - WatchBoolSignal mAmbientChangeSignal; + WatchTimeSignal mTickSignal; + WatchTimeSignal mAmbientTickSignal; + WatchBoolSignal mAmbientChangeSignal; private: - WatchApplicationState mState; + WatchApplicationState mState; }; inline WatchApplication& GetImplementation(Dali::WatchApplication& watch) @@ -148,7 +144,6 @@ inline const WatchApplication& GetImplementation(const Dali::WatchApplication& w return static_cast(handle); } - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application.cpp b/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application.cpp index b449c67..89b93f1 100644 --- a/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application.cpp +++ b/dali/internal/adaptor/tizen-wayland/tizen-wearable/watch-application.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,21 +26,20 @@ namespace Dali { - WatchApplication WatchApplication::New() { - return New( NULL, NULL ); + return New(NULL, NULL); } -WatchApplication WatchApplication::New( int* argc, char **argv[] ) +WatchApplication WatchApplication::New(int* argc, char** argv[]) { - Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New( argc, argv, "", OPAQUE ); + Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New(argc, argv, "", OPAQUE); return WatchApplication(internal.Get()); } -WatchApplication WatchApplication::New( int* argc, char **argv[], const std::string& stylesheet ) +WatchApplication WatchApplication::New(int* argc, char** argv[], const std::string& stylesheet) { - Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New( argc, argv, stylesheet, OPAQUE ); + Internal::Adaptor::WatchApplicationPtr internal = Internal::Adaptor::WatchApplication::New(argc, argv, stylesheet, OPAQUE); return WatchApplication(internal.Get()); } @@ -52,13 +51,13 @@ WatchApplication::WatchApplication() { } -WatchApplication::WatchApplication( const WatchApplication& copy ) = default; +WatchApplication::WatchApplication(const WatchApplication& copy) = default; -WatchApplication& WatchApplication::operator=( const WatchApplication& rhs ) = default; +WatchApplication& WatchApplication::operator=(const WatchApplication& rhs) = default; -WatchApplication::WatchApplication( WatchApplication&& rhs ) = default; +WatchApplication::WatchApplication(WatchApplication&& rhs) = default; -WatchApplication& WatchApplication::operator=( WatchApplication&& rhs ) = default; +WatchApplication& WatchApplication::operator=(WatchApplication&& rhs) = default; WatchApplication::WatchTimeSignal& WatchApplication::TimeTickSignal() { @@ -80,5 +79,4 @@ WatchApplication::WatchApplication(Internal::Adaptor::WatchApplication* implemen { } - } // namespace Dali diff --git a/dali/internal/adaptor/ubuntu/framework-ubuntu.cpp b/dali/internal/adaptor/ubuntu/framework-ubuntu.cpp index fe29484..a0d1c15 100644 --- a/dali/internal/adaptor/ubuntu/framework-ubuntu.cpp +++ b/dali/internal/adaptor/ubuntu/framework-ubuntu.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ #include // EXTERNAL INCLUDES +#include #include #include -#include #include @@ -30,16 +30,12 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - /// Application Status Enum enum { @@ -61,10 +57,10 @@ struct Framework::Impl // Constructor Impl(void* data) - : mAbortCallBack( NULL ), - mCallbackManager( CallbackManager::New() ), - mLanguage( "NOT_SUPPORTED" ), - mRegion( "NOT_SUPPORTED" ) + : mAbortCallBack(NULL), + mCallbackManager(CallbackManager::New()), + mLanguage("NOT_SUPPORTED"), + mRegion("NOT_SUPPORTED") { } @@ -89,17 +85,17 @@ struct Framework::Impl } // Data - CallbackBase* mAbortCallBack; - CallbackManager *mCallbackManager; - std::string mLanguage; - std::string mRegion; + CallbackBase* mAbortCallBack; + CallbackManager* mCallbackManager; + std::string mLanguage; + std::string mRegion; // Static methods /** * Called by AppCore on application creation. */ - static bool AppCreate(void *data) + static bool AppCreate(void* data) { return static_cast(data)->AppStatusHandler(APP_CREATE, NULL); } @@ -107,7 +103,7 @@ struct Framework::Impl /** * Called by AppCore when the application should terminate. */ - static void AppTerminate(void *data) + static void AppTerminate(void* data) { static_cast(data)->AppStatusHandler(APP_TERMINATE, NULL); } @@ -115,7 +111,7 @@ struct Framework::Impl /** * Called by AppCore when the application is paused. */ - static void AppPause(void *data) + static void AppPause(void* data) { static_cast(data)->AppStatusHandler(APP_PAUSE, NULL); } @@ -123,7 +119,7 @@ struct Framework::Impl /** * Called by AppCore when the application is resumed. */ - static void AppResume(void *data) + static void AppResume(void* data) { static_cast(data)->AppStatusHandler(APP_RESUME, NULL); } @@ -135,10 +131,9 @@ struct Framework::Impl { static_cast(data)->AppStatusHandler(APP_LANGUAGE_CHANGE, NULL); } - }; -Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type ) +Framework::Framework(Framework::Observer& observer, int* argc, char*** argv, Type type) : mObserver(observer), mInitialised(false), mPaused(false), @@ -147,7 +142,7 @@ Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Ty mArgv(argv), mBundleName(""), mBundleId(""), - mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ), + mAbortHandler(MakeCallback(this, &Framework::AbortCallback)), mImpl(NULL) { InitThreads(); @@ -156,7 +151,7 @@ Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Ty Framework::~Framework() { - if (mRunning) + if(mRunning) { Quit(); } @@ -168,7 +163,7 @@ void Framework::Run() { mRunning = true; - elm_init( mArgc ? *mArgc : 0, mArgv ? *mArgv : nullptr ); + elm_init(mArgc ? *mArgc : 0, mArgv ? *mArgv : nullptr); Impl::AppCreate(this); @@ -189,7 +184,7 @@ bool Framework::IsMainLoopRunning() return mRunning; } -void Framework::AddAbortCallback( CallbackBase* callback ) +void Framework::AddAbortCallback(CallbackBase* callback) { mImpl->mAbortCallBack = callback; } @@ -213,16 +208,16 @@ std::string Framework::GetResourcePath() { // "DALI_APPLICATION_PACKAGE" is used by Ubuntu specifically to get the already configured Application package path. const char* ubuntuEnvironmentVariable = "DALI_APPLICATION_PACKAGE"; - char* value = getenv( ubuntuEnvironmentVariable ); + char* value = getenv(ubuntuEnvironmentVariable); std::string resourcePath; - if ( value != NULL ) + if(value != NULL) { resourcePath = value; } - if( resourcePath.back() != '/' ) + if(resourcePath.back() != '/') { - resourcePath+="/"; + resourcePath += "/"; } return resourcePath; @@ -231,9 +226,9 @@ std::string Framework::GetResourcePath() std::string Framework::GetDataPath() { const char* ubuntuEnvironmentVariable = "DALI_APPLICATION_DATA_DIR"; - char* value = getenv( ubuntuEnvironmentVariable ); + char* value = getenv(ubuntuEnvironmentVariable); std::string dataPath; - if ( value != NULL ) + if(value != NULL) { dataPath = value; } @@ -246,12 +241,12 @@ void Framework::SetBundleId(const std::string& id) mBundleId = id; } -void Framework::AbortCallback( ) +void Framework::AbortCallback() { // if an abort call back has been installed run it. - if (mImpl->mAbortCallBack) + if(mImpl->mAbortCallBack) { - CallbackBase::Execute( *mImpl->mAbortCallBack ); + CallbackBase::Execute(*mImpl->mAbortCallBack); } else { @@ -259,9 +254,9 @@ void Framework::AbortCallback( ) } } -bool Framework::AppStatusHandler(int type, void *bundleData) +bool Framework::AppStatusHandler(int type, void* bundleData) { - switch (type) + switch(type) { case APP_CREATE: { diff --git a/dali/internal/adaptor/windows/framework-win.cpp b/dali/internal/adaptor/windows/framework-win.cpp old mode 100755 new mode 100644 index 01c334a..2a5ab92 --- a/dali/internal/adaptor/windows/framework-win.cpp +++ b/dali/internal/adaptor/windows/framework-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,21 +23,17 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - /// Application Status Enum enum { @@ -58,10 +54,10 @@ struct Framework::Impl // Constructor Impl(void* data) - : mAbortCallBack( NULL ), - mCallbackManager( CallbackManager::New() ), - mLanguage( "NOT_SUPPORTED" ), - mRegion( "NOT_SUPPORTED" ) + : mAbortCallBack(NULL), + mCallbackManager(CallbackManager::New()), + mLanguage("NOT_SUPPORTED"), + mRegion("NOT_SUPPORTED") { } @@ -90,7 +86,7 @@ struct Framework::Impl /** * Called by AppCore on application creation. */ - static bool AppCreate(void *data) + static bool AppCreate(void* data) { return static_cast(data)->AppStatusHandler(APP_CREATE, NULL); } @@ -98,7 +94,7 @@ struct Framework::Impl /** * Called by AppCore when the application should terminate. */ - static void AppTerminate(void *data) + static void AppTerminate(void* data) { static_cast(data)->AppStatusHandler(APP_TERMINATE, NULL); } @@ -106,7 +102,7 @@ struct Framework::Impl /** * Called by AppCore when the application is paused. */ - static void AppPause(void *data) + static void AppPause(void* data) { static_cast(data)->AppStatusHandler(APP_PAUSE, NULL); } @@ -114,7 +110,7 @@ struct Framework::Impl /** * Called by AppCore when the application is resumed. */ - static void AppResume(void *data) + static void AppResume(void* data) { static_cast(data)->AppStatusHandler(APP_RESUME, NULL); } @@ -129,13 +125,13 @@ struct Framework::Impl void Run() { - MSG nMsg = { 0 }; + MSG nMsg = {0}; - while (GetMessage(&nMsg, 0, NULL, NULL)) + while(GetMessage(&nMsg, 0, NULL, NULL)) { - if (WIN_CALLBACK_EVENT == nMsg.message) + if(WIN_CALLBACK_EVENT == nMsg.message) { - Dali::CallbackBase *callback = (Dali::CallbackBase*)nMsg.wParam; + Dali::CallbackBase* callback = (Dali::CallbackBase*)nMsg.wParam; Dali::CallbackBase::Execute(*callback); } @@ -144,7 +140,7 @@ struct Framework::Impl mCallbackManager->ClearIdleCallbacks(); - if (WM_CLOSE == nMsg.message) + if(WM_CLOSE == nMsg.message) { break; } @@ -155,16 +151,16 @@ struct Framework::Impl { } - void SetCallbackBase( CallbackBase *base ) + void SetCallbackBase(CallbackBase* base) { mAbortCallBack = base; } bool ExcuteCallback() { - if( NULL != mAbortCallBack ) + if(NULL != mAbortCallBack) { - CallbackBase::Execute( *mAbortCallBack ); + CallbackBase::Execute(*mAbortCallBack); return true; } else @@ -175,20 +171,20 @@ struct Framework::Impl private: // Undefined - Impl( const Impl& impl ) = delete; + Impl(const Impl& impl) = delete; // Undefined - Impl& operator=( const Impl& impl ) = delete; + Impl& operator=(const Impl& impl) = delete; private: // Data - CallbackBase* mAbortCallBack; - CallbackManager *mCallbackManager; - std::string mLanguage; - std::string mRegion; + CallbackBase* mAbortCallBack; + CallbackManager* mCallbackManager; + std::string mLanguage; + std::string mRegion; }; -Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Type type ) +Framework::Framework(Framework::Observer& observer, int* argc, char*** argv, Type type) : mObserver(observer), mInitialised(false), mPaused(false), @@ -197,16 +193,16 @@ Framework::Framework( Framework::Observer& observer, int *argc, char ***argv, Ty mArgv(argv), mBundleName(""), mBundleId(""), - mAbortHandler( MakeCallback( this, &Framework::AbortCallback ) ), + mAbortHandler(MakeCallback(this, &Framework::AbortCallback)), mImpl(NULL) { - InitThreads(); - mImpl = new Impl(this); + InitThreads(); + mImpl = new Impl(this); } Framework::~Framework() { - if (mRunning) + if(mRunning) { Quit(); } @@ -216,11 +212,11 @@ Framework::~Framework() void Framework::Run() { - mRunning = true; + mRunning = true; - Impl::AppCreate(this); - mImpl->Run(); - mRunning = false; + Impl::AppCreate(this); + mImpl->Run(); + mRunning = false; } void Framework::Quit() @@ -233,9 +229,9 @@ bool Framework::IsMainLoopRunning() return mRunning; } -void Framework::AddAbortCallback( CallbackBase* callback ) +void Framework::AddAbortCallback(CallbackBase* callback) { - mImpl->SetCallbackBase( callback ); + mImpl->SetCallbackBase(callback); } std::string Framework::GetBundleName() const @@ -257,17 +253,17 @@ std::string Framework::GetResourcePath() { // "DALI_APPLICATION_PACKAGE" is used by Windows specifically to get the already configured Application package path. const char* winEnvironmentVariable = "DALI_APPLICATION_PACKAGE"; - char* value = getenv( winEnvironmentVariable ); + char* value = getenv(winEnvironmentVariable); std::string resourcePath; - if ( value != NULL ) + if(value != NULL) { resourcePath = value; } - if( resourcePath.back() != '/' ) + if(resourcePath.back() != '/') { - resourcePath+="/"; + resourcePath += "/"; } return resourcePath; @@ -284,18 +280,18 @@ void Framework::SetBundleId(const std::string& id) mBundleId = id; } -void Framework::AbortCallback( ) +void Framework::AbortCallback() { // if an abort call back has been installed run it. - if( false == mImpl->ExcuteCallback() ) + if(false == mImpl->ExcuteCallback()) { Quit(); } } -bool Framework::AppStatusHandler(int type, void *bundleData) +bool Framework::AppStatusHandler(int type, void* bundleData) { - switch (type) + switch(type) { case APP_CREATE: { diff --git a/dali/internal/addons/common/addon-manager-impl.h b/dali/internal/addons/common/addon-manager-impl.h index f431c49..5850d47 100644 --- a/dali/internal/addons/common/addon-manager-impl.h +++ b/dali/internal/addons/common/addon-manager-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADDON_MANAGER_IMPL /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,9 @@ #include +#include #include #include -#include namespace Dali { @@ -34,7 +34,6 @@ namespace Internal class AddOnManager { protected: - /** * @brief Constructor */ @@ -50,7 +49,7 @@ public: * @brief Registers the dispatch table with AddOnManager. * @param[in] dispatchTable Pointer to the valid dispatch table */ - virtual void RegisterAddOnDispatchTable( const AddOnDispatchTable* dispatchTable ) = 0; + virtual void RegisterAddOnDispatchTable(const AddOnDispatchTable* dispatchTable) = 0; /** * @brief Retrieves list of the available AddOns @@ -64,14 +63,14 @@ public: * @param[out]] info Output reference * @return True on success, False if extension info cannot be retrieved */ - virtual bool GetAddOnInfo(const std::string& name, AddOnInfo& info ) = 0; + virtual bool GetAddOnInfo(const std::string& name, AddOnInfo& info) = 0; /** * @brief Loads and initialises specified AddOns * @param[in] extensionNames Array of extension names * @return vector of initialised AddOnLibrary handles */ - virtual std::vector LoadAddOns( const std::vector& addonNames ) = 0; + virtual std::vector LoadAddOns(const std::vector& addonNames) = 0; /** * @brief Returns AddOn global function pointer @@ -79,7 +78,7 @@ public: * @param[in] procName Name of the function to retrieve * @return Pointer to the function or null if function doesn't exist */ - virtual void* GetGlobalProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) = 0; + virtual void* GetGlobalProc(const Dali::AddOnLibrary& addonHandle, const char* procName) = 0; /** * @brief Returns addon instance function pointer @@ -87,35 +86,43 @@ public: * @param[in] procName Name of the function to retrieve * @return Pointer to the function or null if function doesn't exist */ - virtual void* GetInstanceProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) = 0; + virtual void* GetInstanceProc(const Dali::AddOnLibrary& addonHandle, const char* procName) = 0; /** * @brief Pause lifecycle event * Implementation is optional and depends whether AddOn needs to handle lifecycle event. */ - virtual void Pause() {} + virtual void Pause() + { + } /** * @brief Resume lifecycle event * Implementation is optional and depends whether AddOn needs to handle lifecycle event. */ - virtual void Resume() {} + virtual void Resume() + { + } /** * @brief Start lifecycle event * Implementation is optional and depends whether AddOn needs to handle lifecycle event. */ - virtual void Start() {} + virtual void Start() + { + } /** * @brief Stop lifecycle event * Implementation is optional and depends whether AddOn needs to handle lifecycle event. */ - virtual void Stop() {} + virtual void Stop() + { + } }; -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali #endif // DALI_CMAKE_EXTENSION_MANAGER_IMPL diff --git a/dali/internal/addons/common/addon-manager.cpp b/dali/internal/addons/common/addon-manager.cpp index ffd193d..e72a58e 100644 --- a/dali/internal/addons/common/addon-manager.cpp +++ b/dali/internal/addons/common/addon-manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,22 +30,22 @@ __attribute__((weak)) Dali::Integration::AddOnManager* CreateAddOnManager() return nullptr; } -} // AddOnManagerFactory -} +} // namespace AddOnManagerFactory +} // namespace Internal namespace Adaptor { - -AddOnManager::AddOnManager(Internal::AddOnManager* impl ) : Integration::AddOnManager() +AddOnManager::AddOnManager(Internal::AddOnManager* impl) +: Integration::AddOnManager() { mImpl.reset(impl); } AddOnManager::~AddOnManager() = default; -void AddOnManager::RegisterAddOnDispatchTable( const AddOnDispatchTable* dispatchTable ) +void AddOnManager::RegisterAddOnDispatchTable(const AddOnDispatchTable* dispatchTable) { - mImpl->RegisterAddOnDispatchTable( dispatchTable ); + mImpl->RegisterAddOnDispatchTable(dispatchTable); } std::vector AddOnManager::EnumerateAddOns() @@ -53,24 +53,24 @@ std::vector AddOnManager::EnumerateAddOns() return mImpl->EnumerateAddOns(); } -bool AddOnManager::GetAddOnInfo(const std::string& name, AddOnInfo& info ) +bool AddOnManager::GetAddOnInfo(const std::string& name, AddOnInfo& info) { - return mImpl->GetAddOnInfo( name, info ); + return mImpl->GetAddOnInfo(name, info); } -std::vector AddOnManager::LoadAddOns(const std::vector& addonNames ) +std::vector AddOnManager::LoadAddOns(const std::vector& addonNames) { - return std::move(mImpl->LoadAddOns( addonNames )); + return std::move(mImpl->LoadAddOns(addonNames)); } -void* AddOnManager::GetGlobalProc(const Dali::AddOnLibrary& addonHandle, const char *procName) +void* AddOnManager::GetGlobalProc(const Dali::AddOnLibrary& addonHandle, const char* procName) { - return mImpl->GetGlobalProc( addonHandle, procName ); + return mImpl->GetGlobalProc(addonHandle, procName); } -void* AddOnManager::GetInstanceProc(const Dali::AddOnLibrary& addonHandle, const char* procName ) +void* AddOnManager::GetInstanceProc(const Dali::AddOnLibrary& addonHandle, const char* procName) { - return mImpl->GetInstanceProc( addonHandle, procName ); + return mImpl->GetInstanceProc(addonHandle, procName); } void AddOnManager::Pause() @@ -93,5 +93,5 @@ void AddOnManager::Stop() mImpl->Stop(); } -} -} \ No newline at end of file +} // namespace Adaptor +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/addons/common/addon-manager.h b/dali/internal/addons/common/addon-manager.h index ab57360..eddbc72 100644 --- a/dali/internal/addons/common/addon-manager.h +++ b/dali/internal/addons/common/addon-manager.h @@ -2,7 +2,7 @@ #define DALI_ADAPTOR_COMMON_ADDON_MANAGER /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ namespace Dali { - namespace Internal { class AddOnManager; @@ -30,11 +29,9 @@ class AddOnManager; namespace Adaptor { - class AddOnManager : public Dali::Integration::AddOnManager { public: - /** * @brief Constructor * @param impl Pointer to the platform specific implementation @@ -52,7 +49,7 @@ public: * event callbacks. * @param[in] dispatchTable Valid pointer to the DispatchTable object */ - void RegisterAddOnDispatchTable( const AddOnDispatchTable* dispatchTable ) override; + void RegisterAddOnDispatchTable(const AddOnDispatchTable* dispatchTable) override; /** * @brief Retrieves list of all the extensions available @@ -66,7 +63,7 @@ public: * @param[out]] info Output reference * @return True on success, False if extension info cannot be retrieved */ - bool GetAddOnInfo(const std::string& name, AddOnInfo& info ) override; + bool GetAddOnInfo(const std::string& name, AddOnInfo& info) override; /** * @brief Loads and initialises specified extensions @@ -74,7 +71,7 @@ public: * @param[in] extensionNames Array of extension names * @return vector of initialised extension handles */ - std::vector LoadAddOns( const std::vector& addonNames ) override; + std::vector LoadAddOns(const std::vector& addonNames) override; /** * @brief Returns addon global function pointer @@ -82,7 +79,7 @@ public: * @param[in] procName Name of the function to retrieve * @return Pointer to the function or null if function doesn't exist */ - void* GetGlobalProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) override; + void* GetGlobalProc(const Dali::AddOnLibrary& addonHandle, const char* procName) override; /** * @brief Returns addon instance function pointer @@ -90,7 +87,7 @@ public: * @param[in] procName Name of the function to retrieve * @return Pointer to the function or null if function doesn't exist */ - void* GetInstanceProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) override; + void* GetInstanceProc(const Dali::AddOnLibrary& addonHandle, const char* procName) override; /** * @brief Lifecycle pause function @@ -113,11 +110,9 @@ public: void Stop() override; private: - std::unique_ptr mImpl; /// Implementation of the AddOnManager - }; -} // namespace Internal +} // namespace Adaptor } // namespace Dali #endif // DALI_ADAPTOR_COMMON_ADDON_MANAGER diff --git a/dali/internal/addons/linux/addon-manager-impl-linux.cpp b/dali/internal/addons/linux/addon-manager-impl-linux.cpp index 036f7e5..2ed12ba 100644 --- a/dali/internal/addons/linux/addon-manager-impl-linux.cpp +++ b/dali/internal/addons/linux/addon-manager-impl-linux.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,16 @@ */ // INTERNAL INCLUDES -#include #include +#include #include // EXTERNAL INCLUDES #include #include -#include #include +#include #include #include @@ -33,54 +33,52 @@ namespace Dali { namespace Internal { - AddOnManagerLinux::AddOnManagerLinux() = default; AddOnManagerLinux::~AddOnManagerLinux() = default; -void AddOnManagerLinux::RegisterAddOnDispatchTable( const AddOnDispatchTable* dispatchTable ) +void AddOnManagerLinux::RegisterAddOnDispatchTable(const AddOnDispatchTable* dispatchTable) { mAddOnNames.emplace_back(dispatchTable->name); mAddOnCache.emplace_back(); - mAddOnCache.back().GetGlobalProc = dispatchTable->GetGlobalProc; + mAddOnCache.back().GetGlobalProc = dispatchTable->GetGlobalProc; mAddOnCache.back().GetInstanceProc = dispatchTable->GetInstanceProc; - mAddOnCache.back().GetAddOnInfo = dispatchTable->GetAddOnInfo; + mAddOnCache.back().GetAddOnInfo = dispatchTable->GetAddOnInfo; auto& callbacks = mAddOnCache.back().lifecycleCallbacks; - auto initEvent = [&callbacks](uint32_t event, void(*fn)() ) { - callbacks[event].function = fn; + auto initEvent = [&callbacks](uint32_t event, void (*fn)()) { + callbacks[event].function = fn; callbacks[event].initialized = true; }; - initEvent( LifecycleCallback::EVENT_START, dispatchTable->OnStart ); - initEvent( LifecycleCallback::EVENT_STOP, dispatchTable->OnStop ); - initEvent( LifecycleCallback::EVENT_PAUSE, dispatchTable->OnPause ); - initEvent( LifecycleCallback::EVENT_RESUME, dispatchTable->OnResume ); + initEvent(LifecycleCallback::EVENT_START, dispatchTable->OnStart); + initEvent(LifecycleCallback::EVENT_STOP, dispatchTable->OnStop); + initEvent(LifecycleCallback::EVENT_PAUSE, dispatchTable->OnPause); + initEvent(LifecycleCallback::EVENT_RESUME, dispatchTable->OnResume); } std::vector AddOnManagerLinux::EnumerateAddOns() { - if( mAddOnNames.empty() ) + if(mAddOnNames.empty()) { // AddOn libs must be separated with ':' character - const char *addonsLibs = Dali::EnvironmentVariable::GetEnvironmentVariable( DALI_ENV_ADDONS_LIBS ); - if (!addonsLibs) + const char* addonsLibs = Dali::EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_ADDONS_LIBS); + if(!addonsLibs) { return {}; } // Get the path where addon libs are stored - const char *addonsPath = Dali::EnvironmentVariable::GetEnvironmentVariable( DALI_ENV_ADDONS_PATH ); + const char* addonsPath = Dali::EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_ADDONS_PATH); std::string addonsPathStr(addonsPath ? addonsPath : "/usr/lib"); // Split libs - std::string addonLibsStr(addonsLibs); + std::string addonLibsStr(addonsLibs); std::vector results; results.emplace_back(); - std::find_if(addonLibsStr.begin(), addonLibsStr.end(), [&results](char &c) - { - if (c == ':') + std::find_if(addonLibsStr.begin(), addonLibsStr.end(), [&results](char& c) { + if(c == ':') { results.emplace_back(); } @@ -91,9 +89,9 @@ std::vector AddOnManagerLinux::EnumerateAddOns() return false; }); - const char *EXTENSION_PATH = (addonsPath) ? addonsPath : "/usr/lib"; + const char* EXTENSION_PATH = (addonsPath) ? addonsPath : "/usr/lib"; - for (auto &name : results) + for(auto& name : results) { std::string fullPath(EXTENSION_PATH); fullPath += "/"; @@ -101,16 +99,16 @@ std::vector AddOnManagerLinux::EnumerateAddOns() // open lib, look for essential symbols. The libary is opened with RTLD_DEEPBIND flag // to make sure the local symbol table is going to be used during lookup first. - auto* handle = dlopen(fullPath.c_str(), RTLD_DEEPBIND|RTLD_LAZY); - if (handle) + auto* handle = dlopen(fullPath.c_str(), RTLD_DEEPBIND | RTLD_LAZY); + if(handle) { - auto& cacheEntry = mAddOnCache.back(); + auto& cacheEntry = mAddOnCache.back(); AddOnInfo info{}; cacheEntry.GetAddOnInfo(info); - cacheEntry.info = info; - cacheEntry.addOnLib = fullPath; - cacheEntry.libHandle = handle; - cacheEntry.opened = false; + cacheEntry.info = info; + cacheEntry.addOnLib = fullPath; + cacheEntry.libHandle = handle; + cacheEntry.opened = false; } else { @@ -121,24 +119,23 @@ std::vector AddOnManagerLinux::EnumerateAddOns() return mAddOnNames; } -bool AddOnManagerLinux::GetAddOnInfo(const std::string& name, AddOnInfo& info ) +bool AddOnManagerLinux::GetAddOnInfo(const std::string& name, AddOnInfo& info) { - if( mAddOnNames.empty() ) + if(mAddOnNames.empty()) { EnumerateAddOns(); } - if( mAddOnNames.empty() ) + if(mAddOnNames.empty()) { return false; } - auto iter = std::find_if( mAddOnCache.begin(), mAddOnCache.end(), [name]( AddOnCacheEntry& item ) - { + auto iter = std::find_if(mAddOnCache.begin(), mAddOnCache.end(), [name](AddOnCacheEntry& item) { return (item.info.name == name); }); - if (iter == mAddOnCache.end()) + if(iter == mAddOnCache.end()) { return false; } @@ -147,13 +144,13 @@ bool AddOnManagerLinux::GetAddOnInfo(const std::string& name, AddOnInfo& info ) return true; } -std::vector AddOnManagerLinux::LoadAddOns( const std::vector& addonNames ) +std::vector AddOnManagerLinux::LoadAddOns(const std::vector& addonNames) { std::vector retval{}; - retval.resize( addonNames.size() ); - std::fill( retval.begin(), retval.end(), nullptr ); + retval.resize(addonNames.size()); + std::fill(retval.begin(), retval.end(), nullptr); - if( mAddOnCache.empty() ) + if(mAddOnCache.empty()) { EnumerateAddOns(); if(mAddOnCache.empty()) @@ -164,12 +161,11 @@ std::vector AddOnManagerLinux::LoadAddOns( const std::vector } auto nameIndex = 0u; - for( const auto& name : addonNames ) + for(const auto& name : addonNames) { auto index = 0u; nameIndex++; - auto iter = std::find_if( mAddOnCache.begin(), mAddOnCache.end(), [&index, name]( AddOnCacheEntry& item ) - { + auto iter = std::find_if(mAddOnCache.begin(), mAddOnCache.end(), [&index, name](AddOnCacheEntry& item) { ++index; return (item.info.name == name); }); @@ -182,36 +178,36 @@ std::vector AddOnManagerLinux::LoadAddOns( const std::vector if(!iter->opened && iter->libHandle) { // Open library, pull symbols and keep the handle - auto& entry = *iter; + auto& entry = *iter; entry.opened = true; } // Store cache index of extension for indirect calling // Stored number in this implementation is always +1 (0 is nullptr, unsuccessful) - retval[nameIndex-1] = reinterpret_cast( index ); + retval[nameIndex - 1] = reinterpret_cast(index); } return retval; } -void* AddOnManagerLinux::GetGlobalProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) +void* AddOnManagerLinux::GetGlobalProc(const Dali::AddOnLibrary& addonHandle, const char* procName) { - if( !addonHandle ) + if(!addonHandle) { return nullptr; } - auto index = (intptr_t(addonHandle)); - const auto& entry = mAddOnCache[ index-1 ]; + auto index = (intptr_t(addonHandle)); + const auto& entry = mAddOnCache[index - 1]; - if(entry.opened && entry.libHandle ) + if(entry.opened && entry.libHandle) { // First call into dispatch table - auto retval = entry.GetGlobalProc( procName ); - if( !retval ) + auto retval = entry.GetGlobalProc(procName); + if(!retval) { // fallback - retval = dlsym( entry.libHandle, procName ); + retval = dlsym(entry.libHandle, procName); } return retval; } @@ -222,23 +218,23 @@ void* AddOnManagerLinux::GetGlobalProc( const Dali::AddOnLibrary& addonHandle, c return nullptr; } -void* AddOnManagerLinux::GetInstanceProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) +void* AddOnManagerLinux::GetInstanceProc(const Dali::AddOnLibrary& addonHandle, const char* procName) { - if( !addonHandle ) + if(!addonHandle) { return nullptr; } - auto index = (intptr_t(addonHandle)); - const auto& entry = mAddOnCache[ index-1 ]; - if(entry.opened && entry.libHandle ) + auto index = (intptr_t(addonHandle)); + const auto& entry = mAddOnCache[index - 1]; + if(entry.opened && entry.libHandle) { // First call into dispatch table - auto retval = entry.GetInstanceProc( procName ); - if( !retval ) + auto retval = entry.GetInstanceProc(procName); + if(!retval) { // fallback - retval = dlsym( entry.libHandle, procName ); + retval = dlsym(entry.libHandle, procName); } return retval; } @@ -247,27 +243,27 @@ void* AddOnManagerLinux::GetInstanceProc( const Dali::AddOnLibrary& addonHandle, void AddOnManagerLinux::Pause() { - InvokeLifecycleFunction( LifecycleCallback::EVENT_PAUSE ); + InvokeLifecycleFunction(LifecycleCallback::EVENT_PAUSE); } void AddOnManagerLinux::Resume() { - InvokeLifecycleFunction( LifecycleCallback::EVENT_RESUME ); + InvokeLifecycleFunction(LifecycleCallback::EVENT_RESUME); } void AddOnManagerLinux::Start() { - InvokeLifecycleFunction( LifecycleCallback::EVENT_START ); + InvokeLifecycleFunction(LifecycleCallback::EVENT_START); } void AddOnManagerLinux::Stop() { - InvokeLifecycleFunction( LifecycleCallback::EVENT_STOP ); + InvokeLifecycleFunction(LifecycleCallback::EVENT_STOP); } -void AddOnManagerLinux::InvokeLifecycleFunction( uint32_t lifecycleEvent ) +void AddOnManagerLinux::InvokeLifecycleFunction(uint32_t lifecycleEvent) { - for( auto& entry : mAddOnCache ) + for(auto& entry : mAddOnCache) { auto& callback = entry.lifecycleCallbacks[lifecycleEvent]; diff --git a/dali/internal/addons/linux/addon-manager-impl-linux.h b/dali/internal/addons/linux/addon-manager-impl-linux.h index 9139321..bac4339 100644 --- a/dali/internal/addons/linux/addon-manager-impl-linux.h +++ b/dali/internal/addons/linux/addon-manager-impl-linux.h @@ -1,7 +1,7 @@ #ifndef DALI_ADDON_MANAGER_IMPL_LINUX #define DALI_ADDON_MANAGER_IMPL_LINUX /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,21 +24,19 @@ // EXTERNAL INCLUDES #include -#include #include +#include namespace Dali { namespace Internal { - /** * Implementation of AddOnManager for Linux based platforms (ie. Tizen, Ubuntu) */ class AddOnManagerLinux : public Internal::AddOnManager { public: - /** * @copydoc Dali::Internal::AddOnManager() */ @@ -52,7 +50,7 @@ public: /** * @copydoc Dali::Internal::AddOnManager::RegisterAddOnDispatchTable() */ - void RegisterAddOnDispatchTable( const AddOnDispatchTable* dispatchTable ) override; + void RegisterAddOnDispatchTable(const AddOnDispatchTable* dispatchTable) override; /** * @copydoc Dali::Internal::AddOnManager::EnumerateAddOns() @@ -62,22 +60,22 @@ public: /** * @copydoc Dali::Internal::AddOnManager::GetAddOnInfo() */ - bool GetAddOnInfo(const std::string& name, AddOnInfo& info ) override; + bool GetAddOnInfo(const std::string& name, AddOnInfo& info) override; /** * @copydoc Dali::Internal::AddOnManager::LoadAddOns() */ - std::vector LoadAddOns( const std::vector& extensionNames ) override; + std::vector LoadAddOns(const std::vector& extensionNames) override; /** * @copydoc Dali::Internal::AddOnManager::GetGlobalProc() */ - void* GetGlobalProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) override; + void* GetGlobalProc(const Dali::AddOnLibrary& addonHandle, const char* procName) override; /** * @copydoc Dali::Internal::AddOnManager::GetInstanceProc() */ - void* GetInstanceProc( const Dali::AddOnLibrary& addonHandle, const char* procName ) override; + void* GetInstanceProc(const Dali::AddOnLibrary& addonHandle, const char* procName) override; /** * @copydoc Dali::Internal::AddOnManager::Pause() @@ -100,12 +98,11 @@ public: void Stop() override; private: - /** * @brief Invokes lifecycle event handling function based on incoming event * @param[in] lifecycleEvent The lifecycle event */ - void InvokeLifecycleFunction( uint32_t lifecycleEvent ); + void InvokeLifecycleFunction(uint32_t lifecycleEvent); /** * @struct Lifecycle callback structure @@ -116,10 +113,10 @@ private: */ struct LifecycleCallback { - const static uint32_t EVENT_PAUSE = 0u; ///< pause event + const static uint32_t EVENT_PAUSE = 0u; ///< pause event const static uint32_t EVENT_RESUME = 1u; ///< resume event - const static uint32_t EVENT_START = 2u; ///< start event - const static uint32_t EVENT_STOP = 3u; ///< stop event + const static uint32_t EVENT_START = 2u; ///< start event + const static uint32_t EVENT_STOP = 3u; ///< stop event /** * @brief Constructor @@ -130,9 +127,9 @@ private: functionName = funcName; } - std::string functionName; ///< Name of lifecycle function - void(*function)() = nullptr; ///< Lifecycle function pointer - bool initialized { false }; ///< Flag indicates whether LifecycleCallback is initialized + std::string functionName; ///< Name of lifecycle function + void (*function)() = nullptr; ///< Lifecycle function pointer + bool initialized{false}; ///< Flag indicates whether LifecycleCallback is initialized }; /** @@ -143,32 +140,31 @@ private: struct AddOnCacheEntry { std::string addOnLib{}; - AddOnInfo info{}; + AddOnInfo info{}; // library handle - void* libHandle {nullptr}; + void* libHandle{nullptr}; // main function pointers - void(*GetAddOnInfo)(AddOnInfo& ) = nullptr; ///< Returns AddOnInfo structure - void*(*GetInstanceProc)( const char* ) = nullptr; ///< Returns pointer of instance function (member funtion) - void*(*GetGlobalProc)( const char* ) = nullptr; ///< Returns pointer of global function (non-member function) + void (*GetAddOnInfo)(AddOnInfo&) = nullptr; ///< Returns AddOnInfo structure + void* (*GetInstanceProc)(const char*) = nullptr; ///< Returns pointer of instance function (member funtion) + void* (*GetGlobalProc)(const char*) = nullptr; ///< Returns pointer of global function (non-member function) // lifecycle functions std::vector lifecycleCallbacks = - { - LifecycleCallback{ "OnPause" }, - LifecycleCallback{ "OnResume" }, - LifecycleCallback{ "OnStart" }, - LifecycleCallback{ "OnStop" }, - }; + { + LifecycleCallback{"OnPause"}, + LifecycleCallback{"OnResume"}, + LifecycleCallback{"OnStart"}, + LifecycleCallback{"OnStop"}, + }; bool opened{false}; }; std::vector mAddOnCache; - std::vector mAddOnNames; + std::vector mAddOnNames; }; - -} -} +} // namespace Internal +} // namespace Dali #endif //DALI_CMAKE_EXTENSION_MANAGER_IMPL_UBUNTU diff --git a/dali/internal/addons/tizen/addon-manager-factory-tizen.cpp b/dali/internal/addons/tizen/addon-manager-factory-tizen.cpp index 53e06aa..bd530ec 100644 --- a/dali/internal/addons/tizen/addon-manager-factory-tizen.cpp +++ b/dali/internal/addons/tizen/addon-manager-factory-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ namespace Internal { Integration::AddOnManager* AddOnManagerFactory::CreateAddOnManager() { - return new Dali::Adaptor::AddOnManager( new AddOnManagerLinux() ); + return new Dali::Adaptor::AddOnManager(new AddOnManagerLinux()); } } // namespace Internal diff --git a/dali/internal/addons/ubuntu/addon-manager-factory-ubuntu.cpp b/dali/internal/addons/ubuntu/addon-manager-factory-ubuntu.cpp index 53e06aa..bd530ec 100644 --- a/dali/internal/addons/ubuntu/addon-manager-factory-ubuntu.cpp +++ b/dali/internal/addons/ubuntu/addon-manager-factory-ubuntu.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ namespace Internal { Integration::AddOnManager* AddOnManagerFactory::CreateAddOnManager() { - return new Dali::Adaptor::AddOnManager( new AddOnManagerLinux() ); + return new Dali::Adaptor::AddOnManager(new AddOnManagerLinux()); } } // namespace Internal diff --git a/dali/internal/clipboard/common/clipboard-event-notifier-impl.cpp b/dali/internal/clipboard/common/clipboard-event-notifier-impl.cpp index ff5acd6..f3cdca0 100644 --- a/dali/internal/clipboard/common/clipboard-event-notifier-impl.cpp +++ b/dali/internal/clipboard/common/clipboard-event-notifier-impl.cpp @@ -19,18 +19,15 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - Dali::ClipboardEventNotifier ClipboardEventNotifier::New() { Dali::ClipboardEventNotifier notifier = Dali::ClipboardEventNotifier(new ClipboardEventNotifier()); @@ -42,20 +39,20 @@ Dali::ClipboardEventNotifier ClipboardEventNotifier::Get() { Dali::ClipboardEventNotifier notifier; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ClipboardEventNotifier ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::ClipboardEventNotifier)); if(handle) { // If so, downcast the handle - notifier = Dali::ClipboardEventNotifier( dynamic_cast< ClipboardEventNotifier* >( handle.GetObjectPtr() ) ); + notifier = Dali::ClipboardEventNotifier(dynamic_cast(handle.GetObjectPtr())); } else { - notifier = Dali::ClipboardEventNotifier( ClipboardEventNotifier::New() ); - service.Register( typeid( notifier ), notifier ); + notifier = Dali::ClipboardEventNotifier(ClipboardEventNotifier::New()); + service.Register(typeid(notifier), notifier); } } @@ -67,7 +64,7 @@ const std::string& ClipboardEventNotifier::GetContent() const return mContent; } -void ClipboardEventNotifier::SetContent( const std::string& content ) +void ClipboardEventNotifier::SetContent(const std::string& content) { mContent = content; } @@ -79,10 +76,10 @@ void ClipboardEventNotifier::ClearContent() void ClipboardEventNotifier::EmitContentSelectedSignal() { - if ( !mContentSelectedSignal.Empty() ) + if(!mContentSelectedSignal.Empty()) { - Dali::ClipboardEventNotifier handle( this ); - mContentSelectedSignal.Emit( handle ); + Dali::ClipboardEventNotifier handle(this); + mContentSelectedSignal.Emit(handle); } } diff --git a/dali/internal/clipboard/common/clipboard-event-notifier-impl.h b/dali/internal/clipboard/common/clipboard-event-notifier-impl.h index 2ec3e56..8e21031 100644 --- a/dali/internal/clipboard/common/clipboard-event-notifier-impl.h +++ b/dali/internal/clipboard/common/clipboard-event-notifier-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_CLIPBOARD_EVENT_NOTIFIER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ */ // EXTERNAL INCLUDES -#include -#include #include +#include +#include // INTERNAL INCLUDES #include @@ -29,20 +29,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * This class listens to Clipboard events. */ class ClipboardEventNotifier : public Dali::BaseObject { public: - typedef Dali::ClipboardEventNotifier::ClipboardEventSignalType ClipboardEventSignalType; // Creation @@ -69,7 +65,7 @@ public: * Sets the selected content. * @param[in] content A string that represents the content that has been selected. */ - void SetContent( const std::string& content ); + void SetContent(const std::string& content); /** * Clears the stored content. @@ -82,7 +78,6 @@ public: void EmitContentSelectedSignal(); public: // Signals - /** * @copydoc Dali::ClipboardEventNotifier::ContentSelectedSignal */ @@ -92,7 +87,6 @@ public: // Signals } private: - // Construction & Destruction /** @@ -106,22 +100,20 @@ private: ~ClipboardEventNotifier() override; // Undefined - ClipboardEventNotifier( const ClipboardEventNotifier& ); - ClipboardEventNotifier& operator=( ClipboardEventNotifier& ); + ClipboardEventNotifier(const ClipboardEventNotifier&); + ClipboardEventNotifier& operator=(ClipboardEventNotifier&); private: - - std::string mContent; ///< The current selected content. + std::string mContent; ///< The current selected content. ClipboardEventSignalType mContentSelectedSignal; public: - // Helpers for public-api forwarding methods inline static Internal::Adaptor::ClipboardEventNotifier& GetImplementation(Dali::ClipboardEventNotifier& detector) { - DALI_ASSERT_ALWAYS( detector && "ClipboardEventNotifier handle is empty" ); + DALI_ASSERT_ALWAYS(detector && "ClipboardEventNotifier handle is empty"); BaseObject& handle = detector.GetBaseObject(); @@ -130,13 +122,12 @@ public: inline static const Internal::Adaptor::ClipboardEventNotifier& GetImplementation(const Dali::ClipboardEventNotifier& detector) { - DALI_ASSERT_ALWAYS( detector && "ClipboardEventNotifier handle is empty" ); + DALI_ASSERT_ALWAYS(detector && "ClipboardEventNotifier handle is empty"); const BaseObject& handle = detector.GetBaseObject(); return static_cast(handle); } - }; } // namespace Adaptor diff --git a/dali/internal/clipboard/common/clipboard-impl.h b/dali/internal/clipboard/common/clipboard-impl.h index b4371ae..eac973b 100644 --- a/dali/internal/clipboard/common/clipboard-impl.h +++ b/dali/internal/clipboard/common/clipboard-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_CLIPBOARD_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,21 +26,17 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Implementation of the Clip Board */ -class Clipboard : public Dali::BaseObject +class Clipboard : public Dali::BaseObject { public: - // Hide the specific windowing system struct Impl; @@ -63,7 +59,7 @@ public: /** * @copydoc Dali::Clipboard::SetItem() */ - bool SetItem(const std::string &itemData); + bool SetItem(const std::string& itemData); /** * @copydoc Dali::Clipboard::RequestItem() @@ -97,20 +93,17 @@ public: * @param[in] event information pointer * @return The buffer pointer for send or receive data */ - char* ExcuteBuffered( bool type, void *event ); + char* ExcuteBuffered(bool type, void* event); private: - // Undefined - Clipboard( const Clipboard& ); - Clipboard& operator=( Clipboard& ); + Clipboard(const Clipboard&); + Clipboard& operator=(Clipboard&); private: - Impl* mImpl; public: - }; // class clipboard } // namespace Adaptor @@ -119,14 +112,14 @@ public: inline static Internal::Adaptor::Clipboard& GetImplementation(Dali::Clipboard& clipboard) { - DALI_ASSERT_ALWAYS( clipboard && "Clipboard handle is empty" ); + DALI_ASSERT_ALWAYS(clipboard && "Clipboard handle is empty"); BaseObject& handle = clipboard.GetBaseObject(); return static_cast(handle); } -inline static const Internal::Adaptor::Clipboard& GetImplementation(const Dali::Clipboard& clipboard) +inline static const Internal::Adaptor::Clipboard& GetImplementation(const Dali::Clipboard& clipboard) { - DALI_ASSERT_ALWAYS( clipboard && "Clipboard handle is empty" ); + DALI_ASSERT_ALWAYS(clipboard && "Clipboard handle is empty"); const BaseObject& handle = clipboard.GetBaseObject(); return static_cast(handle); } diff --git a/dali/internal/clipboard/generic/clipboard-impl-generic.cpp b/dali/internal/clipboard/generic/clipboard-impl-generic.cpp old mode 100755 new mode 100644 index 8e08371..379d102 --- a/dali/internal/clipboard/generic/clipboard-impl-generic.cpp +++ b/dali/internal/clipboard/generic/clipboard-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,19 +23,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - struct Clipboard::Impl { }; -Clipboard::Clipboard( Impl* impl ) -: mImpl( impl ) +Clipboard::Clipboard(Impl* impl) +: mImpl(impl) { } @@ -47,28 +44,28 @@ Dali::Clipboard Clipboard::Get() { Dali::Clipboard clipboard; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::Clipboard)); if(handle) { // If so, downcast the handle - clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) ); + clipboard = Dali::Clipboard(dynamic_cast(handle.GetObjectPtr())); } else { - Clipboard::Impl* impl( new Clipboard::Impl() ); - clipboard = Dali::Clipboard( new Clipboard(impl) ); - service.Register( typeid(Dali::Clipboard), clipboard ); + Clipboard::Impl* impl(new Clipboard::Impl()); + clipboard = Dali::Clipboard(new Clipboard(impl)); + service.Register(typeid(Dali::Clipboard), clipboard); } } return clipboard; } -bool Clipboard::SetItem(const std::string &itemData ) +bool Clipboard::SetItem(const std::string& itemData) { return true; } @@ -95,7 +92,7 @@ bool Clipboard::IsVisible() const return false; } -char* Clipboard::ExcuteBuffered( bool type, void *event ) +char* Clipboard::ExcuteBuffered(bool type, void* event) { return NULL; } diff --git a/dali/internal/clipboard/tizen-wayland/clipboard-impl-ecore-wl.cpp b/dali/internal/clipboard/tizen-wayland/clipboard-impl-ecore-wl.cpp old mode 100755 new mode 100644 index 52b18d6..15aa6a5 --- a/dali/internal/clipboard/tizen-wayland/clipboard-impl-ecore-wl.cpp +++ b/dali/internal/clipboard/tizen-wayland/clipboard-impl-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ */ // CLASS HEADER -#include #include +#include // EXTERNAL INCLUDES #include @@ -28,10 +28,10 @@ #include #endif -#include -#include #include #include +#include +#include #include #ifdef DALI_ELDBUS_AVAILABLE @@ -41,8 +41,8 @@ #define CBHM_DBUS_OBJPATH "/org/tizen/cbhm/dbus" #ifndef CBHM_DBUS_INTERFACE #define CBHM_DBUS_INTERFACE "org.tizen.cbhm.dbus" -#endif /* CBHM_DBUS_INTERFACE */ -#define CBHM_COUNT_ALL 0 // ATOM_INDEX_CBHM_COUNT_ALL +#endif /* CBHM_DBUS_INTERFACE */ +#define CBHM_COUNT_ALL 0 // ATOM_INDEX_CBHM_COUNT_ALL /////////////////////////////////////////////////////////////////////////////////////////////////// // Clipboard @@ -50,31 +50,28 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - struct Clipboard::Impl { Impl() { - Eldbus_Object *eldbus_obj; + Eldbus_Object* eldbus_obj; eldbus_init(); - cbhm_conn = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SESSION); - eldbus_obj = eldbus_object_get(cbhm_conn, CBHM_DBUS_INTERFACE, CBHM_DBUS_OBJPATH); + cbhm_conn = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SESSION); + eldbus_obj = eldbus_object_get(cbhm_conn, CBHM_DBUS_INTERFACE, CBHM_DBUS_OBJPATH); eldbus_proxy = eldbus_proxy_get(eldbus_obj, CBHM_DBUS_INTERFACE); eldbus_name_owner_changed_callback_add(cbhm_conn, CBHM_DBUS_INTERFACE, NULL, cbhm_conn, EINA_TRUE); eldbus_proxy_signal_handler_add(eldbus_proxy, "ItemClicked", _on_item_clicked, this); - mVisible = false; + mVisible = false; mIsFirstTimeHidden = true; } ~Impl() { - if (cbhm_conn) + if(cbhm_conn) eldbus_connection_unref(cbhm_conn); eldbus_shutdown(); } @@ -89,12 +86,14 @@ struct Clipboard::Impl return cbhm_conn; } - void SetItem( const std::string &itemData ) + void SetItem(const std::string& itemData) { - const char *types[10] = {0, }; + const char* types[10] = { + 0, + }; int i = -1; - if (itemData.length() == 0) + if(itemData.length() == 0) { return; } @@ -109,20 +108,22 @@ struct Clipboard::Impl types[++i] = "CLIPBOARD_END"; #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get( ecore_wl2_connected_display_get( NULL ) ); - ecore_wl2_dnd_selection_set( input, types ); + Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get(ecore_wl2_connected_display_get(NULL)); + ecore_wl2_dnd_selection_set(input, types); #else - ecore_wl_dnd_selection_set( ecore_wl_input_get(), types ); + ecore_wl_dnd_selection_set(ecore_wl_input_get(), types); #endif } void RequestItem() { #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get( ecore_wl2_connected_display_get( NULL ) ); - ecore_wl2_dnd_selection_get( input ); + Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get(ecore_wl2_connected_display_get(NULL)); + ecore_wl2_dnd_selection_get(input); #else - const char *types[10] = {0, }; + const char* types[10] = { + 0, + }; int i = -1; types[++i] = "text/plain;charset=utf-8"; @@ -130,77 +131,78 @@ struct Clipboard::Impl #endif Dali::ClipboardEventNotifier clipboardEventNotifier(Dali::ClipboardEventNotifier::Get()); - if ( clipboardEventNotifier ) + if(clipboardEventNotifier) { - clipboardEventNotifier.SetContent( mSendBuffer ); + clipboardEventNotifier.SetContent(mSendBuffer); clipboardEventNotifier.EmitContentSelectedSignal(); } } - char *ExcuteSend( void *event ) + char* ExcuteSend(void* event) { #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Event_Data_Source_Send *ev = reinterpret_cast( event ); + Ecore_Wl2_Event_Data_Source_Send* ev = reinterpret_cast(event); #else - Ecore_Wl_Event_Data_Source_Send *ev = reinterpret_cast( event ); + Ecore_Wl_Event_Data_Source_Send* ev = reinterpret_cast(event); #endif - int len_buf = mSendBuffer.length(); - int len_remained = len_buf; - int len_written = 0, ret; - const char *buf = mSendBuffer.c_str(); + int len_buf = mSendBuffer.length(); + int len_remained = len_buf; + int len_written = 0, ret; + const char* buf = mSendBuffer.c_str(); - while (len_written < len_buf) + while(len_written < len_buf) { - ret = write(ev->fd, buf, len_remained); - if (ret == -1) break; - buf += ret; - len_written += ret; - len_remained -= ret; + ret = write(ev->fd, buf, len_remained); + if(ret == -1) break; + buf += ret; + len_written += ret; + len_remained -= ret; } close(ev->fd); return NULL; } - char *ExcuteReceive( void *event ) + char* ExcuteReceive(void* event) { #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Event_Selection_Data_Ready *ev = reinterpret_cast( event ); + Ecore_Wl2_Event_Selection_Data_Ready* ev = reinterpret_cast(event); #else - Ecore_Wl_Event_Selection_Data_Ready *ev = reinterpret_cast( event ); + Ecore_Wl_Event_Selection_Data_Ready* ev = reinterpret_cast(event); #endif - return reinterpret_cast( ev->data ); + return reinterpret_cast(ev->data); } int GetCount() { Eldbus_Message *reply, *req; - const char *errname = NULL, *errmsg = NULL; - int count = -1; + const char * errname = NULL, *errmsg = NULL; + int count = -1; - if (!(req = eldbus_proxy_method_call_new(eldbus_proxy, "CbhmGetCount"))) + if(!(req = eldbus_proxy_method_call_new(eldbus_proxy, "CbhmGetCount"))) { DALI_LOG_ERROR("Failed to create method call on org.freedesktop.DBus.Properties.Get"); return -1; } eldbus_message_ref(req); - eldbus_message_arguments_append(req, "i", CBHM_COUNT_ALL) ; + eldbus_message_arguments_append(req, "i", CBHM_COUNT_ALL); reply = eldbus_proxy_send_and_block(eldbus_proxy, req, 100); - if (!reply || eldbus_message_error_get(reply, &errname, &errmsg)) + if(!reply || eldbus_message_error_get(reply, &errname, &errmsg)) { DALI_LOG_ERROR("Unable to call method org.freedesktop.DBus.Properties.Get: %s %s", - errname, errmsg); + errname, + errmsg); eldbus_message_unref(req); - if( reply ) + if(reply) { eldbus_message_unref(reply); } return -1; } - if (!eldbus_message_arguments_get(reply, "i", &count)) + if(!eldbus_message_arguments_get(reply, "i", &count)) { DALI_LOG_ERROR("Cannot get arguments from eldbus"); eldbus_message_unref(req); @@ -218,19 +220,19 @@ struct Clipboard::Impl { eldbus_proxy_call(cbhm_proxy_get(), "CbhmShow", NULL, NULL, -1, "s", "0"); mIsFirstTimeHidden = true; - mVisible = true; + mVisible = true; } - void HideClipboard( bool skipFirstHide ) + void HideClipboard(bool skipFirstHide) { - if ( skipFirstHide && mIsFirstTimeHidden ) + if(skipFirstHide && mIsFirstTimeHidden) { mIsFirstTimeHidden = false; return; } eldbus_proxy_call(cbhm_proxy_get(), "CbhmHide", NULL, NULL, -1, ""); mIsFirstTimeHidden = false; - mVisible = false; + mVisible = false; } bool IsVisible() const @@ -238,17 +240,17 @@ struct Clipboard::Impl return mVisible; } - static void _on_item_clicked(void *data, const Eldbus_Message *msg EINA_UNUSED) + static void _on_item_clicked(void* data, const Eldbus_Message* msg EINA_UNUSED) { static_cast(data)->RequestItem(); } - Eldbus_Proxy *eldbus_proxy; - Eldbus_Connection *cbhm_conn; + Eldbus_Proxy* eldbus_proxy; + Eldbus_Connection* cbhm_conn; std::string mSendBuffer; - bool mVisible; - bool mIsFirstTimeHidden; + bool mVisible; + bool mIsFirstTimeHidden; }; Clipboard::Clipboard(Impl* impl) @@ -265,30 +267,30 @@ Dali::Clipboard Clipboard::Get() { Dali::Clipboard clipboard; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::Clipboard)); if(handle) { // If so, downcast the handle - clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) ); + clipboard = Dali::Clipboard(dynamic_cast(handle.GetObjectPtr())); } else { - Clipboard::Impl* impl( new Clipboard::Impl() ); - clipboard = Dali::Clipboard( new Clipboard(impl) ); - service.Register( typeid(Dali::Clipboard), clipboard ); + Clipboard::Impl* impl(new Clipboard::Impl()); + clipboard = Dali::Clipboard(new Clipboard(impl)); + service.Register(typeid(Dali::Clipboard), clipboard); } } return clipboard; } -bool Clipboard::SetItem(const std::string &itemData ) +bool Clipboard::SetItem(const std::string& itemData) { - mImpl->SetItem( itemData ); + mImpl->SetItem(itemData); return true; } @@ -323,9 +325,9 @@ bool Clipboard::IsVisible() const return mImpl->IsVisible(); } -char* Clipboard::ExcuteBuffered( bool type, void *event ) +char* Clipboard::ExcuteBuffered(bool type, void* event) { - return (type ? mImpl->ExcuteSend( event ) : mImpl->ExcuteReceive( event )); + return (type ? mImpl->ExcuteSend(event) : mImpl->ExcuteReceive(event)); } } // namespace Adaptor diff --git a/dali/internal/clipboard/ubuntu-x11/clipboard-impl-x.cpp b/dali/internal/clipboard/ubuntu-x11/clipboard-impl-x.cpp index 1cb8704..20b0964 100644 --- a/dali/internal/clipboard/ubuntu-x11/clipboard-impl-x.cpp +++ b/dali/internal/clipboard/ubuntu-x11/clipboard-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,28 +19,28 @@ #include // EXTERNAL INCLUDES +#include #include #include #include -#include // INTERNAL INCLUDES -#include -#include #include +#include #include +#include namespace //unnamed namespace { const char* const CBHM_WINDOW = "CBHM_XWIN"; -const char* const CBHM_MSG = "CBHM_MSG"; -const char* const CBHM_ITEM = "CBHM_ITEM"; +const char* const CBHM_MSG = "CBHM_MSG"; +const char* const CBHM_ITEM = "CBHM_ITEM"; const char* const CBHM_cCOUNT = "CBHM_cCOUNT"; -const char* const CBHM_ERROR = "CBHM_ERROR"; -const char* const SET_ITEM = "SET_ITEM"; -const char* const SHOW = "show0"; -const char* const HIDE = "cbhm_hide"; -} +const char* const CBHM_ERROR = "CBHM_ERROR"; +const char* const SET_ITEM = "SET_ITEM"; +const char* const SHOW = "show0"; +const char* const HIDE = "cbhm_hide"; +} // namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Clipboard @@ -48,16 +48,13 @@ const char* const HIDE = "cbhm_hide"; namespace Dali { - namespace Internal { - namespace Adaptor { - struct Clipboard::Impl { - Impl( Ecore_X_Window ecoreXwin ) + Impl(Ecore_X_Window ecoreXwin) { mApplicationWindow = ecoreXwin; } @@ -66,7 +63,7 @@ struct Clipboard::Impl }; Clipboard::Clipboard(Impl* impl) -: mImpl( impl ) +: mImpl(impl) { } @@ -79,51 +76,51 @@ Dali::Clipboard Clipboard::Get() { Dali::Clipboard clipboard; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::Clipboard ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::Clipboard)); if(handle) { // If so, downcast the handle - clipboard = Dali::Clipboard( dynamic_cast< Clipboard* >( handle.GetObjectPtr() ) ); + clipboard = Dali::Clipboard(dynamic_cast(handle.GetObjectPtr())); } else { - Adaptor& adaptorImpl( Adaptor::GetImplementation( Adaptor::Get() ) ); - Any nativewindow = adaptorImpl.GetNativeWindowHandle(); + Adaptor& adaptorImpl(Adaptor::GetImplementation(Adaptor::Get())); + Any nativewindow = adaptorImpl.GetNativeWindowHandle(); // The Ecore_X_Window needs to use the Clipboard. // Only when the render surface is window, we can get the Ecore_X_Window. - Ecore_X_Window ecoreXwin( AnyCast(nativewindow) ); - if (ecoreXwin) + Ecore_X_Window ecoreXwin(AnyCast(nativewindow)); + if(ecoreXwin) { // If we fail to get Ecore_X_Window, we can't use the Clipboard correctly. // Thus you have to call "ecore_imf_context_client_window_set" somewhere. // In EvasPlugIn, this function is called in EvasPlugin::ConnectEcoreEvent(). - Clipboard::Impl* impl( new Clipboard::Impl( ecoreXwin ) ); - clipboard = Dali::Clipboard( new Clipboard( impl ) ); - service.Register( typeid( clipboard ), clipboard ); + Clipboard::Impl* impl(new Clipboard::Impl(ecoreXwin)); + clipboard = Dali::Clipboard(new Clipboard(impl)); + service.Register(typeid(clipboard), clipboard); } } } return clipboard; } -bool Clipboard::SetItem(const std::string &itemData ) +bool Clipboard::SetItem(const std::string& itemData) { - Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow(); - Ecore_X_Atom atomCbhmItem = ecore_x_atom_get( CBHM_ITEM ); - Ecore_X_Atom dataType = ECORE_X_ATOM_STRING; + Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow(); + Ecore_X_Atom atomCbhmItem = ecore_x_atom_get(CBHM_ITEM); + Ecore_X_Atom dataType = ECORE_X_ATOM_STRING; // Set item (property) to send - ecore_x_window_prop_property_set( cbhmWin, atomCbhmItem, dataType, 8, const_cast( itemData.c_str() ), itemData.length() + 1 ); + ecore_x_window_prop_property_set(cbhmWin, atomCbhmItem, dataType, 8, const_cast(itemData.c_str()), itemData.length() + 1); ecore_x_sync(); // Trigger sending of item (property) - Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG ); - ECore::WindowInterface::SendXEvent(ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SET_ITEM ); + Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get(CBHM_MSG); + ECore::WindowInterface::SendXEvent(ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SET_ITEM); return true; } @@ -132,28 +129,28 @@ bool Clipboard::SetItem(const std::string &itemData ) */ void Clipboard::RequestItem() { - int index = 0; + int index = 0; char sendBuf[20]; - snprintf( sendBuf, 20, "%s%d", CBHM_ITEM, index ); - Ecore_X_Atom xAtomCbhmItem = ecore_x_atom_get( sendBuf ); + snprintf(sendBuf, 20, "%s%d", CBHM_ITEM, index); + Ecore_X_Atom xAtomCbhmItem = ecore_x_atom_get(sendBuf); Ecore_X_Atom xAtomItemType = 0; - std::string clipboardString( ECore::WindowInterface::GetWindowProperty(xAtomCbhmItem, &xAtomItemType, index ) ); + std::string clipboardString(ECore::WindowInterface::GetWindowProperty(xAtomCbhmItem, &xAtomItemType, index)); // Only return the text string if the Atom type is text (Do not return a text string/URL for images). - if( !clipboardString.empty() && - ( xAtomItemType == ECORE_X_ATOM_TEXT || xAtomItemType == ECORE_X_ATOM_COMPOUND_TEXT || xAtomItemType == ECORE_X_ATOM_STRING || xAtomItemType == ECORE_X_ATOM_UTF8_STRING ) ) + if(!clipboardString.empty() && + (xAtomItemType == ECORE_X_ATOM_TEXT || xAtomItemType == ECORE_X_ATOM_COMPOUND_TEXT || xAtomItemType == ECORE_X_ATOM_STRING || xAtomItemType == ECORE_X_ATOM_UTF8_STRING)) { - Ecore_X_Atom xAtomCbhmError = ecore_x_atom_get( CBHM_ERROR ); - if ( xAtomItemType != xAtomCbhmError ) + Ecore_X_Atom xAtomCbhmError = ecore_x_atom_get(CBHM_ERROR); + if(xAtomItemType != xAtomCbhmError) { // Call ClipboardEventNotifier to notify event observe of retrieved string Dali::ClipboardEventNotifier clipboardEventNotifier(ClipboardEventNotifier::Get()); - if ( clipboardEventNotifier ) + if(clipboardEventNotifier) { - ClipboardEventNotifier& notifierImpl( ClipboardEventNotifier::GetImplementation( clipboardEventNotifier ) ); + ClipboardEventNotifier& notifierImpl(ClipboardEventNotifier::GetImplementation(clipboardEventNotifier)); - notifierImpl.SetContent( clipboardString ); + notifierImpl.SetContent(clipboardString); notifierImpl.EmitContentSelectedSignal(); } } @@ -165,14 +162,14 @@ void Clipboard::RequestItem() */ unsigned int Clipboard::NumberOfItems() { - Ecore_X_Atom xAtomCbhmCountGet = ecore_x_atom_get( CBHM_cCOUNT ); + Ecore_X_Atom xAtomCbhmCountGet = ecore_x_atom_get(CBHM_cCOUNT); - std::string ret( ECore::WindowInterface::GetWindowProperty( xAtomCbhmCountGet, NULL, 0 ) ); - int count = 0; + std::string ret(ECore::WindowInterface::GetWindowProperty(xAtomCbhmCountGet, NULL, 0)); + int count = 0; - if ( !ret.empty() ) + if(!ret.empty()) { - count = atoi( ret.c_str() ); + count = atoi(ret.c_str()); } return count; @@ -190,16 +187,16 @@ void Clipboard::ShowClipboard() Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow(); // Launch the clipboard window - Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG ); - ECore::WindowInterface::SendXEvent( ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SHOW ); + Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get(CBHM_MSG); + ECore::WindowInterface::SendXEvent(ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, SHOW); } void Clipboard::HideClipboard(bool skipFirstHide) { Ecore_X_Window cbhmWin = ECore::WindowInterface::GetWindow(); // Launch the clipboard window - Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get( CBHM_MSG ); - ECore::WindowInterface::SendXEvent( ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, HIDE ); + Ecore_X_Atom atomCbhmMsg = ecore_x_atom_get(CBHM_MSG); + ECore::WindowInterface::SendXEvent(ecore_x_display_get(), cbhmWin, False, NoEventMask, atomCbhmMsg, 8, HIDE); // release the ownership of SECONDARY selection ecore_x_selection_secondary_clear(); @@ -210,22 +207,22 @@ bool Clipboard::IsVisible() const return false; } -char* Clipboard::ExcuteBuffered( bool type, void *event ) +char* Clipboard::ExcuteBuffered(bool type, void* event) { - if( !type ) + if(!type) { // Receive - Ecore_X_Event_Selection_Notify* selectionNotifyEvent = static_cast< Ecore_X_Event_Selection_Notify* >( event ); + Ecore_X_Event_Selection_Notify* selectionNotifyEvent = static_cast(event); - Ecore_X_Selection_Data* selectionData = static_cast< Ecore_X_Selection_Data* >( selectionNotifyEvent->data ); - if( selectionData->data ) + Ecore_X_Selection_Data* selectionData = static_cast(selectionNotifyEvent->data); + if(selectionData->data) { - if( selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY ) + if(selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY) { // Claim the ownership of the SECONDARY selection. - ecore_x_selection_secondary_set( mImpl->mApplicationWindow, "", 1 ); + ecore_x_selection_secondary_set(mImpl->mApplicationWindow, "", 1); - return ( reinterpret_cast< char* >( selectionData->data ) ); + return (reinterpret_cast(selectionData->data)); } } } diff --git a/dali/internal/graphics/android/egl-image-extensions-android.cpp b/dali/internal/graphics/android/egl-image-extensions-android.cpp index 7630148..e05f4ce 100644 --- a/dali/internal/graphics/android/egl-image-extensions-android.cpp +++ b/dali/internal/graphics/android/egl-image-extensions-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include @@ -31,99 +30,93 @@ // INTERNAL INCLUDES #include - namespace { // function pointers assigned in InitializeEglImageKHR -PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0; -PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0; +PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0; +PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0; PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0; } // unnamed namespace - namespace Dali { - namespace Internal { - namespace Adaptor { - EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl) -: mEglImplementation( eglImpl ), - mImageKHRInitialized( false ), - mImageKHRInitializeFailed( false ) +: mEglImplementation(eglImpl), + mImageKHRInitialized(false), + mImageKHRInitializeFailed(false) { - DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" ); + DALI_ASSERT_ALWAYS(eglImpl && "EGL Implementation not instantiated"); } EglImageExtensions::~EglImageExtensions() = default; void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer) { - if( mImageKHRInitialized == false ) + if(mImageKHRInitialized == false) { InitializeEglImageKHR(); } - if( mImageKHRInitialized == false ) + if(mImageKHRInitialized == false) { return NULL; } // No extensions const EGLint attribs[] = - { - EGL_NONE - }; + { + EGL_NONE}; // EGL constants use C casts #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(), - EGL_NO_CONTEXT, - EGL_NATIVE_BUFFER_ANDROID, - clientBuffer, - attribs ); - - DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "eglCreateImageKHR failed!\n"); - if( EGL_NO_IMAGE_KHR == eglImage ) + EGLImageKHR eglImage = eglCreateImageKHRProc(mEglImplementation->GetDisplay(), + EGL_NO_CONTEXT, + EGL_NATIVE_BUFFER_ANDROID, + clientBuffer, + attribs); + + DALI_ASSERT_DEBUG(EGL_NO_IMAGE_KHR != eglImage && "eglCreateImageKHR failed!\n"); + if(EGL_NO_IMAGE_KHR == eglImage) { - switch( eglGetError() ) + switch(eglGetError()) { - case EGL_SUCCESS : + case EGL_SUCCESS: { break; } case EGL_BAD_DISPLAY: { - DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" ); + DALI_LOG_ERROR("EGL_BAD_DISPLAY: Invalid EGLDisplay object\n"); break; } case EGL_BAD_CONTEXT: { - DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" ); + DALI_LOG_ERROR("EGL_BAD_CONTEXT: Invalid EGLContext object\n"); break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n"); break; } case EGL_BAD_MATCH: { - DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" ); + DALI_LOG_ERROR("EGL_BAD_MATCH: attrib_list does not match target\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n"); break; } case EGL_BAD_ALLOC: { - DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" ); + DALI_LOG_ERROR("EGL_BAD_ALLOC: Insufficient memory is available\n"); break; } default: @@ -139,39 +132,39 @@ void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer) void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) { - DALI_ASSERT_DEBUG( mImageKHRInitialized ); + DALI_ASSERT_DEBUG(mImageKHRInitialized); - if( ! mImageKHRInitialized ) + if(!mImageKHRInitialized) { return; } - if( eglImageKHR == NULL ) + if(eglImageKHR == NULL) { return; } - EGLImageKHR eglImage = static_cast( eglImageKHR ); + EGLImageKHR eglImage = static_cast(eglImageKHR); - EGLBoolean result = eglDestroyImageKHRProc( mEglImplementation->GetDisplay(), eglImage ); + EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage); - if( EGL_FALSE == result ) + if(EGL_FALSE == result) { - switch( eglGetError() ) + switch(eglGetError()) { case EGL_BAD_DISPLAY: { - DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" ); + DALI_LOG_ERROR("EGL_BAD_DISPLAY: Invalid EGLDisplay object\n"); break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: EGLImage sibling error\n"); break; } default: @@ -184,9 +177,9 @@ void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) { - DALI_ASSERT_DEBUG( mImageKHRInitialized ); + DALI_ASSERT_DEBUG(mImageKHRInitialized); - if( eglImageKHR != NULL ) + if(eglImageKHR != NULL) { EGLImageKHR eglImage = static_cast(eglImageKHR); @@ -194,13 +187,13 @@ void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) GLint glError = glGetError(); #endif - glEGLImageTargetTexture2DOESProc(GL_TEXTURE_2D, reinterpret_cast< GLeglImageOES >( eglImage ) ); + glEGLImageTargetTexture2DOESProc(GL_TEXTURE_2D, reinterpret_cast(eglImage)); #ifdef EGL_ERROR_CHECKING glError = glGetError(); - if( GL_NO_ERROR != glError ) + if(GL_NO_ERROR != glError) { - DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError ); + DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError); } #endif } @@ -209,14 +202,14 @@ void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) void EglImageExtensions::InitializeEglImageKHR() { // avoid trying to reload extended KHR functions, if it fails the first time - if( ! mImageKHRInitializeFailed ) + if(!mImageKHRInitializeFailed) { - eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") ); - eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") ); - glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") ); + eglCreateImageKHRProc = reinterpret_cast(eglGetProcAddress("eglCreateImageKHR")); + eglDestroyImageKHRProc = reinterpret_cast(eglGetProcAddress("eglDestroyImageKHR")); + glEGLImageTargetTexture2DOESProc = reinterpret_cast(eglGetProcAddress("glEGLImageTargetTexture2DOES")); } - if( eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc ) + if(eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc) { mImageKHRInitialized = true; } diff --git a/dali/internal/graphics/common/egl-image-extensions.h b/dali/internal/graphics/common/egl-image-extensions.h index 82f8459..b68f218 100644 --- a/dali/internal/graphics/common/egl-image-extensions.h +++ b/dali/internal/graphics/common/egl-image-extensions.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_EGL_IMAGE_EXTENSIONS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,9 +48,7 @@ public: */ ~EglImageExtensions(); - -public: // EGLImageKHR extension support - +public: // EGLImageKHR extension support /** * If the EGL Image extension is available this function returns a * EGLImageKHR @@ -80,9 +78,9 @@ public: // EGLImageKHR extension support private: EglImplementation* mEglImplementation; - bool mImageKHRInitialized; ///< Flag for whether extended KHR functions loaded - bool mImageKHRInitializeFailed; ///< Flag to avoid trying to reload extended KHR functions, if - /// it fails the first time + bool mImageKHRInitialized; ///< Flag for whether extended KHR functions loaded + bool mImageKHRInitializeFailed; ///< Flag to avoid trying to reload extended KHR functions, if + /// it fails the first time }; } // namespace Adaptor diff --git a/dali/internal/graphics/common/graphics-factory-interface.h b/dali/internal/graphics/common/graphics-factory-interface.h index bcec0af..7d83158 100644 --- a/dali/internal/graphics/common/graphics-factory-interface.h +++ b/dali/internal/graphics/common/graphics-factory-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_BASE_GRAPHICS_FACTORY_INTERFACE_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -28,10 +28,8 @@ class GraphicsInterface; namespace Internal { - namespace Adaptor { - /** * Factory interface for creating Graphics Factory implementation */ @@ -53,13 +51,13 @@ protected: /** * Virtual protected destructor - no deletion through this interface */ - virtual ~GraphicsFactoryInterface() {}; + virtual ~GraphicsFactoryInterface(){}; }; -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali #endif // DALI_INTERNAL_BASE_GRAPHICS_FACTORY_INTERFACE_H diff --git a/dali/internal/graphics/generic/egl-image-extensions-generic.cpp b/dali/internal/graphics/generic/egl-image-extensions-generic.cpp index 70ddfde..2c86d85 100644 --- a/dali/internal/graphics/generic/egl-image-extensions-generic.cpp +++ b/dali/internal/graphics/generic/egl-image-extensions-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include @@ -31,31 +30,26 @@ // INTERNAL INCLUDES #include - namespace { // function pointers assigned in InitializeEglImageKHR -PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0; -PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0; +PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0; +PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0; PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0; } // unnamed namespace - namespace Dali { - namespace Internal { - namespace Adaptor { - EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl) : mEglImplementation(eglImpl), mImageKHRInitialized(false), mImageKHRInitializeFailed(false) { - DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" ); + DALI_ASSERT_ALWAYS(eglImpl && "EGL Implementation not instantiated"); } EglImageExtensions::~EglImageExtensions() @@ -64,66 +58,64 @@ EglImageExtensions::~EglImageExtensions() void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer) { - if (mImageKHRInitialized == false) + if(mImageKHRInitialized == false) { InitializeEglImageKHR(); } - if (mImageKHRInitialized == false) + if(mImageKHRInitialized == false) { return NULL; } // Use the EGL image extension const EGLint attribs[] = + { + EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; + + EGLImageKHR eglImage = eglCreateImageKHRProc(mEglImplementation->GetDisplay(), + EGL_NO_CONTEXT, + EGL_NATIVE_PIXMAP_KHR, + clientBuffer, + attribs); + + DALI_ASSERT_DEBUG(EGL_NO_IMAGE_KHR != eglImage && "X11Image::GlExtensionCreate eglCreateImageKHR failed!\n"); + if(EGL_NO_IMAGE_KHR == eglImage) { - EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, - EGL_NONE - }; - - EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(), - EGL_NO_CONTEXT, - EGL_NATIVE_PIXMAP_KHR, - clientBuffer, - attribs ); - - DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "X11Image::GlExtensionCreate eglCreateImageKHR failed!\n"); - if( EGL_NO_IMAGE_KHR == eglImage ) - { - switch( eglGetError() ) + switch(eglGetError()) { - case EGL_SUCCESS : + case EGL_SUCCESS: { break; } case EGL_BAD_DISPLAY: { - DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" ); + DALI_LOG_ERROR("EGL_BAD_DISPLAY: Invalid EGLDisplay object\n"); break; } case EGL_BAD_CONTEXT: { - DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" ); + DALI_LOG_ERROR("EGL_BAD_CONTEXT: Invalid EGLContext object\n"); break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n"); break; } case EGL_BAD_MATCH: { - DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" ); + DALI_LOG_ERROR("EGL_BAD_MATCH: attrib_list does not match target\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n"); break; } case EGL_BAD_ALLOC: { - DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" ); + DALI_LOG_ERROR("EGL_BAD_ALLOC: Insufficient memory is available\n"); break; } default: @@ -138,14 +130,14 @@ void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer) void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) { - DALI_ASSERT_DEBUG( mImageKHRInitialized ); + DALI_ASSERT_DEBUG(mImageKHRInitialized); - if( ! mImageKHRInitialized ) + if(!mImageKHRInitialized) { return; } - if( eglImageKHR == NULL ) + if(eglImageKHR == NULL) { return; } @@ -154,23 +146,23 @@ void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage); - if( EGL_FALSE == result ) + if(EGL_FALSE == result) { - switch( eglGetError() ) + switch(eglGetError()) { case EGL_BAD_DISPLAY: { - DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" ); + DALI_LOG_ERROR("EGL_BAD_DISPLAY: Invalid EGLDisplay object\n"); break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: EGLImage sibling error\n"); break; } default: @@ -183,9 +175,9 @@ void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) { - DALI_ASSERT_DEBUG( mImageKHRInitialized ); + DALI_ASSERT_DEBUG(mImageKHRInitialized); - if( eglImageKHR != NULL ) + if(eglImageKHR != NULL) { EGLImageKHR eglImage = static_cast(eglImageKHR); @@ -193,13 +185,13 @@ void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) GLint glError = glGetError(); #endif - glEGLImageTargetTexture2DOESProc(GL_TEXTURE_2D, reinterpret_cast< GLeglImageOES >( eglImage ) ); + glEGLImageTargetTexture2DOESProc(GL_TEXTURE_2D, reinterpret_cast(eglImage)); #ifdef EGL_ERROR_CHECKING glError = glGetError(); - if( GL_NO_ERROR != glError ) + if(GL_NO_ERROR != glError) { - DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError ); + DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError); } #endif } @@ -208,14 +200,14 @@ void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) void EglImageExtensions::InitializeEglImageKHR() { // avoid trying to reload extended KHR functions, if it fails the first time - if( ! mImageKHRInitializeFailed ) + if(!mImageKHRInitializeFailed) { - eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") ); - eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") ); - glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") ); + eglCreateImageKHRProc = reinterpret_cast(eglGetProcAddress("eglCreateImageKHR")); + eglDestroyImageKHRProc = reinterpret_cast(eglGetProcAddress("eglDestroyImageKHR")); + glEGLImageTargetTexture2DOESProc = reinterpret_cast(eglGetProcAddress("glEGLImageTargetTexture2DOES")); } - if (eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc) + if(eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc) { mImageKHRInitialized = true; } diff --git a/dali/internal/graphics/gles/egl-context-helper-implementation.cpp b/dali/internal/graphics/gles/egl-context-helper-implementation.cpp index 15085a1..6a4a46c 100644 --- a/dali/internal/graphics/gles/egl-context-helper-implementation.cpp +++ b/dali/internal/graphics/gles/egl-context-helper-implementation.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,28 +31,27 @@ namespace Internal { namespace Adaptor { - EglContextHelperImplementation::EglContextHelperImplementation() -: mEglImplementation( NULL ) +: mEglImplementation(NULL) { } -void EglContextHelperImplementation::Initialize( EglImplementation* eglImpl ) +void EglContextHelperImplementation::Initialize(EglImplementation* eglImpl) { mEglImplementation = eglImpl; } void EglContextHelperImplementation::MakeSurfacelessContextCurrent() { - if ( mEglImplementation && mEglImplementation->IsSurfacelessContextSupported() ) + if(mEglImplementation && mEglImplementation->IsSurfacelessContextSupported()) { - mEglImplementation->MakeContextCurrent( EGL_NO_SURFACE, mEglImplementation->GetContext() ); + mEglImplementation->MakeContextCurrent(EGL_NO_SURFACE, mEglImplementation->GetContext()); } } void EglContextHelperImplementation::MakeContextNull() { - if ( mEglImplementation ) + if(mEglImplementation) { mEglImplementation->MakeContextNull(); } @@ -60,12 +59,12 @@ void EglContextHelperImplementation::MakeContextNull() void EglContextHelperImplementation::WaitClient() { - if ( mEglImplementation ) + if(mEglImplementation) { mEglImplementation->WaitClient(); } } -} // namespace Dali -} // namespace Internal } // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/graphics/gles/egl-context-helper-implementation.h b/dali/internal/graphics/gles/egl-context-helper-implementation.h index ba188f4..961b4c8 100644 --- a/dali/internal/graphics/gles/egl-context-helper-implementation.h +++ b/dali/internal/graphics/gles/egl-context-helper-implementation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_EGL_CONTEXT_HELPER_IMPLEMENTATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ namespace Dali { - namespace Integration { class RenderSurface; @@ -37,7 +36,6 @@ namespace Internal { namespace Adaptor { - class EglImplementation; /** @@ -61,7 +59,7 @@ public: * Initialize with the Egl implementation. * @param[in] impl The EGL implementation (to access the EGL context) */ - void Initialize( EglImplementation* impl ); + void Initialize(EglImplementation* impl); /** * @copydoc Dali::Integration::GlContextHelperAbstraction::MakeSurfacelessContextCurrent() @@ -79,7 +77,6 @@ public: void WaitClient() override; private: - EglImplementation* mEglImplementation; ///< Egl implementation (to access the EGL context) }; diff --git a/dali/internal/graphics/gles/egl-debug.cpp b/dali/internal/graphics/gles/egl-debug.cpp index 1f5bbfa..7c96d3d 100644 --- a/dali/internal/graphics/gles/egl-debug.cpp +++ b/dali/internal/graphics/gles/egl-debug.cpp @@ -23,19 +23,15 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace Egl { - -void PrintError( EGLint error) +void PrintError(EGLint error) { - switch (error) + switch(error) { case EGL_BAD_DISPLAY: { @@ -100,10 +96,10 @@ void PrintError( EGLint error) } } -} // namespace Egl +} // namespace Egl -} // namespace Adaptor +} // namespace Adaptor -} // namespace Internal +} // namespace Internal -} // namespace Dali +} // namespace Dali diff --git a/dali/internal/graphics/gles/egl-debug.h b/dali/internal/graphics/gles/egl-debug.h index 81b6a5e..72c3d3f 100644 --- a/dali/internal/graphics/gles/egl-debug.h +++ b/dali/internal/graphics/gles/egl-debug.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_EGL_DEBUG_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,24 +22,20 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace Egl { +void PrintError(EGLint error); -void PrintError( EGLint error); - -} // namespace Egl +} // namespace Egl -} // namespace Adaptor +} // namespace Adaptor -} // namespace Internal +} // namespace Internal -} // namespace Dali +} // namespace Dali #endif //DALI_INTERNAL_EGL_DEBUG_H diff --git a/dali/internal/graphics/gles/egl-factory-interface.h b/dali/internal/graphics/gles/egl-factory-interface.h index 3a8f9f6..1cd1270 100644 --- a/dali/internal/graphics/gles/egl-factory-interface.h +++ b/dali/internal/graphics/gles/egl-factory-interface.h @@ -20,14 +20,12 @@ namespace Dali { - class EglInterface; namespace Internal { namespace Adaptor { - /** * Factory interface for creating EGL implementation */ @@ -49,11 +47,11 @@ protected: /** * Virtual protected destructor - no deletion through this interface */ - virtual ~EglFactoryInterface() {}; + virtual ~EglFactoryInterface(){}; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_BASE_EGL_FACTORY_INTERFACE_H diff --git a/dali/internal/graphics/gles/egl-implementation.cpp b/dali/internal/graphics/gles/egl-implementation.cpp old mode 100755 new mode 100644 index ee4e08e..8168b72 --- a/dali/internal/graphics/gles/egl-implementation.cpp +++ b/dali/internal/graphics/gles/egl-implementation.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,19 +15,18 @@ * */ - // CLASS HEADER #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include // EGL constants use C style casts #pragma GCC diagnostic push @@ -35,63 +34,60 @@ namespace { - const uint32_t THRESHOLD_SWAPBUFFER_COUNT = 5; - const uint32_t CHECK_EXTENSION_NUMBER = 4; - const uint32_t EGL_VERSION_SUPPORT_SURFACELESS_CONTEXT = 15; - const std::string EGL_KHR_SURFACELESS_CONTEXT = "EGL_KHR_surfaceless_context"; - const std::string EGL_KHR_CREATE_CONTEXT = "EGL_KHR_create_context"; - const std::string EGL_KHR_PARTIAL_UPDATE = "EGL_KHR_partial_update"; - const std::string EGL_KHR_SWAP_BUFFERS_WITH_DAMAGE = "EGL_KHR_swap_buffers_with_damage"; +const uint32_t THRESHOLD_SWAPBUFFER_COUNT = 5; +const uint32_t CHECK_EXTENSION_NUMBER = 4; +const uint32_t EGL_VERSION_SUPPORT_SURFACELESS_CONTEXT = 15; +const std::string EGL_KHR_SURFACELESS_CONTEXT = "EGL_KHR_surfaceless_context"; +const std::string EGL_KHR_CREATE_CONTEXT = "EGL_KHR_create_context"; +const std::string EGL_KHR_PARTIAL_UPDATE = "EGL_KHR_partial_update"; +const std::string EGL_KHR_SWAP_BUFFERS_WITH_DAMAGE = "EGL_KHR_swap_buffers_with_damage"; -} +} // namespace namespace Dali { - namespace Internal { - namespace Adaptor { - -#define TEST_EGL_ERROR(lastCommand) \ -{ \ - EGLint err = eglGetError(); \ - if (err != EGL_SUCCESS) \ - { \ - DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \ - Egl::PrintError(err); \ - DALI_ASSERT_ALWAYS(0 && "EGL error"); \ - } \ -} - -EglImplementation::EglImplementation( int multiSamplingLevel, - Integration::DepthBufferAvailable depthBufferRequired, - Integration::StencilBufferAvailable stencilBufferRequired , - Integration::PartialUpdateAvailable partialUpdateRequired ) +#define TEST_EGL_ERROR(lastCommand) \ + { \ + EGLint err = eglGetError(); \ + if(err != EGL_SUCCESS) \ + { \ + DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \ + Egl::PrintError(err); \ + DALI_ASSERT_ALWAYS(0 && "EGL error"); \ + } \ + } + +EglImplementation::EglImplementation(int multiSamplingLevel, + Integration::DepthBufferAvailable depthBufferRequired, + Integration::StencilBufferAvailable stencilBufferRequired, + Integration::PartialUpdateAvailable partialUpdateRequired) : mContextAttribs(), - mEglNativeDisplay( 0 ), - mEglNativeWindow( 0 ), - mCurrentEglNativePixmap( 0 ), - mEglDisplay( 0 ), - mEglConfig( 0 ), - mEglContext( 0 ), - mCurrentEglSurface( 0 ), - mCurrentEglContext( EGL_NO_CONTEXT ), - mMultiSamplingLevel( multiSamplingLevel ), - mGlesVersion( 30 ), - mColorDepth( COLOR_DEPTH_24 ), - mGlesInitialized( false ), - mIsOwnSurface( true ), - mIsWindow( true ), - mDepthBufferRequired( depthBufferRequired == Integration::DepthBufferAvailable::TRUE ), - mStencilBufferRequired( stencilBufferRequired == Integration::StencilBufferAvailable::TRUE ), - mPartialUpdateRequired( partialUpdateRequired == Integration::PartialUpdateAvailable::TRUE ), - mIsSurfacelessContextSupported( false ), - mIsKhrCreateContextSupported( false ), - mSwapBufferCountAfterResume( 0 ), - mEglSetDamageRegionKHR( 0 ), - mEglSwapBuffersWithDamageKHR( 0 ) + mEglNativeDisplay(0), + mEglNativeWindow(0), + mCurrentEglNativePixmap(0), + mEglDisplay(0), + mEglConfig(0), + mEglContext(0), + mCurrentEglSurface(0), + mCurrentEglContext(EGL_NO_CONTEXT), + mMultiSamplingLevel(multiSamplingLevel), + mGlesVersion(30), + mColorDepth(COLOR_DEPTH_24), + mGlesInitialized(false), + mIsOwnSurface(true), + mIsWindow(true), + mDepthBufferRequired(depthBufferRequired == Integration::DepthBufferAvailable::TRUE), + mStencilBufferRequired(stencilBufferRequired == Integration::StencilBufferAvailable::TRUE), + mPartialUpdateRequired(partialUpdateRequired == Integration::PartialUpdateAvailable::TRUE), + mIsSurfacelessContextSupported(false), + mIsKhrCreateContextSupported(false), + mSwapBufferCountAfterResume(0), + mEglSetDamageRegionKHR(0), + mEglSwapBuffersWithDamageKHR(0) { } @@ -100,30 +96,30 @@ EglImplementation::~EglImplementation() TerminateGles(); } -bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwnSurface ) +bool EglImplementation::InitializeGles(EGLNativeDisplayType display, bool isOwnSurface) { - if ( !mGlesInitialized ) + if(!mGlesInitialized) { mEglNativeDisplay = display; // Try to get the display connection for the native display first - mEglDisplay = eglGetDisplay( mEglNativeDisplay ); + mEglDisplay = eglGetDisplay(mEglNativeDisplay); - if( mEglDisplay == EGL_NO_DISPLAY ) + if(mEglDisplay == EGL_NO_DISPLAY) { // If failed, try to get the default display connection - mEglDisplay = eglGetDisplay( EGL_DEFAULT_DISPLAY ); + mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); } - if( mEglDisplay == EGL_NO_DISPLAY ) + if(mEglDisplay == EGL_NO_DISPLAY) { // Still failed to get a display connection - throw Dali::DaliException( "", "OpenGL ES is not supported"); + throw Dali::DaliException("", "OpenGL ES is not supported"); } EGLint majorVersion = 0; EGLint minorVersion = 0; - if ( !eglInitialize( mEglDisplay, &majorVersion, &minorVersion ) ) + if(!eglInitialize(mEglDisplay, &majorVersion, &minorVersion)) { return false; } @@ -132,26 +128,26 @@ bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwn mIsOwnSurface = isOwnSurface; } - const char* const versionStr = eglQueryString( mEglDisplay, EGL_VERSION ); - const char* const extensionStr = eglQueryString( mEglDisplay, EGL_EXTENSIONS ); + const char* const versionStr = eglQueryString(mEglDisplay, EGL_VERSION); + const char* const extensionStr = eglQueryString(mEglDisplay, EGL_EXTENSIONS); // Query EGL extensions to check whether required extensions are supported - std::istringstream versionStream( versionStr ); - std::string majorVersion, minorVersion; - std::getline( versionStream, majorVersion, '.' ); - std::getline( versionStream, minorVersion ); + std::istringstream versionStream(versionStr); + std::string majorVersion, minorVersion; + std::getline(versionStream, majorVersion, '.'); + std::getline(versionStream, minorVersion); uint32_t extensionCheckCount = 0; - if( stoul( majorVersion ) * 10 + stoul( minorVersion ) >= EGL_VERSION_SUPPORT_SURFACELESS_CONTEXT ) + if(stoul(majorVersion) * 10 + stoul(minorVersion) >= EGL_VERSION_SUPPORT_SURFACELESS_CONTEXT) { mIsSurfacelessContextSupported = true; - mIsKhrCreateContextSupported = true; + mIsKhrCreateContextSupported = true; extensionCheckCount += 2; } std::istringstream stream(extensionStr); - std::string currentExtension; - bool isKhrPartialUpdateSupported = false; - bool isKhrSwapBuffersWithDamageSupported = false; + std::string currentExtension; + bool isKhrPartialUpdateSupported = false; + bool isKhrSwapBuffersWithDamageSupported = false; while(std::getline(stream, currentExtension, ' ') && extensionCheckCount < CHECK_EXTENSION_NUMBER) { if(currentExtension == EGL_KHR_SURFACELESS_CONTEXT && !mIsSurfacelessContextSupported) @@ -184,17 +180,18 @@ bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwn mGlesInitialized = true; // We want to display this information all the time, so use the LogMessage directly - Integration::Log::LogMessage(Integration::Log::DebugInfo, "EGL Information\n" - " PartialUpdate %d\n" - " Vendor: %s\n" - " Version: %s\n" - " Client APIs: %s\n" - " Extensions: %s\n", - mPartialUpdateRequired, - eglQueryString( mEglDisplay, EGL_VENDOR ), - versionStr, - eglQueryString( mEglDisplay, EGL_CLIENT_APIS ), - extensionStr); + Integration::Log::LogMessage(Integration::Log::DebugInfo, + "EGL Information\n" + " PartialUpdate %d\n" + " Vendor: %s\n" + " Version: %s\n" + " Client APIs: %s\n" + " Extensions: %s\n", + mPartialUpdateRequired, + eglQueryString(mEglDisplay, EGL_VENDOR), + versionStr, + eglQueryString(mEglDisplay, EGL_CLIENT_APIS), + extensionStr); return mGlesInitialized; } @@ -202,12 +199,12 @@ bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwn bool EglImplementation::CreateContext() { // make sure a context isn't created twice - DALI_ASSERT_ALWAYS( (mEglContext == 0) && "EGL context recreated" ); + DALI_ASSERT_ALWAYS((mEglContext == 0) && "EGL context recreated"); mEglContext = eglCreateContext(mEglDisplay, mEglConfig, NULL, &(mContextAttribs[0])); TEST_EGL_ERROR("eglCreateContext render thread"); - DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != mEglContext && "EGL context not created" ); + DALI_ASSERT_ALWAYS(EGL_NO_CONTEXT != mEglContext && "EGL context not created"); DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR)); DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER)); @@ -216,13 +213,13 @@ bool EglImplementation::CreateContext() DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS)); mEglSetDamageRegionKHR = reinterpret_cast(eglGetProcAddress("eglSetDamageRegionKHR")); - if (!mEglSetDamageRegionKHR) + if(!mEglSetDamageRegionKHR) { DALI_LOG_ERROR("Coudn't find eglSetDamageRegionKHR!\n"); mPartialUpdateRequired = false; } mEglSwapBuffersWithDamageKHR = reinterpret_cast(eglGetProcAddress("eglSwapBuffersWithDamageKHR")); - if (!mEglSwapBuffersWithDamageKHR) + if(!mEglSwapBuffersWithDamageKHR) { DALI_LOG_ERROR("Coudn't find eglSwapBuffersWithDamageKHR!\n"); mPartialUpdateRequired = false; @@ -230,15 +227,15 @@ bool EglImplementation::CreateContext() return true; } -bool EglImplementation::CreateWindowContext( EGLContext& eglContext ) +bool EglImplementation::CreateWindowContext(EGLContext& eglContext) { // make sure a context isn't created twice - DALI_ASSERT_ALWAYS( (eglContext == 0) && "EGL context recreated" ); + DALI_ASSERT_ALWAYS((eglContext == 0) && "EGL context recreated"); eglContext = eglCreateContext(mEglDisplay, mEglConfig, mEglContext, &(mContextAttribs[0])); TEST_EGL_ERROR("eglCreateContext render thread"); - DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != eglContext && "EGL context not created" ); + DALI_ASSERT_ALWAYS(EGL_NO_CONTEXT != eglContext && "EGL context not created"); DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR)); DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER)); @@ -246,16 +243,16 @@ bool EglImplementation::CreateWindowContext( EGLContext& eglContext ) DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS)); - mEglWindowContexts.push_back( eglContext ); + mEglWindowContexts.push_back(eglContext); mEglSetDamageRegionKHR = reinterpret_cast(eglGetProcAddress("eglSetDamageRegionKHR")); - if (!mEglSetDamageRegionKHR) + if(!mEglSetDamageRegionKHR) { DALI_LOG_ERROR("Coudn't find eglSetDamageRegionKHR!\n"); mPartialUpdateRequired = false; } mEglSwapBuffersWithDamageKHR = reinterpret_cast(eglGetProcAddress("eglSwapBuffersWithDamageKHR")); - if (!mEglSwapBuffersWithDamageKHR) + if(!mEglSwapBuffersWithDamageKHR) { DALI_LOG_ERROR("Coudn't find eglSwapBuffersWithDamageKHR!\n"); mPartialUpdateRequired = false; @@ -263,29 +260,29 @@ bool EglImplementation::CreateWindowContext( EGLContext& eglContext ) return true; } -void EglImplementation::DestroyContext( EGLContext& eglContext ) +void EglImplementation::DestroyContext(EGLContext& eglContext) { - if( eglContext ) + if(eglContext) { - eglDestroyContext( mEglDisplay, eglContext ); + eglDestroyContext(mEglDisplay, eglContext); eglContext = 0; } } -void EglImplementation::DestroySurface( EGLSurface& eglSurface ) +void EglImplementation::DestroySurface(EGLSurface& eglSurface) { if(mIsOwnSurface && eglSurface) { // Make context null to prevent crash in driver side MakeContextNull(); - eglDestroySurface( mEglDisplay, eglSurface ); + eglDestroySurface(mEglDisplay, eglSurface); eglSurface = 0; } } -void EglImplementation::MakeContextCurrent( EGLSurface eglSurface, EGLContext eglContext ) +void EglImplementation::MakeContextCurrent(EGLSurface eglSurface, EGLContext eglContext) { - if (mCurrentEglContext == eglContext) + if(mCurrentEglContext == eglContext) { return; } @@ -294,14 +291,14 @@ void EglImplementation::MakeContextCurrent( EGLSurface eglSurface, EGLContext eg if(mIsOwnSurface) { - eglMakeCurrent( mEglDisplay, eglSurface, eglSurface, eglContext ); + eglMakeCurrent(mEglDisplay, eglSurface, eglSurface, eglContext); mCurrentEglContext = eglContext; } EGLint error = eglGetError(); - if ( error != EGL_SUCCESS ) + if(error != EGL_SUCCESS) { Egl::PrintError(error); @@ -309,26 +306,26 @@ void EglImplementation::MakeContextCurrent( EGLSurface eglSurface, EGLContext eg } } -void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface ) +void EglImplementation::MakeCurrent(EGLNativePixmapType pixmap, EGLSurface eglSurface) { - if (mCurrentEglContext == mEglContext) + if(mCurrentEglContext == mEglContext) { return; } mCurrentEglNativePixmap = pixmap; - mCurrentEglSurface = eglSurface; + mCurrentEglSurface = eglSurface; if(mIsOwnSurface) { - eglMakeCurrent( mEglDisplay, eglSurface, eglSurface, mEglContext ); + eglMakeCurrent(mEglDisplay, eglSurface, eglSurface, mEglContext); mCurrentEglContext = mEglContext; } EGLint error = eglGetError(); - if ( error != EGL_SUCCESS ) + if(error != EGL_SUCCESS) { Egl::PrintError(error); @@ -339,18 +336,18 @@ void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglS void EglImplementation::MakeContextNull() { // clear the current context - eglMakeCurrent( mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT ); + eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); mCurrentEglContext = EGL_NO_CONTEXT; } void EglImplementation::TerminateGles() { - if ( mGlesInitialized ) + if(mGlesInitialized) { // Make context null to prevent crash in driver side MakeContextNull(); - for ( auto eglSurface : mEglWindowSurfaces ) + for(auto eglSurface : mEglWindowSurfaces) { if(mIsOwnSurface && eglSurface) { @@ -358,16 +355,16 @@ void EglImplementation::TerminateGles() } } eglDestroyContext(mEglDisplay, mEglContext); - for ( auto eglContext : mEglWindowContexts ) + for(auto eglContext : mEglWindowContexts) { eglDestroyContext(mEglDisplay, eglContext); } eglTerminate(mEglDisplay); - mEglDisplay = NULL; - mEglConfig = NULL; - mEglContext = NULL; + mEglDisplay = NULL; + mEglConfig = NULL; + mEglContext = NULL; mCurrentEglSurface = NULL; mCurrentEglContext = EGL_NO_CONTEXT; @@ -380,24 +377,24 @@ bool EglImplementation::IsGlesInitialized() const return mGlesInitialized; } -void EglImplementation::SwapBuffers( EGLSurface& eglSurface ) +void EglImplementation::SwapBuffers(EGLSurface& eglSurface) { - if ( eglSurface != EGL_NO_SURFACE ) // skip if using surfaceless context + if(eglSurface != EGL_NO_SURFACE) // skip if using surfaceless context { #ifndef DALI_PROFILE_UBUNTU - if( mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT ) + if(mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT) { - DALI_LOG_RELEASE_INFO( "EglImplementation::SwapBuffers started.\n" ); + DALI_LOG_RELEASE_INFO("EglImplementation::SwapBuffers started.\n"); } #endif //DALI_PROFILE_UBUNTU // DALI_LOG_ERROR("EglImplementation::SwapBuffers()\n"); - eglSwapBuffers( mEglDisplay, eglSurface ); + eglSwapBuffers(mEglDisplay, eglSurface); #ifndef DALI_PROFILE_UBUNTU - if( mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT ) + if(mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT) { - DALI_LOG_RELEASE_INFO( "EglImplementation::SwapBuffers finished.\n" ); + DALI_LOG_RELEASE_INFO("EglImplementation::SwapBuffers finished.\n"); mSwapBufferCountAfterResume++; } #endif //DALI_PROFILE_UBUNTU @@ -408,7 +405,7 @@ EGLint EglImplementation::GetBufferAge(EGLSurface& eglSurface) const { EGLint age = 0; eglQuerySurface(mEglDisplay, eglSurface, EGL_BUFFER_AGE_EXT, &age); - if (age < 0) + if(age < 0) { DALI_LOG_ERROR("eglQuerySurface(%d)\n", eglGetError()); age = 0; @@ -416,7 +413,7 @@ EGLint EglImplementation::GetBufferAge(EGLSurface& eglSurface) const // 0 - invalid buffer // 1, 2, 3 - if (age > 3) + if(age > 3) { DALI_LOG_ERROR("EglImplementation::GetBufferAge() buffer age %d > 3\n", age); age = 0; // shoudn't be more than 3 back buffers, if there is just reset, I don't want to add extra history level @@ -425,59 +422,59 @@ EGLint EglImplementation::GetBufferAge(EGLSurface& eglSurface) const return age; } -void EglImplementation::SetDamageRegion( EGLSurface& eglSurface, std::vector< Rect< int > >& damagedRects ) +void EglImplementation::SetDamageRegion(EGLSurface& eglSurface, std::vector>& damagedRects) { - if( !mPartialUpdateRequired ) + if(!mPartialUpdateRequired) { return; } - if( eglSurface != EGL_NO_SURFACE ) // skip if using surfaceless context + if(eglSurface != EGL_NO_SURFACE) // skip if using surfaceless context { - EGLBoolean result = mEglSetDamageRegionKHR( mEglDisplay, eglSurface, reinterpret_cast< int* >( damagedRects.data() ), 1 ); - if (result == EGL_FALSE) + EGLBoolean result = mEglSetDamageRegionKHR(mEglDisplay, eglSurface, reinterpret_cast(damagedRects.data()), 1); + if(result == EGL_FALSE) { - DALI_LOG_ERROR( "eglSetDamageRegionKHR(%d)\n", eglGetError() ); + DALI_LOG_ERROR("eglSetDamageRegionKHR(%d)\n", eglGetError()); } } } void EglImplementation::SwapBuffers(EGLSurface& eglSurface, const std::vector>& damagedRects) { - if (eglSurface != EGL_NO_SURFACE ) // skip if using surfaceless context + if(eglSurface != EGL_NO_SURFACE) // skip if using surfaceless context { - if (!mPartialUpdateRequired ) + if(!mPartialUpdateRequired) { SwapBuffers(eglSurface); return; } #ifndef DALI_PROFILE_UBUNTU - if( mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT ) + if(mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT) { - DALI_LOG_RELEASE_INFO( "EglImplementation::SwapBuffers started.\n" ); + DALI_LOG_RELEASE_INFO("EglImplementation::SwapBuffers started.\n"); } #endif //DALI_PROFILE_UBUNTU - EGLBoolean result = mEglSwapBuffersWithDamageKHR(mEglDisplay, eglSurface, reinterpret_cast(const_cast< std::vector< Rect< int > >& >( damagedRects ).data()), damagedRects.size()); - if (result == EGL_FALSE) + EGLBoolean result = mEglSwapBuffersWithDamageKHR(mEglDisplay, eglSurface, reinterpret_cast(const_cast>&>(damagedRects).data()), damagedRects.size()); + if(result == EGL_FALSE) { DALI_LOG_ERROR("eglSwapBuffersWithDamageKHR(%d)\n", eglGetError()); } #ifndef DALI_PROFILE_UBUNTU - if( mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT ) + if(mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT) { - DALI_LOG_RELEASE_INFO( "EglImplementation::SwapBuffers finished.\n" ); + DALI_LOG_RELEASE_INFO("EglImplementation::SwapBuffers finished.\n"); mSwapBufferCountAfterResume++; } #endif //DALI_PROFILE_UBUNTU } } -void EglImplementation::CopyBuffers( EGLSurface& eglSurface ) +void EglImplementation::CopyBuffers(EGLSurface& eglSurface) { - eglCopyBuffers( mEglDisplay, eglSurface, mCurrentEglNativePixmap ); + eglCopyBuffers(mEglDisplay, eglSurface, mCurrentEglNativePixmap); } void EglImplementation::WaitGL() @@ -485,7 +482,7 @@ void EglImplementation::WaitGL() eglWaitGL(); } -bool EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth ) +bool EglImplementation::ChooseConfig(bool isWindowType, ColorDepth depth) { if(mEglConfig && isWindowType == mIsWindow && mColorDepth == depth) { @@ -493,78 +490,78 @@ bool EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth ) } mColorDepth = depth; - mIsWindow = isWindowType; + mIsWindow = isWindowType; - EGLint numConfigs; + EGLint numConfigs; Vector configAttribs; configAttribs.Reserve(31); if(isWindowType) { - configAttribs.PushBack( EGL_SURFACE_TYPE ); - configAttribs.PushBack( EGL_WINDOW_BIT ); + configAttribs.PushBack(EGL_SURFACE_TYPE); + configAttribs.PushBack(EGL_WINDOW_BIT); } else { - configAttribs.PushBack( EGL_SURFACE_TYPE ); - configAttribs.PushBack( EGL_PIXMAP_BIT ); + configAttribs.PushBack(EGL_SURFACE_TYPE); + configAttribs.PushBack(EGL_PIXMAP_BIT); } - configAttribs.PushBack( EGL_RENDERABLE_TYPE ); + configAttribs.PushBack(EGL_RENDERABLE_TYPE); - if( mGlesVersion >= 30 ) + if(mGlesVersion >= 30) { - configAttribs.PushBack( EGL_OPENGL_ES3_BIT_KHR ); + configAttribs.PushBack(EGL_OPENGL_ES3_BIT_KHR); } else { - configAttribs.PushBack( EGL_OPENGL_ES2_BIT ); + configAttribs.PushBack(EGL_OPENGL_ES2_BIT); } -// TODO: enable this flag when it becomes supported -// configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR ); -// configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR ); + // TODO: enable this flag when it becomes supported + // configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR ); + // configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR ); - configAttribs.PushBack( EGL_RED_SIZE ); - configAttribs.PushBack( 8 ); - configAttribs.PushBack( EGL_GREEN_SIZE ); - configAttribs.PushBack( 8 ); - configAttribs.PushBack( EGL_BLUE_SIZE ); - configAttribs.PushBack( 8 ); + configAttribs.PushBack(EGL_RED_SIZE); + configAttribs.PushBack(8); + configAttribs.PushBack(EGL_GREEN_SIZE); + configAttribs.PushBack(8); + configAttribs.PushBack(EGL_BLUE_SIZE); + configAttribs.PushBack(8); -// For underlay video playback, we also need to set the alpha value of the 24/32bit window. - configAttribs.PushBack( EGL_ALPHA_SIZE ); - configAttribs.PushBack( 8 ); + // For underlay video playback, we also need to set the alpha value of the 24/32bit window. + configAttribs.PushBack(EGL_ALPHA_SIZE); + configAttribs.PushBack(8); - configAttribs.PushBack( EGL_DEPTH_SIZE ); - configAttribs.PushBack( mDepthBufferRequired ? 24 : 0 ); - configAttribs.PushBack( EGL_STENCIL_SIZE ); - configAttribs.PushBack( mStencilBufferRequired ? 8 : 0 ); + configAttribs.PushBack(EGL_DEPTH_SIZE); + configAttribs.PushBack(mDepthBufferRequired ? 24 : 0); + configAttribs.PushBack(EGL_STENCIL_SIZE); + configAttribs.PushBack(mStencilBufferRequired ? 8 : 0); #ifndef DALI_PROFILE_UBUNTU - if( mMultiSamplingLevel != EGL_DONT_CARE ) + if(mMultiSamplingLevel != EGL_DONT_CARE) { - configAttribs.PushBack( EGL_SAMPLES ); - configAttribs.PushBack( mMultiSamplingLevel ); - configAttribs.PushBack( EGL_SAMPLE_BUFFERS ); - configAttribs.PushBack( 1 ); + configAttribs.PushBack(EGL_SAMPLES); + configAttribs.PushBack(mMultiSamplingLevel); + configAttribs.PushBack(EGL_SAMPLE_BUFFERS); + configAttribs.PushBack(1); } #endif // DALI_PROFILE_UBUNTU - configAttribs.PushBack( EGL_NONE ); + configAttribs.PushBack(EGL_NONE); // Ensure number of configs is set to 1 as on some drivers, // eglChooseConfig succeeds but does not actually create a proper configuration. - if ( ( eglChooseConfig( mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs ) != EGL_TRUE ) || - ( numConfigs != 1 ) ) + if((eglChooseConfig(mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs) != EGL_TRUE) || + (numConfigs != 1)) { - if( mGlesVersion >= 30 ) + if(mGlesVersion >= 30) { mEglConfig = NULL; DALI_LOG_ERROR("Fail to use OpenGL es 3.0. Retrying to use OpenGL es 2.0."); return false; } - if ( numConfigs != 1 ) + if(numConfigs != 1) { DALI_LOG_ERROR("No configurations found.\n"); @@ -572,7 +569,7 @@ bool EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth ) } EGLint error = eglGetError(); - switch (error) + switch(error) { case EGL_BAD_DISPLAY: { @@ -602,63 +599,63 @@ bool EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth ) DALI_ASSERT_ALWAYS(false && "eglChooseConfig failed!"); return false; } - Integration::Log::LogMessage(Integration::Log::DebugInfo, "Using OpenGL es %d.%d.\n", mGlesVersion / 10, mGlesVersion % 10 ); + Integration::Log::LogMessage(Integration::Log::DebugInfo, "Using OpenGL es %d.%d.\n", mGlesVersion / 10, mGlesVersion % 10); mContextAttribs.Clear(); - if( mIsKhrCreateContextSupported ) + if(mIsKhrCreateContextSupported) { mContextAttribs.Reserve(5); - mContextAttribs.PushBack( EGL_CONTEXT_MAJOR_VERSION_KHR ); - mContextAttribs.PushBack( mGlesVersion / 10 ); - mContextAttribs.PushBack( EGL_CONTEXT_MINOR_VERSION_KHR ); - mContextAttribs.PushBack( mGlesVersion % 10 ); + mContextAttribs.PushBack(EGL_CONTEXT_MAJOR_VERSION_KHR); + mContextAttribs.PushBack(mGlesVersion / 10); + mContextAttribs.PushBack(EGL_CONTEXT_MINOR_VERSION_KHR); + mContextAttribs.PushBack(mGlesVersion % 10); } else { mContextAttribs.Reserve(3); - mContextAttribs.PushBack( EGL_CONTEXT_CLIENT_VERSION ); - mContextAttribs.PushBack( mGlesVersion / 10 ); + mContextAttribs.PushBack(EGL_CONTEXT_CLIENT_VERSION); + mContextAttribs.PushBack(mGlesVersion / 10); } - mContextAttribs.PushBack( EGL_NONE ); + mContextAttribs.PushBack(EGL_NONE); return true; } -EGLSurface EglImplementation::CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth ) +EGLSurface EglImplementation::CreateSurfaceWindow(EGLNativeWindowType window, ColorDepth depth) { mEglNativeWindow = window; - mColorDepth = depth; - mIsWindow = true; + mColorDepth = depth; + mIsWindow = true; // egl choose config ChooseConfig(mIsWindow, mColorDepth); - mCurrentEglSurface = eglCreateWindowSurface( mEglDisplay, mEglConfig, mEglNativeWindow, NULL ); + mCurrentEglSurface = eglCreateWindowSurface(mEglDisplay, mEglConfig, mEglNativeWindow, NULL); TEST_EGL_ERROR("eglCreateWindowSurface"); - DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create window surface failed" ); + DALI_ASSERT_ALWAYS(mCurrentEglSurface && "Create window surface failed"); return mCurrentEglSurface; } -EGLSurface EglImplementation::CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth ) +EGLSurface EglImplementation::CreateSurfacePixmap(EGLNativePixmapType pixmap, ColorDepth depth) { mCurrentEglNativePixmap = pixmap; - mColorDepth = depth; - mIsWindow = false; + mColorDepth = depth; + mIsWindow = false; // egl choose config ChooseConfig(mIsWindow, mColorDepth); - mCurrentEglSurface = eglCreatePixmapSurface( mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL ); + mCurrentEglSurface = eglCreatePixmapSurface(mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL); TEST_EGL_ERROR("eglCreatePixmapSurface"); - DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create pixmap surface failed" ); + DALI_ASSERT_ALWAYS(mCurrentEglSurface && "Create pixmap surface failed"); return mCurrentEglSurface; } -bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window, EGLSurface& eglSurface, EGLContext& eglContext ) +bool EglImplementation::ReplaceSurfaceWindow(EGLNativeWindowType window, EGLSurface& eglSurface, EGLContext& eglContext) { bool contextLost = false; @@ -666,36 +663,36 @@ bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window, EGLSur // the surface is bound to the context, so set the context to null MakeContextNull(); - if( eglSurface ) + if(eglSurface) { // destroy the surface - DestroySurface( eglSurface ); + DestroySurface(eglSurface); } // create the EGL surface - EGLSurface newEglSurface = CreateSurfaceWindow( window, mColorDepth ); + EGLSurface newEglSurface = CreateSurfaceWindow(window, mColorDepth); // set the context to be current with the new surface - MakeContextCurrent( newEglSurface, eglContext ); + MakeContextCurrent(newEglSurface, eglContext); return contextLost; } -bool EglImplementation::ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface ) +bool EglImplementation::ReplaceSurfacePixmap(EGLNativePixmapType pixmap, EGLSurface& eglSurface) { bool contextLost = false; // display connection has not changed, then we can just create a new surface // create the EGL surface - eglSurface = CreateSurfacePixmap( pixmap, mColorDepth ); + eglSurface = CreateSurfacePixmap(pixmap, mColorDepth); // set the eglSurface to be current - MakeCurrent( pixmap, eglSurface ); + MakeCurrent(pixmap, eglSurface); return contextLost; } -void EglImplementation::SetGlesVersion( const int32_t glesVersion ) +void EglImplementation::SetGlesVersion(const int32_t glesVersion) { mGlesVersion = glesVersion; } @@ -728,7 +725,7 @@ bool EglImplementation::IsSurfacelessContextSupported() const void EglImplementation::WaitClient() { // Wait for EGL to finish executing all rendering calls for the current context - if ( eglWaitClient() != EGL_TRUE ) + if(eglWaitClient() != EGL_TRUE) { TEST_EGL_ERROR("eglWaitClient"); } diff --git a/dali/internal/graphics/gles/egl-implementation.h b/dali/internal/graphics/gles/egl-implementation.h index 8a23ef1..7712658 100644 --- a/dali/internal/graphics/gles/egl-implementation.h +++ b/dali/internal/graphics/gles/egl-implementation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_EGL_IMPLEMENTATION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,11 +22,11 @@ #include #include +#include #include #include #include #include -#include // INTERNAL INCLUDES #include @@ -37,14 +37,12 @@ namespace Internal { namespace Adaptor { - /** * EglImplementation class provides an EGL implementation. */ class EglImplementation : public EglInterface { public: - /** * Constructor * @param[in] multiSamplingLevel The Multi-sampling level required @@ -52,10 +50,10 @@ public: * @param[in] stencilBufferRequired Whether the stencil buffer is required * @param[in] partialUpdatedRequired Whether the partial update is required */ - EglImplementation( int multiSamplingLevel, - Integration::DepthBufferAvailable depthBufferRequired, - Integration::StencilBufferAvailable stencilBufferRequired, - Integration::PartialUpdateAvailable partialUpdateRequired ); + EglImplementation(int multiSamplingLevel, + Integration::DepthBufferAvailable depthBufferRequired, + Integration::StencilBufferAvailable stencilBufferRequired, + Integration::PartialUpdateAvailable partialUpdateRequired); /** * Destructor @@ -63,7 +61,6 @@ public: ~EglImplementation() override; public: - /** * (Called from RenderSurface, not RenderThread, so not in i/f, hence, not virtual) * Initialize GL @@ -71,7 +68,7 @@ public: * @param isOwnSurface whether the surface is own or not * @return true on success, false on failure */ - bool InitializeGles( EGLNativeDisplayType display, bool isOwnSurface = true ); + bool InitializeGles(EGLNativeDisplayType display, bool isOwnSurface = true); /** * Create the OpenGL context for the shared resource. @@ -83,22 +80,22 @@ public: * Create the OpenGL context for the window. * @return true if successful */ - bool CreateWindowContext( EGLContext& mEglContext ); + bool CreateWindowContext(EGLContext& mEglContext); /** * Destroy the OpenGL context. */ - void DestroyContext( EGLContext& eglContext ); + void DestroyContext(EGLContext& eglContext); /** * Destroy the OpenGL surface. */ - void DestroySurface( EGLSurface& eglSurface ); + void DestroySurface(EGLSurface& eglSurface); /** * Make the OpenGL context current */ - void MakeContextCurrent( EGLSurface eglSurface, EGLContext eglContext ) override; + void MakeContextCurrent(EGLSurface eglSurface, EGLContext eglContext) override; /** * clear the OpenGL context @@ -111,7 +108,7 @@ public: * @param pixmap The pixmap to replace the current surface * @param eglSurface The eglSurface to replace the current OpenGL surface. */ - void MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface ); + void MakeCurrent(EGLNativePixmapType pixmap, EGLSurface eglSurface); /** * Terminate GL @@ -127,27 +124,27 @@ public: /** * Performs an OpenGL swap buffers command */ - void SwapBuffers( EGLSurface& eglSurface ) override; + void SwapBuffers(EGLSurface& eglSurface) override; /** * Gets current back buffer age */ - EGLint GetBufferAge( EGLSurface& eglSurface ) const; + EGLint GetBufferAge(EGLSurface& eglSurface) const; /** * Performs an OpenGL set damage command with damaged rects */ - void SetDamageRegion( EGLSurface& eglSurface, std::vector< Rect< int > >& damagedRects ); + void SetDamageRegion(EGLSurface& eglSurface, std::vector>& damagedRects); /** * Performs an OpenGL swap buffers command with damaged rects */ - virtual void SwapBuffers( EGLSurface& eglSurface, const std::vector>& damagedRects ); + virtual void SwapBuffers(EGLSurface& eglSurface, const std::vector>& damagedRects); /** * Performs an OpenGL copy buffers command */ - void CopyBuffers( EGLSurface& eglSurface ) override; + void CopyBuffers(EGLSurface& eglSurface) override; /** * Performs an EGL wait GL command @@ -160,7 +157,7 @@ public: * @param colorDepth Bit per pixel value (ex. 32 or 24) * @return true if the eglChooseConfig is succeed. */ - bool ChooseConfig( bool isWindowType, ColorDepth depth ); + bool ChooseConfig(bool isWindowType, ColorDepth depth); /** * Create an OpenGL surface using a window @@ -168,7 +165,7 @@ public: * @param colorDepth Bit per pixel value (ex. 32 or 24) * @return Handle to an on-screen EGL window surface (the requester has an ownership of this egl surface) */ - EGLSurface CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth ); + EGLSurface CreateSurfaceWindow(EGLNativeWindowType window, ColorDepth depth); /** * Create the OpenGL surface using a pixmap @@ -176,7 +173,7 @@ public: * @param colorDepth Bit per pixel value (ex. 32 or 24) * @return Handle to an off-screen EGL pixmap surface (the requester has an ownership of this egl surface) */ - EGLSurface CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth ); + EGLSurface CreateSurfacePixmap(EGLNativePixmapType pixmap, ColorDepth depth); /** * Replaces the render surface @@ -184,7 +181,7 @@ public: * @return true if the context was lost due to a change in display * between old surface and new surface */ - bool ReplaceSurfaceWindow( EGLNativeWindowType window, EGLSurface& eglSurface, EGLContext& eglContext ); + bool ReplaceSurfaceWindow(EGLNativeWindowType window, EGLSurface& eglSurface, EGLContext& eglContext); /** * Replaces the render surface @@ -193,12 +190,12 @@ public: * @return true if the context was lost due to a change in x-display * between old surface and new surface */ - bool ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface ); + bool ReplaceSurfacePixmap(EGLNativePixmapType pixmap, EGLSurface& eglSurface); /** * Sets gles version */ - void SetGlesVersion( const int32_t glesVersion ); + void SetGlesVersion(const int32_t glesVersion); /** * Sets Whether the frame is the first after Resume. @@ -241,46 +238,44 @@ public: bool IsPartialUpdateRequired() const; private: - - Vector mContextAttribs; + Vector mContextAttribs; EGLNativeDisplayType mEglNativeDisplay; - EGLNativeWindowType mEglNativeWindow; + EGLNativeWindowType mEglNativeWindow; - EGLNativePixmapType mCurrentEglNativePixmap; + EGLNativePixmapType mCurrentEglNativePixmap; - EGLDisplay mEglDisplay; - EGLConfig mEglConfig; - EGLContext mEglContext; ///< The resource context holding assets such as textures to be shared + EGLDisplay mEglDisplay; + EGLConfig mEglConfig; + EGLContext mEglContext; ///< The resource context holding assets such as textures to be shared typedef std::vector EglWindowContextContainer; - EglWindowContextContainer mEglWindowContexts; ///< The EGL context for the window + EglWindowContextContainer mEglWindowContexts; ///< The EGL context for the window - EGLSurface mCurrentEglSurface; - EGLContext mCurrentEglContext; + EGLSurface mCurrentEglSurface; + EGLContext mCurrentEglContext; typedef std::vector EglWindowSurfaceContainer; - EglWindowSurfaceContainer mEglWindowSurfaces; ///< The EGL surface for the window + EglWindowSurfaceContainer mEglWindowSurfaces; ///< The EGL surface for the window - int32_t mMultiSamplingLevel; - int32_t mGlesVersion; + int32_t mMultiSamplingLevel; + int32_t mGlesVersion; - ColorDepth mColorDepth; + ColorDepth mColorDepth; - bool mGlesInitialized; - bool mIsOwnSurface; - bool mIsWindow; - bool mDepthBufferRequired; - bool mStencilBufferRequired; - bool mPartialUpdateRequired; - bool mIsSurfacelessContextSupported; - bool mIsKhrCreateContextSupported; + bool mGlesInitialized; + bool mIsOwnSurface; + bool mIsWindow; + bool mDepthBufferRequired; + bool mStencilBufferRequired; + bool mPartialUpdateRequired; + bool mIsSurfacelessContextSupported; + bool mIsKhrCreateContextSupported; - uint32_t mSwapBufferCountAfterResume; - PFNEGLSETDAMAGEREGIONKHRPROC mEglSetDamageRegionKHR; + uint32_t mSwapBufferCountAfterResume; + PFNEGLSETDAMAGEREGIONKHRPROC mEglSetDamageRegionKHR; PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC mEglSwapBuffersWithDamageKHR; - }; } // namespace Adaptor diff --git a/dali/internal/graphics/gles/egl-sync-implementation.cpp b/dali/internal/graphics/gles/egl-sync-implementation.cpp index a941f02..24f2434 100644 --- a/dali/internal/graphics/gles/egl-sync-implementation.cpp +++ b/dali/internal/graphics/gles/egl-sync-implementation.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ #ifdef _ARCH_ARM_ +#include #include #include -#include #endif @@ -36,9 +36,9 @@ #ifdef _ARCH_ARM_ // function pointers -static PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR = NULL; +static PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR = NULL; static PFNEGLCLIENTWAITSYNCKHRPROC eglClientWaitSyncKHR = NULL; -static PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR = NULL; +static PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR = NULL; #endif @@ -48,16 +48,15 @@ namespace Internal { namespace Adaptor { - #ifdef _ARCH_ARM_ -EglSyncObject::EglSyncObject( EglImplementation& eglSyncImpl ) +EglSyncObject::EglSyncObject(EglImplementation& eglSyncImpl) : mEglSync(NULL), mEglImplementation(eglSyncImpl) { EGLDisplay display = mEglImplementation.GetDisplay(); - mEglSync = eglCreateSyncKHR( display, EGL_SYNC_FENCE_KHR, NULL ); - if (mEglSync == EGL_NO_SYNC_KHR) + mEglSync = eglCreateSyncKHR(display, EGL_SYNC_FENCE_KHR, NULL); + if(mEglSync == EGL_NO_SYNC_KHR) { DALI_LOG_ERROR("eglCreateSyncKHR failed %#0.4x\n", eglGetError()); mEglSync = NULL; @@ -66,11 +65,11 @@ EglSyncObject::EglSyncObject( EglImplementation& eglSyncImpl ) EglSyncObject::~EglSyncObject() { - if( mEglSync != NULL ) + if(mEglSync != NULL) { - eglDestroySyncKHR( mEglImplementation.GetDisplay(), mEglSync ); + eglDestroySyncKHR(mEglImplementation.GetDisplay(), mEglSync); EGLint error = eglGetError(); - if( EGL_SUCCESS != error ) + if(EGL_SUCCESS != error) { DALI_LOG_ERROR("eglDestroySyncKHR failed %#0.4x\n", error); } @@ -81,15 +80,15 @@ bool EglSyncObject::IsSynced() { bool synced = false; - if( mEglSync != NULL ) + if(mEglSync != NULL) { - EGLint result = eglClientWaitSyncKHR( mEglImplementation.GetDisplay(), mEglSync, 0, 0ull ); - EGLint error = eglGetError(); - if( EGL_SUCCESS != error ) + EGLint result = eglClientWaitSyncKHR(mEglImplementation.GetDisplay(), mEglSync, 0, 0ull); + EGLint error = eglGetError(); + if(EGL_SUCCESS != error) { DALI_LOG_ERROR("eglClientWaitSyncKHR failed %#0.4x\n", error); } - else if( result == EGL_CONDITION_SATISFIED_KHR ) + else if(result == EGL_CONDITION_SATISFIED_KHR) { synced = true; } @@ -99,9 +98,9 @@ bool EglSyncObject::IsSynced() } EglSyncImplementation::EglSyncImplementation() -: mEglImplementation( NULL ), - mSyncInitialized( false ), - mSyncInitializeFailed( false ) +: mEglImplementation(NULL), + mSyncInitialized(false), + mSyncInitializeFailed(false) { } @@ -109,36 +108,36 @@ EglSyncImplementation::~EglSyncImplementation() { } -void EglSyncImplementation::Initialize( EglImplementation* eglImpl ) +void EglSyncImplementation::Initialize(EglImplementation* eglImpl) { mEglImplementation = eglImpl; } Integration::GlSyncAbstraction::SyncObject* EglSyncImplementation::CreateSyncObject() { - DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" ); - if( mSyncInitialized == false ) + DALI_ASSERT_ALWAYS(mEglImplementation && "Sync Implementation not initialized"); + if(mSyncInitialized == false) { InitializeEglSync(); } EglSyncObject* syncObject = new EglSyncObject(*mEglImplementation); - mSyncObjects.PushBack( syncObject ); + mSyncObjects.PushBack(syncObject); return syncObject; } -void EglSyncImplementation::DestroySyncObject( Integration::GlSyncAbstraction::SyncObject* syncObject ) +void EglSyncImplementation::DestroySyncObject(Integration::GlSyncAbstraction::SyncObject* syncObject) { - DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" ); + DALI_ASSERT_ALWAYS(mEglImplementation && "Sync Implementation not initialized"); - if( mSyncInitialized == false ) + if(mSyncInitialized == false) { InitializeEglSync(); } - for( SyncIter iter=mSyncObjects.Begin(), end=mSyncObjects.End(); iter != end; ++iter ) + for(SyncIter iter = mSyncObjects.Begin(), end = mSyncObjects.End(); iter != end; ++iter) { - if( *iter == syncObject ) + if(*iter == syncObject) { mSyncObjects.Erase(iter); break; @@ -150,14 +149,14 @@ void EglSyncImplementation::DestroySyncObject( Integration::GlSyncAbstraction::S void EglSyncImplementation::InitializeEglSync() { - if( ! mSyncInitializeFailed ) + if(!mSyncInitializeFailed) { - eglCreateSyncKHR = reinterpret_cast< PFNEGLCREATESYNCKHRPROC >( eglGetProcAddress("eglCreateSyncKHR") ); - eglClientWaitSyncKHR = reinterpret_cast< PFNEGLCLIENTWAITSYNCKHRPROC >( eglGetProcAddress("eglClientWaitSyncKHR") ); - eglDestroySyncKHR = reinterpret_cast< PFNEGLDESTROYSYNCKHRPROC >( eglGetProcAddress("eglDestroySyncKHR") ); + eglCreateSyncKHR = reinterpret_cast(eglGetProcAddress("eglCreateSyncKHR")); + eglClientWaitSyncKHR = reinterpret_cast(eglGetProcAddress("eglClientWaitSyncKHR")); + eglDestroySyncKHR = reinterpret_cast(eglGetProcAddress("eglDestroySyncKHR")); } - if( eglCreateSyncKHR && eglClientWaitSyncKHR && eglDestroySyncKHR ) + if(eglCreateSyncKHR && eglClientWaitSyncKHR && eglDestroySyncKHR) { mSyncInitialized = true; } @@ -169,7 +168,7 @@ void EglSyncImplementation::InitializeEglSync() #else -EglSyncObject::EglSyncObject( EglImplementation& eglImpl ) +EglSyncObject::EglSyncObject(EglImplementation& eglImpl) : mPollCounter(3), mEglImplementation(eglImpl) { @@ -190,9 +189,9 @@ bool EglSyncObject::IsSynced() } EglSyncImplementation::EglSyncImplementation() -: mEglImplementation( NULL ), - mSyncInitialized( false ), - mSyncInitializeFailed( false ) +: mEglImplementation(NULL), + mSyncInitialized(false), + mSyncInitializeFailed(false) { } @@ -200,20 +199,20 @@ EglSyncImplementation::~EglSyncImplementation() { } -void EglSyncImplementation::Initialize( EglImplementation* eglImpl ) +void EglSyncImplementation::Initialize(EglImplementation* eglImpl) { mEglImplementation = eglImpl; } Integration::GlSyncAbstraction::SyncObject* EglSyncImplementation::CreateSyncObject() { - DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" ); + DALI_ASSERT_ALWAYS(mEglImplementation && "Sync Implementation not initialized"); return new EglSyncObject(*mEglImplementation); } void EglSyncImplementation::DestroySyncObject(Integration::GlSyncAbstraction::SyncObject* syncObject) { - DALI_ASSERT_ALWAYS( mEglImplementation && "Sync Implementation not initialized" ); + DALI_ASSERT_ALWAYS(mEglImplementation && "Sync Implementation not initialized"); // The abstraction's virtual destructor is protected, so that Core can't delete the sync objects // directly (This object also needs removing from the mSyncObject container in the ARM @@ -228,6 +227,6 @@ void EglSyncImplementation::InitializeEglSync() #endif -} // namespace Dali -} // namespace Internal } // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/graphics/gles/egl-sync-implementation.h b/dali/internal/graphics/gles/egl-sync-implementation.h index be69521..218e647 100644 --- a/dali/internal/graphics/gles/egl-sync-implementation.h +++ b/dali/internal/graphics/gles/egl-sync-implementation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_EGL_SYNC_IMPLEMENTATION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include // INTERNAL INCLUDES #include @@ -40,7 +40,7 @@ public: /** * Constructor */ - EglSyncObject( EglImplementation& eglSyncImpl ); + EglSyncObject(EglImplementation& eglSyncImpl); /** * Destructor @@ -61,7 +61,6 @@ private: EglImplementation& mEglImplementation; }; - /** * GlSyncImplementation is a concrete implementation for GlSyncAbstraction. * It provides fence syncing for resources such as FrameBuffers using EGL extensions @@ -87,7 +86,7 @@ public: * Initialize the sync object with the Egl implementation. * @param[in] impl The EGL implementation (to access display) */ - void Initialize( EglImplementation* impl ); + void Initialize(EglImplementation* impl); /** * @copydoc Dali::Integration::GlSyncAbstraction::CreateSyncObject() @@ -106,12 +105,12 @@ private: void InitializeEglSync(); private: - typedef Vector SyncContainer; - typedef SyncContainer::Iterator SyncIter; + typedef Vector SyncContainer; + typedef SyncContainer::Iterator SyncIter; - EglImplementation* mEglImplementation; ///< Egl implementation (to get display) - bool mSyncInitialized; ///< Flag to perform initialization on first use - bool mSyncInitializeFailed; ///< Flag to avoid reloading functions if failed once + EglImplementation* mEglImplementation; ///< Egl implementation (to get display) + bool mSyncInitialized; ///< Flag to perform initialization on first use + bool mSyncInitializeFailed; ///< Flag to avoid reloading functions if failed once SyncContainer mSyncObjects; }; diff --git a/dali/internal/graphics/gles/gl-extensions.cpp b/dali/internal/graphics/gles/gl-extensions.cpp index f61d9dd..1790fe5 100644 --- a/dali/internal/graphics/gles/gl-extensions.cpp +++ b/dali/internal/graphics/gles/gl-extensions.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,26 +26,23 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - GlExtensions::GlExtensions() : #ifdef GL_EXT_discard_framebuffer - mGlDiscardFramebuffer( nullptr ), + mGlDiscardFramebuffer(nullptr), #endif #ifdef GL_OES_get_program_binary - mGlGetProgramBinaryOES( nullptr ), - mGlProgramBinaryOES( nullptr ), + mGlGetProgramBinaryOES(nullptr), + mGlProgramBinaryOES(nullptr), #endif #ifdef GL_KHR_blend_equation_advanced - mBlendBarrierKHR( nullptr ), + mBlendBarrierKHR(nullptr), #endif - mInitialized( false ) + mInitialized(false) { } @@ -53,17 +50,17 @@ GlExtensions::~GlExtensions() { } -void GlExtensions::DiscardFrameBuffer(GLenum target, GLsizei numAttachments, const GLenum *attachments) +void GlExtensions::DiscardFrameBuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments) { // initialize extension on first use as on some hw platforms a context // has to be bound for the extensions to return correct pointer - if( !mInitialized ) + if(!mInitialized) { Initialize(); } #ifdef GL_EXT_discard_framebuffer - if( mGlDiscardFramebuffer ) + if(mGlDiscardFramebuffer) { mGlDiscardFramebuffer(target, numAttachments, attachments); } @@ -74,17 +71,17 @@ void GlExtensions::DiscardFrameBuffer(GLenum target, GLsizei numAttachments, con #endif } -void GlExtensions::GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary) +void GlExtensions::GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) { // initialize extension on first use as on some hw platforms a context // has to be bound for the extensions to return correct pointer - if( !mInitialized ) + if(!mInitialized) { Initialize(); } #ifdef GL_OES_get_program_binary - if (mGlGetProgramBinaryOES) + if(mGlGetProgramBinaryOES) { mGlGetProgramBinaryOES(program, bufSize, length, binaryFormat, binary); } @@ -96,17 +93,17 @@ void GlExtensions::GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei #endif } -void GlExtensions::ProgramBinaryOES(GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length) +void GlExtensions::ProgramBinaryOES(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLint length) { // initialize extension on first use as on some hw platforms a context // has to be bound for the extensions to return correct pointer - if( !mInitialized ) + if(!mInitialized) { Initialize(); } #ifdef GL_OES_get_program_binary - if (mGlProgramBinaryOES) + if(mGlProgramBinaryOES) { mGlProgramBinaryOES(program, binaryFormat, binary, length); } @@ -122,13 +119,13 @@ bool GlExtensions::BlendBarrierKHR() { // initialize extension on first use as on some hw platforms a context // has to be bound for the extensions to return correct pointer - if( !mInitialized ) + if(!mInitialized) { Initialize(); } #ifdef GL_KHR_blend_equation_advanced - if (mBlendBarrierKHR) + if(mBlendBarrierKHR) { mBlendBarrierKHR(); return true; @@ -144,16 +141,16 @@ void GlExtensions::Initialize() mInitialized = true; #ifdef GL_EXT_discard_framebuffer - mGlDiscardFramebuffer = reinterpret_cast< PFNGLDISCARDFRAMEBUFFEREXTPROC >( eglGetProcAddress("glDiscardFramebufferEXT") ); + mGlDiscardFramebuffer = reinterpret_cast(eglGetProcAddress("glDiscardFramebufferEXT")); #endif #ifdef GL_OES_get_program_binary - mGlGetProgramBinaryOES = reinterpret_cast< PFNGLGETPROGRAMBINARYOESPROC >( eglGetProcAddress("glGetProgramBinaryOES") ); - mGlProgramBinaryOES = reinterpret_cast< PFNGLPROGRAMBINARYOESPROC >( eglGetProcAddress("glProgramBinaryOES") ); + mGlGetProgramBinaryOES = reinterpret_cast(eglGetProcAddress("glGetProgramBinaryOES")); + mGlProgramBinaryOES = reinterpret_cast(eglGetProcAddress("glProgramBinaryOES")); #endif #ifdef GL_KHR_blend_equation_advanced - mBlendBarrierKHR = reinterpret_cast< PFNGLBLENDBARRIERKHRPROC >( eglGetProcAddress("glBlendBarrierKHR") ); + mBlendBarrierKHR = reinterpret_cast(eglGetProcAddress("glBlendBarrierKHR")); #endif } diff --git a/dali/internal/graphics/gles/gl-extensions.h b/dali/internal/graphics/gles/gl-extensions.h index 887c714..fe457e2 100644 --- a/dali/internal/graphics/gles/gl-extensions.h +++ b/dali/internal/graphics/gles/gl-extensions.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_GL_EXTENSION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,27 +20,22 @@ // EXTERNAL INCLUDES -#include #include #include - +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * GlExtensions class provides GL extensions support */ class GlExtensions { public: - /** * Constructor */ @@ -51,9 +46,7 @@ public: */ ~GlExtensions(); - public: - /** * If the GL extension is available this function discards specified data in attachments * from being copied from the target to improve performance. @@ -65,7 +58,7 @@ public: * @param numAttachments is the count of attachments * @param attachments is a pointer to the attachments */ - void DiscardFrameBuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); + void DiscardFrameBuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments); /** * GLES extension @@ -76,7 +69,7 @@ public: * @param[out] binaryFormat The format of the program binary * @param[out] binary The actual program bytecode */ - void GetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, GLvoid *binary); + void GetProgramBinaryOES(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary); /** * GLES extension @@ -86,16 +79,15 @@ public: * @param[in] binary The program bytecode * @param[in] length The number of bytes in binary */ - void ProgramBinaryOES (GLuint program, GLenum binaryFormat, const GLvoid *binary, GLint length); + void ProgramBinaryOES(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLint length); /** * KHR extension * Specify a boundary between passes when using advanced blend equations. */ - bool BlendBarrierKHR (); + bool BlendBarrierKHR(); private: - /** * Lazy Initialize extensions on first use */ @@ -107,7 +99,7 @@ private: #ifdef GL_OES_get_program_binary PFNGLGETPROGRAMBINARYOESPROC mGlGetProgramBinaryOES; - PFNGLPROGRAMBINARYOESPROC mGlProgramBinaryOES; + PFNGLPROGRAMBINARYOESPROC mGlProgramBinaryOES; #endif #ifdef GL_KHR_blend_equation_advanced @@ -115,7 +107,6 @@ private: #endif bool mInitialized; - }; } // namespace Adaptor diff --git a/dali/internal/graphics/gles/gl-implementation.h b/dali/internal/graphics/gles/gl-implementation.h index 5f1078e..bcc8c86 100644 --- a/dali/internal/graphics/gles/gl-implementation.h +++ b/dali/internal/graphics/gles/gl-implementation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_GL_IMPLEMENTATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ */ // EXTERNAL INCLUDES -#include -#include #include #include -#include #include +#include #include +#include +#include // INTERNAL INCLUDES #include @@ -34,19 +34,15 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - -const int32_t INITIAL_GLES_VERSION = 30; +const int32_t INITIAL_GLES_VERSION = 30; const int32_t GLES_VERSION_SUPPORT_BLEND_EQUATION_ADVANCED = 32; -const char* KHR_BLEND_EQUATION_ADVANCED = "GL_KHR_blend_equation_advanced"; +const char* KHR_BLEND_EQUATION_ADVANCED = "GL_KHR_blend_equation_advanced"; const char* FRAGMENT_SHADER_ADVANCED_BLEND_EQUATION_PREFIX = "#extension GL_KHR_blend_equation_advanced : enable\n" @@ -57,7 +53,7 @@ const char* FRAGMENT_SHADER_ADVANCED_BLEND_EQUATION_PREFIX = const char* FRAGMENT_SHADER_OUTPUT_COLOR_STRING = "out mediump vec4 fragColor;\n"; -} +} // namespace /** * GlImplementation is a concrete implementation for GlAbstraction. @@ -66,24 +62,25 @@ const char* FRAGMENT_SHADER_OUTPUT_COLOR_STRING = */ class GlImplementation : public Dali::Integration::GlAbstraction { - public: GlImplementation() - : mContextCreatedWaitCondition(), - mMaxTextureSize( 0 ), - mVertexShaderPrefix(""), - mGlesVersion( INITIAL_GLES_VERSION ), - mShadingLanguageVersion( 100 ), - mShadingLanguageVersionCached( false ), - mIsSurfacelessContextSupported( false ), - mIsAdvancedBlendEquationSupportedCached( false ), - mIsAdvancedBlendEquationSupported( false ), - mIsContextCreated( false ) + : mContextCreatedWaitCondition(), + mMaxTextureSize(0), + mVertexShaderPrefix(""), + mGlesVersion(INITIAL_GLES_VERSION), + mShadingLanguageVersion(100), + mShadingLanguageVersionCached(false), + mIsSurfacelessContextSupported(false), + mIsAdvancedBlendEquationSupportedCached(false), + mIsAdvancedBlendEquationSupported(false), + mIsContextCreated(false) { - mImpl.reset( new Gles3Implementation() ); + mImpl.reset(new Gles3Implementation()); } - virtual ~GlImplementation() {} + virtual ~GlImplementation() + { + } void PreRender() override { @@ -97,25 +94,25 @@ public: void ContextCreated() { - glGetIntegerv( GL_MAX_TEXTURE_SIZE, &mMaxTextureSize ); + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize); GLint majorVersion, minorVersion; - glGetIntegerv( GL_MAJOR_VERSION, &majorVersion ); - glGetIntegerv( GL_MINOR_VERSION, &minorVersion ); + glGetIntegerv(GL_MAJOR_VERSION, &majorVersion); + glGetIntegerv(GL_MINOR_VERSION, &minorVersion); mGlesVersion = majorVersion * 10 + minorVersion; - if( mGlesVersion >= GLES_VERSION_SUPPORT_BLEND_EQUATION_ADVANCED ) + if(mGlesVersion >= GLES_VERSION_SUPPORT_BLEND_EQUATION_ADVANCED) { mIsAdvancedBlendEquationSupported = true; } else { // when mIsAdvancedBlendEquationSupported is cached, we don't need to check all the extensions. - if( !mIsAdvancedBlendEquationSupportedCached ) + if(!mIsAdvancedBlendEquationSupportedCached) { const char* const extensionStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); std::istringstream stream(extensionStr); - std::string currentExtension; + std::string currentExtension; while(std::getline(stream, currentExtension, ' ')) { if(currentExtension == KHR_BLEND_EQUATION_ADVANCED) @@ -130,8 +127,8 @@ public: if(!mShadingLanguageVersionCached) { std::istringstream shadingLanguageVersionStream(reinterpret_cast(glGetString(GL_SHADING_LANGUAGE_VERSION))); - std::string token; - uint32_t tokenCount = 0; + std::string token; + uint32_t tokenCount = 0; while(std::getline(shadingLanguageVersionStream, token, ' ')) { if(tokenCount == 3 && token == "ES") @@ -148,29 +145,29 @@ public: } { - ConditionalWait::ScopedLock lock( mContextCreatedWaitCondition ); + ConditionalWait::ScopedLock lock(mContextCreatedWaitCondition); mIsContextCreated = true; - mContextCreatedWaitCondition.Notify( lock ); + mContextCreatedWaitCondition.Notify(lock); } } - void SetGlesVersion( const int32_t glesVersion ) + void SetGlesVersion(const int32_t glesVersion) { - if( mGlesVersion / 10 != glesVersion / 10 ) + if(mGlesVersion / 10 != glesVersion / 10) { mGlesVersion = glesVersion; - if( mGlesVersion >= 30 ) + if(mGlesVersion >= 30) { - mImpl.reset( new Gles3Implementation() ); + mImpl.reset(new Gles3Implementation()); } else { - mImpl.reset( new Gles2Implementation() ); + mImpl.reset(new Gles2Implementation()); } } } - void SetIsSurfacelessContextSupported( const bool isSupported ) + void SetIsSurfacelessContextSupported(const bool isSupported) { mIsSurfacelessContextSupported = isSupported; } @@ -188,10 +185,10 @@ public: bool IsAdvancedBlendEquationSupported() { - ConditionalWait::ScopedLock lock( mContextCreatedWaitCondition ); + ConditionalWait::ScopedLock lock(mContextCreatedWaitCondition); if(!mIsContextCreated && !mIsAdvancedBlendEquationSupportedCached) { - mContextCreatedWaitCondition.Wait( lock ); + mContextCreatedWaitCondition.Wait(lock); } return mIsAdvancedBlendEquationSupported; } @@ -243,7 +240,7 @@ public: { if(mShaderVersionPrefix == "") { - mShaderVersionPrefix = "#version " + std::to_string( GetShadingLanguageVersion() ); + mShaderVersionPrefix = "#version " + std::to_string(GetShadingLanguageVersion()); if(GetShadingLanguageVersion() < 300) { mShaderVersionPrefix += "\n"; @@ -305,1285 +302,1285 @@ public: return mFragmentShaderPrefix; } - bool TextureRequiresConverting( const GLenum imageGlFormat, const GLenum textureGlFormat, const bool isSubImage ) const override + bool TextureRequiresConverting(const GLenum imageGlFormat, const GLenum textureGlFormat, const bool isSubImage) const override { - bool convert = ( ( imageGlFormat == GL_RGB ) && ( textureGlFormat == GL_RGBA ) ); - if( mGlesVersion >= 30 ) + bool convert = ((imageGlFormat == GL_RGB) && (textureGlFormat == GL_RGBA)); + if(mGlesVersion >= 30) { // Don't convert manually from RGB to RGBA if GLES >= 3.0 and a sub-image is uploaded. - convert = ( convert && !isSubImage ); + convert = (convert && !isSubImage); } return convert; } int GetMaxTextureSize() { - ConditionalWait::ScopedLock lock( mContextCreatedWaitCondition ); - if( !mIsContextCreated ) + ConditionalWait::ScopedLock lock(mContextCreatedWaitCondition); + if(!mIsContextCreated) { - mContextCreatedWaitCondition.Wait( lock ); + mContextCreatedWaitCondition.Wait(lock); } return mMaxTextureSize; } int GetGlesVersion() { - ConditionalWait::ScopedLock lock( mContextCreatedWaitCondition ); - if( !mIsContextCreated ) + ConditionalWait::ScopedLock lock(mContextCreatedWaitCondition); + if(!mIsContextCreated) { - mContextCreatedWaitCondition.Wait( lock ); + mContextCreatedWaitCondition.Wait(lock); } return mGlesVersion; } - void SetShadingLanguageVersion( int shadingLanguageVersion ) + void SetShadingLanguageVersion(int shadingLanguageVersion) { - mShadingLanguageVersion = shadingLanguageVersion; + mShadingLanguageVersion = shadingLanguageVersion; mShadingLanguageVersionCached = true; } int GetShadingLanguageVersion() { - ConditionalWait::ScopedLock lock( mContextCreatedWaitCondition ); - if( !mIsContextCreated && !mShadingLanguageVersionCached ) + ConditionalWait::ScopedLock lock(mContextCreatedWaitCondition); + if(!mIsContextCreated && !mShadingLanguageVersionCached) { - mContextCreatedWaitCondition.Wait( lock ); + mContextCreatedWaitCondition.Wait(lock); } return mShadingLanguageVersion; } /* OpenGL ES 2.0 */ - void ActiveTexture( GLenum texture ) override + void ActiveTexture(GLenum texture) override { - glActiveTexture( texture ); + glActiveTexture(texture); } - void AttachShader( GLuint program, GLuint shader ) override + void AttachShader(GLuint program, GLuint shader) override { - glAttachShader( program, shader ); + glAttachShader(program, shader); } - void BindAttribLocation( GLuint program, GLuint index, const char* name ) override + void BindAttribLocation(GLuint program, GLuint index, const char* name) override { - glBindAttribLocation( program, index, name ); + glBindAttribLocation(program, index, name); } - void BindBuffer( GLenum target, GLuint buffer ) override + void BindBuffer(GLenum target, GLuint buffer) override { - glBindBuffer( target, buffer ); + glBindBuffer(target, buffer); } - void BindFramebuffer( GLenum target, GLuint framebuffer ) override + void BindFramebuffer(GLenum target, GLuint framebuffer) override { - glBindFramebuffer( target, framebuffer ); + glBindFramebuffer(target, framebuffer); } - void BindRenderbuffer( GLenum target, GLuint renderbuffer ) override + void BindRenderbuffer(GLenum target, GLuint renderbuffer) override { - glBindRenderbuffer( target, renderbuffer ); + glBindRenderbuffer(target, renderbuffer); } - void BindTexture( GLenum target, GLuint texture ) override + void BindTexture(GLenum target, GLuint texture) override { - glBindTexture( target, texture ); + glBindTexture(target, texture); } - void BlendColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha ) override + void BlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) override { - glBlendColor( red, green, blue, alpha ); + glBlendColor(red, green, blue, alpha); } - void BlendEquation( GLenum mode ) override + void BlendEquation(GLenum mode) override { - glBlendEquation( mode ); + glBlendEquation(mode); } - void BlendEquationSeparate( GLenum modeRGB, GLenum modeAlpha ) override + void BlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) override { - glBlendEquationSeparate( modeRGB, modeAlpha ); + glBlendEquationSeparate(modeRGB, modeAlpha); } - void BlendFunc( GLenum sfactor, GLenum dfactor ) override + void BlendFunc(GLenum sfactor, GLenum dfactor) override { - glBlendFunc( sfactor, dfactor ); + glBlendFunc(sfactor, dfactor); } - void BlendFuncSeparate( GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha ) override + void BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) override { - glBlendFuncSeparate( srcRGB, dstRGB, srcAlpha, dstAlpha ); + glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } - void BufferData( GLenum target, GLsizeiptr size, const void* data, GLenum usage ) override + void BufferData(GLenum target, GLsizeiptr size, const void* data, GLenum usage) override { - glBufferData( target, size, data, usage ); + glBufferData(target, size, data, usage); } - void BufferSubData( GLenum target, GLintptr offset, GLsizeiptr size, const void* data ) override + void BufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void* data) override { - glBufferSubData( target, offset, size, data ); + glBufferSubData(target, offset, size, data); } - GLenum CheckFramebufferStatus( GLenum target ) override + GLenum CheckFramebufferStatus(GLenum target) override { - return glCheckFramebufferStatus( target ); + return glCheckFramebufferStatus(target); } - void Clear( GLbitfield mask ) override + void Clear(GLbitfield mask) override { - glClear( mask ); + glClear(mask); } - void ClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha ) override + void ClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) override { - glClearColor( red, green, blue, alpha ); + glClearColor(red, green, blue, alpha); } - void ClearDepthf( GLclampf depth ) override + void ClearDepthf(GLclampf depth) override { - glClearDepthf( depth ); + glClearDepthf(depth); } - void ClearStencil( GLint s ) override + void ClearStencil(GLint s) override { - glClearStencil( s ); + glClearStencil(s); } - void ColorMask( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha ) override + void ColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) override { - glColorMask( red, green, blue, alpha ); + glColorMask(red, green, blue, alpha); } - void CompileShader( GLuint shader ) override + void CompileShader(GLuint shader) override { - glCompileShader( shader ); + glCompileShader(shader); } - void CompressedTexImage2D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data ) override + void CompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void* data) override { - glCompressedTexImage2D( target, level, internalformat, width, height, border, imageSize, data ); + glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } - void CompressedTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data ) override + void CompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void* data) override { - glCompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, imageSize, data ); + glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } - void CopyTexImage2D( GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border ) override + void CopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) override { - glCopyTexImage2D( target, level, internalformat, x, y, width, height, border ); + glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } - void CopyTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height ) override + void CopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) override { - glCopyTexSubImage2D( target, level, xoffset, yoffset, x, y, width, height ); + glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - GLuint CreateProgram( void ) override + GLuint CreateProgram(void) override { return glCreateProgram(); } - GLuint CreateShader( GLenum type ) override + GLuint CreateShader(GLenum type) override { - return glCreateShader( type ); + return glCreateShader(type); } - void CullFace( GLenum mode ) override + void CullFace(GLenum mode) override { - glCullFace( mode ); + glCullFace(mode); } - void DeleteBuffers( GLsizei n, const GLuint* buffers ) override + void DeleteBuffers(GLsizei n, const GLuint* buffers) override { - glDeleteBuffers( n, buffers ); + glDeleteBuffers(n, buffers); } - void DeleteFramebuffers( GLsizei n, const GLuint* framebuffers ) override + void DeleteFramebuffers(GLsizei n, const GLuint* framebuffers) override { - glDeleteFramebuffers( n, framebuffers ); + glDeleteFramebuffers(n, framebuffers); } - void DeleteProgram( GLuint program ) override + void DeleteProgram(GLuint program) override { - glDeleteProgram( program ); + glDeleteProgram(program); } - void DeleteRenderbuffers( GLsizei n, const GLuint* renderbuffers ) override + void DeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) override { - glDeleteRenderbuffers( n, renderbuffers ); + glDeleteRenderbuffers(n, renderbuffers); } - void DeleteShader( GLuint shader ) override + void DeleteShader(GLuint shader) override { - glDeleteShader( shader ); + glDeleteShader(shader); } - void DeleteTextures( GLsizei n, const GLuint* textures ) override + void DeleteTextures(GLsizei n, const GLuint* textures) override { - glDeleteTextures( n, textures ); + glDeleteTextures(n, textures); } - void DepthFunc( GLenum func ) override + void DepthFunc(GLenum func) override { - glDepthFunc( func ); + glDepthFunc(func); } - void DepthMask( GLboolean flag ) override + void DepthMask(GLboolean flag) override { - glDepthMask( flag ); + glDepthMask(flag); } - void DepthRangef( GLclampf zNear, GLclampf zFar ) override + void DepthRangef(GLclampf zNear, GLclampf zFar) override { - glDepthRangef( zNear, zFar ); + glDepthRangef(zNear, zFar); } - void DetachShader( GLuint program, GLuint shader ) override + void DetachShader(GLuint program, GLuint shader) override { - glDetachShader( program, shader ); + glDetachShader(program, shader); } - void Disable( GLenum cap ) override + void Disable(GLenum cap) override { - glDisable( cap ); + glDisable(cap); } - void DisableVertexAttribArray( GLuint index ) override + void DisableVertexAttribArray(GLuint index) override { - glDisableVertexAttribArray( index ); + glDisableVertexAttribArray(index); } - void DrawArrays( GLenum mode, GLint first, GLsizei count ) override + void DrawArrays(GLenum mode, GLint first, GLsizei count) override { - glDrawArrays( mode, first, count ); + glDrawArrays(mode, first, count); } - void DrawElements( GLenum mode, GLsizei count, GLenum type, const void* indices ) override + void DrawElements(GLenum mode, GLsizei count, GLenum type, const void* indices) override { - glDrawElements( mode, count, type, indices ); + glDrawElements(mode, count, type, indices); } - void Enable( GLenum cap ) override + void Enable(GLenum cap) override { - glEnable( cap ); + glEnable(cap); } - void EnableVertexAttribArray( GLuint index ) override + void EnableVertexAttribArray(GLuint index) override { - glEnableVertexAttribArray( index ); + glEnableVertexAttribArray(index); } - void Finish( void ) override + void Finish(void) override { glFinish(); } - void Flush( void ) override + void Flush(void) override { glFlush(); } - void FramebufferRenderbuffer( GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer ) override + void FramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) override { - glFramebufferRenderbuffer( target, attachment, renderbuffertarget, renderbuffer ); + glFramebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); } - void FramebufferTexture2D( GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level ) override + void FramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) override { - glFramebufferTexture2D( target, attachment, textarget, texture, level ); + glFramebufferTexture2D(target, attachment, textarget, texture, level); } - void FrontFace( GLenum mode ) override + void FrontFace(GLenum mode) override { - glFrontFace( mode ); + glFrontFace(mode); } - void GenBuffers( GLsizei n, GLuint* buffers ) override + void GenBuffers(GLsizei n, GLuint* buffers) override { - glGenBuffers( n, buffers ); + glGenBuffers(n, buffers); } - void GenerateMipmap( GLenum target ) override + void GenerateMipmap(GLenum target) override { - glGenerateMipmap( target ); + glGenerateMipmap(target); } - void GenFramebuffers( GLsizei n, GLuint* framebuffers ) override + void GenFramebuffers(GLsizei n, GLuint* framebuffers) override { - glGenFramebuffers( n, framebuffers ); + glGenFramebuffers(n, framebuffers); } - void GenRenderbuffers( GLsizei n, GLuint* renderbuffers ) override + void GenRenderbuffers(GLsizei n, GLuint* renderbuffers) override { - glGenRenderbuffers( n, renderbuffers ); + glGenRenderbuffers(n, renderbuffers); } - void GenTextures( GLsizei n, GLuint* textures ) override + void GenTextures(GLsizei n, GLuint* textures) override { - glGenTextures( n, textures ); + glGenTextures(n, textures); } - void GetActiveAttrib( GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name ) override + void GetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name) override { - glGetActiveAttrib( program, index, bufsize, length, size, type, name ); + glGetActiveAttrib(program, index, bufsize, length, size, type, name); } - void GetActiveUniform( GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name ) override + void GetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, char* name) override { - glGetActiveUniform( program, index, bufsize, length, size, type, name ); + glGetActiveUniform(program, index, bufsize, length, size, type, name); } - void GetAttachedShaders( GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders ) override + void GetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) override { - glGetAttachedShaders( program, maxcount, count, shaders ); + glGetAttachedShaders(program, maxcount, count, shaders); } - int GetAttribLocation( GLuint program, const char* name ) override + int GetAttribLocation(GLuint program, const char* name) override { - return glGetAttribLocation( program, name ); + return glGetAttribLocation(program, name); } - void GetBooleanv( GLenum pname, GLboolean* params ) override + void GetBooleanv(GLenum pname, GLboolean* params) override { - glGetBooleanv( pname, params ); + glGetBooleanv(pname, params); } - void GetBufferParameteriv( GLenum target, GLenum pname, GLint* params ) override + void GetBufferParameteriv(GLenum target, GLenum pname, GLint* params) override { - glGetBufferParameteriv( target, pname, params ); + glGetBufferParameteriv(target, pname, params); } - GLenum GetError( void ) override + GLenum GetError(void) override { return glGetError(); } - void GetFloatv( GLenum pname, GLfloat* params ) override + void GetFloatv(GLenum pname, GLfloat* params) override { - glGetFloatv( pname, params ); + glGetFloatv(pname, params); } - void GetFramebufferAttachmentParameteriv( GLenum target, GLenum attachment, GLenum pname, GLint* params ) override + void GetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params) override { - glGetFramebufferAttachmentParameteriv( target, attachment, pname, params ); + glGetFramebufferAttachmentParameteriv(target, attachment, pname, params); } - void GetIntegerv( GLenum pname, GLint* params ) override + void GetIntegerv(GLenum pname, GLint* params) override { - glGetIntegerv( pname, params ); + glGetIntegerv(pname, params); } - void GetProgramiv( GLuint program, GLenum pname, GLint* params ) override + void GetProgramiv(GLuint program, GLenum pname, GLint* params) override { - glGetProgramiv( program, pname, params ); + glGetProgramiv(program, pname, params); } - void GetProgramInfoLog( GLuint program, GLsizei bufsize, GLsizei* length, char* infolog ) override + void GetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, char* infolog) override { - glGetProgramInfoLog( program, bufsize, length, infolog ); + glGetProgramInfoLog(program, bufsize, length, infolog); } - void GetRenderbufferParameteriv( GLenum target, GLenum pname, GLint* params ) override + void GetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params) override { - glGetRenderbufferParameteriv( target, pname, params ); + glGetRenderbufferParameteriv(target, pname, params); } - void GetShaderiv( GLuint shader, GLenum pname, GLint* params ) override + void GetShaderiv(GLuint shader, GLenum pname, GLint* params) override { - glGetShaderiv( shader, pname, params ); + glGetShaderiv(shader, pname, params); } - void GetShaderInfoLog( GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog ) override + void GetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, char* infolog) override { - glGetShaderInfoLog( shader, bufsize, length, infolog ); + glGetShaderInfoLog(shader, bufsize, length, infolog); } - void GetShaderPrecisionFormat( GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision ) override + void GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) override { - glGetShaderPrecisionFormat( shadertype, precisiontype, range, precision ); + glGetShaderPrecisionFormat(shadertype, precisiontype, range, precision); } - void GetShaderSource( GLuint shader, GLsizei bufsize, GLsizei* length, char* source ) override + void GetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, char* source) override { - glGetShaderSource( shader, bufsize, length, source ); + glGetShaderSource(shader, bufsize, length, source); } - const GLubyte* GetString( GLenum name ) override + const GLubyte* GetString(GLenum name) override { - return glGetString( name ); + return glGetString(name); } - void GetTexParameterfv( GLenum target, GLenum pname, GLfloat* params ) override + void GetTexParameterfv(GLenum target, GLenum pname, GLfloat* params) override { - glGetTexParameterfv( target, pname, params ); + glGetTexParameterfv(target, pname, params); } - void GetTexParameteriv( GLenum target, GLenum pname, GLint* params ) override + void GetTexParameteriv(GLenum target, GLenum pname, GLint* params) override { - glGetTexParameteriv( target, pname, params ); + glGetTexParameteriv(target, pname, params); } - void GetUniformfv( GLuint program, GLint location, GLfloat* params ) override + void GetUniformfv(GLuint program, GLint location, GLfloat* params) override { - glGetUniformfv( program, location, params ); + glGetUniformfv(program, location, params); } - void GetUniformiv( GLuint program, GLint location, GLint* params ) override + void GetUniformiv(GLuint program, GLint location, GLint* params) override { - glGetUniformiv( program, location, params ); + glGetUniformiv(program, location, params); } - int GetUniformLocation( GLuint program, const char* name ) override + int GetUniformLocation(GLuint program, const char* name) override { - return glGetUniformLocation( program, name ); + return glGetUniformLocation(program, name); } - void GetVertexAttribfv( GLuint index, GLenum pname, GLfloat* params ) override + void GetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params) override { - glGetVertexAttribfv( index, pname, params ); + glGetVertexAttribfv(index, pname, params); } - void GetVertexAttribiv( GLuint index, GLenum pname, GLint* params ) override + void GetVertexAttribiv(GLuint index, GLenum pname, GLint* params) override { - glGetVertexAttribiv( index, pname, params ); + glGetVertexAttribiv(index, pname, params); } - void GetVertexAttribPointerv( GLuint index, GLenum pname, void** pointer ) override + void GetVertexAttribPointerv(GLuint index, GLenum pname, void** pointer) override { - glGetVertexAttribPointerv( index, pname, pointer ); + glGetVertexAttribPointerv(index, pname, pointer); } - void Hint( GLenum target, GLenum mode ) override + void Hint(GLenum target, GLenum mode) override { - glHint( target, mode ); + glHint(target, mode); } - GLboolean IsBuffer( GLuint buffer ) override + GLboolean IsBuffer(GLuint buffer) override { - return glIsBuffer( buffer ); + return glIsBuffer(buffer); } - GLboolean IsEnabled( GLenum cap ) override + GLboolean IsEnabled(GLenum cap) override { - return glIsEnabled( cap ); + return glIsEnabled(cap); } - GLboolean IsFramebuffer( GLuint framebuffer ) override + GLboolean IsFramebuffer(GLuint framebuffer) override { - return glIsFramebuffer( framebuffer ); + return glIsFramebuffer(framebuffer); } - GLboolean IsProgram( GLuint program ) override + GLboolean IsProgram(GLuint program) override { - return glIsProgram( program ); + return glIsProgram(program); } - GLboolean IsRenderbuffer( GLuint renderbuffer ) override + GLboolean IsRenderbuffer(GLuint renderbuffer) override { - return glIsRenderbuffer( renderbuffer ); + return glIsRenderbuffer(renderbuffer); } - GLboolean IsShader( GLuint shader ) override + GLboolean IsShader(GLuint shader) override { - return glIsShader( shader ); + return glIsShader(shader); } - GLboolean IsTexture( GLuint texture ) override + GLboolean IsTexture(GLuint texture) override { - return glIsTexture( texture ); + return glIsTexture(texture); } - void LineWidth( GLfloat width ) override + void LineWidth(GLfloat width) override { - glLineWidth( width ); + glLineWidth(width); } - void LinkProgram( GLuint program ) override + void LinkProgram(GLuint program) override { - glLinkProgram( program ); + glLinkProgram(program); } - void PixelStorei( GLenum pname, GLint param ) override + void PixelStorei(GLenum pname, GLint param) override { - glPixelStorei( pname, param ); + glPixelStorei(pname, param); } - void PolygonOffset( GLfloat factor, GLfloat units ) override + void PolygonOffset(GLfloat factor, GLfloat units) override { - glPolygonOffset( factor, units ); + glPolygonOffset(factor, units); } - void ReadPixels( GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels ) override + void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) override { - glReadPixels( x, y, width, height, format, type, pixels ); + glReadPixels(x, y, width, height, format, type, pixels); } - void ReleaseShaderCompiler( void ) override + void ReleaseShaderCompiler(void) override { glReleaseShaderCompiler(); } - void RenderbufferStorage( GLenum target, GLenum internalformat, GLsizei width, GLsizei height ) override + void RenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) override { - glRenderbufferStorage( target, internalformat, width, height ); + glRenderbufferStorage(target, internalformat, width, height); } - void SampleCoverage( GLclampf value, GLboolean invert ) override + void SampleCoverage(GLclampf value, GLboolean invert) override { - glSampleCoverage( value, invert ); + glSampleCoverage(value, invert); } - void Scissor( GLint x, GLint y, GLsizei width, GLsizei height ) override + void Scissor(GLint x, GLint y, GLsizei width, GLsizei height) override { - glScissor( x, y, width, height ); + glScissor(x, y, width, height); } - void ShaderBinary( GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length ) override + void ShaderBinary(GLsizei n, const GLuint* shaders, GLenum binaryformat, const void* binary, GLsizei length) override { - glShaderBinary( n, shaders, binaryformat, binary, length ); + glShaderBinary(n, shaders, binaryformat, binary, length); } - void ShaderSource( GLuint shader, GLsizei count, const char** string, const GLint* length ) override + void ShaderSource(GLuint shader, GLsizei count, const char** string, const GLint* length) override { - glShaderSource( shader, count, string, length ); + glShaderSource(shader, count, string, length); } - void StencilFunc( GLenum func, GLint ref, GLuint mask ) override + void StencilFunc(GLenum func, GLint ref, GLuint mask) override { - glStencilFunc( func, ref, mask ); + glStencilFunc(func, ref, mask); } - void StencilFuncSeparate( GLenum face, GLenum func, GLint ref, GLuint mask ) override + void StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask) override { - glStencilFuncSeparate( face, func, ref, mask ); + glStencilFuncSeparate(face, func, ref, mask); } - void StencilMask( GLuint mask ) override + void StencilMask(GLuint mask) override { - glStencilMask( mask ); + glStencilMask(mask); } - void StencilMaskSeparate( GLenum face, GLuint mask ) override + void StencilMaskSeparate(GLenum face, GLuint mask) override { - glStencilMaskSeparate( face, mask ); + glStencilMaskSeparate(face, mask); } - void StencilOp( GLenum fail, GLenum zfail, GLenum zpass ) override + void StencilOp(GLenum fail, GLenum zfail, GLenum zpass) override { - glStencilOp( fail, zfail, zpass ); + glStencilOp(fail, zfail, zpass); } - void StencilOpSeparate( GLenum face, GLenum fail, GLenum zfail, GLenum zpass ) override + void StencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass) override { - glStencilOpSeparate( face, fail, zfail, zpass ); + glStencilOpSeparate(face, fail, zfail, zpass); } - void TexImage2D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels ) override + void TexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) override { - glTexImage2D( target, level, internalformat, width, height, border, format, type, pixels ); + glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } - void TexParameterf( GLenum target, GLenum pname, GLfloat param ) override + void TexParameterf(GLenum target, GLenum pname, GLfloat param) override { - glTexParameterf( target, pname, param ); + glTexParameterf(target, pname, param); } - void TexParameterfv( GLenum target, GLenum pname, const GLfloat* params ) override + void TexParameterfv(GLenum target, GLenum pname, const GLfloat* params) override { - glTexParameterfv( target, pname, params ); + glTexParameterfv(target, pname, params); } - void TexParameteri( GLenum target, GLenum pname, GLint param ) override + void TexParameteri(GLenum target, GLenum pname, GLint param) override { - glTexParameteri( target, pname, param ); + glTexParameteri(target, pname, param); } - void TexParameteriv( GLenum target, GLenum pname, const GLint* params ) override + void TexParameteriv(GLenum target, GLenum pname, const GLint* params) override { - glTexParameteriv( target, pname, params ); + glTexParameteriv(target, pname, params); } - void TexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels ) override + void TexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* pixels) override { - glTexSubImage2D( target, level, xoffset, yoffset, width, height, format, type, pixels ); + glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } - void Uniform1f( GLint location, GLfloat x ) override + void Uniform1f(GLint location, GLfloat x) override { - glUniform1f( location, x ); + glUniform1f(location, x); } - void Uniform1fv( GLint location, GLsizei count, const GLfloat* v ) override + void Uniform1fv(GLint location, GLsizei count, const GLfloat* v) override { - glUniform1fv( location, count, v ); + glUniform1fv(location, count, v); } - void Uniform1i( GLint location, GLint x ) override + void Uniform1i(GLint location, GLint x) override { - glUniform1i( location, x ); + glUniform1i(location, x); } - void Uniform1iv( GLint location, GLsizei count, const GLint* v ) override + void Uniform1iv(GLint location, GLsizei count, const GLint* v) override { - glUniform1iv( location, count, v ); + glUniform1iv(location, count, v); } - void Uniform2f( GLint location, GLfloat x, GLfloat y ) override + void Uniform2f(GLint location, GLfloat x, GLfloat y) override { - glUniform2f( location, x, y ); + glUniform2f(location, x, y); } - void Uniform2fv( GLint location, GLsizei count, const GLfloat* v ) override + void Uniform2fv(GLint location, GLsizei count, const GLfloat* v) override { - glUniform2fv( location, count, v ); + glUniform2fv(location, count, v); } - void Uniform2i( GLint location, GLint x, GLint y ) override + void Uniform2i(GLint location, GLint x, GLint y) override { - glUniform2i( location, x, y ); + glUniform2i(location, x, y); } - void Uniform2iv( GLint location, GLsizei count, const GLint* v ) override + void Uniform2iv(GLint location, GLsizei count, const GLint* v) override { - glUniform2iv( location, count, v ); + glUniform2iv(location, count, v); } - void Uniform3f( GLint location, GLfloat x, GLfloat y, GLfloat z ) override + void Uniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z) override { - glUniform3f( location, x, y, z ); + glUniform3f(location, x, y, z); } - void Uniform3fv( GLint location, GLsizei count, const GLfloat* v ) override + void Uniform3fv(GLint location, GLsizei count, const GLfloat* v) override { - glUniform3fv( location, count, v ); + glUniform3fv(location, count, v); } - void Uniform3i( GLint location, GLint x, GLint y, GLint z ) override + void Uniform3i(GLint location, GLint x, GLint y, GLint z) override { - glUniform3i( location, x, y, z ); + glUniform3i(location, x, y, z); } - void Uniform3iv( GLint location, GLsizei count, const GLint* v ) override + void Uniform3iv(GLint location, GLsizei count, const GLint* v) override { - glUniform3iv( location, count, v ); + glUniform3iv(location, count, v); } - void Uniform4f( GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w ) override + void Uniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) override { - glUniform4f( location, x, y, z, w ); + glUniform4f(location, x, y, z, w); } - void Uniform4fv( GLint location, GLsizei count, const GLfloat* v ) override + void Uniform4fv(GLint location, GLsizei count, const GLfloat* v) override { - glUniform4fv( location, count, v ); + glUniform4fv(location, count, v); } - void Uniform4i( GLint location, GLint x, GLint y, GLint z, GLint w ) override + void Uniform4i(GLint location, GLint x, GLint y, GLint z, GLint w) override { - glUniform4i( location, x, y, z, w ); + glUniform4i(location, x, y, z, w); } - void Uniform4iv( GLint location, GLsizei count, const GLint* v ) override + void Uniform4iv(GLint location, GLsizei count, const GLint* v) override { - glUniform4iv( location, count, v ); + glUniform4iv(location, count, v); } - void UniformMatrix2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix2fv( location, count, transpose, value ); + glUniformMatrix2fv(location, count, transpose, value); } - void UniformMatrix3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix3fv( location, count, transpose, value ); + glUniformMatrix3fv(location, count, transpose, value); } - void UniformMatrix4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix4fv( location, count, transpose, value ); + glUniformMatrix4fv(location, count, transpose, value); } - void UseProgram( GLuint program ) override + void UseProgram(GLuint program) override { - glUseProgram( program ); + glUseProgram(program); } - void ValidateProgram( GLuint program ) override + void ValidateProgram(GLuint program) override { - glValidateProgram( program ); + glValidateProgram(program); } - void VertexAttrib1f( GLuint indx, GLfloat x ) override + void VertexAttrib1f(GLuint indx, GLfloat x) override { - glVertexAttrib1f( indx, x ); + glVertexAttrib1f(indx, x); } - void VertexAttrib1fv( GLuint indx, const GLfloat* values ) override + void VertexAttrib1fv(GLuint indx, const GLfloat* values) override { - glVertexAttrib1fv( indx, values ); + glVertexAttrib1fv(indx, values); } - void VertexAttrib2f( GLuint indx, GLfloat x, GLfloat y ) override + void VertexAttrib2f(GLuint indx, GLfloat x, GLfloat y) override { - glVertexAttrib2f( indx, x, y ); + glVertexAttrib2f(indx, x, y); } - void VertexAttrib2fv( GLuint indx, const GLfloat* values ) override + void VertexAttrib2fv(GLuint indx, const GLfloat* values) override { - glVertexAttrib2fv( indx, values ); + glVertexAttrib2fv(indx, values); } - void VertexAttrib3f( GLuint indx, GLfloat x, GLfloat y, GLfloat z ) override + void VertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z) override { - glVertexAttrib3f( indx, x, y, z ); + glVertexAttrib3f(indx, x, y, z); } - void VertexAttrib3fv( GLuint indx, const GLfloat* values ) override + void VertexAttrib3fv(GLuint indx, const GLfloat* values) override { - glVertexAttrib3fv( indx, values ); + glVertexAttrib3fv(indx, values); } - void VertexAttrib4f( GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w ) override + void VertexAttrib4f(GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w) override { - glVertexAttrib4f( indx, x, y, z, w ); + glVertexAttrib4f(indx, x, y, z, w); } - void VertexAttrib4fv( GLuint indx, const GLfloat* values ) override + void VertexAttrib4fv(GLuint indx, const GLfloat* values) override { - glVertexAttrib4fv( indx, values ); + glVertexAttrib4fv(indx, values); } - void VertexAttribPointer( GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr ) override + void VertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* ptr) override { - glVertexAttribPointer( indx, size, type, normalized, stride, ptr ); + glVertexAttribPointer(indx, size, type, normalized, stride, ptr); } - void Viewport( GLint x, GLint y, GLsizei width, GLsizei height ) override + void Viewport(GLint x, GLint y, GLsizei width, GLsizei height) override { - glViewport( x, y, width, height ); + glViewport(x, y, width, height); } /* OpenGL ES 3.0 */ - void ReadBuffer( GLenum mode ) override + void ReadBuffer(GLenum mode) override { - mImpl->ReadBuffer( mode ); + mImpl->ReadBuffer(mode); } - void DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices ) override + void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) override { - mImpl->DrawRangeElements( mode, start, end, count, type, indices ); + mImpl->DrawRangeElements(mode, start, end, count, type, indices); } - void TexImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels ) override + void TexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels) override { - mImpl->TexImage3D( target, level, internalformat, width, height, depth, border, format, type, pixels ); + mImpl->TexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels); } - void TexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels ) override + void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) override { - mImpl->TexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels ); + mImpl->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); } - void CopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) override + void CopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) override { - mImpl->CopyTexSubImage3D( target, level, xoffset, yoffset, zoffset, x, y, width, height ); + mImpl->CopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height); } - void CompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data ) override + void CompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data) override { - mImpl->CompressedTexImage3D( target, level, internalformat, width, height, depth, border, imageSize, data ); + mImpl->CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data); } - void CompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data ) override + void CompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data) override { - mImpl->CompressedTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data ); + mImpl->CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data); } - void GenQueries( GLsizei n, GLuint* ids ) override + void GenQueries(GLsizei n, GLuint* ids) override { - mImpl->GenQueries( n, ids ); + mImpl->GenQueries(n, ids); } - void DeleteQueries( GLsizei n, const GLuint* ids ) override + void DeleteQueries(GLsizei n, const GLuint* ids) override { - mImpl->DeleteQueries( n, ids ); + mImpl->DeleteQueries(n, ids); } - GLboolean IsQuery( GLuint id ) override + GLboolean IsQuery(GLuint id) override { - return mImpl->IsQuery( id ); + return mImpl->IsQuery(id); } - void BeginQuery( GLenum target, GLuint id ) override + void BeginQuery(GLenum target, GLuint id) override { - mImpl->BeginQuery( target, id ); + mImpl->BeginQuery(target, id); } - void EndQuery( GLenum target ) override + void EndQuery(GLenum target) override { - mImpl->EndQuery( target ); + mImpl->EndQuery(target); } - void GetQueryiv( GLenum target, GLenum pname, GLint* params ) override + void GetQueryiv(GLenum target, GLenum pname, GLint* params) override { - mImpl->GetQueryiv( target, pname, params ); + mImpl->GetQueryiv(target, pname, params); } - void GetQueryObjectuiv( GLuint id, GLenum pname, GLuint* params ) override + void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params) override { - mImpl->GetQueryObjectuiv( id, pname, params ); + mImpl->GetQueryObjectuiv(id, pname, params); } - GLboolean UnmapBuffer( GLenum target ) override + GLboolean UnmapBuffer(GLenum target) override { - return mImpl->UnmapBuffer( target ); + return mImpl->UnmapBuffer(target); } - void GetBufferPointerv( GLenum target, GLenum pname, GLvoid** params ) override + void GetBufferPointerv(GLenum target, GLenum pname, GLvoid** params) override { - mImpl->GetBufferPointerv( target, pname, params ); + mImpl->GetBufferPointerv(target, pname, params); } - void DrawBuffers( GLsizei n, const GLenum* bufs ) override + void DrawBuffers(GLsizei n, const GLenum* bufs) override { - mImpl->DrawBuffers( n, bufs ); + mImpl->DrawBuffers(n, bufs); } - void UniformMatrix2x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - mImpl->UniformMatrix2x3fv( location, count, transpose, value ); + mImpl->UniformMatrix2x3fv(location, count, transpose, value); } - void UniformMatrix3x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - mImpl->UniformMatrix3x2fv( location, count, transpose, value ); + mImpl->UniformMatrix3x2fv(location, count, transpose, value); } - void UniformMatrix2x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - mImpl->UniformMatrix2x4fv( location, count, transpose, value ); + mImpl->UniformMatrix2x4fv(location, count, transpose, value); } - void UniformMatrix4x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - mImpl->UniformMatrix4x2fv( location, count, transpose, value ); + mImpl->UniformMatrix4x2fv(location, count, transpose, value); } - void UniformMatrix3x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - mImpl->UniformMatrix3x4fv( location, count, transpose, value ); + mImpl->UniformMatrix3x4fv(location, count, transpose, value); } - void UniformMatrix4x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - mImpl->UniformMatrix4x3fv( location, count, transpose, value ); + mImpl->UniformMatrix4x3fv(location, count, transpose, value); } - void BlitFramebuffer( GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter ) override + void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override { - mImpl->BlitFramebuffer( srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter ); + mImpl->BlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } - void RenderbufferStorageMultisample( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height ) override + void RenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) override { - mImpl->RenderbufferStorageMultisample( target, samples, internalformat, width, height ); + mImpl->RenderbufferStorageMultisample(target, samples, internalformat, width, height); } - void FramebufferTextureLayer( GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer ) override + void FramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) override { - mImpl->FramebufferTextureLayer( target, attachment, texture, level, layer ); + mImpl->FramebufferTextureLayer(target, attachment, texture, level, layer); } - GLvoid* MapBufferRange( GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access ) override + GLvoid* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) override { - return mImpl->MapBufferRange( target, offset, length, access ); + return mImpl->MapBufferRange(target, offset, length, access); } - void FlushMappedBufferRange( GLenum target, GLintptr offset, GLsizeiptr length ) override + void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) override { - mImpl->FlushMappedBufferRange( target, offset, length ); + mImpl->FlushMappedBufferRange(target, offset, length); } - void BindVertexArray( GLuint array ) override + void BindVertexArray(GLuint array) override { - mImpl->BindVertexArray( array ); + mImpl->BindVertexArray(array); } - void DeleteVertexArrays( GLsizei n, const GLuint* arrays ) override + void DeleteVertexArrays(GLsizei n, const GLuint* arrays) override { - mImpl->DeleteVertexArrays( n, arrays ); + mImpl->DeleteVertexArrays(n, arrays); } - void GenVertexArrays( GLsizei n, GLuint* arrays ) override + void GenVertexArrays(GLsizei n, GLuint* arrays) override { - mImpl->GenVertexArrays( n, arrays ); + mImpl->GenVertexArrays(n, arrays); } - GLboolean IsVertexArray( GLuint array ) override + GLboolean IsVertexArray(GLuint array) override { - return mImpl->IsVertexArray( array ); + return mImpl->IsVertexArray(array); } - void GetIntegeri_v( GLenum target, GLuint index, GLint* data ) override + void GetIntegeri_v(GLenum target, GLuint index, GLint* data) override { - mImpl->GetIntegeri_v( target, index, data ); + mImpl->GetIntegeri_v(target, index, data); } - void BeginTransformFeedback( GLenum primitiveMode ) override + void BeginTransformFeedback(GLenum primitiveMode) override { - mImpl->BeginTransformFeedback( primitiveMode ); + mImpl->BeginTransformFeedback(primitiveMode); } - void EndTransformFeedback( void ) override + void EndTransformFeedback(void) override { mImpl->EndTransformFeedback(); } - void BindBufferRange( GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size ) override + void BindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) override { - mImpl->BindBufferRange( target, index, buffer, offset, size ); + mImpl->BindBufferRange(target, index, buffer, offset, size); } - void BindBufferBase( GLenum target, GLuint index, GLuint buffer ) override + void BindBufferBase(GLenum target, GLuint index, GLuint buffer) override { - mImpl->BindBufferBase( target, index, buffer ); + mImpl->BindBufferBase(target, index, buffer); } - void TransformFeedbackVaryings( GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode ) override + void TransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) override { - mImpl->TransformFeedbackVaryings( program, count, varyings, bufferMode ); + mImpl->TransformFeedbackVaryings(program, count, varyings, bufferMode); } - void GetTransformFeedbackVarying( GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name ) override + void GetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) override { - mImpl->GetTransformFeedbackVarying( program, index, bufSize, length, size, type, name ); + mImpl->GetTransformFeedbackVarying(program, index, bufSize, length, size, type, name); } - void VertexAttribIPointer( GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer ) override + void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) override { - mImpl->VertexAttribIPointer( index, size, type, stride, pointer ); + mImpl->VertexAttribIPointer(index, size, type, stride, pointer); } - void GetVertexAttribIiv( GLuint index, GLenum pname, GLint* params ) override + void GetVertexAttribIiv(GLuint index, GLenum pname, GLint* params) override { - mImpl->GetVertexAttribIiv( index, pname, params ); + mImpl->GetVertexAttribIiv(index, pname, params); } - void GetVertexAttribIuiv( GLuint index, GLenum pname, GLuint* params ) override + void GetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params) override { - mImpl->GetVertexAttribIuiv( index, pname, params ); + mImpl->GetVertexAttribIuiv(index, pname, params); } - void VertexAttribI4i( GLuint index, GLint x, GLint y, GLint z, GLint w ) override + void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w) override { - mImpl->VertexAttribI4i( index, x, y, z, w ); + mImpl->VertexAttribI4i(index, x, y, z, w); } - void VertexAttribI4ui( GLuint index, GLuint x, GLuint y, GLuint z, GLuint w ) override + void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) override { - mImpl->VertexAttribI4ui( index, x, y, z, w ); + mImpl->VertexAttribI4ui(index, x, y, z, w); } - void VertexAttribI4iv( GLuint index, const GLint* v ) override + void VertexAttribI4iv(GLuint index, const GLint* v) override { - mImpl->VertexAttribI4iv( index, v ); + mImpl->VertexAttribI4iv(index, v); } - void VertexAttribI4uiv( GLuint index, const GLuint* v ) override + void VertexAttribI4uiv(GLuint index, const GLuint* v) override { - mImpl->VertexAttribI4uiv( index, v ); + mImpl->VertexAttribI4uiv(index, v); } - void GetUniformuiv( GLuint program, GLint location, GLuint* params ) override + void GetUniformuiv(GLuint program, GLint location, GLuint* params) override { - mImpl->GetUniformuiv( program, location, params ); + mImpl->GetUniformuiv(program, location, params); } - GLint GetFragDataLocation( GLuint program, const GLchar *name ) override + GLint GetFragDataLocation(GLuint program, const GLchar* name) override { - return mImpl->GetFragDataLocation( program, name ); + return mImpl->GetFragDataLocation(program, name); } - void Uniform1ui( GLint location, GLuint v0 ) override + void Uniform1ui(GLint location, GLuint v0) override { - mImpl->Uniform1ui( location, v0 ); + mImpl->Uniform1ui(location, v0); } - void Uniform2ui( GLint location, GLuint v0, GLuint v1 ) override + void Uniform2ui(GLint location, GLuint v0, GLuint v1) override { - mImpl->Uniform2ui( location, v0, v1 ); + mImpl->Uniform2ui(location, v0, v1); } - void Uniform3ui( GLint location, GLuint v0, GLuint v1, GLuint v2 ) override + void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2) override { - mImpl->Uniform3ui( location, v0, v1, v2 ); + mImpl->Uniform3ui(location, v0, v1, v2); } - void Uniform4ui( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ) override + void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) override { - mImpl->Uniform4ui( location, v0, v1, v2, v3 ); + mImpl->Uniform4ui(location, v0, v1, v2, v3); } - void Uniform1uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform1uiv(GLint location, GLsizei count, const GLuint* value) override { - mImpl->Uniform1uiv( location, count, value ); + mImpl->Uniform1uiv(location, count, value); } - void Uniform2uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform2uiv(GLint location, GLsizei count, const GLuint* value) override { - mImpl->Uniform2uiv( location, count, value ); + mImpl->Uniform2uiv(location, count, value); } - void Uniform3uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform3uiv(GLint location, GLsizei count, const GLuint* value) override { - mImpl->Uniform3uiv( location, count, value ); + mImpl->Uniform3uiv(location, count, value); } - void Uniform4uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform4uiv(GLint location, GLsizei count, const GLuint* value) override { - mImpl->Uniform4uiv( location, count, value ); + mImpl->Uniform4uiv(location, count, value); } - void ClearBufferiv( GLenum buffer, GLint drawbuffer, const GLint* value ) override + void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value) override { - mImpl->ClearBufferiv( buffer, drawbuffer, value ); + mImpl->ClearBufferiv(buffer, drawbuffer, value); } - void ClearBufferuiv( GLenum buffer, GLint drawbuffer, const GLuint* value ) override + void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value) override { - mImpl->ClearBufferuiv( buffer, drawbuffer, value ); + mImpl->ClearBufferuiv(buffer, drawbuffer, value); } - void ClearBufferfv( GLenum buffer, GLint drawbuffer, const GLfloat* value ) override + void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value) override { - mImpl->ClearBufferfv( buffer, drawbuffer, value ); + mImpl->ClearBufferfv(buffer, drawbuffer, value); } - void ClearBufferfi( GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil ) override + void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) override { - mImpl->ClearBufferfi( buffer, drawbuffer, depth, stencil ); + mImpl->ClearBufferfi(buffer, drawbuffer, depth, stencil); } - const GLubyte* GetStringi( GLenum name, GLuint index ) override + const GLubyte* GetStringi(GLenum name, GLuint index) override { - return mImpl->GetStringi( name, index ); + return mImpl->GetStringi(name, index); } - void CopyBufferSubData( GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size ) override + void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) override { - mImpl->CopyBufferSubData( readTarget, writeTarget, readOffset, writeOffset, size ); + mImpl->CopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); } - void GetUniformIndices( GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices ) override + void GetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) override { - mImpl->GetUniformIndices( program, uniformCount, uniformNames, uniformIndices ); + mImpl->GetUniformIndices(program, uniformCount, uniformNames, uniformIndices); } - void GetActiveUniformsiv( GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params ) override + void GetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) override { - mImpl->GetActiveUniformsiv( program, uniformCount, uniformIndices, pname, params ); + mImpl->GetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params); } - GLuint GetUniformBlockIndex( GLuint program, const GLchar* uniformBlockName ) override + GLuint GetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName) override { - return mImpl->GetUniformBlockIndex( program, uniformBlockName ); + return mImpl->GetUniformBlockIndex(program, uniformBlockName); } - void GetActiveUniformBlockiv( GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params ) override + void GetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) override { - mImpl->GetActiveUniformBlockiv( program, uniformBlockIndex, pname, params ); + mImpl->GetActiveUniformBlockiv(program, uniformBlockIndex, pname, params); } - void GetActiveUniformBlockName( GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName ) override + void GetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) override { - mImpl->GetActiveUniformBlockName( program, uniformBlockIndex, bufSize, length, uniformBlockName ); + mImpl->GetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName); } - void UniformBlockBinding( GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding ) override + void UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override { - mImpl->UniformBlockBinding( program, uniformBlockIndex, uniformBlockBinding ); + mImpl->UniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); } - void DrawArraysInstanced( GLenum mode, GLint first, GLsizei count, GLsizei instanceCount ) override + void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount) override { - mImpl->DrawArraysInstanced( mode, first, count, instanceCount ); + mImpl->DrawArraysInstanced(mode, first, count, instanceCount); } - void DrawElementsInstanced( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount ) override + void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount) override { - mImpl->DrawElementsInstanced( mode, count, type, indices, instanceCount ); + mImpl->DrawElementsInstanced(mode, count, type, indices, instanceCount); } - GLsync FenceSync( GLenum condition, GLbitfield flags ) override + GLsync FenceSync(GLenum condition, GLbitfield flags) override { - return mImpl->FenceSync( condition, flags ); + return mImpl->FenceSync(condition, flags); } - GLboolean IsSync( GLsync sync ) override + GLboolean IsSync(GLsync sync) override { - return mImpl->IsSync( sync ); + return mImpl->IsSync(sync); } - void DeleteSync( GLsync sync ) override + void DeleteSync(GLsync sync) override { - mImpl->DeleteSync( sync ); + mImpl->DeleteSync(sync); } - GLenum ClientWaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) override + GLenum ClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) override { - return mImpl->ClientWaitSync( sync, flags, timeout ); + return mImpl->ClientWaitSync(sync, flags, timeout); } - void WaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) override + void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) override { - mImpl->WaitSync( sync, flags, timeout ); + mImpl->WaitSync(sync, flags, timeout); } - void GetInteger64v( GLenum pname, GLint64* params ) override + void GetInteger64v(GLenum pname, GLint64* params) override { - mImpl->GetInteger64v( pname, params ); + mImpl->GetInteger64v(pname, params); } - void GetSynciv( GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values ) override + void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) override { - mImpl->GetSynciv( sync, pname, bufSize, length, values ); + mImpl->GetSynciv(sync, pname, bufSize, length, values); } - void GetInteger64i_v( GLenum target, GLuint index, GLint64* data ) override + void GetInteger64i_v(GLenum target, GLuint index, GLint64* data) override { - mImpl->GetInteger64i_v( target, index, data ); + mImpl->GetInteger64i_v(target, index, data); } - void GetBufferParameteri64v( GLenum target, GLenum pname, GLint64* params ) override + void GetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params) override { - mImpl->GetBufferParameteri64v( target, pname, params ); + mImpl->GetBufferParameteri64v(target, pname, params); } - void GenSamplers( GLsizei count, GLuint* samplers ) override + void GenSamplers(GLsizei count, GLuint* samplers) override { - mImpl->GenSamplers( count, samplers ); + mImpl->GenSamplers(count, samplers); } - void DeleteSamplers( GLsizei count, const GLuint* samplers ) override + void DeleteSamplers(GLsizei count, const GLuint* samplers) override { - mImpl->DeleteSamplers( count, samplers ); + mImpl->DeleteSamplers(count, samplers); } - GLboolean IsSampler( GLuint sampler ) override + GLboolean IsSampler(GLuint sampler) override { - return mImpl->IsSampler( sampler ); + return mImpl->IsSampler(sampler); } - void BindSampler( GLuint unit, GLuint sampler ) override + void BindSampler(GLuint unit, GLuint sampler) override { - mImpl->BindSampler( unit, sampler ); + mImpl->BindSampler(unit, sampler); } - void SamplerParameteri( GLuint sampler, GLenum pname, GLint param ) override + void SamplerParameteri(GLuint sampler, GLenum pname, GLint param) override { - mImpl->SamplerParameteri( sampler, pname, param ); + mImpl->SamplerParameteri(sampler, pname, param); } - void SamplerParameteriv( GLuint sampler, GLenum pname, const GLint* param ) override + void SamplerParameteriv(GLuint sampler, GLenum pname, const GLint* param) override { - mImpl->SamplerParameteriv( sampler, pname, param ); + mImpl->SamplerParameteriv(sampler, pname, param); } - void SamplerParameterf( GLuint sampler, GLenum pname, GLfloat param ) override + void SamplerParameterf(GLuint sampler, GLenum pname, GLfloat param) override { - mImpl->SamplerParameterf( sampler, pname, param ); + mImpl->SamplerParameterf(sampler, pname, param); } - void SamplerParameterfv( GLuint sampler, GLenum pname, const GLfloat* param ) override + void SamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat* param) override { - mImpl->SamplerParameterfv( sampler, pname, param ); + mImpl->SamplerParameterfv(sampler, pname, param); } - void GetSamplerParameteriv( GLuint sampler, GLenum pname, GLint* params ) override + void GetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params) override { - mImpl->GetSamplerParameteriv( sampler, pname, params ); + mImpl->GetSamplerParameteriv(sampler, pname, params); } - void GetSamplerParameterfv( GLuint sampler, GLenum pname, GLfloat* params ) override + void GetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params) override { - mImpl->GetSamplerParameterfv( sampler, pname, params ); + mImpl->GetSamplerParameterfv(sampler, pname, params); } - void VertexAttribDivisor( GLuint index, GLuint divisor ) override + void VertexAttribDivisor(GLuint index, GLuint divisor) override { - mImpl->VertexAttribDivisor( index, divisor ); + mImpl->VertexAttribDivisor(index, divisor); } - void BindTransformFeedback( GLenum target, GLuint id ) override + void BindTransformFeedback(GLenum target, GLuint id) override { - mImpl->BindTransformFeedback( target, id ); + mImpl->BindTransformFeedback(target, id); } - void DeleteTransformFeedbacks( GLsizei n, const GLuint* ids ) override + void DeleteTransformFeedbacks(GLsizei n, const GLuint* ids) override { - mImpl->DeleteTransformFeedbacks( n, ids ); + mImpl->DeleteTransformFeedbacks(n, ids); } - void GenTransformFeedbacks( GLsizei n, GLuint* ids ) override + void GenTransformFeedbacks(GLsizei n, GLuint* ids) override { - mImpl->GenTransformFeedbacks( n, ids ); + mImpl->GenTransformFeedbacks(n, ids); } - GLboolean IsTransformFeedback( GLuint id ) override + GLboolean IsTransformFeedback(GLuint id) override { - return mImpl->IsTransformFeedback( id ); + return mImpl->IsTransformFeedback(id); } - void PauseTransformFeedback( void ) override + void PauseTransformFeedback(void) override { mImpl->PauseTransformFeedback(); } - void ResumeTransformFeedback( void ) override + void ResumeTransformFeedback(void) override { mImpl->ResumeTransformFeedback(); } - void GetProgramBinary( GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary ) override + void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) override { - mImpl->GetProgramBinary( program, bufSize, length, binaryFormat, binary ); + mImpl->GetProgramBinary(program, bufSize, length, binaryFormat, binary); } - void ProgramBinary( GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length ) override + void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) override { - mImpl->ProgramBinary( program, binaryFormat, binary, length ); + mImpl->ProgramBinary(program, binaryFormat, binary, length); } - void ProgramParameteri( GLuint program, GLenum pname, GLint value ) override + void ProgramParameteri(GLuint program, GLenum pname, GLint value) override { - mImpl->ProgramParameteri( program, pname, value ); + mImpl->ProgramParameteri(program, pname, value); } - void InvalidateFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments ) override + void InvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments) override { - mImpl->InvalidateFramebuffer( target, numAttachments, attachments ); + mImpl->InvalidateFramebuffer(target, numAttachments, attachments); } - void InvalidateSubFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height ) override + void InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height) override { - mImpl->InvalidateSubFramebuffer( target, numAttachments, attachments, x, y, width, height ); + mImpl->InvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height); } - void TexStorage2D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height ) override + void TexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) override { - mImpl->TexStorage2D( target, levels, internalformat, width, height ); + mImpl->TexStorage2D(target, levels, internalformat, width, height); } - void TexStorage3D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth ) override + void TexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) override { - mImpl->TexStorage3D( target, levels, internalformat, width, height, depth ); + mImpl->TexStorage3D(target, levels, internalformat, width, height, depth); } - void GetInternalformativ( GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params ) override + void GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) override { - mImpl->GetInternalformativ( target, internalformat, pname, bufSize, params ); + mImpl->GetInternalformativ(target, internalformat, pname, bufSize, params); } void BlendBarrier(void) @@ -1597,18 +1594,18 @@ public: private: std::unique_ptr mImpl; - ConditionalWait mContextCreatedWaitCondition; - GLint mMaxTextureSize; - std::string mShaderVersionPrefix; - std::string mVertexShaderPrefix; - std::string mFragmentShaderPrefix; - int32_t mGlesVersion; - int32_t mShadingLanguageVersion; - bool mShadingLanguageVersionCached; - bool mIsSurfacelessContextSupported; - bool mIsAdvancedBlendEquationSupportedCached; - bool mIsAdvancedBlendEquationSupported; - bool mIsContextCreated; + ConditionalWait mContextCreatedWaitCondition; + GLint mMaxTextureSize; + std::string mShaderVersionPrefix; + std::string mVertexShaderPrefix; + std::string mFragmentShaderPrefix; + int32_t mGlesVersion; + int32_t mShadingLanguageVersion; + bool mShadingLanguageVersionCached; + bool mIsSurfacelessContextSupported; + bool mIsAdvancedBlendEquationSupportedCached; + bool mIsAdvancedBlendEquationSupported; + bool mIsContextCreated; }; } // namespace Adaptor diff --git a/dali/internal/graphics/gles/gles-abstraction.h b/dali/internal/graphics/gles/gles-abstraction.h index 6334b27..80e0c6e 100644 --- a/dali/internal/graphics/gles/gles-abstraction.h +++ b/dali/internal/graphics/gles/gles-abstraction.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_GLES_ABSTRACTION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,232 +20,227 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class GlesAbstraction { - public: - /** * Destructor */ - virtual ~GlesAbstraction() {}; + virtual ~GlesAbstraction(){}; - virtual void ReadBuffer( GLenum mode ) = 0; + virtual void ReadBuffer(GLenum mode) = 0; - virtual void DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices ) = 0; + virtual void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) = 0; - virtual void TexImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels ) = 0; + virtual void TexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels) = 0; - virtual void TexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels ) = 0; + virtual void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) = 0; - virtual void CopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) = 0; + virtual void CopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) = 0; - virtual void CompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data ) = 0; + virtual void CompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data) = 0; - virtual void CompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data ) = 0; + virtual void CompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data) = 0; - virtual void GenQueries( GLsizei n, GLuint* ids ) = 0; + virtual void GenQueries(GLsizei n, GLuint* ids) = 0; - virtual void DeleteQueries( GLsizei n, const GLuint* ids ) = 0; + virtual void DeleteQueries(GLsizei n, const GLuint* ids) = 0; - virtual GLboolean IsQuery( GLuint id ) = 0; + virtual GLboolean IsQuery(GLuint id) = 0; - virtual void BeginQuery( GLenum target, GLuint id ) = 0; + virtual void BeginQuery(GLenum target, GLuint id) = 0; - virtual void EndQuery( GLenum target ) = 0; + virtual void EndQuery(GLenum target) = 0; - virtual void GetQueryiv( GLenum target, GLenum pname, GLint* params ) = 0; + virtual void GetQueryiv(GLenum target, GLenum pname, GLint* params) = 0; - virtual void GetQueryObjectuiv( GLuint id, GLenum pname, GLuint* params ) = 0; + virtual void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params) = 0; - virtual GLboolean UnmapBuffer( GLenum target ) = 0; + virtual GLboolean UnmapBuffer(GLenum target) = 0; - virtual void GetBufferPointerv( GLenum target, GLenum pname, GLvoid** params ) = 0; + virtual void GetBufferPointerv(GLenum target, GLenum pname, GLvoid** params) = 0; - virtual void DrawBuffers( GLsizei n, const GLenum* bufs ) = 0; + virtual void DrawBuffers(GLsizei n, const GLenum* bufs) = 0; - virtual void UniformMatrix2x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) = 0; + virtual void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) = 0; - virtual void UniformMatrix3x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) = 0; + virtual void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) = 0; - virtual void UniformMatrix2x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) = 0; + virtual void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) = 0; - virtual void UniformMatrix4x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) = 0; + virtual void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) = 0; - virtual void UniformMatrix3x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) = 0; + virtual void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) = 0; - virtual void UniformMatrix4x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) = 0; + virtual void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) = 0; - virtual void BlitFramebuffer( GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter ) = 0; + virtual void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) = 0; - virtual void RenderbufferStorageMultisample( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height ) = 0; + virtual void RenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) = 0; - virtual void FramebufferTextureLayer( GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer ) = 0; + virtual void FramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) = 0; - virtual GLvoid* MapBufferRange( GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access ) = 0; + virtual GLvoid* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) = 0; - virtual void FlushMappedBufferRange( GLenum target, GLintptr offset, GLsizeiptr length ) = 0; + virtual void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) = 0; - virtual void BindVertexArray( GLuint array ) = 0; + virtual void BindVertexArray(GLuint array) = 0; - virtual void DeleteVertexArrays( GLsizei n, const GLuint* arrays ) = 0; + virtual void DeleteVertexArrays(GLsizei n, const GLuint* arrays) = 0; - virtual void GenVertexArrays( GLsizei n, GLuint* arrays ) = 0; + virtual void GenVertexArrays(GLsizei n, GLuint* arrays) = 0; - virtual GLboolean IsVertexArray( GLuint array ) = 0; + virtual GLboolean IsVertexArray(GLuint array) = 0; - virtual void GetIntegeri_v( GLenum target, GLuint index, GLint* data ) = 0; + virtual void GetIntegeri_v(GLenum target, GLuint index, GLint* data) = 0; - virtual void BeginTransformFeedback( GLenum primitiveMode ) = 0; + virtual void BeginTransformFeedback(GLenum primitiveMode) = 0; - virtual void EndTransformFeedback( void ) = 0; + virtual void EndTransformFeedback(void) = 0; - virtual void BindBufferRange( GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size ) = 0; + virtual void BindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) = 0; - virtual void BindBufferBase( GLenum target, GLuint index, GLuint buffer ) = 0; + virtual void BindBufferBase(GLenum target, GLuint index, GLuint buffer) = 0; - virtual void TransformFeedbackVaryings( GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode ) = 0; + virtual void TransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) = 0; - virtual void GetTransformFeedbackVarying( GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name ) = 0; + virtual void GetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) = 0; - virtual void VertexAttribIPointer( GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer ) = 0; + virtual void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) = 0; - virtual void GetVertexAttribIiv( GLuint index, GLenum pname, GLint* params ) = 0; + virtual void GetVertexAttribIiv(GLuint index, GLenum pname, GLint* params) = 0; - virtual void GetVertexAttribIuiv( GLuint index, GLenum pname, GLuint* params ) = 0; + virtual void GetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params) = 0; - virtual void VertexAttribI4i( GLuint index, GLint x, GLint y, GLint z, GLint w ) = 0; + virtual void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w) = 0; - virtual void VertexAttribI4ui( GLuint index, GLuint x, GLuint y, GLuint z, GLuint w ) = 0; + virtual void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) = 0; - virtual void VertexAttribI4iv( GLuint index, const GLint* v ) = 0; + virtual void VertexAttribI4iv(GLuint index, const GLint* v) = 0; - virtual void VertexAttribI4uiv( GLuint index, const GLuint* v ) = 0; + virtual void VertexAttribI4uiv(GLuint index, const GLuint* v) = 0; - virtual void GetUniformuiv( GLuint program, GLint location, GLuint* params ) = 0; + virtual void GetUniformuiv(GLuint program, GLint location, GLuint* params) = 0; - virtual GLint GetFragDataLocation( GLuint program, const GLchar *name ) = 0; + virtual GLint GetFragDataLocation(GLuint program, const GLchar* name) = 0; - virtual void Uniform1ui( GLint location, GLuint v0 ) = 0; + virtual void Uniform1ui(GLint location, GLuint v0) = 0; - virtual void Uniform2ui( GLint location, GLuint v0, GLuint v1 ) = 0; + virtual void Uniform2ui(GLint location, GLuint v0, GLuint v1) = 0; - virtual void Uniform3ui( GLint location, GLuint v0, GLuint v1, GLuint v2 ) = 0; + virtual void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2) = 0; - virtual void Uniform4ui( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ) = 0; + virtual void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) = 0; - virtual void Uniform1uiv( GLint location, GLsizei count, const GLuint* value ) = 0; + virtual void Uniform1uiv(GLint location, GLsizei count, const GLuint* value) = 0; - virtual void Uniform2uiv( GLint location, GLsizei count, const GLuint* value ) = 0; + virtual void Uniform2uiv(GLint location, GLsizei count, const GLuint* value) = 0; - virtual void Uniform3uiv( GLint location, GLsizei count, const GLuint* value ) = 0; + virtual void Uniform3uiv(GLint location, GLsizei count, const GLuint* value) = 0; - virtual void Uniform4uiv( GLint location, GLsizei count, const GLuint* value ) = 0; + virtual void Uniform4uiv(GLint location, GLsizei count, const GLuint* value) = 0; - virtual void ClearBufferiv( GLenum buffer, GLint drawbuffer, const GLint* value ) = 0; + virtual void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value) = 0; - virtual void ClearBufferuiv( GLenum buffer, GLint drawbuffer, const GLuint* value ) = 0; + virtual void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value) = 0; - virtual void ClearBufferfv( GLenum buffer, GLint drawbuffer, const GLfloat* value ) = 0; + virtual void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value) = 0; - virtual void ClearBufferfi( GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil ) = 0; + virtual void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) = 0; - virtual const GLubyte* GetStringi( GLenum name, GLuint index ) = 0; + virtual const GLubyte* GetStringi(GLenum name, GLuint index) = 0; - virtual void CopyBufferSubData( GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size ) = 0; + virtual void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) = 0; - virtual void GetUniformIndices( GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices ) = 0; + virtual void GetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) = 0; - virtual void GetActiveUniformsiv( GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params ) = 0; + virtual void GetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) = 0; - virtual GLuint GetUniformBlockIndex( GLuint program, const GLchar* uniformBlockName ) = 0; + virtual GLuint GetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName) = 0; - virtual void GetActiveUniformBlockiv( GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params ) = 0; + virtual void GetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) = 0; - virtual void GetActiveUniformBlockName( GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName ) = 0; + virtual void GetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) = 0; - virtual void UniformBlockBinding( GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding ) = 0; + virtual void UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) = 0; - virtual void DrawArraysInstanced( GLenum mode, GLint first, GLsizei count, GLsizei instanceCount ) = 0; + virtual void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount) = 0; - virtual void DrawElementsInstanced( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount ) = 0; + virtual void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount) = 0; - virtual GLsync FenceSync( GLenum condition, GLbitfield flags ) = 0; + virtual GLsync FenceSync(GLenum condition, GLbitfield flags) = 0; - virtual GLboolean IsSync( GLsync sync ) = 0; + virtual GLboolean IsSync(GLsync sync) = 0; - virtual void DeleteSync( GLsync sync ) = 0; + virtual void DeleteSync(GLsync sync) = 0; - virtual GLenum ClientWaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) = 0; + virtual GLenum ClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) = 0; - virtual void WaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) = 0; + virtual void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) = 0; - virtual void GetInteger64v( GLenum pname, GLint64* params ) = 0; + virtual void GetInteger64v(GLenum pname, GLint64* params) = 0; - virtual void GetSynciv( GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values ) = 0; + virtual void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) = 0; - virtual void GetInteger64i_v( GLenum target, GLuint index, GLint64* data ) = 0; + virtual void GetInteger64i_v(GLenum target, GLuint index, GLint64* data) = 0; - virtual void GetBufferParameteri64v( GLenum target, GLenum pname, GLint64* params ) = 0; + virtual void GetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params) = 0; - virtual void GenSamplers( GLsizei count, GLuint* samplers ) = 0; + virtual void GenSamplers(GLsizei count, GLuint* samplers) = 0; - virtual void DeleteSamplers( GLsizei count, const GLuint* samplers ) = 0; + virtual void DeleteSamplers(GLsizei count, const GLuint* samplers) = 0; - virtual GLboolean IsSampler( GLuint sampler ) = 0; + virtual GLboolean IsSampler(GLuint sampler) = 0; - virtual void BindSampler( GLuint unit, GLuint sampler ) = 0; + virtual void BindSampler(GLuint unit, GLuint sampler) = 0; - virtual void SamplerParameteri( GLuint sampler, GLenum pname, GLint param ) = 0; + virtual void SamplerParameteri(GLuint sampler, GLenum pname, GLint param) = 0; - virtual void SamplerParameteriv( GLuint sampler, GLenum pname, const GLint* param ) = 0; + virtual void SamplerParameteriv(GLuint sampler, GLenum pname, const GLint* param) = 0; - virtual void SamplerParameterf( GLuint sampler, GLenum pname, GLfloat param ) = 0; + virtual void SamplerParameterf(GLuint sampler, GLenum pname, GLfloat param) = 0; - virtual void SamplerParameterfv( GLuint sampler, GLenum pname, const GLfloat* param ) = 0; + virtual void SamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat* param) = 0; - virtual void GetSamplerParameteriv( GLuint sampler, GLenum pname, GLint* params ) = 0; + virtual void GetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params) = 0; - virtual void GetSamplerParameterfv( GLuint sampler, GLenum pname, GLfloat* params ) = 0; + virtual void GetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params) = 0; - virtual void VertexAttribDivisor( GLuint index, GLuint divisor ) = 0; + virtual void VertexAttribDivisor(GLuint index, GLuint divisor) = 0; - virtual void BindTransformFeedback( GLenum target, GLuint id ) = 0; + virtual void BindTransformFeedback(GLenum target, GLuint id) = 0; - virtual void DeleteTransformFeedbacks( GLsizei n, const GLuint* ids ) = 0; + virtual void DeleteTransformFeedbacks(GLsizei n, const GLuint* ids) = 0; - virtual void GenTransformFeedbacks( GLsizei n, GLuint* ids ) = 0; + virtual void GenTransformFeedbacks(GLsizei n, GLuint* ids) = 0; - virtual GLboolean IsTransformFeedback( GLuint id ) = 0; + virtual GLboolean IsTransformFeedback(GLuint id) = 0; - virtual void PauseTransformFeedback( void ) = 0; + virtual void PauseTransformFeedback(void) = 0; - virtual void ResumeTransformFeedback( void ) = 0; + virtual void ResumeTransformFeedback(void) = 0; - virtual void GetProgramBinary( GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary ) = 0; + virtual void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) = 0; - virtual void ProgramBinary( GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length ) = 0; + virtual void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) = 0; - virtual void ProgramParameteri( GLuint program, GLenum pname, GLint value ) = 0; + virtual void ProgramParameteri(GLuint program, GLenum pname, GLint value) = 0; - virtual void InvalidateFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments ) = 0; + virtual void InvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments) = 0; - virtual void InvalidateSubFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height ) = 0; + virtual void InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height) = 0; - virtual void TexStorage2D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height ) = 0; + virtual void TexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) = 0; - virtual void TexStorage3D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth ) = 0; + virtual void TexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) = 0; - virtual void GetInternalformativ( GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params ) = 0; + virtual void GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) = 0; - virtual void BlendBarrier( void ) = 0; + virtual void BlendBarrier(void) = 0; }; } // namespace Adaptor diff --git a/dali/internal/graphics/gles/gles2-implementation.h b/dali/internal/graphics/gles/gles2-implementation.h index cee1c77..4ca86b3 100644 --- a/dali/internal/graphics/gles/gles2-implementation.h +++ b/dali/internal/graphics/gles/gles2-implementation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_GLES2_IMPLEMENTATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ * */ - // EXTERNAL INCLUDES +// EXTERNAL INCLUDES #include // INTERNAL INCLUDES @@ -27,556 +27,556 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class Gles2Implementation : public GlesAbstraction { - public: - Gles2Implementation() {} + Gles2Implementation() + { + } - ~Gles2Implementation() override {} + ~Gles2Implementation() override + { + } - void ReadBuffer( GLenum mode ) override + void ReadBuffer(GLenum mode) override { - DALI_LOG_ERROR( "glReadBuffer is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glReadBuffer is not supported in OpenGL es 2.0\n"); } - void DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices ) override + void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) override { - DALI_LOG_ERROR( "glDrawRangeElements is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDrawRangeElements is not supported in OpenGL es 2.0\n"); } - void TexImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels ) override + void TexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels) override { - DALI_LOG_ERROR( "glTexImage3D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glTexImage3D is not supported in OpenGL es 2.0\n"); } - void TexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels ) override + void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) override { - DALI_LOG_ERROR( "glTexSubImage3D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glTexSubImage3D is not supported in OpenGL es 2.0\n"); } - void CopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) override + void CopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) override { - DALI_LOG_ERROR( "glCopyTexSubImage3D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glCopyTexSubImage3D is not supported in OpenGL es 2.0\n"); } - void CompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data ) override + void CompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data) override { - DALI_LOG_ERROR( "glCompressedTexImage3D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glCompressedTexImage3D is not supported in OpenGL es 2.0\n"); } - void CompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data ) override + void CompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data) override { - DALI_LOG_ERROR( "glCompressedTexSubImage3D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glCompressedTexSubImage3D is not supported in OpenGL es 2.0\n"); } - void GenQueries( GLsizei n, GLuint* ids ) override + void GenQueries(GLsizei n, GLuint* ids) override { - DALI_LOG_ERROR( "glGenQueries is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGenQueries is not supported in OpenGL es 2.0\n"); } - void DeleteQueries( GLsizei n, const GLuint* ids ) override + void DeleteQueries(GLsizei n, const GLuint* ids) override { - DALI_LOG_ERROR( "glDeleteQueries is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDeleteQueries is not supported in OpenGL es 2.0\n"); } - GLboolean IsQuery( GLuint id ) override + GLboolean IsQuery(GLuint id) override { - DALI_LOG_ERROR( "glIsQuery is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glIsQuery is not supported in OpenGL es 2.0\n"); return 0; } - void BeginQuery( GLenum target, GLuint id ) override + void BeginQuery(GLenum target, GLuint id) override { - DALI_LOG_ERROR( "glBeginQuery is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBeginQuery is not supported in OpenGL es 2.0\n"); } - void EndQuery( GLenum target ) override + void EndQuery(GLenum target) override { - DALI_LOG_ERROR( "glEndQuery is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glEndQuery is not supported in OpenGL es 2.0\n"); } - void GetQueryiv( GLenum target, GLenum pname, GLint* params ) override + void GetQueryiv(GLenum target, GLenum pname, GLint* params) override { - DALI_LOG_ERROR( "glGetQueryiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetQueryiv is not supported in OpenGL es 2.0\n"); } - void GetQueryObjectuiv( GLuint id, GLenum pname, GLuint* params ) override + void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params) override { - DALI_LOG_ERROR( "glGetQueryObjectuiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetQueryObjectuiv is not supported in OpenGL es 2.0\n"); } - GLboolean UnmapBuffer( GLenum target ) override + GLboolean UnmapBuffer(GLenum target) override { - DALI_LOG_ERROR( "glUnmapBuffer is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUnmapBuffer is not supported in OpenGL es 2.0\n"); return 0; } - void GetBufferPointerv( GLenum target, GLenum pname, GLvoid** params ) override + void GetBufferPointerv(GLenum target, GLenum pname, GLvoid** params) override { - DALI_LOG_ERROR( "glGetBufferPointerv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetBufferPointerv is not supported in OpenGL es 2.0\n"); } - void DrawBuffers( GLsizei n, const GLenum* bufs ) override + void DrawBuffers(GLsizei n, const GLenum* bufs) override { - DALI_LOG_ERROR( "glDrawBuffers is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDrawBuffers is not supported in OpenGL es 2.0\n"); } - void UniformMatrix2x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - DALI_LOG_ERROR( "glUniformMatrix2x3fv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformMatrix2x3fv is not supported in OpenGL es 2.0\n"); } - void UniformMatrix3x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - DALI_LOG_ERROR( "glUniformMatrix3x2fv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformMatrix3x2fv is not supported in OpenGL es 2.0\n"); } - void UniformMatrix2x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - DALI_LOG_ERROR( "glUniformMatrix2x4fv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformMatrix2x4fv is not supported in OpenGL es 2.0\n"); } - void UniformMatrix4x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - DALI_LOG_ERROR( "glUniformMatrix4x2fv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformMatrix4x2fv is not supported in OpenGL es 2.0\n"); } - void UniformMatrix3x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - DALI_LOG_ERROR( "glUniformMatrix3x4fv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformMatrix3x4fv is not supported in OpenGL es 2.0\n"); } - void UniformMatrix4x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - DALI_LOG_ERROR( "glUniformMatrix4x3fv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformMatrix4x3fv is not supported in OpenGL es 2.0\n"); } - void BlitFramebuffer( GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter ) override + void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override { - DALI_LOG_ERROR( "glBlitFramebuffer is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBlitFramebuffer is not supported in OpenGL es 2.0\n"); } - void RenderbufferStorageMultisample( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height ) override + void RenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) override { - DALI_LOG_ERROR( "glRenderbufferStorageMultisample is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glRenderbufferStorageMultisample is not supported in OpenGL es 2.0\n"); } - void FramebufferTextureLayer( GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer ) override + void FramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) override { - DALI_LOG_ERROR( "glFramebufferTextureLayer is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glFramebufferTextureLayer is not supported in OpenGL es 2.0\n"); } - GLvoid* MapBufferRange( GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access ) override + GLvoid* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) override { - DALI_LOG_ERROR( "glMapBufferRange is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glMapBufferRange is not supported in OpenGL es 2.0\n"); return NULL; } - void FlushMappedBufferRange( GLenum target, GLintptr offset, GLsizeiptr length ) override + void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) override { - DALI_LOG_ERROR( "glFlushMappedBufferRange is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glFlushMappedBufferRange is not supported in OpenGL es 2.0\n"); } - void BindVertexArray( GLuint array ) override + void BindVertexArray(GLuint array) override { - DALI_LOG_ERROR( "glBindVertexArray is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBindVertexArray is not supported in OpenGL es 2.0\n"); } - void DeleteVertexArrays( GLsizei n, const GLuint* arrays ) override + void DeleteVertexArrays(GLsizei n, const GLuint* arrays) override { - DALI_LOG_ERROR( "glDeleteVertexArrays is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDeleteVertexArrays is not supported in OpenGL es 2.0\n"); } - void GenVertexArrays( GLsizei n, GLuint* arrays ) override + void GenVertexArrays(GLsizei n, GLuint* arrays) override { - DALI_LOG_ERROR( "glGenVertexArrays is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGenVertexArrays is not supported in OpenGL es 2.0\n"); } - GLboolean IsVertexArray( GLuint array ) override + GLboolean IsVertexArray(GLuint array) override { - DALI_LOG_ERROR( "glIsVertexArray is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glIsVertexArray is not supported in OpenGL es 2.0\n"); return 0; } - void GetIntegeri_v( GLenum target, GLuint index, GLint* data ) override + void GetIntegeri_v(GLenum target, GLuint index, GLint* data) override { - DALI_LOG_ERROR( "glGetIntegeri_v is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetIntegeri_v is not supported in OpenGL es 2.0\n"); } - void BeginTransformFeedback( GLenum primitiveMode ) override + void BeginTransformFeedback(GLenum primitiveMode) override { - DALI_LOG_ERROR( "glBeginTransformFeedback is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBeginTransformFeedback is not supported in OpenGL es 2.0\n"); } - void EndTransformFeedback( void ) override + void EndTransformFeedback(void) override { - DALI_LOG_ERROR( "glEndTransformFeedback is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glEndTransformFeedback is not supported in OpenGL es 2.0\n"); } - void BindBufferRange( GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size ) override + void BindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) override { - DALI_LOG_ERROR( "glBindBufferRange is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBindBufferRange is not supported in OpenGL es 2.0\n"); } - void BindBufferBase( GLenum target, GLuint index, GLuint buffer ) override + void BindBufferBase(GLenum target, GLuint index, GLuint buffer) override { - DALI_LOG_ERROR( "glBindBufferBase is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBindBufferBase is not supported in OpenGL es 2.0\n"); } - void TransformFeedbackVaryings( GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode ) override + void TransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) override { - DALI_LOG_ERROR( "glTransformFeedbackVaryings is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glTransformFeedbackVaryings is not supported in OpenGL es 2.0\n"); } - void GetTransformFeedbackVarying( GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name ) override + void GetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) override { - DALI_LOG_ERROR( "glGetTransformFeedbackVarying is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetTransformFeedbackVarying is not supported in OpenGL es 2.0\n"); } - void VertexAttribIPointer( GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer ) override + void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) override { - DALI_LOG_ERROR( "glVertexAttribIPointer is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glVertexAttribIPointer is not supported in OpenGL es 2.0\n"); } - void GetVertexAttribIiv( GLuint index, GLenum pname, GLint* params ) override + void GetVertexAttribIiv(GLuint index, GLenum pname, GLint* params) override { - DALI_LOG_ERROR( "glGetVertexAttribIiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetVertexAttribIiv is not supported in OpenGL es 2.0\n"); } - void GetVertexAttribIuiv( GLuint index, GLenum pname, GLuint* params ) override + void GetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params) override { - DALI_LOG_ERROR( "glGetVertexAttribIuiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetVertexAttribIuiv is not supported in OpenGL es 2.0\n"); } - void VertexAttribI4i( GLuint index, GLint x, GLint y, GLint z, GLint w ) override + void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w) override { - DALI_LOG_ERROR( "glVertexAttribI4i is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glVertexAttribI4i is not supported in OpenGL es 2.0\n"); } - void VertexAttribI4ui( GLuint index, GLuint x, GLuint y, GLuint z, GLuint w ) override + void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) override { - DALI_LOG_ERROR( "glVertexAttribI4ui is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glVertexAttribI4ui is not supported in OpenGL es 2.0\n"); } - void VertexAttribI4iv( GLuint index, const GLint* v ) override + void VertexAttribI4iv(GLuint index, const GLint* v) override { - DALI_LOG_ERROR( "glVertexAttribI4iv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glVertexAttribI4iv is not supported in OpenGL es 2.0\n"); } - void VertexAttribI4uiv( GLuint index, const GLuint* v ) override + void VertexAttribI4uiv(GLuint index, const GLuint* v) override { - DALI_LOG_ERROR( "glVertexAttribI4uiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glVertexAttribI4uiv is not supported in OpenGL es 2.0\n"); } - void GetUniformuiv( GLuint program, GLint location, GLuint* params ) override + void GetUniformuiv(GLuint program, GLint location, GLuint* params) override { - DALI_LOG_ERROR( "glGetUniformuiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetUniformuiv is not supported in OpenGL es 2.0\n"); } - GLint GetFragDataLocation( GLuint program, const GLchar *name ) override + GLint GetFragDataLocation(GLuint program, const GLchar* name) override { - DALI_LOG_ERROR( "glGetFragDataLocation is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetFragDataLocation is not supported in OpenGL es 2.0\n"); return -1; } - void Uniform1ui( GLint location, GLuint v0 ) override + void Uniform1ui(GLint location, GLuint v0) override { - DALI_LOG_ERROR( "glUniform1ui is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform1ui is not supported in OpenGL es 2.0\n"); } - void Uniform2ui( GLint location, GLuint v0, GLuint v1 ) override + void Uniform2ui(GLint location, GLuint v0, GLuint v1) override { - DALI_LOG_ERROR( "glUniform2ui is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform2ui is not supported in OpenGL es 2.0\n"); } - void Uniform3ui( GLint location, GLuint v0, GLuint v1, GLuint v2 ) override + void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2) override { - DALI_LOG_ERROR( "glUniform3ui is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform3ui is not supported in OpenGL es 2.0\n"); } - void Uniform4ui( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ) override + void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) override { - DALI_LOG_ERROR( "glUniform4ui is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform4ui is not supported in OpenGL es 2.0\n"); } - void Uniform1uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform1uiv(GLint location, GLsizei count, const GLuint* value) override { - DALI_LOG_ERROR( "glUniform1uiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform1uiv is not supported in OpenGL es 2.0\n"); } - void Uniform2uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform2uiv(GLint location, GLsizei count, const GLuint* value) override { - DALI_LOG_ERROR( "glUniform2uiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform2uiv is not supported in OpenGL es 2.0\n"); } - void Uniform3uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform3uiv(GLint location, GLsizei count, const GLuint* value) override { - DALI_LOG_ERROR( "glUniform3uiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform3uiv is not supported in OpenGL es 2.0\n"); } - void Uniform4uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform4uiv(GLint location, GLsizei count, const GLuint* value) override { - DALI_LOG_ERROR( "glUniform4uiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniform4uiv is not supported in OpenGL es 2.0\n"); } - void ClearBufferiv( GLenum buffer, GLint drawbuffer, const GLint* value ) override + void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value) override { - DALI_LOG_ERROR( "glClearBufferiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glClearBufferiv is not supported in OpenGL es 2.0\n"); } - void ClearBufferuiv( GLenum buffer, GLint drawbuffer, const GLuint* value ) override + void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value) override { - DALI_LOG_ERROR( "glClearBufferuiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glClearBufferuiv is not supported in OpenGL es 2.0\n"); } - void ClearBufferfv( GLenum buffer, GLint drawbuffer, const GLfloat* value ) override + void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value) override { - DALI_LOG_ERROR( "glClearBufferfv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glClearBufferfv is not supported in OpenGL es 2.0\n"); } - void ClearBufferfi( GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil ) override + void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) override { - DALI_LOG_ERROR( "glClearBufferfi is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glClearBufferfi is not supported in OpenGL es 2.0\n"); } - const GLubyte* GetStringi( GLenum name, GLuint index ) override + const GLubyte* GetStringi(GLenum name, GLuint index) override { - DALI_LOG_ERROR( "glGetStringi is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetStringi is not supported in OpenGL es 2.0\n"); return NULL; } - void CopyBufferSubData( GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size ) override + void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) override { - DALI_LOG_ERROR( "glCopyBufferSubData is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glCopyBufferSubData is not supported in OpenGL es 2.0\n"); } - void GetUniformIndices( GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices ) override + void GetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) override { - DALI_LOG_ERROR( "glGetUniformIndices is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetUniformIndices is not supported in OpenGL es 2.0\n"); } - void GetActiveUniformsiv( GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params ) override + void GetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) override { - DALI_LOG_ERROR( "glGetActiveUniformsiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetActiveUniformsiv is not supported in OpenGL es 2.0\n"); } - GLuint GetUniformBlockIndex( GLuint program, const GLchar* uniformBlockName ) override + GLuint GetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName) override { - DALI_LOG_ERROR( "glGetUniformBlockIndex is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetUniformBlockIndex is not supported in OpenGL es 2.0\n"); return 0; } - void GetActiveUniformBlockiv( GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params ) override + void GetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) override { - DALI_LOG_ERROR( "glGetActiveUniformBlockiv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetActiveUniformBlockiv is not supported in OpenGL es 2.0\n"); } - void GetActiveUniformBlockName( GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName ) override + void GetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) override { - DALI_LOG_ERROR( "glGetActiveUniformBlockName is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetActiveUniformBlockName is not supported in OpenGL es 2.0\n"); } - void UniformBlockBinding( GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding ) override + void UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override { - DALI_LOG_ERROR( "glUniformBlockBinding is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glUniformBlockBinding is not supported in OpenGL es 2.0\n"); } - void DrawArraysInstanced( GLenum mode, GLint first, GLsizei count, GLsizei instanceCount ) override + void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount) override { - DALI_LOG_ERROR( "glDrawArraysInstanced is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDrawArraysInstanced is not supported in OpenGL es 2.0\n"); } - void DrawElementsInstanced( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount ) override + void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount) override { - DALI_LOG_ERROR( "glDrawElementsInstanced is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDrawElementsInstanced is not supported in OpenGL es 2.0\n"); } - GLsync FenceSync( GLenum condition, GLbitfield flags ) override + GLsync FenceSync(GLenum condition, GLbitfield flags) override { - DALI_LOG_ERROR( "glFenceSync is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glFenceSync is not supported in OpenGL es 2.0\n"); return NULL; } - GLboolean IsSync( GLsync sync ) override + GLboolean IsSync(GLsync sync) override { - DALI_LOG_ERROR( "glIsSync is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glIsSync is not supported in OpenGL es 2.0\n"); return 0; } - void DeleteSync( GLsync sync ) override + void DeleteSync(GLsync sync) override { - DALI_LOG_ERROR( "glDeleteSync is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDeleteSync is not supported in OpenGL es 2.0\n"); } - GLenum ClientWaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) override + GLenum ClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) override { - DALI_LOG_ERROR( "glClientWaitSync is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glClientWaitSync is not supported in OpenGL es 2.0\n"); return 0; } - void WaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) override + void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) override { - DALI_LOG_ERROR( "glWaitSync is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glWaitSync is not supported in OpenGL es 2.0\n"); } - void GetInteger64v( GLenum pname, GLint64* params ) override + void GetInteger64v(GLenum pname, GLint64* params) override { - DALI_LOG_ERROR( "glGetInteger64v is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetInteger64v is not supported in OpenGL es 2.0\n"); } - void GetSynciv( GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values ) override + void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) override { - DALI_LOG_ERROR( "glGetSynciv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetSynciv is not supported in OpenGL es 2.0\n"); } - void GetInteger64i_v( GLenum target, GLuint index, GLint64* data ) override + void GetInteger64i_v(GLenum target, GLuint index, GLint64* data) override { - DALI_LOG_ERROR( "glGetInteger64i_v is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetInteger64i_v is not supported in OpenGL es 2.0\n"); } - void GetBufferParameteri64v( GLenum target, GLenum pname, GLint64* params ) override + void GetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params) override { - DALI_LOG_ERROR( "glGetBufferParameteri64v is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetBufferParameteri64v is not supported in OpenGL es 2.0\n"); } - void GenSamplers( GLsizei count, GLuint* samplers ) override + void GenSamplers(GLsizei count, GLuint* samplers) override { - DALI_LOG_ERROR( "glGenSamplers is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGenSamplers is not supported in OpenGL es 2.0\n"); } - void DeleteSamplers( GLsizei count, const GLuint* samplers ) override + void DeleteSamplers(GLsizei count, const GLuint* samplers) override { - DALI_LOG_ERROR( "glDeleteSamplers is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDeleteSamplers is not supported in OpenGL es 2.0\n"); } - GLboolean IsSampler( GLuint sampler ) override + GLboolean IsSampler(GLuint sampler) override { - DALI_LOG_ERROR( "glIsSampler is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glIsSampler is not supported in OpenGL es 2.0\n"); return 0; } - void BindSampler( GLuint unit, GLuint sampler ) override + void BindSampler(GLuint unit, GLuint sampler) override { - DALI_LOG_ERROR( "glBindSampler is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBindSampler is not supported in OpenGL es 2.0\n"); } - void SamplerParameteri( GLuint sampler, GLenum pname, GLint param ) override + void SamplerParameteri(GLuint sampler, GLenum pname, GLint param) override { - DALI_LOG_ERROR( "glSamplerParameteri is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glSamplerParameteri is not supported in OpenGL es 2.0\n"); } - void SamplerParameteriv( GLuint sampler, GLenum pname, const GLint* param ) override + void SamplerParameteriv(GLuint sampler, GLenum pname, const GLint* param) override { - DALI_LOG_ERROR( "glSamplerParameteriv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glSamplerParameteriv is not supported in OpenGL es 2.0\n"); } - void SamplerParameterf( GLuint sampler, GLenum pname, GLfloat param ) override + void SamplerParameterf(GLuint sampler, GLenum pname, GLfloat param) override { - DALI_LOG_ERROR( "glSamplerParameterf is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glSamplerParameterf is not supported in OpenGL es 2.0\n"); } - void SamplerParameterfv( GLuint sampler, GLenum pname, const GLfloat* param ) override + void SamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat* param) override { - DALI_LOG_ERROR( "glSamplerParameterfv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glSamplerParameterfv is not supported in OpenGL es 2.0\n"); } - void GetSamplerParameteriv( GLuint sampler, GLenum pname, GLint* params ) override + void GetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params) override { - DALI_LOG_ERROR( "glGetSamplerParameteriv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetSamplerParameteriv is not supported in OpenGL es 2.0\n"); } - void GetSamplerParameterfv( GLuint sampler, GLenum pname, GLfloat* params ) override + void GetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params) override { - DALI_LOG_ERROR( "glGetSamplerParameterfv is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetSamplerParameterfv is not supported in OpenGL es 2.0\n"); } - void VertexAttribDivisor( GLuint index, GLuint divisor ) override + void VertexAttribDivisor(GLuint index, GLuint divisor) override { - DALI_LOG_ERROR( "glVertexAttribDivisor is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glVertexAttribDivisor is not supported in OpenGL es 2.0\n"); } - void BindTransformFeedback( GLenum target, GLuint id ) override + void BindTransformFeedback(GLenum target, GLuint id) override { - DALI_LOG_ERROR( "glBindTransformFeedback is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glBindTransformFeedback is not supported in OpenGL es 2.0\n"); } - void DeleteTransformFeedbacks( GLsizei n, const GLuint* ids ) override + void DeleteTransformFeedbacks(GLsizei n, const GLuint* ids) override { - DALI_LOG_ERROR( "glDeleteTransformFeedbacks is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glDeleteTransformFeedbacks is not supported in OpenGL es 2.0\n"); } - void GenTransformFeedbacks( GLsizei n, GLuint* ids ) override + void GenTransformFeedbacks(GLsizei n, GLuint* ids) override { - DALI_LOG_ERROR( "glGenTransformFeedbacks is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGenTransformFeedbacks is not supported in OpenGL es 2.0\n"); } - GLboolean IsTransformFeedback( GLuint id ) override + GLboolean IsTransformFeedback(GLuint id) override { - DALI_LOG_ERROR( "glIsTransformFeedback is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glIsTransformFeedback is not supported in OpenGL es 2.0\n"); return 0; } - void PauseTransformFeedback( void ) override + void PauseTransformFeedback(void) override { - DALI_LOG_ERROR( "glPauseTransformFeedback is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glPauseTransformFeedback is not supported in OpenGL es 2.0\n"); } - void ResumeTransformFeedback( void ) override + void ResumeTransformFeedback(void) override { - DALI_LOG_ERROR( "glResumeTransformFeedback is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glResumeTransformFeedback is not supported in OpenGL es 2.0\n"); } - void GetProgramBinary( GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary ) override + void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) override { - mGlExtensions.GetProgramBinaryOES( program, bufSize, length, binaryFormat, binary ); + mGlExtensions.GetProgramBinaryOES(program, bufSize, length, binaryFormat, binary); } - void ProgramBinary( GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length ) override + void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) override { - mGlExtensions.ProgramBinaryOES( program, binaryFormat, binary, length ); + mGlExtensions.ProgramBinaryOES(program, binaryFormat, binary, length); } - void ProgramParameteri( GLuint program, GLenum pname, GLint value ) override + void ProgramParameteri(GLuint program, GLenum pname, GLint value) override { - DALI_LOG_ERROR( "glProgramParameteri is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glProgramParameteri is not supported in OpenGL es 2.0\n"); } - void InvalidateFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments ) override + void InvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments) override { - mGlExtensions.DiscardFrameBuffer( target, numAttachments, attachments ); + mGlExtensions.DiscardFrameBuffer(target, numAttachments, attachments); } - void InvalidateSubFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height ) override + void InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height) override { - DALI_LOG_ERROR( "glInvalidateSubFramebuffer is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glInvalidateSubFramebuffer is not supported in OpenGL es 2.0\n"); } - void TexStorage2D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height ) override + void TexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) override { - DALI_LOG_ERROR( "glTexStorage2D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glTexStorage2D is not supported in OpenGL es 2.0\n"); } - void TexStorage3D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth ) override + void TexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) override { - DALI_LOG_ERROR( "glTexStorage3D is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glTexStorage3D is not supported in OpenGL es 2.0\n"); } - void GetInternalformativ( GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params ) override + void GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) override { - DALI_LOG_ERROR( "glGetInternalformativ is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("glGetInternalformativ is not supported in OpenGL es 2.0\n"); } - void BlendBarrier( void ) override + void BlendBarrier(void) override { - DALI_LOG_ERROR( "BlendBarrier is not supported in OpenGL es 2.0\n" ); + DALI_LOG_ERROR("BlendBarrier is not supported in OpenGL es 2.0\n"); } private: diff --git a/dali/internal/graphics/gles/gles3-implementation.h b/dali/internal/graphics/gles/gles3-implementation.h index 173cd6a..dbdeddf 100644 --- a/dali/internal/graphics/gles/gles3-implementation.h +++ b/dali/internal/graphics/gles/gles3-implementation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_GLES3_IMPLEMENTATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ * */ - // EXTERNAL INCLUDES +// EXTERNAL INCLUDES #include #include @@ -27,542 +27,542 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class Gles3Implementation : public GlesAbstraction { - public: - Gles3Implementation() {} + Gles3Implementation() + { + } - ~Gles3Implementation() override {} + ~Gles3Implementation() override + { + } - void ReadBuffer( GLenum mode ) override + void ReadBuffer(GLenum mode) override { - glReadBuffer( mode ); + glReadBuffer(mode); } - void DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices ) override + void DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices) override { - glDrawRangeElements( mode, start, end, count, type, indices ); + glDrawRangeElements(mode, start, end, count, type, indices); } - void TexImage3D( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels ) override + void TexImage3D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels) override { - glTexImage3D( target, level, internalformat, width, height, depth, border, format, type, pixels ); + glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels); } - void TexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels ) override + void TexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels) override { - glTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels ); + glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels); } - void CopyTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height ) override + void CopyTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height) override { - glCopyTexSubImage3D( target, level, xoffset, yoffset, zoffset, x, y, width, height ); + glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height); } - void CompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data ) override + void CompressedTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data) override { - glCompressedTexImage3D( target, level, internalformat, width, height, depth, border, imageSize, data ); + glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data); } - void CompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data ) override + void CompressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data) override { - glCompressedTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data ); + glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data); } - void GenQueries( GLsizei n, GLuint* ids ) override + void GenQueries(GLsizei n, GLuint* ids) override { - glGenQueries( n, ids ); + glGenQueries(n, ids); } - void DeleteQueries( GLsizei n, const GLuint* ids ) override + void DeleteQueries(GLsizei n, const GLuint* ids) override { - glDeleteQueries( n, ids ); + glDeleteQueries(n, ids); } - GLboolean IsQuery( GLuint id ) override + GLboolean IsQuery(GLuint id) override { - return glIsQuery( id ); + return glIsQuery(id); } - void BeginQuery( GLenum target, GLuint id ) override + void BeginQuery(GLenum target, GLuint id) override { - glBeginQuery( target, id ); + glBeginQuery(target, id); } - void EndQuery( GLenum target ) override + void EndQuery(GLenum target) override { - glEndQuery( target ); + glEndQuery(target); } - void GetQueryiv( GLenum target, GLenum pname, GLint* params ) override + void GetQueryiv(GLenum target, GLenum pname, GLint* params) override { - glGetQueryiv( target, pname, params ); + glGetQueryiv(target, pname, params); } - void GetQueryObjectuiv( GLuint id, GLenum pname, GLuint* params ) override + void GetQueryObjectuiv(GLuint id, GLenum pname, GLuint* params) override { - glGetQueryObjectuiv( id, pname, params ); + glGetQueryObjectuiv(id, pname, params); } - GLboolean UnmapBuffer( GLenum target ) override + GLboolean UnmapBuffer(GLenum target) override { - return glUnmapBuffer( target ); + return glUnmapBuffer(target); } - void GetBufferPointerv( GLenum target, GLenum pname, GLvoid** params ) override + void GetBufferPointerv(GLenum target, GLenum pname, GLvoid** params) override { - glGetBufferPointerv( target, pname, params ); + glGetBufferPointerv(target, pname, params); } - void DrawBuffers( GLsizei n, const GLenum* bufs ) override + void DrawBuffers(GLsizei n, const GLenum* bufs) override { - glDrawBuffers( n, bufs ); + glDrawBuffers(n, bufs); } - void UniformMatrix2x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix2x3fv( location, count, transpose, value ); + glUniformMatrix2x3fv(location, count, transpose, value); } - void UniformMatrix3x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix3x2fv( location, count, transpose, value ); + glUniformMatrix3x2fv(location, count, transpose, value); } - void UniformMatrix2x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix2x4fv( location, count, transpose, value ); + glUniformMatrix2x4fv(location, count, transpose, value); } - void UniformMatrix4x2fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix4x2fv( location, count, transpose, value ); + glUniformMatrix4x2fv(location, count, transpose, value); } - void UniformMatrix3x4fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix3x4fv( location, count, transpose, value ); + glUniformMatrix3x4fv(location, count, transpose, value); } - void UniformMatrix4x3fv( GLint location, GLsizei count, GLboolean transpose, const GLfloat* value ) override + void UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) override { - glUniformMatrix4x3fv( location, count, transpose, value ); + glUniformMatrix4x3fv(location, count, transpose, value); } - void BlitFramebuffer( GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter ) override + void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) override { - glBlitFramebuffer( srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter ); + glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } - void RenderbufferStorageMultisample( GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height ) override + void RenderbufferStorageMultisample(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height) override { - glRenderbufferStorageMultisample( target, samples, internalformat, width, height ); + glRenderbufferStorageMultisample(target, samples, internalformat, width, height); } - void FramebufferTextureLayer( GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer ) override + void FramebufferTextureLayer(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer) override { - glFramebufferTextureLayer( target, attachment, texture, level, layer ); + glFramebufferTextureLayer(target, attachment, texture, level, layer); } - GLvoid* MapBufferRange( GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access ) override + GLvoid* MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access) override { - return glMapBufferRange( target, offset, length, access ); + return glMapBufferRange(target, offset, length, access); } - void FlushMappedBufferRange( GLenum target, GLintptr offset, GLsizeiptr length ) override + void FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length) override { - glFlushMappedBufferRange( target, offset, length ); + glFlushMappedBufferRange(target, offset, length); } - void BindVertexArray( GLuint array ) override + void BindVertexArray(GLuint array) override { - glBindVertexArray( array ); + glBindVertexArray(array); } - void DeleteVertexArrays( GLsizei n, const GLuint* arrays ) override + void DeleteVertexArrays(GLsizei n, const GLuint* arrays) override { - glDeleteVertexArrays( n, arrays ); + glDeleteVertexArrays(n, arrays); } - void GenVertexArrays( GLsizei n, GLuint* arrays ) override + void GenVertexArrays(GLsizei n, GLuint* arrays) override { - glGenVertexArrays( n, arrays ); + glGenVertexArrays(n, arrays); } - GLboolean IsVertexArray( GLuint array ) override + GLboolean IsVertexArray(GLuint array) override { - return glIsVertexArray( array ); + return glIsVertexArray(array); } - void GetIntegeri_v( GLenum target, GLuint index, GLint* data ) override + void GetIntegeri_v(GLenum target, GLuint index, GLint* data) override { - glGetIntegeri_v( target, index, data ); + glGetIntegeri_v(target, index, data); } - void BeginTransformFeedback( GLenum primitiveMode ) override + void BeginTransformFeedback(GLenum primitiveMode) override { - glBeginTransformFeedback( primitiveMode ); + glBeginTransformFeedback(primitiveMode); } - void EndTransformFeedback( void ) override + void EndTransformFeedback(void) override { glEndTransformFeedback(); } - void BindBufferRange( GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size ) override + void BindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size) override { - glBindBufferRange( target, index, buffer, offset, size ); + glBindBufferRange(target, index, buffer, offset, size); } - void BindBufferBase( GLenum target, GLuint index, GLuint buffer ) override + void BindBufferBase(GLenum target, GLuint index, GLuint buffer) override { - glBindBufferBase( target, index, buffer ); + glBindBufferBase(target, index, buffer); } - void TransformFeedbackVaryings( GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode ) override + void TransformFeedbackVaryings(GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode) override { - glTransformFeedbackVaryings( program, count, varyings, bufferMode ); + glTransformFeedbackVaryings(program, count, varyings, bufferMode); } - void GetTransformFeedbackVarying( GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name ) override + void GetTransformFeedbackVarying(GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name) override { - glGetTransformFeedbackVarying( program, index, bufSize, length, size, type, name ); + glGetTransformFeedbackVarying(program, index, bufSize, length, size, type, name); } - void VertexAttribIPointer( GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer ) override + void VertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer) override { - glVertexAttribIPointer( index, size, type, stride, pointer ); + glVertexAttribIPointer(index, size, type, stride, pointer); } - void GetVertexAttribIiv( GLuint index, GLenum pname, GLint* params ) override + void GetVertexAttribIiv(GLuint index, GLenum pname, GLint* params) override { - glGetVertexAttribIiv( index, pname, params ); + glGetVertexAttribIiv(index, pname, params); } - void GetVertexAttribIuiv( GLuint index, GLenum pname, GLuint* params ) override + void GetVertexAttribIuiv(GLuint index, GLenum pname, GLuint* params) override { - glGetVertexAttribIuiv( index, pname, params ); + glGetVertexAttribIuiv(index, pname, params); } - void VertexAttribI4i( GLuint index, GLint x, GLint y, GLint z, GLint w ) override + void VertexAttribI4i(GLuint index, GLint x, GLint y, GLint z, GLint w) override { - glVertexAttribI4i( index, x, y, z, w ); + glVertexAttribI4i(index, x, y, z, w); } - void VertexAttribI4ui( GLuint index, GLuint x, GLuint y, GLuint z, GLuint w ) override + void VertexAttribI4ui(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w) override { - glVertexAttribI4ui( index, x, y, z, w ); + glVertexAttribI4ui(index, x, y, z, w); } - void VertexAttribI4iv( GLuint index, const GLint* v ) override + void VertexAttribI4iv(GLuint index, const GLint* v) override { - glVertexAttribI4iv( index, v ); + glVertexAttribI4iv(index, v); } - void VertexAttribI4uiv( GLuint index, const GLuint* v ) override + void VertexAttribI4uiv(GLuint index, const GLuint* v) override { - glVertexAttribI4uiv( index, v ); + glVertexAttribI4uiv(index, v); } - void GetUniformuiv( GLuint program, GLint location, GLuint* params ) override + void GetUniformuiv(GLuint program, GLint location, GLuint* params) override { - glGetUniformuiv( program, location, params ); + glGetUniformuiv(program, location, params); } - GLint GetFragDataLocation( GLuint program, const GLchar *name ) override + GLint GetFragDataLocation(GLuint program, const GLchar* name) override { - return glGetFragDataLocation( program, name ); + return glGetFragDataLocation(program, name); } - void Uniform1ui( GLint location, GLuint v0 ) override + void Uniform1ui(GLint location, GLuint v0) override { - glUniform1ui( location, v0 ); + glUniform1ui(location, v0); } - void Uniform2ui( GLint location, GLuint v0, GLuint v1 ) override + void Uniform2ui(GLint location, GLuint v0, GLuint v1) override { - glUniform2ui( location, v0, v1 ); + glUniform2ui(location, v0, v1); } - void Uniform3ui( GLint location, GLuint v0, GLuint v1, GLuint v2 ) override + void Uniform3ui(GLint location, GLuint v0, GLuint v1, GLuint v2) override { - glUniform3ui( location, v0, v1, v2 ); + glUniform3ui(location, v0, v1, v2); } - void Uniform4ui( GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3 ) override + void Uniform4ui(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3) override { - glUniform4ui( location, v0, v1, v2, v3 ); + glUniform4ui(location, v0, v1, v2, v3); } - void Uniform1uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform1uiv(GLint location, GLsizei count, const GLuint* value) override { - glUniform1uiv( location, count, value ); + glUniform1uiv(location, count, value); } - void Uniform2uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform2uiv(GLint location, GLsizei count, const GLuint* value) override { - glUniform2uiv( location, count, value ); + glUniform2uiv(location, count, value); } - void Uniform3uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform3uiv(GLint location, GLsizei count, const GLuint* value) override { - glUniform3uiv( location, count, value ); + glUniform3uiv(location, count, value); } - void Uniform4uiv( GLint location, GLsizei count, const GLuint* value ) override + void Uniform4uiv(GLint location, GLsizei count, const GLuint* value) override { - glUniform4uiv( location, count, value ); + glUniform4uiv(location, count, value); } - void ClearBufferiv( GLenum buffer, GLint drawbuffer, const GLint* value ) override + void ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint* value) override { - glClearBufferiv( buffer, drawbuffer, value ); + glClearBufferiv(buffer, drawbuffer, value); } - void ClearBufferuiv( GLenum buffer, GLint drawbuffer, const GLuint* value ) override + void ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint* value) override { - glClearBufferuiv( buffer, drawbuffer, value ); + glClearBufferuiv(buffer, drawbuffer, value); } - void ClearBufferfv( GLenum buffer, GLint drawbuffer, const GLfloat* value ) override + void ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat* value) override { - glClearBufferfv( buffer, drawbuffer, value ); + glClearBufferfv(buffer, drawbuffer, value); } - void ClearBufferfi( GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil ) override + void ClearBufferfi(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil) override { - glClearBufferfi( buffer, drawbuffer, depth, stencil ); + glClearBufferfi(buffer, drawbuffer, depth, stencil); } - const GLubyte* GetStringi( GLenum name, GLuint index ) override + const GLubyte* GetStringi(GLenum name, GLuint index) override { - return glGetStringi( name, index ); + return glGetStringi(name, index); } - void CopyBufferSubData( GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size ) override + void CopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size) override { - glCopyBufferSubData( readTarget, writeTarget, readOffset, writeOffset, size ); + glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size); } - void GetUniformIndices( GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices ) override + void GetUniformIndices(GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices) override { - glGetUniformIndices( program, uniformCount, uniformNames, uniformIndices ); + glGetUniformIndices(program, uniformCount, uniformNames, uniformIndices); } - void GetActiveUniformsiv( GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params ) override + void GetActiveUniformsiv(GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params) override { - glGetActiveUniformsiv( program, uniformCount, uniformIndices, pname, params ); + glGetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params); } - GLuint GetUniformBlockIndex( GLuint program, const GLchar* uniformBlockName ) override + GLuint GetUniformBlockIndex(GLuint program, const GLchar* uniformBlockName) override { - return glGetUniformBlockIndex( program, uniformBlockName ); + return glGetUniformBlockIndex(program, uniformBlockName); } - void GetActiveUniformBlockiv( GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params ) override + void GetActiveUniformBlockiv(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params) override { - glGetActiveUniformBlockiv( program, uniformBlockIndex, pname, params ); + glGetActiveUniformBlockiv(program, uniformBlockIndex, pname, params); } - void GetActiveUniformBlockName( GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName ) override + void GetActiveUniformBlockName(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName) override { - glGetActiveUniformBlockName( program, uniformBlockIndex, bufSize, length, uniformBlockName ); + glGetActiveUniformBlockName(program, uniformBlockIndex, bufSize, length, uniformBlockName); } - void UniformBlockBinding( GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding ) override + void UniformBlockBinding(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding) override { - glUniformBlockBinding( program, uniformBlockIndex, uniformBlockBinding ); + glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding); } - void DrawArraysInstanced( GLenum mode, GLint first, GLsizei count, GLsizei instanceCount ) override + void DrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount) override { - glDrawArraysInstanced( mode, first, count, instanceCount ); + glDrawArraysInstanced(mode, first, count, instanceCount); } - void DrawElementsInstanced( GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount ) override + void DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount) override { - glDrawElementsInstanced( mode, count, type, indices, instanceCount ); + glDrawElementsInstanced(mode, count, type, indices, instanceCount); } - GLsync FenceSync( GLenum condition, GLbitfield flags ) override + GLsync FenceSync(GLenum condition, GLbitfield flags) override { - return glFenceSync( condition, flags ); + return glFenceSync(condition, flags); } - GLboolean IsSync( GLsync sync ) override + GLboolean IsSync(GLsync sync) override { - return glIsSync( sync ); + return glIsSync(sync); } - void DeleteSync( GLsync sync ) override + void DeleteSync(GLsync sync) override { - glDeleteSync( sync ); + glDeleteSync(sync); } - GLenum ClientWaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) override + GLenum ClientWaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) override { - return glClientWaitSync( sync, flags, timeout ); + return glClientWaitSync(sync, flags, timeout); } - void WaitSync( GLsync sync, GLbitfield flags, GLuint64 timeout ) override + void WaitSync(GLsync sync, GLbitfield flags, GLuint64 timeout) override { - glWaitSync( sync, flags, timeout ); + glWaitSync(sync, flags, timeout); } - void GetInteger64v( GLenum pname, GLint64* params ) override + void GetInteger64v(GLenum pname, GLint64* params) override { - glGetInteger64v( pname, params ); + glGetInteger64v(pname, params); } - void GetSynciv( GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values ) override + void GetSynciv(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values) override { - glGetSynciv( sync, pname, bufSize, length, values ); + glGetSynciv(sync, pname, bufSize, length, values); } - void GetInteger64i_v( GLenum target, GLuint index, GLint64* data ) override + void GetInteger64i_v(GLenum target, GLuint index, GLint64* data) override { - glGetInteger64i_v( target, index, data ); + glGetInteger64i_v(target, index, data); } - void GetBufferParameteri64v( GLenum target, GLenum pname, GLint64* params ) override + void GetBufferParameteri64v(GLenum target, GLenum pname, GLint64* params) override { - glGetBufferParameteri64v( target, pname, params ); + glGetBufferParameteri64v(target, pname, params); } - void GenSamplers( GLsizei count, GLuint* samplers ) override + void GenSamplers(GLsizei count, GLuint* samplers) override { - glGenSamplers( count, samplers ); + glGenSamplers(count, samplers); } - void DeleteSamplers( GLsizei count, const GLuint* samplers ) override + void DeleteSamplers(GLsizei count, const GLuint* samplers) override { - glDeleteSamplers( count, samplers ); + glDeleteSamplers(count, samplers); } - GLboolean IsSampler( GLuint sampler ) override + GLboolean IsSampler(GLuint sampler) override { - return glIsSampler( sampler ); + return glIsSampler(sampler); } - void BindSampler( GLuint unit, GLuint sampler ) override + void BindSampler(GLuint unit, GLuint sampler) override { - glBindSampler( unit, sampler ); + glBindSampler(unit, sampler); } - void SamplerParameteri( GLuint sampler, GLenum pname, GLint param ) override + void SamplerParameteri(GLuint sampler, GLenum pname, GLint param) override { - glSamplerParameteri( sampler, pname, param ); + glSamplerParameteri(sampler, pname, param); } - void SamplerParameteriv( GLuint sampler, GLenum pname, const GLint* param ) override + void SamplerParameteriv(GLuint sampler, GLenum pname, const GLint* param) override { - glSamplerParameteriv( sampler, pname, param ); + glSamplerParameteriv(sampler, pname, param); } - void SamplerParameterf( GLuint sampler, GLenum pname, GLfloat param ) override + void SamplerParameterf(GLuint sampler, GLenum pname, GLfloat param) override { - glSamplerParameterf( sampler, pname, param ); + glSamplerParameterf(sampler, pname, param); } - void SamplerParameterfv( GLuint sampler, GLenum pname, const GLfloat* param ) override + void SamplerParameterfv(GLuint sampler, GLenum pname, const GLfloat* param) override { - glSamplerParameterfv( sampler, pname, param ); + glSamplerParameterfv(sampler, pname, param); } - void GetSamplerParameteriv( GLuint sampler, GLenum pname, GLint* params ) override + void GetSamplerParameteriv(GLuint sampler, GLenum pname, GLint* params) override { - glGetSamplerParameteriv( sampler, pname, params ); + glGetSamplerParameteriv(sampler, pname, params); } - void GetSamplerParameterfv( GLuint sampler, GLenum pname, GLfloat* params ) override + void GetSamplerParameterfv(GLuint sampler, GLenum pname, GLfloat* params) override { - glGetSamplerParameterfv( sampler, pname, params ); + glGetSamplerParameterfv(sampler, pname, params); } - void VertexAttribDivisor( GLuint index, GLuint divisor ) override + void VertexAttribDivisor(GLuint index, GLuint divisor) override { - glVertexAttribDivisor( index, divisor ); + glVertexAttribDivisor(index, divisor); } - void BindTransformFeedback( GLenum target, GLuint id ) override + void BindTransformFeedback(GLenum target, GLuint id) override { - glBindTransformFeedback( target, id ); + glBindTransformFeedback(target, id); } - void DeleteTransformFeedbacks( GLsizei n, const GLuint* ids ) override + void DeleteTransformFeedbacks(GLsizei n, const GLuint* ids) override { - glDeleteTransformFeedbacks( n, ids ); + glDeleteTransformFeedbacks(n, ids); } - void GenTransformFeedbacks( GLsizei n, GLuint* ids ) override + void GenTransformFeedbacks(GLsizei n, GLuint* ids) override { - glGenTransformFeedbacks( n, ids ); + glGenTransformFeedbacks(n, ids); } - GLboolean IsTransformFeedback( GLuint id ) override + GLboolean IsTransformFeedback(GLuint id) override { - return glIsTransformFeedback( id ); + return glIsTransformFeedback(id); } - void PauseTransformFeedback( void ) override + void PauseTransformFeedback(void) override { glPauseTransformFeedback(); } - void ResumeTransformFeedback( void ) override + void ResumeTransformFeedback(void) override { glResumeTransformFeedback(); } - void GetProgramBinary( GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary ) override + void GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary) override { - glGetProgramBinary( program, bufSize, length, binaryFormat, binary ); + glGetProgramBinary(program, bufSize, length, binaryFormat, binary); } - void ProgramBinary( GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length ) override + void ProgramBinary(GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length) override { - glProgramBinary( program, binaryFormat, binary, length ); + glProgramBinary(program, binaryFormat, binary, length); } - void ProgramParameteri( GLuint program, GLenum pname, GLint value ) override + void ProgramParameteri(GLuint program, GLenum pname, GLint value) override { - glProgramParameteri( program, pname, value ); + glProgramParameteri(program, pname, value); } - void InvalidateFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments ) override + void InvalidateFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments) override { - glInvalidateFramebuffer( target, numAttachments, attachments ); + glInvalidateFramebuffer(target, numAttachments, attachments); } - void InvalidateSubFramebuffer( GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height ) override + void InvalidateSubFramebuffer(GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height) override { - glInvalidateSubFramebuffer( target, numAttachments, attachments, x, y, width, height ); + glInvalidateSubFramebuffer(target, numAttachments, attachments, x, y, width, height); } - void TexStorage2D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height ) override + void TexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height) override { - glTexStorage2D( target, levels, internalformat, width, height ); + glTexStorage2D(target, levels, internalformat, width, height); } - void TexStorage3D( GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth ) override + void TexStorage3D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth) override { - glTexStorage3D( target, levels, internalformat, width, height, depth ); + glTexStorage3D(target, levels, internalformat, width, height, depth); } - void GetInternalformativ( GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params ) override + void GetInternalformativ(GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params) override { - glGetInternalformativ( target, internalformat, pname, bufSize, params ); + glGetInternalformativ(target, internalformat, pname, bufSize, params); } - void BlendBarrier( void ) override + void BlendBarrier(void) override { if(!mGlExtensions.BlendBarrierKHR()) { diff --git a/dali/internal/graphics/macos/egl-image-extensions.cpp b/dali/internal/graphics/macos/egl-image-extensions.cpp index 671c45a..dd6f4bc 100644 --- a/dali/internal/graphics/macos/egl-image-extensions.cpp +++ b/dali/internal/graphics/macos/egl-image-extensions.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include @@ -27,13 +26,12 @@ namespace Dali::Internal::Adaptor { - EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl) : mEglImplementation(eglImpl), mImageKHRInitialized(false), mImageKHRInitializeFailed(false) { - DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" ); + DALI_ASSERT_ALWAYS(eglImpl && "EGL Implementation not instantiated"); } EglImageExtensions::~EglImageExtensions() diff --git a/dali/internal/graphics/tizen/egl-image-extensions-tizen.cpp b/dali/internal/graphics/tizen/egl-image-extensions-tizen.cpp index 4d0bf18..9beaccc 100644 --- a/dali/internal/graphics/tizen/egl-image-extensions-tizen.cpp +++ b/dali/internal/graphics/tizen/egl-image-extensions-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include @@ -39,27 +38,23 @@ namespace { // function pointers assigned in InitializeEglImageKHR -PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0; -PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0; +PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHRProc = 0; +PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHRProc = 0; PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOESProc = 0; } // unnamed namespace - namespace Dali { - namespace Internal { - namespace Adaptor { - EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl) : mEglImplementation(eglImpl), mImageKHRInitialized(false), mImageKHRInitializeFailed(false) { - DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" ); + DALI_ASSERT_ALWAYS(eglImpl && "EGL Implementation not instantiated"); } EglImageExtensions::~EglImageExtensions() @@ -68,65 +63,63 @@ EglImageExtensions::~EglImageExtensions() void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer) { - if (mImageKHRInitialized == false) + if(mImageKHRInitialized == false) { InitializeEglImageKHR(); } - if (mImageKHRInitialized == false) + if(mImageKHRInitialized == false) { return NULL; } // Use the EGL image extension const EGLint attribs[] = - { - EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, - EGL_NONE - }; + { + EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; - EGLImageKHR eglImage = eglCreateImageKHRProc( mEglImplementation->GetDisplay(), - EGL_NO_CONTEXT, - EGL_NATIVE_SURFACE_TIZEN, - clientBuffer, - attribs ); + EGLImageKHR eglImage = eglCreateImageKHRProc(mEglImplementation->GetDisplay(), + EGL_NO_CONTEXT, + EGL_NATIVE_SURFACE_TIZEN, + clientBuffer, + attribs); - if( EGL_NO_IMAGE_KHR == eglImage ) + if(EGL_NO_IMAGE_KHR == eglImage) { - switch( eglGetError() ) + switch(eglGetError()) { - case EGL_SUCCESS : + case EGL_SUCCESS: { break; } case EGL_BAD_DISPLAY: { - DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" ); + DALI_LOG_ERROR("EGL_BAD_DISPLAY: Invalid EGLDisplay object\n"); break; } case EGL_BAD_CONTEXT: { - DALI_LOG_ERROR( "EGL_BAD_CONTEXT: Invalid EGLContext object\n" ); + DALI_LOG_ERROR("EGL_BAD_CONTEXT: Invalid EGLContext object\n"); break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: Invalid target parameter or attribute in attrib_list\n"); break; } case EGL_BAD_MATCH: { - DALI_LOG_ERROR( "EGL_BAD_MATCH: attrib_list does not match target\n" ); + DALI_LOG_ERROR("EGL_BAD_MATCH: attrib_list does not match target\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: Previously bound off-screen, or EGLImage sibling error\n"); break; } case EGL_BAD_ALLOC: { - DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" ); + DALI_LOG_ERROR("EGL_BAD_ALLOC: Insufficient memory is available\n"); break; } default: @@ -135,21 +128,21 @@ void* EglImageExtensions::CreateImageKHR(EGLClientBuffer clientBuffer) } } } - DALI_ASSERT_DEBUG( EGL_NO_IMAGE_KHR != eglImage && "EglImageExtensions::CreateImageKHR: eglCreateImageKHR failed!\n"); + DALI_ASSERT_DEBUG(EGL_NO_IMAGE_KHR != eglImage && "EglImageExtensions::CreateImageKHR: eglCreateImageKHR failed!\n"); return eglImage; } void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) { - DALI_ASSERT_DEBUG( mImageKHRInitialized ); + DALI_ASSERT_DEBUG(mImageKHRInitialized); - if( ! mImageKHRInitialized ) + if(!mImageKHRInitialized) { return; } - if( eglImageKHR == NULL ) + if(eglImageKHR == NULL) { return; } @@ -158,23 +151,23 @@ void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) EGLBoolean result = eglDestroyImageKHRProc(mEglImplementation->GetDisplay(), eglImage); - if( EGL_FALSE == result ) + if(EGL_FALSE == result) { - switch( eglGetError() ) + switch(eglGetError()) { case EGL_BAD_DISPLAY: { - DALI_LOG_ERROR( "EGL_BAD_DISPLAY: Invalid EGLDisplay object\n" ); + DALI_LOG_ERROR("EGL_BAD_DISPLAY: Invalid EGLDisplay object\n"); break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: eglImage is not a valid EGLImageKHR object created with respect to EGLDisplay\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: EGLImage sibling error\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: EGLImage sibling error\n"); break; } default: @@ -187,9 +180,9 @@ void EglImageExtensions::DestroyImageKHR(void* eglImageKHR) void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) { - DALI_ASSERT_DEBUG( mImageKHRInitialized ); + DALI_ASSERT_DEBUG(mImageKHRInitialized); - if( eglImageKHR != NULL ) + if(eglImageKHR != NULL) { EGLImageKHR eglImage = static_cast(eglImageKHR); @@ -197,13 +190,13 @@ void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) GLint glError = glGetError(); #endif - glEGLImageTargetTexture2DOESProc(GL_TEXTURE_EXTERNAL_OES, reinterpret_cast< GLeglImageOES >( eglImage ) ); + glEGLImageTargetTexture2DOESProc(GL_TEXTURE_EXTERNAL_OES, reinterpret_cast(eglImage)); #ifdef EGL_ERROR_CHECKING glError = glGetError(); - if( GL_NO_ERROR != glError ) + if(GL_NO_ERROR != glError) { - DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError ); + DALI_LOG_ERROR(" glEGLImageTargetTexture2DOES returned error %0x04x\n", glError); } #endif } @@ -212,14 +205,14 @@ void EglImageExtensions::TargetTextureKHR(void* eglImageKHR) void EglImageExtensions::InitializeEglImageKHR() { // avoid trying to reload extended KHR functions, if it fails the first time - if( ! mImageKHRInitializeFailed ) + if(!mImageKHRInitializeFailed) { - eglCreateImageKHRProc = reinterpret_cast< PFNEGLCREATEIMAGEKHRPROC >( eglGetProcAddress("eglCreateImageKHR") ); - eglDestroyImageKHRProc = reinterpret_cast< PFNEGLDESTROYIMAGEKHRPROC >( eglGetProcAddress("eglDestroyImageKHR") ); - glEGLImageTargetTexture2DOESProc = reinterpret_cast< PFNGLEGLIMAGETARGETTEXTURE2DOESPROC >( eglGetProcAddress("glEGLImageTargetTexture2DOES") ); + eglCreateImageKHRProc = reinterpret_cast(eglGetProcAddress("eglCreateImageKHR")); + eglDestroyImageKHRProc = reinterpret_cast(eglGetProcAddress("eglDestroyImageKHR")); + glEGLImageTargetTexture2DOESProc = reinterpret_cast(eglGetProcAddress("glEGLImageTargetTexture2DOES")); } - if (eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc) + if(eglCreateImageKHRProc && eglDestroyImageKHRProc && glEGLImageTargetTexture2DOESProc) { mImageKHRInitialized = true; } diff --git a/dali/internal/graphics/windows-gl/egl-image-extensions.cpp b/dali/internal/graphics/windows-gl/egl-image-extensions.cpp old mode 100755 new mode 100644 index 9b4ab64..9ea1d5d --- a/dali/internal/graphics/windows-gl/egl-image-extensions.cpp +++ b/dali/internal/graphics/windows-gl/egl-image-extensions.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include @@ -25,23 +24,18 @@ // INTERNAL INCLUDES #include - - namespace Dali { - namespace Internal { - namespace Adaptor { - EglImageExtensions::EglImageExtensions(EglImplementation* eglImpl) : mEglImplementation(eglImpl), mImageKHRInitialized(false), mImageKHRInitializeFailed(false) { - DALI_ASSERT_ALWAYS( eglImpl && "EGL Implementation not instantiated" ); + DALI_ASSERT_ALWAYS(eglImpl && "EGL Implementation not instantiated"); } EglImageExtensions::~EglImageExtensions() diff --git a/dali/internal/haptics/common/feedback-player-impl.cpp b/dali/internal/haptics/common/feedback-player-impl.cpp index 7468372..c7a74ee 100644 --- a/dali/internal/haptics/common/feedback-player-impl.cpp +++ b/dali/internal/haptics/common/feedback-player-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,36 +19,32 @@ #include // EXTERNAL INCLUDES -#include #include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { - // Type Registration Dali::BaseHandle Create() { return FeedbackPlayer::Get(); } -Dali::TypeRegistration FEEDBACK_PLAYER_TYPE( typeid(Dali::FeedbackPlayer), typeid(Dali::BaseHandle), Create ); +Dali::TypeRegistration FEEDBACK_PLAYER_TYPE(typeid(Dali::FeedbackPlayer), typeid(Dali::BaseHandle), Create); } // unnamed namespace Dali::FeedbackPlayer FeedbackPlayer::New() { - Dali::FeedbackPlayer player = Dali::FeedbackPlayer( new FeedbackPlayer() ); + Dali::FeedbackPlayer player = Dali::FeedbackPlayer(new FeedbackPlayer()); return player; } @@ -56,34 +52,34 @@ Dali::FeedbackPlayer FeedbackPlayer::Get() { Dali::FeedbackPlayer player; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::FeedbackPlayer ) ); - if ( handle ) + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::FeedbackPlayer)); + if(handle) { // If so, downcast the handle - player = Dali::FeedbackPlayer( dynamic_cast< FeedbackPlayer* >( handle.GetObjectPtr() ) ); + player = Dali::FeedbackPlayer(dynamic_cast(handle.GetObjectPtr())); } else { - player = Dali::FeedbackPlayer( New() ); - service.Register( typeid( player ), player ); + player = Dali::FeedbackPlayer(New()); + service.Register(typeid(player), player); } } return player; } -void FeedbackPlayer::PlayMonotone( unsigned int duration ) +void FeedbackPlayer::PlayMonotone(unsigned int duration) { - mPlugin.PlayHapticMonotone( duration ); + mPlugin.PlayHapticMonotone(duration); } -void FeedbackPlayer::PlayFile( const std::string& filePath ) +void FeedbackPlayer::PlayFile(const std::string& filePath) { - mPlugin.PlayHaptic( filePath ); + mPlugin.PlayHaptic(filePath); } void FeedbackPlayer::Stop() @@ -91,17 +87,17 @@ void FeedbackPlayer::Stop() mPlugin.StopHaptic(); } -int FeedbackPlayer::PlaySound( const std::string& filename ) +int FeedbackPlayer::PlaySound(const std::string& filename) { return mPlugin.PlaySound(filename); } -void FeedbackPlayer::StopSound( int handle ) +void FeedbackPlayer::StopSound(int handle) { mPlugin.StopSound(handle); } -void FeedbackPlayer::PlayFeedbackPattern( int type, int pattern ) +void FeedbackPlayer::PlayFeedbackPattern(int type, int pattern) { mPlugin.PlayFeedbackPattern(type, pattern); } @@ -110,11 +106,11 @@ bool FeedbackPlayer::LoadFile(const std::string& filename, std::string& data) { bool loaded = false; - std::streampos bufferSize = 0; + std::streampos bufferSize = 0; Dali::Vector fileBuffer; - if( Dali::FileLoader::ReadFile( filename, bufferSize, fileBuffer, FileLoader::FileType::TEXT ) ) + if(Dali::FileLoader::ReadFile(filename, bufferSize, fileBuffer, FileLoader::FileType::TEXT)) { - data.assign( &fileBuffer[0], bufferSize ); + data.assign(&fileBuffer[0], bufferSize); loaded = true; } @@ -122,7 +118,7 @@ bool FeedbackPlayer::LoadFile(const std::string& filename, std::string& data) } FeedbackPlayer::FeedbackPlayer() -: mPlugin( FeedbackPluginProxy::DEFAULT_OBJECT_NAME ) +: mPlugin(FeedbackPluginProxy::DEFAULT_OBJECT_NAME) { } diff --git a/dali/internal/haptics/common/feedback-player-impl.h b/dali/internal/haptics/common/feedback-player-impl.h index 856f6ef..e1dfa6a 100644 --- a/dali/internal/haptics/common/feedback-player-impl.h +++ b/dali/internal/haptics/common/feedback-player-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_FEEDBACK_PLAYER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -28,13 +28,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class FeedbackPluginProxy; /** @@ -42,9 +39,7 @@ class FeedbackPluginProxy; */ class FeedbackPlayer : public Dali::BaseObject { - public: - /** * Create a FeedbackPlayer. * This should only be called once by the Adaptor class. @@ -66,7 +61,7 @@ public: /** * @copydoc Dali::FeedbackPlayer::PlayFile() */ - void PlayFile( const std::string& filePath ); + void PlayFile(const std::string& filePath); /** * @copydoc Dali::FeedbackPlayer::Stop() @@ -76,17 +71,17 @@ public: /** * @copydoc Dali::FeedbackPlayer::PlaySound() */ - int PlaySound( const std::string& fileName ); + int PlaySound(const std::string& fileName); /** * @copydoc Dali::FeedbackPlayer::StopSound() */ - void StopSound( int handle ); + void StopSound(int handle); /** * @copydoc Dali::FeedbackPlayer::PlayFeedbackPattern() */ - void PlayFeedbackPattern( int type, int pattern ); + void PlayFeedbackPattern(int type, int pattern); /** * @copydoc Dali::FeedbackPlayer::LoadFile() @@ -94,7 +89,6 @@ public: bool LoadFile(const std::string& filename, std::string& data); private: - /** * Private Constructor; see also FeedbackPlayer::New() */ @@ -112,7 +106,6 @@ private: FeedbackPlayer& operator=(FeedbackPlayer&); private: - FeedbackPluginProxy mPlugin; }; @@ -124,7 +117,7 @@ private: inline Internal::Adaptor::FeedbackPlayer& GetImplementation(Dali::FeedbackPlayer& player) { - DALI_ASSERT_ALWAYS( player && "FeedbackPlayer handle is empty" ); + DALI_ASSERT_ALWAYS(player && "FeedbackPlayer handle is empty"); BaseObject& handle = player.GetBaseObject(); @@ -133,7 +126,7 @@ inline Internal::Adaptor::FeedbackPlayer& GetImplementation(Dali::FeedbackPlayer inline const Internal::Adaptor::FeedbackPlayer& GetImplementation(const Dali::FeedbackPlayer& player) { - DALI_ASSERT_ALWAYS( player && "FeedbackPlayer handle is empty" ); + DALI_ASSERT_ALWAYS(player && "FeedbackPlayer handle is empty"); const BaseObject& handle = player.GetBaseObject(); diff --git a/dali/internal/haptics/common/feedback-plugin-proxy.cpp b/dali/internal/haptics/common/feedback-plugin-proxy.cpp index 6829d21..ed59a9d 100644 --- a/dali/internal/haptics/common/feedback-plugin-proxy.cpp +++ b/dali/internal/haptics/common/feedback-plugin-proxy.cpp @@ -19,119 +19,116 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - -const char * const FeedbackPluginProxy::DEFAULT_OBJECT_NAME( "libdali2-feedback-plugin.so" ); - -FeedbackPluginProxy::FeedbackPluginProxy( const std::string& sharedObjectName ) -: mInitializeAttempted( false ), - mLibHandle( NULL ), - mSharedObjectName( sharedObjectName ), - mCreatePluginFunctionPtr( NULL ), - mFeedbackPlugin( NULL ) +const char* const FeedbackPluginProxy::DEFAULT_OBJECT_NAME("libdali2-feedback-plugin.so"); + +FeedbackPluginProxy::FeedbackPluginProxy(const std::string& sharedObjectName) +: mInitializeAttempted(false), + mLibHandle(NULL), + mSharedObjectName(sharedObjectName), + mCreatePluginFunctionPtr(NULL), + mFeedbackPlugin(NULL) { // Lazily initialize when sound/haptic is first played } FeedbackPluginProxy::~FeedbackPluginProxy() { - if( mFeedbackPlugin ) + if(mFeedbackPlugin) { delete mFeedbackPlugin; mFeedbackPlugin = NULL; - if( mLibHandle && dlclose( mLibHandle ) ) + if(mLibHandle && dlclose(mLibHandle)) { - DALI_LOG_ERROR( "Error closing dali feedback plugin library: %s\n", dlerror() ); + DALI_LOG_ERROR("Error closing dali feedback plugin library: %s\n", dlerror()); } } } -void FeedbackPluginProxy::PlayHaptic( const std::string& filePath ) +void FeedbackPluginProxy::PlayHaptic(const std::string& filePath) { // Lazy initialization Initialize(); - if( mFeedbackPlugin ) + if(mFeedbackPlugin) { - mFeedbackPlugin->PlayHaptic( filePath ); + mFeedbackPlugin->PlayHaptic(filePath); } } -void FeedbackPluginProxy::PlayHapticMonotone( unsigned int duration ) +void FeedbackPluginProxy::PlayHapticMonotone(unsigned int duration) { // Lazy initialization Initialize(); - if( mFeedbackPlugin ) + if(mFeedbackPlugin) { - mFeedbackPlugin->PlayHapticMonotone( duration ); + mFeedbackPlugin->PlayHapticMonotone(duration); } } void FeedbackPluginProxy::StopHaptic() { // Must already have been initialized to play haptic - if( mFeedbackPlugin ) + if(mFeedbackPlugin) { mFeedbackPlugin->StopHaptic(); } } -int FeedbackPluginProxy::PlaySound( const std::string& fileName ) +int FeedbackPluginProxy::PlaySound(const std::string& fileName) { // Lazy initialization Initialize(); - if( mFeedbackPlugin ) + if(mFeedbackPlugin) { - return mFeedbackPlugin->PlaySound( fileName ); + return mFeedbackPlugin->PlaySound(fileName); } return 0; } -void FeedbackPluginProxy::StopSound( int handle ) +void FeedbackPluginProxy::StopSound(int handle) { // Must already have been initialized to play sound - if ( mFeedbackPlugin ) + if(mFeedbackPlugin) { - mFeedbackPlugin->StopSound( handle ); + mFeedbackPlugin->StopSound(handle); } } -void FeedbackPluginProxy::PlayFeedbackPattern( int type, int pattern ) +void FeedbackPluginProxy::PlayFeedbackPattern(int type, int pattern) { // Lazy initialization Initialize(); - if( mFeedbackPlugin ) + if(mFeedbackPlugin) { - mFeedbackPlugin->PlayFeedbackPattern( type, pattern ); + mFeedbackPlugin->PlayFeedbackPattern(type, pattern); } } void FeedbackPluginProxy::Initialize() { // Only attempt to load dll once - if ( !mInitializeAttempted ) + if(!mInitializeAttempted) { mInitializeAttempted = true; - mLibHandle = dlopen( mSharedObjectName.c_str(), RTLD_NOW | RTLD_GLOBAL ); - if( !mLibHandle ) + mLibHandle = dlopen(mSharedObjectName.c_str(), RTLD_NOW | RTLD_GLOBAL); + if(!mLibHandle) { - DALI_LOG_ERROR( "Cannot load dali feedback plugin library error: %s\n", dlerror() ); + DALI_LOG_ERROR("Cannot load dali feedback plugin library error: %s\n", dlerror()); return; } diff --git a/dali/internal/haptics/common/feedback-plugin-proxy.h b/dali/internal/haptics/common/feedback-plugin-proxy.h index fb17ad9..4f92a69 100644 --- a/dali/internal/haptics/common/feedback-plugin-proxy.h +++ b/dali/internal/haptics/common/feedback-plugin-proxy.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_FEEDBACK_PLUGIN_PROXY_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,14 +26,11 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -typedef Dali::FeedbackPlugin::SoundStopCallBack SoundStopCallBack; +typedef Dali::FeedbackPlugin::SoundStopCallBack SoundStopCallBack; typedef Dali::FeedbackPlugin::CreateFeedbackPlugin CreateFeedbackPlugin; /** @@ -42,18 +39,16 @@ typedef Dali::FeedbackPlugin::CreateFeedbackPlugin CreateFeedbackPlugin; class FeedbackPluginProxy { public: - /** * The default feedback plugin proxy. */ - static const char * const DEFAULT_OBJECT_NAME; + static const char* const DEFAULT_OBJECT_NAME; public: - /** * Constructor. */ - FeedbackPluginProxy( const std::string& sharedObjectName ); + FeedbackPluginProxy(const std::string& sharedObjectName); /** * The destructor @@ -63,12 +58,12 @@ public: /** * @copydoc Dali::Integration::FeedbackPlugin::PlayHaptic() */ - void PlayHaptic( const std::string& filePath ); + void PlayHaptic(const std::string& filePath); /** * @copydoc Dali::FeedbackPlugin::PlayHapticMonotone() */ - void PlayHapticMonotone( unsigned int duration ); + void PlayHapticMonotone(unsigned int duration); /** * @copydoc Dali::FeedbackPlugin::StopHaptic() @@ -78,30 +73,28 @@ public: /** * @copydoc Dali::FeedbackPlugin::PlaySound() */ - int PlaySound( const std::string& fileName ); + int PlaySound(const std::string& fileName); /** * @copydoc Dali::FeedbackPlugin::StopSound() */ - void StopSound( int handle ); + void StopSound(int handle); /** * @copydoc Dali::FeedbackPlugin::PlayFeedbackPattern() */ - void PlayFeedbackPattern( int type, int pattern ); + void PlayFeedbackPattern(int type, int pattern); private: - /** * Dynamically loads the feedback plugin. */ void Initialize(); private: - - bool mInitializeAttempted; - void* mLibHandle; - std::string mSharedObjectName; + bool mInitializeAttempted; + void* mLibHandle; + std::string mSharedObjectName; CreateFeedbackPlugin* mCreatePluginFunctionPtr; Dali::FeedbackPlugin* mFeedbackPlugin; }; diff --git a/dali/internal/imaging/android/native-image-source-factory-android.cpp b/dali/internal/imaging/android/native-image-source-factory-android.cpp index b37c532..6e3913d 100644 --- a/dali/internal/imaging/android/native-image-source-factory-android.cpp +++ b/dali/internal/imaging/android/native-image-source-factory-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,26 +28,23 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< NativeImageSource > NativeImageSourceFactoryAndroid::CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +std::unique_ptr NativeImageSourceFactoryAndroid::CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - return std::unique_ptr< NativeImageSource >( NativeImageSourceAndroid::New( width, height, depth, nativeImageSource ) ); + return std::unique_ptr(NativeImageSourceAndroid::New(width, height, depth, nativeImageSource)); } -std::unique_ptr< NativeImageSourceQueue > NativeImageSourceFactoryAndroid::CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +std::unique_ptr NativeImageSourceFactoryAndroid::CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - return std::unique_ptr< NativeImageSourceQueue >( NativeImageSourceQueueAndroid::New( width, height, depth, nativeImageSourceQueue ) ); + return std::unique_ptr(NativeImageSourceQueueAndroid::New(width, height, depth, nativeImageSourceQueue)); } // this should be created from somewhere -std::unique_ptr< NativeImageSourceFactory > GetNativeImageSourceFactory() +std::unique_ptr GetNativeImageSourceFactory() { // returns native image source factory - return std::unique_ptr< NativeImageSourceFactoryAndroid >( new NativeImageSourceFactoryAndroid() ); + return std::unique_ptr(new NativeImageSourceFactoryAndroid()); } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/imaging/android/native-image-source-factory-android.h b/dali/internal/imaging/android/native-image-source-factory-android.h index 45bfe6d..a35d7ce 100644 --- a/dali/internal/imaging/android/native-image-source-factory-android.h +++ b/dali/internal/imaging/android/native-image-source-factory-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_ANDROID_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,21 +27,16 @@ namespace Internal { namespace Adaptor { - class NativeImageSourceFactoryAndroid : public NativeImageSourceFactory { public: + std::unique_ptr CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) override; - std::unique_ptr< NativeImageSource > CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) override; - - std::unique_ptr< NativeImageSourceQueue > CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) override; - + std::unique_ptr CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) override; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_ANDROID_H diff --git a/dali/internal/imaging/android/native-image-source-impl-android.cpp b/dali/internal/imaging/android/native-image-source-impl-android.cpp old mode 100755 new mode 100644 index 1052d0b..c3f8493 --- a/dali/internal/imaging/android/native-image-source-impl-android.cpp +++ b/dali/internal/imaging/android/native-image-source-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,40 +25,36 @@ // EXTERNAL INCLUDES #include -#include #include +#include // INTERNAL INCLUDES #include +#include #include #include -#include - namespace { const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n"; -const char* SAMPLER_TYPE = "samplerExternalOES"; -} - +const char* SAMPLER_TYPE = "samplerExternalOES"; +} // namespace namespace Dali { - namespace Internal { - namespace Adaptor { using Dali::Integration::PixelBuffer; -NativeImageSourceAndroid* NativeImageSourceAndroid::New( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +NativeImageSourceAndroid* NativeImageSourceAndroid::New(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - NativeImageSourceAndroid* image = new NativeImageSourceAndroid( width, height, depth, nativeImageSource ); - DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." ); + NativeImageSourceAndroid* image = new NativeImageSourceAndroid(width, height, depth, nativeImageSource); + DALI_ASSERT_DEBUG(image && "NativeImageSource allocation failed."); // 2nd phase construction - if( image ) //< Defensive in case we ever compile without exceptions. + if(image) //< Defensive in case we ever compile without exceptions. { image->Initialize(); } @@ -66,36 +62,36 @@ NativeImageSourceAndroid* NativeImageSourceAndroid::New( uint32_t width, uint32_ return image; } -NativeImageSourceAndroid::NativeImageSourceAndroid( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) -: mWidth( width ), - mHeight( height ), - mOwnPixmap( true ), - mPixmap( NULL ), - mBlendingRequired( false ), - mColorDepth( depth ), - mEglImageKHR( NULL ), - mEglImageExtensions( NULL ) +NativeImageSourceAndroid::NativeImageSourceAndroid(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) +: mWidth(width), + mHeight(height), + mOwnPixmap(true), + mPixmap(NULL), + mBlendingRequired(false), + mColorDepth(depth), + mEglImageKHR(NULL), + mEglImageExtensions(NULL) { - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() ); - auto eglGraphics = static_cast( graphics ); + GraphicsInterface* graphics = &(Adaptor::GetImplementation(Adaptor::Get()).GetGraphicsInterface()); + auto eglGraphics = static_cast(graphics); mEglImageExtensions = eglGraphics->GetImageExtensions(); - DALI_ASSERT_DEBUG( mEglImageExtensions ); + DALI_ASSERT_DEBUG(mEglImageExtensions); // assign the pixmap - mPixmap = static_cast( GetPixmapFromAny( nativeImageSource ) ); - if( !mPixmap ) + mPixmap = static_cast(GetPixmapFromAny(nativeImageSource)); + if(!mPixmap) { AHardwareBuffer_Desc bufferDescription; - memset( &bufferDescription, 0, sizeof( AHardwareBuffer_Desc ) ); - bufferDescription.width = width; + memset(&bufferDescription, 0, sizeof(AHardwareBuffer_Desc)); + bufferDescription.width = width; bufferDescription.height = height; bufferDescription.layers = 1; - bufferDescription.usage = AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE; - switch( mColorDepth ) + bufferDescription.usage = AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN | AHARDWAREBUFFER_USAGE_CPU_READ_RARELY | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE; + switch(mColorDepth) { case Dali::NativeImageSource::COLOR_DEPTH_32: case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: @@ -112,8 +108,8 @@ NativeImageSourceAndroid::NativeImageSourceAndroid( uint32_t width, uint32_t hei break; } - int ret = AHardwareBuffer_allocate( &bufferDescription, &mPixmap ); - if( ret ) + int ret = AHardwareBuffer_allocate(&bufferDescription, &mPixmap); + if(ret) { DALI_LOG_ERROR("Failed to allocate AHardwareBuffer %d", ret); } @@ -124,9 +120,9 @@ NativeImageSourceAndroid::NativeImageSourceAndroid( uint32_t width, uint32_t hei void NativeImageSourceAndroid::Initialize() { - if( mPixmap && !mOwnPixmap ) + if(mPixmap && !mOwnPixmap) { - AHardwareBuffer_acquire( mPixmap ) ; + AHardwareBuffer_acquire(mPixmap); // find out the pixmap width / height and color depth GetPixmapDetails(); @@ -135,27 +131,27 @@ void NativeImageSourceAndroid::Initialize() NativeImageSourceAndroid::~NativeImageSourceAndroid() { - AHardwareBuffer_release( mPixmap ); + AHardwareBuffer_release(mPixmap); mPixmap = NULL; } Any NativeImageSourceAndroid::GetNativeImageSource() const { - return Any( mPixmap ); + return Any(mPixmap); } bool NativeImageSourceAndroid::GetPixels(std::vector& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const { - DALI_ASSERT_DEBUG( sizeof(unsigned) == 4 ); + DALI_ASSERT_DEBUG(sizeof(unsigned) == 4); bool success = false; width = mWidth; height = mHeight; AHardwareBuffer_Desc bufferDescription; - memset( &bufferDescription, 0, sizeof( AHardwareBuffer_Desc ) ); - AHardwareBuffer_describe( mPixmap, &bufferDescription ); - switch( bufferDescription.format ) + memset(&bufferDescription, 0, sizeof(AHardwareBuffer_Desc)); + AHardwareBuffer_describe(mPixmap, &bufferDescription); + switch(bufferDescription.format) { case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: pixelFormat = Pixel::Format::RGBA8888; @@ -176,40 +172,40 @@ bool NativeImageSourceAndroid::GetPixels(std::vector& pixbuf, uns } void* buffer = NULL; - int ret = AHardwareBuffer_lock( mPixmap, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1, NULL, &buffer ); - if( ret != 0 ) + int ret = AHardwareBuffer_lock(mPixmap, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1, NULL, &buffer); + if(ret != 0) { DALI_LOG_ERROR("Failed to AHardwareBuffer_lock %d", ret); return success; } uint32_t pixelBytes = GetBytesPerPixel(pixelFormat); - if ( bufferDescription.stride < (pixelBytes * bufferDescription.width) ) + if(bufferDescription.stride < (pixelBytes * bufferDescription.width)) { //On Android device, bufferDescription.stride doesn't seem to mean (width * pixelbytes) //in an actual case, (AHardwareBuffer_Desc) bufferDescription = (width = 1080, height = 1060, layers = 1, format = 1, usage = 306, stride = 1088, rfu0 = 0, rfu1 = 0) //deal with situation uint32_t dstStride = pixelBytes * bufferDescription.width; uint32_t srcStride = pixelBytes * bufferDescription.stride; - uint32_t size = dstStride * bufferDescription.height; - pixbuf.resize( size ); + uint32_t size = dstStride * bufferDescription.height; + pixbuf.resize(size); //copy each row over const unsigned char* ptrSrc = reinterpret_cast(buffer); - unsigned char* ptrDst = pixbuf.data(); - for (int y=0; y < bufferDescription.height; y++, ptrSrc += srcStride, ptrDst += dstStride ) + unsigned char* ptrDst = pixbuf.data(); + for(int y = 0; y < bufferDescription.height; y++, ptrSrc += srcStride, ptrDst += dstStride) { - memcpy( ptrDst, ptrSrc, dstStride ); + memcpy(ptrDst, ptrSrc, dstStride); } } else { uint32_t size = bufferDescription.stride * bufferDescription.height; - pixbuf.resize( size ); - memcpy( pixbuf.data(), buffer, size ); + pixbuf.resize(size); + memcpy(pixbuf.data(), buffer, size); } - ret = AHardwareBuffer_unlock( mPixmap, NULL ); - if( ret != 0 ) + ret = AHardwareBuffer_unlock(mPixmap, NULL); + if(ret != 0) { DALI_LOG_ERROR("failed to AHardwareBuffer_unlock %d", ret); return success; @@ -219,19 +215,19 @@ bool NativeImageSourceAndroid::GetPixels(std::vector& pixbuf, uns return success; } -void NativeImageSourceAndroid::SetSource( Any source ) +void NativeImageSourceAndroid::SetSource(Any source) { - if( mPixmap ) + if(mPixmap) { mOwnPixmap = false; - AHardwareBuffer_release( mPixmap ); + AHardwareBuffer_release(mPixmap); mPixmap = NULL; } - mPixmap = static_cast( GetPixmapFromAny( source ) ); + mPixmap = static_cast(GetPixmapFromAny(source)); - if( mPixmap ) + if(mPixmap) { // we don't own the pixmap mOwnPixmap = false; @@ -241,7 +237,7 @@ void NativeImageSourceAndroid::SetSource( Any source ) } } -bool NativeImageSourceAndroid::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) +bool NativeImageSourceAndroid::IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) { return true; } @@ -249,57 +245,57 @@ bool NativeImageSourceAndroid::IsColorDepthSupported( Dali::NativeImageSource::C bool NativeImageSourceAndroid::CreateResource() { // if the image existed previously delete it. - if( mEglImageKHR != NULL ) + if(mEglImageKHR != NULL) { DestroyResource(); } - DALI_ASSERT_ALWAYS( mPixmap ); - EGLClientBuffer eglBuffer = eglGetNativeClientBufferANDROID( mPixmap ); - switch( eglGetError() ) + DALI_ASSERT_ALWAYS(mPixmap); + EGLClientBuffer eglBuffer = eglGetNativeClientBufferANDROID(mPixmap); + switch(eglGetError()) { - case EGL_SUCCESS : + case EGL_SUCCESS: { break; } case EGL_BAD_PARAMETER: { - DALI_LOG_ERROR( "EGL_BAD_PARAMETER: bad pixmap parameter\n" ); + DALI_LOG_ERROR("EGL_BAD_PARAMETER: bad pixmap parameter\n"); break; } case EGL_BAD_ACCESS: { - DALI_LOG_ERROR( "EGL_BAD_ACCESS: bad access to pixmap\n" ); + DALI_LOG_ERROR("EGL_BAD_ACCESS: bad access to pixmap\n"); break; } case EGL_BAD_ALLOC: { - DALI_LOG_ERROR( "EGL_BAD_ALLOC: Insufficient memory is available\n" ); + DALI_LOG_ERROR("EGL_BAD_ALLOC: Insufficient memory is available\n"); break; } default: { - DALI_LOG_ERROR( "eglGetNativeClientBufferANDROID error\n" ); + DALI_LOG_ERROR("eglGetNativeClientBufferANDROID error\n"); break; } } - DALI_ASSERT_ALWAYS( eglBuffer ); - mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer ); + DALI_ASSERT_ALWAYS(eglBuffer); + mEglImageKHR = mEglImageExtensions->CreateImageKHR(eglBuffer); return mEglImageKHR != NULL; } void NativeImageSourceAndroid::DestroyResource() { - mEglImageExtensions->DestroyImageKHR( mEglImageKHR ); + mEglImageExtensions->DestroyImageKHR(mEglImageKHR); mEglImageKHR = NULL; } uint32_t NativeImageSourceAndroid::TargetTexture() { - mEglImageExtensions->TargetTextureKHR( mEglImageKHR ); + mEglImageExtensions->TargetTextureKHR(mEglImageKHR); return 0; } @@ -323,15 +319,14 @@ const char* NativeImageSourceAndroid::GetCustomSamplerTypename() const return nullptr; } - void* NativeImageSourceAndroid::GetPixmapFromAny(Any pixmap) const { - if( pixmap.Empty() ) + if(pixmap.Empty()) { return 0; } - return AnyCast( pixmap ); + return AnyCast(pixmap); } void NativeImageSourceAndroid::GetPixmapDetails() @@ -340,40 +335,40 @@ void NativeImageSourceAndroid::GetPixmapDetails() mBlendingRequired = false; AHardwareBuffer_Desc bufferDescription; - memset( &bufferDescription, 0, sizeof( AHardwareBuffer_Desc ) ); - AHardwareBuffer_describe( mPixmap, &bufferDescription ); + memset(&bufferDescription, 0, sizeof(AHardwareBuffer_Desc)); + AHardwareBuffer_describe(mPixmap, &bufferDescription); - mWidth = bufferDescription.width; + mWidth = bufferDescription.width; mHeight = bufferDescription.height; - switch (bufferDescription.format) + switch(bufferDescription.format) { - case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: - mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_32; - break; - case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM: - mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_24; - break; - case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM: - mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_16; - break; - case AHARDWAREBUFFER_FORMAT_BLOB: - default: - mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_8; + case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM: + mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_32; + break; + case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM: + mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_24; + break; + case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM: + mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_16; + break; + case AHARDWAREBUFFER_FORMAT_BLOB: + default: + mColorDepth = Dali::NativeImageSource::COLOR_DEPTH_8; } } -uint8_t* NativeImageSourceAndroid::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) +uint8_t* NativeImageSourceAndroid::AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) { - if( mPixmap ) + if(mPixmap) { AHardwareBuffer_Desc bufferDescription; - memset( &bufferDescription, 0, sizeof( AHardwareBuffer_Desc ) ); - AHardwareBuffer_describe( mPixmap, &bufferDescription ); + memset(&bufferDescription, 0, sizeof(AHardwareBuffer_Desc)); + AHardwareBuffer_describe(mPixmap, &bufferDescription); void* buffer = NULL; - if( AHardwareBuffer_lock( mPixmap, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1, NULL, &buffer ) != 0 ) + if(AHardwareBuffer_lock(mPixmap, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1, NULL, &buffer) != 0) { - DALI_LOG_ERROR( "Failed to AHardwareBuffer_lock\n" ); + DALI_LOG_ERROR("Failed to AHardwareBuffer_lock\n"); return NULL; } @@ -381,20 +376,19 @@ uint8_t* NativeImageSourceAndroid::AcquireBuffer( uint16_t& width, uint16_t& hei width = bufferDescription.width; height = bufferDescription.height; - return static_cast< uint8_t* >( buffer ); + return static_cast(buffer); } return NULL; } - bool NativeImageSourceAndroid::ReleaseBuffer() { - if( mPixmap ) + if(mPixmap) { - if( AHardwareBuffer_unlock( mPixmap, NULL ) != 0 ) + if(AHardwareBuffer_unlock(mPixmap, NULL) != 0) { - DALI_LOG_ERROR( "failed to AHardwareBuffer_unlock\n" ); + DALI_LOG_ERROR("failed to AHardwareBuffer_unlock\n"); return false; } return true; @@ -404,6 +398,6 @@ bool NativeImageSourceAndroid::ReleaseBuffer() } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/android/native-image-source-impl-android.h b/dali/internal/imaging/android/native-image-source-impl-android.h old mode 100755 new mode 100644 index bd3e101..04e44bc --- a/dali/internal/imaging/android/native-image-source-impl-android.h +++ b/dali/internal/imaging/android/native-image-source-impl-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,10 +30,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class EglImageExtensions; @@ -44,7 +42,6 @@ class EglImageExtensions; class NativeImageSourceAndroid : public Internal::Adaptor::NativeImageSource { public: - /** * Create a new NativeImageSource internally. * Depending on hardware the width and height may have to be a power of two. @@ -54,10 +51,10 @@ public: * @param[in] nativeImageSource contains either: Android hardware buffer or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceAndroid* New( uint32_t width, - uint32_t height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + static NativeImageSourceAndroid* New(uint32_t width, + uint32_t height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * @copydoc Dali::NativeImageSource::GetNativeImageSource() */ @@ -66,17 +63,17 @@ public: /** * @copydoc Dali::NativeImageSource::GetPixels() */ - bool GetPixels(std::vector &pixbuf, uint32_t &width, uint32_t &height, Pixel::Format& pixelFormat ) const override; + bool GetPixels(std::vector& pixbuf, uint32_t& width, uint32_t& height, Pixel::Format& pixelFormat) const override; /** * @copydoc Dali::NativeImageSource::SetSource( Any source ) */ - void SetSource( Any source ) override; + void SetSource(Any source) override; /** * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth ) */ - bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override; + bool IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) override; /** * destructor @@ -169,7 +166,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::AcquireBuffer() */ - uint8_t* AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) override; + uint8_t* AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) override; /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::ReleaseBuffer() @@ -177,7 +174,6 @@ public: bool ReleaseBuffer() override; private: - /** * Private constructor; @see NativeImageSource::New() * @param[in] width The width of the image. @@ -185,10 +181,10 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty */ - NativeImageSourceAndroid( uint32_t width, - uint32_t height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + NativeImageSourceAndroid(uint32_t width, + uint32_t height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * 2nd phase construction. @@ -209,15 +205,14 @@ private: void GetPixmapDetails(); private: - - uint32_t mWidth; ///< image width - uint32_t mHeight; ///< image heights - bool mOwnPixmap; ///< Whether we created pixmap or not - AHardwareBuffer* mPixmap; ///< - bool mBlendingRequired; ///< Whether blending is required - Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image - void* mEglImageKHR; ///< From EGL extension - EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions + uint32_t mWidth; ///< image width + uint32_t mHeight; ///< image heights + bool mOwnPixmap; ///< Whether we created pixmap or not + AHardwareBuffer* mPixmap; ///< + bool mBlendingRequired; ///< Whether blending is required + Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image + void* mEglImageKHR; ///< From EGL extension + EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions }; } // namespace Adaptor diff --git a/dali/internal/imaging/android/native-image-source-queue-impl-android.cpp b/dali/internal/imaging/android/native-image-source-queue-impl-android.cpp index db9ba4f..5df59b4 100644 --- a/dali/internal/imaging/android/native-image-source-queue-impl-android.cpp +++ b/dali/internal/imaging/android/native-image-source-queue-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,38 +23,34 @@ #include // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - const char* FRAGMENT_PREFIX = "\n"; -const char* SAMPLER_TYPE = "sampler2D"; +const char* SAMPLER_TYPE = "sampler2D"; -} +} // namespace -NativeImageSourceQueueAndroid* NativeImageSourceQueueAndroid::New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +NativeImageSourceQueueAndroid* NativeImageSourceQueueAndroid::New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - NativeImageSourceQueueAndroid* image = new NativeImageSourceQueueAndroid( width, height, depth, nativeImageSourceQueue ); + NativeImageSourceQueueAndroid* image = new NativeImageSourceQueueAndroid(width, height, depth, nativeImageSourceQueue); return image; } -NativeImageSourceQueueAndroid::NativeImageSourceQueueAndroid( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) -: mWidth( width ), - mHeight( height ) +NativeImageSourceQueueAndroid::NativeImageSourceQueueAndroid(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) +: mWidth(width), + mHeight(height) { - DALI_LOG_ERROR( "NativeImageSourceQueueAndroid::NativeImageSourceQueueAndroid: Not supported\n" ); + DALI_LOG_ERROR("NativeImageSourceQueueAndroid::NativeImageSourceQueueAndroid: Not supported\n"); } NativeImageSourceQueueAndroid::~NativeImageSourceQueueAndroid() @@ -66,9 +62,9 @@ Any NativeImageSourceQueueAndroid::GetNativeImageSourceQueue() const return Any(); } -void NativeImageSourceQueueAndroid::SetSize( uint32_t width, uint32_t height ) +void NativeImageSourceQueueAndroid::SetSize(uint32_t width, uint32_t height) { - mWidth = width; + mWidth = width; mHeight = height; } @@ -121,6 +117,6 @@ bool NativeImageSourceQueueAndroid::SourceChanged() const } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/android/native-image-source-queue-impl-android.h b/dali/internal/imaging/android/native-image-source-queue-impl-android.h index d0570d1..92766b9 100644 --- a/dali/internal/imaging/android/native-image-source-queue-impl-android.h +++ b/dali/internal/imaging/android/native-image-source-queue-impl-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_QUEUE_IMPL_ANDROID_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,23 +25,19 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class EglGraphics; class EglImageExtensions; /** * Dali internal NativeImageSourceQueue. */ -class NativeImageSourceQueueAndroid: public Internal::Adaptor::NativeImageSourceQueue +class NativeImageSourceQueueAndroid : public Internal::Adaptor::NativeImageSourceQueue { public: - /** * Create a new NativeImageSourceQueueAndroid internally. * Depending on hardware the width and height may have to be a power of two. @@ -51,7 +47,7 @@ public: * @param[in] nativeImageSourceQueue contains tbm_surface_queue_h or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceQueueAndroid* New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + static NativeImageSourceQueueAndroid* New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); /** * @copydoc Dali::NativeImageSourceQueue::GetNativeImageSourceQueue() @@ -61,7 +57,7 @@ public: /** * @copydoc Dali::NativeImageSourceQueue::SetSize */ - void SetSize( uint32_t width, uint32_t height ) override; + void SetSize(uint32_t width, uint32_t height) override; /** * @copydoc Dali::NativeImageSourceQueue::IgnoreSourceImage @@ -151,7 +147,6 @@ public: bool SourceChanged() const override; private: - /** * Private constructor; @see NativeImageSourceQueue::New() * @param[in] width The width of the image. @@ -159,13 +154,11 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSourceQueue contains tbm_surface_queue_h or is empty */ - NativeImageSourceQueueAndroid( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + NativeImageSourceQueueAndroid(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); private: - - uint32_t mWidth; ///< image width - uint32_t mHeight; ///< image height - + uint32_t mWidth; ///< image width + uint32_t mHeight; ///< image height }; } // namespace Adaptor diff --git a/dali/internal/imaging/common/alpha-mask.cpp b/dali/internal/imaging/common/alpha-mask.cpp index e2e0b25..d7f7016 100644 --- a/dali/internal/imaging/common/alpha-mask.cpp +++ b/dali/internal/imaging/common/alpha-mask.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,11 +14,11 @@ * limitations under the License. */ -#include #include +#include #include +#include #include // For ImageDimensions -#include namespace Dali { @@ -26,142 +26,140 @@ namespace Internal { namespace Adaptor { - -void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask ) +void ApplyMaskToAlphaChannel(PixelBuffer& buffer, const PixelBuffer& mask) { - int srcAlphaByteOffset=0; - int srcAlphaMask=0; - Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat(); + int srcAlphaByteOffset = 0; + int srcAlphaMask = 0; + Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat(); - if( Pixel::HasAlpha(srcPixelFormat) ) + if(Pixel::HasAlpha(srcPixelFormat)) { - Dali::Pixel::GetAlphaOffsetAndMask( srcPixelFormat, srcAlphaByteOffset, srcAlphaMask ); + Dali::Pixel::GetAlphaOffsetAndMask(srcPixelFormat, srcAlphaByteOffset, srcAlphaMask); } - else if( srcPixelFormat == Pixel::L8 ) + else if(srcPixelFormat == Pixel::L8) { - srcAlphaMask=0xFF; + srcAlphaMask = 0xFF; } - int destAlphaByteOffset=0; - int destAlphaMask=0; - Dali::Pixel::Format destPixelFormat = buffer.GetPixelFormat(); - Dali::Pixel::GetAlphaOffsetAndMask( destPixelFormat, destAlphaByteOffset, destAlphaMask ); + int destAlphaByteOffset = 0; + int destAlphaMask = 0; + Dali::Pixel::Format destPixelFormat = buffer.GetPixelFormat(); + Dali::Pixel::GetAlphaOffsetAndMask(destPixelFormat, destAlphaByteOffset, destAlphaMask); - unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcPixelFormat ); - unsigned char* srcBuffer = mask.GetBuffer(); - unsigned char* destBuffer = buffer.GetBuffer(); + unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel(srcPixelFormat); + unsigned char* srcBuffer = mask.GetBuffer(); + unsigned char* destBuffer = buffer.GetBuffer(); - unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel( buffer.GetPixelFormat() ); + unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel(buffer.GetPixelFormat()); - int srcOffset=0; - int destOffset=0; + int srcOffset = 0; + int destOffset = 0; float srcAlphaValue = 1.0f; // if image is premultiplied, the other channels of the image need to multiply by alpha. - if( buffer.IsAlphaPreMultiplied() ) + if(buffer.IsAlphaPreMultiplied()) { - for( unsigned int row = 0; row < buffer.GetHeight(); ++row ) + for(unsigned int row = 0; row < buffer.GetHeight(); ++row) { - for( unsigned int col = 0; col < buffer.GetWidth(); ++col ) + for(unsigned int col = 0; col < buffer.GetWidth(); ++col) { - auto srcAlpha = ReadChannel( srcBuffer + srcOffset, srcPixelFormat, Adaptor::ALPHA); - auto destRed = ReadChannel( destBuffer + destOffset, destPixelFormat, Adaptor::RED); - auto destGreen = ReadChannel( destBuffer + destOffset, destPixelFormat, Adaptor::GREEN); - auto destBlue = ReadChannel( destBuffer + destOffset, destPixelFormat, Adaptor::BLUE); - auto destLuminance = ReadChannel( destBuffer + destOffset, destPixelFormat, Adaptor::LUMINANCE); - auto destAlpha = ReadChannel( destBuffer + destOffset, destPixelFormat, Adaptor::ALPHA); - - WriteChannel( destBuffer + destOffset, destPixelFormat, Adaptor::RED, destRed*srcAlpha / 255 ); - WriteChannel( destBuffer + destOffset, destPixelFormat, Adaptor::GREEN, destGreen*srcAlpha/255 ); - WriteChannel( destBuffer + destOffset, destPixelFormat, Adaptor::BLUE, destBlue*srcAlpha/255 ); - WriteChannel( destBuffer + destOffset, destPixelFormat, Adaptor::LUMINANCE, destLuminance*srcAlpha/255 ); - WriteChannel( destBuffer + destOffset, destPixelFormat, Adaptor::ALPHA, destAlpha*srcAlpha/255 ); - - srcOffset += srcBytesPerPixel; + auto srcAlpha = ReadChannel(srcBuffer + srcOffset, srcPixelFormat, Adaptor::ALPHA); + auto destRed = ReadChannel(destBuffer + destOffset, destPixelFormat, Adaptor::RED); + auto destGreen = ReadChannel(destBuffer + destOffset, destPixelFormat, Adaptor::GREEN); + auto destBlue = ReadChannel(destBuffer + destOffset, destPixelFormat, Adaptor::BLUE); + auto destLuminance = ReadChannel(destBuffer + destOffset, destPixelFormat, Adaptor::LUMINANCE); + auto destAlpha = ReadChannel(destBuffer + destOffset, destPixelFormat, Adaptor::ALPHA); + + WriteChannel(destBuffer + destOffset, destPixelFormat, Adaptor::RED, destRed * srcAlpha / 255); + WriteChannel(destBuffer + destOffset, destPixelFormat, Adaptor::GREEN, destGreen * srcAlpha / 255); + WriteChannel(destBuffer + destOffset, destPixelFormat, Adaptor::BLUE, destBlue * srcAlpha / 255); + WriteChannel(destBuffer + destOffset, destPixelFormat, Adaptor::LUMINANCE, destLuminance * srcAlpha / 255); + WriteChannel(destBuffer + destOffset, destPixelFormat, Adaptor::ALPHA, destAlpha * srcAlpha / 255); + + srcOffset += srcBytesPerPixel; destOffset += destBytesPerPixel; } } } else { - for( unsigned int row = 0; row < buffer.GetHeight(); ++row ) + for(unsigned int row = 0; row < buffer.GetHeight(); ++row) { - for( unsigned int col = 0; col < buffer.GetWidth(); ++col ) + for(unsigned int col = 0; col < buffer.GetWidth(); ++col) { unsigned char alpha = srcBuffer[srcOffset + srcAlphaByteOffset] & srcAlphaMask; - srcAlphaValue = float(alpha)/255.0f; + srcAlphaValue = float(alpha) / 255.0f; - unsigned char destAlpha = destBuffer[destOffset + destAlphaByteOffset] & destAlphaMask; - float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f); - destAlpha = destAlphaValue; + unsigned char destAlpha = destBuffer[destOffset + destAlphaByteOffset] & destAlphaMask; + float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f); + destAlpha = destAlphaValue; destBuffer[destOffset + destAlphaByteOffset] &= ~destAlphaMask; - destBuffer[destOffset + destAlphaByteOffset] |= ( destAlpha & destAlphaMask ); + destBuffer[destOffset + destAlphaByteOffset] |= (destAlpha & destAlphaMask); - srcOffset += srcBytesPerPixel; + srcOffset += srcBytesPerPixel; destOffset += destBytesPerPixel; } } } } -PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuffer& mask ) +PixelBufferPtr CreateNewMaskedBuffer(const PixelBuffer& buffer, const PixelBuffer& mask) { // Set up source alpha offsets - int srcAlphaByteOffset=0; - int srcAlphaMask=0; - Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat(); + int srcAlphaByteOffset = 0; + int srcAlphaMask = 0; + Dali::Pixel::Format srcPixelFormat = mask.GetPixelFormat(); - if( Pixel::HasAlpha(srcPixelFormat) ) + if(Pixel::HasAlpha(srcPixelFormat)) { - Dali::Pixel::GetAlphaOffsetAndMask( srcPixelFormat, srcAlphaByteOffset, srcAlphaMask ); + Dali::Pixel::GetAlphaOffsetAndMask(srcPixelFormat, srcAlphaByteOffset, srcAlphaMask); } - else if( srcPixelFormat == Pixel::L8 ) + else if(srcPixelFormat == Pixel::L8) { - srcAlphaMask=0xFF; + srcAlphaMask = 0xFF; } - unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcPixelFormat ); - unsigned char* srcBuffer = mask.GetBuffer(); + unsigned int srcBytesPerPixel = Dali::Pixel::GetBytesPerPixel(srcPixelFormat); + unsigned char* srcBuffer = mask.GetBuffer(); // Set up source color offsets - Dali::Pixel::Format srcColorPixelFormat = buffer.GetPixelFormat(); - unsigned int srcColorBytesPerPixel = Dali::Pixel::GetBytesPerPixel( srcColorPixelFormat ); + Dali::Pixel::Format srcColorPixelFormat = buffer.GetPixelFormat(); + unsigned int srcColorBytesPerPixel = Dali::Pixel::GetBytesPerPixel(srcColorPixelFormat); // Setup destination offsets - Dali::Pixel::Format destPixelFormat = Dali::Pixel::RGBA8888; - unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel( destPixelFormat ); - int destAlphaByteOffset=0; - int destAlphaMask=0; - Dali::Pixel::GetAlphaOffsetAndMask( destPixelFormat, destAlphaByteOffset, destAlphaMask ); - - PixelBufferPtr newPixelBuffer = PixelBuffer::New( buffer.GetWidth(), buffer.GetHeight(), - destPixelFormat ); - unsigned char* destBuffer = newPixelBuffer->GetBuffer(); - unsigned char* oldBuffer = buffer.GetBuffer(); - - int srcAlphaOffset=0; - int srcColorOffset=0; - int destOffset=0; - bool hasAlpha = Dali::Pixel::HasAlpha(buffer.GetPixelFormat()); + Dali::Pixel::Format destPixelFormat = Dali::Pixel::RGBA8888; + unsigned int destBytesPerPixel = Dali::Pixel::GetBytesPerPixel(destPixelFormat); + int destAlphaByteOffset = 0; + int destAlphaMask = 0; + Dali::Pixel::GetAlphaOffsetAndMask(destPixelFormat, destAlphaByteOffset, destAlphaMask); - float srcAlphaValue = 1.0f; - unsigned char destAlpha = 0; + PixelBufferPtr newPixelBuffer = PixelBuffer::New(buffer.GetWidth(), buffer.GetHeight(), destPixelFormat); + unsigned char* destBuffer = newPixelBuffer->GetBuffer(); + unsigned char* oldBuffer = buffer.GetBuffer(); + + int srcAlphaOffset = 0; + int srcColorOffset = 0; + int destOffset = 0; + bool hasAlpha = Dali::Pixel::HasAlpha(buffer.GetPixelFormat()); + + float srcAlphaValue = 1.0f; + unsigned char destAlpha = 0; - for( unsigned int row = 0; row < buffer.GetHeight(); ++row ) + for(unsigned int row = 0; row < buffer.GetHeight(); ++row) { - for( unsigned int col = 0; col < buffer.GetWidth(); ++col ) + for(unsigned int col = 0; col < buffer.GetWidth(); ++col) { unsigned char alpha = srcBuffer[srcAlphaOffset + srcAlphaByteOffset] & srcAlphaMask; - srcAlphaValue = float(alpha)/255.0f; + srcAlphaValue = float(alpha) / 255.0f; - ConvertColorChannelsToRGBA8888(oldBuffer, srcColorOffset, srcColorPixelFormat, destBuffer, destOffset ); + ConvertColorChannelsToRGBA8888(oldBuffer, srcColorOffset, srcColorPixelFormat, destBuffer, destOffset); - if( hasAlpha ) + if(hasAlpha) { - destAlpha = ConvertAlphaChannelToA8( oldBuffer, srcColorOffset, srcColorPixelFormat ); + destAlpha = ConvertAlphaChannelToA8(oldBuffer, srcColorOffset, srcColorPixelFormat); float destAlphaValue = Clamp(float(destAlpha) * srcAlphaValue, 0.0f, 255.0f); - destAlpha = destAlphaValue; + destAlpha = destAlphaValue; } else { @@ -169,7 +167,7 @@ PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuff } destBuffer[destOffset + destAlphaByteOffset] &= ~destAlphaMask; - destBuffer[destOffset + destAlphaByteOffset] |= ( destAlpha & destAlphaMask ); + destBuffer[destOffset + destAlphaByteOffset] |= (destAlpha & destAlphaMask); srcColorOffset += srcColorBytesPerPixel; srcAlphaOffset += srcBytesPerPixel; @@ -182,6 +180,6 @@ PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuff } //namespace Adaptor -}// namespace Internal +} // namespace Internal -}// namespace Dali +} // namespace Dali diff --git a/dali/internal/imaging/common/alpha-mask.h b/dali/internal/imaging/common/alpha-mask.h index 4d01466..44f8c03 100644 --- a/dali/internal/imaging/common/alpha-mask.h +++ b/dali/internal/imaging/common/alpha-mask.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_ALPHA_MASK_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,12 @@ namespace Internal { namespace Adaptor { - /** * Apply the mask to a buffer's alpha channel * @param[in] buffer The buffer to apply the mask to * @param[in] mask The mask to apply */ -void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask ); +void ApplyMaskToAlphaChannel(PixelBuffer& buffer, const PixelBuffer& mask); /** * Create a new PixelBuffer with an alpha channel large enough to handle the alpha from @@ -42,7 +41,7 @@ void ApplyMaskToAlphaChannel( PixelBuffer& buffer, const PixelBuffer& mask ); * @param[in] mask The mask to apply * @return A new pixel buffer containing the masked image */ -PixelBufferPtr CreateNewMaskedBuffer( const PixelBuffer& buffer, const PixelBuffer& mask ); +PixelBufferPtr CreateNewMaskedBuffer(const PixelBuffer& buffer, const PixelBuffer& mask); } //namespace Adaptor } //namespace Internal diff --git a/dali/internal/imaging/common/animated-image-loading-impl.h b/dali/internal/imaging/common/animated-image-loading-impl.h index 5d5d8af..13be270 100644 --- a/dali/internal/imaging/common/animated-image-loading-impl.h +++ b/dali/internal/imaging/common/animated-image-loading-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ANIMATED_IMAGE_LOADING_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,14 +19,14 @@ */ // EXTERNAL INCLUDES #include +#include #include #include -#include #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -35,10 +35,8 @@ typedef Dali::Uint16Pair ImageDimensions; namespace Internal { - namespace Adaptor { - class AnimatedImageLoading; typedef IntrusivePtr AnimatedImageLoadingPtr; @@ -49,19 +47,18 @@ typedef IntrusivePtr AnimatedImageLoadingPtr; class AnimatedImageLoading : public BaseObject { public: - /** * @copydoc Dali::AnimatedImageLoading::New() */ - static AnimatedImageLoadingPtr New( const std::string& url, bool isLocalResource ); + static AnimatedImageLoadingPtr New(const std::string& url, bool isLocalResource); AnimatedImageLoading() = default; // Moveable but not copyable - AnimatedImageLoading( const AnimatedImageLoading& ); - AnimatedImageLoading& operator=( const AnimatedImageLoading& ); - AnimatedImageLoading( AnimatedImageLoading&& ) = default; - AnimatedImageLoading& operator=( AnimatedImageLoading&& ) = default; + AnimatedImageLoading(const AnimatedImageLoading&); + AnimatedImageLoading& operator =(const AnimatedImageLoading&); + AnimatedImageLoading(AnimatedImageLoading&&) = default; + AnimatedImageLoading& operator=(AnimatedImageLoading&&) = default; /** * @brief Destructor @@ -71,12 +68,12 @@ public: /** * @copydoc Dali::AnimatedImageLoading::LoadNextNFrames() */ - virtual bool LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector& pixelData ) = 0; + virtual bool LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector& pixelData) = 0; /** * @copydoc Dali::AnimatedImageLoading::LoadFrame() */ - virtual Dali::Devel::PixelBuffer LoadFrame( uint32_t frameIndex ) = 0; + virtual Dali::Devel::PixelBuffer LoadFrame(uint32_t frameIndex) = 0; /** * @copydoc Dali::AnimatedImageLoading::GetImageSize() @@ -91,7 +88,7 @@ public: /** * @copydoc Dali::AnimatedImageLoading::LoadFrameDelays() */ - virtual uint32_t GetFrameInterval( uint32_t frameIndex ) const = 0; + virtual uint32_t GetFrameInterval(uint32_t frameIndex) const = 0; /** * @copydoc Dali::AnimatedImageLoading::GetUrl() @@ -105,22 +102,22 @@ public: // Helpers for api forwarding methods -inline Internal::Adaptor::AnimatedImageLoading& GetImplementation( Dali::AnimatedImageLoading& handle) +inline Internal::Adaptor::AnimatedImageLoading& GetImplementation(Dali::AnimatedImageLoading& handle) { - DALI_ASSERT_ALWAYS( handle && "AnimatedImageLoading handle is empty" ); + DALI_ASSERT_ALWAYS(handle && "AnimatedImageLoading handle is empty"); BaseObject& object = handle.GetBaseObject(); - return static_cast< Internal::Adaptor::AnimatedImageLoading& >( object ); + return static_cast(object); } -inline const Internal::Adaptor::AnimatedImageLoading& GetImplementation( const Dali::AnimatedImageLoading& handle ) +inline const Internal::Adaptor::AnimatedImageLoading& GetImplementation(const Dali::AnimatedImageLoading& handle) { - DALI_ASSERT_ALWAYS( handle && "AnimatedImageLoading handle is empty" ); + DALI_ASSERT_ALWAYS(handle && "AnimatedImageLoading handle is empty"); const BaseObject& object = handle.GetBaseObject(); - return static_cast< const Internal::Adaptor::AnimatedImageLoading& >( object ); + return static_cast(object); } } // namespace Dali diff --git a/dali/internal/imaging/common/file-download.cpp b/dali/internal/imaging/common/file-download.cpp old mode 100755 new mode 100644 index 534eb75..cee5ba2 --- a/dali/internal/imaging/common/file-download.cpp +++ b/dali/internal/imaging/common/file-download.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ #include // EXTERNAL INCLUDES +#include #include #include -#include -#include #include +#include // INTERNAL INCLUDES #include @@ -32,21 +32,18 @@ using namespace Dali::Integration; namespace Dali { - namespace TizenPlatform { - namespace // unnamed namespace { - -const int CONNECTION_TIMEOUT_SECONDS( 30L ); -const int TIMEOUT_SECONDS( 120L ); -const long VERBOSE_MODE = 0L; // 0 == off, 1 == on -const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on -const long EXCLUDE_HEADER = 0L; -const long INCLUDE_HEADER = 1L; -const long INCLUDE_BODY = 0L; -const long EXCLUDE_BODY = 1L; +const int CONNECTION_TIMEOUT_SECONDS(30L); +const int TIMEOUT_SECONDS(120L); +const long VERBOSE_MODE = 0L; // 0 == off, 1 == on +const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on +const long EXCLUDE_HEADER = 0L; +const long INCLUDE_HEADER = 1L; +const long INCLUDE_BODY = 0L; +const long EXCLUDE_BODY = 1L; /** * Curl library environment. Direct initialize ensures it's constructed before adaptor @@ -54,187 +51,182 @@ const long EXCLUDE_BODY = 1L; */ static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment; -void ConfigureCurlOptions( CURL* curlHandle, const std::string& url ) +void ConfigureCurlOptions(CURL* curlHandle, const std::string& url) { - curl_easy_setopt( curlHandle, CURLOPT_URL, url.c_str() ); - curl_easy_setopt( curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE ); + curl_easy_setopt(curlHandle, CURLOPT_URL, url.c_str()); + curl_easy_setopt(curlHandle, CURLOPT_VERBOSE, VERBOSE_MODE); // CURLOPT_FAILONERROR is not fail-safe especially when authentication is involved ( see manual ) // Removed CURLOPT_FAILONERROR option - curl_easy_setopt( curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS ); - curl_easy_setopt( curlHandle, CURLOPT_TIMEOUT, TIMEOUT_SECONDS ); - curl_easy_setopt( curlHandle, CURLOPT_HEADER, INCLUDE_HEADER ); - curl_easy_setopt( curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY ); - curl_easy_setopt( curlHandle, CURLOPT_FOLLOWLOCATION, 1L ); - curl_easy_setopt( curlHandle, CURLOPT_MAXREDIRS, 5L ); + curl_easy_setopt(curlHandle, CURLOPT_CONNECTTIMEOUT, CONNECTION_TIMEOUT_SECONDS); + curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT, TIMEOUT_SECONDS); + curl_easy_setopt(curlHandle, CURLOPT_HEADER, INCLUDE_HEADER); + curl_easy_setopt(curlHandle, CURLOPT_NOBODY, EXCLUDE_BODY); + curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curlHandle, CURLOPT_MAXREDIRS, 5L); // If the proxy variable is set, ensure it's also used. // In theory, this variable should be used by the curl library; however, something // is overriding it. char* proxy = std::getenv("http_proxy"); - if( proxy != nullptr ) + if(proxy != nullptr) { - curl_easy_setopt( curlHandle, CURLOPT_PROXY, proxy); + curl_easy_setopt(curlHandle, CURLOPT_PROXY, proxy); } - } // Without a write function or a buffer (file descriptor) to write to, curl will pump out // header/body contents to stdout -size_t DummyWrite(char *ptr, size_t size, size_t nmemb, void *userdata) +size_t DummyWrite(char* ptr, size_t size, size_t nmemb, void* userdata) { return size * nmemb; } struct ChunkData { - std::vector< uint8_t > data; + std::vector data; }; -size_t ChunkLoader(char *ptr, size_t size, size_t nmemb, void *userdata) +size_t ChunkLoader(char* ptr, size_t size, size_t nmemb, void* userdata) { - std::vector* chunks = static_cast*>( userdata ); - int numBytes = size*nmemb; - chunks->push_back( ChunkData() ); - ChunkData& chunkData = (*chunks)[chunks->size()-1]; - chunkData.data.reserve( numBytes ); - memcpy( &chunkData.data[0], ptr, numBytes ); + std::vector* chunks = static_cast*>(userdata); + int numBytes = size * nmemb; + chunks->push_back(ChunkData()); + ChunkData& chunkData = (*chunks)[chunks->size() - 1]; + chunkData.data.reserve(numBytes); + memcpy(&chunkData.data[0], ptr, numBytes); return numBytes; } - -CURLcode DownloadFileDataWithSize( CURL* curlHandle, Dali::Vector& dataBuffer, size_t dataSize ) +CURLcode DownloadFileDataWithSize(CURL* curlHandle, Dali::Vector& dataBuffer, size_t dataSize) { - CURLcode result( CURLE_OK ); + CURLcode result(CURLE_OK); // create - Dali::Internal::Platform::FileWriter fileWriter( dataBuffer, dataSize ); - FILE* dataBufferFilePointer = fileWriter.GetFile(); - if( NULL != dataBufferFilePointer ) + Dali::Internal::Platform::FileWriter fileWriter(dataBuffer, dataSize); + FILE* dataBufferFilePointer = fileWriter.GetFile(); + if(NULL != dataBufferFilePointer) { // we only want the body which contains the file data - curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER ); - curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY ); + curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER); + curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY); // disable the write callback, and get curl to write directly into our data buffer - curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, NULL ); - curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer ); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, NULL); + curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer); // synchronous request of the body data - result = curl_easy_perform( curlHandle ); + result = curl_easy_perform(curlHandle); } return result; } -CURLcode DownloadFileDataByChunk( CURL* curlHandle, Dali::Vector& dataBuffer, size_t& dataSize ) +CURLcode DownloadFileDataByChunk(CURL* curlHandle, Dali::Vector& dataBuffer, size_t& dataSize) { // create - std::vector< ChunkData > chunks; + std::vector chunks; // we only want the body which contains the file data - curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER ); - curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY ); + curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER); + curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY); // Enable the write callback. - curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader ); - curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, &chunks ); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader); + curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &chunks); // synchronous request of the body data - CURLcode result = curl_easy_perform( curlHandle ); + CURLcode result = curl_easy_perform(curlHandle); // chunks should now contain all of the chunked data. Reassemble into a single vector dataSize = 0; - for( size_t i=0; i& dataBuffer, - size_t& dataSize, - size_t maximumAllowedSizeBytes, - char* errorBuffer) +bool DownloadFile(CURL* curlHandle, + const std::string& url, + Dali::Vector& dataBuffer, + size_t& dataSize, + size_t maximumAllowedSizeBytes, + char* errorBuffer) { - CURLcode result( CURLE_OK ); - double size(0); + CURLcode result(CURLE_OK); + double size(0); // setup curl to download just the header so we can extract the content length - ConfigureCurlOptions( curlHandle, url ); - curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite); + ConfigureCurlOptions(curlHandle, url); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite); if(errorBuffer != nullptr) { - errorBuffer[0]=0; + errorBuffer[0] = 0; } // perform the request to get the header - result = curl_easy_perform( curlHandle ); + result = curl_easy_perform(curlHandle); - if( result != CURLE_OK) + if(result != CURLE_OK) { if(errorBuffer != nullptr) { - DALI_LOG_ERROR( "Failed to download http header for \"%s\" with error code %d (%s)\n", url.c_str(), result, &errorBuffer[0] ); + DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d (%s)\n", url.c_str(), result, &errorBuffer[0]); } else { - DALI_LOG_ERROR( "Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result); + DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result); } return false; } // get the content length, -1 == size is not known - curl_easy_getinfo( curlHandle,CURLINFO_CONTENT_LENGTH_DOWNLOAD , &size ); - + curl_easy_getinfo(curlHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size); - if( size >= maximumAllowedSizeBytes ) + if(size >= maximumAllowedSizeBytes) { - DALI_LOG_ERROR( "File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str() ); + DALI_LOG_ERROR("File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str()); return false; } - else if( size > 0 ) + else if(size > 0) { // If we know the size up front, allocate once and avoid chunk copies. - dataSize = static_cast( size ); - result = DownloadFileDataWithSize( curlHandle, dataBuffer, dataSize ); + dataSize = static_cast(size); + result = DownloadFileDataWithSize(curlHandle, dataBuffer, dataSize); } else { - result = DownloadFileDataByChunk( curlHandle, dataBuffer, dataSize ); + result = DownloadFileDataByChunk(curlHandle, dataBuffer, dataSize); } - if( result != CURLE_OK ) + if(result != CURLE_OK) { - if( errorBuffer != nullptr ) + if(errorBuffer != nullptr) { - DALI_LOG_ERROR( "Failed to download image file \"%s\" with error code %d\n", url.c_str(), result ); + DALI_LOG_ERROR("Failed to download image file \"%s\" with error code %d\n", url.c_str(), result); } else { - DALI_LOG_ERROR( "Failed to download image file \"%s\" with error code %d (%s)\n", url.c_str(), result, errorBuffer ); } + DALI_LOG_ERROR("Failed to download image file \"%s\" with error code %d (%s)\n", url.c_str(), result, errorBuffer); + } return false; } return true; } - } // unnamed namespace - namespace Network { - CurlEnvironment::CurlEnvironment() { // Must be called before we attempt any loads. e.g. by using curl_easy_init() @@ -247,32 +239,31 @@ CurlEnvironment::~CurlEnvironment() curl_global_cleanup(); } -bool DownloadRemoteFileIntoMemory( const std::string& url, - Dali::Vector& dataBuffer, - size_t& dataSize, - size_t maximumAllowedSizeBytes ) +bool DownloadRemoteFileIntoMemory(const std::string& url, + Dali::Vector& dataBuffer, + size_t& dataSize, + size_t maximumAllowedSizeBytes) { bool result = false; - if( url.empty() ) + if(url.empty()) { DALI_LOG_WARNING("empty url requested \n"); return false; } - // start a libcurl easy session, this internally calls curl_global_init, if we ever have more than one download // thread we need to explicity call curl_global_init() on startup from a single thread. CURL* curlHandle = curl_easy_init(); - if ( curlHandle ) + if(curlHandle) { std::vector errorBuffer(CURL_ERROR_SIZE); - curl_easy_setopt( curlHandle, CURLOPT_ERRORBUFFER, &errorBuffer[0]); - result = DownloadFile( curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes, &errorBuffer[0]); + curl_easy_setopt(curlHandle, CURLOPT_ERRORBUFFER, &errorBuffer[0]); + result = DownloadFile(curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes, &errorBuffer[0]); // clean up session - curl_easy_cleanup( curlHandle ); + curl_easy_cleanup(curlHandle); } return result; } diff --git a/dali/internal/imaging/common/file-download.h b/dali/internal/imaging/common/file-download.h old mode 100755 new mode 100644 index d53438c..b1bb8ac --- a/dali/internal/imaging/common/file-download.h +++ b/dali/internal/imaging/common/file-download.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_NETWORK_FILE_DOWNLOAD_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,19 +20,16 @@ // EXTERNAL INCLUDES #include -#include -#include //c++11 #include // uint8 +#include //c++11 +#include namespace Dali { - namespace TizenPlatform { - namespace Network { - /** * Set up the cURL environment - this will ensure curl_global_init is called on startup * and curl_global_cleanup is called on shutdown. @@ -54,13 +51,12 @@ public: // Moveable but not copyable - CurlEnvironment( const CurlEnvironment& ) = delete; - CurlEnvironment& operator=( const CurlEnvironment& ) = delete; - CurlEnvironment( CurlEnvironment&& ) = default; - CurlEnvironment& operator=( CurlEnvironment&& ) = default; + CurlEnvironment(const CurlEnvironment&) = delete; + CurlEnvironment& operator=(const CurlEnvironment&) = delete; + CurlEnvironment(CurlEnvironment&&) = default; + CurlEnvironment& operator=(CurlEnvironment&&) = default; }; - /** * Download a requested file into a memory buffer. * @@ -75,10 +71,10 @@ public: * @return true on success, false on failure * */ -bool DownloadRemoteFileIntoMemory( const std::string& url, - Dali::Vector& dataBuffer, - size_t& dataSize, - size_t maximumAllowedSizeBytes ); +bool DownloadRemoteFileIntoMemory(const std::string& url, + Dali::Vector& dataBuffer, + size_t& dataSize, + size_t maximumAllowedSizeBytes); } // namespace Network diff --git a/dali/internal/imaging/common/gaussian-blur.cpp b/dali/internal/imaging/common/gaussian-blur.cpp index 73eda57..c10c577 100644 --- a/dali/internal/imaging/common/gaussian-blur.cpp +++ b/dali/internal/imaging/common/gaussian-blur.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,114 +24,109 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - - - -void ConvoluteAndTranspose( unsigned char* inBuffer, - unsigned char* outBuffer, - const unsigned int bufferWidth, - const unsigned int bufferHeight, - const float blurRadius ) +void ConvoluteAndTranspose(unsigned char* inBuffer, + unsigned char* outBuffer, + const unsigned int bufferWidth, + const unsigned int bufferHeight, + const float blurRadius) { // Calculate the weights for gaussian blur - int radius = static_cast( std::ceil( blurRadius ) ); - int rows = radius * 2 + 1; + int radius = static_cast(std::ceil(blurRadius)); + int rows = radius * 2 + 1; - float sigma = ( blurRadius < Math::MACHINE_EPSILON_1 ) ? 0.0f : blurRadius * 0.4f + 0.6f; // The same equation used by Android - float sigma22 = 2.0f * sigma * sigma; - float sqrtSigmaPi2 = std::sqrt( 2.0f * Math::PI ) * sigma; - float radius2 = radius * radius; + float sigma = (blurRadius < Math::MACHINE_EPSILON_1) ? 0.0f : blurRadius * 0.4f + 0.6f; // The same equation used by Android + float sigma22 = 2.0f * sigma * sigma; + float sqrtSigmaPi2 = std::sqrt(2.0f * Math::PI) * sigma; + float radius2 = radius * radius; float normalizeFactor = 0.0f; float* weightMatrix = new float[rows]; - int index = 0; + int index = 0; - for ( int row = -radius; row <= radius; row++ ) + for(int row = -radius; row <= radius; row++) { float distance = row * row; - if ( distance > radius2 ) + if(distance > radius2) { weightMatrix[index] = 0.0f; } else { - weightMatrix[index] = static_cast( std::exp( -( distance ) / sigma22 ) / sqrtSigmaPi2 ); + weightMatrix[index] = static_cast(std::exp(-(distance) / sigma22) / sqrtSigmaPi2); } normalizeFactor += weightMatrix[index]; index++; } - for ( int i = 0; i < rows; i++ ) + for(int i = 0; i < rows; i++) { weightMatrix[i] /= normalizeFactor; } // Perform the convolution and transposition using the weights - int columns = rows; + int columns = rows; int columns2 = columns / 2; - for ( unsigned int y = 0; y < bufferHeight; y++ ) + for(unsigned int y = 0; y < bufferHeight; y++) { unsigned int targetPixelIndex = y; - unsigned int ioffset = y * bufferWidth; - for ( unsigned int x = 0; x < bufferWidth; x++ ) + unsigned int ioffset = y * bufferWidth; + for(unsigned int x = 0; x < bufferWidth; x++) { float r = 0.0f, g = 0.0f, b = 0.0f, a = 0.0f; - int weightColumnOffset = columns2; - for ( int column = -columns2; column <= columns2; column++ ) + int weightColumnOffset = columns2; + for(int column = -columns2; column <= columns2; column++) { float weight = weightMatrix[weightColumnOffset + column]; - if ( fabsf( weight ) > Math::MACHINE_EPSILON_1 ) + if(fabsf(weight) > Math::MACHINE_EPSILON_1) { - int ix = x + column; - ix = std::max( 0, std::min( ix, static_cast( bufferWidth - 1 ) ) ); + int ix = x + column; + ix = std::max(0, std::min(ix, static_cast(bufferWidth - 1))); unsigned int sourcePixelIndex = ioffset + ix; - r += weight * inBuffer[sourcePixelIndex*4]; - g += weight * inBuffer[sourcePixelIndex*4+1]; - b += weight * inBuffer[sourcePixelIndex*4+2]; - a += weight * inBuffer[sourcePixelIndex*4+3]; + r += weight * inBuffer[sourcePixelIndex * 4]; + g += weight * inBuffer[sourcePixelIndex * 4 + 1]; + b += weight * inBuffer[sourcePixelIndex * 4 + 2]; + a += weight * inBuffer[sourcePixelIndex * 4 + 3]; } } - outBuffer[targetPixelIndex*4] = std::max( 0, std::min( static_cast( r + 0.5f ), 255 ) ); - outBuffer[targetPixelIndex*4+1] = std::max( 0, std::min( static_cast( g + 0.5f ), 255 ) ); - outBuffer[targetPixelIndex*4+2] = std::max( 0, std::min( static_cast( b + 0.5f ), 255 ) ); - outBuffer[targetPixelIndex*4+3] = std::max( 0, std::min( static_cast( a + 0.5f ), 255 ) ); + outBuffer[targetPixelIndex * 4] = std::max(0, std::min(static_cast(r + 0.5f), 255)); + outBuffer[targetPixelIndex * 4 + 1] = std::max(0, std::min(static_cast(g + 0.5f), 255)); + outBuffer[targetPixelIndex * 4 + 2] = std::max(0, std::min(static_cast(b + 0.5f), 255)); + outBuffer[targetPixelIndex * 4 + 3] = std::max(0, std::min(static_cast(a + 0.5f), 255)); targetPixelIndex += bufferHeight; } } - delete [] weightMatrix; + delete[] weightMatrix; } -void PerformGaussianBlurRGBA( PixelBuffer& buffer, const float blurRadius ) +void PerformGaussianBlurRGBA(PixelBuffer& buffer, const float blurRadius) { - unsigned int bufferWidth = buffer.GetWidth(); + unsigned int bufferWidth = buffer.GetWidth(); unsigned int bufferHeight = buffer.GetHeight(); // Create a temporary buffer for the two-pass blur - PixelBufferPtr softShadowImageBuffer = PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 ); - memcpy( softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), 4u * bufferWidth * bufferHeight ); + PixelBufferPtr softShadowImageBuffer = PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888); + memcpy(softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), 4u * bufferWidth * bufferHeight); // We perform the blur first but write its output image buffer transposed, so that we // can just do it in two passes. The first pass blurs horizontally and transposes, the // second pass does the same, but as the image is now transposed, it's really doing a // vertical blur. The second transposition makes the image the right way up again. This // is much faster than doing a 2D convolution. - ConvoluteAndTranspose( buffer.GetBuffer(), softShadowImageBuffer->GetBuffer(), bufferWidth, bufferHeight, blurRadius ); - ConvoluteAndTranspose( softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), bufferHeight, bufferWidth, blurRadius ); + ConvoluteAndTranspose(buffer.GetBuffer(), softShadowImageBuffer->GetBuffer(), bufferWidth, bufferHeight, blurRadius); + ConvoluteAndTranspose(softShadowImageBuffer->GetBuffer(), buffer.GetBuffer(), bufferHeight, bufferWidth, blurRadius); // On leaving scope, softShadowImageBuffer will get destroyed. } } //namespace Adaptor -}// namespace Internal +} // namespace Internal -}// namespace Dali +} // namespace Dali diff --git a/dali/internal/imaging/common/gaussian-blur.h b/dali/internal/imaging/common/gaussian-blur.h index 28b4342..58dcff0 100644 --- a/dali/internal/imaging/common/gaussian-blur.h +++ b/dali/internal/imaging/common/gaussian-blur.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_GAUSSIAN_BLUR_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Perform a one dimension Gaussian blur convolution and write its output buffer transposed. * @@ -37,7 +34,7 @@ namespace Adaptor * @param[in] bufferHeight The height of the buffer * @param[in] blurRadius The radius for Gaussian blur */ -void ConvoluteAndTranspose( unsigned char* inBuffer, unsigned char* outBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight, const float blurRadius ); +void ConvoluteAndTranspose(unsigned char* inBuffer, unsigned char* outBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight, const float blurRadius); /** * Perform Gaussian blur on a buffer. @@ -50,7 +47,7 @@ void ConvoluteAndTranspose( unsigned char* inBuffer, unsigned char* outBuffer, c * @param[in] buffer The buffer to apply the Gaussian blur to * @param[in] blurRadius The radius for Gaussian blur */ -void PerformGaussianBlurRGBA( PixelBuffer& buffer, const float blurRadius ); +void PerformGaussianBlurRGBA(PixelBuffer& buffer, const float blurRadius); } //namespace Adaptor diff --git a/dali/internal/imaging/common/gif-loading.cpp b/dali/internal/imaging/common/gif-loading.cpp index 27242e7..69d5b7a 100644 --- a/dali/internal/imaging/common/gif-loading.cpp +++ b/dali/internal/imaging/common/gif-loading.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,86 +21,84 @@ #include // EXTERNAL INCLUDES -#include -#include #include -#include #include +#include +#include +#include #include #include #include -#include #include #include +#include -#define IMG_TOO_BIG( w, h ) \ - ( ( static_cast(w) * static_cast(h) ) >= \ - ( (1ULL << (29 * (sizeof(void *) / 4))) - 2048) ) +#define IMG_TOO_BIG(w, h) \ + ((static_cast(w) * static_cast(h)) >= \ + ((1ULL << (29 * (sizeof(void*) / 4))) - 2048)) -#define LOADERR( x ) \ - do { \ - DALI_LOG_ERROR( x ); \ - goto on_error; \ - } while ( 0 ) +#define LOADERR(x) \ + do \ + { \ + DALI_LOG_ERROR(x); \ + goto on_error; \ + } while(0) namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) -Debug::Filter *gGifLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" ); +Debug::Filter* gGifLoadingLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_GIF_LOADING"); #endif -const int IMG_MAX_SIZE = 65000; -constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024; +const int IMG_MAX_SIZE = 65000; +constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024; #if GIFLIB_MAJOR < 5 -const int DISPOSE_BACKGROUND = 2; /* Set area too background color */ -const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */ +const int DISPOSE_BACKGROUND = 2; /* Set area too background color */ +const int DISPOSE_PREVIOUS = 3; /* Restore to previous content */ #endif struct FrameInfo { FrameInfo() - : x( 0 ), - y( 0 ), - w( 0 ), - h( 0 ), - delay( 0 ), - transparent( -1 ), - dispose( DISPOSE_BACKGROUND ), - interlace( 0 ) + : x(0), + y(0), + w(0), + h(0), + delay(0), + transparent(-1), + dispose(DISPOSE_BACKGROUND), + interlace(0) { } - int x, y, w, h; - unsigned short delay; // delay time in 1/100ths of a sec - short transparent : 10; // -1 == not, anything else == index - short dispose : 6; // 0, 1, 2, 3 (others invalid) - short interlace : 1; // interlaced or not + int x, y, w, h; + unsigned short delay; // delay time in 1/100ths of a sec + short transparent : 10; // -1 == not, anything else == index + short dispose : 6; // 0, 1, 2, 3 (others invalid) + short interlace : 1; // interlaced or not }; struct ImageFrame { ImageFrame() - : index( 0 ), - data( nullptr ), + : index(0), + data(nullptr), info(), - loaded( false ) + loaded(false) { } ~ImageFrame() { - if( data != nullptr ) + if(data != nullptr) { // De-allocate memory of the frame data. delete[] data; @@ -109,27 +107,27 @@ struct ImageFrame } int index; - uint32_t *data; /* frame decoding data */ - FrameInfo info; /* special image type info */ - bool loaded : 1; + uint32_t* data; /* frame decoding data */ + FrameInfo info; /* special image type info */ + bool loaded : 1; }; struct GifAnimationData { GifAnimationData() - : frames( ), - frameCount( 0 ), - loopCount( 0 ), - currentFrame( 0 ), - animated( false ) + : frames(), + frameCount(0), + loopCount(0), + currentFrame(0), + animated(false) { } std::vector frames; - int frameCount; - int loopCount; - int currentFrame; - bool animated; + int frameCount; + int loopCount; + int currentFrame; + bool animated; }; // Forward declaration @@ -144,18 +142,18 @@ struct LoaderInfo struct FileData { FileData() - : fileName( nullptr ), - globalMap ( nullptr ), - length( 0 ), - isLocalResource( true ) + : fileName(nullptr), + globalMap(nullptr), + length(0), + isLocalResource(true) { } ~FileData() { - if( globalMap ) + if(globalMap) { - free( globalMap ); + free(globalMap); globalMap = nullptr; } } @@ -167,37 +165,37 @@ struct LoaderInfo bool LoadRemoteFile(); public: - const char *fileName; /**< The absolute path of the file. */ - unsigned char *globalMap ; /**< A pointer to the entire contents of the file */ - long long length; /**< The length of the file in bytes. */ - bool isLocalResource; /**< The flag whether the file is a local resource */ + const char* fileName; /**< The absolute path of the file. */ + unsigned char* globalMap; /**< A pointer to the entire contents of the file */ + long long length; /**< The length of the file in bytes. */ + bool isLocalResource; /**< The flag whether the file is a local resource */ }; struct FileInfo { FileInfo() - : map( nullptr ), - position( 0 ), - length( 0 ) + : map(nullptr), + position(0), + length(0) { } - unsigned char *map; - int position, length; // yes - gif uses ints for file sizes. + unsigned char* map; + int position, length; // yes - gif uses ints for file sizes. }; - FileData fileData; - GifAnimationData animated; + FileData fileData; + GifAnimationData animated; std::unique_ptr gifAccessor{nullptr}; - int imageNumber{0}; - FileInfo fileInfo; + int imageNumber{0}; + FileInfo fileInfo; }; struct ImageProperties { unsigned int w{0}; unsigned int h{0}; - bool alpha{0}; + bool alpha{0}; }; /** @@ -211,15 +209,14 @@ struct GifAccessor */ GifAccessor(LoaderInfo::FileInfo& fileInfo) { - // actually ask libgif to open the file #if GIFLIB_MAJOR >= 5 - gif = DGifOpen( &fileInfo, FileRead, NULL ); + gif = DGifOpen(&fileInfo, FileRead, NULL); #else - gif = DGifOpen( &fileInfo, FileRead ); + gif = DGifOpen(&fileInfo, FileRead); #endif - if (!gif) + if(!gif) { DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); } @@ -229,10 +226,10 @@ struct GifAccessor { if(gif) { -#if (GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1)) - DGifCloseFile( gif, NULL ); +#if(GIFLIB_MAJOR > 5) || ((GIFLIB_MAJOR == 5) && (GIFLIB_MINOR >= 1)) + DGifCloseFile(gif, NULL); #else - DGifCloseFile( gif ); + DGifCloseFile(gif); #endif } } @@ -245,31 +242,30 @@ struct GifAccessor * @param[in] len The length in bytes to be copied * @return The data length of the image in bytes */ - static int FileRead( GifFileType *gifFileType, GifByteType *buffer, int length ) + static int FileRead(GifFileType* gifFileType, GifByteType* buffer, int length) { - LoaderInfo::FileInfo *fi = reinterpret_cast( gifFileType->UserData ); + LoaderInfo::FileInfo* fi = reinterpret_cast(gifFileType->UserData); - if( fi->position >= fi->length ) + if(fi->position >= fi->length) { return 0; // if at or past end - no } - if( (fi->position + length) >= fi->length ) + if((fi->position + length) >= fi->length) { length = fi->length - fi->position; } - memcpy( buffer, fi->map + fi->position, length ); + memcpy(buffer, fi->map + fi->position, length); fi->position += length; return length; } - - GifFileType *gif = nullptr; + GifFileType* gif = nullptr; }; bool LoaderInfo::FileData::LoadFile() { - bool success=false; - if( isLocalResource ) + bool success = false; + if(isLocalResource) { success = LoadLocalFile(); } @@ -282,28 +278,28 @@ bool LoaderInfo::FileData::LoadFile() bool LoaderInfo::FileData::LoadLocalFile() { - Internal::Platform::FileReader fileReader( fileName ); - FILE *fp = fileReader.GetFile(); - if( fp == NULL ) + Internal::Platform::FileReader fileReader(fileName); + FILE* fp = fileReader.GetFile(); + if(fp == NULL) { return false; } - if( fseek( fp, 0, SEEK_END ) <= -1 ) + if(fseek(fp, 0, SEEK_END) <= -1) { return false; } - length = ftell( fp ); - if( length <= -1 ) + length = ftell(fp); + if(length <= -1) { return false; } - if( ( ! fseek( fp, 0, SEEK_SET ) ) ) + if((!fseek(fp, 0, SEEK_SET))) { - globalMap = reinterpret_cast( malloc(sizeof( GifByteType ) * length ) ); - length = fread( globalMap, sizeof( GifByteType ), length, fp); + globalMap = reinterpret_cast(malloc(sizeof(GifByteType) * length)); + length = fread(globalMap, sizeof(GifByteType), length, fp); } else { @@ -315,36 +311,35 @@ bool LoaderInfo::FileData::LoadLocalFile() bool LoaderInfo::FileData::LoadRemoteFile() { // remote file - bool succeeded=false; + bool succeeded = false; Dali::Vector dataBuffer; - size_t dataSize; + size_t dataSize; - succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( fileName, dataBuffer, dataSize, - MAXIMUM_DOWNLOAD_IMAGE_SIZE ); - if( succeeded ) + succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory(fileName, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE); + if(succeeded) { size_t blobSize = dataBuffer.Size(); - if( blobSize > 0U ) + if(blobSize > 0U) { // Open a file handle on the memory buffer: - Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize ); - FILE * const fp = fileReader.GetFile(); - if ( NULL != fp ) + Dali::Internal::Platform::FileReader fileReader(dataBuffer, blobSize); + FILE* const fp = fileReader.GetFile(); + if(NULL != fp) { - if( ( ! fseek( fp, 0, SEEK_SET ) ) ) + if((!fseek(fp, 0, SEEK_SET))) { - globalMap = reinterpret_cast( malloc(sizeof( GifByteType ) * blobSize ) ); - length = fread( globalMap, sizeof( GifByteType ), blobSize, fp); + globalMap = reinterpret_cast(malloc(sizeof(GifByteType) * blobSize)); + length = fread(globalMap, sizeof(GifByteType), blobSize, fp); succeeded = true; } else { - DALI_LOG_ERROR( "Error seeking within file\n" ); + DALI_LOG_ERROR("Error seeking within file\n"); } } else { - DALI_LOG_ERROR( "Error reading file\n" ); + DALI_LOG_ERROR("Error reading file\n"); } } } @@ -352,7 +347,6 @@ bool LoaderInfo::FileData::LoadRemoteFile() return succeeded; } - /** * @brief This combines R, G, B and Alpha values into a single 32-bit (ABGR) value. * @@ -360,14 +354,14 @@ bool LoaderInfo::FileData::LoadRemoteFile() * @param[in] index Frame index to be searched in GIF * @return A pointer to the ImageFrame. */ -inline int CombinePixelABGR( int a, int r, int g, int b ) +inline int CombinePixelABGR(int a, int r, int g, int b) { - return ( ((a) << 24) + ((b) << 16) + ((g) << 8) + (r) ); + return (((a) << 24) + ((b) << 16) + ((g) << 8) + (r)); } -inline int PixelLookup( ColorMapObject *colorMap, int index ) +inline int PixelLookup(ColorMapObject* colorMap, int index) { - return CombinePixelABGR( 0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue ); + return CombinePixelABGR(0xFF, colorMap->Colors[index].Red, colorMap->Colors[index].Green, colorMap->Colors[index].Blue); } /** @@ -377,13 +371,13 @@ inline int PixelLookup( ColorMapObject *colorMap, int index ) * @param[in] index Frame index to be searched in GIF * @return A pointer to the ImageFrame. */ -ImageFrame *FindFrame( const GifAnimationData &animated, int index ) +ImageFrame* FindFrame(const GifAnimationData& animated, int index) { - for( auto &&elem : animated.frames ) + for(auto&& elem : animated.frames) { - if( elem.index == index ) + if(elem.index == index) { - return const_cast( &elem ); + return const_cast(&elem); } } return nullptr; @@ -400,15 +394,15 @@ ImageFrame *FindFrame( const GifAnimationData &animated, int index ) * @param[in] width Width of the image * @param[in] height Height of the image */ -void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, int height ) +void FillImage(uint32_t* data, int row, uint32_t val, int x, int y, int width, int height) { - int xAxis, yAxis; - uint32_t *pixelPosition; + int xAxis, yAxis; + uint32_t* pixelPosition; - for( yAxis = 0; yAxis < height; yAxis++ ) + for(yAxis = 0; yAxis < height; yAxis++) { pixelPosition = data + ((y + yAxis) * row) + x; - for( xAxis = 0; xAxis < width; xAxis++ ) + for(xAxis = 0; xAxis < width; xAxis++) { *pixelPosition = val; pixelPosition++; @@ -428,16 +422,16 @@ void FillImage( uint32_t *data, int row, uint32_t val, int x, int y, int width, * @param[in] width Width of the image * @param[in] height Height of the image */ -void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, int x, int y, int w, int h ) +void FillFrame(uint32_t* data, int row, GifFileType* gif, FrameInfo* frameInfo, int x, int y, int w, int h) { // solid color fill for pre frame region - if( frameInfo->transparent < 0 ) + if(frameInfo->transparent < 0) { - ColorMapObject *colorMap; - int backGroundColor; + ColorMapObject* colorMap; + int backGroundColor; // work out color to use from colorMap - if( gif->Image.ColorMap ) + if(gif->Image.ColorMap) { colorMap = gif->Image.ColorMap; } @@ -447,16 +441,12 @@ void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, } backGroundColor = gif->SBackGroundColor; // and do the fill - FillImage( data, row, - CombinePixelABGR( 0xff, colorMap->Colors[backGroundColor].Red, - colorMap->Colors[backGroundColor].Green, - colorMap->Colors[backGroundColor].Blue ), - x, y, w, h ); + FillImage(data, row, CombinePixelABGR(0xff, colorMap->Colors[backGroundColor].Red, colorMap->Colors[backGroundColor].Green, colorMap->Colors[backGroundColor].Blue), x, y, w, h); } // fill in region with 0 (transparent) else { - FillImage( data, row, 0, x, y, w, h ); + FillImage(data, row, 0, x, y, w, h); } } @@ -466,12 +456,12 @@ void FillFrame( uint32_t *data, int row, GifFileType *gif, FrameInfo *frameInfo, * @param[in] gif A pointer pointing to GIF File Type * @param[in] frameInfo A pointer pointing to Frame Information data */ -void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo ) +void StoreFrameInfo(GifFileType* gif, FrameInfo* frameInfo) { - frameInfo->x = gif->Image.Left; - frameInfo->y = gif->Image.Top; - frameInfo->w = gif->Image.Width; - frameInfo->h = gif->Image.Height; + frameInfo->x = gif->Image.Left; + frameInfo->y = gif->Image.Top; + frameInfo->w = gif->Image.Width; + frameInfo->h = gif->Image.Height; frameInfo->interlace = gif->Image.Interlace; } @@ -486,12 +476,12 @@ void StoreFrameInfo( GifFileType *gif, FrameInfo *frameInfo ) * @param[in] width Width of the image * @param[in] height Height of the image */ -void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height ) +void CheckTransparency(bool& full, FrameInfo* frameInfo, int width, int height) { - if( ( frameInfo->x == 0 ) && ( frameInfo->y == 0 ) && - ( frameInfo->w == width ) && ( frameInfo->h == height ) ) + if((frameInfo->x == 0) && (frameInfo->y == 0) && + (frameInfo->w == width) && (frameInfo->h == height)) { - if( frameInfo->transparent >= 0 ) + if(frameInfo->transparent >= 0) { full = false; } @@ -505,25 +495,25 @@ void CheckTransparency( bool &full, FrameInfo *frameInfo, int width, int height /** * @brief Fix coords and work out an x and y inset in orig data if out of image bounds. */ -void ClipCoordinates( int imageWidth, int imageHeight, int *xin, int *yin, int x0, int y0, int w0, int h0, int *x, int *y, int *w, int *h ) +void ClipCoordinates(int imageWidth, int imageHeight, int* xin, int* yin, int x0, int y0, int w0, int h0, int* x, int* y, int* w, int* h) { - if( x0 < 0 ) + if(x0 < 0) { w0 += x0; *xin = -x0; - x0 = 0; + x0 = 0; } - if( (x0 + w0) > imageWidth ) + if((x0 + w0) > imageWidth) { w0 = imageWidth - x0; } - if( y0 < 0 ) + if(y0 < 0) { h0 += y0; *yin = -y0; - y0 = 0; + y0 = 0; } - if( (y0 + h0) > imageHeight ) + if((y0 + h0) > imageHeight) { h0 = imageHeight - y0; } @@ -544,42 +534,42 @@ void ClipCoordinates( int imageWidth, int imageHeight, int *xin, int *yin, int x * @param[in] prevframe The previous frame * @param[in] lastPreservedFrame The last preserved frame */ -void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame *thisframe, ImageFrame *prevframe, ImageFrame *lastPreservedFrame ) +void FlushFrames(GifAnimationData& animated, int width, int height, ImageFrame* thisframe, ImageFrame* prevframe, ImageFrame* lastPreservedFrame) { - DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n" ); + DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() START \n"); // target is the amount of memory we want to be under for stored frames int total = 0, target = 512 * 1024; // total up the amount of memory used by stored frames for this image - for( auto &&frame : animated.frames ) + for(auto&& frame : animated.frames) { - if( frame.data ) + if(frame.data) { total++; } } - total *= ( width * height * sizeof( uint32_t ) ); + total *= (width * height * sizeof(uint32_t)); - DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total ); + DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "Total used frame size: %d\n", total); // If we use more than target (512k) for frames - flush - if( total > target ) + if(total > target) { // Clean frames (except current and previous) until below target - for( auto &&frame : animated.frames ) + for(auto&& frame : animated.frames) { - if( (frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) && - (!lastPreservedFrame || frame.index != lastPreservedFrame->index) ) + if((frame.index != thisframe->index) && (!prevframe || frame.index != prevframe->index) && + (!lastPreservedFrame || frame.index != lastPreservedFrame->index)) { - if( frame.data != nullptr ) + if(frame.data != nullptr) { delete[] frame.data; frame.data = nullptr; // subtract memory used and if below target - stop flush - total -= ( width * height * sizeof( uint32_t ) ); - if( total < target ) + total -= (width * height * sizeof(uint32_t)); + if(total < target) { break; } @@ -588,7 +578,7 @@ void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame } } - DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n" ); + DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "FlushFrames() END \n"); } /** @@ -600,7 +590,7 @@ void FlushFrames( GifAnimationData &animated, int width, int height, ImageFrame * @param[in] delay The frame delay of new frame * @param[in] index The index of new frame */ -FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, int delay, int index ) +FrameInfo* NewFrame(GifAnimationData& animated, int transparent, int dispose, int delay, int index) { ImageFrame frame; @@ -615,64 +605,62 @@ FrameInfo *NewFrame( GifAnimationData &animated, int transparent, int dispose, i frame.index = index; // that frame is stored AT image/screen size - animated.frames.push_back( frame ); + animated.frames.push_back(frame); - DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size() ); + DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "NewFrame: animated.frames.size() = %d\n", animated.frames.size()); - return &( animated.frames.back().info ); + return &(animated.frames.back().info); } - /** * @brief Decode a gif image into rows then expand to 32bit into the destination * data pointer. */ -bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin, - int transparent, int x, int y, int w, int h, bool fill ) +bool DecodeImage(GifFileType* gif, uint32_t* data, int rowpix, int xin, int yin, int transparent, int x, int y, int w, int h, bool fill) { - int intoffset[] = {0, 4, 2, 1}; - int intjump[] = {8, 8, 4, 2}; - int i, xx, yy, pix, gifW, gifH; - GifRowType *rows = NULL; - bool ret = false; - ColorMapObject *colorMap; - uint32_t *p; + int intoffset[] = {0, 4, 2, 1}; + int intjump[] = {8, 8, 4, 2}; + int i, xx, yy, pix, gifW, gifH; + GifRowType* rows = NULL; + bool ret = false; + ColorMapObject* colorMap; + uint32_t* p; // what we need is image size. - SavedImage *sp; - sp = &gif->SavedImages[ gif->ImageCount - 1 ]; + SavedImage* sp; + sp = &gif->SavedImages[gif->ImageCount - 1]; gifW = sp->ImageDesc.Width; gifH = sp->ImageDesc.Height; - if( ( gifW < w ) || ( gifH < h ) ) + if((gifW < w) || (gifH < h)) { - DALI_ASSERT_DEBUG( false && "Dimensions are bigger than the Gif image size"); + DALI_ASSERT_DEBUG(false && "Dimensions are bigger than the Gif image size"); goto on_error; } // build a blob of memory to have pointers to rows of pixels // AND store the decoded gif pixels (1 byte per pixel) as welll - rows = static_cast( malloc( (gifH * sizeof(GifRowType) ) + ( gifW * gifH * sizeof(GifPixelType) ))); - if( !rows ) + rows = static_cast(malloc((gifH * sizeof(GifRowType)) + (gifW * gifH * sizeof(GifPixelType)))); + if(!rows) { goto on_error; } // fill in the pointers at the start - for( yy = 0; yy < gifH; yy++ ) + for(yy = 0; yy < gifH; yy++) { - rows[yy] = reinterpret_cast(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType)); + rows[yy] = reinterpret_cast(rows) + (gifH * sizeof(GifRowType)) + (yy * gifW * sizeof(GifPixelType)); } // if gif is interlaced, walk interlace pattern and decode into rows - if( gif->Image.Interlace ) + if(gif->Image.Interlace) { - for( i = 0; i < 4; i++ ) + for(i = 0; i < 4; i++) { - for( yy = intoffset[i]; yy < gifH; yy += intjump[i] ) + for(yy = intoffset[i]; yy < gifH; yy += intjump[i]) { - if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK ) + if(DGifGetLine(gif, rows[yy], gifW) != GIF_OK) { goto on_error; } @@ -682,9 +670,9 @@ bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin // normal top to bottom - decode into rows else { - for( yy = 0; yy < gifH; yy++ ) + for(yy = 0; yy < gifH; yy++) { - if( DGifGetLine( gif, rows[yy], gifW ) != GIF_OK ) + if(DGifGetLine(gif, rows[yy], gifW) != GIF_OK) { goto on_error; } @@ -692,7 +680,7 @@ bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin } // work out what colormap to use - if( gif->Image.ColorMap ) + if(gif->Image.ColorMap) { colorMap = gif->Image.ColorMap; } @@ -702,20 +690,20 @@ bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin } // if we need to deal with transparent pixels at all... - if( transparent >= 0 ) + if(transparent >= 0) { // if we are told to FILL (overwrite with transparency kept) - if( fill ) + if(fill) { - for( yy = 0; yy < h; yy++ ) + for(yy = 0; yy < h; yy++) { p = data + ((y + yy) * rowpix) + x; - for( xx = 0; xx < w; xx++ ) + for(xx = 0; xx < w; xx++) { pix = rows[yin + yy][xin + xx]; - if( pix != transparent ) + if(pix != transparent) { - *p = PixelLookup( colorMap, pix ); + *p = PixelLookup(colorMap, pix); } else { @@ -728,15 +716,15 @@ bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin // paste on top with transparent pixels untouched else { - for( yy = 0; yy < h; yy++ ) + for(yy = 0; yy < h; yy++) { p = data + ((y + yy) * rowpix) + x; - for( xx = 0; xx < w; xx++ ) + for(xx = 0; xx < w; xx++) { pix = rows[yin + yy][xin + xx]; - if( pix != transparent ) + if(pix != transparent) { - *p = PixelLookup( colorMap, pix ); + *p = PixelLookup(colorMap, pix); } p++; } @@ -746,13 +734,13 @@ bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin else { // walk pixels without worring about transparency at all - for( yy = 0; yy < h; yy++ ) + for(yy = 0; yy < h; yy++) { p = data + ((y + yy) * rowpix) + x; - for( xx = 0; xx < w; xx++ ) + for(xx = 0; xx < w; xx++) { pix = rows[yin + yy][xin + xx]; - *p = PixelLookup( colorMap, pix ); + *p = PixelLookup(colorMap, pix); p++; } } @@ -760,15 +748,13 @@ bool DecodeImage( GifFileType *gif, uint32_t *data, int rowpix, int xin, int yin ret = true; on_error: - if( rows ) + if(rows) { - free( rows ); + free(rows); } return ret; } - - /** * @brief Reader header from the gif file and populates structures accordingly. * @@ -777,22 +763,22 @@ on_error: * @param[out] error Error code * @return The true or false whether reading was successful or not. */ -bool ReadHeader( LoaderInfo &loaderInfo, - ImageProperties &prop, //output struct - int *error ) +bool ReadHeader(LoaderInfo& loaderInfo, + ImageProperties& prop, //output struct + int* error) { - GifAnimationData &animated = loaderInfo.animated; - LoaderInfo::FileData &fileData = loaderInfo.fileData; - bool success = false; - LoaderInfo::FileInfo fileInfo; - GifRecordType rec; + GifAnimationData& animated = loaderInfo.animated; + LoaderInfo::FileData& fileData = loaderInfo.fileData; + bool success = false; + LoaderInfo::FileInfo fileInfo; + GifRecordType rec; // it is possible which gif file have error midle of frames, // in that case we should play gif file until meet error frame. - int imageNumber = 0; - int loopCount = -1; - FrameInfo *frameInfo = NULL; - bool full = true; + int imageNumber = 0; + int loopCount = -1; + FrameInfo* frameInfo = NULL; + bool full = true; success = fileData.LoadFile(); if(!success || !fileData.globalMap) @@ -802,21 +788,21 @@ bool ReadHeader( LoaderInfo &loaderInfo, } else { - fileInfo.map = fileData.globalMap; - fileInfo.length = fileData.length; + fileInfo.map = fileData.globalMap; + fileInfo.length = fileData.length; fileInfo.position = 0; GifAccessor gifAccessor(fileInfo); - if( gifAccessor.gif ) + if(gifAccessor.gif) { // get the gif "screen size" (the actual image size) prop.w = gifAccessor.gif->SWidth; prop.h = gifAccessor.gif->SHeight; // if size is invalid - abort here - if( (prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h) ) + if((prop.w < 1) || (prop.h < 1) || (prop.w > IMG_MAX_SIZE) || (prop.h > IMG_MAX_SIZE) || IMG_TOO_BIG(prop.w, prop.h)) { - if( IMG_TOO_BIG(prop.w, prop.h) ) + if(IMG_TOO_BIG(prop.w, prop.h)) { success = false; DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED"); @@ -830,113 +816,113 @@ bool ReadHeader( LoaderInfo &loaderInfo, else { // walk through gif records in file to figure out info - success=true; + success = true; do { - if( DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR ) + if(DGifGetRecordType(gifAccessor.gif, &rec) == GIF_ERROR) { // if we have a gif that ends part way through a sequence // (or animation) consider it valid and just break - no error - if( imageNumber <= 1 ) + if(imageNumber <= 1) { - success=true; + success = true; } else { - success=false; + success = false; DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); } break; } // get image description section - if( rec == IMAGE_DESC_RECORD_TYPE ) + if(rec == IMAGE_DESC_RECORD_TYPE) { - int img_code; - GifByteType *img; + int img_code; + GifByteType* img; // get image desc - if( DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR ) + if(DGifGetImageDesc(gifAccessor.gif) == GIF_ERROR) { - success=false; + success = false; DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); break; } // skip decoding and just walk image to next - if( DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR ) + if(DGifGetCode(gifAccessor.gif, &img_code, &img) == GIF_ERROR) { - success=false; + success = false; DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); break; } // skip till next... - while( img ) + while(img) { img = NULL; - DGifGetCodeNext( gifAccessor.gif, &img ); + DGifGetCodeNext(gifAccessor.gif, &img); } // store geometry in the last frame info data - if( frameInfo ) + if(frameInfo) { - StoreFrameInfo( gifAccessor.gif, frameInfo ); - CheckTransparency( full, frameInfo, prop.w, prop.h ); + StoreFrameInfo(gifAccessor.gif, frameInfo); + CheckTransparency(full, frameInfo, prop.w, prop.h); } // or if we dont have a frameInfo entry - create one even for stills else { // allocate and save frame with field data - frameInfo = NewFrame( animated, -1, 0, 0, imageNumber + 1 ); - if (!frameInfo) + frameInfo = NewFrame(animated, -1, 0, 0, imageNumber + 1); + if(!frameInfo) { - success=false; + success = false; DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED"); break; } // store geometry info from gif image - StoreFrameInfo( gifAccessor.gif, frameInfo ); + StoreFrameInfo(gifAccessor.gif, frameInfo); // check for transparency/alpha - CheckTransparency( full, frameInfo, prop.w, prop.h ); + CheckTransparency(full, frameInfo, prop.w, prop.h); } imageNumber++; } // we have an extension code block - for animated gifs for sure - else if( rec == EXTENSION_RECORD_TYPE ) + else if(rec == EXTENSION_RECORD_TYPE) { - int ext_code; - GifByteType *ext = NULL; + int ext_code; + GifByteType* ext = NULL; // get the first extension entry - DGifGetExtension( gifAccessor.gif, &ext_code, &ext ); - while( ext ) + DGifGetExtension(gifAccessor.gif, &ext_code, &ext); + while(ext) { // graphic control extension - for animated gif data // and transparent index + flag - if( ext_code == 0xf9 ) + if(ext_code == 0xf9) { // create frame and store it in image int transparencyIndex = (ext[1] & 1) ? ext[4] : -1; - int disposeMode = (ext[1] >> 2) & 0x7; - int delay = (int(ext[3]) << 8) | int(ext[2]); - frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1); - if( !frameInfo ) + int disposeMode = (ext[1] >> 2) & 0x7; + int delay = (int(ext[3]) << 8) | int(ext[2]); + frameInfo = NewFrame(animated, transparencyIndex, disposeMode, delay, imageNumber + 1); + if(!frameInfo) { - success=false; + success = false; DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED"); break; } } // netscape extension indicating loop count. - else if( ext_code == 0xff ) /* application extension */ + else if(ext_code == 0xff) /* application extension */ { - if( !strncmp(reinterpret_cast(&ext[1]), "NETSCAPE2.0", 11) || - !strncmp(reinterpret_cast(&ext[1]), "ANIMEXTS1.0", 11) ) + if(!strncmp(reinterpret_cast(&ext[1]), "NETSCAPE2.0", 11) || + !strncmp(reinterpret_cast(&ext[1]), "ANIMEXTS1.0", 11)) { ext = NULL; - DGifGetExtensionNext( gifAccessor.gif, &ext ); - if( ext[1] == 0x01 ) + DGifGetExtensionNext(gifAccessor.gif, &ext); + if(ext[1] == 0x01) { loopCount = (int(ext[3]) << 8) | int(ext[2]); - if( loopCount > 0 ) + if(loopCount > 0) { loopCount++; } @@ -946,23 +932,23 @@ bool ReadHeader( LoaderInfo &loaderInfo, // and continue onto the next extension entry ext = NULL; - DGifGetExtensionNext( gifAccessor.gif, &ext ); + DGifGetExtensionNext(gifAccessor.gif, &ext); } } - } while( rec != TERMINATE_RECORD_TYPE && success ); + } while(rec != TERMINATE_RECORD_TYPE && success); - if( success ) + if(success) { // if the gif main says we have more than one image or our image counting // says so, then this image is animated - indicate this - if( (gifAccessor.gif->ImageCount > 1) || (imageNumber > 1) ) + if((gifAccessor.gif->ImageCount > 1) || (imageNumber > 1)) { - animated.animated = 1; + animated.animated = 1; animated.loopCount = loopCount; } - animated.frameCount = std::min( gifAccessor.gif->ImageCount, imageNumber ); + animated.frameCount = std::min(gifAccessor.gif->ImageCount, imageNumber); - if( !full ) + if(!full) { prop.alpha = 1; } @@ -987,42 +973,43 @@ bool ReadHeader( LoaderInfo &loaderInfo, * @param[out] error Error code * @return The true or false whether reading was successful or not. */ -bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w and h - unsigned char *pixels, int *error ) +bool ReadNextFrame(LoaderInfo& loaderInfo, ImageProperties& prop, // use for w and h + unsigned char* pixels, + int* error) { - GifAnimationData &animated = loaderInfo.animated; - LoaderInfo::FileData &fileData = loaderInfo.fileData; - bool ret = false; - GifRecordType rec; - int index = 0, imageNumber = 0; - FrameInfo *frameInfo; - ImageFrame *frame = NULL; - ImageFrame *lastPreservedFrame = NULL; + GifAnimationData& animated = loaderInfo.animated; + LoaderInfo::FileData& fileData = loaderInfo.fileData; + bool ret = false; + GifRecordType rec; + int index = 0, imageNumber = 0; + FrameInfo* frameInfo; + ImageFrame* frame = NULL; + ImageFrame* lastPreservedFrame = NULL; index = animated.currentFrame; // if index is invalid for animated image - error out - if ((animated.animated) && ((index <= 0) || (index > animated.frameCount))) + if((animated.animated) && ((index <= 0) || (index > animated.frameCount))) { DALI_LOG_ERROR("LOAD_ERROR_GENERIC"); return false; } // find the given frame index - frame = FindFrame( animated, index ); - if( !frame ) + frame = FindFrame(animated, index); + if(!frame) { DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE"); return false; } - else if( !(frame->loaded) || !(frame->data) ) + else if(!(frame->loaded) || !(frame->data)) { // if we want to go backwards, we likely need/want to re-decode from the // start as we have nothing to build on. If there is a gif, imageNumber // has been set already. - if( loaderInfo.gifAccessor && loaderInfo.imageNumber > 0) + if(loaderInfo.gifAccessor && loaderInfo.imageNumber > 0) { - if( (index > 0) && (index < loaderInfo.imageNumber) && (animated.animated) ) + if((index > 0) && (index < loaderInfo.imageNumber) && (animated.animated)) { loaderInfo.gifAccessor.reset(); loaderInfo.imageNumber = 0; @@ -1030,18 +1017,18 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w } // actually ask libgif to open the file - if( !loaderInfo.gifAccessor ) + if(!loaderInfo.gifAccessor) { - loaderInfo.fileInfo.map = fileData.globalMap ; - loaderInfo.fileInfo.length = fileData.length; + loaderInfo.fileInfo.map = fileData.globalMap; + loaderInfo.fileInfo.length = fileData.length; loaderInfo.fileInfo.position = 0; - if( !loaderInfo.fileInfo.map ) + if(!loaderInfo.fileInfo.map) { DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE"); return false; } std::unique_ptr gifAccessor = std::make_unique(loaderInfo.fileInfo); - if( !gifAccessor->gif ) + if(!gifAccessor->gif) { DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); return false; @@ -1056,35 +1043,35 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w // walk through gif records in file to figure out info do { - if( DGifGetRecordType( loaderInfo.gifAccessor->gif, &rec ) == GIF_ERROR ) + if(DGifGetRecordType(loaderInfo.gifAccessor->gif, &rec) == GIF_ERROR) { DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); return false; } - if( rec == EXTENSION_RECORD_TYPE ) + if(rec == EXTENSION_RECORD_TYPE) { - int ext_code; - GifByteType *ext = NULL; - DGifGetExtension( loaderInfo.gifAccessor->gif, &ext_code, &ext ); + int ext_code; + GifByteType* ext = NULL; + DGifGetExtension(loaderInfo.gifAccessor->gif, &ext_code, &ext); - while( ext ) + while(ext) { ext = NULL; - DGifGetExtensionNext( loaderInfo.gifAccessor->gif, &ext ); + DGifGetExtensionNext(loaderInfo.gifAccessor->gif, &ext); } } // get image description section - else if( rec == IMAGE_DESC_RECORD_TYPE ) + else if(rec == IMAGE_DESC_RECORD_TYPE) { - int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0; - int img_code; - GifByteType *img; - ImageFrame *previousFrame = NULL; - ImageFrame *thisFrame = NULL; + int xin = 0, yin = 0, x = 0, y = 0, w = 0, h = 0; + int img_code; + GifByteType* img; + ImageFrame* previousFrame = NULL; + ImageFrame* thisFrame = NULL; // get image desc - if( DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR ) + if(DGifGetImageDesc(loaderInfo.gifAccessor->gif) == GIF_ERROR) { DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); return false; @@ -1092,79 +1079,73 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w // get the previous frame entry AND the current one to fill in previousFrame = FindFrame(animated, imageNumber - 1); - thisFrame = FindFrame(animated, imageNumber); + thisFrame = FindFrame(animated, imageNumber); // if we have a frame AND we're animated AND we have no data... - if( (thisFrame) && (!thisFrame->data) && (animated.animated) ) + if((thisFrame) && (!thisFrame->data) && (animated.animated)) { bool first = false; // allocate it thisFrame->data = new uint32_t[prop.w * prop.h]; - if( !thisFrame->data ) + if(!thisFrame->data) { DALI_LOG_ERROR("LOAD_ERROR_RESOURCE_ALLOCATION_FAILED"); return false; } // if we have no prior frame OR prior frame data... empty - if( (!previousFrame) || (!previousFrame->data) ) + if((!previousFrame) || (!previousFrame->data)) { - first = true; + first = true; frameInfo = &(thisFrame->info); - memset( thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t) ); + memset(thisFrame->data, 0, prop.w * prop.h * sizeof(uint32_t)); } // we have a prior frame to copy data from... else { - frameInfo = &( previousFrame->info ); + frameInfo = &(previousFrame->info); // fix coords of sub image in case it goes out... - ClipCoordinates( prop.w, prop.h, &xin, &yin, - frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, - &x, &y, &w, &h ); + ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h); // if dispose mode is not restore - then copy pre frame - if( frameInfo->dispose != DISPOSE_PREVIOUS ) + if(frameInfo->dispose != DISPOSE_PREVIOUS) { - memcpy( thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t) ); + memcpy(thisFrame->data, previousFrame->data, prop.w * prop.h * sizeof(uint32_t)); } // if dispose mode is "background" then fill with bg - if( frameInfo->dispose == DISPOSE_BACKGROUND ) + if(frameInfo->dispose == DISPOSE_BACKGROUND) { - FillFrame( thisFrame->data, prop.w, loaderInfo.gifAccessor->gif, frameInfo, x, y, w, h ); + FillFrame(thisFrame->data, prop.w, loaderInfo.gifAccessor->gif, frameInfo, x, y, w, h); } - else if( frameInfo->dispose == DISPOSE_PREVIOUS ) // GIF_DISPOSE_RESTORE + else if(frameInfo->dispose == DISPOSE_PREVIOUS) // GIF_DISPOSE_RESTORE { int prevIndex = 2; do { // Find last preserved frame. - lastPreservedFrame = FindFrame( animated, imageNumber - prevIndex ); - if( ! lastPreservedFrame ) + lastPreservedFrame = FindFrame(animated, imageNumber - prevIndex); + if(!lastPreservedFrame) { - DALI_LOG_ERROR( "LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND" ); + DALI_LOG_ERROR("LOAD_ERROR_LAST_PRESERVED_FRAME_NOT_FOUND"); return false; } prevIndex++; - } while( lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS ); + } while(lastPreservedFrame && lastPreservedFrame->info.dispose == DISPOSE_PREVIOUS); - if ( lastPreservedFrame ) + if(lastPreservedFrame) { - memcpy( thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t) ); + memcpy(thisFrame->data, lastPreservedFrame->data, prop.w * prop.h * sizeof(uint32_t)); } } } // now draw this frame on top - frameInfo = &( thisFrame->info ); - ClipCoordinates( prop.w, prop.h, &xin, &yin, - frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, - &x, &y, &w, &h ); - if( !DecodeImage( loaderInfo.gifAccessor->gif, thisFrame->data, prop.w, - xin, yin, frameInfo->transparent, - x, y, w, h, first) ) + frameInfo = &(thisFrame->info); + ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h); + if(!DecodeImage(loaderInfo.gifAccessor->gif, thisFrame->data, prop.w, xin, yin, frameInfo->transparent, x, y, w, h, first)) { DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE"); return false; @@ -1173,28 +1154,24 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w // mark as loaded and done thisFrame->loaded = true; - FlushFrames( animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame ); + FlushFrames(animated, prop.w, prop.h, thisFrame, previousFrame, lastPreservedFrame); } // if we have a frame BUT the image is not animated. different // path - else if( (thisFrame) && (!thisFrame->data) && (!animated.animated) ) + else if((thisFrame) && (!thisFrame->data) && (!animated.animated)) { // if we don't have the data decoded yet - decode it - if( (!thisFrame->loaded) || (!thisFrame->data) ) + if((!thisFrame->loaded) || (!thisFrame->data)) { // use frame info but we WONT allocate frame pixels - frameInfo = &( thisFrame->info ); - ClipCoordinates( prop.w, prop.h, &xin, &yin, - frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, - &x, &y, &w, &h ); + frameInfo = &(thisFrame->info); + ClipCoordinates(prop.w, prop.h, &xin, &yin, frameInfo->x, frameInfo->y, frameInfo->w, frameInfo->h, &x, &y, &w, &h); // clear out all pixels - FillFrame( reinterpret_cast(pixels), prop.w, loaderInfo.gifAccessor->gif, - frameInfo, 0, 0, prop.w, prop.h ); + FillFrame(reinterpret_cast(pixels), prop.w, loaderInfo.gifAccessor->gif, frameInfo, 0, 0, prop.w, prop.h); // and decode the gif with overwriting - if( !DecodeImage( loaderInfo.gifAccessor->gif, reinterpret_cast(pixels), - prop.w, xin, yin, frameInfo->transparent, x, y, w, h, true) ) + if(!DecodeImage(loaderInfo.gifAccessor->gif, reinterpret_cast(pixels), prop.w, xin, yin, frameInfo->transparent, x, y, w, h, true)) { DALI_LOG_ERROR("LOAD_ERROR_CORRUPT_FILE"); return false; @@ -1208,31 +1185,31 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w else { // skip decoding and just walk image to next - if( DGifGetCode( loaderInfo.gifAccessor->gif, &img_code, &img ) == GIF_ERROR ) + if(DGifGetCode(loaderInfo.gifAccessor->gif, &img_code, &img) == GIF_ERROR) { DALI_LOG_ERROR("LOAD_ERROR_UNKNOWN_FORMAT"); return false; } - while( img ) + while(img) { img = NULL; - DGifGetCodeNext( loaderInfo.gifAccessor->gif, &img ); + DGifGetCodeNext(loaderInfo.gifAccessor->gif, &img); } } imageNumber++; // if we found the image we wanted - get out of here - if( imageNumber > index ) + if(imageNumber > index) { break; } } - } while( rec != TERMINATE_RECORD_TYPE ); + } while(rec != TERMINATE_RECORD_TYPE); // if we are at the end of the animation or not animated, close file loaderInfo.imageNumber = imageNumber; - if( (animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE) ) + if((animated.frameCount <= 1) || (rec == TERMINATE_RECORD_TYPE)) { loaderInfo.gifAccessor.reset(); loaderInfo.imageNumber = 0; @@ -1241,13 +1218,13 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w // no errors in header scan etc. so set err and return value *error = 0; - ret = true; + ret = true; // if it was an animated image we need to copy the data to the // pixels for the image from the frame holding the data - if( animated.animated && frame->data ) + if(animated.animated && frame->data) { - memcpy( pixels, frame->data, prop.w * prop.h * sizeof( uint32_t ) ); + memcpy(pixels, frame->data, prop.w * prop.h * sizeof(uint32_t)); } return ret; @@ -1258,66 +1235,63 @@ bool ReadNextFrame( LoaderInfo &loaderInfo, ImageProperties &prop, // use for w struct GifLoading::Impl { public: - Impl( const std::string& url, bool isLocalResource ) - : mUrl( url ) + Impl(const std::string& url, bool isLocalResource) + : mUrl(url) { loaderInfo.gifAccessor = nullptr; int error; - loaderInfo.fileData.fileName = mUrl.c_str(); + loaderInfo.fileData.fileName = mUrl.c_str(); loaderInfo.fileData.isLocalResource = isLocalResource; - ReadHeader( loaderInfo, imageProperties, &error ); + ReadHeader(loaderInfo, imageProperties, &error); } // Moveable but not copyable - Impl( const Impl& ) = delete; - Impl& operator=( const Impl& ) = delete; - Impl( Impl&& ) = default; - Impl& operator=( Impl&& ) = default; + Impl(const Impl&) = delete; + Impl& operator=(const Impl&) = delete; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; - std::string mUrl; - LoaderInfo loaderInfo; + std::string mUrl; + LoaderInfo loaderInfo; ImageProperties imageProperties; }; -AnimatedImageLoadingPtr GifLoading::New( const std::string &url, bool isLocalResource ) +AnimatedImageLoadingPtr GifLoading::New(const std::string& url, bool isLocalResource) { - return AnimatedImageLoadingPtr( new GifLoading( url, isLocalResource ) ); + return AnimatedImageLoadingPtr(new GifLoading(url, isLocalResource)); } -GifLoading::GifLoading( const std::string &url, bool isLocalResource ) -: mImpl( new GifLoading::Impl( url, isLocalResource ) ) +GifLoading::GifLoading(const std::string& url, bool isLocalResource) +: mImpl(new GifLoading::Impl(url, isLocalResource)) { } - GifLoading::~GifLoading() { delete mImpl; } -bool GifLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector &pixelData ) +bool GifLoading::LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector& pixelData) { - int error; + int error; bool ret = false; - const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof( uint32_t ); + const int bufferSize = mImpl->imageProperties.w * mImpl->imageProperties.h * sizeof(uint32_t); - DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count ); + DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count); - for( int i = 0; i < count; ++i ) + for(int i = 0; i < count; ++i) { - auto pixelBuffer = new unsigned char[ bufferSize ]; + auto pixelBuffer = new unsigned char[bufferSize]; - mImpl->loaderInfo.animated.currentFrame = 1 + ( (frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount ); + mImpl->loaderInfo.animated.currentFrame = 1 + ((frameStartIndex + i) % mImpl->loaderInfo.animated.frameCount); - if( ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error ) ) + if(ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer, &error)) { - if( pixelBuffer ) + if(pixelBuffer) { - pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize, - mImpl->imageProperties.w, mImpl->imageProperties.h, - Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) ); + pixelData.push_back(Dali::PixelData::New(pixelBuffer, bufferSize, mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY)); ret = true; } } @@ -1326,19 +1300,19 @@ bool GifLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vect return ret; } -Dali::Devel::PixelBuffer GifLoading::LoadFrame( uint32_t frameIndex ) +Dali::Devel::PixelBuffer GifLoading::LoadFrame(uint32_t frameIndex) { - int error; + int error; Dali::Devel::PixelBuffer pixelBuffer; - DALI_LOG_INFO( gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex ); + DALI_LOG_INFO(gGifLoadingLogFilter, Debug::Concise, "LoadFrame( frameIndex:%d )\n", frameIndex); - pixelBuffer = Dali::Devel::PixelBuffer::New( mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888 ); + pixelBuffer = Dali::Devel::PixelBuffer::New(mImpl->imageProperties.w, mImpl->imageProperties.h, Dali::Pixel::RGBA8888); - mImpl->loaderInfo.animated.currentFrame = 1 + ( frameIndex % mImpl->loaderInfo.animated.frameCount ); - ReadNextFrame( mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error ); + mImpl->loaderInfo.animated.currentFrame = 1 + (frameIndex % mImpl->loaderInfo.animated.frameCount); + ReadNextFrame(mImpl->loaderInfo, mImpl->imageProperties, pixelBuffer.GetBuffer(), &error); - if( error != 0 ) + if(error != 0) { pixelBuffer = Dali::Devel::PixelBuffer(); } @@ -1347,7 +1321,7 @@ Dali::Devel::PixelBuffer GifLoading::LoadFrame( uint32_t frameIndex ) ImageDimensions GifLoading::GetImageSize() const { - return ImageDimensions( mImpl->imageProperties.w, mImpl->imageProperties.h ); + return ImageDimensions(mImpl->imageProperties.w, mImpl->imageProperties.h); } uint32_t GifLoading::GetImageCount() const @@ -1355,7 +1329,7 @@ uint32_t GifLoading::GetImageCount() const return mImpl->loaderInfo.animated.frameCount; } -uint32_t GifLoading::GetFrameInterval( uint32_t frameIndex ) const +uint32_t GifLoading::GetFrameInterval(uint32_t frameIndex) const { return mImpl->loaderInfo.animated.frames[frameIndex].info.delay * 10; } diff --git a/dali/internal/imaging/common/gif-loading.h b/dali/internal/imaging/common/gif-loading.h index c53fcde..b817084 100644 --- a/dali/internal/imaging/common/gif-loading.h +++ b/dali/internal/imaging/common/gif-loading.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_GIF_LOADING_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,26 +18,23 @@ * */ // EXTERNAL INCLUDES -#include -#include -#include #include #include +#include #include +#include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Class to manage loading frames of an animated gif in small chunks. Lazy initializes only when * data is actually needed. @@ -45,17 +42,16 @@ namespace Adaptor * is released. (This is to speed up frame loads, which would otherwise have to re-acquire the * data from disk) */ -class GifLoading: public Internal::Adaptor::AnimatedImageLoading +class GifLoading : public Internal::Adaptor::AnimatedImageLoading { public: - /** * Create a GifLoading with the given url and resourceType. * @param[in] url The url of the gif image to load * @param[in] isLocalResource The true or false whether this is a local resource. * @return A newly created GifLoading. */ - static AnimatedImageLoadingPtr New( const std::string& url, bool isLocalResource ); + static AnimatedImageLoadingPtr New(const std::string& url, bool isLocalResource); /** * @brief Constructor @@ -64,7 +60,7 @@ public: * @param[in] url The url of the gif image to load * @param[in] isLocalResource The true or false whether this is a local resource. */ - GifLoading( const std::string& url, bool isLocalResource ); + GifLoading(const std::string& url, bool isLocalResource); /** * @brief Destructor @@ -81,9 +77,9 @@ public: * @param[out] pixelData The vector in which to return the frame data * @return True if the frame data was successfully loaded */ - bool LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector& pixelData ) override; + bool LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector& pixelData) override; - /** + /** * @brief Load the next Frame of the animated image. * * @note This function will load the entire animated image into memory if not already loaded. @@ -91,7 +87,7 @@ public: * @return Dali::Devel::PixelBuffer The loaded PixelBuffer. If loading is fail, return empty handle. */ - Dali::Devel::PixelBuffer LoadFrame( uint32_t frameIndex ) override; + Dali::Devel::PixelBuffer LoadFrame(uint32_t frameIndex) override; /** * @brief Get the size of a gif image. @@ -112,7 +108,7 @@ public: * * @return The time interval of the frame(microsecond). */ - uint32_t GetFrameInterval( uint32_t frameIndex ) const override; + uint32_t GetFrameInterval(uint32_t frameIndex) const override; /** * @brief Get the animated image file URL diff --git a/dali/internal/imaging/common/http-utils.cpp b/dali/internal/imaging/common/http-utils.cpp index 97d5e19..3291907 100644 --- a/dali/internal/imaging/common/http-utils.cpp +++ b/dali/internal/imaging/common/http-utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,33 +23,31 @@ namespace Dali { - namespace TizenPlatform { - namespace { const unsigned int MIN_HTTP_URL_LENGTH = 12; // assume we have a least http://xx/yy -const char HTTP_URL[] = "http://"; -const char HTTPS_URL[] = "https://"; -} +const char HTTP_URL[] = "http://"; +const char HTTPS_URL[] = "https://"; +} // namespace -bool Network::IsHttpUrl( const std::string& path ) +bool Network::IsHttpUrl(const std::string& path) { - if( path.size() <= MIN_HTTP_URL_LENGTH ) - { - return false; - } - - if( ( strncasecmp( path.c_str(), HTTP_URL, sizeof(HTTP_URL) -1 ) == 0 ) || - ( strncasecmp( path.c_str(), HTTPS_URL, sizeof(HTTPS_URL) -1 ) == 0 ) ) - { - return true; - } - - return false; + if(path.size() <= MIN_HTTP_URL_LENGTH) + { + return false; + } + + if((strncasecmp(path.c_str(), HTTP_URL, sizeof(HTTP_URL) - 1) == 0) || + (strncasecmp(path.c_str(), HTTPS_URL, sizeof(HTTPS_URL) - 1) == 0)) + { + return true; + } + + return false; } -} // TizenPlatform +} // namespace TizenPlatform -} // Dali +} // namespace Dali diff --git a/dali/internal/imaging/common/http-utils.h b/dali/internal/imaging/common/http-utils.h index 01de460..dabe9e3 100644 --- a/dali/internal/imaging/common/http-utils.h +++ b/dali/internal/imaging/common/http-utils.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_NETWORK_UTILS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,21 +21,18 @@ namespace Dali { - namespace TizenPlatform { - namespace Network { - /** * @brief Tests if a string starts with either http:// or https:// * @param[in] path string * @return true if the path is a http url */ -bool IsHttpUrl( const std::string& path ); +bool IsHttpUrl(const std::string& path); -} // Network +} // namespace Network } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/image-loader-plugin-proxy.cpp b/dali/internal/imaging/common/image-loader-plugin-proxy.cpp old mode 100755 new mode 100644 index 126754a..c2c9c6f --- a/dali/internal/imaging/common/image-loader-plugin-proxy.cpp +++ b/dali/internal/imaging/common/image-loader-plugin-proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,29 +19,24 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace ImageLoaderPluginProxy { +static const char* DEFAULT_OBJECT_NAME("libdali2-image-loader-plugin.so"); - -static const char * DEFAULT_OBJECT_NAME( "libdali2-image-loader-plugin.so" ); - -static bool mInitializeAttempted = false; -static void* mLibHandle = NULL; -static CreateImageLoaderPlugin* mCreatePluginFunctionPtr = NULL; +static bool mInitializeAttempted = false; +static void* mLibHandle = NULL; +static CreateImageLoaderPlugin* mCreatePluginFunctionPtr = NULL; static DestroyImageLoaderPlugin* mDestroyImageLoaderPluginPtr = NULL; -static Dali::ImageLoaderPlugin* mImageLoaderPlugin = NULL; +static Dali::ImageLoaderPlugin* mImageLoaderPlugin = NULL; #if defined(DEBUG_ENABLED) /** @@ -52,47 +47,46 @@ static Dali::ImageLoaderPlugin* mImageLoaderPlugin = NULL; * LOG_IMAGE_LOADER_PLUGIN=3 dali-demo #< on, verbose * */ -Debug::Filter* gImageLoaderPluginLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_IMAGE_LOADER_PLUGIN" ); +Debug::Filter* gImageLoaderPluginLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMAGE_LOADER_PLUGIN"); #endif void Initialize() { // Only attempt to load dll once char* error = NULL; - if ( !mInitializeAttempted ) + if(!mInitializeAttempted) { mInitializeAttempted = true; - mLibHandle = dlopen( DEFAULT_OBJECT_NAME, RTLD_LAZY ); - error = dlerror(); - if( !mLibHandle ) + mLibHandle = dlopen(DEFAULT_OBJECT_NAME, RTLD_LAZY); + error = dlerror(); + if(!mLibHandle) { - DALI_LOG_INFO( gImageLoaderPluginLogFilter, Dali::Integration::Log::Verbose, "Cannot load dali image loading plugin library error: %s\n", error ); + DALI_LOG_INFO(gImageLoaderPluginLogFilter, Dali::Integration::Log::Verbose, "Cannot load dali image loading plugin library error: %s\n", error); return; } // load plugin - mCreatePluginFunctionPtr = reinterpret_cast( dlsym( mLibHandle, "CreateImageLoaderPlugin" ) ); - error = dlerror(); - if( !mCreatePluginFunctionPtr ) + mCreatePluginFunctionPtr = reinterpret_cast(dlsym(mLibHandle, "CreateImageLoaderPlugin")); + error = dlerror(); + if(!mCreatePluginFunctionPtr) { - DALI_LOG_ERROR("Cannot load symbol CreateImageLoaderPlugin(): %s\n", error ); + DALI_LOG_ERROR("Cannot load symbol CreateImageLoaderPlugin(): %s\n", error); return; } - mDestroyImageLoaderPluginPtr = reinterpret_cast( dlsym( mLibHandle, "DestroyImageLoaderPlugin" ) ); - error = dlerror(); - if( !mDestroyImageLoaderPluginPtr ) + mDestroyImageLoaderPluginPtr = reinterpret_cast(dlsym(mLibHandle, "DestroyImageLoaderPlugin")); + error = dlerror(); + if(!mDestroyImageLoaderPluginPtr) { - DALI_LOG_ERROR("Cannot load symbol DestroyImageLoaderPlugin(): %s\n", error ); + DALI_LOG_ERROR("Cannot load symbol DestroyImageLoaderPlugin(): %s\n", error); return; } - mImageLoaderPlugin = mCreatePluginFunctionPtr(); - error = dlerror(); - if( !mImageLoaderPlugin ) + error = dlerror(); + if(!mImageLoaderPlugin) { - DALI_LOG_ERROR("Call to function CreateImageLoaderPlugin() failed : %s\n", error ); + DALI_LOG_ERROR("Call to function CreateImageLoaderPlugin() failed : %s\n", error); return; } } @@ -100,18 +94,18 @@ void Initialize() void Destroy() { - if( mImageLoaderPlugin && mDestroyImageLoaderPluginPtr ) + if(mImageLoaderPlugin && mDestroyImageLoaderPluginPtr) { - mDestroyImageLoaderPluginPtr( mImageLoaderPlugin ); + mDestroyImageLoaderPluginPtr(mImageLoaderPlugin); mImageLoaderPlugin = NULL; } } -const ImageLoader::BitmapLoader* BitmapLoaderLookup( const std::string& filename ) +const ImageLoader::BitmapLoader* BitmapLoaderLookup(const std::string& filename) { - if( mImageLoaderPlugin ) + if(mImageLoaderPlugin) { - const ImageLoader::BitmapLoader* data = mImageLoaderPlugin->BitmapLoaderLookup( filename ); + const ImageLoader::BitmapLoader* data = mImageLoaderPlugin->BitmapLoaderLookup(filename); return data; } return NULL; @@ -119,7 +113,6 @@ const ImageLoader::BitmapLoader* BitmapLoaderLookup( const std::string& filename } // namespace ImageLoaderPluginProxy - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/imaging/common/image-loader-plugin-proxy.h b/dali/internal/imaging/common/image-loader-plugin-proxy.h old mode 100755 new mode 100644 index 53d36d8..aafe086 --- a/dali/internal/imaging/common/image-loader-plugin-proxy.h +++ b/dali/internal/imaging/common/image-loader-plugin-proxy.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_IMAGE_LOADING_PLUGIN_PROXY_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,36 +26,29 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace ImageLoaderPluginProxy { +using CreateImageLoaderPlugin = Dali::ImageLoaderPlugin::CreateImageLoaderPlugin; +using DestroyImageLoaderPlugin = Dali::ImageLoaderPlugin::DestroyImageLoaderPlugin; - using CreateImageLoaderPlugin = Dali::ImageLoaderPlugin::CreateImageLoaderPlugin; - using DestroyImageLoaderPlugin = Dali::ImageLoaderPlugin::DestroyImageLoaderPlugin; - - - /** +/** * @brief Initialize */ - void Initialize(); - +void Initialize(); - /** +/** * @brief Destroy */ - void Destroy(); +void Destroy(); - /** +/** * @brief BitmapLoaderLookup */ - const ImageLoader::BitmapLoader* BitmapLoaderLookup( const std::string& filename ); - +const ImageLoader::BitmapLoader* BitmapLoaderLookup(const std::string& filename); } // namespace ImageLoaderPluginProxy diff --git a/dali/internal/imaging/common/image-loader.cpp b/dali/internal/imaging/common/image-loader.cpp old mode 100755 new mode 100644 index 5980796..8160468 --- a/dali/internal/imaging/common/image-loader.cpp +++ b/dali/internal/imaging/common/image-loader.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ #include #include +#include +#include +#include #include #include #include @@ -27,9 +30,6 @@ #include #include #include -#include -#include -#include #include using namespace Dali::Integration; @@ -38,11 +38,10 @@ namespace Dali { namespace TizenPlatform { - namespace { #if defined(DEBUG_ENABLED) -Integration::Log::Filter* gLogFilter = Debug::Filter::New( Debug::Concise, false, "LOG_IMAGE_LOADING" ); +Integration::Log::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, false, "LOG_IMAGE_LOADING"); #endif static unsigned int gMaxTextureSize = 4096; @@ -76,17 +75,19 @@ enum FileFormats * A lookup table containing all the bitmap loaders with the appropriate information. * Has to be in sync with enum FileFormats */ +// clang-format off const Dali::ImageLoader::BitmapLoader BITMAP_LOADER_LOOKUP_TABLE[FORMAT_TOTAL_COUNT] = -{ - { Png::MAGIC_BYTE_1, Png::MAGIC_BYTE_2, LoadBitmapFromPng, LoadPngHeader, Bitmap::BITMAP_2D_PACKED_PIXELS }, - { Jpeg::MAGIC_BYTE_1, Jpeg::MAGIC_BYTE_2, LoadBitmapFromJpeg, LoadJpegHeader, Bitmap::BITMAP_2D_PACKED_PIXELS }, - { Bmp::MAGIC_BYTE_1, Bmp::MAGIC_BYTE_2, LoadBitmapFromBmp, LoadBmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS }, - { Gif::MAGIC_BYTE_1, Gif::MAGIC_BYTE_2, LoadBitmapFromGif, LoadGifHeader, Bitmap::BITMAP_2D_PACKED_PIXELS }, - { Ktx::MAGIC_BYTE_1, Ktx::MAGIC_BYTE_2, LoadBitmapFromKtx, LoadKtxHeader, Bitmap::BITMAP_COMPRESSED }, - { Astc::MAGIC_BYTE_1, Astc::MAGIC_BYTE_2, LoadBitmapFromAstc, LoadAstcHeader, Bitmap::BITMAP_COMPRESSED }, - { Ico::MAGIC_BYTE_1, Ico::MAGIC_BYTE_2, LoadBitmapFromIco, LoadIcoHeader, Bitmap::BITMAP_2D_PACKED_PIXELS }, - { 0x0, 0x0, LoadBitmapFromWbmp, LoadWbmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS }, -}; + { + {Png::MAGIC_BYTE_1, Png::MAGIC_BYTE_2, LoadBitmapFromPng, LoadPngHeader, Bitmap::BITMAP_2D_PACKED_PIXELS}, + {Jpeg::MAGIC_BYTE_1, Jpeg::MAGIC_BYTE_2, LoadBitmapFromJpeg, LoadJpegHeader, Bitmap::BITMAP_2D_PACKED_PIXELS}, + {Bmp::MAGIC_BYTE_1, Bmp::MAGIC_BYTE_2, LoadBitmapFromBmp, LoadBmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS}, + {Gif::MAGIC_BYTE_1, Gif::MAGIC_BYTE_2, LoadBitmapFromGif, LoadGifHeader, Bitmap::BITMAP_2D_PACKED_PIXELS}, + {Ktx::MAGIC_BYTE_1, Ktx::MAGIC_BYTE_2, LoadBitmapFromKtx, LoadKtxHeader, Bitmap::BITMAP_COMPRESSED }, + {Astc::MAGIC_BYTE_1, Astc::MAGIC_BYTE_2, LoadBitmapFromAstc, LoadAstcHeader, Bitmap::BITMAP_COMPRESSED }, + {Ico::MAGIC_BYTE_1, Ico::MAGIC_BYTE_2, LoadBitmapFromIco, LoadIcoHeader, Bitmap::BITMAP_2D_PACKED_PIXELS}, + {0x0, 0x0, LoadBitmapFromWbmp, LoadWbmpHeader, Bitmap::BITMAP_2D_PACKED_PIXELS}, + }; +// clang-format on const unsigned int MAGIC_LENGTH = 2; @@ -96,32 +97,34 @@ const unsigned int MAGIC_LENGTH = 2; struct FormatExtension { const std::string extension; - FileFormats format; + FileFormats format; }; +// clang-format off const FormatExtension FORMAT_EXTENSIONS[] = -{ - { ".png", FORMAT_PNG }, - { ".jpg", FORMAT_JPEG }, - { ".bmp", FORMAT_BMP }, - { ".gif", FORMAT_GIF }, - { ".ktx", FORMAT_KTX }, - { ".astc", FORMAT_ASTC }, - { ".ico", FORMAT_ICO }, - { ".wbmp", FORMAT_WBMP } -}; + { + {".png", FORMAT_PNG }, + {".jpg", FORMAT_JPEG}, + {".bmp", FORMAT_BMP }, + {".gif", FORMAT_GIF }, + {".ktx", FORMAT_KTX }, + {".astc", FORMAT_ASTC}, + {".ico", FORMAT_ICO }, + {".wbmp", FORMAT_WBMP} + }; +// clang-format on const unsigned int FORMAT_EXTENSIONS_COUNT = sizeof(FORMAT_EXTENSIONS) / sizeof(FormatExtension); -FileFormats GetFormatHint( const std::string& filename ) +FileFormats GetFormatHint(const std::string& filename) { FileFormats format = FORMAT_UNKNOWN; - for ( unsigned int i = 0; i < FORMAT_EXTENSIONS_COUNT; ++i ) + for(unsigned int i = 0; i < FORMAT_EXTENSIONS_COUNT; ++i) { unsigned int length = FORMAT_EXTENSIONS[i].extension.size(); - if ( ( filename.size() > length ) && - ( 0 == filename.compare( filename.size() - length, length, FORMAT_EXTENSIONS[i].extension ) ) ) + if((filename.size() > length) && + (0 == filename.compare(filename.size() - length, length, FORMAT_EXTENSIONS[i].extension))) { format = FORMAT_EXTENSIONS[i].format; break; @@ -141,69 +144,69 @@ FileFormats GetFormatHint( const std::string& filename ) * @param[out] profile The kind of bitmap to hold the bits loaded for the bitmap. * @return true, if we can decode the image, false otherwise */ -bool GetBitmapLoaderFunctions( FILE *fp, - FileFormats format, - Dali::ImageLoader::LoadBitmapFunction& loader, - Dali::ImageLoader::LoadBitmapHeaderFunction& header, - Bitmap::Profile& profile, - const std::string& filename ) +bool GetBitmapLoaderFunctions(FILE* fp, + FileFormats format, + Dali::ImageLoader::LoadBitmapFunction& loader, + Dali::ImageLoader::LoadBitmapHeaderFunction& header, + Bitmap::Profile& profile, + const std::string& filename) { unsigned char magic[MAGIC_LENGTH]; - size_t read = fread(magic, sizeof(unsigned char), MAGIC_LENGTH, fp); + size_t read = fread(magic, sizeof(unsigned char), MAGIC_LENGTH, fp); // Reset to the start of the file. - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking to start of file\n"); } - if (read != MAGIC_LENGTH) + if(read != MAGIC_LENGTH) { return false; } - bool loaderFound = false; - const Dali::ImageLoader::BitmapLoader *lookupPtr = BITMAP_LOADER_LOOKUP_TABLE; - Dali::ImageLoader::Input defaultInput( fp ); + bool loaderFound = false; + const Dali::ImageLoader::BitmapLoader* lookupPtr = BITMAP_LOADER_LOOKUP_TABLE; + Dali::ImageLoader::Input defaultInput(fp); // try plugin image loader - const Dali::ImageLoader::BitmapLoader* data = Internal::Adaptor::ImageLoaderPluginProxy::BitmapLoaderLookup( filename ); - if( data != NULL ) + const Dali::ImageLoader::BitmapLoader* data = Internal::Adaptor::ImageLoaderPluginProxy::BitmapLoaderLookup(filename); + if(data != NULL) { - lookupPtr = data; - unsigned int width = 0; + lookupPtr = data; + unsigned int width = 0; unsigned int height = 0; - loaderFound = lookupPtr->header( fp, width, height ); + loaderFound = lookupPtr->header(fp, width, height); } // try hinted format - if ( false == loaderFound && format != FORMAT_UNKNOWN ) + if(false == loaderFound && format != FORMAT_UNKNOWN) { lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + format; - if ( format >= FORMAT_MAGIC_BYTE_COUNT || - ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] ) ) + if(format >= FORMAT_MAGIC_BYTE_COUNT || + (lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1])) { - unsigned int width = 0; + unsigned int width = 0; unsigned int height = 0; - loaderFound = lookupPtr->header( fp, width, height ); + loaderFound = lookupPtr->header(fp, width, height); } } // then try to get a match with formats that have magic bytes - if ( false == loaderFound ) + if(false == loaderFound) { - for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE; - lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT; - ++lookupPtr ) + for(lookupPtr = BITMAP_LOADER_LOOKUP_TABLE; + lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT; + ++lookupPtr) { - if ( lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1] ) + if(lookupPtr->magicByte1 == magic[0] && lookupPtr->magicByte2 == magic[1]) { // to seperate ico file format and wbmp file format - unsigned int width = 0; + unsigned int width = 0; unsigned int height = 0; - loaderFound = lookupPtr->header(fp, width, height); + loaderFound = lookupPtr->header(fp, width, height); } - if (loaderFound) + if(loaderFound) { break; } @@ -211,17 +214,17 @@ bool GetBitmapLoaderFunctions( FILE *fp, } // finally try formats that do not use magic bytes - if ( false == loaderFound ) + if(false == loaderFound) { - for ( lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT; - lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_TOTAL_COUNT; - ++lookupPtr ) + for(lookupPtr = BITMAP_LOADER_LOOKUP_TABLE + FORMAT_MAGIC_BYTE_COUNT; + lookupPtr < BITMAP_LOADER_LOOKUP_TABLE + FORMAT_TOTAL_COUNT; + ++lookupPtr) { // to seperate ico file format and wbmp file format - unsigned int width = 0; + unsigned int width = 0; unsigned int height = 0; - loaderFound = lookupPtr->header(fp, width, height); - if (loaderFound) + loaderFound = lookupPtr->header(fp, width, height); + if(loaderFound) { break; } @@ -229,7 +232,7 @@ bool GetBitmapLoaderFunctions( FILE *fp, } // if a loader was found set the outputs - if ( loaderFound ) + if(loaderFound) { loader = lookupPtr->loader; header = lookupPtr->header; @@ -237,7 +240,7 @@ bool GetBitmapLoaderFunctions( FILE *fp, } // Reset to the start of the file. - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking to start of file\n"); } @@ -247,83 +250,80 @@ bool GetBitmapLoaderFunctions( FILE *fp, } // anonymous namespace - namespace ImageLoader { - -bool ConvertStreamToBitmap( const BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer ) +bool ConvertStreamToBitmap(const BitmapResourceType& resource, std::string path, FILE* const fp, Dali::Devel::PixelBuffer& pixelBuffer) { - DALI_LOG_TRACE_METHOD( gLogFilter ); + DALI_LOG_TRACE_METHOD(gLogFilter); bool result = false; - if (fp != NULL) + if(fp != NULL) { - Dali::ImageLoader::LoadBitmapFunction function; + Dali::ImageLoader::LoadBitmapFunction function; Dali::ImageLoader::LoadBitmapHeaderFunction header; Bitmap::Profile profile; - if ( GetBitmapLoaderFunctions( fp, - GetFormatHint( path ), - function, - header, - profile, - path ) ) + if(GetBitmapLoaderFunctions(fp, + GetFormatHint(path), + function, + header, + profile, + path)) { - const Dali::ImageLoader::ScalingParameters scalingParameters( resource.size, resource.scalingMode, resource.samplingMode ); - const Dali::ImageLoader::Input input( fp, scalingParameters, resource.orientationCorrection ); + const Dali::ImageLoader::ScalingParameters scalingParameters(resource.size, resource.scalingMode, resource.samplingMode); + const Dali::ImageLoader::Input input(fp, scalingParameters, resource.orientationCorrection); // Run the image type decoder: - result = function( input, pixelBuffer ); + result = function(input, pixelBuffer); - if (!result) + if(!result) { - DALI_LOG_WARNING( "Unable to convert %s\n", path.c_str() ); + DALI_LOG_WARNING("Unable to convert %s\n", path.c_str()); pixelBuffer.Reset(); } - pixelBuffer = Internal::Platform::ApplyAttributesToBitmap( pixelBuffer, resource.size, resource.scalingMode, resource.samplingMode ); + pixelBuffer = Internal::Platform::ApplyAttributesToBitmap(pixelBuffer, resource.size, resource.scalingMode, resource.samplingMode); } else { - DALI_LOG_WARNING( "Image Decoder for %s unavailable\n", path.c_str() ); + DALI_LOG_WARNING("Image Decoder for %s unavailable\n", path.c_str()); } } return result; } -ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path ) +ResourcePointer LoadImageSynchronously(const Integration::BitmapResourceType& resource, const std::string& path) { - ResourcePointer result; + ResourcePointer result; Dali::Devel::PixelBuffer bitmap; - Internal::Platform::FileReader fileReader( path ); - FILE * const fp = fileReader.GetFile(); - if( fp != NULL ) + Internal::Platform::FileReader fileReader(path); + FILE* const fp = fileReader.GetFile(); + if(fp != NULL) { bool success = ConvertStreamToBitmap(resource, path, fp, bitmap); - if (success && bitmap) + if(success && bitmap) { Bitmap::Profile profile{Bitmap::Profile::BITMAP_2D_PACKED_PIXELS}; // For backward compatibility the Bitmap must be created auto retval = Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD); - DALI_LOG_SET_OBJECT_STRING( retval, path ); + DALI_LOG_SET_OBJECT_STRING(retval, path); retval->GetPackedPixelsProfile()->ReserveBuffer( - bitmap.GetPixelFormat(), - bitmap.GetWidth(), - bitmap.GetHeight(), - bitmap.GetWidth(), - bitmap.GetHeight() - ); + bitmap.GetPixelFormat(), + bitmap.GetWidth(), + bitmap.GetHeight(), + bitmap.GetWidth(), + bitmap.GetHeight()); auto& impl = Dali::GetImplementation(bitmap); - std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer()); + std::copy(impl.GetBuffer(), impl.GetBuffer() + impl.GetBufferSize(), retval->GetBuffer()); result.Reset(retval); } } @@ -331,33 +331,33 @@ ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& r } ///@ToDo: Rename GetClosestImageSize() functions. Make them use the orientation correction and scaling information. Requires jpeg loader to tell us about reorientation. [Is there still a requirement for this functionality at all?] -ImageDimensions GetClosestImageSize( const std::string& filename, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ) +ImageDimensions GetClosestImageSize(const std::string& filename, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection) { - unsigned int width = 0; + unsigned int width = 0; unsigned int height = 0; - Internal::Platform::FileReader fileReader( filename ); - FILE *fp = fileReader.GetFile(); - if (fp != NULL) + Internal::Platform::FileReader fileReader(filename); + FILE* fp = fileReader.GetFile(); + if(fp != NULL) { - Dali::ImageLoader::LoadBitmapFunction loaderFunction; + Dali::ImageLoader::LoadBitmapFunction loaderFunction; Dali::ImageLoader::LoadBitmapHeaderFunction headerFunction; - Bitmap::Profile profile; - - if ( GetBitmapLoaderFunctions( fp, - GetFormatHint(filename), - loaderFunction, - headerFunction, - profile, - filename ) ) + Bitmap::Profile profile; + + if(GetBitmapLoaderFunctions(fp, + GetFormatHint(filename), + loaderFunction, + headerFunction, + profile, + filename)) { - const Dali::ImageLoader::Input input( fp, Dali::ImageLoader::ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection ); + const Dali::ImageLoader::Input input(fp, Dali::ImageLoader::ScalingParameters(size, fittingMode, samplingMode), orientationCorrection); - const bool read_res = headerFunction( input, width, height ); + const bool read_res = headerFunction(input, width, height); if(!read_res) { DALI_LOG_WARNING("Image Decoder failed to read header for %s\n", filename.c_str()); @@ -368,58 +368,58 @@ ImageDimensions GetClosestImageSize( const std::string& filename, DALI_LOG_WARNING("Image Decoder for %s unavailable\n", filename.c_str()); } } - return ImageDimensions( width, height ); + return ImageDimensions(width, height); } -ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ) +ImageDimensions GetClosestImageSize(Integration::ResourcePointer resourceBuffer, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection) { - unsigned int width = 0; + unsigned int width = 0; unsigned int height = 0; // Get the blob of binary data that we need to decode: - DALI_ASSERT_DEBUG( resourceBuffer ); - Dali::RefCountedVector* const encodedBlob = reinterpret_cast*>( resourceBuffer.Get() ); + DALI_ASSERT_DEBUG(resourceBuffer); + Dali::RefCountedVector* const encodedBlob = reinterpret_cast*>(resourceBuffer.Get()); - if( encodedBlob != 0 ) + if(encodedBlob != 0) { - if( encodedBlob->GetVector().Size() ) + if(encodedBlob->GetVector().Size()) { // Open a file handle on the memory buffer: - Internal::Platform::FileReader fileReader( encodedBlob->GetVector() ); - FILE *fp = fileReader.GetFile(); - if ( fp != NULL ) + Internal::Platform::FileReader fileReader(encodedBlob->GetVector()); + FILE* fp = fileReader.GetFile(); + if(fp != NULL) { - Dali::ImageLoader::LoadBitmapFunction loaderFunction; + Dali::ImageLoader::LoadBitmapFunction loaderFunction; Dali::ImageLoader::LoadBitmapHeaderFunction headerFunction; - Bitmap::Profile profile; - - if ( GetBitmapLoaderFunctions( fp, - FORMAT_UNKNOWN, - loaderFunction, - headerFunction, - profile, - "" ) ) + Bitmap::Profile profile; + + if(GetBitmapLoaderFunctions(fp, + FORMAT_UNKNOWN, + loaderFunction, + headerFunction, + profile, + "")) { - const Dali::ImageLoader::Input input( fp, Dali::ImageLoader::ScalingParameters( size, fittingMode, samplingMode ), orientationCorrection ); - const bool read_res = headerFunction( input, width, height ); - if( !read_res ) + const Dali::ImageLoader::Input input(fp, Dali::ImageLoader::ScalingParameters(size, fittingMode, samplingMode), orientationCorrection); + const bool read_res = headerFunction(input, width, height); + if(!read_res) { - DALI_LOG_WARNING( "Image Decoder failed to read header for resourceBuffer\n" ); + DALI_LOG_WARNING("Image Decoder failed to read header for resourceBuffer\n"); } } } } } - return ImageDimensions( width, height ); + return ImageDimensions(width, height); } -void SetMaxTextureSize( unsigned int size ) +void SetMaxTextureSize(unsigned int size) { - gMaxTextureSize = size; + gMaxTextureSize = size; gMaxTextureSizeUpdated = true; } @@ -433,6 +433,6 @@ bool MaxTextureSizeUpdated() return gMaxTextureSizeUpdated; } -} // ImageLoader -} // TizenPlatform -} // Dali +} // namespace ImageLoader +} // namespace TizenPlatform +} // namespace Dali diff --git a/dali/internal/imaging/common/image-loader.h b/dali/internal/imaging/common/image-loader.h index a7c42a0..f63b186 100644 --- a/dali/internal/imaging/common/image-loader.h +++ b/dali/internal/imaging/common/image-loader.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_IMAGE_LOADER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,11 @@ */ // EXTERNAL INCLUDES -#include -#include +#include #include +#include +#include #include -#include #include namespace Dali @@ -30,7 +30,7 @@ namespace Dali namespace Integration { typedef IntrusivePtr ResourcePointer; -} // Integration +} // namespace Integration namespace TizenPlatform { @@ -44,7 +44,7 @@ namespace ImageLoader * @param[out] bitmap Pointer to write bitmap to * @return true on success, false on failure */ -bool ConvertStreamToBitmap( const Integration::BitmapResourceType& resource, std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer ); +bool ConvertStreamToBitmap(const Integration::BitmapResourceType& resource, std::string path, FILE* const fp, Dali::Devel::PixelBuffer& pixelBuffer); /** * Convert a bitmap and write to a file stream. @@ -53,7 +53,7 @@ bool ConvertStreamToBitmap( const Integration::BitmapResourceType& resource, std * @param[out] pixelData Reference to PixelData object. * @return true on success, false on failure */ -bool ConvertBitmapToStream( std::string path, FILE * const fp, Dali::Devel::PixelBuffer& pixelBuffer ); +bool ConvertBitmapToStream(std::string path, FILE* const fp, Dali::Devel::PixelBuffer& pixelBuffer); /** * Loads an image synchronously @@ -61,32 +61,32 @@ bool ConvertBitmapToStream( std::string path, FILE * const fp, Dali::Devel::Pixe * @param path to the image * @return bitmap */ -Integration::ResourcePointer LoadImageSynchronously( const Integration::BitmapResourceType& resource, const std::string& path ); +Integration::ResourcePointer LoadImageSynchronously(const Integration::BitmapResourceType& resource, const std::string& path); /** * @returns the closest image size */ -ImageDimensions GetClosestImageSize( const std::string& filename, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ); +ImageDimensions GetClosestImageSize(const std::string& filename, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection); /** * @returns the closest image size */ -ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ); +ImageDimensions GetClosestImageSize(Integration::ResourcePointer resourceBuffer, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection); /** * @brief Set the maximum texture size. Then size can be kwown by GL_MAX_TEXTURE_SIZE. * * @param [in] size The maximum texture size to set */ -void SetMaxTextureSize( unsigned int size ); +void SetMaxTextureSize(unsigned int size); /** * @brief Get the maximum texture size. @@ -102,8 +102,8 @@ unsigned int GetMaxTextureSize(); */ bool MaxTextureSizeUpdated(); -} // ImageLoader -} // TizenPlatform -} // Dali +} // namespace ImageLoader +} // namespace TizenPlatform +} // namespace Dali #endif // DALI_TIZEN_PLATFORM_IMAGE_LOADER_H diff --git a/dali/internal/imaging/common/image-operations.cpp b/dali/internal/imaging/common/image-operations.cpp old mode 100755 new mode 100644 index d75e027..96828b8 --- a/dali/internal/imaging/common/image-operations.cpp +++ b/dali/internal/imaging/common/image-operations.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,16 @@ #include // EXTERNAL INCLUDES -#include -#include -#include -#include -#include +#include #include #include #include +#include #include -#include +#include +#include +#include +#include // INTERNAL INCLUDES @@ -37,25 +37,23 @@ namespace Internal { namespace Platform { - namespace { - // The BORDER_FILL_VALUE is a single byte value that is used for horizontal and vertical borders. // A value of 0x00 gives us transparency for pixel buffers with an alpha channel, or black otherwise. // We can optionally use a Vector4 color here, but at reduced fill speed. -const uint8_t BORDER_FILL_VALUE( 0x00 ); +const uint8_t BORDER_FILL_VALUE(0x00); // A maximum size limit for newly created bitmaps. ( 1u << 16 ) - 1 is chosen as we are using 16bit words for dimensions. -const unsigned int MAXIMUM_TARGET_BITMAP_SIZE( ( 1u << 16 ) - 1 ); +const unsigned int MAXIMUM_TARGET_BITMAP_SIZE((1u << 16) - 1); // Constants used by the ImageResampler. -const float DEFAULT_SOURCE_GAMMA = 1.75f; ///< Default source gamma value used in the Resampler() function. Partial gamma correction looks better on mips. Set to 1.0 to disable gamma correction. -const float FILTER_SCALE = 1.f; ///< Default filter scale value used in the Resampler() function. Filter scale - values < 1.0 cause aliasing, but create sharper looking mips. +const float DEFAULT_SOURCE_GAMMA = 1.75f; ///< Default source gamma value used in the Resampler() function. Partial gamma correction looks better on mips. Set to 1.0 to disable gamma correction. +const float FILTER_SCALE = 1.f; ///< Default filter scale value used in the Resampler() function. Filter scale - values < 1.0 cause aliasing, but create sharper looking mips. const float RAD_135 = Math::PI_2 + Math::PI_4; ///< 135 degrees in radians; -const float RAD_225 = RAD_135 + Math::PI_2; ///< 225 degrees in radians; +const float RAD_225 = RAD_135 + Math::PI_2; ///< 225 degrees in radians; const float RAD_270 = 3.f * Math::PI_2; ///< 270 degrees in radians; -const float RAD_315 = RAD_225 + Math::PI_2; ///< 315 degrees in radians; +const float RAD_315 = RAD_225 + Math::PI_2; ///< 315 degrees in radians; using Integration::Bitmap; using Integration::BitmapPtr; @@ -98,7 +96,6 @@ struct Pixel2Bytes uint8_t a; } __attribute__((packed, aligned(2))); //< Tell the compiler it is okay to use a single 16 bit load. - #if defined(DEBUG_ENABLED) /** * Disable logging of image operations or make it verbose from the commandline @@ -108,11 +105,11 @@ struct Pixel2Bytes * LOG_IMAGE_OPERATIONS=3 dali-demo #< on, verbose * */ -Debug::Filter* gImageOpsLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_IMAGE_OPERATIONS" ); +Debug::Filter* gImageOpsLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMAGE_OPERATIONS"); #endif /** @return The greatest even number less than or equal to the argument. */ -inline unsigned int EvenDown( const unsigned int a ) +inline unsigned int EvenDown(const unsigned int a) { const unsigned int evened = a & ~1u; return evened; @@ -121,24 +118,24 @@ inline unsigned int EvenDown( const unsigned int a ) /** * @brief Log bad parameters. */ -void ValidateScalingParameters( const unsigned int inputWidth, - const unsigned int inputHeight, - const unsigned int desiredWidth, - const unsigned int desiredHeight ) +void ValidateScalingParameters(const unsigned int inputWidth, + const unsigned int inputHeight, + const unsigned int desiredWidth, + const unsigned int desiredHeight) { - if( desiredWidth > inputWidth || desiredHeight > inputHeight ) + if(desiredWidth > inputWidth || desiredHeight > inputHeight) { - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Upscaling not supported (%u, %u -> %u, %u).\n", inputWidth, inputHeight, desiredWidth, desiredHeight ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Upscaling not supported (%u, %u -> %u, %u).\n", inputWidth, inputHeight, desiredWidth, desiredHeight); } - if( desiredWidth == 0u || desiredHeight == 0u ) + if(desiredWidth == 0u || desiredHeight == 0u) { - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Downscaling to a zero-area target is pointless.\n" ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Downscaling to a zero-area target is pointless.\n"); } - if( inputWidth == 0u || inputHeight == 0u ) + if(inputWidth == 0u || inputHeight == 0u) { - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Zero area images cannot be scaled\n" ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Zero area images cannot be scaled\n"); } } @@ -146,38 +143,38 @@ void ValidateScalingParameters( const unsigned int inputWidth, * @brief Do debug assertions common to all scanline halving functions. * @note Inline and in anon namespace so should boil away in release builds. */ -inline void DebugAssertScanlineParameters( const uint8_t * const pixels, const unsigned int width ) +inline void DebugAssertScanlineParameters(const uint8_t* const pixels, const unsigned int width) { - DALI_ASSERT_DEBUG( pixels && "Null pointer." ); - DALI_ASSERT_DEBUG( width > 1u && "Can't average fewer than two pixels." ); - DALI_ASSERT_DEBUG( width < 131072u && "Unusually wide image: are you sure you meant to pass that value in?" ); + DALI_ASSERT_DEBUG(pixels && "Null pointer."); + DALI_ASSERT_DEBUG(width > 1u && "Can't average fewer than two pixels."); + DALI_ASSERT_DEBUG(width < 131072u && "Unusually wide image: are you sure you meant to pass that value in?"); } /** * @brief Assertions on params to functions averaging pairs of scanlines. * @note Inline as intended to boil away in release. */ -inline void DebugAssertDualScanlineParameters( const uint8_t * const scanline1, - const uint8_t * const scanline2, - uint8_t* const outputScanline, - const size_t widthInComponents ) +inline void DebugAssertDualScanlineParameters(const uint8_t* const scanline1, + const uint8_t* const scanline2, + uint8_t* const outputScanline, + const size_t widthInComponents) { - DALI_ASSERT_DEBUG( scanline1 && "Null pointer." ); - DALI_ASSERT_DEBUG( scanline2 && "Null pointer." ); - DALI_ASSERT_DEBUG( outputScanline && "Null pointer." ); - DALI_ASSERT_DEBUG( ((scanline1 >= scanline2 + widthInComponents) || (scanline2 >= scanline1 + widthInComponents )) && "Scanlines alias." ); - DALI_ASSERT_DEBUG( ((outputScanline >= (scanline2 + widthInComponents)) || (scanline2 >= (scanline1 + widthInComponents))) && "Scanline 2 aliases output." ); + DALI_ASSERT_DEBUG(scanline1 && "Null pointer."); + DALI_ASSERT_DEBUG(scanline2 && "Null pointer."); + DALI_ASSERT_DEBUG(outputScanline && "Null pointer."); + DALI_ASSERT_DEBUG(((scanline1 >= scanline2 + widthInComponents) || (scanline2 >= scanline1 + widthInComponents)) && "Scanlines alias."); + DALI_ASSERT_DEBUG(((outputScanline >= (scanline2 + widthInComponents)) || (scanline2 >= (scanline1 + widthInComponents))) && "Scanline 2 aliases output."); } /** * @brief Converts a scaling mode to the definition of which dimensions matter when box filtering as a part of that mode. */ -BoxDimensionTest DimensionTestForScalingMode( FittingMode::Type fittingMode ) +BoxDimensionTest DimensionTestForScalingMode(FittingMode::Type fittingMode) { BoxDimensionTest dimensionTest; dimensionTest = BoxDimensionTestEither; - switch( fittingMode ) + switch(fittingMode) { // Shrink to fit attempts to make one or zero dimensions smaller than the // desired dimensions and one or two dimensions exactly the same as the desired @@ -216,20 +213,20 @@ BoxDimensionTest DimensionTestForScalingMode( FittingMode::Type fittingMode ) * @brief Work out the dimensions for a uniform scaling of the input to map it * into the target while effecting ShinkToFit scaling mode. */ -ImageDimensions FitForShrinkToFit( ImageDimensions target, ImageDimensions source ) +ImageDimensions FitForShrinkToFit(ImageDimensions target, ImageDimensions source) { // Scale the input by the least extreme of the two dimensions: const float widthScale = target.GetX() / float(source.GetX()); const float heightScale = target.GetY() / float(source.GetY()); - const float scale = widthScale < heightScale ? widthScale : heightScale; + const float scale = widthScale < heightScale ? widthScale : heightScale; // Do no scaling at all if the result would increase area: - if( scale >= 1.0f ) + if(scale >= 1.0f) { return source; } - return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f ); + return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f); } /** @@ -239,85 +236,85 @@ ImageDimensions FitForShrinkToFit( ImageDimensions target, ImageDimensions sourc * bottom or left and right to be cropped away unless the source was pre-cropped * to match the destination aspect ratio. */ -ImageDimensions FitForScaleToFill( ImageDimensions target, ImageDimensions source ) +ImageDimensions FitForScaleToFill(ImageDimensions target, ImageDimensions source) { - DALI_ASSERT_DEBUG( source.GetX() > 0 && source.GetY() > 0 && "Zero-area rectangles should not be passed-in" ); + DALI_ASSERT_DEBUG(source.GetX() > 0 && source.GetY() > 0 && "Zero-area rectangles should not be passed-in"); // Scale the input by the least extreme of the two dimensions: const float widthScale = target.GetX() / float(source.GetX()); const float heightScale = target.GetY() / float(source.GetY()); - const float scale = widthScale > heightScale ? widthScale : heightScale; + const float scale = widthScale > heightScale ? widthScale : heightScale; // Do no scaling at all if the result would increase area: - if( scale >= 1.0f ) + if(scale >= 1.0f) { return source; } - return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f ); + return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f); } /** * @brief Work out the dimensions for a uniform scaling of the input to map it * into the target while effecting FIT_WIDTH scaling mode. */ -ImageDimensions FitForFitWidth( ImageDimensions target, ImageDimensions source ) +ImageDimensions FitForFitWidth(ImageDimensions target, ImageDimensions source) { - DALI_ASSERT_DEBUG( source.GetX() > 0 && "Cant fit a zero-dimension rectangle." ); - const float scale = target.GetX() / float(source.GetX()); + DALI_ASSERT_DEBUG(source.GetX() > 0 && "Cant fit a zero-dimension rectangle."); + const float scale = target.GetX() / float(source.GetX()); // Do no scaling at all if the result would increase area: - if( scale >= 1.0f ) + if(scale >= 1.0f) { - return source; + return source; } - return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f ); + return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f); } /** * @brief Work out the dimensions for a uniform scaling of the input to map it * into the target while effecting FIT_HEIGHT scaling mode. */ -ImageDimensions FitForFitHeight( ImageDimensions target, ImageDimensions source ) +ImageDimensions FitForFitHeight(ImageDimensions target, ImageDimensions source) { - DALI_ASSERT_DEBUG( source.GetY() > 0 && "Cant fit a zero-dimension rectangle." ); + DALI_ASSERT_DEBUG(source.GetY() > 0 && "Cant fit a zero-dimension rectangle."); const float scale = target.GetY() / float(source.GetY()); // Do no scaling at all if the result would increase area: - if( scale >= 1.0f ) + if(scale >= 1.0f) { return source; } - return ImageDimensions( source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f ); + return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f); } /** * @brief Generate the rectangle to use as the target of a pixel sampling pass * (e.g., nearest or linear). */ -ImageDimensions FitToScalingMode( ImageDimensions requestedSize, ImageDimensions sourceSize, FittingMode::Type fittingMode ) +ImageDimensions FitToScalingMode(ImageDimensions requestedSize, ImageDimensions sourceSize, FittingMode::Type fittingMode) { ImageDimensions fitDimensions; - switch( fittingMode ) + switch(fittingMode) { case FittingMode::SHRINK_TO_FIT: { - fitDimensions = FitForShrinkToFit( requestedSize, sourceSize ); + fitDimensions = FitForShrinkToFit(requestedSize, sourceSize); break; } case FittingMode::SCALE_TO_FILL: { - fitDimensions = FitForScaleToFill( requestedSize, sourceSize ); + fitDimensions = FitForScaleToFill(requestedSize, sourceSize); break; } case FittingMode::FIT_WIDTH: { - fitDimensions = FitForFitWidth( requestedSize, sourceSize ); + fitDimensions = FitForFitWidth(requestedSize, sourceSize); break; } case FittingMode::FIT_HEIGHT: { - fitDimensions = FitForFitHeight( requestedSize, sourceSize ); + fitDimensions = FitForFitHeight(requestedSize, sourceSize); break; } } @@ -337,53 +334,53 @@ ImageDimensions FitToScalingMode( ImageDimensions requestedSize, ImageDimensions * @param[out] scanlinesToCrop The number of scanlines to remove from the image (can be negative to represent Y borders required) * @param[out] columnsToCrop The number of columns to remove from the image (can be negative to represent X borders required) */ -void CalculateBordersFromFittingMode( ImageDimensions sourceSize, FittingMode::Type fittingMode, ImageDimensions& requestedSize, int& scanlinesToCrop, int& columnsToCrop ) +void CalculateBordersFromFittingMode(ImageDimensions sourceSize, FittingMode::Type fittingMode, ImageDimensions& requestedSize, int& scanlinesToCrop, int& columnsToCrop) { - const int sourceWidth( static_cast( sourceSize.GetWidth() ) ); - const int sourceHeight( static_cast(sourceSize.GetHeight() ) ); - const float targetAspect( static_cast< float >( requestedSize.GetWidth() ) / static_cast< float >( requestedSize.GetHeight() ) ); - int finalWidth = 0; - int finalHeight = 0; + const int sourceWidth(static_cast(sourceSize.GetWidth())); + const int sourceHeight(static_cast(sourceSize.GetHeight())); + const float targetAspect(static_cast(requestedSize.GetWidth()) / static_cast(requestedSize.GetHeight())); + int finalWidth = 0; + int finalHeight = 0; - switch( fittingMode ) + switch(fittingMode) { case FittingMode::FIT_WIDTH: { - finalWidth = sourceWidth; - finalHeight = static_cast< float >( sourceWidth ) / targetAspect; + finalWidth = sourceWidth; + finalHeight = static_cast(sourceWidth) / targetAspect; - columnsToCrop = 0; - scanlinesToCrop = -( finalHeight - sourceHeight ); + columnsToCrop = 0; + scanlinesToCrop = -(finalHeight - sourceHeight); break; } case FittingMode::FIT_HEIGHT: { - finalWidth = static_cast< float >( sourceHeight ) * targetAspect; + finalWidth = static_cast(sourceHeight) * targetAspect; finalHeight = sourceHeight; - columnsToCrop = -( finalWidth - sourceWidth ); + columnsToCrop = -(finalWidth - sourceWidth); scanlinesToCrop = 0; break; } case FittingMode::SHRINK_TO_FIT: { - const float sourceAspect( static_cast< float >( sourceWidth ) / static_cast< float >( sourceHeight ) ); - if( sourceAspect > targetAspect ) + const float sourceAspect(static_cast(sourceWidth) / static_cast(sourceHeight)); + if(sourceAspect > targetAspect) { - finalWidth = sourceWidth; - finalHeight = static_cast< float >( sourceWidth ) / targetAspect; + finalWidth = sourceWidth; + finalHeight = static_cast(sourceWidth) / targetAspect; - columnsToCrop = 0; - scanlinesToCrop = -( finalHeight - sourceHeight ); + columnsToCrop = 0; + scanlinesToCrop = -(finalHeight - sourceHeight); } else { - finalWidth = static_cast< float >( sourceHeight ) * targetAspect; + finalWidth = static_cast(sourceHeight) * targetAspect; finalHeight = sourceHeight; - columnsToCrop = -( finalWidth - sourceWidth ); + columnsToCrop = -(finalWidth - sourceWidth); scanlinesToCrop = 0; } break; @@ -391,43 +388,43 @@ void CalculateBordersFromFittingMode( ImageDimensions sourceSize, FittingMode:: case FittingMode::SCALE_TO_FILL: { - const float sourceAspect( static_cast< float >( sourceWidth ) / static_cast< float >( sourceHeight ) ); - if( sourceAspect > targetAspect ) + const float sourceAspect(static_cast(sourceWidth) / static_cast(sourceHeight)); + if(sourceAspect > targetAspect) { - finalWidth = static_cast< float >( sourceHeight ) * targetAspect; + finalWidth = static_cast(sourceHeight) * targetAspect; finalHeight = sourceHeight; - columnsToCrop = -( finalWidth - sourceWidth ); + columnsToCrop = -(finalWidth - sourceWidth); scanlinesToCrop = 0; } else { - finalWidth = sourceWidth; - finalHeight = static_cast< float >( sourceWidth ) / targetAspect; + finalWidth = sourceWidth; + finalHeight = static_cast(sourceWidth) / targetAspect; - columnsToCrop = 0; - scanlinesToCrop = -( finalHeight - sourceHeight ); + columnsToCrop = 0; + scanlinesToCrop = -(finalHeight - sourceHeight); } break; } } - requestedSize.SetWidth( finalWidth ); - requestedSize.SetHeight( finalHeight ); + requestedSize.SetWidth(finalWidth); + requestedSize.SetHeight(finalHeight); } /** * @brief Construct a pixel buffer object from a copy of the pixel array passed in. */ -Dali::Devel::PixelBuffer MakePixelBuffer( const uint8_t * const pixels, Pixel::Format pixelFormat, unsigned int width, unsigned int height ) +Dali::Devel::PixelBuffer MakePixelBuffer(const uint8_t* const pixels, Pixel::Format pixelFormat, unsigned int width, unsigned int height) { - DALI_ASSERT_DEBUG( pixels && "Null bitmap buffer to copy." ); + DALI_ASSERT_DEBUG(pixels && "Null bitmap buffer to copy."); // Allocate a pixel buffer to hold the image passed in: - auto newBitmap = Dali::Devel::PixelBuffer::New( width, height, pixelFormat ); + auto newBitmap = Dali::Devel::PixelBuffer::New(width, height, pixelFormat); // Copy over the pixels from the downscaled image that was generated in-place in the pixel buffer of the input bitmap: - memcpy( newBitmap.GetBuffer(), pixels, width * height * Pixel::GetBytesPerPixel( pixelFormat ) ); + memcpy(newBitmap.GetBuffer(), pixels, width * height * Pixel::GetBytesPerPixel(pixelFormat)); return newBitmap; } @@ -440,62 +437,62 @@ Dali::Devel::PixelBuffer MakePixelBuffer( const uint8_t * const pixels, Pixel::F * @param[in] requestedHeight Height of area to scale image into. Can be zero. * @return Dimensions of area to scale image into after special rules are applied. */ -ImageDimensions CalculateDesiredDimensions( unsigned int bitmapWidth, unsigned int bitmapHeight, unsigned int requestedWidth, unsigned int requestedHeight ) +ImageDimensions CalculateDesiredDimensions(unsigned int bitmapWidth, unsigned int bitmapHeight, unsigned int requestedWidth, unsigned int requestedHeight) { unsigned int maxSize = Dali::GetMaxTextureSize(); // If no dimensions have been requested, default to the source ones: - if( requestedWidth == 0 && requestedHeight == 0 ) + if(requestedWidth == 0 && requestedHeight == 0) { - if( bitmapWidth <= maxSize && bitmapHeight <= maxSize ) + if(bitmapWidth <= maxSize && bitmapHeight <= maxSize) { - return ImageDimensions( bitmapWidth, bitmapHeight ); + return ImageDimensions(bitmapWidth, bitmapHeight); } else { // Calculate the size from the max texture size and the source image aspect ratio - if( bitmapWidth > bitmapHeight ) + if(bitmapWidth > bitmapHeight) { - return ImageDimensions( maxSize, bitmapHeight * maxSize / static_cast< float >( bitmapWidth ) + 0.5f ); + return ImageDimensions(maxSize, bitmapHeight * maxSize / static_cast(bitmapWidth) + 0.5f); } else { - return ImageDimensions( bitmapWidth * maxSize / static_cast< float >( bitmapHeight ) + 0.5f, maxSize ); + return ImageDimensions(bitmapWidth * maxSize / static_cast(bitmapHeight) + 0.5f, maxSize); } } } // If both dimensions have values requested, use them both: - if( requestedWidth != 0 && requestedHeight != 0 ) + if(requestedWidth != 0 && requestedHeight != 0) { - if( requestedWidth <= maxSize && requestedHeight <= maxSize ) + if(requestedWidth <= maxSize && requestedHeight <= maxSize) { - return ImageDimensions( requestedWidth, requestedHeight ); + return ImageDimensions(requestedWidth, requestedHeight); } else { // Calculate the size from the max texture size and the source image aspect ratio - if( requestedWidth > requestedHeight ) + if(requestedWidth > requestedHeight) { - return ImageDimensions( maxSize, requestedHeight * maxSize / static_cast< float >( requestedWidth ) + 0.5f ); + return ImageDimensions(maxSize, requestedHeight * maxSize / static_cast(requestedWidth) + 0.5f); } else { - return ImageDimensions( requestedWidth * maxSize / static_cast< float >( requestedHeight ) + 0.5f, maxSize ); + return ImageDimensions(requestedWidth * maxSize / static_cast(requestedHeight) + 0.5f, maxSize); } } } // Only one of the dimensions has been requested. Calculate the other from // the requested one and the source image aspect ratio: - if( requestedWidth != 0 ) + if(requestedWidth != 0) { - requestedWidth = std::min( requestedWidth, maxSize ); - return ImageDimensions( requestedWidth, bitmapHeight / float(bitmapWidth) * requestedWidth + 0.5f ); + requestedWidth = std::min(requestedWidth, maxSize); + return ImageDimensions(requestedWidth, bitmapHeight / float(bitmapWidth) * requestedWidth + 0.5f); } - requestedHeight = std::min( requestedHeight, maxSize ); - return ImageDimensions( bitmapWidth / float(bitmapHeight) * requestedHeight + 0.5f, requestedHeight ); + requestedHeight = std::min(requestedHeight, maxSize); + return ImageDimensions(bitmapWidth / float(bitmapHeight) * requestedHeight + 0.5f, requestedHeight); } /** @@ -515,23 +512,23 @@ ImageDimensions CalculateDesiredDimensions( unsigned int bitmapWidth, unsigned i * * @return Whether the rotation succeded. */ -bool Rotate90( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - uint8_t*& pixelsOut, - unsigned int& widthOut, - unsigned int& heightOut ) +bool Rotate90(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + uint8_t*& pixelsOut, + unsigned int& widthOut, + unsigned int& heightOut) { // The new size of the image. - widthOut = heightIn; + widthOut = heightIn; heightOut = widthIn; // Allocate memory for the rotated buffer. - pixelsOut = static_cast( malloc ( widthOut * heightOut * pixelSize ) ); - if( nullptr == pixelsOut ) + pixelsOut = static_cast(malloc(widthOut * heightOut * pixelSize)); + if(nullptr == pixelsOut) { - widthOut = 0u; + widthOut = 0u; heightOut = 0u; // Return if the memory allocations fails. @@ -539,19 +536,19 @@ bool Rotate90( const uint8_t* const pixelsIn, } // Rotate the buffer. - for( unsigned int y = 0u; y < heightIn; ++y ) + for(unsigned int y = 0u; y < heightIn; ++y) { const unsigned int srcLineIndex = y * widthIn; - const unsigned int dstX = y; - for( unsigned int x = 0u; x < widthIn; ++x ) + const unsigned int dstX = y; + for(unsigned int x = 0u; x < widthIn; ++x) { - const unsigned int dstY = heightOut - x - 1u; - const unsigned int dstIndex = pixelSize * ( dstY * widthOut + dstX ); - const unsigned int srcIndex = pixelSize * ( srcLineIndex + x ); + const unsigned int dstY = heightOut - x - 1u; + const unsigned int dstIndex = pixelSize * (dstY * widthOut + dstX); + const unsigned int srcIndex = pixelSize * (srcLineIndex + x); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( pixelsOut + dstIndex + channel ) = *( pixelsIn + srcIndex + channel ); + *(pixelsOut + dstIndex + channel) = *(pixelsIn + srcIndex + channel); } } } @@ -574,34 +571,34 @@ bool Rotate90( const uint8_t* const pixelsIn, * * @return Whether the rotation succeded. */ -bool Rotate180( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - uint8_t*& pixelsOut ) +bool Rotate180(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + uint8_t*& pixelsOut) { // Allocate memory for the rotated buffer. - pixelsOut = static_cast( malloc ( widthIn * heightIn * pixelSize ) ); - if( nullptr == pixelsOut ) + pixelsOut = static_cast(malloc(widthIn * heightIn * pixelSize)); + if(nullptr == pixelsOut) { // Return if the memory allocations fails. return false; } // Rotate the buffer. - for( unsigned int y = 0u; y < heightIn; ++y ) + for(unsigned int y = 0u; y < heightIn; ++y) { const unsigned int srcLineIndex = y * widthIn; - const unsigned int dstY = heightIn - y - 1u; - for( unsigned int x = 0u; x < widthIn; ++x ) + const unsigned int dstY = heightIn - y - 1u; + for(unsigned int x = 0u; x < widthIn; ++x) { - const unsigned int dstX = widthIn - x - 1u; - const unsigned int dstIndex = pixelSize * ( dstY * widthIn + dstX ); - const unsigned int srcIndex = pixelSize * ( srcLineIndex + x ); + const unsigned int dstX = widthIn - x - 1u; + const unsigned int dstIndex = pixelSize * (dstY * widthIn + dstX); + const unsigned int srcIndex = pixelSize * (srcLineIndex + x); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( pixelsOut + dstIndex + channel ) = *( pixelsIn + srcIndex + channel ); + *(pixelsOut + dstIndex + channel) = *(pixelsIn + srcIndex + channel); } } } @@ -626,23 +623,23 @@ bool Rotate180( const uint8_t* const pixelsIn, * * @return Whether the rotation succeded. */ -bool Rotate270( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - uint8_t*& pixelsOut, - unsigned int& widthOut, - unsigned int& heightOut ) +bool Rotate270(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + uint8_t*& pixelsOut, + unsigned int& widthOut, + unsigned int& heightOut) { // The new size of the image. - widthOut = heightIn; + widthOut = heightIn; heightOut = widthIn; // Allocate memory for the rotated buffer. - pixelsOut = static_cast( malloc ( widthOut * heightOut * pixelSize ) ); - if( nullptr == pixelsOut ) + pixelsOut = static_cast(malloc(widthOut * heightOut * pixelSize)); + if(nullptr == pixelsOut) { - widthOut = 0u; + widthOut = 0u; heightOut = 0u; // Return if the memory allocations fails. @@ -650,19 +647,19 @@ bool Rotate270( const uint8_t* const pixelsIn, } // Rotate the buffer. - for( unsigned int y = 0u; y < heightIn; ++y ) + for(unsigned int y = 0u; y < heightIn; ++y) { const unsigned int srcLineIndex = y * widthIn; - const unsigned int dstX = widthOut - y - 1u; - for( unsigned int x = 0u; x < widthIn; ++x ) + const unsigned int dstX = widthOut - y - 1u; + for(unsigned int x = 0u; x < widthIn; ++x) { - const unsigned int dstY = x; - const unsigned int dstIndex = pixelSize * ( dstY * widthOut + dstX ); - const unsigned int srcIndex = pixelSize * ( srcLineIndex + x ); + const unsigned int dstY = x; + const unsigned int dstIndex = pixelSize * (dstY * widthOut + dstX); + const unsigned int srcIndex = pixelSize * (srcLineIndex + x); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( pixelsOut + dstIndex + channel ) = *( pixelsIn + srcIndex + channel ); + *(pixelsOut + dstIndex + channel) = *(pixelsIn + srcIndex + channel); } } } @@ -685,58 +682,58 @@ bool Rotate270( const uint8_t* const pixelsIn, * @param[in] offset The skew offset. * @param[in] weight The relative weight of right pixel. */ -void HorizontalSkew( const uint8_t* const srcBufferPtr, - int srcWidth, - unsigned int pixelSize, - uint8_t*& dstBufferPtr, - int dstWidth, - unsigned int row, - int offset, - float weight ) +void HorizontalSkew(const uint8_t* const srcBufferPtr, + int srcWidth, + unsigned int pixelSize, + uint8_t*& dstBufferPtr, + int dstWidth, + unsigned int row, + int offset, + float weight) { - if( offset > 0 ) + if(offset > 0) { // Fill gap left of skew with background. - memset( dstBufferPtr + row * pixelSize * dstWidth, 0u, pixelSize * offset ); + memset(dstBufferPtr + row * pixelSize * dstWidth, 0u, pixelSize * offset); } - unsigned char oldLeft[4u] = { 0u, 0u, 0u, 0u }; + unsigned char oldLeft[4u] = {0u, 0u, 0u, 0u}; int i = 0; - for( i = 0u; i < srcWidth; ++i ) + for(i = 0u; i < srcWidth; ++i) { // Loop through row pixels - const unsigned int srcIndex = pixelSize * ( row * srcWidth + i ); + const unsigned int srcIndex = pixelSize * (row * srcWidth + i); - unsigned char src[4u] = { 0u, 0u, 0u, 0u }; - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + unsigned char src[4u] = {0u, 0u, 0u, 0u}; + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - src[channel] = *( srcBufferPtr + srcIndex + channel ); + src[channel] = *(srcBufferPtr + srcIndex + channel); } // Calculate weights - unsigned char left[4u] = { 0u, 0u, 0u, 0u }; - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + unsigned char left[4u] = {0u, 0u, 0u, 0u}; + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - left[channel] = static_cast( static_cast( src[channel] ) * weight ); + left[channel] = static_cast(static_cast(src[channel]) * weight); // Update left over on source - src[channel] -= ( left[channel] - oldLeft[channel] ); + src[channel] -= (left[channel] - oldLeft[channel]); } // Check boundaries - if( ( i + offset >= 0 ) && ( i + offset < dstWidth ) ) + if((i + offset >= 0) && (i + offset < dstWidth)) { - const unsigned int dstIndex = pixelSize * ( row * dstWidth + i + offset ); + const unsigned int dstIndex = pixelSize * (row * dstWidth + i + offset); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( dstBufferPtr + dstIndex + channel ) = src[channel]; + *(dstBufferPtr + dstIndex + channel) = src[channel]; } } // Save leftover for next pixel in scan - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { oldLeft[channel] = left[channel]; } @@ -744,19 +741,19 @@ void HorizontalSkew( const uint8_t* const srcBufferPtr, // Go to rightmost point of skew i += offset; - if( i < dstWidth ) + if(i < dstWidth) { // If still in image bounds, put leftovers there - const unsigned int dstIndex = pixelSize * ( row * dstWidth + i ); + const unsigned int dstIndex = pixelSize * (row * dstWidth + i); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( dstBufferPtr + dstIndex + channel ) = oldLeft[channel]; + *(dstBufferPtr + dstIndex + channel) = oldLeft[channel]; } // Clear to the right of the skewed line with background ++i; - memset( dstBufferPtr + pixelSize * ( row * dstWidth + i ), 0u, pixelSize * ( dstWidth - i ) ); + memset(dstBufferPtr + pixelSize * (row * dstWidth + i), 0u, pixelSize * (dstWidth - i)); } } @@ -777,67 +774,67 @@ void HorizontalSkew( const uint8_t* const srcBufferPtr, * @param[in] offset The skew offset. * @param[in] weight The relative weight of uppeer pixel. */ -void VerticalSkew( const uint8_t* const srcBufferPtr, - int srcWidth, - int srcHeight, - unsigned int pixelSize, - uint8_t*& dstBufferPtr, - int dstWidth, - int dstHeight, - unsigned int column, - int offset, - float weight ) -{ - for( int i = 0; i < offset; ++i ) +void VerticalSkew(const uint8_t* const srcBufferPtr, + int srcWidth, + int srcHeight, + unsigned int pixelSize, + uint8_t*& dstBufferPtr, + int dstWidth, + int dstHeight, + unsigned int column, + int offset, + float weight) +{ + for(int i = 0; i < offset; ++i) { // Fill gap above skew with background - const unsigned int dstIndex = pixelSize * ( i * dstWidth + column ); + const unsigned int dstIndex = pixelSize * (i * dstWidth + column); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( dstBufferPtr + dstIndex + channel ) = 0u; + *(dstBufferPtr + dstIndex + channel) = 0u; } } - unsigned char oldLeft[4u] = { 0u, 0u, 0u, 0u }; + unsigned char oldLeft[4u] = {0u, 0u, 0u, 0u}; int yPos = 0; - int i = 0; - for( i = 0; i < srcHeight; ++i ) + int i = 0; + for(i = 0; i < srcHeight; ++i) { // Loop through column pixels - const unsigned int srcIndex = pixelSize * ( i * srcWidth + column ); + const unsigned int srcIndex = pixelSize * (i * srcWidth + column); - unsigned char src[4u] = { 0u, 0u, 0u, 0u }; - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + unsigned char src[4u] = {0u, 0u, 0u, 0u}; + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - src[channel] = *( srcBufferPtr + srcIndex + channel ); + src[channel] = *(srcBufferPtr + srcIndex + channel); } yPos = i + offset; // Calculate weights - unsigned char left[4u] = { 0u, 0u, 0u, 0u }; - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + unsigned char left[4u] = {0u, 0u, 0u, 0u}; + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - left[channel] = static_cast( static_cast( src[channel] ) * weight ); + left[channel] = static_cast(static_cast(src[channel]) * weight); // Update left over on source - src[channel] -= ( left[channel] - oldLeft[channel] ); + src[channel] -= (left[channel] - oldLeft[channel]); } // Check boundaries - if( ( yPos >= 0 ) && ( yPos < dstHeight ) ) + if((yPos >= 0) && (yPos < dstHeight)) { - const unsigned int dstIndex = pixelSize * ( yPos * dstWidth + column ); + const unsigned int dstIndex = pixelSize * (yPos * dstWidth + column); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( dstBufferPtr + dstIndex + channel ) = src[channel]; + *(dstBufferPtr + dstIndex + channel) = src[channel]; } } // Save leftover for next pixel in scan - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { oldLeft[channel] = left[channel]; } @@ -845,34 +842,34 @@ void VerticalSkew( const uint8_t* const srcBufferPtr, // Go to bottom point of skew i = yPos; - if( i < dstHeight ) + if(i < dstHeight) { // If still in image bounds, put leftovers there - const unsigned int dstIndex = pixelSize * ( i * dstWidth + column ); + const unsigned int dstIndex = pixelSize * (i * dstWidth + column); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( dstBufferPtr + dstIndex + channel ) = oldLeft[channel]; + *(dstBufferPtr + dstIndex + channel) = oldLeft[channel]; } } - while( ++i < dstHeight ) + while(++i < dstHeight) { // Clear below skewed line with background - const unsigned int dstIndex = pixelSize * ( i * dstWidth + column ); + const unsigned int dstIndex = pixelSize * (i * dstWidth + column); - for( unsigned int channel = 0u; channel < pixelSize; ++channel ) + for(unsigned int channel = 0u; channel < pixelSize; ++channel) { - *( dstBufferPtr + dstIndex + channel ) = 0u; + *(dstBufferPtr + dstIndex + channel) = 0u; } } } -} // namespace - unnamed +} // namespace -ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, ImageDimensions requestedDimensions ) +ImageDimensions CalculateDesiredDimensions(ImageDimensions rawDimensions, ImageDimensions requestedDimensions) { - return CalculateDesiredDimensions( rawDimensions.GetWidth(), rawDimensions.GetHeight(), requestedDimensions.GetWidth(), requestedDimensions.GetHeight() ) ; + return CalculateDesiredDimensions(rawDimensions.GetWidth(), rawDimensions.GetHeight(), requestedDimensions.GetWidth(), requestedDimensions.GetHeight()); } /** @@ -895,7 +892,7 @@ ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, Image * @return A new bitmap with the padding and cropping required for fitting mode applied. * If no modification is needed or possible, the passed in bitmap is returned. */ -Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode ); +Dali::Devel::PixelBuffer CropAndPadForFittingMode(Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode); /** * @brief Adds horizontal or vertical borders to the source image. @@ -905,118 +902,118 @@ Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bit * @param[in] targetDimensions The dimensions of the destination image. * @param[in] padDimensions The columns and scanlines to pad with borders. */ -void AddBorders( PixelBuffer *targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions ); +void AddBorders(PixelBuffer* targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions); -Dali::Devel::PixelBuffer ApplyAttributesToBitmap( Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode ) +Dali::Devel::PixelBuffer ApplyAttributesToBitmap(Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode) { - if( bitmap ) + if(bitmap) { // Calculate the desired box, accounting for a possible zero component: - const ImageDimensions desiredDimensions = CalculateDesiredDimensions( bitmap.GetWidth(), bitmap.GetHeight(), dimensions.GetWidth(), dimensions.GetHeight() ); + const ImageDimensions desiredDimensions = CalculateDesiredDimensions(bitmap.GetWidth(), bitmap.GetHeight(), dimensions.GetWidth(), dimensions.GetHeight()); // If a different size than the raw one has been requested, resize the image // maximally using a repeated box filter without making it smaller than the // requested size in either dimension: - bitmap = DownscaleBitmap( bitmap, desiredDimensions, fittingMode, samplingMode ); + bitmap = DownscaleBitmap(bitmap, desiredDimensions, fittingMode, samplingMode); // Cut the bitmap according to the desired width and height so that the // resulting bitmap has the same aspect ratio as the desired dimensions. // Add crop and add borders if necessary depending on fitting mode. - if( bitmap ) + if(bitmap) { - bitmap = CropAndPadForFittingMode( bitmap, desiredDimensions, fittingMode ); + bitmap = CropAndPadForFittingMode(bitmap, desiredDimensions, fittingMode); } } return bitmap; } -Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode ) +Dali::Devel::PixelBuffer CropAndPadForFittingMode(Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode) { - const unsigned int inputWidth = bitmap.GetWidth(); + const unsigned int inputWidth = bitmap.GetWidth(); const unsigned int inputHeight = bitmap.GetHeight(); - if( desiredDimensions.GetWidth() < 1u || desiredDimensions.GetHeight() < 1u ) + if(desiredDimensions.GetWidth() < 1u || desiredDimensions.GetHeight() < 1u) { - DALI_LOG_WARNING( "Image scaling aborted as desired dimensions too small (%u, %u).\n", desiredDimensions.GetWidth(), desiredDimensions.GetHeight() ); + DALI_LOG_WARNING("Image scaling aborted as desired dimensions too small (%u, %u).\n", desiredDimensions.GetWidth(), desiredDimensions.GetHeight()); } - else if( inputWidth != desiredDimensions.GetWidth() || inputHeight != desiredDimensions.GetHeight() ) + else if(inputWidth != desiredDimensions.GetWidth() || inputHeight != desiredDimensions.GetHeight()) { // Calculate any padding or cropping that needs to be done based on the fitting mode. // Note: If the desired size is larger than the original image, the desired size will be // reduced while maintaining the aspect, in order to save unnecessary memory usage. int scanlinesToCrop = 0; - int columnsToCrop = 0; + int columnsToCrop = 0; - CalculateBordersFromFittingMode( ImageDimensions( inputWidth, inputHeight ), fittingMode, desiredDimensions, scanlinesToCrop, columnsToCrop ); + CalculateBordersFromFittingMode(ImageDimensions(inputWidth, inputHeight), fittingMode, desiredDimensions, scanlinesToCrop, columnsToCrop); - unsigned int desiredWidth( desiredDimensions.GetWidth() ); - unsigned int desiredHeight( desiredDimensions.GetHeight() ); + unsigned int desiredWidth(desiredDimensions.GetWidth()); + unsigned int desiredHeight(desiredDimensions.GetHeight()); // Action the changes by making a new bitmap with the central part of the loaded one if required. - if( scanlinesToCrop != 0 || columnsToCrop != 0 ) + if(scanlinesToCrop != 0 || columnsToCrop != 0) { // Split the adding and removing of scanlines and columns into separate variables, // so we can use one piece of generic code to action the changes. unsigned int scanlinesToPad = 0; - unsigned int columnsToPad = 0; - if( scanlinesToCrop < 0 ) + unsigned int columnsToPad = 0; + if(scanlinesToCrop < 0) { - scanlinesToPad = -scanlinesToCrop; + scanlinesToPad = -scanlinesToCrop; scanlinesToCrop = 0; } - if( columnsToCrop < 0 ) + if(columnsToCrop < 0) { - columnsToPad = -columnsToCrop; + columnsToPad = -columnsToCrop; columnsToCrop = 0; } // If there is no filtering, then the final image size can become very large, exit if larger than maximum. - if( ( desiredWidth > MAXIMUM_TARGET_BITMAP_SIZE ) || ( desiredHeight > MAXIMUM_TARGET_BITMAP_SIZE ) || - ( columnsToPad > MAXIMUM_TARGET_BITMAP_SIZE ) || ( scanlinesToPad > MAXIMUM_TARGET_BITMAP_SIZE ) ) + if((desiredWidth > MAXIMUM_TARGET_BITMAP_SIZE) || (desiredHeight > MAXIMUM_TARGET_BITMAP_SIZE) || + (columnsToPad > MAXIMUM_TARGET_BITMAP_SIZE) || (scanlinesToPad > MAXIMUM_TARGET_BITMAP_SIZE)) { - DALI_LOG_WARNING( "Image scaling aborted as final dimensions too large (%u, %u).\n", desiredWidth, desiredHeight ); + DALI_LOG_WARNING("Image scaling aborted as final dimensions too large (%u, %u).\n", desiredWidth, desiredHeight); return bitmap; } // Create new PixelBuffer with the desired size. const auto pixelFormat = bitmap.GetPixelFormat(); - auto croppedBitmap = Devel::PixelBuffer::New( desiredWidth, desiredHeight, pixelFormat ); + auto croppedBitmap = Devel::PixelBuffer::New(desiredWidth, desiredHeight, pixelFormat); // Add some pre-calculated offsets to the bitmap pointers so this is not done within a loop. // The cropping is added to the source pointer, and the padding is added to the destination. - const auto bytesPerPixel = Pixel::GetBytesPerPixel( pixelFormat ); - const PixelBuffer * const sourcePixels = bitmap.GetBuffer() + ( ( ( ( scanlinesToCrop / 2 ) * inputWidth ) + ( columnsToCrop / 2 ) ) * bytesPerPixel ); - PixelBuffer * const targetPixels = croppedBitmap.GetBuffer(); - PixelBuffer * const targetPixelsActive = targetPixels + ( ( ( ( scanlinesToPad / 2 ) * desiredWidth ) + ( columnsToPad / 2 ) ) * bytesPerPixel ); - DALI_ASSERT_DEBUG( sourcePixels && targetPixels ); + const auto bytesPerPixel = Pixel::GetBytesPerPixel(pixelFormat); + const PixelBuffer* const sourcePixels = bitmap.GetBuffer() + ((((scanlinesToCrop / 2) * inputWidth) + (columnsToCrop / 2)) * bytesPerPixel); + PixelBuffer* const targetPixels = croppedBitmap.GetBuffer(); + PixelBuffer* const targetPixelsActive = targetPixels + ((((scanlinesToPad / 2) * desiredWidth) + (columnsToPad / 2)) * bytesPerPixel); + DALI_ASSERT_DEBUG(sourcePixels && targetPixels); // Copy the image data to the new bitmap. // Optimize to a single memcpy if the left and right edges don't need a crop or a pad. - unsigned int outputSpan( desiredWidth * bytesPerPixel ); - if( columnsToCrop == 0 && columnsToPad == 0 ) + unsigned int outputSpan(desiredWidth * bytesPerPixel); + if(columnsToCrop == 0 && columnsToPad == 0) { - memcpy( targetPixelsActive, sourcePixels, ( desiredHeight - scanlinesToPad ) * outputSpan ); + memcpy(targetPixelsActive, sourcePixels, (desiredHeight - scanlinesToPad) * outputSpan); } else { // The width needs to change (due to either a crop or a pad), so we copy a scanline at a time. // Precalculate any constants to optimize the inner loop. - const unsigned int inputSpan( inputWidth * bytesPerPixel ); - const unsigned int copySpan( ( desiredWidth - columnsToPad ) * bytesPerPixel ); - const unsigned int scanlinesToCopy( desiredHeight - scanlinesToPad ); + const unsigned int inputSpan(inputWidth * bytesPerPixel); + const unsigned int copySpan((desiredWidth - columnsToPad) * bytesPerPixel); + const unsigned int scanlinesToCopy(desiredHeight - scanlinesToPad); - for( unsigned int y = 0; y < scanlinesToCopy; ++y ) + for(unsigned int y = 0; y < scanlinesToCopy; ++y) { - memcpy( &targetPixelsActive[ y * outputSpan ], &sourcePixels[ y * inputSpan ], copySpan ); + memcpy(&targetPixelsActive[y * outputSpan], &sourcePixels[y * inputSpan], copySpan); } } // Add vertical or horizontal borders to the final image (if required). - desiredDimensions.SetWidth( desiredWidth ); - desiredDimensions.SetHeight( desiredHeight ); - AddBorders( croppedBitmap.GetBuffer(), bytesPerPixel, desiredDimensions, ImageDimensions( columnsToPad, scanlinesToPad ) ); + desiredDimensions.SetWidth(desiredWidth); + desiredDimensions.SetHeight(desiredHeight); + AddBorders(croppedBitmap.GetBuffer(), bytesPerPixel, desiredDimensions, ImageDimensions(columnsToPad, scanlinesToPad)); // Overwrite the loaded bitmap with the cropped version bitmap = croppedBitmap; } @@ -1025,111 +1022,111 @@ Dali::Devel::PixelBuffer CropAndPadForFittingMode( Dali::Devel::PixelBuffer& bit return bitmap; } -void AddBorders( PixelBuffer *targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions ) +void AddBorders(PixelBuffer* targetPixels, const unsigned int bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions) { // Assign ints for faster access. - unsigned int desiredWidth( targetDimensions.GetWidth() ); - unsigned int desiredHeight( targetDimensions.GetHeight() ); - unsigned int columnsToPad( padDimensions.GetWidth() ); - unsigned int scanlinesToPad( padDimensions.GetHeight() ); - unsigned int outputSpan( desiredWidth * bytesPerPixel ); + unsigned int desiredWidth(targetDimensions.GetWidth()); + unsigned int desiredHeight(targetDimensions.GetHeight()); + unsigned int columnsToPad(padDimensions.GetWidth()); + unsigned int scanlinesToPad(padDimensions.GetHeight()); + unsigned int outputSpan(desiredWidth * bytesPerPixel); // Add letterboxing (symmetrical borders) if needed. - if( scanlinesToPad > 0 ) + if(scanlinesToPad > 0) { // Add a top border. Note: This is (deliberately) rounded down if padding is an odd number. - memset( targetPixels, BORDER_FILL_VALUE, ( scanlinesToPad / 2 ) * outputSpan ); + memset(targetPixels, BORDER_FILL_VALUE, (scanlinesToPad / 2) * outputSpan); // We subtract scanlinesToPad/2 from scanlinesToPad so that we have the correct // offset for odd numbers (as the top border is 1 pixel smaller in these cases. - unsigned int bottomBorderHeight = scanlinesToPad - ( scanlinesToPad / 2 ); + unsigned int bottomBorderHeight = scanlinesToPad - (scanlinesToPad / 2); // Bottom border. - memset( &targetPixels[ ( desiredHeight - bottomBorderHeight ) * outputSpan ], BORDER_FILL_VALUE, bottomBorderHeight * outputSpan ); + memset(&targetPixels[(desiredHeight - bottomBorderHeight) * outputSpan], BORDER_FILL_VALUE, bottomBorderHeight * outputSpan); } - else if( columnsToPad > 0 ) + else if(columnsToPad > 0) { // Add a left and right border. // Left: // Pre-calculate span size outside of loop. - unsigned int leftBorderSpanWidth( ( columnsToPad / 2 ) * bytesPerPixel ); - for( unsigned int y = 0; y < desiredHeight; ++y ) + unsigned int leftBorderSpanWidth((columnsToPad / 2) * bytesPerPixel); + for(unsigned int y = 0; y < desiredHeight; ++y) { - memset( &targetPixels[ y * outputSpan ], BORDER_FILL_VALUE, leftBorderSpanWidth ); + memset(&targetPixels[y * outputSpan], BORDER_FILL_VALUE, leftBorderSpanWidth); } // Right: // Pre-calculate the initial x offset as it is always the same for a small optimization. // We subtract columnsToPad/2 from columnsToPad so that we have the correct // offset for odd numbers (as the left border is 1 pixel smaller in these cases. - unsigned int rightBorderWidth = columnsToPad - ( columnsToPad / 2 ); - PixelBuffer * const destPixelsRightBorder( targetPixels + ( ( desiredWidth - rightBorderWidth ) * bytesPerPixel ) ); - unsigned int rightBorderSpanWidth = rightBorderWidth * bytesPerPixel; + unsigned int rightBorderWidth = columnsToPad - (columnsToPad / 2); + PixelBuffer* const destPixelsRightBorder(targetPixels + ((desiredWidth - rightBorderWidth) * bytesPerPixel)); + unsigned int rightBorderSpanWidth = rightBorderWidth * bytesPerPixel; - for( unsigned int y = 0; y < desiredHeight; ++y ) + for(unsigned int y = 0; y < desiredHeight; ++y) { - memset( &destPixelsRightBorder[ y * outputSpan ], BORDER_FILL_VALUE, rightBorderSpanWidth ); + memset(&destPixelsRightBorder[y * outputSpan], BORDER_FILL_VALUE, rightBorderSpanWidth); } } } -Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap, - ImageDimensions desired, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode ) +Dali::Devel::PixelBuffer DownscaleBitmap(Dali::Devel::PixelBuffer bitmap, + ImageDimensions desired, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode) { // Source dimensions as loaded from resources (e.g. filesystem): auto bitmapWidth = bitmap.GetWidth(); auto bitmapHeight = bitmap.GetHeight(); // Desired dimensions (the rectangle to fit the source image to): - auto desiredWidth = desired.GetWidth(); + auto desiredWidth = desired.GetWidth(); auto desiredHeight = desired.GetHeight(); - Dali::Devel::PixelBuffer outputBitmap { bitmap }; + Dali::Devel::PixelBuffer outputBitmap{bitmap}; // If a different size than the raw one has been requested, resize the image: if( - (desiredWidth > 0.0f) && (desiredHeight > 0.0f) && - ((desiredWidth < bitmapWidth) || (desiredHeight < bitmapHeight)) ) + (desiredWidth > 0.0f) && (desiredHeight > 0.0f) && + ((desiredWidth < bitmapWidth) || (desiredHeight < bitmapHeight))) { auto pixelFormat = bitmap.GetPixelFormat(); // Do the fast power of 2 iterated box filter to get to roughly the right side if the filter mode requests that: unsigned int shrunkWidth = -1, shrunkHeight = -1; - DownscaleInPlacePow2( bitmap.GetBuffer(), pixelFormat, bitmapWidth, bitmapHeight, desiredWidth, desiredHeight, fittingMode, samplingMode, shrunkWidth, shrunkHeight ); + DownscaleInPlacePow2(bitmap.GetBuffer(), pixelFormat, bitmapWidth, bitmapHeight, desiredWidth, desiredHeight, fittingMode, samplingMode, shrunkWidth, shrunkHeight); // Work out the dimensions of the downscaled bitmap, given the scaling mode and desired dimensions: - const ImageDimensions filteredDimensions = FitToScalingMode( ImageDimensions( desiredWidth, desiredHeight ), ImageDimensions( shrunkWidth, shrunkHeight ), fittingMode ); - const unsigned int filteredWidth = filteredDimensions.GetWidth(); - const unsigned int filteredHeight = filteredDimensions.GetHeight(); + const ImageDimensions filteredDimensions = FitToScalingMode(ImageDimensions(desiredWidth, desiredHeight), ImageDimensions(shrunkWidth, shrunkHeight), fittingMode); + const unsigned int filteredWidth = filteredDimensions.GetWidth(); + const unsigned int filteredHeight = filteredDimensions.GetHeight(); // Run a filter to scale down the bitmap if it needs it: bool filtered = false; - if( filteredWidth < shrunkWidth || filteredHeight < shrunkHeight ) + if(filteredWidth < shrunkWidth || filteredHeight < shrunkHeight) { - if( samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR || - samplingMode == SamplingMode::NEAREST || samplingMode == SamplingMode::BOX_THEN_NEAREST ) + if(samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR || + samplingMode == SamplingMode::NEAREST || samplingMode == SamplingMode::BOX_THEN_NEAREST) { - outputBitmap = Dali::Devel::PixelBuffer::New( filteredWidth, filteredHeight, pixelFormat ); + outputBitmap = Dali::Devel::PixelBuffer::New(filteredWidth, filteredHeight, pixelFormat); - if( outputBitmap ) + if(outputBitmap) { - if( samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR ) + if(samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR) { - LinearSample( bitmap.GetBuffer(), ImageDimensions(shrunkWidth, shrunkHeight), pixelFormat, outputBitmap.GetBuffer(), filteredDimensions ); + LinearSample(bitmap.GetBuffer(), ImageDimensions(shrunkWidth, shrunkHeight), pixelFormat, outputBitmap.GetBuffer(), filteredDimensions); } else { - PointSample( bitmap.GetBuffer(), shrunkWidth, shrunkHeight, pixelFormat, outputBitmap.GetBuffer(), filteredWidth, filteredHeight ); + PointSample(bitmap.GetBuffer(), shrunkWidth, shrunkHeight, pixelFormat, outputBitmap.GetBuffer(), filteredWidth, filteredHeight); } filtered = true; } } } // Copy out the 2^x downscaled, box-filtered pixels if no secondary filter (point or linear) was applied: - if( filtered == false && ( shrunkWidth < bitmapWidth || shrunkHeight < bitmapHeight ) ) + if(filtered == false && (shrunkWidth < bitmapWidth || shrunkHeight < bitmapHeight)) { - outputBitmap = MakePixelBuffer( bitmap.GetBuffer(), pixelFormat, shrunkWidth, shrunkHeight ); + outputBitmap = MakePixelBuffer(bitmap.GetBuffer(), pixelFormat, shrunkWidth, shrunkHeight); } } @@ -1146,15 +1143,15 @@ namespace * @param desiredWidth The target width for the downscaling. * @param desiredHeight The target height for the downscaling. */ -bool ContinueScaling( BoxDimensionTest test, unsigned int scaledWidth, unsigned int scaledHeight, unsigned int desiredWidth, unsigned int desiredHeight ) +bool ContinueScaling(BoxDimensionTest test, unsigned int scaledWidth, unsigned int scaledHeight, unsigned int desiredWidth, unsigned int desiredHeight) { - bool keepScaling = false; - const unsigned int nextWidth = scaledWidth >> 1u; - const unsigned int nextHeight = scaledHeight >> 1u; + bool keepScaling = false; + const unsigned int nextWidth = scaledWidth >> 1u; + const unsigned int nextHeight = scaledHeight >> 1u; - if( nextWidth >= 1u && nextHeight >= 1u ) + if(nextWidth >= 1u && nextHeight >= 1u) { - switch( test ) + switch(test) { case BoxDimensionTestEither: { @@ -1193,43 +1190,42 @@ bool ContinueScaling( BoxDimensionTest test, unsigned int scaledWidth, unsigned **/ template< int BYTES_PER_PIXEL, - void (*HalveScanlineInPlace)( unsigned char * const pixels, const unsigned int width ), - void (*AverageScanlines) ( const unsigned char * const scanline1, const unsigned char * const __restrict__ scanline2, unsigned char* const outputScanline, const unsigned int width ) -> -void DownscaleInPlacePow2Generic( unsigned char * const pixels, - const unsigned int inputWidth, - const unsigned int inputHeight, - const unsigned int desiredWidth, - const unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned& outWidth, - unsigned& outHeight ) -{ - if( pixels == 0 ) + void (*HalveScanlineInPlace)(unsigned char* const pixels, const unsigned int width), + void (*AverageScanlines)(const unsigned char* const scanline1, const unsigned char* const __restrict__ scanline2, unsigned char* const outputScanline, const unsigned int width)> +void DownscaleInPlacePow2Generic(unsigned char* const pixels, + const unsigned int inputWidth, + const unsigned int inputHeight, + const unsigned int desiredWidth, + const unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned& outWidth, + unsigned& outHeight) +{ + if(pixels == 0) { return; } - ValidateScalingParameters( inputWidth, inputHeight, desiredWidth, desiredHeight ); + ValidateScalingParameters(inputWidth, inputHeight, desiredWidth, desiredHeight); // Scale the image until it would be smaller than desired, stopping if the // resulting height or width would be less than 1: unsigned int scaledWidth = inputWidth, scaledHeight = inputHeight; - while( ContinueScaling( dimensionTest, scaledWidth, scaledHeight, desiredWidth, desiredHeight ) ) + while(ContinueScaling(dimensionTest, scaledWidth, scaledHeight, desiredWidth, desiredHeight)) { const unsigned int lastWidth = scaledWidth; - scaledWidth >>= 1u; + scaledWidth >>= 1u; scaledHeight >>= 1u; - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Scaling to %u\t%u.\n", scaledWidth, scaledHeight ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Scaling to %u\t%u.\n", scaledWidth, scaledHeight); const unsigned int lastScanlinePair = scaledHeight - 1; // Scale pairs of scanlines until any spare one at the end is dropped: - for( unsigned int y = 0; y <= lastScanlinePair; ++y ) + for(unsigned int y = 0; y <= lastScanlinePair; ++y) { // Scale two scanlines horizontally: - HalveScanlineInPlace( &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL], lastWidth ); - HalveScanlineInPlace( &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL], lastWidth ); + HalveScanlineInPlace(&pixels[y * 2 * lastWidth * BYTES_PER_PIXEL], lastWidth); + HalveScanlineInPlace(&pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL], lastWidth); // Scale vertical pairs of pixels while the last two scanlines are still warm in // the CPU cache(s): @@ -1237,27 +1233,27 @@ void DownscaleInPlacePow2Generic( unsigned char * const pixels, // images but even a 4k wide RGB888 image will use just 24kB of cache (4k pixels // * 3 Bpp * 2 scanlines) for two scanlines on the first iteration. AverageScanlines( - &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL], - &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL], - &pixels[y * scaledWidth * BYTES_PER_PIXEL], - scaledWidth ); + &pixels[y * 2 * lastWidth * BYTES_PER_PIXEL], + &pixels[(y * 2 + 1) * lastWidth * BYTES_PER_PIXEL], + &pixels[y * scaledWidth * BYTES_PER_PIXEL], + scaledWidth); } } ///@note: we could finish off with one of two mutually exclusive passes, one squashing horizontally as far as possible, and the other vertically, if we knew a following cpu point or bilinear filter would restore the desired aspect ratio. - outWidth = scaledWidth; + outWidth = scaledWidth; outHeight = scaledHeight; } -} +} // namespace -void HalveScanlineInPlaceRGB888( unsigned char * const pixels, const unsigned int width ) +void HalveScanlineInPlaceRGB888(unsigned char* const pixels, const unsigned int width) { - DebugAssertScanlineParameters( pixels, width ); + DebugAssertScanlineParameters(pixels, width); - const unsigned int lastPair = EvenDown( width - 2 ); + const unsigned int lastPair = EvenDown(width - 2); - for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel ) + for(unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel) { // Load all the byte pixel components we need: const unsigned int c11 = pixels[pixel * 3]; @@ -1268,51 +1264,51 @@ void HalveScanlineInPlaceRGB888( unsigned char * const pixels, const unsigned in const unsigned int c23 = pixels[pixel * 3 + 5]; // Save the averaged byte pixel components: - pixels[outPixel * 3] = static_cast( AverageComponent( c11, c21 ) ); - pixels[outPixel * 3 + 1] = static_cast( AverageComponent( c12, c22 ) ); - pixels[outPixel * 3 + 2] = static_cast( AverageComponent( c13, c23 ) ); + pixels[outPixel * 3] = static_cast(AverageComponent(c11, c21)); + pixels[outPixel * 3 + 1] = static_cast(AverageComponent(c12, c22)); + pixels[outPixel * 3 + 2] = static_cast(AverageComponent(c13, c23)); } } -void HalveScanlineInPlaceRGBA8888( unsigned char * const pixels, const unsigned int width ) +void HalveScanlineInPlaceRGBA8888(unsigned char* const pixels, const unsigned int width) { - DebugAssertScanlineParameters( pixels, width ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." ); + DebugAssertScanlineParameters(pixels, width); + DALI_ASSERT_DEBUG(((reinterpret_cast(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms."); uint32_t* const alignedPixels = reinterpret_cast(pixels); - const unsigned int lastPair = EvenDown( width - 2 ); + const unsigned int lastPair = EvenDown(width - 2); - for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel ) + for(unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel) { - const uint32_t averaged = AveragePixelRGBA8888( alignedPixels[pixel], alignedPixels[pixel + 1] ); + const uint32_t averaged = AveragePixelRGBA8888(alignedPixels[pixel], alignedPixels[pixel + 1]); alignedPixels[outPixel] = averaged; } } -void HalveScanlineInPlaceRGB565( unsigned char * pixels, unsigned int width ) +void HalveScanlineInPlaceRGB565(unsigned char* pixels, unsigned int width) { - DebugAssertScanlineParameters( pixels, width ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(pixels) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." ); + DebugAssertScanlineParameters(pixels, width); + DALI_ASSERT_DEBUG(((reinterpret_cast(pixels) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms."); uint16_t* const alignedPixels = reinterpret_cast(pixels); - const unsigned int lastPair = EvenDown( width - 2 ); + const unsigned int lastPair = EvenDown(width - 2); - for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel ) + for(unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel) { - const uint32_t averaged = AveragePixelRGB565( alignedPixels[pixel], alignedPixels[pixel + 1] ); + const uint32_t averaged = AveragePixelRGB565(alignedPixels[pixel], alignedPixels[pixel + 1]); alignedPixels[outPixel] = averaged; } } -void HalveScanlineInPlace2Bytes( unsigned char * const pixels, const unsigned int width ) +void HalveScanlineInPlace2Bytes(unsigned char* const pixels, const unsigned int width) { - DebugAssertScanlineParameters( pixels, width ); + DebugAssertScanlineParameters(pixels, width); - const unsigned int lastPair = EvenDown( width - 2 ); + const unsigned int lastPair = EvenDown(width - 2); - for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel ) + for(unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel) { // Load all the byte pixel components we need: const unsigned int c11 = pixels[pixel * 2]; @@ -1321,25 +1317,25 @@ void HalveScanlineInPlace2Bytes( unsigned char * const pixels, const unsigned in const unsigned int c22 = pixels[pixel * 2 + 3]; // Save the averaged byte pixel components: - pixels[outPixel * 2] = static_cast( AverageComponent( c11, c21 ) ); - pixels[outPixel * 2 + 1] = static_cast( AverageComponent( c12, c22 ) ); + pixels[outPixel * 2] = static_cast(AverageComponent(c11, c21)); + pixels[outPixel * 2 + 1] = static_cast(AverageComponent(c12, c22)); } } -void HalveScanlineInPlace1Byte( unsigned char * const pixels, const unsigned int width ) +void HalveScanlineInPlace1Byte(unsigned char* const pixels, const unsigned int width) { - DebugAssertScanlineParameters( pixels, width ); + DebugAssertScanlineParameters(pixels, width); - const unsigned int lastPair = EvenDown( width - 2 ); + const unsigned int lastPair = EvenDown(width - 2); - for( unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel ) + for(unsigned int pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel) { // Load all the byte pixel components we need: const unsigned int c1 = pixels[pixel]; const unsigned int c2 = pixels[pixel + 1]; // Save the averaged byte pixel component: - pixels[outPixel] = static_cast( AverageComponent( c1, c2 ) ); + pixels[outPixel] = static_cast(AverageComponent(c1, c2)); } } @@ -1347,174 +1343,174 @@ void HalveScanlineInPlace1Byte( unsigned char * const pixels, const unsigned int * @ToDo: Optimise for ARM using a 4 bytes at a time loop wrapped around the single ARMV6 instruction: UHADD8 R4, R0, R5. Note, this is not neon. It runs in the normal integer pipeline so there is no downside like a stall moving between integer and copro, or extra power for clocking-up the idle copro. * if (widthInComponents >= 7) { word32* aligned1 = scanline1 + 3 & 3; word32* aligned1_end = scanline1 + widthInPixels & 3; while(aligned1 < aligned1_end) { UHADD8 *aligned1++, *aligned2++, *alignedoutput++ } .. + 0 to 3 spare pixels at each end. */ -void AverageScanlines1( const unsigned char * const scanline1, - const unsigned char * const __restrict__ scanline2, - unsigned char* const outputScanline, - const unsigned int width ) +void AverageScanlines1(const unsigned char* const scanline1, + const unsigned char* const __restrict__ scanline2, + unsigned char* const outputScanline, + const unsigned int width) { - DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width ); + DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width); - for( unsigned int component = 0; component < width; ++component ) + for(unsigned int component = 0; component < width; ++component) { - outputScanline[component] = static_cast( AverageComponent( scanline1[component], scanline2[component] ) ); + outputScanline[component] = static_cast(AverageComponent(scanline1[component], scanline2[component])); } } -void AverageScanlines2( const unsigned char * const scanline1, - const unsigned char * const __restrict__ scanline2, - unsigned char* const outputScanline, - const unsigned int width ) +void AverageScanlines2(const unsigned char* const scanline1, + const unsigned char* const __restrict__ scanline2, + unsigned char* const outputScanline, + const unsigned int width) { - DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 2 ); + DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 2); - for( unsigned int component = 0; component < width * 2; ++component ) + for(unsigned int component = 0; component < width * 2; ++component) { - outputScanline[component] = static_cast( AverageComponent( scanline1[component], scanline2[component] ) ); + outputScanline[component] = static_cast(AverageComponent(scanline1[component], scanline2[component])); } } -void AverageScanlines3( const unsigned char * const scanline1, - const unsigned char * const __restrict__ scanline2, - unsigned char* const outputScanline, - const unsigned int width ) +void AverageScanlines3(const unsigned char* const scanline1, + const unsigned char* const __restrict__ scanline2, + unsigned char* const outputScanline, + const unsigned int width) { - DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 3 ); + DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 3); - for( unsigned int component = 0; component < width * 3; ++component ) + for(unsigned int component = 0; component < width * 3; ++component) { - outputScanline[component] = static_cast( AverageComponent( scanline1[component], scanline2[component] ) ); + outputScanline[component] = static_cast(AverageComponent(scanline1[component], scanline2[component])); } } -void AverageScanlinesRGBA8888( const unsigned char * const scanline1, - const unsigned char * const __restrict__ scanline2, - unsigned char * const outputScanline, - const unsigned int width ) +void AverageScanlinesRGBA8888(const unsigned char* const scanline1, + const unsigned char* const __restrict__ scanline2, + unsigned char* const outputScanline, + const unsigned int width) { - DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 4 ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(scanline1) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(scanline2) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(outputScanline) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." ); + DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 4); + DALI_ASSERT_DEBUG(((reinterpret_cast(scanline1) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms."); + DALI_ASSERT_DEBUG(((reinterpret_cast(scanline2) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms."); + DALI_ASSERT_DEBUG(((reinterpret_cast(outputScanline) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms."); const uint32_t* const alignedScanline1 = reinterpret_cast(scanline1); const uint32_t* const alignedScanline2 = reinterpret_cast(scanline2); - uint32_t* const alignedOutput = reinterpret_cast(outputScanline); + uint32_t* const alignedOutput = reinterpret_cast(outputScanline); - for( unsigned int pixel = 0; pixel < width; ++pixel ) + for(unsigned int pixel = 0; pixel < width; ++pixel) { - alignedOutput[pixel] = AveragePixelRGBA8888( alignedScanline1[pixel], alignedScanline2[pixel] ); + alignedOutput[pixel] = AveragePixelRGBA8888(alignedScanline1[pixel], alignedScanline2[pixel]); } } -void AverageScanlinesRGB565( const unsigned char * const scanline1, - const unsigned char * const __restrict__ scanline2, - unsigned char * const outputScanline, - const unsigned int width ) +void AverageScanlinesRGB565(const unsigned char* const scanline1, + const unsigned char* const __restrict__ scanline2, + unsigned char* const outputScanline, + const unsigned int width) { - DebugAssertDualScanlineParameters( scanline1, scanline2, outputScanline, width * 2 ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(scanline1) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(scanline2) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." ); - DALI_ASSERT_DEBUG( ((reinterpret_cast(outputScanline) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms." ); + DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 2); + DALI_ASSERT_DEBUG(((reinterpret_cast(scanline1) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms."); + DALI_ASSERT_DEBUG(((reinterpret_cast(scanline2) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms."); + DALI_ASSERT_DEBUG(((reinterpret_cast(outputScanline) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms."); const uint16_t* const alignedScanline1 = reinterpret_cast(scanline1); const uint16_t* const alignedScanline2 = reinterpret_cast(scanline2); - uint16_t* const alignedOutput = reinterpret_cast(outputScanline); + uint16_t* const alignedOutput = reinterpret_cast(outputScanline); - for( unsigned int pixel = 0; pixel < width; ++pixel ) + for(unsigned int pixel = 0; pixel < width; ++pixel) { - alignedOutput[pixel] = AveragePixelRGB565( alignedScanline1[pixel], alignedScanline2[pixel] ); + alignedOutput[pixel] = AveragePixelRGB565(alignedScanline1[pixel], alignedScanline2[pixel]); } } /// Dispatch to pixel format appropriate box filter downscaling functions. -void DownscaleInPlacePow2( unsigned char * const pixels, - Pixel::Format pixelFormat, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - unsigned& outWidth, - unsigned& outHeight ) -{ - outWidth = inputWidth; +void DownscaleInPlacePow2(unsigned char* const pixels, + Pixel::Format pixelFormat, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + unsigned& outWidth, + unsigned& outHeight) +{ + outWidth = inputWidth; outHeight = inputHeight; // Perform power of 2 iterated 4:1 box filtering if the requested filter mode requires it: - if( samplingMode == SamplingMode::BOX || samplingMode == SamplingMode::BOX_THEN_NEAREST || samplingMode == SamplingMode::BOX_THEN_LINEAR ) + if(samplingMode == SamplingMode::BOX || samplingMode == SamplingMode::BOX_THEN_NEAREST || samplingMode == SamplingMode::BOX_THEN_LINEAR) { // Check the pixel format is one that is supported: - if( pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 ) + if(pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8) { - const BoxDimensionTest dimensionTest = DimensionTestForScalingMode( fittingMode ); + const BoxDimensionTest dimensionTest = DimensionTestForScalingMode(fittingMode); - if( pixelFormat == Pixel::RGBA8888 ) + if(pixelFormat == Pixel::RGBA8888) { - Internal::Platform::DownscaleInPlacePow2RGBA8888( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + Internal::Platform::DownscaleInPlacePow2RGBA8888(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } - else if( pixelFormat == Pixel::RGB888 ) + else if(pixelFormat == Pixel::RGB888) { - Internal::Platform::DownscaleInPlacePow2RGB888( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + Internal::Platform::DownscaleInPlacePow2RGB888(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } - else if( pixelFormat == Pixel::RGB565 ) + else if(pixelFormat == Pixel::RGB565) { - Internal::Platform::DownscaleInPlacePow2RGB565( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + Internal::Platform::DownscaleInPlacePow2RGB565(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } - else if( pixelFormat == Pixel::LA88 ) + else if(pixelFormat == Pixel::LA88) { - Internal::Platform::DownscaleInPlacePow2ComponentPair( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + Internal::Platform::DownscaleInPlacePow2ComponentPair(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } - else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 ) + else if(pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8) { - Internal::Platform::DownscaleInPlacePow2SingleBytePerPixel( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + Internal::Platform::DownscaleInPlacePow2SingleBytePerPixel(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } else { - DALI_ASSERT_DEBUG( false && "Inner branch conditions don't match outer branch." ); + DALI_ASSERT_DEBUG(false && "Inner branch conditions don't match outer branch."); } } } else { - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not shrunk: unsupported pixel format: %u.\n", unsigned(pixelFormat) ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not shrunk: unsupported pixel format: %u.\n", unsigned(pixelFormat)); } } -void DownscaleInPlacePow2RGB888( unsigned char *pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned& outWidth, - unsigned& outHeight ) +void DownscaleInPlacePow2RGB888(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned& outWidth, + unsigned& outHeight) { - DownscaleInPlacePow2Generic<3, HalveScanlineInPlaceRGB888, AverageScanlines3>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + DownscaleInPlacePow2Generic<3, HalveScanlineInPlaceRGB888, AverageScanlines3>(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } -void DownscaleInPlacePow2RGBA8888( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned& outWidth, - unsigned& outHeight ) +void DownscaleInPlacePow2RGBA8888(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned& outWidth, + unsigned& outHeight) { - DALI_ASSERT_DEBUG( ((reinterpret_cast(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms." ); - DownscaleInPlacePow2Generic<4, HalveScanlineInPlaceRGBA8888, AverageScanlinesRGBA8888>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + DALI_ASSERT_DEBUG(((reinterpret_cast(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms."); + DownscaleInPlacePow2Generic<4, HalveScanlineInPlaceRGBA8888, AverageScanlinesRGBA8888>(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } -void DownscaleInPlacePow2RGB565( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ) +void DownscaleInPlacePow2RGB565(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight) { - DownscaleInPlacePow2Generic<2, HalveScanlineInPlaceRGB565, AverageScanlinesRGB565>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + DownscaleInPlacePow2Generic<2, HalveScanlineInPlaceRGB565, AverageScanlinesRGB565>(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } /** @@ -1522,33 +1518,32 @@ void DownscaleInPlacePow2RGB565( unsigned char * pixels, * * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565. */ -void DownscaleInPlacePow2ComponentPair( unsigned char *pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned& outWidth, - unsigned& outHeight ) +void DownscaleInPlacePow2ComponentPair(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned& outWidth, + unsigned& outHeight) { - DownscaleInPlacePow2Generic<2, HalveScanlineInPlace2Bytes, AverageScanlines2>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + DownscaleInPlacePow2Generic<2, HalveScanlineInPlace2Bytes, AverageScanlines2>(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } -void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ) +void DownscaleInPlacePow2SingleBytePerPixel(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight) { - DownscaleInPlacePow2Generic<1, HalveScanlineInPlace1Byte, AverageScanlines1>( pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight ); + DownscaleInPlacePow2Generic<1, HalveScanlineInPlace1Byte, AverageScanlines1>(pixels, inputWidth, inputHeight, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight); } namespace { - /** * @brief Point sample an image to a new resolution (like GL_NEAREST). * @@ -1557,124 +1552,124 @@ namespace * functions below which are exported to rest of module. */ template -inline void PointSampleAddressablePixels( const uint8_t * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - uint8_t * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ) +inline void PointSampleAddressablePixels(const uint8_t* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + uint8_t* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight) { - DALI_ASSERT_DEBUG( ((desiredWidth <= inputWidth && desiredHeight <= inputHeight) || - outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL) || outPixels <= inPixels - desiredWidth * desiredHeight * sizeof(PIXEL)) && - "The input and output buffers must not overlap for an upscaling."); - DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( inPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." ); - DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( outPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." ); + DALI_ASSERT_DEBUG(((desiredWidth <= inputWidth && desiredHeight <= inputHeight) || + outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL) || outPixels <= inPixels - desiredWidth * desiredHeight * sizeof(PIXEL)) && + "The input and output buffers must not overlap for an upscaling."); + DALI_ASSERT_DEBUG(reinterpret_cast(inPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)."); + DALI_ASSERT_DEBUG(reinterpret_cast(outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)."); - if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u ) + if(inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u) { return; } - const PIXEL* const inAligned = reinterpret_cast(inPixels); + const PIXEL* const inAligned = reinterpret_cast(inPixels); PIXEL* const outAligned = reinterpret_cast(outPixels); - const unsigned int deltaX = (inputWidth << 16u) / desiredWidth; - const unsigned int deltaY = (inputHeight << 16u) / desiredHeight; + const unsigned int deltaX = (inputWidth << 16u) / desiredWidth; + const unsigned int deltaY = (inputHeight << 16u) / desiredHeight; unsigned int inY = 0; - for( unsigned int outY = 0; outY < desiredHeight; ++outY ) + for(unsigned int outY = 0; outY < desiredHeight; ++outY) { // Round fixed point y coordinate to nearest integer: - const unsigned int integerY = (inY + (1u << 15u)) >> 16u; - const PIXEL* const inScanline = &inAligned[inputWidth * integerY]; - PIXEL* const outScanline = &outAligned[desiredWidth * outY]; + const unsigned int integerY = (inY + (1u << 15u)) >> 16u; + const PIXEL* const inScanline = &inAligned[inputWidth * integerY]; + PIXEL* const outScanline = &outAligned[desiredWidth * outY]; - DALI_ASSERT_DEBUG( integerY < inputHeight ); - DALI_ASSERT_DEBUG( reinterpret_cast(inScanline) < ( inPixels + inputWidth * inputHeight * sizeof(PIXEL) ) ); - DALI_ASSERT_DEBUG( reinterpret_cast(outScanline) < ( outPixels + desiredWidth * desiredHeight * sizeof(PIXEL) ) ); + DALI_ASSERT_DEBUG(integerY < inputHeight); + DALI_ASSERT_DEBUG(reinterpret_cast(inScanline) < (inPixels + inputWidth * inputHeight * sizeof(PIXEL))); + DALI_ASSERT_DEBUG(reinterpret_cast(outScanline) < (outPixels + desiredWidth * desiredHeight * sizeof(PIXEL))); unsigned int inX = 0; - for( unsigned int outX = 0; outX < desiredWidth; ++outX ) + for(unsigned int outX = 0; outX < desiredWidth; ++outX) { // Round the fixed-point x coordinate to an integer: - const unsigned int integerX = (inX + (1u << 15u)) >> 16u; + const unsigned int integerX = (inX + (1u << 15u)) >> 16u; const PIXEL* const inPixelAddress = &inScanline[integerX]; - const PIXEL pixel = *inPixelAddress; - outScanline[outX] = pixel; + const PIXEL pixel = *inPixelAddress; + outScanline[outX] = pixel; inX += deltaX; } inY += deltaY; } } -} +} // namespace // RGBA8888 -void PointSample4BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ) +void PointSample4BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight) { - PointSampleAddressablePixels( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSampleAddressablePixels(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } // RGB565, LA88 -void PointSample2BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ) +void PointSample2BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight) { - PointSampleAddressablePixels( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSampleAddressablePixels(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } // L8, A8 -void PointSample1BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ) +void PointSample1BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight) { - PointSampleAddressablePixels( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSampleAddressablePixels(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } /* RGB888 * RGB888 is a special case as its pixels are not aligned addressable units. */ -void PointSample3BPP( const uint8_t * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - uint8_t * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ) +void PointSample3BPP(const uint8_t* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + uint8_t* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight) { - if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u ) + if(inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u) { return; } const unsigned int BYTES_PER_PIXEL = 3; // Generate fixed-point 16.16 deltas in input image coordinates: - const unsigned int deltaX = (inputWidth << 16u) / desiredWidth; + const unsigned int deltaX = (inputWidth << 16u) / desiredWidth; const unsigned int deltaY = (inputHeight << 16u) / desiredHeight; // Step through output image in whole integer pixel steps while tracking the // corresponding locations in the input image using 16.16 fixed-point // coordinates: unsigned int inY = 0; //< 16.16 fixed-point input image y-coord. - for( unsigned int outY = 0; outY < desiredHeight; ++outY ) + for(unsigned int outY = 0; outY < desiredHeight; ++outY) { - const unsigned int integerY = (inY + (1u << 15u)) >> 16u; - const uint8_t* const inScanline = &inPixels[inputWidth * integerY * BYTES_PER_PIXEL]; - uint8_t* const outScanline = &outPixels[desiredWidth * outY * BYTES_PER_PIXEL]; - unsigned int inX = 0; //< 16.16 fixed-point input image x-coord. + const unsigned int integerY = (inY + (1u << 15u)) >> 16u; + const uint8_t* const inScanline = &inPixels[inputWidth * integerY * BYTES_PER_PIXEL]; + uint8_t* const outScanline = &outPixels[desiredWidth * outY * BYTES_PER_PIXEL]; + unsigned int inX = 0; //< 16.16 fixed-point input image x-coord. - for( unsigned int outX = 0; outX < desiredWidth * BYTES_PER_PIXEL; outX += BYTES_PER_PIXEL ) + for(unsigned int outX = 0; outX < desiredWidth * BYTES_PER_PIXEL; outX += BYTES_PER_PIXEL) { // Round the fixed-point input coordinate to the address of the input pixel to sample: - const unsigned int integerX = (inX + (1u << 15u)) >> 16u; + const unsigned int integerX = (inX + (1u << 15u)) >> 16u; const uint8_t* const inPixelAddress = &inScanline[integerX * BYTES_PER_PIXEL]; // Issue loads for all pixel color components up-front: @@ -1684,9 +1679,9 @@ void PointSample3BPP( const uint8_t * inPixels, ///@ToDo: Optimise - Benchmark one 32bit load that will be unaligned 2/3 of the time + 3 rotate and masks, versus these three aligned byte loads, versus using an RGB packed, aligned(1) struct and letting compiler pick a strategy. // Output the pixel components: - outScanline[outX] = static_cast( c0 ); - outScanline[outX + 1] = static_cast( c1 ); - outScanline[outX + 2] = static_cast( c2 ); + outScanline[outX] = static_cast(c0); + outScanline[outX + 1] = static_cast(c1); + outScanline[outX + 2] = static_cast(c2); // Increment the fixed-point input coordinate: inX += deltaX; @@ -1697,41 +1692,41 @@ void PointSample3BPP( const uint8_t * inPixels, } // Dispatch to a format-appropriate point sampling function: -void PointSample( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - Pixel::Format pixelFormat, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ) +void PointSample(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + Pixel::Format pixelFormat, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight) { // Check the pixel format is one that is supported: - if( pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 ) + if(pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8) { - if( pixelFormat == Pixel::RGB888 ) + if(pixelFormat == Pixel::RGB888) { - PointSample3BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSample3BPP(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } - else if( pixelFormat == Pixel::RGBA8888 ) + else if(pixelFormat == Pixel::RGBA8888) { - PointSample4BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSample4BPP(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } - else if( pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 ) + else if(pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88) { - PointSample2BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSample2BPP(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } - else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 ) + else if(pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8) { - PointSample1BPP( inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight ); + PointSample1BPP(inPixels, inputWidth, inputHeight, outPixels, desiredWidth, desiredHeight); } else { - DALI_ASSERT_DEBUG( 0 == "Inner branch conditions don't match outer branch." ); + DALI_ASSERT_DEBUG(0 == "Inner branch conditions don't match outer branch."); } } else { - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not point sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat) ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not point sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat)); } } @@ -1739,49 +1734,48 @@ void PointSample( const unsigned char * inPixels, namespace { - /** @brief Blend 4 pixels together using horizontal and vertical weights. */ -inline uint8_t BilinearFilter1BPPByte( uint8_t tl, uint8_t tr, uint8_t bl, uint8_t br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ) +inline uint8_t BilinearFilter1BPPByte(uint8_t tl, uint8_t tr, uint8_t bl, uint8_t br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical) { - return static_cast( BilinearFilter1Component( tl, tr, bl, br, fractBlendHorizontal, fractBlendVertical ) ); + return static_cast(BilinearFilter1Component(tl, tr, bl, br, fractBlendHorizontal, fractBlendVertical)); } /** @copydoc BilinearFilter1BPPByte */ -inline Pixel2Bytes BilinearFilter2Bytes( Pixel2Bytes tl, Pixel2Bytes tr, Pixel2Bytes bl, Pixel2Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ) +inline Pixel2Bytes BilinearFilter2Bytes(Pixel2Bytes tl, Pixel2Bytes tr, Pixel2Bytes bl, Pixel2Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical) { Pixel2Bytes pixel; - pixel.l = static_cast( BilinearFilter1Component( tl.l, tr.l, bl.l, br.l, fractBlendHorizontal, fractBlendVertical ) ); - pixel.a = static_cast( BilinearFilter1Component( tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical ) ); + pixel.l = static_cast(BilinearFilter1Component(tl.l, tr.l, bl.l, br.l, fractBlendHorizontal, fractBlendVertical)); + pixel.a = static_cast(BilinearFilter1Component(tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical)); return pixel; } /** @copydoc BilinearFilter1BPPByte */ -inline Pixel3Bytes BilinearFilterRGB888( Pixel3Bytes tl, Pixel3Bytes tr, Pixel3Bytes bl, Pixel3Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ) +inline Pixel3Bytes BilinearFilterRGB888(Pixel3Bytes tl, Pixel3Bytes tr, Pixel3Bytes bl, Pixel3Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical) { Pixel3Bytes pixel; - pixel.r = static_cast( BilinearFilter1Component( tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical ) ); - pixel.g = static_cast( BilinearFilter1Component( tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical ) ); - pixel.b = static_cast( BilinearFilter1Component( tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical ) ); + pixel.r = static_cast(BilinearFilter1Component(tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical)); + pixel.g = static_cast(BilinearFilter1Component(tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical)); + pixel.b = static_cast(BilinearFilter1Component(tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical)); return pixel; } /** @copydoc BilinearFilter1BPPByte */ -inline PixelRGB565 BilinearFilterRGB565( PixelRGB565 tl, PixelRGB565 tr, PixelRGB565 bl, PixelRGB565 br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ) +inline PixelRGB565 BilinearFilterRGB565(PixelRGB565 tl, PixelRGB565 tr, PixelRGB565 bl, PixelRGB565 br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical) { - const PixelRGB565 pixel = static_cast( (BilinearFilter1Component( tl >> 11u, tr >> 11u, bl >> 11u, br >> 11u, fractBlendHorizontal, fractBlendVertical ) << 11u) + - (BilinearFilter1Component( (tl >> 5u) & 63u, (tr >> 5u) & 63u, (bl >> 5u) & 63u, (br >> 5u) & 63u, fractBlendHorizontal, fractBlendVertical ) << 5u) + - BilinearFilter1Component( tl & 31u, tr & 31u, bl & 31u, br & 31u, fractBlendHorizontal, fractBlendVertical ) ); + const PixelRGB565 pixel = static_cast((BilinearFilter1Component(tl >> 11u, tr >> 11u, bl >> 11u, br >> 11u, fractBlendHorizontal, fractBlendVertical) << 11u) + + (BilinearFilter1Component((tl >> 5u) & 63u, (tr >> 5u) & 63u, (bl >> 5u) & 63u, (br >> 5u) & 63u, fractBlendHorizontal, fractBlendVertical) << 5u) + + BilinearFilter1Component(tl & 31u, tr & 31u, bl & 31u, br & 31u, fractBlendHorizontal, fractBlendVertical)); return pixel; } /** @copydoc BilinearFilter1BPPByte */ -inline Pixel4Bytes BilinearFilter4Bytes( Pixel4Bytes tl, Pixel4Bytes tr, Pixel4Bytes bl, Pixel4Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ) +inline Pixel4Bytes BilinearFilter4Bytes(Pixel4Bytes tl, Pixel4Bytes tr, Pixel4Bytes bl, Pixel4Bytes br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical) { Pixel4Bytes pixel; - pixel.r = static_cast( BilinearFilter1Component( tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical ) ); - pixel.g = static_cast( BilinearFilter1Component( tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical ) ); - pixel.b = static_cast( BilinearFilter1Component( tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical ) ); - pixel.a = static_cast( BilinearFilter1Component( tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical ) ); + pixel.r = static_cast(BilinearFilter1Component(tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical)); + pixel.g = static_cast(BilinearFilter1Component(tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical)); + pixel.b = static_cast(BilinearFilter1Component(tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical)); + pixel.a = static_cast(BilinearFilter1Component(tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical)); return pixel; } @@ -1792,55 +1786,54 @@ inline Pixel4Bytes BilinearFilter4Bytes( Pixel4Bytes tl, Pixel4Bytes tr, Pixel4B */ template< typename PIXEL, - PIXEL (*BilinearFilter) ( PIXEL tl, PIXEL tr, PIXEL bl, PIXEL br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ), - bool DEBUG_ASSERT_ALIGNMENT -> -inline void LinearSampleGeneric( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) -{ - const unsigned int inputWidth = inputDimensions.GetWidth(); - const unsigned int inputHeight = inputDimensions.GetHeight(); - const unsigned int desiredWidth = desiredDimensions.GetWidth(); + PIXEL (*BilinearFilter)(PIXEL tl, PIXEL tr, PIXEL bl, PIXEL br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical), + bool DEBUG_ASSERT_ALIGNMENT> +inline void LinearSampleGeneric(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) +{ + const unsigned int inputWidth = inputDimensions.GetWidth(); + const unsigned int inputHeight = inputDimensions.GetHeight(); + const unsigned int desiredWidth = desiredDimensions.GetWidth(); const unsigned int desiredHeight = desiredDimensions.GetHeight(); - DALI_ASSERT_DEBUG( ((outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL)) || - (inPixels >= outPixels + desiredWidth * desiredHeight * sizeof(PIXEL))) && - "Input and output buffers cannot overlap."); - if( DEBUG_ASSERT_ALIGNMENT ) + DALI_ASSERT_DEBUG(((outPixels >= inPixels + inputWidth * inputHeight * sizeof(PIXEL)) || + (inPixels >= outPixels + desiredWidth * desiredHeight * sizeof(PIXEL))) && + "Input and output buffers cannot overlap."); + if(DEBUG_ASSERT_ALIGNMENT) { - DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( inPixels ) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." ); - DALI_ASSERT_DEBUG( reinterpret_cast< uint64_t >( outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)." ); + DALI_ASSERT_DEBUG(reinterpret_cast(inPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)."); + DALI_ASSERT_DEBUG(reinterpret_cast(outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...)."); } - if( inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u ) + if(inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u) { return; } - const PIXEL* const inAligned = reinterpret_cast(inPixels); + const PIXEL* const inAligned = reinterpret_cast(inPixels); PIXEL* const outAligned = reinterpret_cast(outPixels); - const unsigned int deltaX = (inputWidth << 16u) / desiredWidth; - const unsigned int deltaY = (inputHeight << 16u) / desiredHeight; + const unsigned int deltaX = (inputWidth << 16u) / desiredWidth; + const unsigned int deltaY = (inputHeight << 16u) / desiredHeight; unsigned int inY = 0; - for( unsigned int outY = 0; outY < desiredHeight; ++outY ) + for(unsigned int outY = 0; outY < desiredHeight; ++outY) { PIXEL* const outScanline = &outAligned[desiredWidth * outY]; // Find the two scanlines to blend and the weight to blend with: - const unsigned int integerY1 = inY >> 16u; - const unsigned int integerY2 = integerY1 >= inputHeight ? integerY1 : integerY1 + 1; + const unsigned int integerY1 = inY >> 16u; + const unsigned int integerY2 = integerY1 >= inputHeight ? integerY1 : integerY1 + 1; const unsigned int inputYWeight = inY & 65535u; - DALI_ASSERT_DEBUG( integerY1 < inputHeight ); - DALI_ASSERT_DEBUG( integerY2 < inputHeight ); + DALI_ASSERT_DEBUG(integerY1 < inputHeight); + DALI_ASSERT_DEBUG(integerY2 < inputHeight); const PIXEL* const inScanline1 = &inAligned[inputWidth * integerY1]; const PIXEL* const inScanline2 = &inAligned[inputWidth * integerY2]; unsigned int inX = 0; - for( unsigned int outX = 0; outX < desiredWidth; ++outX ) + for(unsigned int outX = 0; outX < desiredWidth; ++outX) { // Work out the two pixel scanline offsets for this cluster of four samples: const unsigned int integerX1 = inX >> 16u; @@ -1855,7 +1848,7 @@ inline void LinearSampleGeneric( const unsigned char * __restrict__ inPixels, // Weighted bilinear filter: const unsigned int inputXWeight = inX & 65535u; - outScanline[outX] = BilinearFilter( pixel1, pixel3, pixel2, pixel4, inputXWeight, inputYWeight ); + outScanline[outX] = BilinearFilter(pixel1, pixel3, pixel2, pixel4, inputXWeight, inputYWeight); inX += deltaX; } @@ -1863,148 +1856,148 @@ inline void LinearSampleGeneric( const unsigned char * __restrict__ inPixels, } } -} +} // namespace // Format-specific linear scaling instantiations: -void LinearSample1BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LinearSample1BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { - LinearSampleGeneric( inPixels, inputDimensions, outPixels, desiredDimensions ); + LinearSampleGeneric(inPixels, inputDimensions, outPixels, desiredDimensions); } -void LinearSample2BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LinearSample2BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { - LinearSampleGeneric( inPixels, inputDimensions, outPixels, desiredDimensions ); + LinearSampleGeneric(inPixels, inputDimensions, outPixels, desiredDimensions); } -void LinearSampleRGB565( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LinearSampleRGB565(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { - LinearSampleGeneric( inPixels, inputDimensions, outPixels, desiredDimensions ); + LinearSampleGeneric(inPixels, inputDimensions, outPixels, desiredDimensions); } -void LinearSample3BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LinearSample3BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { - LinearSampleGeneric( inPixels, inputDimensions, outPixels, desiredDimensions ); + LinearSampleGeneric(inPixels, inputDimensions, outPixels, desiredDimensions); } -void LinearSample4BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LinearSample4BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { - LinearSampleGeneric( inPixels, inputDimensions, outPixels, desiredDimensions ); + LinearSampleGeneric(inPixels, inputDimensions, outPixels, desiredDimensions); } - -void Resample( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions, - Resampler::Filter filterType, - int numChannels, bool hasAlpha ) +void Resample(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions, + Resampler::Filter filterType, + int numChannels, + bool hasAlpha) { // Got from the test.cpp of the ImageResampler lib. - const float ONE_DIV_255 = 1.0f / 255.0f; - const int MAX_UNSIGNED_CHAR = std::numeric_limits::max(); - const int LINEAR_TO_SRGB_TABLE_SIZE = 4096; - const int ALPHA_CHANNEL = hasAlpha ? (numChannels-1) : 0; + const float ONE_DIV_255 = 1.0f / 255.0f; + const int MAX_UNSIGNED_CHAR = std::numeric_limits::max(); + const int LINEAR_TO_SRGB_TABLE_SIZE = 4096; + const int ALPHA_CHANNEL = hasAlpha ? (numChannels - 1) : 0; - static bool loadColorSpaces = true; - static float srgbToLinear[MAX_UNSIGNED_CHAR + 1]; + static bool loadColorSpaces = true; + static float srgbToLinear[MAX_UNSIGNED_CHAR + 1]; static unsigned char linearToSrgb[LINEAR_TO_SRGB_TABLE_SIZE]; - if( loadColorSpaces ) // Only create the color space conversions on the first execution + if(loadColorSpaces) // Only create the color space conversions on the first execution { loadColorSpaces = false; - for( int i = 0; i <= MAX_UNSIGNED_CHAR; ++i ) + for(int i = 0; i <= MAX_UNSIGNED_CHAR; ++i) { - srgbToLinear[i] = pow( static_cast( i ) * ONE_DIV_255, DEFAULT_SOURCE_GAMMA ); + srgbToLinear[i] = pow(static_cast(i) * ONE_DIV_255, DEFAULT_SOURCE_GAMMA); } - const float invLinearToSrgbTableSize = 1.0f / static_cast( LINEAR_TO_SRGB_TABLE_SIZE ); - const float invSourceGamma = 1.0f / DEFAULT_SOURCE_GAMMA; + const float invLinearToSrgbTableSize = 1.0f / static_cast(LINEAR_TO_SRGB_TABLE_SIZE); + const float invSourceGamma = 1.0f / DEFAULT_SOURCE_GAMMA; - for( int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i ) + for(int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i) { - int k = static_cast( 255.0f * pow( static_cast( i ) * invLinearToSrgbTableSize, invSourceGamma ) + 0.5f ); - if( k < 0 ) + int k = static_cast(255.0f * pow(static_cast(i) * invLinearToSrgbTableSize, invSourceGamma) + 0.5f); + if(k < 0) { k = 0; } - else if( k > MAX_UNSIGNED_CHAR ) + else if(k > MAX_UNSIGNED_CHAR) { k = MAX_UNSIGNED_CHAR; } - linearToSrgb[i] = static_cast( k ); + linearToSrgb[i] = static_cast(k); } } - std::vector resamplers( numChannels ); + std::vector resamplers(numChannels); std::vector> samples(numChannels); - const int srcWidth = inputDimensions.GetWidth(); + const int srcWidth = inputDimensions.GetWidth(); const int srcHeight = inputDimensions.GetHeight(); - const int dstWidth = desiredDimensions.GetWidth(); + const int dstWidth = desiredDimensions.GetWidth(); const int dstHeight = desiredDimensions.GetHeight(); // Now create a Resampler instance for each component to process. The first instance will create new contributor tables, which are shared by the resamplers // used for the other components (a memory and slight cache efficiency optimization). - resamplers[0] = new Resampler( srcWidth, - srcHeight, - dstWidth, - dstHeight, - Resampler::BOUNDARY_CLAMP, - 0.0f, // sample_low, - 1.0f, // sample_high. Clamp output samples to specified range, or disable clamping if sample_low >= sample_high. - filterType, // The type of filter. - NULL, // Pclist_x, - NULL, // Pclist_y. Optional pointers to contributor lists from another instance of a Resampler. - FILTER_SCALE, // src_x_ofs, - FILTER_SCALE ); // src_y_ofs. Offset input image by specified amount (fractional values okay). - samples[0].Resize( srcWidth ); - for( int i = 1; i < numChannels; ++i ) - { - resamplers[i] = new Resampler( srcWidth, - srcHeight, - dstWidth, - dstHeight, - Resampler::BOUNDARY_CLAMP, - 0.0f, - 1.0f, - filterType, - resamplers[0]->get_clist_x(), - resamplers[0]->get_clist_y(), - FILTER_SCALE, - FILTER_SCALE ); - samples[i].Resize( srcWidth ); + resamplers[0] = new Resampler(srcWidth, + srcHeight, + dstWidth, + dstHeight, + Resampler::BOUNDARY_CLAMP, + 0.0f, // sample_low, + 1.0f, // sample_high. Clamp output samples to specified range, or disable clamping if sample_low >= sample_high. + filterType, // The type of filter. + NULL, // Pclist_x, + NULL, // Pclist_y. Optional pointers to contributor lists from another instance of a Resampler. + FILTER_SCALE, // src_x_ofs, + FILTER_SCALE); // src_y_ofs. Offset input image by specified amount (fractional values okay). + samples[0].Resize(srcWidth); + for(int i = 1; i < numChannels; ++i) + { + resamplers[i] = new Resampler(srcWidth, + srcHeight, + dstWidth, + dstHeight, + Resampler::BOUNDARY_CLAMP, + 0.0f, + 1.0f, + filterType, + resamplers[0]->get_clist_x(), + resamplers[0]->get_clist_y(), + FILTER_SCALE, + FILTER_SCALE); + samples[i].Resize(srcWidth); } const int srcPitch = srcWidth * numChannels; const int dstPitch = dstWidth * numChannels; - int dstY = 0; + int dstY = 0; - for( int srcY = 0; srcY < srcHeight; ++srcY ) + for(int srcY = 0; srcY < srcHeight; ++srcY) { const unsigned char* pSrc = &inPixels[srcY * srcPitch]; - for( int x = 0; x < srcWidth; ++x ) + for(int x = 0; x < srcWidth; ++x) { - for( int c = 0; c < numChannels; ++c ) + for(int c = 0; c < numChannels; ++c) { - if( c == ALPHA_CHANNEL && hasAlpha ) + if(c == ALPHA_CHANNEL && hasAlpha) { samples[c][x] = *pSrc++ * ONE_DIV_255; } @@ -2015,52 +2008,52 @@ void Resample( const unsigned char * __restrict__ inPixels, } } - for( int c = 0; c < numChannels; ++c ) + for(int c = 0; c < numChannels; ++c) { - if( !resamplers[c]->put_line( &samples[c][0] ) ) + if(!resamplers[c]->put_line(&samples[c][0])) { - DALI_ASSERT_DEBUG( !"Out of memory" ); + DALI_ASSERT_DEBUG(!"Out of memory"); } } for(;;) { int compIndex; - for( compIndex = 0; compIndex < numChannels; ++compIndex ) + for(compIndex = 0; compIndex < numChannels; ++compIndex) { const float* pOutputSamples = resamplers[compIndex]->get_line(); - if( !pOutputSamples ) + if(!pOutputSamples) { break; } - const bool isAlphaChannel = ( compIndex == ALPHA_CHANNEL && hasAlpha ); - DALI_ASSERT_DEBUG( dstY < dstHeight ); + const bool isAlphaChannel = (compIndex == ALPHA_CHANNEL && hasAlpha); + DALI_ASSERT_DEBUG(dstY < dstHeight); unsigned char* pDst = &outPixels[dstY * dstPitch + compIndex]; - for( int x = 0; x < dstWidth; ++x ) + for(int x = 0; x < dstWidth; ++x) { - if( isAlphaChannel ) + if(isAlphaChannel) { - int c = static_cast( 255.0f * pOutputSamples[x] + 0.5f ); - if( c < 0 ) + int c = static_cast(255.0f * pOutputSamples[x] + 0.5f); + if(c < 0) { c = 0; } - else if( c > MAX_UNSIGNED_CHAR ) + else if(c > MAX_UNSIGNED_CHAR) { c = MAX_UNSIGNED_CHAR; } - *pDst = static_cast( c ); + *pDst = static_cast(c); } else { - int j = static_cast( LINEAR_TO_SRGB_TABLE_SIZE * pOutputSamples[x] + 0.5f ); - if( j < 0 ) + int j = static_cast(LINEAR_TO_SRGB_TABLE_SIZE * pOutputSamples[x] + 0.5f); + if(j < 0) { j = 0; } - else if( j >= LINEAR_TO_SRGB_TABLE_SIZE ) + else if(j >= LINEAR_TO_SRGB_TABLE_SIZE) { j = LINEAR_TO_SRGB_TABLE_SIZE - 1; } @@ -2070,7 +2063,7 @@ void Resample( const unsigned char * __restrict__ inPixels, pDst += numChannels; } } - if( compIndex < numChannels ) + if(compIndex < numChannels) { break; } @@ -2080,99 +2073,99 @@ void Resample( const unsigned char * __restrict__ inPixels, } // Delete the resamplers. - for( int i = 0; i < numChannels; ++i ) + for(int i = 0; i < numChannels; ++i) { delete resamplers[i]; } } -void LanczosSample4BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LanczosSample4BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { - Resample( inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 4, true ); + Resample(inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 4, true); } -void LanczosSample1BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ) +void LanczosSample1BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions) { // For L8 images - Resample( inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 1, false ); + Resample(inPixels, inputDimensions, outPixels, desiredDimensions, Resampler::LANCZOS4, 1, false); } // Dispatch to a format-appropriate linear sampling function: -void LinearSample( const unsigned char * __restrict__ inPixels, - ImageDimensions inDimensions, - Pixel::Format pixelFormat, - unsigned char * __restrict__ outPixels, - ImageDimensions outDimensions ) +void LinearSample(const unsigned char* __restrict__ inPixels, + ImageDimensions inDimensions, + Pixel::Format pixelFormat, + unsigned char* __restrict__ outPixels, + ImageDimensions outDimensions) { // Check the pixel format is one that is supported: - if( pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::RGB565 ) + if(pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::RGB565) { - if( pixelFormat == Pixel::RGB888 ) + if(pixelFormat == Pixel::RGB888) { - LinearSample3BPP( inPixels, inDimensions, outPixels, outDimensions ); + LinearSample3BPP(inPixels, inDimensions, outPixels, outDimensions); } - else if( pixelFormat == Pixel::RGBA8888 ) + else if(pixelFormat == Pixel::RGBA8888) { - LinearSample4BPP( inPixels, inDimensions, outPixels, outDimensions ); + LinearSample4BPP(inPixels, inDimensions, outPixels, outDimensions); } - else if( pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 ) + else if(pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8) { - LinearSample1BPP( inPixels, inDimensions, outPixels, outDimensions ); + LinearSample1BPP(inPixels, inDimensions, outPixels, outDimensions); } - else if( pixelFormat == Pixel::LA88 ) + else if(pixelFormat == Pixel::LA88) { - LinearSample2BPP( inPixels, inDimensions, outPixels, outDimensions ); + LinearSample2BPP(inPixels, inDimensions, outPixels, outDimensions); } - else if ( pixelFormat == Pixel::RGB565 ) + else if(pixelFormat == Pixel::RGB565) { - LinearSampleRGB565( inPixels, inDimensions, outPixels, outDimensions ); + LinearSampleRGB565(inPixels, inDimensions, outPixels, outDimensions); } else { - DALI_ASSERT_DEBUG( 0 == "Inner branch conditions don't match outer branch." ); + DALI_ASSERT_DEBUG(0 == "Inner branch conditions don't match outer branch."); } } else { - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not linear sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat) ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not linear sampled: unsupported pixel format: %u.\n", unsigned(pixelFormat)); } } -void RotateByShear( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - float radians, - uint8_t*& pixelsOut, - unsigned int& widthOut, - unsigned int& heightOut ) +void RotateByShear(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + float radians, + uint8_t*& pixelsOut, + unsigned int& widthOut, + unsigned int& heightOut) { // @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv. // Do first the fast rotations to transform the angle into a (-45..45] range. float fastRotationPerformed = false; - if( ( radians > Math::PI_4 ) && ( radians <= RAD_135 ) ) + if((radians > Math::PI_4) && (radians <= RAD_135)) { // Angle in (45.0 .. 135.0] // Rotate image by 90 degrees into temporary image, // so it requires only an extra rotation angle // of -45.0 .. +45.0 to complete rotation. - fastRotationPerformed = Rotate90( pixelsIn, - widthIn, - heightIn, - pixelSize, - pixelsOut, - widthOut, - heightOut ); - - if( !fastRotationPerformed ) + fastRotationPerformed = Rotate90(pixelsIn, + widthIn, + heightIn, + pixelSize, + pixelsOut, + widthOut, + heightOut); + + if(!fastRotationPerformed) { DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "fast rotation failed\n"); // The fast rotation failed. @@ -2181,20 +2174,20 @@ void RotateByShear( const uint8_t* const pixelsIn, radians -= Math::PI_2; } - else if( ( radians > RAD_135 ) && ( radians <= RAD_225 ) ) + else if((radians > RAD_135) && (radians <= RAD_225)) { // Angle in (135.0 .. 225.0] // Rotate image by 180 degrees into temporary image, // so it requires only an extra rotation angle // of -45.0 .. +45.0 to complete rotation. - fastRotationPerformed = Rotate180( pixelsIn, - widthIn, - heightIn, - pixelSize, - pixelsOut ); + fastRotationPerformed = Rotate180(pixelsIn, + widthIn, + heightIn, + pixelSize, + pixelsOut); - if( !fastRotationPerformed ) + if(!fastRotationPerformed) { DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "fast rotation failed\n"); // The fast rotation failed. @@ -2202,25 +2195,25 @@ void RotateByShear( const uint8_t* const pixelsIn, } radians -= Math::PI; - widthOut = widthIn; + widthOut = widthIn; heightOut = heightIn; } - else if( ( radians > RAD_225 ) && ( radians <= RAD_315 ) ) + else if((radians > RAD_225) && (radians <= RAD_315)) { // Angle in (225.0 .. 315.0] // Rotate image by 270 degrees into temporary image, // so it requires only an extra rotation angle // of -45.0 .. +45.0 to complete rotation. - fastRotationPerformed = Rotate270( pixelsIn, - widthIn, - heightIn, - pixelSize, - pixelsOut, - widthOut, - heightOut ); + fastRotationPerformed = Rotate270(pixelsIn, + widthIn, + heightIn, + pixelSize, + pixelsOut, + widthOut, + heightOut); - if( !fastRotationPerformed ) + if(!fastRotationPerformed) { DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "fast rotation failed\n"); // The fast rotation failed. @@ -2230,7 +2223,7 @@ void RotateByShear( const uint8_t* const pixelsIn, radians -= RAD_270; } - if( fabs( radians ) < Dali::Math::MACHINE_EPSILON_10 ) + if(fabs(radians) < Dali::Math::MACHINE_EPSILON_10) { // Nothing else to do if the angle is zero. // The rotation angle was 90, 180 or 270. @@ -2239,17 +2232,17 @@ void RotateByShear( const uint8_t* const pixelsIn, return; } - const uint8_t* const firstHorizontalSkewPixelsIn = fastRotationPerformed ? pixelsOut : pixelsIn; - std::unique_ptr tmpPixelsInPtr( ( fastRotationPerformed ? pixelsOut : nullptr ), free ); + const uint8_t* const firstHorizontalSkewPixelsIn = fastRotationPerformed ? pixelsOut : pixelsIn; + std::unique_ptr tmpPixelsInPtr((fastRotationPerformed ? pixelsOut : nullptr), free); // Reset the input/output - widthIn = widthOut; - heightIn = heightOut; + widthIn = widthOut; + heightIn = heightOut; pixelsOut = nullptr; - const float angleSinus = sin( radians ); - const float angleCosinus = cos( radians ); - const float angleTangent = tan( 0.5f * radians ); + const float angleSinus = sin(radians); + const float angleCosinus = cos(radians); + const float angleTangent = tan(0.5f * radians); /////////////////////////////////////// // Perform 1st shear (horizontal) @@ -2257,15 +2250,15 @@ void RotateByShear( const uint8_t* const pixelsIn, // Calculate first shear (horizontal) destination image dimensions - widthOut = widthIn + static_cast( fabs( angleTangent ) * static_cast( heightIn ) ); + widthOut = widthIn + static_cast(fabs(angleTangent) * static_cast(heightIn)); heightOut = heightIn; // Allocate the buffer for the 1st shear - pixelsOut = static_cast( malloc( widthOut * heightOut * pixelSize ) ); + pixelsOut = static_cast(malloc(widthOut * heightOut * pixelSize)); - if( nullptr == pixelsOut ) + if(nullptr == pixelsOut) { - widthOut = 0u; + widthOut = 0u; heightOut = 0u; DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n"); @@ -2275,17 +2268,17 @@ void RotateByShear( const uint8_t* const pixelsIn, return; } - for( unsigned int y = 0u; y < heightOut; ++y ) + for(unsigned int y = 0u; y < heightOut; ++y) { - const float shear = angleTangent * ( ( angleTangent >= 0.f ) ? ( 0.5f + static_cast( y ) ) : ( 0.5f + static_cast( y ) - static_cast( heightOut ) ) ); + const float shear = angleTangent * ((angleTangent >= 0.f) ? (0.5f + static_cast(y)) : (0.5f + static_cast(y) - static_cast(heightOut))); - const int intShear = static_cast( floor( shear ) ); - HorizontalSkew( firstHorizontalSkewPixelsIn, widthIn, pixelSize, pixelsOut, widthOut, y, intShear, shear - static_cast( intShear ) ); + const int intShear = static_cast(floor(shear)); + HorizontalSkew(firstHorizontalSkewPixelsIn, widthIn, pixelSize, pixelsOut, widthOut, y, intShear, shear - static_cast(intShear)); } // Reset the 'pixel in' pointer with the output of the 'First Horizontal Skew' and free the memory allocated by the 'Fast Rotations'. - tmpPixelsInPtr.reset( pixelsOut ); - unsigned int tmpWidthIn = widthOut; + tmpPixelsInPtr.reset(pixelsOut); + unsigned int tmpWidthIn = widthOut; unsigned int tmpHeightIn = heightOut; // Reset the input/output @@ -2296,14 +2289,14 @@ void RotateByShear( const uint8_t* const pixelsIn, /////////////////////////////////////// // Calc 2nd shear (vertical) destination image dimensions - heightOut = static_cast( static_cast( widthIn ) * fabs( angleSinus ) + static_cast( heightIn ) * angleCosinus ); + heightOut = static_cast(static_cast(widthIn) * fabs(angleSinus) + static_cast(heightIn) * angleCosinus); // Allocate the buffer for the 2nd shear - pixelsOut = static_cast( malloc( widthOut * heightOut * pixelSize ) ); + pixelsOut = static_cast(malloc(widthOut * heightOut * pixelSize)); - if( nullptr == pixelsOut ) + if(nullptr == pixelsOut) { - widthOut = 0u; + widthOut = 0u; heightOut = 0u; DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n"); @@ -2313,34 +2306,34 @@ void RotateByShear( const uint8_t* const pixelsIn, } // Variable skew offset - float offset = angleSinus * ( ( angleSinus > 0.f ) ? static_cast( widthIn - 1u ) : -( static_cast( widthIn ) - static_cast( widthOut ) ) ); + float offset = angleSinus * ((angleSinus > 0.f) ? static_cast(widthIn - 1u) : -(static_cast(widthIn) - static_cast(widthOut))); unsigned int column = 0u; - for( column = 0u; column < widthOut; ++column, offset -= angleSinus ) + for(column = 0u; column < widthOut; ++column, offset -= angleSinus) { - const int shear = static_cast( floor( offset ) ); - VerticalSkew( tmpPixelsInPtr.get(), tmpWidthIn, tmpHeightIn, pixelSize, pixelsOut, widthOut, heightOut, column, shear, offset - static_cast( shear ) ); + const int shear = static_cast(floor(offset)); + VerticalSkew(tmpPixelsInPtr.get(), tmpWidthIn, tmpHeightIn, pixelSize, pixelsOut, widthOut, heightOut, column, shear, offset - static_cast(shear)); } // Reset the 'pixel in' pointer with the output of the 'Vertical Skew' and free the memory allocated by the 'First Horizontal Skew'. // Reset the input/output - tmpPixelsInPtr.reset( pixelsOut ); - tmpWidthIn = widthOut; + tmpPixelsInPtr.reset(pixelsOut); + tmpWidthIn = widthOut; tmpHeightIn = heightOut; - pixelsOut = nullptr; + pixelsOut = nullptr; /////////////////////////////////////// // Perform 3rd shear (horizontal) /////////////////////////////////////// // Calc 3rd shear (horizontal) destination image dimensions - widthOut = static_cast( static_cast( heightIn ) * fabs( angleSinus ) + static_cast( widthIn ) * angleCosinus ) + 1u; + widthOut = static_cast(static_cast(heightIn) * fabs(angleSinus) + static_cast(widthIn) * angleCosinus) + 1u; // Allocate the buffer for the 3rd shear - pixelsOut = static_cast( malloc( widthOut * heightOut * pixelSize ) ); + pixelsOut = static_cast(malloc(widthOut * heightOut * pixelSize)); - if( nullptr == pixelsOut ) + if(nullptr == pixelsOut) { - widthOut = 0u; + widthOut = 0u; heightOut = 0u; DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n"); @@ -2349,62 +2342,62 @@ void RotateByShear( const uint8_t* const pixelsIn, return; } - offset = ( angleSinus >= 0.f ) ? -angleSinus * angleTangent * static_cast( widthIn - 1u ) : angleTangent * ( static_cast( widthIn - 1u ) * -angleSinus + ( 1.f - static_cast( heightOut ) ) ); + offset = (angleSinus >= 0.f) ? -angleSinus * angleTangent * static_cast(widthIn - 1u) : angleTangent * (static_cast(widthIn - 1u) * -angleSinus + (1.f - static_cast(heightOut))); - for( unsigned int y = 0u; y < heightOut; ++y, offset += angleTangent ) + for(unsigned int y = 0u; y < heightOut; ++y, offset += angleTangent) { - const int shear = static_cast( floor( offset ) ); - HorizontalSkew( tmpPixelsInPtr.get(), tmpWidthIn, pixelSize, pixelsOut, widthOut, y, shear, offset - static_cast( shear ) ); + const int shear = static_cast(floor(offset)); + HorizontalSkew(tmpPixelsInPtr.get(), tmpWidthIn, pixelSize, pixelsOut, widthOut, y, shear, offset - static_cast(shear)); } // The deleter of the tmpPixelsInPtr unique pointer is called freeing the memory allocated by the 'Vertical Skew'. // @note Allocated memory by the last 'Horizontal Skew' has to be freed by the caller to this function. } -void HorizontalShear( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - float radians, - uint8_t*& pixelsOut, - unsigned int& widthOut, - unsigned int& heightOut ) +void HorizontalShear(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + float radians, + uint8_t*& pixelsOut, + unsigned int& widthOut, + unsigned int& heightOut) { // Calculate the destination image dimensions. - const float absRadians = fabs( radians ); + const float absRadians = fabs(radians); - if( absRadians > Math::PI_4 ) + if(absRadians > Math::PI_4) { // Can't shear more than 45 degrees. - widthOut = 0u; + widthOut = 0u; heightOut = 0u; - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Can't shear more than 45 degrees (PI/4 radians). radians : %f\n", radians ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Can't shear more than 45 degrees (PI/4 radians). radians : %f\n", radians); return; } - widthOut = widthIn + static_cast( ceil ( absRadians * static_cast( heightIn ) ) ); + widthOut = widthIn + static_cast(ceil(absRadians * static_cast(heightIn))); heightOut = heightIn; // Allocate the buffer for the shear. - pixelsOut = static_cast( malloc( widthOut * heightOut * pixelSize ) ); + pixelsOut = static_cast(malloc(widthOut * heightOut * pixelSize)); - if( nullptr == pixelsOut ) + if(nullptr == pixelsOut) { - widthOut = 0u; + widthOut = 0u; heightOut = 0u; - DALI_LOG_INFO( gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n" ); + DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n"); return; } - for( unsigned int y = 0u; y < heightOut; ++y ) + for(unsigned int y = 0u; y < heightOut; ++y) { - const float shear = radians * ( ( radians >= 0.f ) ? ( 0.5f + static_cast( y ) ) : ( 0.5f + static_cast( y ) - static_cast( heightOut ) ) ); + const float shear = radians * ((radians >= 0.f) ? (0.5f + static_cast(y)) : (0.5f + static_cast(y) - static_cast(heightOut))); - const int intShear = static_cast( floor( shear ) ); - HorizontalSkew( pixelsIn, widthIn, pixelSize, pixelsOut, widthOut, y, intShear, shear - static_cast( intShear ) ); + const int intShear = static_cast(floor(shear)); + HorizontalSkew(pixelsIn, widthIn, pixelSize, pixelsOut, widthOut, y, intShear, shear - static_cast(intShear)); } } diff --git a/dali/internal/imaging/common/image-operations.h b/dali/internal/imaging/common/image-operations.h old mode 100755 new mode 100644 index 6ae9ba1..81a722c --- a/dali/internal/imaging/common/image-operations.h +++ b/dali/internal/imaging/common/image-operations.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,10 @@ #include // INTERNAL INCLUDES +#include #include #include #include -#include namespace Dali { @@ -33,7 +33,6 @@ namespace Internal { namespace Platform { - /** * @brief Identify which combination of x and y dimensions matter in terminating iterative box filtering. */ @@ -60,7 +59,7 @@ typedef Uint16Pair ImageDimensions; * @param[in] requestedDimensions Width and height of area to scale image into. Can be zero. * @return Dimensions of area to scale image into after special rules are applied. */ -ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, ImageDimensions requestedDimensions ); +ImageDimensions CalculateDesiredDimensions(ImageDimensions rawDimensions, ImageDimensions requestedDimensions); /** * @defgroup BitmapOperations Bitmap-to-Bitmap Image operations. @@ -81,16 +80,16 @@ ImageDimensions CalculateDesiredDimensions( ImageDimensions rawDimensions, Image * bitmap passed-in, or the original bitmap passed in if the attributes * have no effect. */ -Dali::Devel::PixelBuffer ApplyAttributesToBitmap( Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode = FittingMode::DEFAULT, SamplingMode::Type samplingMode = SamplingMode::DEFAULT ); +Dali::Devel::PixelBuffer ApplyAttributesToBitmap(Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode = FittingMode::DEFAULT, SamplingMode::Type samplingMode = SamplingMode::DEFAULT); /** * @brief Apply downscaling to a bitmap according to requested attributes. * @note The input bitmap pixel buffer may be modified and used as scratch working space for efficiency, so it must be discarded. **/ -Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap, - ImageDimensions desired, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode ); +Dali::Devel::PixelBuffer DownscaleBitmap(Dali::Devel::PixelBuffer bitmap, + ImageDimensions desired, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode); /**@}*/ /** @@ -113,16 +112,16 @@ Dali::Devel::PixelBuffer DownscaleBitmap( Dali::Devel::PixelBuffer bitmap, * @param[out] outWidth The resulting width after downscaling. * @param[out] outHeight The resulting height after downscaling. */ -void DownscaleInPlacePow2( unsigned char * const pixels, - Pixel::Format pixelFormat, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - unsigned& outWidth, - unsigned& outHeight ); +void DownscaleInPlacePow2(unsigned char* const pixels, + Pixel::Format pixelFormat, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + unsigned& outWidth, + unsigned& outHeight); /** * @brief Destructive in-place downscaling by a power of 2 factor. @@ -138,68 +137,68 @@ void DownscaleInPlacePow2( unsigned char * const pixels, * @param[out] outWidth The resulting width after downscaling. * @param[out] outHeight The resulting height after downscaling. */ -void DownscaleInPlacePow2RGB888( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ); +void DownscaleInPlacePow2RGB888(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight); /** * @copydoc DownscaleInPlacePow2RGB888 */ -void DownscaleInPlacePow2RGBA8888( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ); +void DownscaleInPlacePow2RGBA8888(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight); /** * @copydoc DownscaleInPlacePow2RGB888 * * For the 2-byte packed 16 bit format RGB565. */ -void DownscaleInPlacePow2RGB565( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ); +void DownscaleInPlacePow2RGB565(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight); /** * @copydoc DownscaleInPlacePow2RGB888 * * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565. */ -void DownscaleInPlacePow2ComponentPair( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ); +void DownscaleInPlacePow2ComponentPair(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight); /** * @copydoc DownscaleInPlacePow2RGB888 * * For single-byte formats such as lum8 or alpha8. */ -void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned int desiredWidth, - unsigned int desiredHeight, - BoxDimensionTest dimensionTest, - unsigned int& outWidth, - unsigned int& outHeight ); +void DownscaleInPlacePow2SingleBytePerPixel(unsigned char* pixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned int desiredWidth, + unsigned int desiredHeight, + BoxDimensionTest dimensionTest, + unsigned int& outWidth, + unsigned int& outHeight); /** * @brief Rescales an input image into the exact output dimensions passed-in. @@ -209,61 +208,61 @@ void DownscaleInPlacePow2SingleBytePerPixel( unsigned char * pixels, * @note inPixels is allowed to alias outPixels if this is a downscaling, * but not for upscaling. */ -void PointSample( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - Pixel::Format pixelFormat, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ); +void PointSample(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + Pixel::Format pixelFormat, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight); /** * @copydoc PointSample * * Specialised for 4-byte formats like RGBA8888 and BGRA8888. */ -void PointSample4BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ); +void PointSample4BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight); /** * @copydoc PointSample * * Specialised for 3-byte formats like RGB888 and BGR888. */ -void PointSample3BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ); +void PointSample3BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight); /** * @copydoc PointSample * * Specialised for 2-byte formats like LA88. */ -void PointSample2BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ); +void PointSample2BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight); /** * @copydoc PointSample * * Specialised for 1-byte formats like L8 and A8. */ -void PointSample1BPP( const unsigned char * inPixels, - unsigned int inputWidth, - unsigned int inputHeight, - unsigned char * outPixels, - unsigned int desiredWidth, - unsigned int desiredHeight ); +void PointSample1BPP(const unsigned char* inPixels, + unsigned int inputWidth, + unsigned int inputHeight, + unsigned char* outPixels, + unsigned int desiredWidth, + unsigned int desiredHeight); /** * @brief Resample input image to output image using a bilinear filter. @@ -273,51 +272,51 @@ void PointSample1BPP( const unsigned char * inPixels, * @pre inPixels must not alias outPixels. The input image should be a totally * separate buffer from the input one. */ -void LinearSample( const unsigned char * __restrict__ inPixels, - ImageDimensions inDimensions, - Pixel::Format pixelFormat, - unsigned char * __restrict__ outPixels, - ImageDimensions outDimensions ); +void LinearSample(const unsigned char* __restrict__ inPixels, + ImageDimensions inDimensions, + Pixel::Format pixelFormat, + unsigned char* __restrict__ outPixels, + ImageDimensions outDimensions); /** * @copydoc LinearSample * * Specialised for one byte per pixel formats. */ -void LinearSample1BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LinearSample1BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @copydoc LinearSample * * Specialised for two byte per pixel formats. */ -void LinearSample2BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LinearSample2BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @copydoc LinearSample * * Specialised for RGB565 16 bit pixel format. */ -void LinearSampleRGB565( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LinearSampleRGB565(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @copydoc LinearSample * * Specialised for three byte per pixel formats like RGB888. */ -void LinearSample3BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LinearSample3BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @copydoc LinearSample @@ -325,10 +324,10 @@ void LinearSample3BPP( const unsigned char * __restrict__ inPixels, * Specialised for four byte per pixel formats like RGBA8888. * @note, If used on RGBA8888, the A component will be blended independently. */ -void LinearSample4BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LinearSample4BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @brief Resamples the input image with the Lanczos algorithm. @@ -341,10 +340,10 @@ void LinearSample4BPP( const unsigned char * __restrict__ inPixels, * @param[out] outPixels Pointer to the output image buffer. * @param[in] desiredDimensions The output dimensions of the image. */ -void LanczosSample4BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LanczosSample4BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @brief Resamples the input image with the Lanczos algorithm. @@ -357,10 +356,10 @@ void LanczosSample4BPP( const unsigned char * __restrict__ inPixels, * @param[out] outPixels Pointer to the output image buffer. * @param[in] desiredDimensions The output dimensions of the image. */ -void LanczosSample1BPP( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions ); +void LanczosSample1BPP(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions); /** * @brief Resamples the input image with the Lanczos algorithm. @@ -373,13 +372,13 @@ void LanczosSample1BPP( const unsigned char * __restrict__ inPixels, * @param[out] outPixels Pointer to the output image buffer. * @param[in] desiredDimensions The output dimensions of the image. */ -void Resample( const unsigned char * __restrict__ inPixels, - ImageDimensions inputDimensions, - unsigned char * __restrict__ outPixels, - ImageDimensions desiredDimensions, - Resampler::Filter filterType, - int numChannels, bool hasAlpha ); - +void Resample(const unsigned char* __restrict__ inPixels, + ImageDimensions inputDimensions, + unsigned char* __restrict__ outPixels, + ImageDimensions desiredDimensions, + Resampler::Filter filterType, + int numChannels, + bool hasAlpha); /** * @brief Rotates the input image with an implementation of the 'Rotate by Shear' algorithm. @@ -398,14 +397,14 @@ void Resample( const unsigned char * __restrict__ inPixels, * @param[out] widthOut The width of the output buffer. * @param[out] heightOut The height of the output buffer. */ -void RotateByShear( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - float radians, - uint8_t*& pixelsOut, - unsigned int& widthOut, - unsigned int& heightOut ); +void RotateByShear(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + float radians, + uint8_t*& pixelsOut, + unsigned int& widthOut, + unsigned int& heightOut); /** * @brief Applies to the input image a horizontal shear transformation. @@ -425,14 +424,14 @@ void RotateByShear( const uint8_t* const pixelsIn, * @param[out] widthOut The width of the output buffer. * @param[out] heightOut The height of the output buffer. */ -void HorizontalShear( const uint8_t* const pixelsIn, - unsigned int widthIn, - unsigned int heightIn, - unsigned int pixelSize, - float radians, - uint8_t*& pixelsOut, - unsigned int& widthOut, - unsigned int& heightOut ); +void HorizontalShear(const uint8_t* const pixelsIn, + unsigned int widthIn, + unsigned int heightIn, + unsigned int pixelSize, + float radians, + uint8_t*& pixelsOut, + unsigned int& widthOut, + unsigned int& heightOut); /**@}*/ @@ -446,27 +445,27 @@ void HorizontalShear( const uint8_t* const pixelsIn, * @param[in,out] pixels The array of pixels to work on. * @param[i] width The number of pixels in the array passed-in. */ -void HalveScanlineInPlaceRGB888( unsigned char * pixels, unsigned int width ); +void HalveScanlineInPlaceRGB888(unsigned char* pixels, unsigned int width); /** * @copydoc HalveScanlineInPlaceRGB888 */ -void HalveScanlineInPlaceRGBA8888( unsigned char * pixels, unsigned int width ); +void HalveScanlineInPlaceRGBA8888(unsigned char* pixels, unsigned int width); /** * @copydoc HalveScanlineInPlaceRGB888 */ -void HalveScanlineInPlaceRGB565( unsigned char * pixels, unsigned int width ); +void HalveScanlineInPlaceRGB565(unsigned char* pixels, unsigned int width); /** * @copydoc HalveScanlineInPlaceRGB888 */ -void HalveScanlineInPlace2Bytes( unsigned char * pixels, unsigned int width ); +void HalveScanlineInPlace2Bytes(unsigned char* pixels, unsigned int width); /** * @copydoc HalveScanlineInPlaceRGB888 */ -void HalveScanlineInPlace1Byte( unsigned char * pixels, unsigned int width ); +void HalveScanlineInPlace1Byte(unsigned char* pixels, unsigned int width); /** * @brief Average pixels at corresponding offsets in two scanlines. @@ -477,45 +476,45 @@ void HalveScanlineInPlace1Byte( unsigned char * pixels, unsigned int width ); * @param[out] outputScanline Destination for the averaged pixels. * @param[in] width The widths of all the scanlines passed-in. */ -void AverageScanlines1( const unsigned char * scanline1, - const unsigned char * scanline2, - unsigned char* outputScanline, - /** Image width in pixels (1 byte == 1 pixel: e.g. lum8 or alpha8).*/ - unsigned int width ); +void AverageScanlines1(const unsigned char* scanline1, + const unsigned char* scanline2, + unsigned char* outputScanline, + /** Image width in pixels (1 byte == 1 pixel: e.g. lum8 or alpha8).*/ + unsigned int width); /** * @copydoc AverageScanlines1 */ -void AverageScanlines2( const unsigned char * scanline1, - const unsigned char * scanline2, - unsigned char* outputScanline, - /** Image width in pixels (2 bytes == 1 pixel: e.g. lum8alpha8).*/ - unsigned int width ); +void AverageScanlines2(const unsigned char* scanline1, + const unsigned char* scanline2, + unsigned char* outputScanline, + /** Image width in pixels (2 bytes == 1 pixel: e.g. lum8alpha8).*/ + unsigned int width); /** * @copydoc AverageScanlines1 */ -void AverageScanlines3( const unsigned char * scanline1, - const unsigned char * scanline2, - unsigned char* outputScanline, - /** Image width in pixels (3 bytes == 1 pixel: e.g. RGB888).*/ - unsigned int width ); +void AverageScanlines3(const unsigned char* scanline1, + const unsigned char* scanline2, + unsigned char* outputScanline, + /** Image width in pixels (3 bytes == 1 pixel: e.g. RGB888).*/ + unsigned int width); /** * @copydoc AverageScanlines1 */ -void AverageScanlinesRGBA8888( const unsigned char * scanline1, - const unsigned char * scanline2, - unsigned char * outputScanline, - unsigned int width ); +void AverageScanlinesRGBA8888(const unsigned char* scanline1, + const unsigned char* scanline2, + unsigned char* outputScanline, + unsigned int width); /** * @copydoc AverageScanlines1 */ -void AverageScanlinesRGB565( const unsigned char * scanline1, - const unsigned char * scanline2, - unsigned char* outputScanline, - unsigned int width ); +void AverageScanlinesRGB565(const unsigned char* scanline1, + const unsigned char* scanline2, + unsigned char* outputScanline, + unsigned int width); /**@}*/ /** @@ -529,7 +528,7 @@ void AverageScanlinesRGB565( const unsigned char * scanline1, * @param[in] a First component to average. * @param[in] b Second component to average. **/ -inline unsigned int AverageComponent( unsigned int a, unsigned int b ) +inline unsigned int AverageComponent(unsigned int a, unsigned int b) { unsigned int avg = (a + b) >> 1u; return avg; @@ -541,13 +540,13 @@ inline unsigned int AverageComponent( unsigned int a, unsigned int b ) * @param[in] a First pixel to average. * @param[in] b Second pixel to average **/ -inline uint32_t AveragePixelRGBA8888( uint32_t a, uint32_t b ) +inline uint32_t AveragePixelRGBA8888(uint32_t a, uint32_t b) { const unsigned int avg = - ((AverageComponent( (a & 0xff000000) >> 1u, (b & 0xff000000) >> 1u ) << 1u) & 0xff000000 ) + - (AverageComponent( a & 0x00ff0000, b & 0x00ff0000 ) & 0x00ff0000 ) + - (AverageComponent( a & 0x0000ff00, b & 0x0000ff00 ) & 0x0000ff00 ) + - (AverageComponent( a & 0x000000ff, b & 0x000000ff ) ); + ((AverageComponent((a & 0xff000000) >> 1u, (b & 0xff000000) >> 1u) << 1u) & 0xff000000) + + (AverageComponent(a & 0x00ff0000, b & 0x00ff0000) & 0x00ff0000) + + (AverageComponent(a & 0x0000ff00, b & 0x0000ff00) & 0x0000ff00) + + (AverageComponent(a & 0x000000ff, b & 0x000000ff)); return avg; ///@ToDo: Optimise by trying return (((a ^ b) & 0xfefefefeUL) >> 1) + (a & b); ///@ToDo: Optimise for ARM using the single ARMV6 instruction: UHADD8 R4, R0, R5. This is not Neon. It runs in the normal integer pipeline so there is no downside like a stall moving between integer and copro. @@ -559,48 +558,48 @@ inline uint32_t AveragePixelRGBA8888( uint32_t a, uint32_t b ) * @param b[in] Low 16 bits hold a color value as RGB565 to average with parameter a. * @return The average color of the two RGB565 pixels passed in, in the low 16 bits of the returned value. **/ -inline uint32_t AveragePixelRGB565( uint32_t a, uint32_t b ) +inline uint32_t AveragePixelRGB565(uint32_t a, uint32_t b) { const unsigned int avg = - (AverageComponent( a & 0xf800, b & 0xf800 ) & 0xf800 ) + - (AverageComponent( a & 0x7e0, b & 0x7e0 ) & 0x7e0 ) + - (AverageComponent( a & 0x1f, b & 0x1f ) ); + (AverageComponent(a & 0xf800, b & 0xf800) & 0xf800) + + (AverageComponent(a & 0x7e0, b & 0x7e0) & 0x7e0) + + (AverageComponent(a & 0x1f, b & 0x1f)); return avg; } /** @return The weighted blend of two integers as a 16.16 fixed-point number, given a 0.16 fixed-point blending factor. */ -inline unsigned int WeightedBlendIntToFixed1616(unsigned int a, unsigned int b, unsigned int fractBlend ) +inline unsigned int WeightedBlendIntToFixed1616(unsigned int a, unsigned int b, unsigned int fractBlend) { - DALI_ASSERT_DEBUG( fractBlend <= 65535u && "Factor should be in 0.16 fixed-point." ); + DALI_ASSERT_DEBUG(fractBlend <= 65535u && "Factor should be in 0.16 fixed-point."); const unsigned int weightedAFixed = a * (65535u - fractBlend); const unsigned int weightedBFixed = b * fractBlend; - const unsigned blended = (weightedAFixed + weightedBFixed); + const unsigned blended = (weightedAFixed + weightedBFixed); return blended; } /** @brief Blend two 16.16 inputs to give a 16.32 output. */ -inline uint64_t WeightedBlendFixed1616ToFixed1632(unsigned int a, unsigned int b, unsigned int fractBlend ) +inline uint64_t WeightedBlendFixed1616ToFixed1632(unsigned int a, unsigned int b, unsigned int fractBlend) { - DALI_ASSERT_DEBUG( fractBlend <= 65535u && "Factor should be in 0.16 fixed-point." ); + DALI_ASSERT_DEBUG(fractBlend <= 65535u && "Factor should be in 0.16 fixed-point."); // Blend while promoting intermediates to 16.32 fixed point: const uint64_t weightedAFixed = uint64_t(a) * (65535u - fractBlend); const uint64_t weightedBFixed = uint64_t(b) * fractBlend; - const uint64_t blended = (weightedAFixed + weightedBFixed); + const uint64_t blended = (weightedAFixed + weightedBFixed); return blended; } /** * @brief Blend 4 taps into one value using horizontal and vertical weights. */ -inline unsigned int BilinearFilter1Component(unsigned int tl, unsigned int tr, unsigned int bl, unsigned int br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical ) +inline unsigned int BilinearFilter1Component(unsigned int tl, unsigned int tr, unsigned int bl, unsigned int br, unsigned int fractBlendHorizontal, unsigned int fractBlendVertical) { - DALI_ASSERT_DEBUG( fractBlendHorizontal <= 65535u && "Factor should be in 0.16 fixed-point." ); - DALI_ASSERT_DEBUG( fractBlendVertical <= 65535u && "Factor should be in 0.16 fixed-point." ); + DALI_ASSERT_DEBUG(fractBlendHorizontal <= 65535u && "Factor should be in 0.16 fixed-point."); + DALI_ASSERT_DEBUG(fractBlendVertical <= 65535u && "Factor should be in 0.16 fixed-point."); - const unsigned int topBlend = WeightedBlendIntToFixed1616( tl, tr, fractBlendHorizontal ); - const unsigned int botBlend = WeightedBlendIntToFixed1616( bl, br, fractBlendHorizontal ); - const uint64_t blended2x2 = WeightedBlendFixed1616ToFixed1632( topBlend, botBlend, fractBlendVertical ); - const unsigned int rounded = (blended2x2 + (1u << 31u) ) >> 32u; + const unsigned int topBlend = WeightedBlendIntToFixed1616(tl, tr, fractBlendHorizontal); + const unsigned int botBlend = WeightedBlendIntToFixed1616(bl, br, fractBlendHorizontal); + const uint64_t blended2x2 = WeightedBlendFixed1616ToFixed1632(topBlend, botBlend, fractBlendVertical); + const unsigned int rounded = (blended2x2 + (1u << 31u)) >> 32u; return rounded; } diff --git a/dali/internal/imaging/common/loader-astc.cpp b/dali/internal/imaging/common/loader-astc.cpp old mode 100755 new mode 100644 index e63d846..4ab6d67 --- a/dali/internal/imaging/common/loader-astc.cpp +++ b/dali/internal/imaging/common/loader-astc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ #include // EXTERNAL INCLUDES -#include -#include -#include #include +#include #include +#include +#include namespace Dali { @@ -31,7 +31,6 @@ namespace TizenPlatform { namespace { - // Max width or height of an image. const unsigned MAX_TEXTURE_DIMENSION = 4096; // Max bytes of image data allowed. Not a precise number, just a sanity check. @@ -45,9 +44,7 @@ typedef uint8_t Byte; // This bytes identify an ASTC native file. const Byte FileIdentifier[] = { - 0x13, 0xAB, 0xA1, 0x5C -}; - + 0x13, 0xAB, 0xA1, 0x5C}; /** * @brief This struct defines the ASTC file header values. From ASTC specifications. @@ -57,14 +54,14 @@ const Byte FileIdentifier[] = { */ struct AstcFileHeader { - unsigned char magic[ 4 ]; + unsigned char magic[4]; unsigned char blockdim_x; unsigned char blockdim_y; unsigned char blockdim_z; - unsigned char xsize[ 3 ]; - unsigned char ysize[ 3 ]; - unsigned char zsize[ 3 ]; -} __attribute__ ( (__packed__)); + unsigned char xsize[3]; + unsigned char ysize[3]; + unsigned char zsize[3]; +} __attribute__((__packed__)); using namespace Pixel; @@ -75,17 +72,16 @@ using namespace Pixel; * IE. Table format is: Increasing order of block width from left-to-right: 4 -> 12 * Increasing order of block height from top-to-bottom: 4 -> 12 */ -Pixel::Format AstcLinearBlockSizeToPixelFormatTable[][( MAXIMUM_ASTC_BLOCK_SIZE - MINIMUM_ASTC_BLOCK_SIZE ) + 1] = { - { COMPRESSED_RGBA_ASTC_4x4_KHR, COMPRESSED_RGBA_ASTC_5x4_KHR, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID }, - { INVALID, COMPRESSED_RGBA_ASTC_5x5_KHR, COMPRESSED_RGBA_ASTC_6x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x5_KHR, INVALID, INVALID }, - { INVALID, INVALID, COMPRESSED_RGBA_ASTC_6x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x6_KHR, INVALID, INVALID }, - { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID }, - { INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_8x8_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x8_KHR, INVALID, INVALID }, - { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID }, - { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_10x10_KHR, INVALID, COMPRESSED_RGBA_ASTC_12x10_KHR }, - { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID }, - { INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_12x12_KHR } -}; +Pixel::Format AstcLinearBlockSizeToPixelFormatTable[][(MAXIMUM_ASTC_BLOCK_SIZE - MINIMUM_ASTC_BLOCK_SIZE) + 1] = { + {COMPRESSED_RGBA_ASTC_4x4_KHR, COMPRESSED_RGBA_ASTC_5x4_KHR, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID}, + {INVALID, COMPRESSED_RGBA_ASTC_5x5_KHR, COMPRESSED_RGBA_ASTC_6x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x5_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x5_KHR, INVALID, INVALID}, + {INVALID, INVALID, COMPRESSED_RGBA_ASTC_6x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_8x6_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x6_KHR, INVALID, INVALID}, + {INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID}, + {INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_8x8_KHR, INVALID, COMPRESSED_RGBA_ASTC_10x8_KHR, INVALID, INVALID}, + {INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID}, + {INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_10x10_KHR, INVALID, COMPRESSED_RGBA_ASTC_12x10_KHR}, + {INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID}, + {INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, INVALID, COMPRESSED_RGBA_ASTC_12x12_KHR}}; /** * @brief Uses header information to return the respective ASTC pixel format. @@ -93,17 +89,17 @@ Pixel::Format AstcLinearBlockSizeToPixelFormatTable[][( MAXIMUM_ASTC_BLOCK_SIZE * @param[in] header A populated AstcFileHeader struct * @return The pixel format, or INVALID if the block size was invalid */ -Pixel::Format GetAstcPixelFormat( AstcFileHeader& header ) +Pixel::Format GetAstcPixelFormat(AstcFileHeader& header) { // Check the block size is valid. This will also prevent an invalid read from the conversion table. - if( ( header.blockdim_x < MINIMUM_ASTC_BLOCK_SIZE ) || ( header.blockdim_x > MAXIMUM_ASTC_BLOCK_SIZE ) || - ( header.blockdim_y < MINIMUM_ASTC_BLOCK_SIZE ) || ( header.blockdim_y > MAXIMUM_ASTC_BLOCK_SIZE ) ) + if((header.blockdim_x < MINIMUM_ASTC_BLOCK_SIZE) || (header.blockdim_x > MAXIMUM_ASTC_BLOCK_SIZE) || + (header.blockdim_y < MINIMUM_ASTC_BLOCK_SIZE) || (header.blockdim_y > MAXIMUM_ASTC_BLOCK_SIZE)) { return Pixel::INVALID; } // Read the equivalent pixel format from the conversion table. - return AstcLinearBlockSizeToPixelFormatTable[ header.blockdim_y - MINIMUM_ASTC_BLOCK_SIZE ][ header.blockdim_x - MINIMUM_ASTC_BLOCK_SIZE ]; + return AstcLinearBlockSizeToPixelFormatTable[header.blockdim_y - MINIMUM_ASTC_BLOCK_SIZE][header.blockdim_x - MINIMUM_ASTC_BLOCK_SIZE]; } /** @@ -115,43 +111,41 @@ Pixel::Format GetAstcPixelFormat( AstcFileHeader& header ) * @param[out] fileHeader This will be populated with the header data * @return True if the file is valid, false otherwise */ -bool LoadAstcHeader( FILE * const filePointer, unsigned int& width, unsigned int& height, AstcFileHeader& fileHeader ) +bool LoadAstcHeader(FILE* const filePointer, unsigned int& width, unsigned int& height, AstcFileHeader& fileHeader) { // Pull the bytes of the file header in as a block: - const unsigned int readLength = sizeof( AstcFileHeader ); - if( fread( &fileHeader, 1, readLength, filePointer ) != readLength ) + const unsigned int readLength = sizeof(AstcFileHeader); + if(fread(&fileHeader, 1, readLength, filePointer) != readLength) { return false; } // Check the header contains the ASTC native file identifier. - bool headerIsValid = memcmp( fileHeader.magic, FileIdentifier, sizeof( fileHeader.magic ) ) == 0; - if( !headerIsValid ) + bool headerIsValid = memcmp(fileHeader.magic, FileIdentifier, sizeof(fileHeader.magic)) == 0; + if(!headerIsValid) { - DALI_LOG_ERROR( "File is not a valid ASTC native file\n" ); + DALI_LOG_ERROR("File is not a valid ASTC native file\n"); // Return here as otherwise, if not a valid ASTC file, we are likely to pick up other header errors spuriously. return false; } // Convert the 3-byte values for width and height to a single resultant value. - width = fileHeader.xsize[0] | ( fileHeader.xsize[1] << 8 ) | ( fileHeader.xsize[2] << 16 ); - height = fileHeader.ysize[0] | ( fileHeader.ysize[1] << 8 ) | ( fileHeader.ysize[2] << 16 ); + width = fileHeader.xsize[0] | (fileHeader.xsize[1] << 8) | (fileHeader.xsize[2] << 16); + height = fileHeader.ysize[0] | (fileHeader.ysize[1] << 8) | (fileHeader.ysize[2] << 16); - const unsigned int zDepth = static_cast( fileHeader.zsize[0] ) - + ( static_cast( fileHeader.zsize[1] ) << 8 ) - + ( static_cast( fileHeader.zsize[2] ) << 16 ); + const unsigned int zDepth = static_cast(fileHeader.zsize[0]) + (static_cast(fileHeader.zsize[1]) << 8) + (static_cast(fileHeader.zsize[2]) << 16); // Check image dimensions are within limits. - if( ( width > MAX_TEXTURE_DIMENSION ) || ( height > MAX_TEXTURE_DIMENSION ) ) + if((width > MAX_TEXTURE_DIMENSION) || (height > MAX_TEXTURE_DIMENSION)) { - DALI_LOG_ERROR( "ASTC file has larger than supported dimensions: %d,%d\n", width, height ); + DALI_LOG_ERROR("ASTC file has larger than supported dimensions: %d,%d\n", width, height); headerIsValid = false; } // Confirm the ASTC block does not have any Z depth. - if( zDepth != 1 ) + if(zDepth != 1) { - DALI_LOG_ERROR( "ASTC files with z size other than 1 are not supported. Z size is: %d\n", zDepth ); + DALI_LOG_ERROR("ASTC files with z size other than 1 are not supported. Z size is: %d\n", zDepth); headerIsValid = false; } @@ -160,69 +154,68 @@ bool LoadAstcHeader( FILE * const filePointer, unsigned int& width, unsigned int } // Unnamed namespace. - // File loading API entry-point: -bool LoadAstcHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadAstcHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { AstcFileHeader fileHeader; - return LoadAstcHeader( input.file, width, height, fileHeader ); + return LoadAstcHeader(input.file, width, height, fileHeader); } // File loading API entry-point: -bool LoadBitmapFromAstc( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromAstc(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { FILE* const filePointer = input.file; - if( !filePointer ) + if(!filePointer) { - DALI_LOG_ERROR( "Null file handle passed to ASTC compressed bitmap file loader.\n" ); + DALI_LOG_ERROR("Null file handle passed to ASTC compressed bitmap file loader.\n"); return false; } // Load the header info. AstcFileHeader fileHeader; - unsigned int width, height; + unsigned int width, height; - if( !LoadAstcHeader( filePointer, width, height, fileHeader ) ) + if(!LoadAstcHeader(filePointer, width, height, fileHeader)) { - DALI_LOG_ERROR( "Could not load ASTC Header from file.\n" ); + DALI_LOG_ERROR("Could not load ASTC Header from file.\n"); return false; } // Retrieve the pixel format from the ASTC block size. - Pixel::Format pixelFormat = GetAstcPixelFormat( fileHeader ); - if( pixelFormat == Pixel::INVALID ) + Pixel::Format pixelFormat = GetAstcPixelFormat(fileHeader); + if(pixelFormat == Pixel::INVALID) { - DALI_LOG_ERROR( "No internal pixel format supported for ASTC file pixel format.\n" ); + DALI_LOG_ERROR("No internal pixel format supported for ASTC file pixel format.\n"); return false; } // Retrieve the file size. - if( fseek( filePointer, 0L, SEEK_END ) ) + if(fseek(filePointer, 0L, SEEK_END)) { - DALI_LOG_ERROR( "Could not seek through file.\n" ); + DALI_LOG_ERROR("Could not seek through file.\n"); return false; } - off_t fileSize = ftell( filePointer ); - if( fileSize == -1L ) + off_t fileSize = ftell(filePointer); + if(fileSize == -1L) { - DALI_LOG_ERROR( "Could not determine ASTC file size.\n" ); + DALI_LOG_ERROR("Could not determine ASTC file size.\n"); return false; } - if( fseek( filePointer, sizeof( AstcFileHeader ), SEEK_SET ) ) + if(fseek(filePointer, sizeof(AstcFileHeader), SEEK_SET)) { - DALI_LOG_ERROR( "Could not seek through file.\n" ); + DALI_LOG_ERROR("Could not seek through file.\n"); return false; } // Data size is file size - header size. - size_t imageByteCount = fileSize - sizeof( AstcFileHeader ); + size_t imageByteCount = fileSize - sizeof(AstcFileHeader); // Sanity-check the image data is not too large and that it is at less than 2 bytes per texel: - if( ( imageByteCount > MAX_IMAGE_DATA_SIZE ) || ( imageByteCount > ( ( static_cast< size_t >( width ) * height ) << 1 ) ) ) + if((imageByteCount > MAX_IMAGE_DATA_SIZE) || (imageByteCount > ((static_cast(width) * height) << 1))) { - DALI_LOG_ERROR( "ASTC file has too large image-data field.\n" ); + DALI_LOG_ERROR("ASTC file has too large image-data field.\n"); return false; } @@ -231,21 +224,21 @@ bool LoadBitmapFromAstc( const Dali::ImageLoader::Input& input, Dali::Devel::Pix // Compressed format won't allocate the buffer auto pixels = bitmap.GetBuffer(); - if( !pixels ) + if(!pixels) { // allocate buffer manually - auto& impl = GetImplementation( bitmap ); - impl.AllocateFixedSize( imageByteCount ); + auto& impl = GetImplementation(bitmap); + impl.AllocateFixedSize(imageByteCount); pixels = bitmap.GetBuffer(); } // Load the image data. - const size_t bytesRead = fread( pixels, 1, imageByteCount, filePointer ); + const size_t bytesRead = fread(pixels, 1, imageByteCount, filePointer); // Check the size of loaded data is what we expected. - if( bytesRead != imageByteCount ) + if(bytesRead != imageByteCount) { - DALI_LOG_ERROR( "Read of image pixel data failed.\n" ); + DALI_LOG_ERROR("Read of image pixel data failed.\n"); return false; } diff --git a/dali/internal/imaging/common/loader-astc.h b/dali/internal/imaging/common/loader-astc.h old mode 100755 new mode 100644 index ed78a7d..4d72d74 --- a/dali/internal/imaging/common/loader-astc.h +++ b/dali/internal/imaging/common/loader-astc.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_ASTC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ * */ -#include #include +#include namespace Dali { @@ -28,10 +28,8 @@ namespace Devel class PixelBuffer; } - namespace TizenPlatform { - class ResourceLoadingClient; namespace Astc @@ -40,7 +38,6 @@ const unsigned char MAGIC_BYTE_1 = 0x13; const unsigned char MAGIC_BYTE_2 = 0xAB; } // namespace Astc - /** * Loads a compressed bitmap image from a ASTC file without decoding it. * This function checks the header first @@ -49,7 +46,7 @@ const unsigned char MAGIC_BYTE_2 = 0xAB; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return True if file loaded successfully, false otherwise */ -bool LoadBitmapFromAstc( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromAstc(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * Loads the header of a ASTC file and fills in the width and height appropriately. @@ -58,8 +55,7 @@ bool LoadBitmapFromAstc( const Dali::ImageLoader::Input& input, Dali::Devel::Pix * @param[out] height Is set with the height of the image * @return True if the header was read successfully, false otherwise */ -bool LoadAstcHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); - +bool LoadAstcHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-bmp.cpp b/dali/internal/imaging/common/loader-bmp.cpp old mode 100755 new mode 100644 index 65120f2..6752735 --- a/dali/internal/imaging/common/loader-bmp.cpp +++ b/dali/internal/imaging/common/loader-bmp.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,45 +17,43 @@ #include -#include #include #include +#include namespace Dali { - namespace TizenPlatform { - namespace { -const unsigned int FileHeaderOffsetOfBF32V4 = 0x7A; -const unsigned int MaskForBFRGB565 = 0x80; +const unsigned int FileHeaderOffsetOfBF32V4 = 0x7A; +const unsigned int MaskForBFRGB565 = 0x80; const unsigned int FileHeaderOffsetOfRGB24V5 = 0x8A; enum BmpFormat { - BMP_RGB1 = 14, //BI_RGB & bpp =1 - BMP_RGB4, //BI_RGB & bpp = 4 - BMP_RGB8, //BI_RGB & bpp = 8 - BMP_RGB555, //BI_RGB & bpp = 16 - BMP_BITFIELDS555, //BI_BITFIELDS & 16bit & R:G:B = 5:5:5 - BMP_BITFIELDS32, //BI_BITFIELDS & 32bit & R:G:B:A = 8:8:8:8 - BMP_RLE8, //BI_RLE8 - BMP_RLE4, //BI_RLE4 - BMP_BITFIELDS32V4,//BI_BITFIELDS & 32bit - BMP_RGB24V5, //BI_RGB & bpp = 24 & bmp version5 + BMP_RGB1 = 14, //BI_RGB & bpp =1 + BMP_RGB4, //BI_RGB & bpp = 4 + BMP_RGB8, //BI_RGB & bpp = 8 + BMP_RGB555, //BI_RGB & bpp = 16 + BMP_BITFIELDS555, //BI_BITFIELDS & 16bit & R:G:B = 5:5:5 + BMP_BITFIELDS32, //BI_BITFIELDS & 32bit & R:G:B:A = 8:8:8:8 + BMP_RLE8, //BI_RLE8 + BMP_RLE4, //BI_RLE4 + BMP_BITFIELDS32V4, //BI_BITFIELDS & 32bit + BMP_RGB24V5, //BI_RGB & bpp = 24 & bmp version5 BMP_NOTEXIST }; struct BmpFileHeader { - unsigned short signature; // Bitmap file signature - unsigned int fileSize; // Bitmap file size in bytes - unsigned short reserved1; // Reserved bits - unsigned short reserved2; // Reserved bits - unsigned int offset; // Offset from BMP file header to BMP bits -} __attribute__ ( (__packed__)); // Stops the structure from being aligned to every 4 bytes + unsigned short signature; // Bitmap file signature + unsigned int fileSize; // Bitmap file size in bytes + unsigned short reserved1; // Reserved bits + unsigned short reserved2; // Reserved bits + unsigned int offset; // Offset from BMP file header to BMP bits +} __attribute__((__packed__)); // Stops the structure from being aligned to every 4 bytes struct BmpInfoHeader { @@ -70,7 +68,7 @@ struct BmpInfoHeader unsigned int yPixelsPerMeter; // The number of pixels per meter in y axis unsigned int numberOfColors; // The number of colors in the color table unsigned int importantColors; // The important color count -} __attribute__ ( (__packed__)); // Stops the structure from being aligned to every 4 bytes +} __attribute__((__packed__)); // Stops the structure from being aligned to every 4 bytes /** * Template function to read from the file directly into our structure. @@ -84,7 +82,7 @@ inline bool ReadHeader(FILE* fp, T& header) const unsigned int readLength = sizeof(T); // Load the information directly into our structure - if ( fread( &header, 1, readLength, fp ) != readLength ) + if(fread(&header, 1, readLength, fp) != readLength) { return false; } @@ -92,22 +90,22 @@ inline bool ReadHeader(FILE* fp, T& header) return true; } -bool LoadBmpHeader(FILE *fp, unsigned int &width, unsigned int &height, BmpFileHeader &fileHeader, BmpInfoHeader &infoHeader) +bool LoadBmpHeader(FILE* fp, unsigned int& width, unsigned int& height, BmpFileHeader& fileHeader, BmpInfoHeader& infoHeader) { - if (!ReadHeader(fp, fileHeader)) + if(!ReadHeader(fp, fileHeader)) { return false; } - if (!ReadHeader(fp, infoHeader)) + if(!ReadHeader(fp, infoHeader)) { return false; } - width = infoHeader.width; + width = infoHeader.width; height = abs(infoHeader.height); - if( infoHeader.width == 0 ) + if(infoHeader.width == 0) { return false; } @@ -126,38 +124,38 @@ bool LoadBmpHeader(FILE *fp, unsigned int &width, unsigned int &height, BmpFileH * @param[in] padding padded to a u_int32 boundary for each line * @return true, if decode successful, false otherwise */ -bool DecodeRGB24V5(FILE *fp, +bool DecodeRGB24V5(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown, - unsigned int rowStride, - unsigned int padding) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown, + unsigned int rowStride, + unsigned int padding) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_RGB24V5 format\n"); return false; } - if ( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RGB24V5 data\n"); return false; } - for(unsigned int yPos = 0; yPos < height; yPos ++) + for(unsigned int yPos = 0; yPos < height; yPos++) { unsigned char* pixelsPtr = NULL; if(topDown) { - pixelsPtr = pixels + ( yPos * rowStride); + pixelsPtr = pixels + (yPos * rowStride); } else { - pixelsPtr = pixels + (((height-1)-yPos) * rowStride); + pixelsPtr = pixels + (((height - 1) - yPos) * rowStride); } - if (fread(pixelsPtr, 1, rowStride, fp) != rowStride) + if(fread(pixelsPtr, 1, rowStride, fp) != rowStride) { DALI_LOG_ERROR("Error reading the BMP image\n"); return false; @@ -165,14 +163,14 @@ bool DecodeRGB24V5(FILE *fp, for(unsigned int i = 0; i < rowStride; i += 3) { unsigned char temp = pixelsPtr[i]; - pixelsPtr[i] = pixelsPtr[i + 2]; - pixelsPtr[i + 2] = temp; + pixelsPtr[i] = pixelsPtr[i + 2]; + pixelsPtr[i + 2] = temp; } - if (padding) + if(padding) { // move past the padding. - if( fseek(fp, padding, SEEK_CUR) ) + if(fseek(fp, padding, SEEK_CUR)) { DALI_LOG_ERROR("Error moving past BMP_RGB24V5 padding\n"); } @@ -193,38 +191,38 @@ bool DecodeRGB24V5(FILE *fp, * @param[in] padding padded to a u_int32 boundary for each line * @return true, if decode successful, false otherwise */ -bool DecodeBF32V4(FILE *fp, +bool DecodeBF32V4(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown, - unsigned int rowStride, - unsigned int padding) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown, + unsigned int rowStride, + unsigned int padding) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_BITFIELDS32V4 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_BITFIELDS32V4 data\n"); return false; } - for(unsigned int yPos = 0; yPos < height; yPos ++) + for(unsigned int yPos = 0; yPos < height; yPos++) { unsigned char* pixelsPtr = NULL; if(topDown) { - pixelsPtr = pixels + ( yPos * rowStride); + pixelsPtr = pixels + (yPos * rowStride); } else { - pixelsPtr = pixels + (((height-1)-yPos) * rowStride); + pixelsPtr = pixels + (((height - 1) - yPos) * rowStride); } - if (fread(pixelsPtr, 1, rowStride, fp) != rowStride) + if(fread(pixelsPtr, 1, rowStride, fp) != rowStride) { DALI_LOG_ERROR("Error reading the BMP image\n"); return false; @@ -232,18 +230,17 @@ bool DecodeBF32V4(FILE *fp, for(unsigned int i = 0; i < rowStride; i += 4) { unsigned char temp = pixelsPtr[i]; - pixelsPtr[i] = pixelsPtr[i + 2]; - pixelsPtr[i + 2] = temp; + pixelsPtr[i] = pixelsPtr[i + 2]; + pixelsPtr[i + 2] = temp; } - if (padding) + if(padding) { // move past the padding. - if( fseek(fp, padding, SEEK_CUR) ) + if(fseek(fp, padding, SEEK_CUR)) { DALI_LOG_ERROR("Error moving past BMP_BITFIELDS32V4 padding\n"); } } - } return true; } @@ -260,41 +257,41 @@ bool DecodeBF32V4(FILE *fp, * @param[in] padding padded to a u_int32 boundary for each line * @return true, if decode successful, false otherwise */ -bool DecodeBF32(FILE *fp, +bool DecodeBF32(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown, - unsigned int rowStride, - unsigned int padding) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown, + unsigned int rowStride, + unsigned int padding) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_BITFIELDS32 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_BITFIELDS32 data\n"); return false; } - for (unsigned int yPos = 0; yPos < height; yPos++) + for(unsigned int yPos = 0; yPos < height; yPos++) { unsigned char* pixelsPtr; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( yPos * rowStride); + pixelsPtr = pixels + (yPos * rowStride); } else { // the data in the file is bottom up, and we store the data top down - pixelsPtr = pixels + (((height-1)-yPos) * rowStride); + pixelsPtr = pixels + (((height - 1) - yPos) * rowStride); } - if (fread(pixelsPtr, 1, rowStride, fp) != rowStride) + if(fread(pixelsPtr, 1, rowStride, fp) != rowStride) { DALI_LOG_ERROR("Error reading the BMP image\n"); return false; @@ -302,14 +299,14 @@ bool DecodeBF32(FILE *fp, for(unsigned int i = 0; i < rowStride; i += 4) { unsigned char temp = pixelsPtr[i]; - pixelsPtr[i] = pixelsPtr[i + 2]; - pixelsPtr[i + 2] = temp; + pixelsPtr[i] = pixelsPtr[i + 2]; + pixelsPtr[i + 2] = temp; } - if (padding) + if(padding) { // move past the padding. - if( fseek(fp, padding, SEEK_CUR) ) + if(fseek(fp, padding, SEEK_CUR)) { DALI_LOG_ERROR("Error moving past BMP_BITFIELDS32 padding\n"); } @@ -328,34 +325,34 @@ bool DecodeBF32(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeBF565(FILE *fp, +bool DecodeBF565(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding RGB565 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking RGB565 data\n"); return false; } - width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; + width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; unsigned int rowStride = width * 2; for(unsigned int i = 0; i < height; i++) { unsigned char* pixelsPtr = NULL; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( i * rowStride); + pixelsPtr = pixels + (i * rowStride); } else { @@ -381,12 +378,12 @@ bool DecodeBF565(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeBF555(FILE *fp, +bool DecodeBF555(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { @@ -394,7 +391,7 @@ bool DecodeBF555(FILE *fp, return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_BITFIELDS555 data\n"); return false; @@ -403,39 +400,39 @@ bool DecodeBF555(FILE *fp, width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; std::vector raw(width * height * 2); - unsigned int rawStride = width * 2; - unsigned int rowStride = width * 3; + unsigned int rawStride = width * 2; + unsigned int rowStride = width * 3; - char *rawPtr = NULL; - for(unsigned int j = 0; j < height; j ++) + char* rawPtr = NULL; + for(unsigned int j = 0; j < height; j++) { - rawPtr = &raw[0] + ( j * rawStride); + rawPtr = &raw[0] + (j * rawStride); if(fread(rawPtr, 1, rawStride, fp) != rawStride) { return false; } } - for (unsigned int yPos = 0; yPos < height; yPos++) + for(unsigned int yPos = 0; yPos < height; yPos++) { unsigned char* pixelsPtr = NULL; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( yPos * rowStride); + pixelsPtr = pixels + (yPos * rowStride); } else { // the data in the file is bottom up, and we store the data top down - pixelsPtr = pixels + (((height-1)-yPos) * rowStride); + pixelsPtr = pixels + (((height - 1) - yPos) * rowStride); } - for(unsigned int k = 0; k < width; k ++) + for(unsigned int k = 0; k < width; k++) { - int index = yPos * rawStride + 2 * k; - pixelsPtr[3 * k] = ((raw[ index + 1] >> 2) & 0x1F) * 0xFF / 0x1F; - pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[ index] >> 5)) * 0xFF/ 0x1F; - pixelsPtr[3 * k + 2] = (raw[ index] & 0x1F) * 0xFF / 0x1F; + int index = yPos * rawStride + 2 * k; + pixelsPtr[3 * k] = ((raw[index + 1] >> 2) & 0x1F) * 0xFF / 0x1F; + pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[index] >> 5)) * 0xFF / 0x1F; + pixelsPtr[3 * k + 2] = (raw[index] & 0x1F) * 0xFF / 0x1F; } } return true; @@ -451,19 +448,19 @@ bool DecodeBF555(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeRGB555(FILE *fp, +bool DecodeRGB555(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_RGB555 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RGB555 data\n"); return false; @@ -471,13 +468,13 @@ bool DecodeRGB555(FILE *fp, width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; std::vector raw(width * height * 2); - unsigned int rawStride = width * 2; - unsigned int rowStride = width * 3; + unsigned int rawStride = width * 2; + unsigned int rowStride = width * 3; - char *rawPtr = NULL; - for(unsigned int j = 0; j < height; j ++) + char* rawPtr = NULL; + for(unsigned int j = 0; j < height; j++) { - rawPtr = &raw[0] + ( j * rawStride); + rawPtr = &raw[0] + (j * rawStride); if(fread(rawPtr, 1, rawStride, fp) != rawStride) { return false; @@ -486,24 +483,23 @@ bool DecodeRGB555(FILE *fp, for(unsigned int i = 0; i < height; i++) { unsigned char* pixelsPtr = NULL; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( i * rowStride); + pixelsPtr = pixels + (i * rowStride); } else { // the data in the file is bottom up, and we store the data top down pixelsPtr = pixels + (((height - 1) - i) * rowStride); } - for(unsigned int k = 0; k < width; k ++) + for(unsigned int k = 0; k < width; k++) { - int index = i * rawStride + 2 * k; - pixelsPtr[3 * k] = ((raw[ index + 1] >> 2) & 0x1F) * 0xFF / 0x1F; - pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[ index] >> 5)) * 0xFF/ 0x1F; - pixelsPtr[3 * k + 2] = (raw[ index] & 0x1F) * 0xFF / 0x1F; + int index = i * rawStride + 2 * k; + pixelsPtr[3 * k] = ((raw[index + 1] >> 2) & 0x1F) * 0xFF / 0x1F; + pixelsPtr[3 * k + 1] = (((raw[index + 1] & 0x03) << 3) | (raw[index] >> 5)) * 0xFF / 0x1F; + pixelsPtr[3 * k + 2] = (raw[index] & 0x1F) * 0xFF / 0x1F; } - } return true; } @@ -518,30 +514,29 @@ bool DecodeRGB555(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeRGB1(FILE *fp, +bool DecodeRGB1(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_RGB1 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RGB1 data\n"); return false; } - unsigned char colorTable[8] = {0}; - char cmd; - unsigned int fillw = ((width & 63) != 0) ? width + 64 - (width & 63) : width; + unsigned char colorTable[8] = {0}; + char cmd; + unsigned int fillw = ((width & 63) != 0) ? width + 64 - (width & 63) : width; std::vector colorIndex(fillw * height); - unsigned int rowStride = fillw * 3; // RGB - + unsigned int rowStride = fillw * 3; // RGB if(fread(colorTable, 1, 8, fp) != 8) { @@ -568,33 +563,33 @@ bool DecodeRGB1(FILE *fp, for(unsigned int index = 0; index < height; index = index + 1) { unsigned char* pixelsPtr = NULL; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( index * rowStride); + pixelsPtr = pixels + (index * rowStride); } else { // the data in the file is bottom up, and we store the data top down pixelsPtr = pixels + (((height - 1) - index) * rowStride); } - for(unsigned int j = 0; j < fillw; j ++) + for(unsigned int j = 0; j < fillw; j++) { unsigned int ctIndex = 0; - if((fillw * index + j ) < (fillw * height)) + if((fillw * index + j) < (fillw * height)) { - ctIndex = colorIndex[ fillw * index + j ]; + ctIndex = colorIndex[fillw * index + j]; } else { break; } // temp solution for PLM bug P130411-5268, there is one mono bmp that cause DecodeRGB1 API crash. - if( ((3 * j + 2) < height * fillw * 3) && (ctIndex < 2)) + if(((3 * j + 2) < height * fillw * 3) && (ctIndex < 2)) { - pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2]; + pixelsPtr[3 * j] = colorTable[4 * ctIndex + 2]; pixelsPtr[3 * j + 1] = colorTable[4 * ctIndex + 1]; - pixelsPtr[3 * j + 2] = colorTable[4 * ctIndex ]; + pixelsPtr[3 * j + 2] = colorTable[4 * ctIndex]; } } } @@ -611,29 +606,29 @@ bool DecodeRGB1(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeRGB4(FILE *fp, +bool DecodeRGB4(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_RGB4 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RGB4 data\n"); return false; } - char colorTable[64]; - char cmd; - unsigned int fillw = ((width & 3) != 0) ? width + 4 - (width & 3) : width; + char colorTable[64]; + char cmd; + unsigned int fillw = ((width & 3) != 0) ? width + 4 - (width & 3) : width; std::vector colorIndex(fillw * height); - unsigned int rowStride = fillw * 3; + unsigned int rowStride = fillw * 3; if(fread(colorTable, 1, 64, fp) != 64) { @@ -642,12 +637,12 @@ bool DecodeRGB4(FILE *fp, for(unsigned int i = 0; i < fillw * height; i += 2) { - if (fread(&cmd, 1, 1, fp) != 1) + if(fread(&cmd, 1, 1, fp) != 1) { return false; } - colorIndex[i] = cmd >> 4; + colorIndex[i] = cmd >> 4; colorIndex[i + 1] = cmd & (0x0F); } unsigned int ctIndex = 0; @@ -655,22 +650,22 @@ bool DecodeRGB4(FILE *fp, for(unsigned int index = 0; index < height; index = index + 1) { unsigned char* pixelsPtr = NULL; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( index * rowStride); + pixelsPtr = pixels + (index * rowStride); } else { // the data in the file is bottom up, and we store the data top down pixelsPtr = pixels + (((height - 1) - index) * rowStride); } - for(unsigned int j = 0; j < fillw; j ++) + for(unsigned int j = 0; j < fillw; j++) { - ctIndex = colorIndex[ fillw * index + j ]; - pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2]; + ctIndex = colorIndex[fillw * index + j]; + pixelsPtr[3 * j] = colorTable[4 * ctIndex + 2]; pixelsPtr[(3 * j + 1)] = colorTable[4 * ctIndex + 1]; - pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex ]; + pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex]; } } @@ -687,19 +682,19 @@ bool DecodeRGB4(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeRGB8(FILE *fp, +bool DecodeRGB8(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { DALI_LOG_ERROR("Error decoding BMP_RGB8 format\n"); return false; } - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RGB8 data\n"); return false; @@ -707,17 +702,17 @@ bool DecodeRGB8(FILE *fp, std::vector colorTable(1024); width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; - char cmd; + char cmd; std::vector colorIndex(width * height); - unsigned int rowStride = width * 3;//RGB8->RGB24 + unsigned int rowStride = width * 3; //RGB8->RGB24 if(fread(&colorTable[0], 1, 1024, fp) != 1024) { return false; } - for(unsigned int i = 0; i < width * height; i ++) + for(unsigned int i = 0; i < width * height; i++) { - if (fread(&cmd, 1, 1, fp) != 1) + if(fread(&cmd, 1, 1, fp) != 1) { return false; } @@ -728,22 +723,22 @@ bool DecodeRGB8(FILE *fp, for(unsigned int index = 0; index < height; index = index + 1) { unsigned char* pixelsPtr = NULL; - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsPtr = pixels + ( index * rowStride); + pixelsPtr = pixels + (index * rowStride); } else { // the data in the file is bottom up, and we store the data top down pixelsPtr = pixels + (((height - 1) - index) * rowStride); } - for(unsigned int j = 0; j < width; j ++) + for(unsigned int j = 0; j < width; j++) { - ctIndex = colorIndex[ width * index + j ]; - pixelsPtr[ 3 * j ] = colorTable[4 * ctIndex + 2]; + ctIndex = colorIndex[width * index + j]; + pixelsPtr[3 * j] = colorTable[4 * ctIndex + 2]; pixelsPtr[(3 * j + 1)] = colorTable[4 * ctIndex + 1]; - pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex ]; + pixelsPtr[(3 * j + 2)] = colorTable[4 * ctIndex]; } } return true; @@ -759,12 +754,12 @@ bool DecodeRGB8(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeRLE4(FILE *fp, +bool DecodeRLE4(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { @@ -772,39 +767,39 @@ bool DecodeRLE4(FILE *fp, return false; } unsigned char* pixelsPtr = pixels; - width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; - char cmd[2]; - unsigned int cmdStride = 2; - char colorTable[64]; + width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; + char cmd[2]; + unsigned int cmdStride = 2; + char colorTable[64]; std::vector colorIndex(width * height >> 1); std::vector run; - unsigned int x = 0; - unsigned int y = 0; - unsigned int dx = 0; - unsigned int dy = 0; + unsigned int x = 0; + unsigned int y = 0; + unsigned int dx = 0; + unsigned int dy = 0; width += (width & 1); width = width >> 1; bool finish = false; - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RLE4 data\n"); return false; } - if (fread(colorTable, 1, 64, fp) != 64) + if(fread(colorTable, 1, 64, fp) != 64) { return false; } while((x >> 1) + y * width < width * height) { - if (finish) + if(finish) { break; } - if (fread(cmd, 1, cmdStride, fp) != cmdStride) + if(fread(cmd, 1, cmdStride, fp) != cmdStride) { return false; } @@ -817,10 +812,10 @@ bool DecodeRLE4(FILE *fp, break; case 0: // end of line x = 0; - y ++; + y++; break; case 2: // delta - if (fread(cmd, 1, cmdStride, fp) != cmdStride) + if(fread(cmd, 1, cmdStride, fp) != cmdStride) { DALI_LOG_ERROR("Error reading the BMP image\n"); return false; @@ -855,9 +850,9 @@ bool DecodeRLE4(FILE *fp, } else { - for(unsigned int i = 0; i < length; i ++) + for(unsigned int i = 0; i < length; i++) { - if((i & 1) == 0)//copy high to low + if((i & 1) == 0) //copy high to low { colorIndex[((x + i) >> 1) + width * (height - y - 1)] |= ((run[i >> 1] & 0xF0) >> 4); } @@ -878,14 +873,14 @@ bool DecodeRLE4(FILE *fp, { length += (length & 1); length >>= 1; - for(unsigned int i = 0; i < length; i ++) + for(unsigned int i = 0; i < length; i++) { - colorIndex[(height-y-1)*width + i + (x >> 1)] = cmd[1]; + colorIndex[(height - y - 1) * width + i + (x >> 1)] = cmd[1]; } } else { - for(unsigned int i = 0; i < length; i ++) + for(unsigned int i = 0; i < length; i++) { if((i & 1) == 0) { @@ -902,17 +897,17 @@ bool DecodeRLE4(FILE *fp, } int ctIndexHigh = 0; - int ctIndexLow = 0; - for(unsigned int index = 0; index < (width * height ); index = index + 1) + int ctIndexLow = 0; + for(unsigned int index = 0; index < (width * height); index = index + 1) { - ctIndexHigh = colorIndex[ index] >> 4; - ctIndexLow = colorIndex[index] & (0x0F); - pixelsPtr[6 * index ] = colorTable[4 * ctIndexHigh + 2]; + ctIndexHigh = colorIndex[index] >> 4; + ctIndexLow = colorIndex[index] & (0x0F); + pixelsPtr[6 * index] = colorTable[4 * ctIndexHigh + 2]; pixelsPtr[6 * index + 1] = colorTable[4 * ctIndexHigh + 1]; - pixelsPtr[6 * index + 2] = colorTable[4 * ctIndexHigh ]; + pixelsPtr[6 * index + 2] = colorTable[4 * ctIndexHigh]; pixelsPtr[6 * index + 3] = colorTable[4 * ctIndexLow + 2]; pixelsPtr[6 * index + 4] = colorTable[4 * ctIndexLow + 1]; - pixelsPtr[6 * index + 5] = colorTable[4 * ctIndexLow ]; + pixelsPtr[6 * index + 5] = colorTable[4 * ctIndexLow]; } return true; } @@ -927,12 +922,12 @@ bool DecodeRLE4(FILE *fp, * @param[in] topDown indicate image data is read from bottom or from top * @return true, if decode successful, false otherwise */ -bool DecodeRLE8(FILE *fp, +bool DecodeRLE8(FILE* fp, unsigned char* pixels, - unsigned int width, - unsigned int height, - unsigned int offset, - bool topDown) + unsigned int width, + unsigned int height, + unsigned int offset, + bool topDown) { if(fp == NULL || pixels == NULL) { @@ -940,44 +935,44 @@ bool DecodeRLE8(FILE *fp, return false; } unsigned char* pixelsPtr = pixels; - unsigned int x = 0; - unsigned int y = 0; - unsigned int cmdStride = 2; + unsigned int x = 0; + unsigned int y = 0; + unsigned int cmdStride = 2; width = ((width & 3) != 0) ? width + 4 - (width & 3) : width; std::vector colorTable(1024); - char cmd[2]; + char cmd[2]; std::vector colorIndex(width * height); - if( fseek(fp, offset, SEEK_SET) ) + if(fseek(fp, offset, SEEK_SET)) { DALI_LOG_ERROR("Error seeking BMP_RLE8 data\n"); return false; } - if (fread(&colorTable[0], 1, 1024, fp) != 1024) + if(fread(&colorTable[0], 1, 1024, fp) != 1024) { return false; } - unsigned int dx = 0; - unsigned int dy = 0; - bool finish = false; - unsigned int length = 0; - unsigned int copylength = 0; + unsigned int dx = 0; + unsigned int dy = 0; + bool finish = false; + unsigned int length = 0; + unsigned int copylength = 0; std::vector run; - while((x + y * width) < width * height ) + while((x + y * width) < width * height) { - if (finish) + if(finish) { break; } - if (fread(cmd, 1, cmdStride, fp) != cmdStride) + if(fread(cmd, 1, cmdStride, fp) != cmdStride) { return false; } - if(cmd[0] == 0)//ESCAPE + if(cmd[0] == 0) //ESCAPE { switch(cmd[1]) { @@ -986,10 +981,10 @@ bool DecodeRLE8(FILE *fp, break; case 0: // end of line x = 0; - y ++; + y++; break; case 2: // delta - if (fread(cmd, 1, cmdStride, fp) != cmdStride) + if(fread(cmd, 1, cmdStride, fp) != cmdStride) { DALI_LOG_ERROR("Error reading the BMP image\n"); return false; @@ -1001,7 +996,7 @@ bool DecodeRLE8(FILE *fp, break; default: //decode a literal run - length = cmd[1] & (0xFF); + length = cmd[1] & (0xFF); copylength = length; //absolute mode must be word-aligned length += (length & 1); @@ -1019,11 +1014,11 @@ bool DecodeRLE8(FILE *fp, x += copylength; break; } - }// end if cmd[0] == + } // end if cmd[0] == else { length = cmd[0] & (0xFF); - for(unsigned int i = 0; i < length; i ++) + for(unsigned int i = 0; i < length; i++) { colorIndex[(height - y - 1) * width + x] = cmd[1]; x++; @@ -1033,27 +1028,27 @@ bool DecodeRLE8(FILE *fp, int ctIndex = 0; for(unsigned int index = 0; index < width * height; index = index + 1) { - ctIndex = colorIndex[ index]; - pixelsPtr[3 * index ] = colorTable[4 * ctIndex + 2]; + ctIndex = colorIndex[index]; + pixelsPtr[3 * index] = colorTable[4 * ctIndex + 2]; pixelsPtr[3 * index + 1] = colorTable[4 * ctIndex + 1]; - pixelsPtr[3 * index + 2] = colorTable[4 * ctIndex ]; + pixelsPtr[3 * index + 2] = colorTable[4 * ctIndex]; } return true; } } // unnamed namespace -bool LoadBmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadBmpHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { BmpFileHeader fileHeader; BmpInfoHeader infoHeader; - bool ret = LoadBmpHeader( input.file, width, height, fileHeader, infoHeader ); + bool ret = LoadBmpHeader(input.file, width, height, fileHeader, infoHeader); return ret; } -bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromBmp(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { //DALI_ASSERT_DEBUG( bitmap.GetPackedPixelsProfile() != 0 && "Need a packed pixel bitmap to load into." ); FILE* const fp = input.file; @@ -1062,30 +1057,30 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe DALI_LOG_ERROR("Error loading bitmap\n"); return false; } - BmpFormat customizedFormat = BMP_NOTEXIST; + BmpFormat customizedFormat = BMP_NOTEXIST; BmpFileHeader fileHeader; BmpInfoHeader infoHeader; // Load the header info unsigned int width, height; - if (!LoadBmpHeader(fp, width, height, fileHeader, infoHeader)) + if(!LoadBmpHeader(fp, width, height, fileHeader, infoHeader)) { - return false; + return false; } Pixel::Format pixelFormat = Pixel::RGB888; switch(infoHeader.compression) { case 0: - switch (infoHeader.bitsPerPixel) + switch(infoHeader.bitsPerPixel) { case 32: pixelFormat = Pixel::BGR8888; break; case 24: - if(fileHeader.offset == FileHeaderOffsetOfRGB24V5)//0x8A + if(fileHeader.offset == FileHeaderOffsetOfRGB24V5) //0x8A { customizedFormat = BMP_RGB24V5; } @@ -1114,7 +1109,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe DALI_LOG_WARNING("%d bits per pixel not supported for BMP files\n", infoHeader.bitsPerPixel); return false; } - break; + break; case 1: //// RLE8 { if(infoHeader.bitsPerPixel == 8) @@ -1135,7 +1130,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe { if(infoHeader.bitsPerPixel == 16) { - if( fseek(fp, 14 + infoHeader.infoHeaderSize + 1, SEEK_SET) ) + if(fseek(fp, 14 + infoHeader.infoHeaderSize + 1, SEEK_SET)) { return false; } @@ -1150,7 +1145,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe { pixelFormat = Pixel::RGB565; } - else if((mask & 0x80) == 0)// mask is 0x 7C + else if((mask & 0x80) == 0) // mask is 0x 7C { customizedFormat = BMP_BITFIELDS555; } @@ -1161,7 +1156,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe } else if(infoHeader.bitsPerPixel == 32) { - if(fileHeader.offset == FileHeaderOffsetOfBF32V4)// 0x7A + if(fileHeader.offset == FileHeaderOffsetOfBF32V4) // 0x7A { customizedFormat = BMP_BITFIELDS32V4; } @@ -1180,77 +1175,77 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe bool topDown = false; // if height is negative, bitmap data is top down - if (infoHeader.height<0) + if(infoHeader.height < 0) { - infoHeader.height = abs(infoHeader.height); - height = infoHeader.height; - topDown = true; + infoHeader.height = abs(infoHeader.height); + height = infoHeader.height; + topDown = true; } - unsigned int rowStride = infoHeader.width * (infoHeader.bitsPerPixel >>3); + unsigned int rowStride = infoHeader.width * (infoHeader.bitsPerPixel >> 3); // bitmaps row stride is padded to 4 bytes unsigned int padding = (rowStride % 4); - if (padding) + if(padding) { padding = 4 - padding; } - int imageW = infoHeader.width; - int pixelBufferW = infoHeader.width; - int pixelBufferH = infoHeader.height; + int imageW = infoHeader.width; + int pixelBufferW = infoHeader.width; + int pixelBufferH = infoHeader.height; auto newPixelFormat = Pixel::Format::INVALID; switch(customizedFormat) { - case BMP_RLE8: - case BMP_RGB8: - case BMP_RGB4: - case BMP_RLE4: - case BMP_RGB555: - case BMP_BITFIELDS555: - { - pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW; - pixelBufferH = abs(infoHeader.height); - newPixelFormat = Pixel::RGB888; - break; - } - case BMP_RGB1: - { - pixelBufferW = ((imageW & 63) != 0) ? imageW + 64 - (imageW & 63) : imageW; - pixelBufferH = abs(infoHeader.height); - newPixelFormat = Pixel::RGB888; - break; - } - case BMP_BITFIELDS32: - case BMP_BITFIELDS32V4: - { - pixelBufferH = abs(infoHeader.height); - newPixelFormat = Pixel::RGB8888; - break; - } - case BMP_RGB24V5: - { - newPixelFormat = Pixel::RGB888; - break; - } - default: - if(pixelFormat == Pixel::RGB565 ) + case BMP_RLE8: + case BMP_RGB8: + case BMP_RGB4: + case BMP_RLE4: + case BMP_RGB555: + case BMP_BITFIELDS555: { - pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW; - pixelBufferH = abs(infoHeader.height); - newPixelFormat = Pixel::RGB565; + pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW; + pixelBufferH = abs(infoHeader.height); + newPixelFormat = Pixel::RGB888; + break; } - else + case BMP_RGB1: { - pixelBufferW = infoHeader.width; - pixelBufferH = infoHeader.height; - newPixelFormat = pixelFormat; + pixelBufferW = ((imageW & 63) != 0) ? imageW + 64 - (imageW & 63) : imageW; + pixelBufferH = abs(infoHeader.height); + newPixelFormat = Pixel::RGB888; + break; } - break; + case BMP_BITFIELDS32: + case BMP_BITFIELDS32V4: + { + pixelBufferH = abs(infoHeader.height); + newPixelFormat = Pixel::RGB8888; + break; + } + case BMP_RGB24V5: + { + newPixelFormat = Pixel::RGB888; + break; + } + default: + if(pixelFormat == Pixel::RGB565) + { + pixelBufferW = ((imageW & 3) != 0) ? imageW + 4 - (imageW & 3) : imageW; + pixelBufferH = abs(infoHeader.height); + newPixelFormat = Pixel::RGB565; + } + else + { + pixelBufferW = infoHeader.width; + pixelBufferH = infoHeader.height; + newPixelFormat = pixelFormat; + } + break; } - bitmap = Dali::Devel::PixelBuffer::New(pixelBufferW, pixelBufferH, newPixelFormat); + bitmap = Dali::Devel::PixelBuffer::New(pixelBufferW, pixelBufferH, newPixelFormat); auto pixels = bitmap.GetBuffer(); // Read the raw bitmap data @@ -1261,7 +1256,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe { case BMP_RGB1: { - decodeResult = DecodeRGB1( fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown); + decodeResult = DecodeRGB1(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown); break; } case BMP_RGB4: @@ -1271,17 +1266,17 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe } case BMP_RLE4: { - decodeResult = DecodeRLE4( fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown); + decodeResult = DecodeRLE4(fp, pixels, infoHeader.width, abs(infoHeader.height), 14 + infoHeader.infoHeaderSize, topDown); break; } case BMP_BITFIELDS32: { - decodeResult = DecodeBF32(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding); + decodeResult = DecodeBF32(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown, rowStride, padding); break; } case BMP_BITFIELDS555: { - decodeResult = DecodeBF555(fp, pixels,infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown); + decodeResult = DecodeBF555(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown); break; } case BMP_RGB555: @@ -1313,24 +1308,24 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe { if(pixelFormat == Pixel::RGB565) { - decodeResult = DecodeBF565(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown); + decodeResult = DecodeBF565(fp, pixels, infoHeader.width, abs(infoHeader.height), fileHeader.offset, topDown); } else { - for (unsigned int yPos = 0; yPos < height; yPos++) + for(unsigned int yPos = 0; yPos < height; yPos++) { - if (topDown) + if(topDown) { // the data in the file is top down, and we store the data top down - pixelsIterator = pixels + ( yPos * rowStride); + pixelsIterator = pixels + (yPos * rowStride); } else { // the data in the file is bottom up, and we store the data top down - pixelsIterator = pixels + (((height-1)-yPos) * rowStride); + pixelsIterator = pixels + (((height - 1) - yPos) * rowStride); } - if (fread(pixelsIterator, 1, rowStride, fp) != rowStride) + if(fread(pixelsIterator, 1, rowStride, fp) != rowStride) { DALI_LOG_ERROR("Error reading the BMP image\n"); break; @@ -1338,19 +1333,19 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe // If 24 bit mode then swap Blue and Red pixels // BGR888 doesn't seem to be supported by dali-core - if (infoHeader.bitsPerPixel == 24 ) + if(infoHeader.bitsPerPixel == 24) { for(unsigned int i = 0; i < rowStride; i += 3) { - unsigned char temp = pixelsIterator[i]; - pixelsIterator[i] = pixelsIterator[i+2]; - pixelsIterator[i+2] = temp; + unsigned char temp = pixelsIterator[i]; + pixelsIterator[i] = pixelsIterator[i + 2]; + pixelsIterator[i + 2] = temp; } } - if (padding) + if(padding) { - if( fseek(fp, padding, SEEK_CUR) ) // move past the padding. + if(fseek(fp, padding, SEEK_CUR)) // move past the padding. { DALI_LOG_ERROR("Error moving past BMP padding\n"); } @@ -1362,7 +1357,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe } } // switch - if( !decodeResult ) + if(!decodeResult) { return false; } diff --git a/dali/internal/imaging/common/loader-bmp.h b/dali/internal/imaging/common/loader-bmp.h old mode 100755 new mode 100644 index 2e95efb..dd8cda1 --- a/dali/internal/imaging/common/loader-bmp.h +++ b/dali/internal/imaging/common/loader-bmp.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_BMP_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ * */ -#include #include +#include namespace Dali { @@ -28,10 +28,8 @@ namespace Devel class PixelBuffer; } - namespace TizenPlatform { - class ResourceLoadingClient; namespace Bmp @@ -47,7 +45,7 @@ const unsigned char MAGIC_BYTE_2 = 0x4D; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file decoded successfully, false otherwise */ -bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromBmp(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * Loads the header of a BMP file and fills in the width and height appropriately. @@ -57,7 +55,7 @@ bool LoadBitmapFromBmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe * @param[out] height Is set with the height of the image * @return true if the file's header was read successully, false otherwise */ -bool LoadBmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadBmpHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-gif.cpp b/dali/internal/imaging/common/loader-gif.cpp old mode 100755 new mode 100644 index cf9b010..57da14f --- a/dali/internal/imaging/common/loader-gif.cpp +++ b/dali/internal/imaging/common/loader-gif.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include -#include #include +#include #include // We need to check if giflib has the new open and close API (including error parameter). @@ -30,13 +30,10 @@ namespace Dali { - namespace TizenPlatform { - namespace { - // simple class to enforce clean-up of GIF structures struct AutoCleanupGif { @@ -52,14 +49,14 @@ struct AutoCleanupGif // clean up GIF resources #ifdef LIBGIF_VERSION_5_1_OR_ABOVE int errorCode = 0; //D_GIF_SUCCEEDED is 0 - DGifCloseFile( gifInfo, &errorCode ); + DGifCloseFile(gifInfo, &errorCode); - if( errorCode ) + if(errorCode) { - DALI_LOG_ERROR( "GIF Loader: DGifCloseFile Error. Code: %d\n", errorCode ); + DALI_LOG_ERROR("GIF Loader: DGifCloseFile Error. Code: %d\n", errorCode); } #else - DGifCloseFile( gifInfo ); + DGifCloseFile(gifInfo); #endif } } @@ -77,35 +74,35 @@ struct InterlacePair // Used in the GIF interlace algorithm to determine the order and which location to read data from // the file. -const InterlacePair INTERLACE_PAIR_TABLE [] = { - { 0, 8 }, // Starting at 0, read every 8 bytes. - { 4, 8 }, // Starting at 4, read every 8 bytes. - { 2, 4 }, // Starting at 2, read every 4 bytes. - { 1, 2 }, // Starting at 1, read every 2 bytes. +const InterlacePair INTERLACE_PAIR_TABLE[] = { + {0, 8}, // Starting at 0, read every 8 bytes. + {4, 8}, // Starting at 4, read every 8 bytes. + {2, 4}, // Starting at 2, read every 4 bytes. + {1, 2}, // Starting at 1, read every 2 bytes. }; -const unsigned int INTERLACE_PAIR_TABLE_SIZE( sizeof( INTERLACE_PAIR_TABLE ) / sizeof( InterlacePair ) ); +const unsigned int INTERLACE_PAIR_TABLE_SIZE(sizeof(INTERLACE_PAIR_TABLE) / sizeof(InterlacePair)); /// Function used by Gif_Lib to read from the image file. -int ReadDataFromGif(GifFileType *gifInfo, GifByteType *data, int length) +int ReadDataFromGif(GifFileType* gifInfo, GifByteType* data, int length) { - FILE *fp = reinterpret_cast(gifInfo->UserData); - return fread( data, sizeof( GifByteType ), length, fp); + FILE* fp = reinterpret_cast(gifInfo->UserData); + return fread(data, sizeof(GifByteType), length, fp); } /// Loads the GIF Header. -bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileType** gifInfo) +bool LoadGifHeader(FILE* fp, unsigned int& width, unsigned int& height, GifFileType** gifInfo) { int errorCode = 0; //D_GIF_SUCCEEDED is 0 #ifdef LIBGIF_VERSION_5_1_OR_ABOVE - *gifInfo = DGifOpen( reinterpret_cast(fp), ReadDataFromGif, &errorCode ); + *gifInfo = DGifOpen(reinterpret_cast(fp), ReadDataFromGif, &errorCode); #else - *gifInfo = DGifOpen( reinterpret_cast(fp), ReadDataFromGif ); + *gifInfo = DGifOpen(reinterpret_cast(fp), ReadDataFromGif); #endif - if ( !(*gifInfo) || errorCode ) + if(!(*gifInfo) || errorCode) { - DALI_LOG_ERROR( "GIF Loader: DGifOpen Error. Code: %d\n", errorCode ); + DALI_LOG_ERROR("GIF Loader: DGifOpen Error. Code: %d\n", errorCode); return false; } @@ -113,7 +110,7 @@ bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileT height = (*gifInfo)->SHeight; // No proper size in GIF. - if ( width <= 0 || height <= 0 ) + if(width <= 0 || height <= 0) { return false; } @@ -122,21 +119,21 @@ bool LoadGifHeader(FILE *fp, unsigned int &width, unsigned int &height, GifFileT } /// Decode the GIF image. -bool DecodeImage( GifFileType* gifInfo, unsigned char* decodedData, const unsigned int width, const unsigned int height, const unsigned int bytesPerRow ) +bool DecodeImage(GifFileType* gifInfo, unsigned char* decodedData, const unsigned int width, const unsigned int height, const unsigned int bytesPerRow) { - if ( gifInfo->Image.Interlace ) + if(gifInfo->Image.Interlace) { // If the image is interlaced, then use the GIF interlace algorithm to read the file appropriately. - const InterlacePair* interlacePairPtr( INTERLACE_PAIR_TABLE ); - for ( unsigned int interlacePair = 0; interlacePair < INTERLACE_PAIR_TABLE_SIZE; ++interlacePair, ++interlacePairPtr ) + const InterlacePair* interlacePairPtr(INTERLACE_PAIR_TABLE); + for(unsigned int interlacePair = 0; interlacePair < INTERLACE_PAIR_TABLE_SIZE; ++interlacePair, ++interlacePairPtr) { - for( unsigned int currentByte = interlacePairPtr->startingByte; currentByte < height; currentByte += interlacePairPtr->incrementalByte ) + for(unsigned int currentByte = interlacePairPtr->startingByte; currentByte < height; currentByte += interlacePairPtr->incrementalByte) { unsigned char* row = decodedData + currentByte * bytesPerRow; - if ( DGifGetLine( gifInfo, row, width ) == GIF_ERROR ) + if(DGifGetLine(gifInfo, row, width) == GIF_ERROR) { - DALI_LOG_ERROR( "GIF Loader: Error reading Interlaced GIF\n" ); + DALI_LOG_ERROR("GIF Loader: Error reading Interlaced GIF\n"); return false; } } @@ -145,13 +142,13 @@ bool DecodeImage( GifFileType* gifInfo, unsigned char* decodedData, const unsign else { // Non-interlace does not require any erratic reading / jumping. - unsigned char* decodedDataPtr( decodedData ); + unsigned char* decodedDataPtr(decodedData); - for ( unsigned int row = 0; row < height; ++row ) + for(unsigned int row = 0; row < height; ++row) { - if ( DGifGetLine( gifInfo, decodedDataPtr, width ) == GIF_ERROR) + if(DGifGetLine(gifInfo, decodedDataPtr, width) == GIF_ERROR) { - DALI_LOG_ERROR( "GIF Loader: Error reading non-interlaced GIF\n" ); + DALI_LOG_ERROR("GIF Loader: Error reading non-interlaced GIF\n"); return false; } decodedDataPtr += bytesPerRow; @@ -161,10 +158,10 @@ bool DecodeImage( GifFileType* gifInfo, unsigned char* decodedData, const unsign } // Retrieves the colors used in the GIF image. -GifColorType* GetImageColors( SavedImage* image, GifFileType* gifInfo ) +GifColorType* GetImageColors(SavedImage* image, GifFileType* gifInfo) { - GifColorType* color( NULL ); - if ( image->ImageDesc.ColorMap ) + GifColorType* color(NULL); + if(image->ImageDesc.ColorMap) { color = image->ImageDesc.ColorMap->Colors; } @@ -177,53 +174,53 @@ GifColorType* GetImageColors( SavedImage* image, GifFileType* gifInfo ) } /// Called when we want to handle IMAGE_DESC_RECORD_TYPE -bool HandleImageDescriptionRecordType( Dali::Devel::PixelBuffer& bitmap, GifFileType* gifInfo, unsigned int width, unsigned int height, bool& finished ) +bool HandleImageDescriptionRecordType(Dali::Devel::PixelBuffer& bitmap, GifFileType* gifInfo, unsigned int width, unsigned int height, bool& finished) { - if ( DGifGetImageDesc( gifInfo ) == GIF_ERROR ) + if(DGifGetImageDesc(gifInfo) == GIF_ERROR) { - DALI_LOG_ERROR( "GIF Loader: Error getting Image Description\n" ); + DALI_LOG_ERROR("GIF Loader: Error getting Image Description\n"); return false; } // Ensure there is at least 1 image in the GIF. - if ( gifInfo->ImageCount < 1 ) + if(gifInfo->ImageCount < 1) { - DALI_LOG_ERROR( "GIF Loader: No Images\n" ); + DALI_LOG_ERROR("GIF Loader: No Images\n"); return false; } - Pixel::Format pixelFormat( Pixel::RGB888 ); + Pixel::Format pixelFormat(Pixel::RGB888); - SavedImage* image( &gifInfo->SavedImages[ gifInfo->ImageCount - 1 ] ); - const GifImageDesc& desc( image->ImageDesc ); + SavedImage* image(&gifInfo->SavedImages[gifInfo->ImageCount - 1]); + const GifImageDesc& desc(image->ImageDesc); - auto decodedData = new unsigned char[ width * height * sizeof( GifPixelType ) ]; + auto decodedData = new unsigned char[width * height * sizeof(GifPixelType)]; - std::unique_ptr ptr{ decodedData }; + std::unique_ptr ptr{decodedData}; - const unsigned int bytesPerRow( width * sizeof( GifPixelType ) ); - const unsigned int actualWidth( desc.Width ); - const unsigned int actualHeight( desc.Height ); + const unsigned int bytesPerRow(width * sizeof(GifPixelType)); + const unsigned int actualWidth(desc.Width); + const unsigned int actualHeight(desc.Height); // Create a buffer to store the decoded data. - bitmap = Dali::Devel::PixelBuffer::New( actualWidth, actualHeight, pixelFormat ); + bitmap = Dali::Devel::PixelBuffer::New(actualWidth, actualHeight, pixelFormat); // Decode the GIF Image - if ( !DecodeImage( gifInfo, decodedData, actualWidth, actualHeight, bytesPerRow ) ) + if(!DecodeImage(gifInfo, decodedData, actualWidth, actualHeight, bytesPerRow)) { return false; } // Get the colormap for the GIF - GifColorType* color( GetImageColors( image, gifInfo ) ); + GifColorType* color(GetImageColors(image, gifInfo)); // If it's an animated GIF, we still only read the first image // Create and populate pixel buffer. auto pixels = bitmap.GetBuffer(); - for (unsigned int row = 0; row < actualHeight; ++row) + for(unsigned int row = 0; row < actualHeight; ++row) { - for (unsigned int column = 0; column < actualWidth; ++column) + for(unsigned int column = 0; column < actualWidth; ++column) { unsigned char index = decodedData[row * width + column]; @@ -238,30 +235,30 @@ bool HandleImageDescriptionRecordType( Dali::Devel::PixelBuffer& bitmap, GifFile } /// Called when we want to handle EXTENSION_RECORD_TYPE -bool HandleExtensionRecordType( GifFileType* gifInfo ) +bool HandleExtensionRecordType(GifFileType* gifInfo) { - SavedImage image; - GifByteType *extensionByte( NULL ); + SavedImage image; + GifByteType* extensionByte(NULL); #ifdef LIBGIF_VERSION_5_1_OR_ABOVE ExtensionBlock extensionBlocks; image.ExtensionBlocks = &extensionBlocks; image.ExtensionBlockCount = 1; - int *extensionBlockTypePointer = &image.ExtensionBlocks->Function; + int* extensionBlockTypePointer = &image.ExtensionBlocks->Function; #else - image.ExtensionBlocks = NULL; + image.ExtensionBlocks = NULL; image.ExtensionBlockCount = 0; - int *extensionBlockTypePointer = &image.Function; + int* extensionBlockTypePointer = &image.Function; #endif // Not really interested in the extensions so just skip them unless there is an error. - for ( int extRetCode = DGifGetExtension( gifInfo, extensionBlockTypePointer, &extensionByte ); - extensionByte != NULL; - extRetCode = DGifGetExtensionNext( gifInfo, &extensionByte ) ) + for(int extRetCode = DGifGetExtension(gifInfo, extensionBlockTypePointer, &extensionByte); + extensionByte != NULL; + extRetCode = DGifGetExtensionNext(gifInfo, &extensionByte)) { - if ( extRetCode == GIF_ERROR ) + if(extRetCode == GIF_ERROR) { - DALI_LOG_ERROR( "GIF Loader: Error reading GIF Extension record.\n" ); + DALI_LOG_ERROR("GIF Loader: Error reading GIF Extension record.\n"); return false; } } @@ -271,53 +268,53 @@ bool HandleExtensionRecordType( GifFileType* gifInfo ) } // unnamed namespace -bool LoadGifHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadGifHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { - GifFileType* gifInfo = NULL; + GifFileType* gifInfo = NULL; AutoCleanupGif autoCleanupGif(gifInfo); - FILE* const fp = input.file; + FILE* const fp = input.file; return LoadGifHeader(fp, width, height, &gifInfo); } -bool LoadBitmapFromGif( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromGif(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { FILE* const fp = input.file; // Load the GIF Header file. - GifFileType* gifInfo( NULL ); - unsigned int width( 0 ); - unsigned int height( 0 ); - if ( !LoadGifHeader( fp, width, height, &gifInfo ) ) + GifFileType* gifInfo(NULL); + unsigned int width(0); + unsigned int height(0); + if(!LoadGifHeader(fp, width, height, &gifInfo)) { return false; } - AutoCleanupGif autoGif( gifInfo ); + AutoCleanupGif autoGif(gifInfo); // Check each record in the GIF file. - bool finished( false ); - GifRecordType recordType( UNDEFINED_RECORD_TYPE ); - for ( int returnCode = DGifGetRecordType( gifInfo, &recordType ); - !finished && recordType != TERMINATE_RECORD_TYPE; - returnCode = DGifGetRecordType( gifInfo, &recordType ) ) + bool finished(false); + GifRecordType recordType(UNDEFINED_RECORD_TYPE); + for(int returnCode = DGifGetRecordType(gifInfo, &recordType); + !finished && recordType != TERMINATE_RECORD_TYPE; + returnCode = DGifGetRecordType(gifInfo, &recordType)) { - if ( returnCode == GIF_ERROR ) + if(returnCode == GIF_ERROR) { - DALI_LOG_ERROR( "GIF Loader: Error getting Record Type\n" ); + DALI_LOG_ERROR("GIF Loader: Error getting Record Type\n"); return false; } - if( IMAGE_DESC_RECORD_TYPE == recordType ) + if(IMAGE_DESC_RECORD_TYPE == recordType) { - if ( !HandleImageDescriptionRecordType( bitmap, gifInfo, width, height, finished ) ) + if(!HandleImageDescriptionRecordType(bitmap, gifInfo, width, height, finished)) { return false; } } - else if ( EXTENSION_RECORD_TYPE == recordType ) + else if(EXTENSION_RECORD_TYPE == recordType) { - if ( !HandleExtensionRecordType( gifInfo )) + if(!HandleExtensionRecordType(gifInfo)) { return false; } diff --git a/dali/internal/imaging/common/loader-gif.h b/dali/internal/imaging/common/loader-gif.h old mode 100755 new mode 100644 index a215ae5..f1a1123 --- a/dali/internal/imaging/common/loader-gif.h +++ b/dali/internal/imaging/common/loader-gif.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_GIF_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ * */ -#include #include +#include namespace Dali { @@ -28,10 +28,8 @@ namespace Devel class PixelBuffer; } - namespace TizenPlatform { - class ResourceLoadingClient; namespace Gif @@ -48,7 +46,7 @@ const unsigned char MAGIC_BYTE_2 = 0x49; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file decoded successfully, false otherwise */ -bool LoadBitmapFromGif( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromGif(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * Loads the header of a GIF file and fills in the width and height appropriately. @@ -58,7 +56,7 @@ bool LoadBitmapFromGif( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe * @param[in/out] height Is set with the height of the image * @return true if the file's header was read successully, false otherwise */ -bool LoadGifHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadGifHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-ico.cpp b/dali/internal/imaging/common/loader-ico.cpp old mode 100755 new mode 100644 index 23331c3..03cefa8 --- a/dali/internal/imaging/common/loader-ico.cpp +++ b/dali/internal/imaging/common/loader-ico.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,19 +51,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace TizenPlatform { - namespace { // Reserved 2 bytes + type 2 bytes + count 2 bytes + count * 16 bytes @@ -73,20 +71,20 @@ const unsigned char ICO_FILE_HEADER = 22; // besides, there are rgba color data = numberOfColors * 4 bytes const unsigned char ICO_IMAGE_INFO_HEADER = 40; -typedef unsigned char DATA8; -#define A_VAL(p) (reinterpret_cast< DATA8 * >( p )[3]) +typedef unsigned char DATA8; +#define A_VAL(p) (reinterpret_cast(p)[3]) -#define RGB_JOIN(r,g,b) \ - (((r) << 16) + ((g) << 8) + (b)) +#define RGB_JOIN(r, g, b) \ + (((r) << 16) + ((g) << 8) + (b)) -#define ARGB_JOIN(a,r,g,b) \ - (((a) << 24) + ((r) << 16) + ((g) << 8) + (b)) +#define ARGB_JOIN(a, r, g, b) \ + (((a) << 24) + ((r) << 16) + ((g) << 8) + (b)) -bool read_ushort(unsigned char *map, size_t length, size_t *position, unsigned short *ret) +bool read_ushort(unsigned char* map, size_t length, size_t* position, unsigned short* ret) { unsigned char b[2]; - if (*position + 2 > length) + if(*position + 2 > length) { return false; } @@ -96,16 +94,16 @@ bool read_ushort(unsigned char *map, size_t length, size_t *position, unsigned s return true; } -bool read_uint(unsigned char *map, size_t length, size_t *position, unsigned int *ret) +bool read_uint(unsigned char* map, size_t length, size_t* position, unsigned int* ret) { unsigned char b[4]; - unsigned int i; + unsigned int i; - if (*position + 4 > length) + if(*position + 4 > length) { return false; } - for (i = 0; i < 4; i++) + for(i = 0; i < 4; i++) { b[i] = map[(*position)++]; } @@ -113,9 +111,9 @@ bool read_uint(unsigned char *map, size_t length, size_t *position, unsigned int return true; } -bool read_uchar(unsigned char *map, size_t length, size_t *position, unsigned char *ret) +bool read_uchar(unsigned char* map, size_t length, size_t* position, unsigned char* ret) { - if (*position + 1 > length) + if(*position + 1 > length) { return false; } @@ -123,9 +121,9 @@ bool read_uchar(unsigned char *map, size_t length, size_t *position, unsigned ch return true; } -bool read_mem(unsigned char *map, size_t length, size_t *position, void *buffer, int size) +bool read_mem(unsigned char* map, size_t length, size_t* position, void* buffer, int size) { - if (*position + size > length) + if(*position + size > length) { return false; } @@ -144,62 +142,62 @@ enum enum { - ICON = 1, + ICON = 1, CURSOR = 2 }; struct IcoData { - int pdelta; - int w, h; - int cols; - int bpp, planes; - int hot_x, hot_y; + int pdelta; + int w, h; + int cols; + int bpp, planes; + int hot_x, hot_y; unsigned int bmoffset, bmsize; }; -bool LoadIcoHeaderHelper( FILE* fp, - IcoData& chosen, - Dali::Vector& map, - unsigned int& fsize ) +bool LoadIcoHeaderHelper(FILE* fp, + IcoData& chosen, + Dali::Vector& map, + unsigned int& fsize) { - memset( &chosen, 0, sizeof(chosen) ); + memset(&chosen, 0, sizeof(chosen)); if(fp == NULL) { DALI_LOG_ERROR("Error loading bitmap\n"); return false; } - size_t position = 0; + size_t position = 0; unsigned short word; - unsigned char byte; + unsigned char byte; - if( fseek(fp,0,SEEK_END) ) + if(fseek(fp, 0, SEEK_END)) { DALI_LOG_ERROR("Error seeking ICO data\n"); return false; } long positionIndicator = ftell(fp); - fsize = 0u; + fsize = 0u; - if( positionIndicator > -1L ) + if(positionIndicator > -1L) { fsize = static_cast(positionIndicator); } - if( 0u == fsize ) + if(0u == fsize) { return false; } - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking ICO data\n"); return false; } - if (fsize < (ICO_FILE_HEADER + ICO_IMAGE_INFO_HEADER)) //6 + 16 + 40 + if(fsize < (ICO_FILE_HEADER + ICO_IMAGE_INFO_HEADER)) //6 + 16 + 40 { return false; } @@ -211,123 +209,122 @@ bool LoadIcoHeaderHelper( FILE* fp, return false; } - int search = BIGGEST; + int search = BIGGEST; unsigned short reserved, type, count; - if (!read_ushort(&map[0], fsize, &position, &reserved)) + if(!read_ushort(&map[0], fsize, &position, &reserved)) { return false; } - if (!read_ushort(&map[0], fsize, &position, &type)) + if(!read_ushort(&map[0], fsize, &position, &type)) { return false; } - if (!read_ushort(&map[0], fsize, &position, &count)) + if(!read_ushort(&map[0], fsize, &position, &count)) { return false; } - if (!((reserved == 0) && + if(!((reserved == 0) && ((type == ICON) || (type == CURSOR)) && (count != 0))) { return false; } - search = BIGGEST; - chosen.pdelta = 0; + search = BIGGEST; + chosen.pdelta = 0; bool have_choice = false; - for (unsigned short i = 0; i < count; i++) + for(unsigned short i = 0; i < count; i++) { unsigned char tw = 0, th = 0, tcols = 0; - if (!read_uchar(&map[0], fsize, &position, &tw)) + if(!read_uchar(&map[0], fsize, &position, &tw)) { return false; } int w = tw; - if (w <= 0) + if(w <= 0) { w = 256; } - if (!read_uchar(&map[0], fsize, &position, &th)) + if(!read_uchar(&map[0], fsize, &position, &th)) { return false; - } int h = th; - if (h <= 0) + if(h <= 0) { h = 256; } - if (!read_uchar(&map[0], fsize, &position, &tcols)) + if(!read_uchar(&map[0], fsize, &position, &tcols)) { return false; } int cols = tcols; - if (!read_uchar(&map[0], fsize, &position, &byte)) + if(!read_uchar(&map[0], fsize, &position, &byte)) { return false; } - if (!read_ushort(&map[0], fsize, &position, &word)) + if(!read_ushort(&map[0], fsize, &position, &word)) { return false; } - int planes=0; - if (type == 1) + int planes = 0; + if(type == 1) { planes = word; } //else hot_x = word; - if (!read_ushort(&map[0], fsize, &position, &word)) + if(!read_ushort(&map[0], fsize, &position, &word)) { return false; } - int bpp=0; - if (type == 1) + int bpp = 0; + if(type == 1) { bpp = word; } // 0 colors means 256 for paletized modes. // Note: We must not do this conversion for bpp greater than 8, as there is no palette. - if( bpp <= 8 && cols == 0 ) + if(bpp <= 8 && cols == 0) { cols = 256; } //else hot_y = word; unsigned int bmoffset, bmsize; - if (!read_uint(&map[0], fsize, &position, &bmsize)) + if(!read_uint(&map[0], fsize, &position, &bmsize)) { return false; } - if (!read_uint(&map[0], fsize, &position, &bmoffset)) + if(!read_uint(&map[0], fsize, &position, &bmoffset)) { return false; } - if ((bmsize <= 0) || (bmoffset <= 0) || (bmoffset >= fsize)) + if((bmsize <= 0) || (bmoffset <= 0) || (bmoffset >= fsize)) { return false; } - if (search == BIGGEST) + if(search == BIGGEST) { int pdelta = w * h; - if ((!have_choice) || - ((pdelta >= chosen.pdelta) && - (((bpp >= 3) && (bpp >= chosen.bpp)) || - ((bpp < 3) && (cols >= chosen.cols))))) + if((!have_choice) || + ((pdelta >= chosen.pdelta) && + (((bpp >= 3) && (bpp >= chosen.bpp)) || + ((bpp < 3) && (cols >= chosen.cols))))) { - have_choice = true; - chosen.pdelta = pdelta; - chosen.w = w; - chosen.h = h; - chosen.cols = cols; - chosen.bpp = bpp; - chosen.planes = planes; - chosen.bmsize = bmsize; + have_choice = true; + chosen.pdelta = pdelta; + chosen.w = w; + chosen.h = h; + chosen.cols = cols; + chosen.bpp = bpp; + chosen.planes = planes; + chosen.bmsize = bmsize; chosen.bmoffset = bmoffset; } } } - if (chosen.bmoffset == 0) + if(chosen.bmoffset == 0) { return false; } @@ -350,52 +347,52 @@ bool LoadIcoHeaderHelper( FILE* fp, * @param[in] palette The palette */ bool HandleBitsPerPixel( - const unsigned int bitcount, - Dali::Vector& map, - unsigned int*& pix, - Dali::Vector& surface, - const unsigned int width, - const unsigned int height, - const unsigned int fsize, - size_t& position, - Dali::Vector& pixbuf, - const unsigned int stride, - const Dali::Vector& palette) + const unsigned int bitcount, + Dali::Vector& map, + unsigned int*& pix, + Dali::Vector& surface, + const unsigned int width, + const unsigned int height, + const unsigned int fsize, + size_t& position, + Dali::Vector& pixbuf, + const unsigned int stride, + const Dali::Vector& palette) { // Note: Switch is in order of most common format first. - switch( bitcount ) + switch(bitcount) { case 32: { unsigned char* p = &map[position]; - pix = &surface[0] + ( ( height - 1 ) * width ); + pix = &surface[0] + ((height - 1) * width); - for( unsigned int i = 0; i < height; i++ ) + for(unsigned int i = 0; i < height; i++) { - for( unsigned int j = 0; j < width; j++ ) + for(unsigned int j = 0; j < width; j++) { - *pix++ = ARGB_JOIN( p[3], p[0], p[1], p[2] ); + *pix++ = ARGB_JOIN(p[3], p[0], p[1], p[2]); p += 4; } // Move the output up 1 line (we subtract 2 lines because we moved forward one line while copying). - pix -= ( width * 2 ); + pix -= (width * 2); } break; } case 24: { - for( unsigned int i = 0; i < height; i++ ) + for(unsigned int i = 0; i < height; i++) { - pix = &surface[0] + ( ( height - 1 - i ) * width ); - if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) ) + pix = &surface[0] + ((height - 1 - i) * width); + if(!read_mem(&map[0], fsize, &position, &pixbuf[0], stride)) { return false; } unsigned char* p = &pixbuf[0]; - for( unsigned int j = 0; j < width; j++ ) + for(unsigned int j = 0; j < width; j++) { - *pix++ = ARGB_JOIN( 0xff, p[0], p[1], p[2] ); + *pix++ = ARGB_JOIN(0xff, p[0], p[1], p[2]); p += 3; } } @@ -404,15 +401,15 @@ bool HandleBitsPerPixel( case 8: { - for( unsigned int i = 0; i < height; i++ ) + for(unsigned int i = 0; i < height; i++) { - pix = &surface[0] + ( ( height - 1 - i ) * width ); - if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) ) + pix = &surface[0] + ((height - 1 - i) * width); + if(!read_mem(&map[0], fsize, &position, &pixbuf[0], stride)) { return false; } unsigned char* p = &pixbuf[0]; - for( unsigned int j = 0; j < width; j++ ) + for(unsigned int j = 0; j < width; j++) { *pix++ = palette[*p++]; } @@ -422,17 +419,17 @@ bool HandleBitsPerPixel( case 4: { - for( unsigned int i = 0; i < height; i++ ) + for(unsigned int i = 0; i < height; i++) { - pix = &surface[0] + ( ( height - 1 - i ) * width ); - if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) ) + pix = &surface[0] + ((height - 1 - i) * width); + if(!read_mem(&map[0], fsize, &position, &pixbuf[0], stride)) { return false; } unsigned char* p = &pixbuf[0]; - for( unsigned int j = 0; j < width; j++ ) + for(unsigned int j = 0; j < width; j++) { - if( j & 0x1 ) + if(j & 0x1) { *pix = palette[*p & 0x0f]; p++; @@ -449,25 +446,25 @@ bool HandleBitsPerPixel( case 1: { - for( unsigned int i = 0; i < height; i++ ) + for(unsigned int i = 0; i < height; i++) { - pix = &surface[0] + ( ( height - 1 - i ) * width ); - if( !read_mem( &map[0], fsize, &position, &pixbuf[0], stride ) ) + pix = &surface[0] + ((height - 1 - i) * width); + if(!read_mem(&map[0], fsize, &position, &pixbuf[0], stride)) { return false; } unsigned char* p = &pixbuf[0]; - for( unsigned int j = 0; j < width; j += 8 ) + for(unsigned int j = 0; j < width; j += 8) { - *pix++ = palette[ *p >> 7 ]; - *pix++ = palette[ *p >> 6 & 0x01 ]; - *pix++ = palette[ *p >> 5 & 0x01 ]; - *pix++ = palette[ *p >> 4 & 0x01 ]; - *pix++ = palette[ *p >> 3 & 0x01 ]; - *pix++ = palette[ *p >> 2 & 0x01 ]; - *pix++ = palette[ *p >> 1 & 0x01 ]; - *pix++ = palette[ *p >> 0 & 0x01 ]; + *pix++ = palette[*p >> 7]; + *pix++ = palette[*p >> 6 & 0x01]; + *pix++ = palette[*p >> 5 & 0x01]; + *pix++ = palette[*p >> 4 & 0x01]; + *pix++ = palette[*p >> 3 & 0x01]; + *pix++ = palette[*p >> 2 & 0x01]; + *pix++ = palette[*p >> 1 & 0x01]; + *pix++ = palette[*p >> 0 & 0x01]; p++; } @@ -477,7 +474,7 @@ bool HandleBitsPerPixel( default: { - DALI_LOG_WARNING( "Image file contains unsupported bits-per-pixel %d\n", bitcount ); + DALI_LOG_WARNING("Image file contains unsupported bits-per-pixel %d\n", bitcount); return false; } } @@ -498,55 +495,55 @@ bool HandleBitsPerPixel( * @param[in/out] surface A reference to the surface buffer */ bool ApplyMask( - Dali::Vector& map, - const unsigned int fsize, - size_t& position, - Dali::Vector& maskbuf, - const unsigned int bitStride, - const unsigned int width, - const unsigned int height, - unsigned int*& pix, - Dali::Vector& surface) + Dali::Vector& map, + const unsigned int fsize, + size_t& position, + Dali::Vector& maskbuf, + const unsigned int bitStride, + const unsigned int width, + const unsigned int height, + unsigned int*& pix, + Dali::Vector& surface) { - if( !read_mem( &map[0], fsize, &position, &maskbuf[0], bitStride * height ) ) + if(!read_mem(&map[0], fsize, &position, &maskbuf[0], bitStride * height)) { return false; } // Apply mask. // Precalc to save time in the loops. - unsigned int bytesPerWidth = width / 8; - unsigned int bytesRemainingPerWidth = width - ( bytesPerWidth << 3 ); + unsigned int bytesPerWidth = width / 8; + unsigned int bytesRemainingPerWidth = width - (bytesPerWidth << 3); // Loop for each line of the image. - for( unsigned int i = 0; i < height; ++i ) + for(unsigned int i = 0; i < height; ++i) { - unsigned char *m = &maskbuf[0] + ( bitStride * i ); - pix = &surface[0] + ( ( height - 1 - i ) * width ); + unsigned char* m = &maskbuf[0] + (bitStride * i); + pix = &surface[0] + ((height - 1 - i) * width); // Do chunks of 8 pixels first so mask operations can be unrolled. - for( unsigned int j = 0; j < bytesPerWidth; ++j ) + for(unsigned int j = 0; j < bytesPerWidth; ++j) { // Unrolled 8 bits of the mask to avoid many conditions and branches. - A_VAL( pix++ ) = ( *m & ( 1 << 7 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 6 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 5 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 4 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 3 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 2 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 1 ) ) ? 0x00 : 0xff; - A_VAL( pix++ ) = ( *m & ( 1 << 0 ) ) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 7)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 6)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 5)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 4)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 3)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 2)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 1)) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << 0)) ? 0x00 : 0xff; m++; } // Handle any remaining width ( < 8 ) or images that are < 8 wide. - if( bytesRemainingPerWidth > 0 ) + if(bytesRemainingPerWidth > 0) { - for( unsigned int j = 0; j < bytesRemainingPerWidth; ++j ) + for(unsigned int j = 0; j < bytesRemainingPerWidth; ++j) { // Note: Although we are doing less that a bytes worth of mask, we still always start on the first bit. // If the image is smaller than 8 pixels wide, each mask will still start on a new byte. - A_VAL( pix++ ) = ( *m & ( 1 << ( 7 - j ) ) ) ? 0x00 : 0xff; + A_VAL(pix++) = (*m & (1 << (7 - j))) ? 0x00 : 0xff; } m++; } @@ -555,162 +552,162 @@ bool ApplyMask( return true; } -}//unnamed namespace +} //unnamed namespace -bool LoadIcoHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadIcoHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { - IcoData chosen; + IcoData chosen; Dali::Vector map; - unsigned int fsize; - FILE* const fp = input.file; + unsigned int fsize; + FILE* const fp = input.file; - if ( false == LoadIcoHeaderHelper(fp, chosen, map, fsize) ) + if(false == LoadIcoHeaderHelper(fp, chosen, map, fsize)) { return false; } - width = chosen.w; + width = chosen.w; height = chosen.h; return true; } -bool LoadBitmapFromIco( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromIco(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { - IcoData chosen; + IcoData chosen; Dali::Vector map; - unsigned int fsize; - FILE* const fp = input.file; + unsigned int fsize; + FILE* const fp = input.file; - if ( false == LoadIcoHeaderHelper(fp, chosen, map, fsize) ) + if(false == LoadIcoHeaderHelper(fp, chosen, map, fsize)) { return false; } - Dali::Vector pal; - Dali::Vector surface; + Dali::Vector pal; + Dali::Vector surface; Dali::Vector maskbuf; Dali::Vector pixbuf; pal.Resize(256 * 4); - unsigned int dword; + unsigned int dword; unsigned short word; - int diff_size = 0; + int diff_size = 0; unsigned int* pix; - size_t position = chosen.bmoffset;//22 == position + size_t position = chosen.bmoffset; //22 == position - unsigned int w = chosen.w; - unsigned int h = chosen.h; + unsigned int w = chosen.w; + unsigned int h = chosen.h; unsigned int cols = chosen.cols; // read bmp header time... let's do some checking - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // headersize - dont care } - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // width } - if (dword > 0) + if(dword > 0) { - if (dword != w) + if(dword != w) { - w = dword; + w = dword; diff_size = 1; } } - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // height } - if (dword > 0) + if(dword > 0) { - if (dword != (h * 2)) + if(dword != (h * 2)) { - h = dword / 2; + h = dword / 2; diff_size = 1; } } - if (diff_size) + if(diff_size) { DALI_LOG_WARNING("Broken ICO file!\n"); } // Set up the surface as soon as we have the width and height, so we have a black image if there are any further errors. - surface.Resize( w * h * 4 ); - memset( &surface[0], 0, w * h * 4 ); + surface.Resize(w * h * 4); + memset(&surface[0], 0, w * h * 4); - if (!read_ushort(&map[0], fsize, &position, &word)) + if(!read_ushort(&map[0], fsize, &position, &word)) { return false; // planes } //planes2 = word; - if (!read_ushort(&map[0], fsize, &position, &word)) + if(!read_ushort(&map[0], fsize, &position, &word)) { return false; // bitcount } unsigned int bitcount = word; - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // compression } //compression = dword; - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // imagesize } //imagesize = dword; - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // z pixels per m } - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // y pizels per m } - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // colors used } //colorsused = dword; - if (!read_uint(&map[0], fsize, &position, &dword)) + if(!read_uint(&map[0], fsize, &position, &dword)) { return false; // colors important } - for( unsigned int i = 0; i < cols ; i ++ ) + for(unsigned int i = 0; i < cols; i++) { unsigned char a, r, g, b; - if (!read_uchar(&map[0], fsize, &position, &b)) + if(!read_uchar(&map[0], fsize, &position, &b)) { return false; } - if (!read_uchar(&map[0], fsize, &position, &g)) + if(!read_uchar(&map[0], fsize, &position, &g)) { return false; } - if (!read_uchar(&map[0], fsize, &position, &r)) + if(!read_uchar(&map[0], fsize, &position, &r)) { return false; } - if (!read_uchar(&map[0], fsize, &position, &a)) + if(!read_uchar(&map[0], fsize, &position, &a)) { return false; } - pal[i] = ARGB_JOIN( 0xff, b, g, r ); + pal[i] = ARGB_JOIN(0xff, b, g, r); } // This is the reference way of calculating the total number of bytes necessary to store one row of pixels. - unsigned int stride = ( ( ( bitcount * w ) + 31 ) / 32 ) * 4; - unsigned int bitStride = ( ( w + 31 ) / 32 ) * 4; + unsigned int stride = (((bitcount * w) + 31) / 32) * 4; + unsigned int bitStride = ((w + 31) / 32) * 4; // Pixbuf only ever contains one scanline worth of data. - pixbuf.Resize( stride ); - maskbuf.Resize( bitStride * h ); + pixbuf.Resize(stride); + maskbuf.Resize(bitStride * h); // Handle different bits-per-pixel. if(!HandleBitsPerPixel(bitcount, map, pix, surface, w, h, fsize, position, pixbuf, stride, pal)) @@ -719,19 +716,19 @@ bool LoadBitmapFromIco( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe } // From the spec: If bpp is less than 32, there will be a 1bpp mask bitmap also. - if(( bitcount < 32 ) && !ApplyMask(map, fsize, position, maskbuf, bitStride, w, h, pix, surface)) + if((bitcount < 32) && !ApplyMask(map, fsize, position, maskbuf, bitStride, w, h, pix, surface)) { // Return false if not able to apply mask when the bpp is less than 32 return false; } - bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::Format::RGBA8888); + bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::Format::RGBA8888); auto pixels = bitmap.GetBuffer(); - memcpy( pixels, &surface[0], w * h * 4 ); + memcpy(pixels, &surface[0], w * h * 4); return true; } -} +} // namespace TizenPlatform -} +} // namespace Dali diff --git a/dali/internal/imaging/common/loader-ico.h b/dali/internal/imaging/common/loader-ico.h old mode 100755 new mode 100644 index c68f154..fefa753 --- a/dali/internal/imaging/common/loader-ico.h +++ b/dali/internal/imaging/common/loader-ico.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_ICO_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ * */ -#include #include +#include namespace Dali { @@ -30,7 +30,6 @@ class PixelBuffer; namespace TizenPlatform { - class ResourceLoadingClient; namespace Ico @@ -38,13 +37,13 @@ namespace Ico //00 00 01 00 01 00 20 20 const unsigned char MAGIC_BYTE_1 = 0x00; const unsigned char MAGIC_BYTE_2 = 0x00; -} +} // namespace Ico /** * @param[in] input Information about the input image (including file pointer) * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file decoded successfully, false otherwise */ -bool LoadBitmapFromIco( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromIco(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * @param[in] input Information about the input image (including file pointer) @@ -52,7 +51,7 @@ bool LoadBitmapFromIco( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe * @param[out] height of image * @return true if header loaded successfully, false otherwise */ -bool LoadIcoHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadIcoHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-jpeg-turbo.cpp b/dali/internal/imaging/common/loader-jpeg-turbo.cpp old mode 100755 new mode 100644 index 1848a1c..901ce7e --- a/dali/internal/imaging/common/loader-jpeg-turbo.cpp +++ b/dali/internal/imaging/common/loader-jpeg-turbo.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,54 +15,53 @@ * */ - // CLASS HEADER +// CLASS HEADER #include // EXTERNAL HEADERS -#include -#include -#include -#include +#include #include #include #include +#include #include -#include +#include #include -#include +#include +#include +#include -#include -#include #include - +#include +#include // INTERNAL HEADERS -#include -#include #include +#include #include +#include namespace { using Dali::Vector; -namespace Pixel = Dali::Pixel; -using PixelArray = unsigned char*; -const unsigned int DECODED_L8 = 1; -const unsigned int DECODED_RGB888 = 3; +namespace Pixel = Dali::Pixel; +using PixelArray = unsigned char*; +const unsigned int DECODED_L8 = 1; +const unsigned int DECODED_RGB888 = 3; const unsigned int DECODED_RGBA8888 = 4; /** Transformations that can be applied to decoded pixels to respect exif orientation * codes in image headers */ enum class JpegTransform { - NONE, //< no transformation 0th-Row = top & 0th-Column = left - FLIP_HORIZONTAL, //< horizontal flip 0th-Row = top & 0th-Column = right - FLIP_VERTICAL, //< vertical flip 0th-Row = bottom & 0th-Column = right - TRANSPOSE, //< transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left - TRANSVERSE, //< transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top - ROTATE_90, //< 90-degree clockwise rotation 0th-Row = right & 0th-Column = top - ROTATE_180, //< 180-degree rotation 0th-Row = right & 0th-Column = bottom - ROTATE_270, //< 270-degree clockwise (or 90 ccw) 0th-Row = left & 0th-Column = bottom + NONE, //< no transformation 0th-Row = top & 0th-Column = left + FLIP_HORIZONTAL, //< horizontal flip 0th-Row = top & 0th-Column = right + FLIP_VERTICAL, //< vertical flip 0th-Row = bottom & 0th-Column = right + TRANSPOSE, //< transpose across UL-to-LR axis 0th-Row = bottom & 0th-Column = left + TRANSVERSE, //< transpose across UR-to-LL axis 0th-Row = left & 0th-Column = top + ROTATE_90, //< 90-degree clockwise rotation 0th-Row = right & 0th-Column = top + ROTATE_180, //< 180-degree rotation 0th-Row = right & 0th-Column = bottom + ROTATE_270, //< 270-degree clockwise (or 90 ccw) 0th-Row = left & 0th-Column = bottom }; /** @@ -72,24 +71,24 @@ enum class JpegTransform struct JpegErrorState { struct jpeg_error_mgr errorManager; - jmp_buf jumpBuffer; + jmp_buf jumpBuffer; }; /** * @brief Called by the JPEG library when it hits an error. * We jump out of the library so our loader code can return an error. */ -void JpegErrorHandler ( j_common_ptr cinfo ) +void JpegErrorHandler(j_common_ptr cinfo) { - DALI_LOG_ERROR( "JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n" ); + DALI_LOG_ERROR("JpegErrorHandler(): libjpeg-turbo fatal error in JPEG decoding.\n"); /* cinfo->err really points to a JpegErrorState struct, so coerce pointer */ - JpegErrorState * myerr = reinterpret_cast( cinfo->err ); + JpegErrorState* myerr = reinterpret_cast(cinfo->err); /* Return control to the setjmp point */ - longjmp( myerr->jumpBuffer, 1 ); + longjmp(myerr->jumpBuffer, 1); } -void JpegOutputMessageHandler( j_common_ptr cinfo ) +void JpegOutputMessageHandler(j_common_ptr cinfo) { /* Stop libjpeg from printing to stderr - Do Nothing */ } @@ -98,16 +97,16 @@ void JpegOutputMessageHandler( j_common_ptr cinfo ) * LibJPEG Turbo tjDecompress2 API doesn't distinguish between errors that still allow * the JPEG to be displayed and fatal errors. */ -bool IsJpegErrorFatal( const std::string& errorMessage ) +bool IsJpegErrorFatal(const std::string& errorMessage) { - if( ( errorMessage.find("Corrupt JPEG data") != std::string::npos ) || - ( errorMessage.find("Invalid SOS parameters") != std::string::npos ) || - ( errorMessage.find("Invalid JPEG file structure") != std::string::npos ) || - ( errorMessage.find("Unsupported JPEG process") != std::string::npos ) || - ( errorMessage.find("Unsupported marker type") != std::string::npos ) || - ( errorMessage.find("Bogus marker length") != std::string::npos ) || - ( errorMessage.find("Bogus DQT index") != std::string::npos ) || - ( errorMessage.find("Bogus Huffman table definition") != std::string::npos )) + if((errorMessage.find("Corrupt JPEG data") != std::string::npos) || + (errorMessage.find("Invalid SOS parameters") != std::string::npos) || + (errorMessage.find("Invalid JPEG file structure") != std::string::npos) || + (errorMessage.find("Unsupported JPEG process") != std::string::npos) || + (errorMessage.find("Unsupported marker type") != std::string::npos) || + (errorMessage.find("Bogus marker length") != std::string::npos) || + (errorMessage.find("Bogus DQT index") != std::string::npos) || + (errorMessage.find("Bogus Huffman table definition") != std::string::npos)) { return false; } @@ -154,17 +153,24 @@ public: UniquePointerSetter(std::unique_ptr& uniquePointer) : mUniquePointer(uniquePointer), mRawPointer(nullptr) - {} + { + } /// @brief Pointer to Pointer cast operator - operator T** () { return &mRawPointer; } + operator T**() + { + return &mRawPointer; + } /// @brief Destructor, reset the unique_ptr - ~UniquePointerSetter() { mUniquePointer.reset(mRawPointer); } + ~UniquePointerSetter() + { + mUniquePointer.reset(mRawPointer); + } private: std::unique_ptr& mUniquePointer; - T* mRawPointer; + T* mRawPointer; }; template @@ -173,17 +179,17 @@ UniquePointerSetter SetPointer(std::unique_ptr& uniquePo return UniquePointerSetter{uniquePointer}; } -using TransformFunction = std::function; +using TransformFunction = std::function; using TransformFunctionArray = std::array; // 1, 3 and 4 bytes per pixel /// @brief Select the transform function depending on the pixel format TransformFunction GetTransformFunction(const TransformFunctionArray& functions, - Pixel::Format pixelFormat) + Pixel::Format pixelFormat) { auto function = TransformFunction{}; int decodedPixelSize = Pixel::GetBytesPerPixel(pixelFormat); - switch( decodedPixelSize ) + switch(decodedPixelSize) { case DECODED_L8: { @@ -212,57 +218,57 @@ TransformFunction GetTransformFunction(const TransformFunctionArray& functions, // Storing Exif fields as properties template -R ConvertExifNumeric( const ExifEntry& entry ) +R ConvertExifNumeric(const ExifEntry& entry) { return static_cast((*reinterpret_cast(entry.data))); } -void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd ) +void AddExifFieldPropertyMap(Dali::Property::Map& out, const ExifEntry& entry, ExifIfd ifd) { - auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd )); - switch( entry.format ) + auto shortName = std::string(exif_tag_get_name_in_ifd(entry.tag, ifd)); + switch(entry.format) { case EXIF_FORMAT_ASCII: { - out.Insert( shortName, std::string( reinterpret_cast(entry.data), entry.size ) ); + out.Insert(shortName, std::string(reinterpret_cast(entry.data), entry.size)); break; } case EXIF_FORMAT_SHORT: { - out.Insert( shortName, ConvertExifNumeric(entry) ); + out.Insert(shortName, ConvertExifNumeric(entry)); break; } case EXIF_FORMAT_LONG: { - out.Insert( shortName, ConvertExifNumeric(entry) ); + out.Insert(shortName, ConvertExifNumeric(entry)); break; } case EXIF_FORMAT_SSHORT: { - out.Insert( shortName, ConvertExifNumeric(entry) ); + out.Insert(shortName, ConvertExifNumeric(entry)); break; } case EXIF_FORMAT_SLONG: { - out.Insert( shortName, ConvertExifNumeric(entry) ); + out.Insert(shortName, ConvertExifNumeric(entry)); break; } case EXIF_FORMAT_FLOAT: { - out.Insert (shortName, ConvertExifNumeric(entry) ); + out.Insert(shortName, ConvertExifNumeric(entry)); break; } case EXIF_FORMAT_DOUBLE: { - out.Insert( shortName, ConvertExifNumeric(entry) ); + out.Insert(shortName, ConvertExifNumeric(entry)); break; } case EXIF_FORMAT_RATIONAL: { - auto values = reinterpret_cast( entry.data ); + auto values = reinterpret_cast(entry.data); Dali::Property::Array array; - array.Add( static_cast(values[0]) ); - array.Add( static_cast(values[1]) ); + array.Add(static_cast(values[0])); + array.Add(static_cast(values[1])); out.Insert(shortName, array); break; } @@ -278,7 +284,7 @@ void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, } case EXIF_FORMAT_SRATIONAL: { - auto values = reinterpret_cast( entry.data ); + auto values = reinterpret_cast(entry.data); Dali::Property::Array array; array.Add(values[0]); array.Add(values[1]); @@ -290,17 +296,17 @@ void AddExifFieldPropertyMap( Dali::Property::Map& out, const ExifEntry& entry, { std::stringstream ss; ss << "EXIF_FORMAT_UNDEFINED, size: " << entry.size << ", components: " << entry.components; - out.Insert( shortName, ss.str()); + out.Insert(shortName, ss.str()); } } } /// @brief Apply a transform to a buffer bool Transform(const TransformFunctionArray& transformFunctions, - PixelArray buffer, - int width, - int height, - Pixel::Format pixelFormat ) + PixelArray buffer, + int width, + int height, + Pixel::Format pixelFormat) { auto transformFunction = GetTransformFunction(transformFunctions, pixelFormat); if(transformFunction) @@ -321,13 +327,13 @@ template void FlipVertical(PixelArray buffer, int width, int height) { // Destination pixel, set as the first pixel of screen - auto to = reinterpret_cast*>( buffer ); + auto to = reinterpret_cast*>(buffer); // Source pixel, as the image is flipped horizontally and vertically, // the source pixel is the end of the buffer of size width * height auto from = reinterpret_cast*>(buffer) + width * height - 1; - for (auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from) + for(auto ix = 0, endLoop = (width * height) / 2; ix < endLoop; ++ix, ++to, --from) { std::swap(*from, *to); } @@ -357,7 +363,7 @@ void Transpose(PixelArray buffer, int width, int height) { for(auto ix = 0; ix < width; ++ix) { - auto to = reinterpret_cast*>(buffer) + iy * width + ix; + auto to = reinterpret_cast*>(buffer) + iy * width + ix; auto from = reinterpret_cast*>(buffer) + (height - 1 - iy) * width + ix; std::swap(*from, *to); } @@ -369,24 +375,23 @@ void Transverse(PixelArray buffer, int width, int height) { using PixelT = PixelType; Vector data; - data.Resize( width * height ); + data.Resize(width * height); auto dataPtr = data.Begin(); auto original = reinterpret_cast(buffer); std::copy(original, original + width * height, dataPtr); auto to = original; - for( auto iy = 0; iy < width; ++iy ) + for(auto iy = 0; iy < width; ++iy) { - for( auto ix = 0; ix < height; ++ix, ++to ) + for(auto ix = 0; ix < height; ++ix, ++to) { auto from = dataPtr + ix * width + iy; - *to = *from; + *to = *from; } } } - template void Rotate90(PixelArray buffer, int width, int height) { @@ -400,9 +405,9 @@ void Rotate90(PixelArray buffer, int width, int height) std::swap(width, height); auto hw = width * height; - hw = - hw - 1; + hw = -hw - 1; - auto to = original + width - 1; + auto to = original + width - 1; auto from = dataPtr; for(auto ix = width; --ix >= 0;) @@ -428,18 +433,17 @@ void Rotate180(PixelArray buffer, int width, int height) std::copy(original, original + width * height, dataPtr); auto to = original; - for( auto iy = 0; iy < width; iy++ ) + for(auto iy = 0; iy < width; iy++) { - for( auto ix = 0; ix < height; ix++ ) + for(auto ix = 0; ix < height; ix++) { auto from = dataPtr + (height - ix) * width - 1 - iy; - *to = *from; + *to = *from; ++to; } } } - template void Rotate270(PixelArray buffer, int width, int height) { @@ -455,11 +459,11 @@ void Rotate270(PixelArray buffer, int width, int height) std::swap(width, height); auto hw = width * height; - auto* to = original + hw - width; + auto* to = original + hw - width; auto* from = dataPtr; - w = -w; - hw = hw + 1; + w = -w; + hw = hw + 1; for(auto ix = width; --ix >= 0;) { for(auto iy = height; --iy >= 0;) @@ -476,26 +480,20 @@ void Rotate270(PixelArray buffer, int width, int height) namespace Dali { - namespace TizenPlatform { - JpegTransform ConvertExifOrientation(ExifData* exifData); -bool TransformSize( int requiredWidth, int requiredHeight, - FittingMode::Type fittingMode, SamplingMode::Type samplingMode, - JpegTransform transform, - int& preXformImageWidth, int& preXformImageHeight, - int& postXformImageWidth, int& postXformImageHeight ); +bool TransformSize(int requiredWidth, int requiredHeight, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, JpegTransform transform, int& preXformImageWidth, int& preXformImageHeight, int& postXformImageWidth, int& postXformImageHeight); -bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height ) +bool LoadJpegHeader(FILE* fp, unsigned int& width, unsigned int& height) { // using libjpeg API to avoid having to read the whole file in a buffer struct jpeg_decompress_struct cinfo; - struct JpegErrorState jerr; - cinfo.err = jpeg_std_error( &jerr.errorManager ); + struct JpegErrorState jerr; + cinfo.err = jpeg_std_error(&jerr.errorManager); jerr.errorManager.output_message = JpegOutputMessageHandler; - jerr.errorManager.error_exit = JpegErrorHandler; + jerr.errorManager.error_exit = JpegErrorHandler; // On error exit from the JPEG lib, control will pass via JpegErrorHandler // into this branch body for cleanup and error return: @@ -508,50 +506,50 @@ bool LoadJpegHeader( FILE *fp, unsigned int &width, unsigned int &height ) // jpeg_create_decompress internally uses C casts #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - jpeg_create_decompress( &cinfo ); + jpeg_create_decompress(&cinfo); #pragma GCC diagnostic pop - jpeg_stdio_src( &cinfo, fp ); + jpeg_stdio_src(&cinfo, fp); // Check header to see if it is JPEG file - if( jpeg_read_header( &cinfo, TRUE ) != JPEG_HEADER_OK ) + if(jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) { width = height = 0; - jpeg_destroy_decompress( &cinfo ); + jpeg_destroy_decompress(&cinfo); return false; } - width = cinfo.image_width; + width = cinfo.image_width; height = cinfo.image_height; - jpeg_destroy_decompress( &cinfo ); + jpeg_destroy_decompress(&cinfo); return true; } -bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromJpeg(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { - const int flags= 0; - FILE* const fp = input.file; + const int flags = 0; + FILE* const fp = input.file; - if( fseek(fp,0,SEEK_END) ) + if(fseek(fp, 0, SEEK_END)) { DALI_LOG_ERROR("Error seeking to end of file\n"); return false; } - long positionIndicator = ftell(fp); - unsigned int jpegBufferSize = 0u; - if( positionIndicator > -1L ) + long positionIndicator = ftell(fp); + unsigned int jpegBufferSize = 0u; + if(positionIndicator > -1L) { jpegBufferSize = static_cast(positionIndicator); } - if( 0u == jpegBufferSize ) + if(0u == jpegBufferSize) { return false; } - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking to start of file\n"); return false; @@ -560,23 +558,23 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix Vector jpegBuffer; try { - jpegBuffer.Resize( jpegBufferSize ); + jpegBuffer.Resize(jpegBufferSize); } catch(...) { - DALI_LOG_ERROR( "Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U ); + DALI_LOG_ERROR("Could not allocate temporary memory to hold JPEG file of size %uMB.\n", jpegBufferSize / 1048576U); return false; } - unsigned char * const jpegBufferPtr = jpegBuffer.Begin(); + unsigned char* const jpegBufferPtr = jpegBuffer.Begin(); // Pull the compressed JPEG image bytes out of a file and into memory: - if( fread( jpegBufferPtr, 1, jpegBufferSize, fp ) != jpegBufferSize ) + if(fread(jpegBufferPtr, 1, jpegBufferSize, fp) != jpegBufferSize) { DALI_LOG_WARNING("Error on image file read.\n"); return false; } - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking to start of file\n"); } @@ -594,21 +592,21 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix // extract exif data auto exifData = MakeExifDataFromData(jpegBufferPtr, jpegBufferSize); - if( exifData && input.reorientationRequested ) + if(exifData && input.reorientationRequested) { transform = ConvertExifOrientation(exifData.get()); } std::unique_ptr exifMap; - exifMap.reset( new Property::Map() ); + exifMap.reset(new Property::Map()); - for( auto k = 0u; k < EXIF_IFD_COUNT; ++k ) + for(auto k = 0u; k < EXIF_IFD_COUNT; ++k) { auto content = exifData->ifd[k]; - for (auto i = 0u; i < content->count; ++i) + for(auto i = 0u; i < content->count; ++i) { - auto &&tag = content->entries[i]; - const char *shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast(k)); + auto&& tag = content->entries[i]; + const char* shortName = exif_tag_get_name_in_ifd(tag->tag, static_cast(k)); if(shortName) { AddExifFieldPropertyMap(*exifMap, *tag, static_cast(k)); @@ -624,13 +622,13 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix // Temporarily separate Ubuntu and other profiles. #ifndef DALI_PROFILE_UBUNTU int jpegColorspace = -1; - if( tjDecompressHeader3( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling, &jpegColorspace ) == -1 ) + if(tjDecompressHeader3(jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling, &jpegColorspace) == -1) { DALI_LOG_ERROR("%s\n", tjGetErrorStr()); // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type. } #else - if( tjDecompressHeader2( jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling ) == -1 ) + if(tjDecompressHeader2(jpeg.get(), jpegBufferPtr, jpegBufferSize, &preXformImageWidth, &preXformImageHeight, &chrominanceSubsampling) == -1) { DALI_LOG_ERROR("%s\n", tjGetErrorStr()); // Do not set width and height to 0 or return early as this sometimes fails only on determining subsampling type. @@ -649,28 +647,21 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix // If transform is a 90 or 270 degree rotation, the logical width and height // request from the client needs to be adjusted to account by effectively // rotating that too, and the final width and height need to be swapped: - int postXformImageWidth = preXformImageWidth; + int postXformImageWidth = preXformImageWidth; int postXformImageHeight = preXformImageHeight; - int scaledPreXformWidth = preXformImageWidth; int scaledPreXformHeight = preXformImageHeight; int scaledPostXformWidth = postXformImageWidth; int scaledPostXformHeight = postXformImageHeight; - TransformSize( requiredWidth, requiredHeight, - input.scalingParameters.scalingMode, - input.scalingParameters.samplingMode, - transform, - scaledPreXformWidth, scaledPreXformHeight, - scaledPostXformWidth, scaledPostXformHeight ); - + TransformSize(requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, scaledPreXformWidth, scaledPreXformHeight, scaledPostXformWidth, scaledPostXformHeight); // Colorspace conversion options - TJPF pixelLibJpegType = TJPF_RGB; - Pixel::Format pixelFormat = Pixel::RGB888; + TJPF pixelLibJpegType = TJPF_RGB; + Pixel::Format pixelFormat = Pixel::RGB888; #ifndef DALI_PROFILE_UBUNTU - switch (jpegColorspace) + switch(jpegColorspace) { case TJCS_RGB: // YCbCr is not an absolute colorspace but rather a mathematical transformation of RGB designed solely for storage and transmission. @@ -678,26 +669,26 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix case TJCS_YCbCr: { pixelLibJpegType = TJPF_RGB; - pixelFormat = Pixel::RGB888; + pixelFormat = Pixel::RGB888; break; } case TJCS_GRAY: { pixelLibJpegType = TJPF_GRAY; - pixelFormat = Pixel::L8; + pixelFormat = Pixel::L8; break; } case TJCS_CMYK: case TJCS_YCCK: { pixelLibJpegType = TJPF_CMYK; - pixelFormat = Pixel::RGBA8888; + pixelFormat = Pixel::RGBA8888; break; } default: { pixelLibJpegType = TJPF_RGB; - pixelFormat = Pixel::RGB888; + pixelFormat = Pixel::RGB888; break; } } @@ -706,27 +697,27 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix bitmap = Dali::Devel::PixelBuffer::New(scaledPostXformWidth, scaledPostXformHeight, pixelFormat); // set metadata - GetImplementation(bitmap).SetMetadata( std::move(exifMap) ); + GetImplementation(bitmap).SetMetadata(std::move(exifMap)); auto bitmapPixelBuffer = bitmap.GetBuffer(); - if( tjDecompress2( jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast( bitmapPixelBuffer ), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags ) == -1 ) + if(tjDecompress2(jpeg.get(), jpegBufferPtr, jpegBufferSize, reinterpret_cast(bitmapPixelBuffer), scaledPreXformWidth, 0, scaledPreXformHeight, pixelLibJpegType, flags) == -1) { std::string errorString = tjGetErrorStr(); - if( IsJpegErrorFatal( errorString ) ) + if(IsJpegErrorFatal(errorString)) { - DALI_LOG_ERROR("%s\n", errorString.c_str() ); - return false; + DALI_LOG_ERROR("%s\n", errorString.c_str()); + return false; } else { - DALI_LOG_WARNING("%s\n", errorString.c_str() ); + DALI_LOG_WARNING("%s\n", errorString.c_str()); } } - const unsigned int bufferWidth = GetTextureDimension( scaledPreXformWidth ); - const unsigned int bufferHeight = GetTextureDimension( scaledPreXformHeight ); + const unsigned int bufferWidth = GetTextureDimension(scaledPreXformWidth); + const unsigned int bufferHeight = GetTextureDimension(scaledPreXformHeight); bool result = false; switch(transform) @@ -739,78 +730,78 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix // 3 orientation changes for a camera held perpendicular to the ground or upside-down: case JpegTransform::ROTATE_180: { - static auto rotate180Functions = TransformFunctionArray { + static auto rotate180Functions = TransformFunctionArray{ &Rotate180<1>, &Rotate180<3>, &Rotate180<4>, }; - result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(rotate180Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } case JpegTransform::ROTATE_270: { - static auto rotate270Functions = TransformFunctionArray { + static auto rotate270Functions = TransformFunctionArray{ &Rotate270<1>, &Rotate270<3>, &Rotate270<4>, }; - result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(rotate270Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } case JpegTransform::ROTATE_90: { - static auto rotate90Functions = TransformFunctionArray { + static auto rotate90Functions = TransformFunctionArray{ &Rotate90<1>, &Rotate90<3>, &Rotate90<4>, }; - result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(rotate90Functions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } case JpegTransform::FLIP_VERTICAL: { - static auto flipVerticalFunctions = TransformFunctionArray { + static auto flipVerticalFunctions = TransformFunctionArray{ &FlipVertical<1>, &FlipVertical<3>, &FlipVertical<4>, }; - result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(flipVerticalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } // Less-common orientation changes, since they don't correspond to a camera's physical orientation: case JpegTransform::FLIP_HORIZONTAL: { - static auto flipHorizontalFunctions = TransformFunctionArray { + static auto flipHorizontalFunctions = TransformFunctionArray{ &FlipHorizontal<1>, &FlipHorizontal<3>, &FlipHorizontal<4>, }; - result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(flipHorizontalFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } case JpegTransform::TRANSPOSE: { - static auto transposeFunctions = TransformFunctionArray { + static auto transposeFunctions = TransformFunctionArray{ &Transpose<1>, &Transpose<3>, &Transpose<4>, }; - result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(transposeFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } case JpegTransform::TRANSVERSE: { - static auto transverseFunctions = TransformFunctionArray { + static auto transverseFunctions = TransformFunctionArray{ &Transverse<1>, &Transverse<3>, &Transverse<4>, }; - result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat ); + result = Transform(transverseFunctions, bitmapPixelBuffer, bufferWidth, bufferHeight, pixelFormat); break; } default: { - DALI_LOG_ERROR( "Unsupported JPEG Orientation transformation: %x.\n", transform ); + DALI_LOG_ERROR("Unsupported JPEG Orientation transformation: %x.\n", transform); break; } } @@ -818,11 +809,9 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix return result; } -bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char >& encodedPixels, - const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality ) +bool EncodeToJpeg(const unsigned char* const pixelBuffer, Vector& encodedPixels, const std::size_t width, const std::size_t height, const Pixel::Format pixelFormat, unsigned quality) { - - if( !pixelBuffer ) + if(!pixelBuffer) { DALI_LOG_ERROR("Null input buffer\n"); return false; @@ -831,7 +820,7 @@ bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char // Translate pixel format enum: int jpegPixelFormat = -1; - switch( pixelFormat ) + switch(pixelFormat) { case Pixel::RGB888: { @@ -852,19 +841,19 @@ bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char } default: { - DALI_LOG_ERROR( "Unsupported pixel format for encoding to JPEG.\n" ); + DALI_LOG_ERROR("Unsupported pixel format for encoding to JPEG.\n"); return false; } } // Assert quality is in the documented allowable range of the jpeg-turbo lib: - DALI_ASSERT_DEBUG( quality >= 1 ); - DALI_ASSERT_DEBUG( quality <= 100 ); - if( quality < 1 ) + DALI_ASSERT_DEBUG(quality >= 1); + DALI_ASSERT_DEBUG(quality <= 100); + if(quality < 1) { quality = 1; } - if( quality > 100 ) + if(quality > 100) { quality = 100; } @@ -872,13 +861,12 @@ bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char // Initialise a JPEG codec: { auto jpeg = MakeJpegCompressor(); - if( !jpeg ) + if(!jpeg) { - DALI_LOG_ERROR( "JPEG Compressor init failed: %s\n", tjGetErrorStr() ); + DALI_LOG_ERROR("JPEG Compressor init failed: %s\n", tjGetErrorStr()); return false; } - // Safely wrap the jpeg codec's buffer in case we are about to throw, then // save the pixels to a persistent buffer that we own and let our cleaner // class clean up the buffer as it goes out of scope: @@ -886,34 +874,39 @@ bool EncodeToJpeg( const unsigned char* const pixelBuffer, Vector< unsigned char // Run the compressor: unsigned long dstBufferSize = 0; - const int flags = 0; - - if( tjCompress2( jpeg.get(), - const_cast(pixelBuffer), - width, 0, height, - jpegPixelFormat, SetPointer(dstBuffer), &dstBufferSize, - TJSAMP_444, quality, flags ) ) + const int flags = 0; + + if(tjCompress2(jpeg.get(), + const_cast(pixelBuffer), + width, + 0, + height, + jpegPixelFormat, + SetPointer(dstBuffer), + &dstBufferSize, + TJSAMP_444, + quality, + flags)) { DALI_LOG_ERROR("JPEG Compression failed: %s\n", tjGetErrorStr()); return false; } - encodedPixels.Resize( dstBufferSize ); - memcpy( encodedPixels.Begin(), dstBuffer.get(), dstBufferSize ); + encodedPixels.Resize(dstBufferSize); + memcpy(encodedPixels.Begin(), dstBuffer.get(), dstBufferSize); } return true; } - JpegTransform ConvertExifOrientation(ExifData* exifData) { - auto transform = JpegTransform::NONE; - ExifEntry * const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION); - int orientation = 0; - if( entry ) + auto transform = JpegTransform::NONE; + ExifEntry* const entry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION); + int orientation = 0; + if(entry) { orientation = exif_get_short(entry->data, exif_data_get_byte_order(entry->parent->parent)); - switch( orientation ) + switch(orientation) { case 1: { @@ -958,7 +951,7 @@ JpegTransform ConvertExifOrientation(ExifData* exifData) default: { // Try to keep loading the file, but let app developer know there was something fishy: - DALI_LOG_WARNING( "Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry ); + DALI_LOG_WARNING("Incorrect/Unknown Orientation setting found in EXIF header of JPEG image (%x). Orientation setting will be ignored.\n", entry); break; } } @@ -966,32 +959,28 @@ JpegTransform ConvertExifOrientation(ExifData* exifData) return transform; } -bool TransformSize( int requiredWidth, int requiredHeight, - FittingMode::Type fittingMode, SamplingMode::Type samplingMode, - JpegTransform transform, - int& preXformImageWidth, int& preXformImageHeight, - int& postXformImageWidth, int& postXformImageHeight ) +bool TransformSize(int requiredWidth, int requiredHeight, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, JpegTransform transform, int& preXformImageWidth, int& preXformImageHeight, int& postXformImageWidth, int& postXformImageHeight) { bool success = true; - if( transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE) + if(transform == JpegTransform::ROTATE_90 || transform == JpegTransform::ROTATE_270 || transform == JpegTransform::ROTATE_180 || transform == JpegTransform::TRANSVERSE) { - std::swap( requiredWidth, requiredHeight ); - std::swap( postXformImageWidth, postXformImageHeight ); + std::swap(requiredWidth, requiredHeight); + std::swap(postXformImageWidth, postXformImageHeight); } // Apply the special rules for when there are one or two zeros in requested dimensions: - const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions( ImageDimensions( postXformImageWidth, postXformImageHeight), ImageDimensions( requiredWidth, requiredHeight ) ); - requiredWidth = correctedDesired.GetWidth(); - requiredHeight = correctedDesired.GetHeight(); + const ImageDimensions correctedDesired = Internal::Platform::CalculateDesiredDimensions(ImageDimensions(postXformImageWidth, postXformImageHeight), ImageDimensions(requiredWidth, requiredHeight)); + requiredWidth = correctedDesired.GetWidth(); + requiredHeight = correctedDesired.GetHeight(); // Rescale image during decode using one of the decoder's built-in rescaling // ratios (expected to be powers of 2), keeping the final image at least as // wide and high as was requested: - int numFactors = 0; - tjscalingfactor* factors = tjGetScalingFactors( &numFactors ); - if( factors == NULL ) + int numFactors = 0; + tjscalingfactor* factors = tjGetScalingFactors(&numFactors); + if(factors == NULL) { DALI_LOG_WARNING("TurboJpeg tjGetScalingFactors error!\n"); success = false; @@ -1002,7 +991,7 @@ bool TransformSize( int requiredWidth, int requiredHeight, // apply it if the application requested one of those: // (use a switch case here so this code will fail to compile if other modes are added) bool downscale = true; - switch( samplingMode ) + switch(samplingMode) { case SamplingMode::BOX: case SamplingMode::BOX_THEN_NEAREST: @@ -1021,31 +1010,31 @@ bool TransformSize( int requiredWidth, int requiredHeight, } } - int scaleFactorIndex( 0 ); - if( downscale ) + int scaleFactorIndex(0); + if(downscale) { // Find nearest supported scaling factor (factors are in sequential order, getting smaller) - for( int i = 1; i < numFactors; ++i ) + for(int i = 1; i < numFactors; ++i) { - bool widthLessRequired = TJSCALED( postXformImageWidth, factors[i]) < requiredWidth; - bool heightLessRequired = TJSCALED( postXformImageHeight, factors[i]) < requiredHeight; + bool widthLessRequired = TJSCALED(postXformImageWidth, factors[i]) < requiredWidth; + bool heightLessRequired = TJSCALED(postXformImageHeight, factors[i]) < requiredHeight; // If either scaled dimension is smaller than the desired one, we were done at the last iteration - if ( (fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired) ) + if((fittingMode == FittingMode::SCALE_TO_FILL) && (widthLessRequired || heightLessRequired)) { break; } // If both dimensions are smaller than the desired one, we were done at the last iteration: - if ( (fittingMode == FittingMode::SHRINK_TO_FIT) && ( widthLessRequired && heightLessRequired ) ) + if((fittingMode == FittingMode::SHRINK_TO_FIT) && (widthLessRequired && heightLessRequired)) { break; } // If the width is smaller than the desired one, we were done at the last iteration: - if ( fittingMode == FittingMode::FIT_WIDTH && widthLessRequired ) + if(fittingMode == FittingMode::FIT_WIDTH && widthLessRequired) { break; } // If the width is smaller than the desired one, we were done at the last iteration: - if ( fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired ) + if(fittingMode == FittingMode::FIT_HEIGHT && heightLessRequired) { break; } @@ -1055,13 +1044,13 @@ bool TransformSize( int requiredWidth, int requiredHeight, } // Regardless of requested size, downscale to avoid exceeding the maximum texture size: - for( int i = scaleFactorIndex; i < numFactors; ++i ) + for(int i = scaleFactorIndex; i < numFactors; ++i) { // Continue downscaling to below maximum texture size (if possible) scaleFactorIndex = i; - if( TJSCALED(postXformImageWidth, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) && - TJSCALED(postXformImageHeight, (factors[i])) < static_cast< int >( Dali::GetMaxTextureSize() ) ) + if(TJSCALED(postXformImageWidth, (factors[i])) < static_cast(Dali::GetMaxTextureSize()) && + TJSCALED(postXformImageHeight, (factors[i])) < static_cast(Dali::GetMaxTextureSize())) { // Current scale-factor downscales to below maximum texture size break; @@ -1069,11 +1058,11 @@ bool TransformSize( int requiredWidth, int requiredHeight, } // We have finally chosen the scale-factor, return width/height values - if( scaleFactorIndex > 0 ) + if(scaleFactorIndex > 0) { - preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex])); - preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex])); - postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex])); + preXformImageWidth = TJSCALED(preXformImageWidth, (factors[scaleFactorIndex])); + preXformImageHeight = TJSCALED(preXformImageHeight, (factors[scaleFactorIndex])); + postXformImageWidth = TJSCALED(postXformImageWidth, (factors[scaleFactorIndex])); postXformImageHeight = TJSCALED(postXformImageHeight, (factors[scaleFactorIndex])); } } @@ -1081,91 +1070,90 @@ bool TransformSize( int requiredWidth, int requiredHeight, return success; } -ExifHandle LoadExifData( FILE* fp ) +ExifHandle LoadExifData(FILE* fp) { - auto exifData = MakeNullExifData(); + auto exifData = MakeNullExifData(); unsigned char dataBuffer[1024]; - if( fseek( fp, 0, SEEK_SET ) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking to start of file\n"); } else { auto exifLoader = std::unique_ptr{ - exif_loader_new(), exif_loader_unref }; + exif_loader_new(), exif_loader_unref}; - while( !feof(fp) ) + while(!feof(fp)) { - int size = fread( dataBuffer, 1, sizeof( dataBuffer ), fp ); - if( size <= 0 ) + int size = fread(dataBuffer, 1, sizeof(dataBuffer), fp); + if(size <= 0) { break; } - if( ! exif_loader_write( exifLoader.get(), dataBuffer, size ) ) + if(!exif_loader_write(exifLoader.get(), dataBuffer, size)) { break; } } - exifData.reset( exif_loader_get_data( exifLoader.get() ) ); + exifData.reset(exif_loader_get_data(exifLoader.get())); } return exifData; } -bool LoadJpegHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadJpegHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { unsigned int requiredWidth = input.scalingParameters.dimensions.GetWidth(); unsigned int requiredHeight = input.scalingParameters.dimensions.GetHeight(); - FILE* const fp = input.file; + FILE* const fp = input.file; bool success = false; - if( requiredWidth == 0 && requiredHeight == 0 ) + if(requiredWidth == 0 && requiredHeight == 0) { - success = LoadJpegHeader( fp, width, height ); + success = LoadJpegHeader(fp, width, height); } else { // Double check we get the same width/height from the header unsigned int headerWidth; unsigned int headerHeight; - if( LoadJpegHeader( fp, headerWidth, headerHeight ) ) + if(LoadJpegHeader(fp, headerWidth, headerHeight)) { auto transform = JpegTransform::NONE; - if( input.reorientationRequested ) + if(input.reorientationRequested) { - auto exifData = LoadExifData( fp ); - if( exifData ) + auto exifData = LoadExifData(fp); + if(exifData) { transform = ConvertExifOrientation(exifData.get()); } - int preXformImageWidth = headerWidth; - int preXformImageHeight = headerHeight; - int postXformImageWidth = headerWidth; + int preXformImageWidth = headerWidth; + int preXformImageHeight = headerHeight; + int postXformImageWidth = headerWidth; int postXformImageHeight = headerHeight; - success = TransformSize( requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight ); + success = TransformSize(requiredWidth, requiredHeight, input.scalingParameters.scalingMode, input.scalingParameters.samplingMode, transform, preXformImageWidth, preXformImageHeight, postXformImageWidth, postXformImageHeight); if(success) { - width = postXformImageWidth; + width = postXformImageWidth; height = postXformImageHeight; } } else { success = true; - width = headerWidth; - height = headerHeight; + width = headerWidth; + height = headerHeight; } } } return success; } - } // namespace TizenPlatform } // namespace Dali diff --git a/dali/internal/imaging/common/loader-jpeg.h b/dali/internal/imaging/common/loader-jpeg.h old mode 100755 new mode 100644 index 29ec9dc..45c99e4 --- a/dali/internal/imaging/common/loader-jpeg.h +++ b/dali/internal/imaging/common/loader-jpeg.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_JPEG_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,11 @@ * */ -#include +#include +#include #include #include -#include -#include +#include namespace Dali { @@ -31,10 +31,8 @@ namespace Devel class PixelBuffer; } - namespace TizenPlatform { - class ResourceLoadingClient; namespace Jpeg @@ -50,7 +48,7 @@ const unsigned char MAGIC_BYTE_2 = 0xD8; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file decoded successfully, false otherwise */ -bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromJpeg(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * Loads the header of a JPEG file and fills in the width and height appropriately. @@ -63,7 +61,7 @@ bool LoadBitmapFromJpeg( const Dali::ImageLoader::Input& input, Dali::Devel::Pix * @param[in/out] height Is set with the height of the image * @return true if the file's header was read successully, false otherwise */ -bool LoadJpegHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadJpegHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); /** * Encode raw pixel data to JPEG format. @@ -74,7 +72,7 @@ bool LoadJpegHeader( const Dali::ImageLoader::Input& input, unsigned int& width, * @param[in] pixelFormat Input pixel format (must be Pixel::RGB888) * @param[in] quality JPEG quality on usual 1 to 100 scale. */ -bool EncodeToJpeg(const unsigned char* pixelBuffer, Vector< unsigned char >& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat, unsigned quality = 80); +bool EncodeToJpeg(const unsigned char* pixelBuffer, Vector& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat, unsigned quality = 80); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-ktx.cpp b/dali/internal/imaging/common/loader-ktx.cpp old mode 100755 new mode 100644 index 09116b6..7600732 --- a/dali/internal/imaging/common/loader-ktx.cpp +++ b/dali/internal/imaging/common/loader-ktx.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,20 +19,17 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include #include +#include namespace Dali { - namespace TizenPlatform { - namespace { - /** Max width or height of an image. */ const unsigned MAX_TEXTURE_DIMENSION = 4096; /** Max bytes of image data allowed. Not a precise number, just a sanity check. */ @@ -44,9 +41,7 @@ const unsigned MAX_BYTES_OF_KEYVALUE_DATA = 65536U; typedef uint8_t Byte; const Byte FileIdentifier[] = { - 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A -}; - + 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; /** The formats we support inside a KTX file container. * Currently only compressed formats are allowed as we'd rather @@ -57,114 +52,113 @@ enum KtxInternalFormat KTX_NOTEXIST = 0, // GLES 2 Extension formats: - KTX_ETC1_RGB8_OES = 0x8D64, - KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00, + KTX_ETC1_RGB8_OES = 0x8D64, + KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00, // GLES 3 Standard compressed formats (values same as in gl3.h): - KTX_COMPRESSED_R11_EAC = 0x9270, - KTX_COMPRESSED_SIGNED_R11_EAC = 0x9271, - KTX_COMPRESSED_RG11_EAC = 0x9272, - KTX_COMPRESSED_SIGNED_RG11_EAC = 0x9273, - KTX_COMPRESSED_RGB8_ETC2 = 0x9274, - KTX_COMPRESSED_SRGB8_ETC2 = 0x9275, - KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276, - KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277, - KTX_COMPRESSED_RGBA8_ETC2_EAC = 0x9278, - KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279, + KTX_COMPRESSED_R11_EAC = 0x9270, + KTX_COMPRESSED_SIGNED_R11_EAC = 0x9271, + KTX_COMPRESSED_RG11_EAC = 0x9272, + KTX_COMPRESSED_SIGNED_RG11_EAC = 0x9273, + KTX_COMPRESSED_RGB8_ETC2 = 0x9274, + KTX_COMPRESSED_SRGB8_ETC2 = 0x9275, + KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276, + KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277, + KTX_COMPRESSED_RGBA8_ETC2_EAC = 0x9278, + KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279, // GLES 3.1 compressed formats: - KTX_COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0, - KTX_COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1, - KTX_COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2, - KTX_COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3, - KTX_COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4, - KTX_COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5, - KTX_COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6, - KTX_COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7, - KTX_COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8, - KTX_COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9, - KTX_COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA, - KTX_COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB, - KTX_COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC, - KTX_COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93D0, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93D1, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93D2, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93D3, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93D4, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93D5, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93D6, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93D7, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93D8, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93D9, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93DA, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93DB, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93DC, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93DD, + KTX_COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0, + KTX_COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1, + KTX_COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2, + KTX_COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3, + KTX_COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4, + KTX_COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5, + KTX_COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6, + KTX_COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7, + KTX_COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8, + KTX_COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9, + KTX_COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA, + KTX_COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB, + KTX_COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC, + KTX_COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93D0, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93D1, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93D2, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93D3, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93D4, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93D5, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93D6, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93D7, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93D8, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93D9, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93DA, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93DB, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93DC, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93DD, // Uncompressed Alpha format - KTX_UNCOMPRESSED_ALPHA8 = 0x1906, + KTX_UNCOMPRESSED_ALPHA8 = 0x1906, KTX_SENTINEL = ~0u }; const unsigned KtxInternalFormats[] = -{ - // GLES 2 Extension formats: - KTX_ETC1_RGB8_OES, - KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, - - // GLES 3 Standard compressed formats: - KTX_COMPRESSED_R11_EAC, - KTX_COMPRESSED_SIGNED_R11_EAC, - KTX_COMPRESSED_RG11_EAC, - KTX_COMPRESSED_SIGNED_RG11_EAC, - KTX_COMPRESSED_RGB8_ETC2, - KTX_COMPRESSED_SRGB8_ETC2, - KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, - KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, - KTX_COMPRESSED_RGBA8_ETC2_EAC, - KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, - - // GLES 3.1 Compressed formats: - KTX_COMPRESSED_RGBA_ASTC_4x4_KHR, - KTX_COMPRESSED_RGBA_ASTC_5x4_KHR, - KTX_COMPRESSED_RGBA_ASTC_5x5_KHR, - KTX_COMPRESSED_RGBA_ASTC_6x5_KHR, - KTX_COMPRESSED_RGBA_ASTC_6x6_KHR, - KTX_COMPRESSED_RGBA_ASTC_8x5_KHR, - KTX_COMPRESSED_RGBA_ASTC_8x6_KHR, - KTX_COMPRESSED_RGBA_ASTC_8x8_KHR, - KTX_COMPRESSED_RGBA_ASTC_10x5_KHR, - KTX_COMPRESSED_RGBA_ASTC_10x6_KHR, - KTX_COMPRESSED_RGBA_ASTC_10x8_KHR, - KTX_COMPRESSED_RGBA_ASTC_10x10_KHR, - KTX_COMPRESSED_RGBA_ASTC_12x10_KHR, - KTX_COMPRESSED_RGBA_ASTC_12x12_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, - KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, + { + // GLES 2 Extension formats: + KTX_ETC1_RGB8_OES, + KTX_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, + + // GLES 3 Standard compressed formats: + KTX_COMPRESSED_R11_EAC, + KTX_COMPRESSED_SIGNED_R11_EAC, + KTX_COMPRESSED_RG11_EAC, + KTX_COMPRESSED_SIGNED_RG11_EAC, + KTX_COMPRESSED_RGB8_ETC2, + KTX_COMPRESSED_SRGB8_ETC2, + KTX_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, + KTX_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, + KTX_COMPRESSED_RGBA8_ETC2_EAC, + KTX_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, + + // GLES 3.1 Compressed formats: + KTX_COMPRESSED_RGBA_ASTC_4x4_KHR, + KTX_COMPRESSED_RGBA_ASTC_5x4_KHR, + KTX_COMPRESSED_RGBA_ASTC_5x5_KHR, + KTX_COMPRESSED_RGBA_ASTC_6x5_KHR, + KTX_COMPRESSED_RGBA_ASTC_6x6_KHR, + KTX_COMPRESSED_RGBA_ASTC_8x5_KHR, + KTX_COMPRESSED_RGBA_ASTC_8x6_KHR, + KTX_COMPRESSED_RGBA_ASTC_8x8_KHR, + KTX_COMPRESSED_RGBA_ASTC_10x5_KHR, + KTX_COMPRESSED_RGBA_ASTC_10x6_KHR, + KTX_COMPRESSED_RGBA_ASTC_10x8_KHR, + KTX_COMPRESSED_RGBA_ASTC_10x10_KHR, + KTX_COMPRESSED_RGBA_ASTC_12x10_KHR, + KTX_COMPRESSED_RGBA_ASTC_12x12_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, + KTX_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, - // Uncompressed Alpha format - KTX_UNCOMPRESSED_ALPHA8, + // Uncompressed Alpha format + KTX_UNCOMPRESSED_ALPHA8, - KTX_SENTINEL -}; + KTX_SENTINEL}; struct KtxFileHeader { - Byte identifier[12]; + Byte identifier[12]; uint32_t endianness; uint32_t glType; uint32_t glTypeSize; @@ -178,7 +172,7 @@ struct KtxFileHeader uint32_t numberOfFaces; uint32_t numberOfMipmapLevels; uint32_t bytesOfKeyValueData; -} __attribute__ ( (__packed__)); +} __attribute__((__packed__)); // Packed attribute stops the structure from being aligned to compiler defaults // so we can be sure of reading the whole thing from file in one call to fread. @@ -188,12 +182,12 @@ struct KtxFileHeader * @param[out] header The structure we want to store our information in * @return true, if read successful, false otherwise */ -inline bool ReadHeader( FILE* filePointer, KtxFileHeader& header ) +inline bool ReadHeader(FILE* filePointer, KtxFileHeader& header) { - const unsigned int readLength = sizeof( KtxFileHeader ); + const unsigned int readLength = sizeof(KtxFileHeader); // Load the information directly into our structure - if( fread( &header, 1, readLength, filePointer ) != readLength ) + if(fread(&header, 1, readLength, filePointer) != readLength) { return false; } @@ -204,12 +198,12 @@ inline bool ReadHeader( FILE* filePointer, KtxFileHeader& header ) /** Check whether the array passed in is the right size and matches the magic * values defined to be at the start of a KTX file by the specification.*/ template -bool CheckFileIdentifier(const Byte * const signature) +bool CheckFileIdentifier(const Byte* const signature) { - const unsigned signatureSize = BYTES_IN_SIGNATURE; + const unsigned signatureSize = BYTES_IN_SIGNATURE; const unsigned identifierSize = sizeof(FileIdentifier); static_assert(signatureSize == identifierSize); - const bool signatureGood = 0 == memcmp( signature, FileIdentifier, std::min( signatureSize, identifierSize ) ); + const bool signatureGood = 0 == memcmp(signature, FileIdentifier, std::min(signatureSize, identifierSize)); return signatureGood; } @@ -454,23 +448,23 @@ bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& form default: { - return false; + return false; } } return true; } -bool LoadKtxHeader( FILE * const fp, unsigned int& width, unsigned int& height, KtxFileHeader& fileHeader ) +bool LoadKtxHeader(FILE* const fp, unsigned int& width, unsigned int& height, KtxFileHeader& fileHeader) { // Pull the bytes of the file header in as a block: - if ( !ReadHeader( fp, fileHeader ) ) + if(!ReadHeader(fp, fileHeader)) { return false; } - width = fileHeader.pixelWidth; + width = fileHeader.pixelWidth; height = fileHeader.pixelHeight; - if ( width > MAX_TEXTURE_DIMENSION || height > MAX_TEXTURE_DIMENSION ) + if(width > MAX_TEXTURE_DIMENSION || height > MAX_TEXTURE_DIMENSION) { return false; } @@ -483,34 +477,34 @@ bool LoadKtxHeader( FILE * const fp, unsigned int& width, unsigned int& height, const bool glFormatCompatibleWithCompressedTex = fileHeader.glFormat == 0; const bool glInternalFormatIsSupportedCompressedTex = ValidInternalFormat(fileHeader.glInternalFormat); // Ignore glBaseInternalFormat - const bool textureIsNot3D = fileHeader.pixelDepth == 0 || fileHeader.pixelDepth == 1; - const bool textureIsNotAnArray = fileHeader.numberOfArrayElements == 0 || fileHeader.numberOfArrayElements == 1; - const bool textureIsNotACubemap = fileHeader.numberOfFaces == 0 || fileHeader.numberOfFaces == 1; - const bool textureHasNoMipmapLevels = fileHeader.numberOfMipmapLevels == 0 || fileHeader.numberOfMipmapLevels == 1; - const bool keyValueDataNotTooLarge = fileHeader.bytesOfKeyValueData <= MAX_BYTES_OF_KEYVALUE_DATA; + const bool textureIsNot3D = fileHeader.pixelDepth == 0 || fileHeader.pixelDepth == 1; + const bool textureIsNotAnArray = fileHeader.numberOfArrayElements == 0 || fileHeader.numberOfArrayElements == 1; + const bool textureIsNotACubemap = fileHeader.numberOfFaces == 0 || fileHeader.numberOfFaces == 1; + const bool textureHasNoMipmapLevels = fileHeader.numberOfMipmapLevels == 0 || fileHeader.numberOfMipmapLevels == 1; + const bool keyValueDataNotTooLarge = fileHeader.bytesOfKeyValueData <= MAX_BYTES_OF_KEYVALUE_DATA; bool headerIsValid = signatureGood && fileEndiannessMatchesSystemEndianness && - glTypeSizeCompatibleWithCompressedTex && textureIsNot3D && textureIsNotAnArray && - textureIsNotACubemap && textureHasNoMipmapLevels && keyValueDataNotTooLarge; + glTypeSizeCompatibleWithCompressedTex && textureIsNot3D && textureIsNotAnArray && + textureIsNotACubemap && textureHasNoMipmapLevels && keyValueDataNotTooLarge; - if( !glTypeIsCompressed ) // check for uncompressed Alpha + if(!glTypeIsCompressed) // check for uncompressed Alpha { - const bool isAlpha = ( ( fileHeader.glBaseInternalFormat == KTX_UNCOMPRESSED_ALPHA8 ) && ( fileHeader.glFormat == KTX_UNCOMPRESSED_ALPHA8 ) && - ( fileHeader.glInternalFormat == KTX_UNCOMPRESSED_ALPHA8 ) ); - headerIsValid = headerIsValid && isAlpha; + const bool isAlpha = ((fileHeader.glBaseInternalFormat == KTX_UNCOMPRESSED_ALPHA8) && (fileHeader.glFormat == KTX_UNCOMPRESSED_ALPHA8) && + (fileHeader.glInternalFormat == KTX_UNCOMPRESSED_ALPHA8)); + headerIsValid = headerIsValid && isAlpha; } else { headerIsValid = headerIsValid && glFormatCompatibleWithCompressedTex && glInternalFormatIsSupportedCompressedTex; } - if( !headerIsValid ) + if(!headerIsValid) { - DALI_LOG_ERROR( "KTX file invalid or using unsupported features. Header tests: sig: %d, endian: %d, gl_type: %d, gl_type_size: %d, gl_format: %d, internal_format: %d, depth: %d, array: %d, faces: %d, mipmap: %d, vey-vals: %d.\n", 0+signatureGood, 0+fileEndiannessMatchesSystemEndianness, 0+glTypeIsCompressed, 0+glTypeSizeCompatibleWithCompressedTex, 0+glFormatCompatibleWithCompressedTex, 0+glInternalFormatIsSupportedCompressedTex, 0+textureIsNot3D, 0+textureIsNotAnArray, 0+textureIsNotACubemap, 0+textureHasNoMipmapLevels, 0+keyValueDataNotTooLarge); + DALI_LOG_ERROR("KTX file invalid or using unsupported features. Header tests: sig: %d, endian: %d, gl_type: %d, gl_type_size: %d, gl_format: %d, internal_format: %d, depth: %d, array: %d, faces: %d, mipmap: %d, vey-vals: %d.\n", 0 + signatureGood, 0 + fileEndiannessMatchesSystemEndianness, 0 + glTypeIsCompressed, 0 + glTypeSizeCompatibleWithCompressedTex, 0 + glFormatCompatibleWithCompressedTex, 0 + glInternalFormatIsSupportedCompressedTex, 0 + textureIsNot3D, 0 + textureIsNotAnArray, 0 + textureIsNotACubemap, 0 + textureHasNoMipmapLevels, 0 + keyValueDataNotTooLarge); } // Warn if there is space wasted in the file: - if( fileHeader.bytesOfKeyValueData > 0U ) + if(fileHeader.bytesOfKeyValueData > 0U) { DALI_LOG_WARNING("Loading of KTX file with key/value header data requested. This should be stripped in application asset/resource build.\n"); } @@ -518,29 +512,28 @@ bool LoadKtxHeader( FILE * const fp, unsigned int& width, unsigned int& height, return headerIsValid; } - } // unnamed namespace // File loading API entry-point: -bool LoadKtxHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadKtxHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { KtxFileHeader fileHeader; - FILE* const fp = input.file; + FILE* const fp = input.file; bool ret = LoadKtxHeader(fp, width, height, fileHeader); return ret; } // File loading API entry-point: -bool LoadBitmapFromKtx( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromKtx(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { static_assert(sizeof(Byte) == 1); static_assert(sizeof(uint32_t) == 4); FILE* const fp = input.file; - if( fp == NULL ) + if(fp == NULL) { - DALI_LOG_ERROR( "Null file handle passed to KTX compressed bitmap file loader.\n" ); + DALI_LOG_ERROR("Null file handle passed to KTX compressed bitmap file loader.\n"); return false; } KtxFileHeader fileHeader; @@ -548,40 +541,40 @@ bool LoadBitmapFromKtx( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe // Load the header info unsigned int width, height; - if (!LoadKtxHeader(fp, width, height, fileHeader)) + if(!LoadKtxHeader(fp, width, height, fileHeader)) { - return false; + return false; } // Skip the key-values: const long int imageSizeOffset = sizeof(KtxFileHeader) + fileHeader.bytesOfKeyValueData; if(fseek(fp, imageSizeOffset, SEEK_SET)) { - DALI_LOG_ERROR( "Seek past key/vals in KTX compressed bitmap file failed.\n" ); + DALI_LOG_ERROR("Seek past key/vals in KTX compressed bitmap file failed.\n"); return false; } // Load the size of the image data: uint32_t imageByteCount = 0; - if ( fread( &imageByteCount, 1, 4, fp ) != 4 ) + if(fread(&imageByteCount, 1, 4, fp) != 4) { - DALI_LOG_ERROR( "Read of image size failed.\n" ); + DALI_LOG_ERROR("Read of image size failed.\n"); return false; } // Sanity-check the image size: - if( imageByteCount > MAX_IMAGE_DATA_SIZE || - // A compressed texture should certainly be less than 2 bytes per texel: - imageByteCount > width * height * 2) + if(imageByteCount > MAX_IMAGE_DATA_SIZE || + // A compressed texture should certainly be less than 2 bytes per texel: + imageByteCount > width * height * 2) { - DALI_LOG_ERROR( "KTX file with too-large image-data field.\n" ); + DALI_LOG_ERROR("KTX file with too-large image-data field.\n"); return false; } Pixel::Format pixelFormat; - const bool pixelFormatKnown = ConvertPixelFormat(fileHeader.glInternalFormat, pixelFormat); + const bool pixelFormatKnown = ConvertPixelFormat(fileHeader.glInternalFormat, pixelFormat); if(!pixelFormatKnown) { - DALI_LOG_ERROR( "No internal pixel format supported for KTX file pixel format.\n" ); + DALI_LOG_ERROR("No internal pixel format supported for KTX file pixel format.\n"); return false; } @@ -590,24 +583,24 @@ bool LoadBitmapFromKtx( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe // Compressed format won't allocate the buffer auto pixels = bitmap.GetBuffer(); - if( !pixels ) + if(!pixels) { // allocate buffer manually - auto &impl = GetImplementation(bitmap); + auto& impl = GetImplementation(bitmap); impl.AllocateFixedSize(imageByteCount); pixels = bitmap.GetBuffer(); } if(!pixels) { - DALI_LOG_ERROR( "Unable to reserve a pixel buffer to load the requested bitmap into.\n" ); + DALI_LOG_ERROR("Unable to reserve a pixel buffer to load the requested bitmap into.\n"); return false; } const size_t bytesRead = fread(pixels, 1, imageByteCount, fp); if(bytesRead != imageByteCount) { - DALI_LOG_ERROR( "Read of image pixel data failed.\n" ); + DALI_LOG_ERROR("Read of image pixel data failed.\n"); return false; } diff --git a/dali/internal/imaging/common/loader-ktx.h b/dali/internal/imaging/common/loader-ktx.h old mode 100755 new mode 100644 index 6853da0..6179560 --- a/dali/internal/imaging/common/loader-ktx.h +++ b/dali/internal/imaging/common/loader-ktx.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_KTX_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ * */ -#include #include +#include namespace Dali { @@ -30,7 +30,6 @@ class PixelBuffer; namespace TizenPlatform { - class ResourceLoadingClient; namespace Ktx @@ -47,7 +46,7 @@ const unsigned char MAGIC_BYTE_2 = 0x4B; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file loaded successfully, false otherwise */ -bool LoadBitmapFromKtx( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromKtx(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * Loads the header of a KTX file and fills in the width and height appropriately. @@ -57,7 +56,7 @@ bool LoadBitmapFromKtx( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe * @param[out] height Is set with the height of the image * @return true if the file's header was read successully, false otherwise */ -bool LoadKtxHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadKtxHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-png.cpp b/dali/internal/imaging/common/loader-png.cpp index 34050fc..e13a8ec 100644 --- a/dali/internal/imaging/common/loader-png.cpp +++ b/dali/internal/imaging/common/loader-png.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,21 +19,19 @@ #include -#include #include +#include +#include #include #include -#include namespace Dali { namespace TizenPlatform { - namespace { - // simple class to enforce clean-up of PNG structures struct auto_png { @@ -52,12 +50,12 @@ struct auto_png } png_structp& png; - png_infop& info; + png_infop& info; }; // struct auto_png; -bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_structp &png, png_infop &info) +bool LoadPngHeader(FILE* fp, unsigned int& width, unsigned int& height, png_structp& png, png_infop& info) { - png_byte header[8] = { 0 }; + png_byte header[8] = {0}; // Check header to see if it is a PNG file size_t size = fread(header, 1, 8, fp); @@ -101,40 +99,40 @@ bool LoadPngHeader(FILE *fp, unsigned int &width, unsigned int &height, png_stru png_read_info(png, info); // dimensions - width = png_get_image_width(png, info); + width = png_get_image_width(png, info); height = png_get_image_height(png, info); return true; } -} // namespace - anonymous +} // namespace -bool LoadPngHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadPngHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { - png_structp png = NULL; - png_infop info = NULL; - auto_png autoPng(png, info); + png_structp png = NULL; + png_infop info = NULL; + auto_png autoPng(png, info); - bool success = LoadPngHeader( input.file, width, height, png, info ); + bool success = LoadPngHeader(input.file, width, height, png, info); return success; } -bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromPng(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { - png_structp png = NULL; - png_infop info = NULL; - auto_png autoPng(png, info); + png_structp png = NULL; + png_infop info = NULL; + auto_png autoPng(png, info); /// @todo: consider parameters unsigned int y; unsigned int width, height; - png_bytep *rows; - unsigned int bpp = 0; // bytes per pixel - bool valid = false; + png_bytep* rows; + unsigned int bpp = 0; // bytes per pixel + bool valid = false; // Load info from the header - if( !LoadPngHeader( input.file, width, height, png, info ) ) + if(!LoadPngHeader(input.file, width, height, png, info)) { return false; } @@ -145,7 +143,7 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe unsigned int colordepth = png_get_bit_depth(png, info); // Ask PNGLib to convert high precision images into something we can use: - if (colordepth == 16) + if(colordepth == 16) { png_set_strip_16(png); colordepth = 8; @@ -153,13 +151,13 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe png_byte colortype = png_get_color_type(png, info); - if( colortype == PNG_COLOR_TYPE_GRAY || - colortype == PNG_COLOR_TYPE_GRAY_ALPHA ) + if(colortype == PNG_COLOR_TYPE_GRAY || + colortype == PNG_COLOR_TYPE_GRAY_ALPHA) { - if( colortype == PNG_COLOR_TYPE_GRAY ) + if(colortype == PNG_COLOR_TYPE_GRAY) { pixelFormat = Pixel::L8; - if( png_get_valid(png, info, PNG_INFO_tRNS) ) + if(png_get_valid(png, info, PNG_INFO_tRNS)) { colortype = PNG_COLOR_TYPE_GRAY_ALPHA; /* expand transparency entry -> alpha channel if present */ @@ -172,7 +170,7 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe pixelFormat = Pixel::LA88; } - if( colordepth < 8 ) + if(colordepth < 8) { /* expand gray (w/reduced bits) -> 8-bit RGB if necessary */ png_set_expand_gray_1_2_4_to_8(png); @@ -181,20 +179,20 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe } valid = true; } - else if(colortype == PNG_COLOR_TYPE_RGB ) + else if(colortype == PNG_COLOR_TYPE_RGB) { switch(colordepth) { case 8: { pixelFormat = Pixel::RGB888; - valid = true; + valid = true; break; } - case 5: /// @todo is this correct for RGB16 5-6-5 ? + case 5: /// @todo is this correct for RGB16 5-6-5 ? { pixelFormat = Pixel::RGB565; - valid = true; + valid = true; break; } default: @@ -210,7 +208,7 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe case 8: { pixelFormat = Pixel::RGBA8888; - valid = true; + valid = true; break; } default: @@ -226,7 +224,7 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe case 1: { pixelFormat = Pixel::LA88; - valid = true; + valid = true; break; } @@ -240,7 +238,7 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe if(png_get_valid(png, info, PNG_INFO_tRNS) == 0x10) { pixelFormat = Pixel::RGBA8888; - valid = true; + valid = true; } else { @@ -259,9 +257,9 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe } } - if( !valid ) + if(!valid) { - DALI_LOG_WARNING( "Unsupported png format\n" ); + DALI_LOG_WARNING("Unsupported png format\n"); return false; } @@ -278,12 +276,12 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe unsigned int rowBytes = png_get_rowbytes(png, info); - unsigned int bufferWidth = GetTextureDimension(width); - unsigned int bufferHeight = GetTextureDimension(height); - unsigned int stride = bufferWidth*bpp; + unsigned int bufferWidth = GetTextureDimension(width); + unsigned int bufferHeight = GetTextureDimension(height); + unsigned int stride = bufferWidth * bpp; // not sure if this ever happens - if( rowBytes > stride ) + if(rowBytes > stride) { stride = GetTextureDimension(rowBytes); @@ -299,15 +297,20 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe default: break; } - } // decode the whole image into bitmap buffer auto pixels = (bitmap = Dali::Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat)).GetBuffer(); DALI_ASSERT_DEBUG(pixels); - rows = reinterpret_cast< png_bytep* >( malloc(sizeof(png_bytep) * height) ); - for(y=0; y(malloc(sizeof(png_bytep) * height)); + if(!rows) + { + DALI_LOG_ERROR("malloc is failed\n"); + return false; + } + + for(y = 0; y < height; y++) { rows[y] = pixels + y * stride; } @@ -338,57 +341,57 @@ struct AutoPngWrite } png_structp& png; - png_infop& info; + png_infop& info; }; // struct AutoPngWrite; namespace { - // Custom libpng write callbacks that buffer to a vector instead of a file: +// Custom libpng write callbacks that buffer to a vector instead of a file: - /** +/** * extern "C" linkage is used because this is a callback that we pass to a C * library which is part of the underlying platform and so potentially compiled * as C rather than C++. * @see http://stackoverflow.com/a/2594222 * */ - extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length) +extern "C" void WriteData(png_structp png_ptr, png_bytep data, png_size_t length) +{ + DALI_ASSERT_DEBUG(png_ptr && data); + if(!png_ptr || !data) { - DALI_ASSERT_DEBUG(png_ptr && data); - if(!png_ptr || !data) - { - return; - } - // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library: - try + return; + } + // Make sure we don't try to propagate a C++ exception up the call stack of a pure C library: + try + { + // Recover our buffer for writing into: + Vector* const encoded_img = static_cast*>(png_get_io_ptr(png_ptr)); + if(encoded_img) { - // Recover our buffer for writing into: - Vector* const encoded_img = static_cast< Vector* >( png_get_io_ptr(png_ptr) ); - if(encoded_img) - { - const Vector::SizeType bufferSize = encoded_img->Count(); - encoded_img->Resize( bufferSize + length ); //< Can throw OOM. - unsigned char* const bufferBack = encoded_img->Begin() + bufferSize; - memcpy(bufferBack, data, length); - } - else - { - DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n"); - } + const Vector::SizeType bufferSize = encoded_img->Count(); + encoded_img->Resize(bufferSize + length); //< Can throw OOM. + unsigned char* const bufferBack = encoded_img->Begin() + bufferSize; + memcpy(bufferBack, data, length); } - catch(...) + else { - DALI_LOG_ERROR("C++ Exception caught\n"); + DALI_LOG_ERROR("PNG buffer for write to memory was passed from libpng as null.\n"); } } - - /** Override the flush with a NOP to prevent libpng trying cstdlib file io. */ - extern "C" void FlushData(png_structp png_ptr) + catch(...) { + DALI_LOG_ERROR("C++ Exception caught\n"); + } +} + +/** Override the flush with a NOP to prevent libpng trying cstdlib file io. */ +extern "C" void FlushData(png_structp png_ptr) +{ #ifdef DEBUG_ENABLED - Debug::LogMessage(Debug::DebugInfo, "PNG Flush"); + Debug::LogMessage(Debug::DebugInfo, "PNG Flush"); #endif // DEBUG_ENABLED - } } +} // namespace /** * Potential improvements: @@ -402,20 +405,20 @@ namespace * 7. If caller asks for no compression, bypass libpng and blat raw data to * disk, topped and tailed with header/tail blocks. */ -bool EncodeToPng( const unsigned char* const pixelBuffer, Vector& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat ) +bool EncodeToPng(const unsigned char* const pixelBuffer, Vector& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat) { // Translate pixel format enum: - int pngPixelFormat = -1; - unsigned pixelBytes = 0; - bool rgbaOrder = true; + int pngPixelFormat = -1; + unsigned pixelBytes = 0; + bool rgbaOrder = true; // Account for RGB versus BGR and presence of alpha in input pixels: - switch( pixelFormat ) + switch(pixelFormat) { case Pixel::RGB888: { pngPixelFormat = PNG_COLOR_TYPE_RGB; - pixelBytes = 3; + pixelBytes = 3; break; } case Pixel::BGRA8888: @@ -426,12 +429,12 @@ bool EncodeToPng( const unsigned char* const pixelBuffer, Vector& case Pixel::RGBA8888: { pngPixelFormat = PNG_COLOR_TYPE_RGB_ALPHA; - pixelBytes = 4; + pixelBytes = 4; break; } default: { - DALI_LOG_ERROR( "Unsupported pixel format for encoding to PNG.\n" ); + DALI_LOG_ERROR("Unsupported pixel format for encoding to PNG.\n"); return false; } } @@ -444,7 +447,7 @@ bool EncodeToPng( const unsigned char* const pixelBuffer, Vector& return false; } /* Allocate/initialize the image information data. REQUIRED */ - png_infop info_ptr = png_create_info_struct( png_ptr ); + png_infop info_ptr = png_create_info_struct(png_ptr); if(!info_ptr) { png_destroy_write_struct(&png_ptr, NULL); @@ -471,37 +474,35 @@ bool EncodeToPng( const unsigned char* const pixelBuffer, Vector& // Explicitly limit the number of filters used per scanline to speed us up: // png_set_filter(png_ptr, 0, PNG_FILTER_NONE); ///!ToDo: Try this once baseline profile is in place. - // PNG_FILTER_SUB | - // PNG_FILTER_UP | - // PNG_FILTER_AVE | - // PNG_FILTER_PAETH | - // PNG_ALL_FILTERS); + // PNG_FILTER_SUB | + // PNG_FILTER_UP | + // PNG_FILTER_AVE | + // PNG_FILTER_PAETH | + // PNG_ALL_FILTERS); // Play with Zlib parameters in optimisation phase: - // png_set_compression_mem_level(png_ptr, 8); - // png_set_compression_strategy(png_ptr, - // Z_DEFAULT_STRATEGY); - // png_set_compression_window_bits(png_ptr, 15); - // png_set_compression_method(png_ptr, 8); - // png_set_compression_buffer_size(png_ptr, 8192) + // png_set_compression_mem_level(png_ptr, 8); + // png_set_compression_strategy(png_ptr, + // Z_DEFAULT_STRATEGY); + // png_set_compression_window_bits(png_ptr, 15); + // png_set_compression_method(png_ptr, 8); + // png_set_compression_buffer_size(png_ptr, 8192) // Let lib_png know if the pixel bytes are in BGR(A) order: if(!rgbaOrder) { - png_set_bgr( png_ptr ); + png_set_bgr(png_ptr); } // Set the image information: - png_set_IHDR(png_ptr, info_ptr, width, height, 8, - pngPixelFormat, interlace, - PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + png_set_IHDR(png_ptr, info_ptr, width, height, 8, pngPixelFormat, interlace, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); // Start to output the PNG data to our buffer: png_write_info(png_ptr, info_ptr); // Walk the rows: - const unsigned row_step = width * pixelBytes; - png_bytep row_ptr = const_cast(pixelBuffer); - const png_bytep row_end = row_ptr + height * row_step; + const unsigned row_step = width * pixelBytes; + png_bytep row_ptr = const_cast(pixelBuffer); + const png_bytep row_end = row_ptr + height * row_step; for(; row_ptr < row_end; row_ptr += row_step) { png_write_row(png_ptr, row_ptr); diff --git a/dali/internal/imaging/common/loader-png.h b/dali/internal/imaging/common/loader-png.h old mode 100755 new mode 100644 index d2d52fb..027fd85 --- a/dali/internal/imaging/common/loader-png.h +++ b/dali/internal/imaging/common/loader-png.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_PNG_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,11 @@ * */ -#include +#include +#include #include #include -#include -#include +#include namespace Dali { @@ -33,7 +33,6 @@ class PixelBuffer; namespace TizenPlatform { - class ResourceLoadingClient; namespace Png @@ -49,7 +48,7 @@ const unsigned char MAGIC_BYTE_2 = 0x50; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file decoded successfully, false otherwise */ -bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromPng(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * Loads the header of a PNG file and fills in the width and height appropriately. @@ -59,7 +58,7 @@ bool LoadBitmapFromPng( const Dali::ImageLoader::Input& input, Dali::Devel::Pixe * @param[out] height Is set with the height of the image * @return true if the file's header was read successully, false otherwise */ -bool LoadPngHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadPngHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); /** * Encode raw pixel data to PNG format. @@ -69,7 +68,7 @@ bool LoadPngHeader( const Dali::ImageLoader::Input& input, unsigned int& width, * @param[in] height Image height * @param[in] pixelFormat Input pixel format (must be Pixel::RGB888) */ -bool EncodeToPng( const unsigned char* pixelBuffer, Vector& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat ); +bool EncodeToPng(const unsigned char* pixelBuffer, Vector& encodedPixels, std::size_t width, std::size_t height, Pixel::Format pixelFormat); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/loader-wbmp.cpp b/dali/internal/imaging/common/loader-wbmp.cpp old mode 100755 new mode 100644 index 6942442..0a6ac47 --- a/dali/internal/imaging/common/loader-wbmp.cpp +++ b/dali/internal/imaging/common/loader-wbmp.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,41 +24,37 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace TizenPlatform { - namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_LOADER_WBMP"); #endif #define IMG_MAX_SIZE 65536 -#define IMG_TOO_BIG(w, h) \ - ((((unsigned long long)w) * ((unsigned long long)h)) >= \ - ((1ULL << (29)) - 2048)) - +#define IMG_TOO_BIG(w, h) \ + ((((unsigned long long)w) * ((unsigned long long)h)) >= \ + ((1ULL << (29)) - 2048)) //extract multiple bytes integer , and saved in *data -int extractMultiByteInteger(unsigned int *data, void *map, size_t length, size_t *position) +int extractMultiByteInteger(unsigned int* data, void* map, size_t length, size_t* position) { // the header field contains an image type indentifier of multi-byte length(TypeField), an octet of general header info(FixHeaderField) //, a multi-byte width field(Width) and a multi-byte height field(Height) and so on. // The actual organisation of the image data depends on the image type // for Ext Headers flag (7th bit), 1 = More will follow, 0 = Last octet // so in the for loop, if(buf & 0x80 == 0), loop will be exited - int targetMultiByteInteger = 0, readBufCount; + int targetMultiByteInteger = 0, readBufCount; unsigned char buf; - for (readBufCount = 0;;) + for(readBufCount = 0;;) { // readBufCount means the count that fetched data from map // extractMultiByteInteger() is to fetch wbmp type , width, and height @@ -67,18 +63,18 @@ int extractMultiByteInteger(unsigned int *data, void *map, size_t length, size_t // for general width and height, if(buf & 0x80) == 0, then the next byte does not need to fetch again // first step, readBufCount = 1 , read int(4 bytes) to buf, if buf & 0x80 !=0, the buf need to continue to fetch // second step, readBufCount = 2, read next( 4 bytes) to buf, if buf & 0x80 == 0, then assigned the buf to target - if ((readBufCount ++) == 4) + if((readBufCount++) == 4) { return -1; } - if (*position > length) + if(*position > length) { return -1; } - buf = reinterpret_cast< unsigned char * >( map )[(*position)++]; + buf = reinterpret_cast(map)[(*position)++]; targetMultiByteInteger = (targetMultiByteInteger << 7) | (buf & 0x7f); - if ((buf & 0x80) == 0) + if((buf & 0x80) == 0) { DALI_LOG_INFO(gLogFilter, Debug::Verbose, "position: %d, readBufCount: %d\n", *position, readBufCount); break; @@ -88,9 +84,9 @@ int extractMultiByteInteger(unsigned int *data, void *map, size_t length, size_t return 0; } -}// end unnamed namespace +} // end unnamed namespace -bool LoadBitmapFromWbmp( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ) +bool LoadBitmapFromWbmp(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap) { FILE* const fp = input.file; if(fp == NULL) @@ -99,35 +95,35 @@ bool LoadBitmapFromWbmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pix return false; } Dali::Vector map; - Dali::Vector surface;//unsigned int - size_t position = 0; + Dali::Vector surface; //unsigned int + size_t position = 0; - unsigned int w, h; - unsigned int type; - unsigned int line_length; - unsigned char *line = NULL; - unsigned int cur = 0, x, y; + unsigned int w, h; + unsigned int type; + unsigned int line_length; + unsigned char* line = NULL; + unsigned int cur = 0, x, y; - if( fseek(fp,0,SEEK_END) ) + if(fseek(fp, 0, SEEK_END)) { DALI_LOG_ERROR("Error seeking WBMP data\n"); return false; } long positionIndicator = ftell(fp); - unsigned int fsize( 0u ); - if( positionIndicator > -1L ) + unsigned int fsize(0u); + if(positionIndicator > -1L) { fsize = static_cast(positionIndicator); } - if( 0u == fsize ) + if(0u == fsize) { DALI_LOG_ERROR("Error: filesize is 0!\n"); return false; } - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking WBMP data\n"); return false; @@ -150,18 +146,18 @@ bool LoadBitmapFromWbmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pix return false; } - if (extractMultiByteInteger(&type, &map[0], fsize, &position) < 0) + if(extractMultiByteInteger(&type, &map[0], fsize, &position) < 0) { return false; } position++; /* skipping one byte */ - if (extractMultiByteInteger(&w, &map[0], fsize, &position) < 0) + if(extractMultiByteInteger(&w, &map[0], fsize, &position) < 0) { return false; } - if (extractMultiByteInteger(&h, &map[0], fsize, &position) < 0) + if(extractMultiByteInteger(&h, &map[0], fsize, &position) < 0) { return false; } @@ -171,47 +167,46 @@ bool LoadBitmapFromWbmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pix return false; } - if ((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE)) + if((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE)) { return false; } - surface.Resize(w* h );//(w * h * 4); - memset(&surface[0], 0, w * h ); // w * h * 4 + surface.Resize(w * h); //(w * h * 4); + memset(&surface[0], 0, w * h); // w * h * 4 line_length = (w + 7) >> 3; - for (y = 0; y < h; y ++) + for(y = 0; y < h; y++) { - if (position + line_length > fsize) + if(position + line_length > fsize) { return false; } line = &map[0] + position; position += line_length; - for (x = 0; x < w; x++) + for(x = 0; x < w; x++) { - int idx = x >> 3; + int idx = x >> 3; int offset = 1 << (0x07 - (x & 0x07)); - if (line[idx] & offset) + if(line[idx] & offset) { - surface[cur] = 0xff;//0xffffffff; + surface[cur] = 0xff; //0xffffffff; } else { - surface[cur] = 0x00;//0xff000000; + surface[cur] = 0x00; //0xff000000; } cur++; } } auto pixels = (bitmap = Dali::Devel::PixelBuffer::New(w, h, Pixel::L8)).GetBuffer(); - memcpy( pixels, &surface[0], w * h ); //w * h * 4 + memcpy(pixels, &surface[0], w * h); //w * h * 4 return true; } - -bool LoadWbmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ) +bool LoadWbmpHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height) { FILE* const fp = input.file; if(fp == NULL) @@ -220,29 +215,29 @@ bool LoadWbmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, return false; } Dali::Vector map; - size_t position = 0; + size_t position = 0; - unsigned int w, h; + unsigned int w, h; unsigned int type; - if( fseek(fp,0,SEEK_END) ) + if(fseek(fp, 0, SEEK_END)) { DALI_LOG_ERROR("Error seeking WBMP data\n"); return false; } long positionIndicator = ftell(fp); - unsigned int fsize( 0u ); - if( positionIndicator > -1L ) + unsigned int fsize(0u); + if(positionIndicator > -1L) { fsize = static_cast(positionIndicator); } - if( 0u == fsize ) + if(0u == fsize) { return false; } - if( fseek(fp, 0, SEEK_SET) ) + if(fseek(fp, 0, SEEK_SET)) { DALI_LOG_ERROR("Error seeking WBMP data\n"); return false; @@ -254,8 +249,8 @@ bool LoadWbmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, } // type(1 byte) + fixedheader(1 byte) + width(uint) + height(uint) - unsigned int headerSize = 1 + 1 + 4 + 4;// 8 + 8 + 32 + 32; - headerSize = std::min(headerSize, fsize); + unsigned int headerSize = 1 + 1 + 4 + 4; // 8 + 8 + 32 + 32; + headerSize = std::min(headerSize, fsize); map.Resize(headerSize); if(fread(&map[0], 1, headerSize, fp) != headerSize) @@ -264,7 +259,7 @@ bool LoadWbmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, return false; } - if (extractMultiByteInteger(&type, &map[0], headerSize, &position) < 0) + if(extractMultiByteInteger(&type, &map[0], headerSize, &position) < 0) { DALI_LOG_ERROR("Error: unable to read type!\n"); return false; @@ -275,27 +270,27 @@ bool LoadWbmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, DALI_LOG_ERROR("Error: unknown format!\n"); return false; } - if (extractMultiByteInteger(&w, &map[0], headerSize, &position) < 0) + if(extractMultiByteInteger(&w, &map[0], headerSize, &position) < 0) { DALI_LOG_ERROR("Error: can not read width!\n"); return false; } - if (extractMultiByteInteger(&h, &map[0], headerSize, &position) < 0) + if(extractMultiByteInteger(&h, &map[0], headerSize, &position) < 0) { DALI_LOG_ERROR("Error: can not read height!\n"); return false; } - if ((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE) ) + if((w < 1) || (h < 1) || (w > IMG_MAX_SIZE) || (h > IMG_MAX_SIZE)) { DALI_LOG_ERROR("Error: file size is not supported!\n"); return false; } - width = w; + width = w; height = h; return true; } -} -} +} // namespace TizenPlatform +} // namespace Dali diff --git a/dali/internal/imaging/common/loader-wbmp.h b/dali/internal/imaging/common/loader-wbmp.h old mode 100755 new mode 100644 index ccc8038..8b4886c --- a/dali/internal/imaging/common/loader-wbmp.h +++ b/dali/internal/imaging/common/loader-wbmp.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_LOADER_WBMP_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,11 @@ * */ -#include #include +#include namespace Dali { - namespace Devel { class PixelBuffer; @@ -31,7 +30,6 @@ class PixelBuffer; namespace TizenPlatform { - class ResourceLoadingClient; /** @@ -39,7 +37,7 @@ class ResourceLoadingClient; * @param[out] bitmap The bitmap class where the decoded image will be stored * @return true if file decoded successfully, false otherwise */ -bool LoadBitmapFromWbmp( const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap ); +bool LoadBitmapFromWbmp(const Dali::ImageLoader::Input& input, Dali::Devel::PixelBuffer& bitmap); /** * @param[in] input Information about the input image (including file pointer) @@ -47,7 +45,7 @@ bool LoadBitmapFromWbmp( const Dali::ImageLoader::Input& input, Dali::Devel::Pix * @param[out] height of image * @return true if header loaded successfully, false otherwise */ -bool LoadWbmpHeader( const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height ); +bool LoadWbmpHeader(const Dali::ImageLoader::Input& input, unsigned int& width, unsigned int& height); } // namespace TizenPlatform diff --git a/dali/internal/imaging/common/native-bitmap-buffer-impl.cpp b/dali/internal/imaging/common/native-bitmap-buffer-impl.cpp index 3aa9442..24a15ff 100644 --- a/dali/internal/imaging/common/native-bitmap-buffer-impl.cpp +++ b/dali/internal/imaging/common/native-bitmap-buffer-impl.cpp @@ -19,35 +19,32 @@ #include // EXTERNAL HEADERS -#include #include +#include // INTERNAL HEADERS -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - -NativeBitmapBuffer::NativeBitmapBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pFormat ) -: mGlAbstraction( nullptr), +NativeBitmapBuffer::NativeBitmapBuffer(Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pFormat) +: mGlAbstraction(nullptr), mWidth(width), mHeight(height), mPixelFormat(pFormat), mLastReadBuffer(NULL) { - DALI_ASSERT_ALWAYS( adaptor ); - mBuffer = new Integration::LocklessBuffer( width * height * Pixel::GetBytesPerPixel(pFormat) ); + DALI_ASSERT_ALWAYS(adaptor); + mBuffer = new Integration::LocklessBuffer(width * height * Pixel::GetBytesPerPixel(pFormat)); - GraphicsInterface* graphics = &(adaptor->GetGraphicsInterface()); - auto eglGraphics = static_cast(graphics); - mGlAbstraction = &(eglGraphics->GetGlAbstraction()); + GraphicsInterface* graphics = &(adaptor->GetGraphicsInterface()); + auto eglGraphics = static_cast(graphics); + mGlAbstraction = &(eglGraphics->GetGlAbstraction()); } NativeBitmapBuffer::~NativeBitmapBuffer() @@ -57,26 +54,26 @@ NativeBitmapBuffer::~NativeBitmapBuffer() void NativeBitmapBuffer::PrepareTexture() { - DALI_ASSERT_ALWAYS( mBuffer ); - GLenum pixelFormat = GL_RGBA; + DALI_ASSERT_ALWAYS(mBuffer); + GLenum pixelFormat = GL_RGBA; GLenum pixelDataType = GL_UNSIGNED_BYTE; - Integration::ConvertToGlFormat( mPixelFormat, pixelDataType, pixelFormat ); + Integration::ConvertToGlFormat(mPixelFormat, pixelDataType, pixelFormat); const unsigned char* buf = mBuffer->Read(); - if( buf && buf != mLastReadBuffer ) // Prevent same buffer being uploaded multiple times + if(buf && buf != mLastReadBuffer) // Prevent same buffer being uploaded multiple times { mLastReadBuffer = buf; // The active texture has already been set to a sampler and bound. - mGlAbstraction->TexImage2D( GL_TEXTURE_2D, 0, pixelFormat, mWidth, mHeight, 0, pixelFormat, pixelDataType, buf ); + mGlAbstraction->TexImage2D(GL_TEXTURE_2D, 0, pixelFormat, mWidth, mHeight, 0, pixelFormat, pixelDataType, buf); } } -void NativeBitmapBuffer::Write( const unsigned char *src, size_t size ) +void NativeBitmapBuffer::Write(const unsigned char* src, size_t size) { - mBuffer->Write( src, size ); // Write will cause LocklessBuffer to switch to the other buffer + mBuffer->Write(src, size); // Write will cause LocklessBuffer to switch to the other buffer } bool NativeBitmapBuffer::CreateResource() @@ -105,7 +102,7 @@ unsigned int NativeBitmapBuffer::GetHeight() const bool NativeBitmapBuffer::RequiresBlending() const { - return Pixel::HasAlpha( mPixelFormat ); + return Pixel::HasAlpha(mPixelFormat); } int NativeBitmapBuffer::GetTextureTarget() const diff --git a/dali/internal/imaging/common/native-bitmap-buffer-impl.h b/dali/internal/imaging/common/native-bitmap-buffer-impl.h index 6a4fc43..5527fd4 100644 --- a/dali/internal/imaging/common/native-bitmap-buffer-impl.h +++ b/dali/internal/imaging/common/native-bitmap-buffer-impl.h @@ -2,7 +2,7 @@ #define DALI_NATIVE_BITMAP_BUFFER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ */ // EXTERNAL HEADERS -#include -#include #include #include #include +#include +#include // INTERNAL HEADERS #include @@ -31,13 +31,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class NativeBitmapBuffer; typedef IntrusivePtr NativeBitmapBufferPtr; @@ -46,7 +43,6 @@ typedef IntrusivePtr NativeBitmapBufferPtr; */ class NativeBitmapBuffer : public NativeImageInterface { - public: /** * Constructor. @@ -55,7 +51,7 @@ public: * @param height height of image * @param pixelFormat pixel format for image */ - NativeBitmapBuffer( Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat ); + NativeBitmapBuffer(Adaptor* adaptor, unsigned int width, unsigned int height, Pixel::Format pixelFormat); /** * virtual destructor @@ -68,7 +64,7 @@ public: * @param[in] size size of data in bytes * @return true if successful, false if currently reading from buffer in render thread */ - void Write( const unsigned char* src, size_t size ); + void Write(const unsigned char* src, size_t size); public: /** @@ -131,19 +127,18 @@ public: */ bool SourceChanged() const override; - private: - NativeBitmapBuffer( const NativeBitmapBuffer& ); ///< not defined - NativeBitmapBuffer& operator =( const NativeBitmapBuffer& ); ///< not defined - NativeBitmapBuffer(); ///< not defined + NativeBitmapBuffer(const NativeBitmapBuffer&); ///< not defined + NativeBitmapBuffer& operator=(const NativeBitmapBuffer&); ///< not defined + NativeBitmapBuffer(); ///< not defined private: - Integration::GlAbstraction* mGlAbstraction; ///< GlAbstraction used + Integration::GlAbstraction* mGlAbstraction; ///< GlAbstraction used - Integration::LocklessBuffer* mBuffer; ///< bitmap data double buffered - unsigned int mWidth; ///< Image width - unsigned int mHeight; ///< Image height - Pixel::Format mPixelFormat; ///< Image pixelformat + Integration::LocklessBuffer* mBuffer; ///< bitmap data double buffered + unsigned int mWidth; ///< Image width + unsigned int mHeight; ///< Image height + Pixel::Format mPixelFormat; ///< Image pixelformat const unsigned char* mLastReadBuffer; ///< last buffer that was read }; diff --git a/dali/internal/imaging/common/native-image-source-factory.h b/dali/internal/imaging/common/native-image-source-factory.h index f334f65..93870c3 100644 --- a/dali/internal/imaging/common/native-image-source-factory.h +++ b/dali/internal/imaging/common/native-image-source-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -31,29 +31,24 @@ namespace Internal { namespace Adaptor { - class NativeImageSource; class NativeImageSourceQueue; class NativeImageSourceFactory { public: - - NativeImageSourceFactory() = default; + NativeImageSourceFactory() = default; virtual ~NativeImageSourceFactory() = default; - virtual std::unique_ptr< NativeImageSource > CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) = 0; - - virtual std::unique_ptr< NativeImageSourceQueue > CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) = 0; + virtual std::unique_ptr CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) = 0; + virtual std::unique_ptr CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) = 0; }; -extern std::unique_ptr< NativeImageSourceFactory > GetNativeImageSourceFactory(); +extern std::unique_ptr GetNativeImageSourceFactory(); -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_H diff --git a/dali/internal/imaging/common/native-image-source-impl.h b/dali/internal/imaging/common/native-image-source-impl.h old mode 100755 new mode 100644 index d0a8010..f2d3295 --- a/dali/internal/imaging/common/native-image-source-impl.h +++ b/dali/internal/imaging/common/native-image-source-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,25 +19,21 @@ */ // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Dali internal NativeImageSource. */ class NativeImageSource { public: - static constexpr uint32_t DEFAULT_QUALITY = 100; /** @@ -49,10 +45,10 @@ public: * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSource* New(uint32_t width, - uint32_t height, + static NativeImageSource* New(uint32_t width, + uint32_t height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + Any nativeImageSource); /** * @copydoc Dali::NativeImageSource::GetNativeImageSource() */ @@ -61,17 +57,17 @@ public: /** * @copydoc Dali::NativeImageSource::GetPixels() */ - virtual bool GetPixels(std::vector &pixbuf, uint32_t &width, uint32_t &height, Pixel::Format& pixelFormat ) const = 0; + virtual bool GetPixels(std::vector& pixbuf, uint32_t& width, uint32_t& height, Pixel::Format& pixelFormat) const = 0; /** * @copydoc Dali::NativeImageSource::SetSource( Any source ) */ - virtual void SetSource( Any source ) = 0; + virtual void SetSource(Any source) = 0; /** * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth ) */ - virtual bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) = 0; + virtual bool IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) = 0; /** * destructor @@ -146,7 +142,7 @@ public: /** * @brief Dali::DevelNativeImageSource::AcquireBuffer() */ - virtual uint8_t* AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) = 0; + virtual uint8_t* AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) = 0; /** * @brief Dali::DevelNativeImageSource::ReleaseBuffer() @@ -156,9 +152,9 @@ public: /** * @copydoc Dali::NativeImageSource::EncodeToFile(const std::string& ) */ - inline bool EncodeToFile( const std::string& filename ) const + inline bool EncodeToFile(const std::string& filename) const { - return EncodeToFile( filename, DEFAULT_QUALITY ); + return EncodeToFile(filename, DEFAULT_QUALITY); } /** @@ -171,21 +167,24 @@ public: * @param[in] quality The quality of encoded jpeg image * @return @c true if the pixels were written, and @c false otherwise */ - inline bool EncodeToFile( const std::string& filename, const uint32_t quality ) const + inline bool EncodeToFile(const std::string& filename, const uint32_t quality) const { - std::vector< uint8_t > pixbuf; - uint32_t width( 0 ), height( 0 ); - Pixel::Format pixelFormat; + std::vector pixbuf; + uint32_t width(0), height(0); + Pixel::Format pixelFormat; - if( GetPixels( pixbuf, width, height, pixelFormat ) ) + if(GetPixels(pixbuf, width, height, pixelFormat)) { - return Dali::EncodeToFile( &pixbuf[0], filename, pixelFormat, width, height, quality ); + return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height, quality); } return false; } public: - inline static Internal::Adaptor::NativeImageSource& GetImplementation( Dali::NativeImageSource& image ) { return *image.mImpl; } + inline static Internal::Adaptor::NativeImageSource& GetImplementation(Dali::NativeImageSource& image) + { + return *image.mImpl; + } }; } // namespace Adaptor diff --git a/dali/internal/imaging/common/native-image-source-queue-impl.h b/dali/internal/imaging/common/native-image-source-queue-impl.h old mode 100755 new mode 100644 index e7638c5..00ccbfc --- a/dali/internal/imaging/common/native-image-source-queue-impl.h +++ b/dali/internal/imaging/common/native-image-source-queue-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_QUEUE_IMPL_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,24 +23,20 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Dali internal NativeImageSourceQueue. */ class NativeImageSourceQueue { public: - /** * @copydoc Dali::NativeImageSourceQueue::New() */ - static NativeImageSourceQueue* New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + static NativeImageSourceQueue* New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); /** * @copydoc Dali::NativeImageSourceQueue::GetNativeImageSourceQueue() @@ -50,7 +46,7 @@ public: /** * @copydoc Dali::NativeImageSourceQueue::SetSize */ - virtual void SetSize( uint32_t width, uint32_t height ) = 0; + virtual void SetSize(uint32_t width, uint32_t height) = 0; /** * @copydoc Dali::NativeImageSourceQueue::IgnoreSourceImage diff --git a/dali/internal/imaging/common/pixel-buffer-impl.cpp b/dali/internal/imaging/common/pixel-buffer-impl.cpp old mode 100755 new mode 100644 index 7490bf4..1b74988 --- a/dali/internal/imaging/common/pixel-buffer-impl.cpp +++ b/dali/internal/imaging/common/pixel-buffer-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,37 +23,34 @@ #include // INTERNAL INCLUDES -#include #include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { const float TWO_PI = 2.f * Math::PI; ///< 360 degrees in radians } // namespace -PixelBuffer::PixelBuffer( unsigned char* buffer, - unsigned int bufferSize, - unsigned int width, - unsigned int height, - Dali::Pixel::Format pixelFormat ) +PixelBuffer::PixelBuffer(unsigned char* buffer, + unsigned int bufferSize, + unsigned int width, + unsigned int height, + Dali::Pixel::Format pixelFormat) : mMetadata(), - mBuffer( buffer ), - mBufferSize( bufferSize ), - mWidth( width ), - mHeight( height ), - mPixelFormat( pixelFormat ), - mPreMultiplied( false ) + mBuffer(buffer), + mBufferSize(bufferSize), + mWidth(width), + mHeight(height), + mPixelFormat(pixelFormat), + mPreMultiplied(false) { } @@ -62,40 +59,40 @@ PixelBuffer::~PixelBuffer() ReleaseBuffer(); } -PixelBufferPtr PixelBuffer::New( unsigned int width, - unsigned int height, - Dali::Pixel::Format pixelFormat ) +PixelBufferPtr PixelBuffer::New(unsigned int width, + unsigned int height, + Dali::Pixel::Format pixelFormat) { - unsigned int bufferSize = width * height * Dali::Pixel::GetBytesPerPixel( pixelFormat ); - unsigned char* buffer = NULL; - if( bufferSize > 0 ) + unsigned int bufferSize = width * height * Dali::Pixel::GetBytesPerPixel(pixelFormat); + unsigned char* buffer = NULL; + if(bufferSize > 0) { - buffer = static_cast( malloc ( bufferSize ) ); + buffer = static_cast(malloc(bufferSize)); } - return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat ); + return new PixelBuffer(buffer, bufferSize, width, height, pixelFormat); } -PixelBufferPtr PixelBuffer::New( unsigned char* buffer, - unsigned int bufferSize, - unsigned int width, - unsigned int height, - Dali::Pixel::Format pixelFormat ) +PixelBufferPtr PixelBuffer::New(unsigned char* buffer, + unsigned int bufferSize, + unsigned int width, + unsigned int height, + Dali::Pixel::Format pixelFormat) { - return new PixelBuffer( buffer, bufferSize, width, height, pixelFormat ); + return new PixelBuffer(buffer, bufferSize, width, height, pixelFormat); } -Dali::PixelData PixelBuffer::Convert( PixelBuffer& pixelBuffer ) +Dali::PixelData PixelBuffer::Convert(PixelBuffer& pixelBuffer) { - Dali::PixelData pixelData = Dali::PixelData::New( pixelBuffer.mBuffer, - pixelBuffer.mBufferSize, - pixelBuffer.mWidth, - pixelBuffer.mHeight, - pixelBuffer.mPixelFormat, - Dali::PixelData::FREE ); - pixelBuffer.mBuffer = NULL; - pixelBuffer.mWidth = 0; - pixelBuffer.mHeight = 0; - pixelBuffer.mBufferSize = 0; + Dali::PixelData pixelData = Dali::PixelData::New(pixelBuffer.mBuffer, + pixelBuffer.mBufferSize, + pixelBuffer.mWidth, + pixelBuffer.mHeight, + pixelBuffer.mPixelFormat, + Dali::PixelData::FREE); + pixelBuffer.mBuffer = NULL; + pixelBuffer.mWidth = 0; + pixelBuffer.mHeight = 0; + pixelBuffer.mBufferSize = 0; return pixelData; } @@ -134,99 +131,96 @@ Dali::PixelData PixelBuffer::CreatePixelData() const { unsigned char* destBuffer = NULL; - if( mBufferSize > 0 ) + if(mBufferSize > 0) { - destBuffer = static_cast( malloc( mBufferSize ) ); - memcpy( destBuffer, mBuffer, mBufferSize ); + destBuffer = static_cast(malloc(mBufferSize)); + memcpy(destBuffer, mBuffer, mBufferSize); } - Dali::PixelData pixelData = Dali::PixelData::New( destBuffer, mBufferSize, - mWidth, mHeight, - mPixelFormat, - Dali::PixelData::FREE ); + Dali::PixelData pixelData = Dali::PixelData::New(destBuffer, mBufferSize, mWidth, mHeight, mPixelFormat, Dali::PixelData::FREE); return pixelData; } -void PixelBuffer::ApplyMask( const PixelBuffer& inMask, float contentScale, bool cropToMask ) +void PixelBuffer::ApplyMask(const PixelBuffer& inMask, float contentScale, bool cropToMask) { - if( cropToMask ) + if(cropToMask) { // First scale this buffer by the contentScale, and crop to the mask size // If it's too small, then scale the mask to match the image size // Then apply the mask - ScaleAndCrop( contentScale, ImageDimensions( inMask.GetWidth(), inMask.GetHeight() ) ); + ScaleAndCrop(contentScale, ImageDimensions(inMask.GetWidth(), inMask.GetHeight())); - if( inMask.mWidth > mWidth || inMask.mHeight > mHeight ) + if(inMask.mWidth > mWidth || inMask.mHeight > mHeight) { - PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) ); - ApplyMaskInternal( *mask ); + PixelBufferPtr mask = NewResize(inMask, ImageDimensions(mWidth, mHeight)); + ApplyMaskInternal(*mask); } else { - ApplyMaskInternal( inMask ); + ApplyMaskInternal(inMask); } } else { // First, scale the mask to match the image size, // then apply the mask. - PixelBufferPtr mask = NewResize( inMask, ImageDimensions( mWidth, mHeight ) ); - ApplyMaskInternal( *mask ); + PixelBufferPtr mask = NewResize(inMask, ImageDimensions(mWidth, mHeight)); + ApplyMaskInternal(*mask); } } -void PixelBuffer::ApplyMaskInternal( const PixelBuffer& mask ) +void PixelBuffer::ApplyMaskInternal(const PixelBuffer& mask) { - int byteOffset=0; - int bitMask=0; + int byteOffset = 0; + int bitMask = 0; Dali::Pixel::GetAlphaOffsetAndMask(mPixelFormat, byteOffset, bitMask); - if( Dali::Pixel::HasAlpha( mPixelFormat ) && bitMask == 255 ) + if(Dali::Pixel::HasAlpha(mPixelFormat) && bitMask == 255) { - ApplyMaskToAlphaChannel( *this, mask ); + ApplyMaskToAlphaChannel(*this, mask); } else { - PixelBufferPtr newPixelBuffer = CreateNewMaskedBuffer( *this, mask ); - TakeOwnershipOfBuffer( *newPixelBuffer ); + PixelBufferPtr newPixelBuffer = CreateNewMaskedBuffer(*this, mask); + TakeOwnershipOfBuffer(*newPixelBuffer); // On leaving scope, newPixelBuffer will get destroyed. } } -void PixelBuffer::TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer ) +void PixelBuffer::TakeOwnershipOfBuffer(PixelBuffer& pixelBuffer) { ReleaseBuffer(); // Take ownership of new buffer - mBuffer = pixelBuffer.mBuffer; + mBuffer = pixelBuffer.mBuffer; pixelBuffer.mBuffer = NULL; - mBufferSize = pixelBuffer.mBufferSize; - mWidth = pixelBuffer.mWidth; - mHeight = pixelBuffer.mHeight; - mPixelFormat = pixelBuffer.mPixelFormat; + mBufferSize = pixelBuffer.mBufferSize; + mWidth = pixelBuffer.mWidth; + mHeight = pixelBuffer.mHeight; + mPixelFormat = pixelBuffer.mPixelFormat; } void PixelBuffer::ReleaseBuffer() { - if( mBuffer ) + if(mBuffer) { - free( mBuffer ); + free(mBuffer); } } -void PixelBuffer::AllocateFixedSize( uint32_t size ) +void PixelBuffer::AllocateFixedSize(uint32_t size) { ReleaseBuffer(); - mBuffer = reinterpret_cast(malloc( size )); + mBuffer = reinterpret_cast(malloc(size)); mBufferSize = size; } -bool PixelBuffer::Rotate( Degree angle ) +bool PixelBuffer::Rotate(Degree angle) { // Check first if Rotate() can perform the operation in the current pixel buffer. bool validPixelFormat = false; - switch( mPixelFormat ) + switch(mPixelFormat) { case Pixel::A8: case Pixel::L8: @@ -248,124 +242,123 @@ bool PixelBuffer::Rotate( Degree angle ) } } - if( !validPixelFormat ) + if(!validPixelFormat) { // Can't rotate the pixel buffer with the current pixel format. - DALI_LOG_ERROR( "Can't rotate the pixel buffer with the current pixel format\n" ); + DALI_LOG_ERROR("Can't rotate the pixel buffer with the current pixel format\n"); return false; } - float radians = Radian( angle ).radian; + float radians = Radian(angle).radian; // Transform the input angle into the range [0..2PI] - radians = fmod( radians, TWO_PI ); - radians += ( radians < 0.f ) ? TWO_PI : 0.f; + radians = fmod(radians, TWO_PI); + radians += (radians < 0.f) ? TWO_PI : 0.f; - if( radians < Dali::Math::MACHINE_EPSILON_10 ) + if(radians < Dali::Math::MACHINE_EPSILON_10) { // Nothing to do if the angle is zero. return true; } - const unsigned int pixelSize = Pixel::GetBytesPerPixel( mPixelFormat ); + const unsigned int pixelSize = Pixel::GetBytesPerPixel(mPixelFormat); uint8_t* pixelsOut = nullptr; - Platform::RotateByShear( mBuffer, - mWidth, - mHeight, - pixelSize, - radians, - pixelsOut, - mWidth, - mHeight ); + Platform::RotateByShear(mBuffer, + mWidth, + mHeight, + pixelSize, + radians, + pixelsOut, + mWidth, + mHeight); // Check whether the rotation succedded and set the new pixel buffer data. const bool success = nullptr != pixelsOut; - if( success ) + if(success) { // Release the memory of the current pixel buffer. ReleaseBuffer(); // Set the new pixel buffer. - mBuffer = pixelsOut; - pixelsOut = nullptr; + mBuffer = pixelsOut; + pixelsOut = nullptr; mBufferSize = mWidth * mHeight * pixelSize; } return success; } -void PixelBuffer::ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions ) +void PixelBuffer::ScaleAndCrop(float scaleFactor, ImageDimensions cropDimensions) { - ImageDimensions outDimensions( float(mWidth) * scaleFactor, - float(mHeight) * scaleFactor ); + ImageDimensions outDimensions(float(mWidth) * scaleFactor, + float(mHeight) * scaleFactor); - if( outDimensions.GetWidth() != mWidth || outDimensions.GetHeight() != mHeight ) + if(outDimensions.GetWidth() != mWidth || outDimensions.GetHeight() != mHeight) { - Resize( outDimensions ); + Resize(outDimensions); } ImageDimensions postCropDimensions( std::min(cropDimensions.GetWidth(), outDimensions.GetWidth()), std::min(cropDimensions.GetHeight(), outDimensions.GetHeight())); - if( postCropDimensions.GetWidth() < outDimensions.GetWidth() || - postCropDimensions.GetHeight() < outDimensions.GetHeight() ) + if(postCropDimensions.GetWidth() < outDimensions.GetWidth() || + postCropDimensions.GetHeight() < outDimensions.GetHeight()) { - uint16_t x = ( outDimensions.GetWidth() - postCropDimensions.GetWidth() ) / 2; - uint16_t y = ( outDimensions.GetHeight() - postCropDimensions.GetHeight() ) / 2; - Crop( x, y, postCropDimensions ); + uint16_t x = (outDimensions.GetWidth() - postCropDimensions.GetWidth()) / 2; + uint16_t y = (outDimensions.GetHeight() - postCropDimensions.GetHeight()) / 2; + Crop(x, y, postCropDimensions); } } -void PixelBuffer::Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions ) +void PixelBuffer::Crop(uint16_t x, uint16_t y, ImageDimensions cropDimensions) { - PixelBufferPtr outBuffer = NewCrop( *this, x, y, cropDimensions ); - TakeOwnershipOfBuffer( *outBuffer ); + PixelBufferPtr outBuffer = NewCrop(*this, x, y, cropDimensions); + TakeOwnershipOfBuffer(*outBuffer); } -PixelBufferPtr PixelBuffer::NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions ) +PixelBufferPtr PixelBuffer::NewCrop(const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions) { - PixelBufferPtr outBuffer = PixelBuffer::New( cropDimensions.GetWidth(), cropDimensions.GetHeight(), inBuffer.GetPixelFormat() ); - int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat ); - int srcStride = inBuffer.mWidth * bytesPerPixel; - int destStride = cropDimensions.GetWidth() * bytesPerPixel; + PixelBufferPtr outBuffer = PixelBuffer::New(cropDimensions.GetWidth(), cropDimensions.GetHeight(), inBuffer.GetPixelFormat()); + int bytesPerPixel = Pixel::GetBytesPerPixel(inBuffer.mPixelFormat); + int srcStride = inBuffer.mWidth * bytesPerPixel; + int destStride = cropDimensions.GetWidth() * bytesPerPixel; // Clamp crop to right edge - if( x + cropDimensions.GetWidth() > inBuffer.mWidth ) + if(x + cropDimensions.GetWidth() > inBuffer.mWidth) { - destStride = ( inBuffer.mWidth - x ) * bytesPerPixel; + destStride = (inBuffer.mWidth - x) * bytesPerPixel; } - int srcOffset = x * bytesPerPixel + y * srcStride; - int destOffset = 0; + int srcOffset = x * bytesPerPixel + y * srcStride; + int destOffset = 0; unsigned char* destBuffer = outBuffer->mBuffer; // Clamp crop to last row unsigned int endRow = y + cropDimensions.GetHeight(); - if( endRow > inBuffer.mHeight ) + if(endRow > inBuffer.mHeight) { - endRow = inBuffer.mHeight - 1 ; + endRow = inBuffer.mHeight - 1; } - for( uint16_t row = y; row < endRow; ++row ) + for(uint16_t row = y; row < endRow; ++row) { - memcpy(destBuffer + destOffset, inBuffer.mBuffer + srcOffset, destStride ); + memcpy(destBuffer + destOffset, inBuffer.mBuffer + srcOffset, destStride); srcOffset += srcStride; destOffset += destStride; } return outBuffer; - } -void PixelBuffer::SetMetadata( const Property::Map& map ) +void PixelBuffer::SetMetadata(const Property::Map& map) { mMetadata.reset(new Property::Map(map)); } bool PixelBuffer::GetMetadata(Property::Map& outMetadata) const { - if( !mMetadata ) + if(!mMetadata) { return false; } @@ -378,91 +371,89 @@ void PixelBuffer::SetMetadata(std::unique_ptr metadata) mMetadata = std::move(metadata); } -void PixelBuffer::Resize( ImageDimensions outDimensions ) +void PixelBuffer::Resize(ImageDimensions outDimensions) { - if( mWidth != outDimensions.GetWidth() || mHeight != outDimensions.GetHeight() ) + if(mWidth != outDimensions.GetWidth() || mHeight != outDimensions.GetHeight()) { - PixelBufferPtr outBuffer = NewResize( *this, outDimensions ); - TakeOwnershipOfBuffer( *outBuffer ); + PixelBufferPtr outBuffer = NewResize(*this, outDimensions); + TakeOwnershipOfBuffer(*outBuffer); } } -PixelBufferPtr PixelBuffer::NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions ) +PixelBufferPtr PixelBuffer::NewResize(const PixelBuffer& inBuffer, ImageDimensions outDimensions) { - PixelBufferPtr outBuffer = PixelBuffer::New( outDimensions.GetWidth(), outDimensions.GetHeight(), inBuffer.GetPixelFormat() ); - ImageDimensions inDimensions( inBuffer.mWidth, inBuffer.mHeight ); + PixelBufferPtr outBuffer = PixelBuffer::New(outDimensions.GetWidth(), outDimensions.GetHeight(), inBuffer.GetPixelFormat()); + ImageDimensions inDimensions(inBuffer.mWidth, inBuffer.mHeight); - bool hasAlpha = Pixel::HasAlpha( inBuffer.mPixelFormat ); - int bytesPerPixel = Pixel::GetBytesPerPixel( inBuffer.mPixelFormat ); + bool hasAlpha = Pixel::HasAlpha(inBuffer.mPixelFormat); + int bytesPerPixel = Pixel::GetBytesPerPixel(inBuffer.mPixelFormat); Resampler::Filter filterType = Resampler::LANCZOS4; - if( inDimensions.GetWidth() < outDimensions.GetWidth() && inDimensions.GetHeight() < outDimensions.GetHeight() ) + if(inDimensions.GetWidth() < outDimensions.GetWidth() && inDimensions.GetHeight() < outDimensions.GetHeight()) { filterType = Resampler::MITCHELL; } // This method only really works for 8 bit wide channels. // (But could be expanded to work) - if( inBuffer.mPixelFormat == Pixel::A8 || - inBuffer.mPixelFormat == Pixel::L8 || - inBuffer.mPixelFormat == Pixel::LA88 || - inBuffer.mPixelFormat == Pixel::RGB888 || - inBuffer.mPixelFormat == Pixel::RGB8888 || - inBuffer.mPixelFormat == Pixel::BGR8888 || - inBuffer.mPixelFormat == Pixel::RGBA8888 || - inBuffer.mPixelFormat == Pixel::BGRA8888 ) + if(inBuffer.mPixelFormat == Pixel::A8 || + inBuffer.mPixelFormat == Pixel::L8 || + inBuffer.mPixelFormat == Pixel::LA88 || + inBuffer.mPixelFormat == Pixel::RGB888 || + inBuffer.mPixelFormat == Pixel::RGB8888 || + inBuffer.mPixelFormat == Pixel::BGR8888 || + inBuffer.mPixelFormat == Pixel::RGBA8888 || + inBuffer.mPixelFormat == Pixel::BGRA8888) { - Dali::Internal::Platform::Resample( inBuffer.mBuffer, inDimensions, - outBuffer->GetBuffer(), outDimensions, - filterType, bytesPerPixel, hasAlpha ); + Dali::Internal::Platform::Resample(inBuffer.mBuffer, inDimensions, outBuffer->GetBuffer(), outDimensions, filterType, bytesPerPixel, hasAlpha); } else { - DALI_LOG_ERROR( "Trying to resize an image with too narrow a channel width" ); + DALI_LOG_ERROR("Trying to resize an image with too narrow a channel width"); } return outBuffer; } -void PixelBuffer::ApplyGaussianBlur( const float blurRadius ) +void PixelBuffer::ApplyGaussianBlur(const float blurRadius) { // This method only works for pixel buffer in RGBA format. - if( mWidth > 0 && mHeight > 0 && mPixelFormat == Pixel::RGBA8888 ) + if(mWidth > 0 && mHeight > 0 && mPixelFormat == Pixel::RGBA8888) { - if ( blurRadius > Math::MACHINE_EPSILON_1 ) + if(blurRadius > Math::MACHINE_EPSILON_1) { - PerformGaussianBlurRGBA( *this, blurRadius ); + PerformGaussianBlurRGBA(*this, blurRadius); } } else { - DALI_LOG_ERROR( "Trying to apply gaussian blur to an empty pixel buffer or a pixel buffer not in RGBA format" ); + DALI_LOG_ERROR("Trying to apply gaussian blur to an empty pixel buffer or a pixel buffer not in RGBA format"); } } void PixelBuffer::MultiplyColorByAlpha() { - auto bytesPerPixel = Pixel::GetBytesPerPixel( mPixelFormat ); + auto bytesPerPixel = Pixel::GetBytesPerPixel(mPixelFormat); // Compressed textures have unknown size of the pixel. Alpha premultiplication // must be skipped in such case - if( Pixel::GetBytesPerPixel(mPixelFormat) && Pixel::HasAlpha(mPixelFormat) ) + if(Pixel::GetBytesPerPixel(mPixelFormat) && Pixel::HasAlpha(mPixelFormat)) { - unsigned char* pixel = mBuffer; + unsigned char* pixel = mBuffer; const unsigned int bufferSize = mWidth * mHeight; - for( unsigned int i=0; i PixelBufferPtr; class PixelBuffer : public BaseObject { public: - /** * @brief Create a PixelBuffer object with a pre-allocated buffer. * The PixelBuffer object owns this buffer, which may be retrieved @@ -53,9 +49,9 @@ public: * @param [in] height Buffer height in pixels * @param [in] pixelFormat The pixel format */ - static PixelBufferPtr New( unsigned int width, - unsigned int height, - Pixel::Format pixelFormat ); + static PixelBufferPtr New(unsigned int width, + unsigned int height, + Pixel::Format pixelFormat); /** * @brief Create a PixelBuffer object. For internal use only. @@ -67,11 +63,11 @@ public: * @param [in] pixelFormat The pixel format * @param [in] releaseFunction The function used to release the memory. */ - static PixelBufferPtr New( unsigned char* buffer, - unsigned int bufferSize, - unsigned int width, - unsigned int height, - Pixel::Format pixelFormat ); + static PixelBufferPtr New(unsigned char* buffer, + unsigned int bufferSize, + unsigned int width, + unsigned int height, + Pixel::Format pixelFormat); /** * Convert a pixelBuffer object into a PixelData object. @@ -80,7 +76,7 @@ public: * @param[in] pixelBuffer The buffer to convert * @return the pixelData */ - static Dali::PixelData Convert( PixelBuffer& pixelBuffer ); + static Dali::PixelData Convert(PixelBuffer& pixelBuffer); /** * @brief Constructor. @@ -91,14 +87,13 @@ public: * @param [in] height Buffer height in pixels * @param [in] pixelFormat The pixel format */ - PixelBuffer( unsigned char* buffer, - unsigned int bufferSize, - unsigned int width, - unsigned int height, - Pixel::Format pixelFormat ); + PixelBuffer(unsigned char* buffer, + unsigned int bufferSize, + unsigned int width, + unsigned int height, + Pixel::Format pixelFormat); protected: - /** * @brief Destructor. * @@ -107,7 +102,6 @@ protected: ~PixelBuffer() override; public: - /** * Get the width of the buffer in pixels. * @return The width of the buffer in pixels @@ -159,14 +153,14 @@ public: * @param[in] cropToMask Whether to crop the output to the mask size (true) or scale the * mask to the content size (false) */ - void ApplyMask( const PixelBuffer& mask, float contentScale, bool cropToMask ); + void ApplyMask(const PixelBuffer& mask, float contentScale, bool cropToMask); /** * @brief Apply a Gaussian blur to the current buffer with the given radius. * * @param[in] blurRadius The radius for Gaussian blur */ - void ApplyGaussianBlur( const float blurRadius ); + void ApplyGaussianBlur(const float blurRadius); /** * Crops this buffer to the given crop rectangle. Assumes the crop rectangle @@ -175,14 +169,14 @@ public: * @param[in] y The top left corner's y * @param[in] cropDimensions The dimensions of the crop */ - void Crop( uint16_t x, uint16_t y, ImageDimensions cropDimensions ); + void Crop(uint16_t x, uint16_t y, ImageDimensions cropDimensions); /** * Resizes the buffer to the given dimensions. Uses either Lanczos4 for downscaling * or Mitchell for upscaling * @param[in] outDimensions The new dimensions */ - void Resize( ImageDimensions outDimensions ); + void Resize(ImageDimensions outDimensions); /** * Multiplies the image's color values by the alpha value. This provides better @@ -195,7 +189,7 @@ public: * * @param map Property map containing Exif fields */ - void SetMetadata( const Property::Map& map ); + void SetMetadata(const Property::Map& map); /** * @brief Returns image metadata as a property map @@ -215,12 +209,12 @@ public: * Allocates fixed amount of memory for the pixel data. Used by compressed formats. * @param[in] size Size of memory to be allocated */ - void AllocateFixedSize( uint32_t size ); + void AllocateFixedSize(uint32_t size); /** * @copydoc Devel::PixelBuffer::Rotate() */ - bool Rotate( Degree angle ); + bool Rotate(Degree angle); /** * @copydoc Devel::PixelBuffer::IsAlphaPreMultiplied() @@ -236,17 +230,17 @@ private: /* * Undefined assignment operator. */ - PixelBuffer& operator= (const PixelBuffer& other); + PixelBuffer& operator=(const PixelBuffer& other); /** * Internal method to apply the mask to this buffer. Expects that they are the same size. */ - void ApplyMaskInternal( const PixelBuffer& mask ); + void ApplyMaskInternal(const PixelBuffer& mask); /** * Takes ownership of the other object's pixel buffer. */ - void TakeOwnershipOfBuffer( PixelBuffer& pixelBuffer ); + void TakeOwnershipOfBuffer(PixelBuffer& pixelBuffer); /** * Release the buffer @@ -257,7 +251,7 @@ private: * Scales this buffer buffer by the given factor, and crops at the center to the * given dimensions. */ - void ScaleAndCrop( float scaleFactor, ImageDimensions cropDimensions ); + void ScaleAndCrop(float scaleFactor, ImageDimensions cropDimensions); /** * Creates a new buffer which is a crop of the passed in buffer, @@ -269,7 +263,7 @@ private: * @param[in] cropDimensions The dimensions of the crop * @return the new pixel buffer */ - static PixelBufferPtr NewCrop( const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions ); + static PixelBufferPtr NewCrop(const PixelBuffer& inBuffer, uint16_t x, uint16_t y, ImageDimensions cropDimensions); /** * Creates a new buffer which is a resized version of the passed in buffer. @@ -278,17 +272,16 @@ private: * @param[in] outDimensions The new dimensions * @return a new buffer of the given size. */ - static PixelBufferPtr NewResize( const PixelBuffer& inBuffer, ImageDimensions outDimensions ); + static PixelBufferPtr NewResize(const PixelBuffer& inBuffer, ImageDimensions outDimensions); private: - - std::unique_ptr mMetadata; ///< Metadata fields - unsigned char* mBuffer; ///< The raw pixel data - unsigned int mBufferSize; ///< Buffer sized in bytes - unsigned int mWidth; ///< Buffer width in pixels - unsigned int mHeight; ///< Buffer height in pixels - Pixel::Format mPixelFormat; ///< Pixel format - bool mPreMultiplied; ///< PreMultiplied + std::unique_ptr mMetadata; ///< Metadata fields + unsigned char* mBuffer; ///< The raw pixel data + unsigned int mBufferSize; ///< Buffer sized in bytes + unsigned int mWidth; ///< Buffer width in pixels + unsigned int mHeight; ///< Buffer height in pixels + Pixel::Format mPixelFormat; ///< Pixel format + bool mPreMultiplied; ///< PreMultiplied }; } // namespace Adaptor @@ -298,22 +291,22 @@ private: /** * Helper methods for public API */ -inline Internal::Adaptor::PixelBuffer& GetImplementation( Devel::PixelBuffer& handle ) +inline Internal::Adaptor::PixelBuffer& GetImplementation(Devel::PixelBuffer& handle) { - DALI_ASSERT_ALWAYS( handle && "handle is empty" ); + DALI_ASSERT_ALWAYS(handle && "handle is empty"); BaseObject& object = handle.GetBaseObject(); - return static_cast( object ); + return static_cast(object); } -inline const Internal::Adaptor::PixelBuffer& GetImplementation( const Devel::PixelBuffer& handle ) +inline const Internal::Adaptor::PixelBuffer& GetImplementation(const Devel::PixelBuffer& handle) { - DALI_ASSERT_ALWAYS( handle && "handle is empty" ); + DALI_ASSERT_ALWAYS(handle && "handle is empty"); const BaseObject& object = handle.GetBaseObject(); - return static_cast( object ); + return static_cast(object); } } // namespace Dali diff --git a/dali/internal/imaging/common/pixel-manipulation.cpp b/dali/internal/imaging/common/pixel-manipulation.cpp index fff8604..9c3f526 100644 --- a/dali/internal/imaging/common/pixel-manipulation.cpp +++ b/dali/internal/imaging/common/pixel-manipulation.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali { @@ -27,10 +27,8 @@ namespace Internal { namespace Adaptor { - namespace { - constexpr Channel ALPHA_CHANNEL_ONLY[] = {ALPHA}; constexpr Channel LUMINANCE_CHANNEL_ONLY[] = {LUMINANCE}; constexpr Channel LUMINANCE_ALPHA_CHANNELS[] = {LUMINANCE, ALPHA}; @@ -51,11 +49,11 @@ constexpr Channel BGRA_CHANNELS[] = {BLUE, GREEN, RED, ALPHA}; template unsigned int ReadChannel(unsigned char* pixelData, Channel channel, const Channel (&channels)[NumberOfChannels]) { - auto num = 0u; + auto num = 0u; auto retVal = 0u; for(auto current : channels) { - if( channel == current ) + if(channel == current) { retVal = static_cast(*(pixelData + num)); break; @@ -78,11 +76,11 @@ template void WriteChannel(unsigned char* pixelData, Channel channel, unsigned int channelValue, const Channel (&channels)[NumberOfChannels]) { auto num = 0u; - for( auto current : channels ) + for(auto current : channels) { - if( channel == current ) + if(channel == current) { - *(pixelData + num) = static_cast( channelValue & 0xFF ); + *(pixelData + num) = static_cast(channelValue & 0xFF); break; } ++num; @@ -101,18 +99,18 @@ void WriteChannel(unsigned char* pixelData, Channel channel, unsigned int channe */ unsigned int ReadChannel565(unsigned char* pixelData, Channel channel, Channel one, Channel two, Channel three) { - if( channel == one ) + if(channel == one) { return (static_cast(*pixelData) & 0xF8) >> 3; } - else if( channel == two ) + else if(channel == two) { return ((static_cast(*pixelData) & 0x07) << 3) | - ((static_cast(*(pixelData+1)) & 0xE0) >> 5); + ((static_cast(*(pixelData + 1)) & 0xE0) >> 5); } - else if( channel == three ) + else if(channel == three) { - return static_cast(*(pixelData+1)) & 0x1F; + return static_cast(*(pixelData + 1)) & 0x1F; } return 0u; } @@ -129,23 +127,23 @@ unsigned int ReadChannel565(unsigned char* pixelData, Channel channel, Channel o */ void WriteChannel565(unsigned char* pixelData, Channel channel, unsigned int channelValue, Channel one, Channel two, Channel three) { - if( channel == one ) + if(channel == one) { - *pixelData &= static_cast( ~0xF8 ); - *pixelData |= static_cast( (channelValue << 3) & 0xF8 ); + *pixelData &= static_cast(~0xF8); + *pixelData |= static_cast((channelValue << 3) & 0xF8); } - else if( channel == two ) + else if(channel == two) { - *pixelData &= static_cast( ~0x07 ); - *pixelData |= static_cast( (channelValue >> 3) & 0x07 ); + *pixelData &= static_cast(~0x07); + *pixelData |= static_cast((channelValue >> 3) & 0x07); - *(pixelData+1) &= static_cast( ~0xE0 ); - *(pixelData+1) |= static_cast( (channelValue << 5) & 0xE0 ); + *(pixelData + 1) &= static_cast(~0xE0); + *(pixelData + 1) |= static_cast((channelValue << 5) & 0xE0); } - else if( channel == three ) + else if(channel == three) { - *(pixelData+1) &= static_cast( ~0x1F ); - *(pixelData+1) |= static_cast( channelValue & 0x1F ); + *(pixelData + 1) &= static_cast(~0x1F); + *(pixelData + 1) |= static_cast(channelValue & 0x1F); } } @@ -162,21 +160,21 @@ void WriteChannel565(unsigned char* pixelData, Channel channel, unsigned int cha */ unsigned int ReadChannel4444(unsigned char* pixelData, Channel channel, Channel one, Channel two, Channel three, Channel four) { - if( channel == one ) + if(channel == one) { return (static_cast(*pixelData) & 0xF0) >> 4; } - else if( channel == two ) + else if(channel == two) { return (static_cast(*pixelData) & 0x0F); } - else if( channel == three ) + else if(channel == three) { - return (static_cast(*(pixelData+1)) & 0xF0) >> 4; + return (static_cast(*(pixelData + 1)) & 0xF0) >> 4; } - else if( channel == four ) + else if(channel == four) { - return (static_cast(*(pixelData+1)) & 0x0F); + return (static_cast(*(pixelData + 1)) & 0x0F); } return 0u; } @@ -194,25 +192,25 @@ unsigned int ReadChannel4444(unsigned char* pixelData, Channel channel, Channel */ void WriteChannel4444(unsigned char* pixelData, Channel channel, unsigned int channelValue, Channel one, Channel two, Channel three, Channel four) { - if( channel == one ) + if(channel == one) { - *pixelData &= static_cast( ~0xF0 ); - *pixelData |= static_cast( (channelValue << 4) & 0xF0 ); + *pixelData &= static_cast(~0xF0); + *pixelData |= static_cast((channelValue << 4) & 0xF0); } - else if( channel == two ) + else if(channel == two) { - *pixelData &= static_cast( ~0x0F ); - *pixelData |= static_cast( channelValue & 0x0F ); + *pixelData &= static_cast(~0x0F); + *pixelData |= static_cast(channelValue & 0x0F); } - else if( channel == three ) + else if(channel == three) { - *(pixelData+1) &= static_cast( ~0xF0 ); - *(pixelData+1) |= static_cast( (channelValue << 4) & 0xF0 ); + *(pixelData + 1) &= static_cast(~0xF0); + *(pixelData + 1) |= static_cast((channelValue << 4) & 0xF0); } - else if( channel == four ) + else if(channel == four) { - *(pixelData+1) &= static_cast( ~0x0F ); - *(pixelData+1) |= static_cast( channelValue & 0x0F ); + *(pixelData + 1) &= static_cast(~0x0F); + *(pixelData + 1) |= static_cast(channelValue & 0x0F); } } @@ -229,22 +227,22 @@ void WriteChannel4444(unsigned char* pixelData, Channel channel, unsigned int ch */ unsigned int ReadChannel5551(unsigned char* pixelData, Channel channel, Channel one, Channel two, Channel three, Channel four) { - if( channel == one ) + if(channel == one) { return (static_cast(*pixelData) & 0xF8) >> 3; } - else if( channel == two ) + else if(channel == two) { return ((static_cast(*pixelData) & 0x07) << 2) | - ((static_cast(*(pixelData+1)) & 0xC0) >> 6); + ((static_cast(*(pixelData + 1)) & 0xC0) >> 6); } - else if( channel == three ) + else if(channel == three) { - return (static_cast(*(pixelData+1)) & 0x3E) >> 1; + return (static_cast(*(pixelData + 1)) & 0x3E) >> 1; } - else if( channel == four ) + else if(channel == four) { - return static_cast(*(pixelData+1)) & 0x01; + return static_cast(*(pixelData + 1)) & 0x01; } return 0u; } @@ -264,28 +262,28 @@ void WriteChannel5551(unsigned char* pixelData, Channel channel, unsigned int ch { // 11111222 22333334 // F8 7 C0 3E 1 - if( channel == one ) + if(channel == one) { - *pixelData &= static_cast( ~0xF8 ); - *pixelData |= static_cast( (channelValue << 3) & 0xF8 ); + *pixelData &= static_cast(~0xF8); + *pixelData |= static_cast((channelValue << 3) & 0xF8); } - else if( channel == two ) + else if(channel == two) { - *pixelData &= static_cast( ~0x07 ); - *pixelData |= static_cast( (channelValue >> 2) & 0x07 ); + *pixelData &= static_cast(~0x07); + *pixelData |= static_cast((channelValue >> 2) & 0x07); - *(pixelData+1) &= static_cast( ~0xC0 ); - *(pixelData+1) |= static_cast( (channelValue << 6) & 0xC0 ); + *(pixelData + 1) &= static_cast(~0xC0); + *(pixelData + 1) |= static_cast((channelValue << 6) & 0xC0); } - else if( channel == three ) + else if(channel == three) { - *(pixelData+1) &= static_cast( ~0x3E ); - *(pixelData+1) |= static_cast( (channelValue << 1) & 0x3E ); + *(pixelData + 1) &= static_cast(~0x3E); + *(pixelData + 1) |= static_cast((channelValue << 1) & 0x3E); } - else if( channel == four ) + else if(channel == four) { - *(pixelData+1) &= static_cast( ~0x01 ); - *(pixelData+1) |= static_cast( channelValue & 0x01 ); + *(pixelData + 1) &= static_cast(~0x01); + *(pixelData + 1) |= static_cast(channelValue & 0x01); } } @@ -295,7 +293,7 @@ struct Location { unsigned int bitShift; unsigned int bitMask; - bool available; + bool available; }; struct Locations @@ -307,10 +305,9 @@ struct Locations Location blue; }; - -bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ) +bool HasChannel(Dali::Pixel::Format pixelFormat, Channel channel) { - switch (pixelFormat) + switch(pixelFormat) { case Dali::Pixel::A8: { @@ -322,7 +319,7 @@ bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ) } case Dali::Pixel::LA88: { - return ( channel == LUMINANCE || channel == ALPHA ); + return (channel == LUMINANCE || channel == ALPHA); } case Dali::Pixel::RGB565: case Dali::Pixel::BGR565: @@ -332,7 +329,7 @@ bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ) case Dali::Pixel::RGB16F: case Dali::Pixel::RGB32F: { - return ( channel == RED || channel == GREEN || channel == BLUE ); + return (channel == RED || channel == GREEN || channel == BLUE); } case Dali::Pixel::RGBA8888: @@ -342,18 +339,18 @@ bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ) case Dali::Pixel::RGBA5551: case Dali::Pixel::BGRA5551: { - return ( channel == RED || channel == GREEN || channel == BLUE || channel == ALPHA ); + return (channel == RED || channel == GREEN || channel == BLUE || channel == ALPHA); } case Dali::Pixel::DEPTH_UNSIGNED_INT: case Dali::Pixel::DEPTH_FLOAT: { - return ( channel == DEPTH ); + return (channel == DEPTH); } case Dali::Pixel::DEPTH_STENCIL: { - return ( channel == DEPTH || channel == STENCIL ); + return (channel == DEPTH || channel == STENCIL); } case Dali::Pixel::INVALID: @@ -406,11 +403,11 @@ bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ) return false; } -unsigned int ReadChannel( unsigned char* pixelData, - Dali::Pixel::Format pixelFormat, - Channel channel ) +unsigned int ReadChannel(unsigned char* pixelData, + Dali::Pixel::Format pixelFormat, + Channel channel) { - switch (pixelFormat) + switch(pixelFormat) { case Dali::Pixel::A8: { @@ -489,12 +486,12 @@ unsigned int ReadChannel( unsigned char* pixelData, } } -void WriteChannel( unsigned char* pixelData, - Dali::Pixel::Format pixelFormat, - Channel channel, - unsigned int channelValue ) +void WriteChannel(unsigned char* pixelData, + Dali::Pixel::Format pixelFormat, + Channel channel, + unsigned int channelValue) { - switch (pixelFormat) + switch(pixelFormat) { case Dali::Pixel::A8: { @@ -585,63 +582,61 @@ void WriteChannel( unsigned char* pixelData, } void ConvertColorChannelsToRGBA8888( - unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat, - unsigned char* destPixel, int destOffset ) + unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat, unsigned char* destPixel, int destOffset) { - int red = ReadChannel(srcPixel+srcOffset, srcFormat, RED ); - int green = ReadChannel(srcPixel+srcOffset, srcFormat, GREEN ); - int blue = ReadChannel(srcPixel+srcOffset, srcFormat, BLUE ); - switch( srcFormat ) + int red = ReadChannel(srcPixel + srcOffset, srcFormat, RED); + int green = ReadChannel(srcPixel + srcOffset, srcFormat, GREEN); + int blue = ReadChannel(srcPixel + srcOffset, srcFormat, BLUE); + switch(srcFormat) { case Dali::Pixel::RGB565: case Dali::Pixel::BGR565: { - red = (red<<3) | (red & 0x07); + red = (red << 3) | (red & 0x07); green = (green << 2) | (green & 0x03); - blue = (blue<<3) | (blue & 0x07); + blue = (blue << 3) | (blue & 0x07); break; } case Dali::Pixel::RGBA4444: case Dali::Pixel::BGRA4444: { - red = (red<<4) | (red&0x0F); - green = (green<<4) | (green&0x0F); - blue = (blue<<4) | (blue&0x0F); + red = (red << 4) | (red & 0x0F); + green = (green << 4) | (green & 0x0F); + blue = (blue << 4) | (blue & 0x0F); break; } case Dali::Pixel::RGBA5551: case Dali::Pixel::BGRA5551: { - red = (red<<3) | (red&0x07); - green = (green<<3) | (green&0x07); - blue = (blue<<3) | (blue&0x07); + red = (red << 3) | (red & 0x07); + green = (green << 3) | (green & 0x07); + blue = (blue << 3) | (blue & 0x07); break; } default: break; } - WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, RED, red); - WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, GREEN, green); - WriteChannel(destPixel+destOffset, Dali::Pixel::RGBA8888, BLUE, blue); + WriteChannel(destPixel + destOffset, Dali::Pixel::RGBA8888, RED, red); + WriteChannel(destPixel + destOffset, Dali::Pixel::RGBA8888, GREEN, green); + WriteChannel(destPixel + destOffset, Dali::Pixel::RGBA8888, BLUE, blue); } - -int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat ) +int ConvertAlphaChannelToA8(unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat) { - int alpha = ReadChannel(srcPixel+srcOffset, srcFormat, ALPHA ); + int alpha = ReadChannel(srcPixel + srcOffset, srcFormat, ALPHA); int destAlpha = alpha; - switch( srcFormat ) + switch(srcFormat) { case Pixel::RGBA5551: case Pixel::BGRA5551: { - destAlpha = (alpha==0)?0:255; + destAlpha = (alpha == 0) ? 0 : 255; break; } case Pixel::RGBA4444: case Pixel::BGRA4444: { - destAlpha = (alpha<<4) | (alpha&0x0F); + destAlpha = (alpha << 4) | (alpha & 0x0F); break; } default: @@ -650,6 +645,6 @@ int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel return destAlpha; } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/imaging/common/pixel-manipulation.h b/dali/internal/imaging/common/pixel-manipulation.h index 99c23e9..24b8aae 100644 --- a/dali/internal/imaging/common/pixel-manipulation.h +++ b/dali/internal/imaging/common/pixel-manipulation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_PIXEL_MANIPULATION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - enum Channel { LUMINANCE, @@ -46,8 +43,7 @@ enum Channel * @param[in] channel The channel to test for * @return true if the channel exists */ -bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ); - +bool HasChannel(Dali::Pixel::Format pixelFormat, Channel channel); /** * Read a colour channel from the pixel with the given pixel format. @@ -57,9 +53,9 @@ bool HasChannel( Dali::Pixel::Format pixelFormat, Channel channel ); * @param[in] channel The channel to read * @return the channel value */ -unsigned int ReadChannel( unsigned char* pixelData, - Dali::Pixel::Format pixelFormat, - Channel channel ); +unsigned int ReadChannel(unsigned char* pixelData, + Dali::Pixel::Format pixelFormat, + Channel channel); /** * Write a colour channel to the pixel with the given pixel format. @@ -68,10 +64,10 @@ unsigned int ReadChannel( unsigned char* pixelData, * @param[in] channel The channel to write * @param[in] channelValue the value to write to the channel */ -void WriteChannel( unsigned char* pixelData, - Dali::Pixel::Format pixelFormat, - Channel channel, - unsigned int channelValue ); +void WriteChannel(unsigned char* pixelData, + Dali::Pixel::Format pixelFormat, + Channel channel, + unsigned int channelValue); /** * Convert the colors in the source pixel from their natural format to RGBA8888. @@ -82,8 +78,7 @@ void WriteChannel( unsigned char* pixelData, * @param[in] destOffset The offset of the pixel to write */ void ConvertColorChannelsToRGBA8888( - unsigned char* srcBuffer, int srcOffset, Dali::Pixel::Format srcFormat, - unsigned char* destBuffer, int destOffset ); + unsigned char* srcBuffer, int srcOffset, Dali::Pixel::Format srcFormat, unsigned char* destBuffer, int destOffset); /** * Convert the alpha in the source pixel to A8. @@ -92,12 +87,10 @@ void ConvertColorChannelsToRGBA8888( * @param[in] srcFormat The pixel format of the source pixel * @return the alpha value in the range 0-255 */ -int ConvertAlphaChannelToA8( unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat ); - - -} // Adaptor -} // Internal -} // Dali +int ConvertAlphaChannelToA8(unsigned char* srcPixel, int srcOffset, Dali::Pixel::Format srcFormat); +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_PIXEL_MANIPULATION_H diff --git a/dali/internal/imaging/common/webp-loading.cpp b/dali/internal/imaging/common/webp-loading.cpp index cc4246a..74a770e 100644 --- a/dali/internal/imaging/common/webp-loading.cpp +++ b/dali/internal/imaging/common/webp-loading.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,79 +31,75 @@ #include #include -#include -#include +#include +#include #include +#include +#include #include #include -#include -#include typedef unsigned char WebPByteType; namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter *gWebPLoadingLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_GIF_LOADING" ); +Debug::Filter* gWebPLoadingLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_GIF_LOADING"); #endif -constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024; +constexpr size_t MAXIMUM_DOWNLOAD_IMAGE_SIZE = 50 * 1024 * 1024; -} +} // namespace struct WebPLoading::Impl { public: - Impl( const std::string& url, bool isLocalResource ) - : mUrl( url ) + Impl(const std::string& url, bool isLocalResource) + : mUrl(url) { #ifdef DALI_WEBP_ENABLED - if( ReadWebPInformation( isLocalResource ) ) + if(ReadWebPInformation(isLocalResource)) { WebPAnimDecoderOptions webPAnimDecoderOptions; - WebPAnimDecoderOptionsInit( &webPAnimDecoderOptions ); + WebPAnimDecoderOptionsInit(&webPAnimDecoderOptions); webPAnimDecoderOptions.color_mode = MODE_RGBA; - mWebPAnimDecoder = WebPAnimDecoderNew( &mWebPData, &webPAnimDecoderOptions ); - WebPAnimDecoderGetInfo( mWebPAnimDecoder, &mWebPAnimInfo ); - mTimeStamp.assign( mWebPAnimInfo.frame_count, 0 ); + mWebPAnimDecoder = WebPAnimDecoderNew(&mWebPData, &webPAnimDecoderOptions); + WebPAnimDecoderGetInfo(mWebPAnimDecoder, &mWebPAnimInfo); + mTimeStamp.assign(mWebPAnimInfo.frame_count, 0); } #endif } - bool ReadWebPInformation( bool isLocalResource ) + bool ReadWebPInformation(bool isLocalResource) { #ifdef DALI_WEBP_ENABLED - WebPDataInit( &mWebPData ); - if( isLocalResource ) + WebPDataInit(&mWebPData); + if(isLocalResource) { - Internal::Platform::FileReader fileReader( mUrl ); - FILE *fp = fileReader.GetFile(); - if( fp == NULL ) + Internal::Platform::FileReader fileReader(mUrl); + FILE* fp = fileReader.GetFile(); + if(fp == NULL) { return false; } - if( fseek( fp, 0, SEEK_END ) <= -1 ) + if(fseek(fp, 0, SEEK_END) <= -1) { return false; } - mWebPData.size = ftell( fp ); - if( ( ! fseek( fp, 0, SEEK_SET ) ) ) + mWebPData.size = ftell(fp); + if((!fseek(fp, 0, SEEK_SET))) { - unsigned char *WebPDataBuffer; - WebPDataBuffer = reinterpret_cast( malloc(sizeof( WebPByteType ) * mWebPData.size ) ); - mWebPData.size = fread( WebPDataBuffer, sizeof( WebPByteType ), mWebPData.size, fp ); + unsigned char* WebPDataBuffer; + WebPDataBuffer = reinterpret_cast(malloc(sizeof(WebPByteType) * mWebPData.size)); + mWebPData.size = fread(WebPDataBuffer, sizeof(WebPByteType), mWebPData.size, fp); mWebPData.bytes = WebPDataBuffer; } else @@ -114,36 +110,36 @@ public: else { // remote file - bool succeeded; + bool succeeded; Dali::Vector dataBuffer; - size_t dataSize; + size_t dataSize; - succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory( mUrl, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE ); - if( succeeded ) + succeeded = TizenPlatform::Network::DownloadRemoteFileIntoMemory(mUrl, dataBuffer, dataSize, MAXIMUM_DOWNLOAD_IMAGE_SIZE); + if(succeeded) { size_t blobSize = dataBuffer.Size(); - if( blobSize > 0U ) + if(blobSize > 0U) { // Open a file handle on the memory buffer: - Dali::Internal::Platform::FileReader fileReader( dataBuffer, blobSize ); - FILE * const fp = fileReader.GetFile(); - if ( NULL != fp ) + Dali::Internal::Platform::FileReader fileReader(dataBuffer, blobSize); + FILE* const fp = fileReader.GetFile(); + if(NULL != fp) { - if( ( ! fseek( fp, 0, SEEK_SET ) ) ) + if((!fseek(fp, 0, SEEK_SET))) { - unsigned char *WebPDataBuffer; - WebPDataBuffer = reinterpret_cast( malloc(sizeof( WebPByteType ) * blobSize ) ); - mWebPData.size = fread( WebPDataBuffer, sizeof( WebPByteType ), mWebPData.size, fp ); + unsigned char* WebPDataBuffer; + WebPDataBuffer = reinterpret_cast(malloc(sizeof(WebPByteType) * blobSize)); + mWebPData.size = fread(WebPDataBuffer, sizeof(WebPByteType), mWebPData.size, fp); mWebPData.bytes = WebPDataBuffer; } else { - DALI_LOG_ERROR( "Error seeking within file\n" ); + DALI_LOG_ERROR("Error seeking within file\n"); } } else { - DALI_LOG_ERROR( "Error reading file\n" ); + DALI_LOG_ERROR("Error reading file\n"); } } } @@ -156,48 +152,48 @@ public: // Moveable but not copyable - Impl( const Impl& ) = delete; - Impl& operator=( const Impl& ) = delete; - Impl( Impl&& ) = default; - Impl& operator=( Impl&& ) = default; + Impl(const Impl&) = delete; + Impl& operator=(const Impl&) = delete; + Impl(Impl&&) = default; + Impl& operator=(Impl&&) = default; ~Impl() { #ifdef DALI_WEBP_ENABLED - if( &mWebPData != NULL ) + if(&mWebPData != NULL) { - free( (void*)mWebPData.bytes ); + free((void*)mWebPData.bytes); mWebPData.bytes = nullptr; - WebPDataInit( &mWebPData ); + WebPDataInit(&mWebPData); } - if( mWebPAnimDecoder ) + if(mWebPAnimDecoder) { WebPAnimDecoderDelete(mWebPAnimDecoder); } #endif } - std::string mUrl; + std::string mUrl; std::vector mTimeStamp; - uint32_t mLoadingFrame{0}; + uint32_t mLoadingFrame{0}; #ifdef DALI_WEBP_ENABLED - WebPData mWebPData{0}; + WebPData mWebPData{0}; WebPAnimDecoder* mWebPAnimDecoder{nullptr}; - WebPAnimInfo mWebPAnimInfo{0}; + WebPAnimInfo mWebPAnimInfo{0}; #endif }; -AnimatedImageLoadingPtr WebPLoading::New( const std::string &url, bool isLocalResource ) +AnimatedImageLoadingPtr WebPLoading::New(const std::string& url, bool isLocalResource) { #ifndef DALI_WEBP_ENABLED - DALI_LOG_ERROR( "The system does not support Animated WebP format.\n" ); + DALI_LOG_ERROR("The system does not support Animated WebP format.\n"); #endif - return AnimatedImageLoadingPtr( new WebPLoading( url, isLocalResource ) ); + return AnimatedImageLoadingPtr(new WebPLoading(url, isLocalResource)); } -WebPLoading::WebPLoading( const std::string &url, bool isLocalResource ) -: mImpl( new WebPLoading::Impl( url, isLocalResource ) ) +WebPLoading::WebPLoading(const std::string& url, bool isLocalResource) +: mImpl(new WebPLoading::Impl(url, isLocalResource)) { } @@ -206,53 +202,51 @@ WebPLoading::~WebPLoading() delete mImpl; } -bool WebPLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector &pixelData ) +bool WebPLoading::LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector& pixelData) { #ifdef DALI_WEBP_ENABLED - if( frameStartIndex >= mImpl->mWebPAnimInfo.frame_count ) + if(frameStartIndex >= mImpl->mWebPAnimInfo.frame_count) { return false; } - DALI_LOG_INFO( gWebPLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count ); + DALI_LOG_INFO(gWebPLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameStartIndex:%d, count:%d )\n", frameStartIndex, count); - if( mImpl->mLoadingFrame > frameStartIndex ) + if(mImpl->mLoadingFrame > frameStartIndex) { mImpl->mLoadingFrame = 0; - WebPAnimDecoderReset( mImpl->mWebPAnimDecoder ); + WebPAnimDecoderReset(mImpl->mWebPAnimDecoder); } - for( ; mImpl->mLoadingFrame < frameStartIndex ; ++mImpl->mLoadingFrame ) + for(; mImpl->mLoadingFrame < frameStartIndex; ++mImpl->mLoadingFrame) { uint8_t* frameBuffer; - int timestamp; - WebPAnimDecoderGetNext( mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp ); + int timestamp; + WebPAnimDecoderGetNext(mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp); mImpl->mTimeStamp[mImpl->mLoadingFrame] = timestamp; } - for( int i = 0; i < count; ++i ) + for(int i = 0; i < count; ++i) { - const int bufferSize = mImpl->mWebPAnimInfo.canvas_width * mImpl->mWebPAnimInfo.canvas_height * sizeof( uint32_t ); - uint8_t* frameBuffer; - int timestamp; - WebPAnimDecoderGetNext( mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp ); + const int bufferSize = mImpl->mWebPAnimInfo.canvas_width * mImpl->mWebPAnimInfo.canvas_height * sizeof(uint32_t); + uint8_t* frameBuffer; + int timestamp; + WebPAnimDecoderGetNext(mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp); - auto pixelBuffer = new uint8_t[ bufferSize ]; - memcpy( pixelBuffer, frameBuffer, bufferSize ); + auto pixelBuffer = new uint8_t[bufferSize]; + memcpy(pixelBuffer, frameBuffer, bufferSize); mImpl->mTimeStamp[mImpl->mLoadingFrame] = timestamp; - if( pixelBuffer ) + if(pixelBuffer) { - pixelData.push_back( Dali::PixelData::New( pixelBuffer, bufferSize, - mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height, - Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY) ); + pixelData.push_back(Dali::PixelData::New(pixelBuffer, bufferSize, mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height, Dali::Pixel::RGBA8888, Dali::PixelData::DELETE_ARRAY)); } mImpl->mLoadingFrame++; - if( mImpl->mLoadingFrame >= mImpl->mWebPAnimInfo.frame_count ) + if(mImpl->mLoadingFrame >= mImpl->mWebPAnimInfo.frame_count) { mImpl->mLoadingFrame = 0; - WebPAnimDecoderReset( mImpl->mWebPAnimDecoder ); + WebPAnimDecoderReset(mImpl->mWebPAnimDecoder); } } @@ -262,45 +256,45 @@ bool WebPLoading::LoadNextNFrames( uint32_t frameStartIndex, int count, std::vec #endif } -Dali::Devel::PixelBuffer WebPLoading::LoadFrame( uint32_t frameIndex ) +Dali::Devel::PixelBuffer WebPLoading::LoadFrame(uint32_t frameIndex) { Dali::Devel::PixelBuffer pixelBuffer; #ifdef DALI_WEBP_ENABLED - if( frameIndex >= mImpl->mWebPAnimInfo.frame_count ) + if(frameIndex >= mImpl->mWebPAnimInfo.frame_count) { return pixelBuffer; } - DALI_LOG_INFO( gWebPLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameIndex:%d )\n", frameIndex ); + DALI_LOG_INFO(gWebPLoadingLogFilter, Debug::Concise, "LoadNextNFrames( frameIndex:%d )\n", frameIndex); - if( mImpl->mLoadingFrame > frameIndex ) + if(mImpl->mLoadingFrame > frameIndex) { mImpl->mLoadingFrame = 0; - WebPAnimDecoderReset( mImpl->mWebPAnimDecoder ); + WebPAnimDecoderReset(mImpl->mWebPAnimDecoder); } - for( ; mImpl->mLoadingFrame < frameIndex ; ++mImpl->mLoadingFrame ) + for(; mImpl->mLoadingFrame < frameIndex; ++mImpl->mLoadingFrame) { uint8_t* frameBuffer; - int timestamp; - WebPAnimDecoderGetNext( mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp ); + int timestamp; + WebPAnimDecoderGetNext(mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp); mImpl->mTimeStamp[mImpl->mLoadingFrame] = timestamp; } - const int bufferSize = mImpl->mWebPAnimInfo.canvas_width * mImpl->mWebPAnimInfo.canvas_height * sizeof( uint32_t ); - uint8_t* frameBuffer; - int timestamp; - WebPAnimDecoderGetNext( mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp ); + const int bufferSize = mImpl->mWebPAnimInfo.canvas_width * mImpl->mWebPAnimInfo.canvas_height * sizeof(uint32_t); + uint8_t* frameBuffer; + int timestamp; + WebPAnimDecoderGetNext(mImpl->mWebPAnimDecoder, &frameBuffer, ×tamp); - pixelBuffer = Dali::Devel::PixelBuffer::New( mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height, Dali::Pixel::RGBA8888 ); - memcpy( pixelBuffer.GetBuffer(), frameBuffer, bufferSize ); + pixelBuffer = Dali::Devel::PixelBuffer::New(mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height, Dali::Pixel::RGBA8888); + memcpy(pixelBuffer.GetBuffer(), frameBuffer, bufferSize); mImpl->mTimeStamp[mImpl->mLoadingFrame] = timestamp; mImpl->mLoadingFrame++; - if( mImpl->mLoadingFrame >= mImpl->mWebPAnimInfo.frame_count ) + if(mImpl->mLoadingFrame >= mImpl->mWebPAnimInfo.frame_count) { mImpl->mLoadingFrame = 0; - WebPAnimDecoderReset( mImpl->mWebPAnimDecoder ); + WebPAnimDecoderReset(mImpl->mWebPAnimDecoder); } #endif return pixelBuffer; @@ -309,7 +303,7 @@ Dali::Devel::PixelBuffer WebPLoading::LoadFrame( uint32_t frameIndex ) ImageDimensions WebPLoading::GetImageSize() const { #ifdef DALI_WEBP_ENABLED - return ImageDimensions( mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height ); + return ImageDimensions(mImpl->mWebPAnimInfo.canvas_width, mImpl->mWebPAnimInfo.canvas_height); #else return ImageDimensions(); #endif @@ -324,15 +318,15 @@ uint32_t WebPLoading::GetImageCount() const #endif } -uint32_t WebPLoading::GetFrameInterval( uint32_t frameIndex ) const +uint32_t WebPLoading::GetFrameInterval(uint32_t frameIndex) const { - if( frameIndex >= GetImageCount() ) + if(frameIndex >= GetImageCount()) { return 0u; } else { - if( frameIndex > 0 ) + if(frameIndex > 0) { return mImpl->mTimeStamp[frameIndex] - mImpl->mTimeStamp[frameIndex - 1]; } diff --git a/dali/internal/imaging/common/webp-loading.h b/dali/internal/imaging/common/webp-loading.h index 430cf53..5806353 100644 --- a/dali/internal/imaging/common/webp-loading.h +++ b/dali/internal/imaging/common/webp-loading.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WEBP_LOADING_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,16 @@ * */ // EXTERNAL INCLUDES -#include -#include -#include #include #include +#include #include +#include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -36,10 +36,8 @@ typedef Dali::Uint16Pair ImageDimensions; namespace Internal { - namespace Adaptor { - /** * Class to manage loading frames of an animated webp in small chunks. Lazy initializes only when * data is actually needed. @@ -47,17 +45,16 @@ namespace Adaptor * is released. (This is to speed up frame loads, which would otherwise have to re-acquire the * data from disk) */ -class WebPLoading: public Internal::Adaptor::AnimatedImageLoading +class WebPLoading : public Internal::Adaptor::AnimatedImageLoading { public: - /** * Create a WebPLoading with the given url and resourceType. * @param[in] url The url of the webp image to load * @param[in] isLocalResource The true or false whether this is a local resource. * @return A newly created WebPLoading. */ - static AnimatedImageLoadingPtr New( const std::string& url, bool isLocalResource ); + static AnimatedImageLoadingPtr New(const std::string& url, bool isLocalResource); /** * @brief Constructor @@ -66,8 +63,7 @@ public: * @param[in] url The url of the webp image to load * @param[in] isLocalResource The true or false whether this is a local resource. */ - WebPLoading( const std::string& url, bool isLocalResource ); - + WebPLoading(const std::string& url, bool isLocalResource); /** * @brief Destructor @@ -84,9 +80,9 @@ public: * @param[out] pixelData The vector in which to return the frame data * @return True if the frame data was successfully loaded */ - bool LoadNextNFrames( uint32_t frameStartIndex, int count, std::vector& pixelData ) override; + bool LoadNextNFrames(uint32_t frameStartIndex, int count, std::vector& pixelData) override; - /** + /** * @brief Load the next Frame of the animated image. * * @note This function will load the entire animated image into memory if not already loaded. @@ -94,7 +90,7 @@ public: * @return Dali::Devel::PixelBuffer The loaded PixelBuffer. If loading is fail, return empty handle. */ - Dali::Devel::PixelBuffer LoadFrame( uint32_t frameIndex ) override; + Dali::Devel::PixelBuffer LoadFrame(uint32_t frameIndex) override; /** * @brief Get the size of a webp image. @@ -115,7 +111,7 @@ public: * * @return The time interval of the frame(microsecond). */ - uint32_t GetFrameInterval( uint32_t frameIndex ) const override; + uint32_t GetFrameInterval(uint32_t frameIndex) const override; std::string GetUrl() const override; diff --git a/dali/internal/imaging/macos/native-image-source-factory-mac.cpp b/dali/internal/imaging/macos/native-image-source-factory-mac.cpp index d905355..32022f2 100644 --- a/dali/internal/imaging/macos/native-image-source-factory-mac.cpp +++ b/dali/internal/imaging/macos/native-image-source-factory-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,44 +19,40 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali::Internal::Adaptor { - -std::unique_ptr< NativeImageSource > +std::unique_ptr NativeImageSourceFactoryCocoa::CreateNativeImageSource( - unsigned int width, - unsigned int height, + unsigned int width, + unsigned int height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource -) + Any nativeImageSource) { - return std::unique_ptr< NativeImageSource >( NativeImageSourceCocoa::New( + return std::unique_ptr(NativeImageSourceCocoa::New( width, height, depth, - nativeImageSource - )); + nativeImageSource)); } -std::unique_ptr< NativeImageSourceQueue > +std::unique_ptr NativeImageSourceFactoryCocoa::CreateNativeImageSourceQueue( - unsigned int width, - unsigned int height, + unsigned int width, + unsigned int height, Dali::NativeImageSourceQueue::ColorDepth depth, - Any nativeImageSourceQueue -) + Any nativeImageSourceQueue) { - return std::unique_ptr< NativeImageSourceQueue >( nullptr ); + return std::unique_ptr(nullptr); } // this should be created from somewhere -std::unique_ptr< NativeImageSourceFactory > GetNativeImageSourceFactory() +std::unique_ptr GetNativeImageSourceFactory() { // returns native image source factory - return std::unique_ptr< NativeImageSourceFactoryCocoa >( new NativeImageSourceFactoryCocoa() ); + return std::unique_ptr(new NativeImageSourceFactoryCocoa()); } -} // Dali::Internal::Adaptor +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/imaging/macos/native-image-source-factory-mac.h b/dali/internal/imaging/macos/native-image-source-factory-mac.h index 65f6f8c..0e2704e 100644 --- a/dali/internal/imaging/macos/native-image-source-factory-mac.h +++ b/dali/internal/imaging/macos/native-image-source-factory-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,23 +22,20 @@ namespace Dali::Internal::Adaptor { - class NativeImageSourceFactoryCocoa : public NativeImageSourceFactory { public: - std::unique_ptr< NativeImageSource > CreateNativeImageSource( - unsigned int width, - unsigned int height, + std::unique_ptr CreateNativeImageSource( + unsigned int width, + unsigned int height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource - ) override; + Any nativeImageSource) override; - std::unique_ptr< NativeImageSourceQueue > CreateNativeImageSourceQueue( - unsigned int width, - unsigned int height, + std::unique_ptr CreateNativeImageSourceQueue( + unsigned int width, + unsigned int height, Dali::NativeImageSourceQueue::ColorDepth depth, - Any nativeImageSourceQueue - ) override; + Any nativeImageSourceQueue) override; }; -} // Dali::Internal::Adaptor +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/imaging/macos/native-image-source-impl-mac.cpp b/dali/internal/imaging/macos/native-image-source-impl-mac.cpp index 385e487..5b80733 100644 --- a/dali/internal/imaging/macos/native-image-source-impl-mac.cpp +++ b/dali/internal/imaging/macos/native-image-source-impl-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,73 +22,70 @@ #include // INTERNAL INCLUDES +#include +#include #include #include -#include -#include namespace Dali::Internal::Adaptor { - using Dali::Integration::PixelBuffer; NativeImageSourceCocoa* NativeImageSourceCocoa::New( - unsigned int width, - unsigned int height, + unsigned int width, + unsigned int height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource -) + Any nativeImageSource) { - return new NativeImageSourceCocoa( width, height, depth, nativeImageSource ); + return new NativeImageSourceCocoa(width, height, depth, nativeImageSource); } NativeImageSourceCocoa::NativeImageSourceCocoa( - unsigned int width, - unsigned int height, + unsigned int width, + unsigned int height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource -) + Any nativeImageSource) : mImage(MakeRef(nullptr)) { - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); - DALI_ASSERT_ALWAYS( nativeImageSource.Empty() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); + DALI_ASSERT_ALWAYS(nativeImageSource.Empty()); - CFStringRef colorSpaceName; + CFStringRef colorSpaceName; CGImageAlphaInfo alphaInfo; - std::size_t bitsPerPixel; + std::size_t bitsPerPixel; - switch (depth) + switch(depth) { case Dali::NativeImageSource::COLOR_DEPTH_8: colorSpaceName = kCGColorSpaceGenericGray; - alphaInfo = kCGImageAlphaNone; - bitsPerPixel = 8; + alphaInfo = kCGImageAlphaNone; + bitsPerPixel = 8; break; case Dali::NativeImageSource::COLOR_DEPTH_16: colorSpaceName = kCGColorSpaceSRGB; - alphaInfo = kCGImageAlphaNone; - bitsPerPixel = 16; + alphaInfo = kCGImageAlphaNone; + bitsPerPixel = 16; break; case Dali::NativeImageSource::COLOR_DEPTH_24: colorSpaceName = kCGColorSpaceSRGB; - alphaInfo = kCGImageAlphaNone; - bitsPerPixel = 24; + alphaInfo = kCGImageAlphaNone; + bitsPerPixel = 24; break; case Dali::NativeImageSource::COLOR_DEPTH_32: default: colorSpaceName = kCGColorSpaceSRGB; - alphaInfo = kCGImageAlphaLast; - bitsPerPixel = 32; + alphaInfo = kCGImageAlphaLast; + bitsPerPixel = 32; break; } // round to next 16 bytes boundary std::size_t bytesPerRow = width & ~0xf; - bytesPerRow = bytesPerRow ? bytesPerRow + 16 : width; + bytesPerRow = bytesPerRow ? bytesPerRow + 16 : width; auto dataProvider = MakeRef(CGDataProviderCreateWithData(nullptr, nullptr, 0, nullptr)); - auto colorSpace = MakeRef(CGColorSpaceCreateWithName(colorSpaceName)); - mImage = MakeRef(CGImageCreate( + auto colorSpace = MakeRef(CGColorSpaceCreateWithName(colorSpaceName)); + mImage = MakeRef(CGImageCreate( width, height, 8, @@ -99,10 +96,9 @@ NativeImageSourceCocoa::NativeImageSourceCocoa( dataProvider.get(), nullptr, true, - kCGRenderingIntentDefault - )); + kCGRenderingIntentDefault)); - if (mImage) + if(mImage) { colorSpace.release(); dataProvider.release(); @@ -122,20 +118,20 @@ Any NativeImageSourceCocoa::GetNativeImageSource() const bool NativeImageSourceCocoa::GetPixels( std::vector& pixbuf, - unsigned& width, unsigned& height, - Pixel::Format& pixelFormat -) const + unsigned& width, + unsigned& height, + Pixel::Format& pixelFormat) const { width = CGImageGetWidth(mImage.get()); height = CGImageGetHeight(mImage.get()); return true; } -void NativeImageSourceCocoa::SetSource( Any source ) +void NativeImageSourceCocoa::SetSource(Any source) { } -bool NativeImageSourceCocoa::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) +bool NativeImageSourceCocoa::IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) { return true; } @@ -191,10 +187,7 @@ unsigned int NativeImageSourceCocoa::GetHeight() const bool NativeImageSourceCocoa::RequiresBlending() const { const auto alphaInfo = CGImageGetAlphaInfo(mImage.get()); - return - alphaInfo != kCGImageAlphaNone - && alphaInfo != kCGImageAlphaNoneSkipFirst - && alphaInfo != kCGImageAlphaNoneSkipLast; + return alphaInfo != kCGImageAlphaNone && alphaInfo != kCGImageAlphaNoneSkipFirst && alphaInfo != kCGImageAlphaNoneSkipLast; } bool NativeImageSourceCocoa::SourceChanged() const @@ -202,12 +195,11 @@ bool NativeImageSourceCocoa::SourceChanged() const return false; } -uint8_t* NativeImageSourceCocoa::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) +uint8_t* NativeImageSourceCocoa::AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) { return nullptr; } - bool NativeImageSourceCocoa::ReleaseBuffer() { return false; diff --git a/dali/internal/imaging/macos/native-image-source-impl-mac.h b/dali/internal/imaging/macos/native-image-source-impl-mac.h index 84ef554..bd0e41b 100644 --- a/dali/internal/imaging/macos/native-image-source-impl-mac.h +++ b/dali/internal/imaging/macos/native-image-source-impl-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,12 @@ // INTERNAL INCLUDES #include +#include #include #include -#include namespace Dali::Internal::Adaptor { - class EglImageExtensions; /** @@ -35,7 +34,6 @@ class EglImageExtensions; class NativeImageSourceCocoa : public Internal::Adaptor::NativeImageSource { public: - /** * Create a new NativeImageSource internally. * Depending on hardware the width and height may have to be a power of two. @@ -46,11 +44,10 @@ public: * @return A smart-pointer to a newly allocated image. */ static NativeImageSourceCocoa* New( - unsigned int width, - unsigned int height, + unsigned int width, + unsigned int height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource - ); + Any nativeImageSource); /** * @copydoc Dali::NativeImageSource::GetNativeImageSource() @@ -61,21 +58,20 @@ public: * @copydoc Dali::NativeImageSource::GetPixels() */ bool GetPixels( - std::vector &pixbuf, - unsigned int &width, - unsigned int &height, - Pixel::Format& pixelFormat - ) const override; + std::vector& pixbuf, + unsigned int& width, + unsigned int& height, + Pixel::Format& pixelFormat) const override; /** * @copydoc Dali::NativeImageSource::SetSource( Any source ) */ - void SetSource( Any source ) override; + void SetSource(Any source) override; /** * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth ) */ - bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override; + bool IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) override; /** * destructor @@ -153,7 +149,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::AcquireBuffer() */ - uint8_t* AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) override; + uint8_t* AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) override; /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::ReleaseBuffer() @@ -161,7 +157,6 @@ public: bool ReleaseBuffer() override; private: - /** * Private constructor; @see NativeImageSource::New() * @param[in] width The width of the image. @@ -170,11 +165,10 @@ private: * @param[in] nativeImageSource contains either: pixmap of type Win32 Pixmap , a WinPixmap or is empty */ NativeImageSourceCocoa( - unsigned int width, - unsigned int height, + unsigned int width, + unsigned int height, Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource - ); + Any nativeImageSource); private: CFRef mImage; diff --git a/dali/internal/imaging/tizen/native-image-source-factory-tizen.cpp b/dali/internal/imaging/tizen/native-image-source-factory-tizen.cpp index 8214508..de89485 100644 --- a/dali/internal/imaging/tizen/native-image-source-factory-tizen.cpp +++ b/dali/internal/imaging/tizen/native-image-source-factory-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,26 +28,23 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< NativeImageSource > NativeImageSourceFactoryTizen::CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +std::unique_ptr NativeImageSourceFactoryTizen::CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - return std::unique_ptr< NativeImageSource >( NativeImageSourceTizen::New( width, height, depth, nativeImageSource ) ); + return std::unique_ptr(NativeImageSourceTizen::New(width, height, depth, nativeImageSource)); } -std::unique_ptr< NativeImageSourceQueue > NativeImageSourceFactoryTizen::CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +std::unique_ptr NativeImageSourceFactoryTizen::CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - return std::unique_ptr< NativeImageSourceQueue >( NativeImageSourceQueueTizen::New( width, height, depth, nativeImageSourceQueue ) ); + return std::unique_ptr(NativeImageSourceQueueTizen::New(width, height, depth, nativeImageSourceQueue)); } // this should be created from somewhere -std::unique_ptr< NativeImageSourceFactory > GetNativeImageSourceFactory() +std::unique_ptr GetNativeImageSourceFactory() { // returns native image source factory - return std::unique_ptr< NativeImageSourceFactoryTizen >( new NativeImageSourceFactoryTizen() ); + return std::unique_ptr(new NativeImageSourceFactoryTizen()); } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/imaging/tizen/native-image-source-factory-tizen.h b/dali/internal/imaging/tizen/native-image-source-factory-tizen.h index 165954e..9bffead 100644 --- a/dali/internal/imaging/tizen/native-image-source-factory-tizen.h +++ b/dali/internal/imaging/tizen/native-image-source-factory-tizen.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_TIZEN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,21 +27,16 @@ namespace Internal { namespace Adaptor { - class NativeImageSourceFactoryTizen : public NativeImageSourceFactory { public: + std::unique_ptr CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) override; - std::unique_ptr< NativeImageSource > CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) override; - - std::unique_ptr< NativeImageSourceQueue > CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) override; - + std::unique_ptr CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) override; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_TIZEN_H diff --git a/dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp b/dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp old mode 100755 new mode 100644 index 4c8621d..f3b526d --- a/dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp +++ b/dali/internal/imaging/tizen/native-image-source-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,29 +21,27 @@ // EXTERNAL INCLUDES #include #include -#include #include +#include // INTERNAL INCLUDES +#include +#include #include #include -#include -#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n"; -const char* SAMPLER_TYPE = "samplerExternalOES"; +const char* SAMPLER_TYPE = "samplerExternalOES"; +// clang-format off tbm_format FORMATS_BLENDING_REQUIRED[] = { TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444, TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444, @@ -55,19 +53,20 @@ tbm_format FORMATS_BLENDING_REQUIRED[] = { TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010, TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102 }; +// clang-format on const int NUM_FORMATS_BLENDING_REQUIRED = 18; -} +} // namespace using Dali::Integration::PixelBuffer; -NativeImageSourceTizen* NativeImageSourceTizen::New( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +NativeImageSourceTizen* NativeImageSourceTizen::New(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - NativeImageSourceTizen* image = new NativeImageSourceTizen( width, height, depth, nativeImageSource ); - DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." ); + NativeImageSourceTizen* image = new NativeImageSourceTizen(width, height, depth, nativeImageSource); + DALI_ASSERT_DEBUG(image && "NativeImageSource allocation failed."); - if( image ) + if(image) { image->Initialize(); } @@ -75,82 +74,82 @@ NativeImageSourceTizen* NativeImageSourceTizen::New( uint32_t width, uint32_t he return image; } -NativeImageSourceTizen::NativeImageSourceTizen( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) -: mWidth( width ), - mHeight( height ), - mOwnTbmSurface( false ), - mTbmSurface( NULL ), - mTbmFormat( 0 ), - mBlendingRequired( false ), - mColorDepth( depth ), - mEglImageKHR( NULL ), - mEglGraphics( NULL ), - mEglImageExtensions( NULL ), - mSetSource( false ), +NativeImageSourceTizen::NativeImageSourceTizen(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) +: mWidth(width), + mHeight(height), + mOwnTbmSurface(false), + mTbmSurface(NULL), + mTbmFormat(0), + mBlendingRequired(false), + mColorDepth(depth), + mEglImageKHR(NULL), + mEglGraphics(NULL), + mEglImageExtensions(NULL), + mSetSource(false), mMutex(), - mIsBufferAcquired( false ) + mIsBufferAcquired(false) { - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() ); - mEglGraphics = static_cast(graphics); + GraphicsInterface* graphics = &(Adaptor::GetImplementation(Adaptor::Get()).GetGraphicsInterface()); + mEglGraphics = static_cast(graphics); - mTbmSurface = GetSurfaceFromAny( nativeImageSource ); + mTbmSurface = GetSurfaceFromAny(nativeImageSource); - if( mTbmSurface != NULL ) + if(mTbmSurface != NULL) { - tbm_surface_internal_ref( mTbmSurface ); - mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) ); - mWidth = tbm_surface_get_width( mTbmSurface ); - mHeight = tbm_surface_get_height( mTbmSurface ); + tbm_surface_internal_ref(mTbmSurface); + mBlendingRequired = CheckBlending(tbm_surface_get_format(mTbmSurface)); + mWidth = tbm_surface_get_width(mTbmSurface); + mHeight = tbm_surface_get_height(mTbmSurface); } } void NativeImageSourceTizen::Initialize() { - if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 ) + if(mTbmSurface != NULL || mWidth == 0 || mHeight == 0) { return; } tbm_format format = TBM_FORMAT_RGB888; - int depth = 0; + int depth = 0; - switch( mColorDepth ) + switch(mColorDepth) { case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: { format = TBM_FORMAT_ARGB8888; - depth = 32; + depth = 32; break; } case Dali::NativeImageSource::COLOR_DEPTH_8: { format = TBM_FORMAT_C8; - depth = 8; + depth = 8; break; } case Dali::NativeImageSource::COLOR_DEPTH_16: { format = TBM_FORMAT_RGB565; - depth = 16; + depth = 16; break; } case Dali::NativeImageSource::COLOR_DEPTH_24: { format = TBM_FORMAT_RGB888; - depth = 24; + depth = 24; break; } case Dali::NativeImageSource::COLOR_DEPTH_32: { format = TBM_FORMAT_ARGB8888; - depth = 32; + depth = 32; break; } default: { - DALI_LOG_WARNING( "Wrong color depth.\n" ); + DALI_LOG_WARNING("Wrong color depth.\n"); return; } } @@ -160,22 +159,22 @@ void NativeImageSourceTizen::Initialize() If depth = 8, Pixel::A8; If depth = 16, Pixel::RGB565; If depth = 32, Pixel::RGBA8888 */ - mBlendingRequired = ( depth == 32 || depth == 8 ); + mBlendingRequired = (depth == 32 || depth == 8); - mTbmSurface = tbm_surface_create( mWidth, mHeight, format ); + mTbmSurface = tbm_surface_create(mWidth, mHeight, format); mOwnTbmSurface = true; } -tbm_surface_h NativeImageSourceTizen::GetSurfaceFromAny( Any source ) const +tbm_surface_h NativeImageSourceTizen::GetSurfaceFromAny(Any source) const { - if( source.Empty() ) + if(source.Empty()) { return NULL; } - if( source.GetType() == typeid( tbm_surface_h ) ) + if(source.GetType() == typeid(tbm_surface_h)) { - return AnyCast< tbm_surface_h >( source ); + return AnyCast(source); } else { @@ -185,22 +184,22 @@ tbm_surface_h NativeImageSourceTizen::GetSurfaceFromAny( Any source ) const void NativeImageSourceTizen::DestroySurface() { - if( mTbmSurface ) + if(mTbmSurface) { - if( mIsBufferAcquired ) + if(mIsBufferAcquired) { ReleaseBuffer(); } - if( mOwnTbmSurface ) + if(mOwnTbmSurface) { - if( tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE ) + if(tbm_surface_destroy(mTbmSurface) != TBM_SURFACE_ERROR_NONE) { - DALI_LOG_ERROR( "Failed to destroy tbm_surface\n" ); + DALI_LOG_ERROR("Failed to destroy tbm_surface\n"); } } else { - tbm_surface_internal_unref( mTbmSurface ); + tbm_surface_internal_unref(mTbmSurface); } } } @@ -212,150 +211,150 @@ NativeImageSourceTizen::~NativeImageSourceTizen() Any NativeImageSourceTizen::GetNativeImageSource() const { - return Any( mTbmSurface ); + return Any(mTbmSurface); } bool NativeImageSourceTizen::GetPixels(std::vector& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const { - Dali::Mutex::ScopedLock lock( mMutex ); - if( mTbmSurface != NULL ) + Dali::Mutex::ScopedLock lock(mMutex); + if(mTbmSurface != NULL) { tbm_surface_info_s surface_info; - if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE ) + if(tbm_surface_map(mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE) { - DALI_LOG_ERROR( "Fail to map tbm_surface\n" ); + DALI_LOG_ERROR("Fail to map tbm_surface\n"); - width = 0; + width = 0; height = 0; return false; } - tbm_format format = surface_info.format; - uint32_t stride = surface_info.planes[0].stride; - unsigned char* ptr = surface_info.planes[0].ptr; + tbm_format format = surface_info.format; + uint32_t stride = surface_info.planes[0].stride; + unsigned char* ptr = surface_info.planes[0].ptr; - width = mWidth; + width = mWidth; height = mHeight; size_t lineSize; size_t offset; size_t cOffset; - switch( format ) + switch(format) { case TBM_FORMAT_RGB888: { - lineSize = width*3; + lineSize = width * 3; pixelFormat = Pixel::RGB888; - pixbuf.resize( lineSize*height ); + pixbuf.resize(lineSize * height); unsigned char* bufptr = &pixbuf[0]; - for( unsigned int r = 0; r < height; ++r, bufptr += lineSize ) + for(unsigned int r = 0; r < height; ++r, bufptr += lineSize) { - for( unsigned int c = 0; c < width; ++c ) + for(unsigned int c = 0; c < width; ++c) { - cOffset = c*3; - offset = cOffset + r*stride; - *(bufptr+cOffset) = ptr[offset+2]; - *(bufptr+cOffset+1) = ptr[offset+1]; - *(bufptr+cOffset+2) = ptr[offset]; + cOffset = c * 3; + offset = cOffset + r * stride; + *(bufptr + cOffset) = ptr[offset + 2]; + *(bufptr + cOffset + 1) = ptr[offset + 1]; + *(bufptr + cOffset + 2) = ptr[offset]; } } break; } case TBM_FORMAT_RGBA8888: { - lineSize = width*4; + lineSize = width * 4; pixelFormat = Pixel::RGBA8888; - pixbuf.resize( lineSize*height ); + pixbuf.resize(lineSize * height); unsigned char* bufptr = &pixbuf[0]; - for( unsigned int r = 0; r < height; ++r, bufptr += lineSize ) + for(unsigned int r = 0; r < height; ++r, bufptr += lineSize) { - for( unsigned int c = 0; c < width; ++c ) + for(unsigned int c = 0; c < width; ++c) { - cOffset = c*4; - offset = cOffset + r*stride; - *(bufptr+cOffset) = ptr[offset+3]; - *(bufptr+cOffset+1) = ptr[offset+2]; - *(bufptr+cOffset+2) = ptr[offset+1]; - *(bufptr+cOffset+3) = ptr[offset]; + cOffset = c * 4; + offset = cOffset + r * stride; + *(bufptr + cOffset) = ptr[offset + 3]; + *(bufptr + cOffset + 1) = ptr[offset + 2]; + *(bufptr + cOffset + 2) = ptr[offset + 1]; + *(bufptr + cOffset + 3) = ptr[offset]; } } break; } case TBM_FORMAT_ARGB8888: { - lineSize = width*4; + lineSize = width * 4; pixelFormat = Pixel::RGBA8888; - pixbuf.resize( lineSize*height ); + pixbuf.resize(lineSize * height); unsigned char* bufptr = &pixbuf[0]; - for( unsigned int r = 0; r < height; ++r, bufptr += lineSize ) + for(unsigned int r = 0; r < height; ++r, bufptr += lineSize) { - for( unsigned int c = 0; c < width; ++c ) + for(unsigned int c = 0; c < width; ++c) { - cOffset = c*4; - offset = cOffset + r*stride; - *(bufptr+cOffset) = ptr[offset+2]; - *(bufptr+cOffset+1) = ptr[offset+1]; - *(bufptr+cOffset+2) = ptr[offset]; - *(bufptr+cOffset+3) = ptr[offset+3]; + cOffset = c * 4; + offset = cOffset + r * stride; + *(bufptr + cOffset) = ptr[offset + 2]; + *(bufptr + cOffset + 1) = ptr[offset + 1]; + *(bufptr + cOffset + 2) = ptr[offset]; + *(bufptr + cOffset + 3) = ptr[offset + 3]; } } break; } default: { - DALI_ASSERT_ALWAYS( 0 && "Tbm surface has unsupported pixel format.\n" ); + DALI_ASSERT_ALWAYS(0 && "Tbm surface has unsupported pixel format.\n"); return false; } } - if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE ) + if(tbm_surface_unmap(mTbmSurface) != TBM_SURFACE_ERROR_NONE) { - DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" ); + DALI_LOG_ERROR("Fail to unmap tbm_surface\n"); } return true; } - DALI_LOG_WARNING( "TBM surface does not exist.\n" ); + DALI_LOG_WARNING("TBM surface does not exist.\n"); - width = 0; + width = 0; height = 0; return false; } -void NativeImageSourceTizen::SetSource( Any source ) +void NativeImageSourceTizen::SetSource(Any source) { - Dali::Mutex::ScopedLock lock( mMutex ); + Dali::Mutex::ScopedLock lock(mMutex); DestroySurface(); mOwnTbmSurface = false; - mTbmSurface = GetSurfaceFromAny( source ); + mTbmSurface = GetSurfaceFromAny(source); - if( mTbmSurface != NULL ) + if(mTbmSurface != NULL) { mSetSource = true; - tbm_surface_internal_ref( mTbmSurface ); - mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) ); - mWidth = tbm_surface_get_width( mTbmSurface ); - mHeight = tbm_surface_get_height( mTbmSurface ); + tbm_surface_internal_ref(mTbmSurface); + mBlendingRequired = CheckBlending(tbm_surface_get_format(mTbmSurface)); + mWidth = tbm_surface_get_width(mTbmSurface); + mHeight = tbm_surface_get_height(mTbmSurface); } } -bool NativeImageSourceTizen::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) +bool NativeImageSourceTizen::IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) { - uint32_t* formats; - uint32_t formatNum; + uint32_t* formats; + uint32_t formatNum; tbm_format format = TBM_FORMAT_RGB888; - switch( colorDepth ) + switch(colorDepth) { case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: { @@ -384,19 +383,19 @@ bool NativeImageSourceTizen::IsColorDepthSupported( Dali::NativeImageSource::Col } } - if( tbm_surface_query_formats( &formats, &formatNum ) ) + if(tbm_surface_query_formats(&formats, &formatNum)) { - for( unsigned int i = 0; i < formatNum; i++ ) + for(unsigned int i = 0; i < formatNum; i++) { - if( formats[i] == format ) + if(formats[i] == format) { - free( formats ); + free(formats); return true; } } } - free( formats ); + free(formats); return false; } @@ -404,24 +403,24 @@ bool NativeImageSourceTizen::CreateResource() { // casting from an unsigned int to a void *, which should then be cast back // to an unsigned int in the driver. - EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface); - if( !eglBuffer || !tbm_surface_internal_is_valid( mTbmSurface ) ) + EGLClientBuffer eglBuffer = reinterpret_cast(mTbmSurface); + if(!eglBuffer || !tbm_surface_internal_is_valid(mTbmSurface)) { return false; } mEglImageExtensions = mEglGraphics->GetImageExtensions(); - DALI_ASSERT_DEBUG( mEglImageExtensions ); + DALI_ASSERT_DEBUG(mEglImageExtensions); - mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer ); + mEglImageKHR = mEglImageExtensions->CreateImageKHR(eglBuffer); return mEglImageKHR != NULL; } void NativeImageSourceTizen::DestroyResource() { - Dali::Mutex::ScopedLock lock( mMutex ); - if( mEglImageKHR ) + Dali::Mutex::ScopedLock lock(mMutex); + if(mEglImageKHR) { mEglImageExtensions->DestroyImageKHR(mEglImageKHR); @@ -438,17 +437,17 @@ uint32_t NativeImageSourceTizen::TargetTexture() void NativeImageSourceTizen::PrepareTexture() { - Dali::Mutex::ScopedLock lock( mMutex ); - if( mSetSource ) + Dali::Mutex::ScopedLock lock(mMutex); + if(mSetSource) { void* eglImage = mEglImageKHR; - if( CreateResource() ) + if(CreateResource()) { TargetTexture(); } - mEglImageExtensions->DestroyImageKHR( eglImage ); + mEglImageExtensions->DestroyImageKHR(eglImage); mSetSource = false; } @@ -479,13 +478,13 @@ bool NativeImageSourceTizen::SourceChanged() const return false; } -bool NativeImageSourceTizen::CheckBlending( tbm_format format ) +bool NativeImageSourceTizen::CheckBlending(tbm_format format) { - if( mTbmFormat != format ) + if(mTbmFormat != format) { for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i) { - if( format == FORMATS_BLENDING_REQUIRED[i] ) + if(format == FORMATS_BLENDING_REQUIRED[i]) { mBlendingRequired = true; break; @@ -497,27 +496,27 @@ bool NativeImageSourceTizen::CheckBlending( tbm_format format ) return mBlendingRequired; } -uint8_t* NativeImageSourceTizen::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) +uint8_t* NativeImageSourceTizen::AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) { - Dali::Mutex::ScopedLock lock( mMutex ); - if( mTbmSurface != NULL ) + Dali::Mutex::ScopedLock lock(mMutex); + if(mTbmSurface != NULL) { tbm_surface_info_s info; - if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &info) != TBM_SURFACE_ERROR_NONE ) + if(tbm_surface_map(mTbmSurface, TBM_SURF_OPTION_READ, &info) != TBM_SURFACE_ERROR_NONE) { - DALI_LOG_ERROR( "Fail to map tbm_surface\n" ); + DALI_LOG_ERROR("Fail to map tbm_surface\n"); - width = 0; + width = 0; height = 0; return NULL; } - tbm_surface_internal_ref( mTbmSurface ); + tbm_surface_internal_ref(mTbmSurface); mIsBufferAcquired = true; stride = info.planes[0].stride; - width = mWidth; + width = mWidth; height = mHeight; return info.planes[0].ptr; @@ -525,27 +524,25 @@ uint8_t* NativeImageSourceTizen::AcquireBuffer( uint16_t& width, uint16_t& heigh return NULL; } - bool NativeImageSourceTizen::ReleaseBuffer() { - Dali::Mutex::ScopedLock lock( mMutex ); - bool ret = false; - if( mTbmSurface != NULL ) + Dali::Mutex::ScopedLock lock(mMutex); + bool ret = false; + if(mTbmSurface != NULL) { - ret = ( tbm_surface_unmap( mTbmSurface ) == TBM_SURFACE_ERROR_NONE ); - if( !ret ) + ret = (tbm_surface_unmap(mTbmSurface) == TBM_SURFACE_ERROR_NONE); + if(!ret) { - DALI_LOG_ERROR( "Fail to unmap tbm_surface\n" ); + DALI_LOG_ERROR("Fail to unmap tbm_surface\n"); } - tbm_surface_internal_unref( mTbmSurface ); + tbm_surface_internal_unref(mTbmSurface); mIsBufferAcquired = false; } return ret; } - } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/tizen/native-image-source-impl-tizen.h b/dali/internal/imaging/tizen/native-image-source-impl-tizen.h old mode 100755 new mode 100644 index 502ad7f..7f48b92 --- a/dali/internal/imaging/tizen/native-image-source-impl-tizen.h +++ b/dali/internal/imaging/tizen/native-image-source-impl-tizen.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_IMPL_TIZEN_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,33 +19,29 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - class EglGraphics; class EglImageExtensions; /** * Dali internal NativeImageSource. */ -class NativeImageSourceTizen: public Internal::Adaptor::NativeImageSource +class NativeImageSourceTizen : public Internal::Adaptor::NativeImageSource { public: - /** * Create a new NativeImageSource internally. * Depending on hardware the width and height may have to be a power of two. @@ -55,10 +51,10 @@ public: * @param[in] nativeImageSource contains tbm_surface_h or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceTizen* New(uint32_t width, - uint32_t height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + static NativeImageSourceTizen* New(uint32_t width, + uint32_t height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * @copydoc Dali::NativeImageSource::GetNativeImageSource() @@ -68,17 +64,17 @@ public: /** * @copydoc Dali::NativeImageSource::GetPixels() */ - bool GetPixels(std::vector &pixbuf, uint32_t &width, uint32_t &height, Pixel::Format& pixelFormat ) const override; + bool GetPixels(std::vector& pixbuf, uint32_t& width, uint32_t& height, Pixel::Format& pixelFormat) const override; /** * @copydoc Dali::NativeImageSource::SetSource( Any source ) */ - void SetSource( Any source ) override; + void SetSource(Any source) override; /** * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth ) */ - bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override; + bool IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) override; /** * destructor @@ -165,7 +161,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::AcquireBuffer() */ - uint8_t* AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) override; + uint8_t* AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) override; /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::ReleaseBuffer() @@ -173,7 +169,6 @@ public: bool ReleaseBuffer() override; private: - /** * Private constructor; @see NativeImageSource::New() * @param[in] width The width of the image. @@ -181,34 +176,33 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty */ - NativeImageSourceTizen(uint32_t width, - unsigned int height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + NativeImageSourceTizen(uint32_t width, + unsigned int height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); void Initialize(); - tbm_surface_h GetSurfaceFromAny( Any source ) const; + tbm_surface_h GetSurfaceFromAny(Any source) const; - bool CheckBlending( tbm_format format ); + bool CheckBlending(tbm_format format); void DestroySurface(); private: - - uint32_t mWidth; ///< image width - uint32_t mHeight; ///< image height - bool mOwnTbmSurface; ///< Whether we created pixmap or not - tbm_surface_h mTbmSurface; - tbm_format mTbmFormat; - bool mBlendingRequired; ///< Whether blending is required - Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image - void* mEglImageKHR; ///< From EGL extension - EglGraphics* mEglGraphics; ///< EGL Graphics - EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions - bool mSetSource; - mutable Dali::Mutex mMutex; - bool mIsBufferAcquired; ///< Whether AcquireBuffer is called + uint32_t mWidth; ///< image width + uint32_t mHeight; ///< image height + bool mOwnTbmSurface; ///< Whether we created pixmap or not + tbm_surface_h mTbmSurface; + tbm_format mTbmFormat; + bool mBlendingRequired; ///< Whether blending is required + Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image + void* mEglImageKHR; ///< From EGL extension + EglGraphics* mEglGraphics; ///< EGL Graphics + EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions + bool mSetSource; + mutable Dali::Mutex mMutex; + bool mIsBufferAcquired; ///< Whether AcquireBuffer is called }; } // namespace Adaptor diff --git a/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.cpp b/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.cpp index 9bf842c..8028efd 100644 --- a/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.cpp +++ b/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,26 +24,24 @@ #include // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { -#define TBM_SURFACE_QUEUE_SIZE 3 +#define TBM_SURFACE_QUEUE_SIZE 3 const char* FRAGMENT_PREFIX = "#extension GL_OES_EGL_image_external:require\n"; -const char* SAMPLER_TYPE = "samplerExternalOES"; +const char* SAMPLER_TYPE = "samplerExternalOES"; +// clang-format off int FORMATS_BLENDING_REQUIRED[] = { TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444, TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444, @@ -55,99 +53,100 @@ int FORMATS_BLENDING_REQUIRED[] = { TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010, TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102 }; +// clang-format on const int NUM_FORMATS_BLENDING_REQUIRED = 18; -} +} // namespace -NativeImageSourceQueueTizen* NativeImageSourceQueueTizen::New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +NativeImageSourceQueueTizen* NativeImageSourceQueueTizen::New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - NativeImageSourceQueueTizen* image = new NativeImageSourceQueueTizen( width, height, depth, nativeImageSourceQueue ); - DALI_ASSERT_DEBUG( image && "NativeImageSourceQueueTizen allocation failed." ); + NativeImageSourceQueueTizen* image = new NativeImageSourceQueueTizen(width, height, depth, nativeImageSourceQueue); + DALI_ASSERT_DEBUG(image && "NativeImageSourceQueueTizen allocation failed."); - if( image ) + if(image) { - image->Initialize( depth ); + image->Initialize(depth); } return image; } -NativeImageSourceQueueTizen::NativeImageSourceQueueTizen( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +NativeImageSourceQueueTizen::NativeImageSourceQueueTizen(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) : mMutex(), - mWidth( width ), - mHeight( height ), - mTbmQueue( NULL ), - mConsumeSurface( NULL ), + mWidth(width), + mHeight(height), + mTbmQueue(NULL), + mConsumeSurface(NULL), mEglImages(), - mEglGraphics( NULL ), - mEglImageExtensions( NULL ), - mOwnTbmQueue( false ), - mBlendingRequired( false ) + mEglGraphics(NULL), + mEglImageExtensions(NULL), + mOwnTbmQueue(false), + mBlendingRequired(false) { - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() ); - mEglGraphics = static_cast(graphics); + GraphicsInterface* graphics = &(Adaptor::GetImplementation(Adaptor::Get()).GetGraphicsInterface()); + mEglGraphics = static_cast(graphics); - mTbmQueue = GetSurfaceFromAny( nativeImageSourceQueue ); + mTbmQueue = GetSurfaceFromAny(nativeImageSourceQueue); - if( mTbmQueue != NULL ) + if(mTbmQueue != NULL) { - mBlendingRequired = CheckBlending( tbm_surface_queue_get_format( mTbmQueue ) ); - mWidth = tbm_surface_queue_get_width( mTbmQueue ); - mHeight = tbm_surface_queue_get_height( mTbmQueue ); + mBlendingRequired = CheckBlending(tbm_surface_queue_get_format(mTbmQueue)); + mWidth = tbm_surface_queue_get_width(mTbmQueue); + mHeight = tbm_surface_queue_get_height(mTbmQueue); } } NativeImageSourceQueueTizen::~NativeImageSourceQueueTizen() { - if( mOwnTbmQueue ) + if(mOwnTbmQueue) { - if( mTbmQueue != NULL ) + if(mTbmQueue != NULL) { - tbm_surface_queue_destroy( mTbmQueue ); + tbm_surface_queue_destroy(mTbmQueue); } } } -void NativeImageSourceQueueTizen::Initialize( Dali::NativeImageSourceQueue::ColorDepth depth ) +void NativeImageSourceQueueTizen::Initialize(Dali::NativeImageSourceQueue::ColorDepth depth) { - if( mWidth == 0 || mHeight == 0 ) + if(mWidth == 0 || mHeight == 0) { return; } - if( mTbmQueue == NULL ) + if(mTbmQueue == NULL) { int format = TBM_FORMAT_ARGB8888; - switch( depth ) + switch(depth) { case Dali::NativeImageSourceQueue::COLOR_DEPTH_DEFAULT: case Dali::NativeImageSourceQueue::COLOR_DEPTH_32: { - format = TBM_FORMAT_ARGB8888; + format = TBM_FORMAT_ARGB8888; mBlendingRequired = true; break; } case Dali::NativeImageSourceQueue::COLOR_DEPTH_24: { - format = TBM_FORMAT_RGB888; + format = TBM_FORMAT_RGB888; mBlendingRequired = false; break; } default: { - DALI_LOG_WARNING( "Wrong color depth.\n" ); + DALI_LOG_WARNING("Wrong color depth.\n"); return; } } - mTbmQueue = tbm_surface_queue_create( TBM_SURFACE_QUEUE_SIZE, mWidth, mHeight, format, 0 ); - if( !mTbmQueue ) + mTbmQueue = tbm_surface_queue_create(TBM_SURFACE_QUEUE_SIZE, mWidth, mHeight, format, 0); + if(!mTbmQueue) { - DALI_LOG_ERROR( "NativeImageSourceQueueTizen::Initialize: tbm_surface_queue_create is failed! [%p]\n", mTbmQueue ); + DALI_LOG_ERROR("NativeImageSourceQueueTizen::Initialize: tbm_surface_queue_create is failed! [%p]\n", mTbmQueue); return; } @@ -155,16 +154,16 @@ void NativeImageSourceQueueTizen::Initialize( Dali::NativeImageSourceQueue::Colo } } -tbm_surface_queue_h NativeImageSourceQueueTizen::GetSurfaceFromAny( Any source ) const +tbm_surface_queue_h NativeImageSourceQueueTizen::GetSurfaceFromAny(Any source) const { - if( source.Empty() ) + if(source.Empty()) { return NULL; } - if( source.GetType() == typeid( tbm_surface_queue_h ) ) + if(source.GetType() == typeid(tbm_surface_queue_h)) { - return AnyCast< tbm_surface_queue_h >( source ); + return AnyCast(source); } else { @@ -174,16 +173,16 @@ tbm_surface_queue_h NativeImageSourceQueueTizen::GetSurfaceFromAny( Any source ) Any NativeImageSourceQueueTizen::GetNativeImageSourceQueue() const { - return Any( mTbmQueue ); + return Any(mTbmQueue); } -void NativeImageSourceQueueTizen::SetSize( uint32_t width, uint32_t height ) +void NativeImageSourceQueueTizen::SetSize(uint32_t width, uint32_t height) { - Dali::Mutex::ScopedLock lock( mMutex ); + Dali::Mutex::ScopedLock lock(mMutex); - tbm_surface_queue_reset( mTbmQueue, width, height, tbm_surface_queue_get_format( mTbmQueue ) ); + tbm_surface_queue_reset(mTbmQueue, width, height, tbm_surface_queue_get_format(mTbmQueue)); - mWidth = width; + mWidth = width; mHeight = height; ResetEglImageList(); @@ -191,20 +190,20 @@ void NativeImageSourceQueueTizen::SetSize( uint32_t width, uint32_t height ) void NativeImageSourceQueueTizen::IgnoreSourceImage() { - Dali::Mutex::ScopedLock lock( mMutex ); - tbm_surface_h surface; + Dali::Mutex::ScopedLock lock(mMutex); + tbm_surface_h surface; - if( tbm_surface_queue_can_acquire( mTbmQueue, 0 ) ) + if(tbm_surface_queue_can_acquire(mTbmQueue, 0)) { - if( tbm_surface_queue_acquire( mTbmQueue, &surface ) != TBM_SURFACE_QUEUE_ERROR_NONE ) + if(tbm_surface_queue_acquire(mTbmQueue, &surface) != TBM_SURFACE_QUEUE_ERROR_NONE) { - DALI_LOG_ERROR( "NativeImageSourceQueueTizen::IgnoreSourceImage: Failed to aquire a tbm_surface\n" ); + DALI_LOG_ERROR("NativeImageSourceQueueTizen::IgnoreSourceImage: Failed to aquire a tbm_surface\n"); return; } - if( tbm_surface_internal_is_valid( surface ) ) + if(tbm_surface_internal_is_valid(surface)) { - tbm_surface_queue_release( mTbmQueue, surface ); + tbm_surface_queue_release(mTbmQueue, surface); } } } @@ -212,14 +211,14 @@ void NativeImageSourceQueueTizen::IgnoreSourceImage() bool NativeImageSourceQueueTizen::CreateResource() { mEglImageExtensions = mEglGraphics->GetImageExtensions(); - DALI_ASSERT_DEBUG( mEglImageExtensions ); + DALI_ASSERT_DEBUG(mEglImageExtensions); return true; } void NativeImageSourceQueueTizen::DestroyResource() { - Dali::Mutex::ScopedLock lock( mMutex ); + Dali::Mutex::ScopedLock lock(mMutex); ResetEglImageList(); } @@ -231,49 +230,49 @@ uint32_t NativeImageSourceQueueTizen::TargetTexture() void NativeImageSourceQueueTizen::PrepareTexture() { - Dali::Mutex::ScopedLock lock( mMutex ); + Dali::Mutex::ScopedLock lock(mMutex); tbm_surface_h oldSurface = mConsumeSurface; - if( tbm_surface_queue_can_acquire( mTbmQueue, 0 ) ) + if(tbm_surface_queue_can_acquire(mTbmQueue, 0)) { - if( tbm_surface_queue_acquire( mTbmQueue, &mConsumeSurface ) != TBM_SURFACE_QUEUE_ERROR_NONE ) + if(tbm_surface_queue_acquire(mTbmQueue, &mConsumeSurface) != TBM_SURFACE_QUEUE_ERROR_NONE) { - DALI_LOG_ERROR( "Failed to aquire a tbm_surface\n" ); + DALI_LOG_ERROR("Failed to aquire a tbm_surface\n"); return; } - if( oldSurface ) + if(oldSurface) { - if( tbm_surface_internal_is_valid( oldSurface ) ) + if(tbm_surface_internal_is_valid(oldSurface)) { - tbm_surface_queue_release( mTbmQueue, oldSurface ); + tbm_surface_queue_release(mTbmQueue, oldSurface); } } - if( mConsumeSurface ) + if(mConsumeSurface) { bool existing = false; - for( auto&& iter : mEglImages ) + for(auto&& iter : mEglImages) { - if( iter.first == mConsumeSurface ) + if(iter.first == mConsumeSurface) { // Find the surface in the existing list existing = true; - mEglImageExtensions->TargetTextureKHR( iter.second ); + mEglImageExtensions->TargetTextureKHR(iter.second); break; } } - if( !existing ) + if(!existing) { // Push the surface - tbm_surface_internal_ref( mConsumeSurface ); + tbm_surface_internal_ref(mConsumeSurface); - void* eglImageKHR = mEglImageExtensions->CreateImageKHR( reinterpret_cast< EGLClientBuffer >( mConsumeSurface ) ); - mEglImageExtensions->TargetTextureKHR( eglImageKHR ); + void* eglImageKHR = mEglImageExtensions->CreateImageKHR(reinterpret_cast(mConsumeSurface)); + mEglImageExtensions->TargetTextureKHR(eglImageKHR); - mEglImages.push_back( EglImagePair( mConsumeSurface, eglImageKHR) ); + mEglImages.push_back(EglImagePair(mConsumeSurface, eglImageKHR)); } } } @@ -304,33 +303,31 @@ bool NativeImageSourceQueueTizen::SourceChanged() const return false; } - - void NativeImageSourceQueueTizen::ResetEglImageList() { - if( mConsumeSurface ) + if(mConsumeSurface) { - if( tbm_surface_internal_is_valid( mConsumeSurface ) ) + if(tbm_surface_internal_is_valid(mConsumeSurface)) { - tbm_surface_queue_release( mTbmQueue, mConsumeSurface ); + tbm_surface_queue_release(mTbmQueue, mConsumeSurface); } mConsumeSurface = NULL; } - for( auto&& iter : mEglImages ) + for(auto&& iter : mEglImages) { - mEglImageExtensions->DestroyImageKHR( iter.second ); + mEglImageExtensions->DestroyImageKHR(iter.second); - tbm_surface_internal_unref( iter.first ); + tbm_surface_internal_unref(iter.first); } mEglImages.clear(); } -bool NativeImageSourceQueueTizen::CheckBlending( int format ) +bool NativeImageSourceQueueTizen::CheckBlending(int format) { - for( int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i ) + for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i) { - if( format == FORMATS_BLENDING_REQUIRED[i] ) + if(format == FORMATS_BLENDING_REQUIRED[i]) { return true; } @@ -341,6 +338,6 @@ bool NativeImageSourceQueueTizen::CheckBlending( int format ) } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.h b/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.h old mode 100755 new mode 100644 index f82059e..4f86eb4 --- a/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.h +++ b/dali/internal/imaging/tizen/native-image-source-queue-impl-tizen.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_QUEUE_IMPL_TIZEN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,23 +29,19 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class EglGraphics; class EglImageExtensions; /** * Dali internal NativeImageSource. */ -class NativeImageSourceQueueTizen: public Internal::Adaptor::NativeImageSourceQueue +class NativeImageSourceQueueTizen : public Internal::Adaptor::NativeImageSourceQueue { public: - /** * Create a new NativeImageSourceQueueTizen internally. * Depending on hardware the width and height may have to be a power of two. @@ -55,7 +51,7 @@ public: * @param[in] nativeImageSourceQueue contains tbm_surface_queue_h or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceQueueTizen* New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + static NativeImageSourceQueueTizen* New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); /** * @copydoc Dali::NativeImageSourceQueue::GetNativeImageSourceQueue() @@ -65,7 +61,7 @@ public: /** * @copydoc Dali::NativeImageSourceQueue::SetSize */ - void SetSize( uint32_t width, uint32_t height ) override; + void SetSize(uint32_t width, uint32_t height) override; /** * @copydoc Dali::NativeImageSourceQueue::IgnoreSourceImage @@ -155,7 +151,6 @@ public: } private: - /** * Private constructor; @see NativeImageSourceQueue::New() * @param[in] width The width of the image. @@ -163,30 +158,29 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSourceQueue contains tbm_surface_queue_h or is empty */ - NativeImageSourceQueueTizen( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + NativeImageSourceQueueTizen(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); - void Initialize( Dali::NativeImageSourceQueue::ColorDepth depth ); + void Initialize(Dali::NativeImageSourceQueue::ColorDepth depth); void ResetEglImageList(); - tbm_surface_queue_h GetSurfaceFromAny( Any source ) const; + tbm_surface_queue_h GetSurfaceFromAny(Any source) const; - bool CheckBlending( int format ); + bool CheckBlending(int format); private: - - typedef std::pair< tbm_surface_h, void* > EglImagePair; - - Dali::Mutex mMutex; ///< Mutex - uint32_t mWidth; ///< image width - uint32_t mHeight; ///< image height - tbm_surface_queue_h mTbmQueue; ///< Tbm surface queue handle - tbm_surface_h mConsumeSurface; ///< The current tbm surface - std::vector< EglImagePair > mEglImages; ///< EGL Image vector - EglGraphics* mEglGraphics; ///< EGL Graphics - EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions - bool mOwnTbmQueue; ///< Whether we created tbm queue - bool mBlendingRequired; ///< Whether blending is required + typedef std::pair EglImagePair; + + Dali::Mutex mMutex; ///< Mutex + uint32_t mWidth; ///< image width + uint32_t mHeight; ///< image height + tbm_surface_queue_h mTbmQueue; ///< Tbm surface queue handle + tbm_surface_h mConsumeSurface; ///< The current tbm surface + std::vector mEglImages; ///< EGL Image vector + EglGraphics* mEglGraphics; ///< EGL Graphics + EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions + bool mOwnTbmQueue; ///< Whether we created tbm queue + bool mBlendingRequired; ///< Whether blending is required }; } // namespace Adaptor diff --git a/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.cpp b/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.cpp index 42b6c39..a614cf0 100644 --- a/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.cpp +++ b/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,26 +28,23 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< NativeImageSource > NativeImageSourceFactoryX::CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +std::unique_ptr NativeImageSourceFactoryX::CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - return std::unique_ptr< NativeImageSource >( NativeImageSourceX::New( width, height, depth, nativeImageSource ) ); + return std::unique_ptr(NativeImageSourceX::New(width, height, depth, nativeImageSource)); } -std::unique_ptr< NativeImageSourceQueue > NativeImageSourceFactoryX::CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +std::unique_ptr NativeImageSourceFactoryX::CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - return std::unique_ptr< NativeImageSourceQueue >( NativeImageSourceQueueX::New( width, height, depth, nativeImageSourceQueue ) ); + return std::unique_ptr(NativeImageSourceQueueX::New(width, height, depth, nativeImageSourceQueue)); } // this should be created from somewhere -std::unique_ptr< NativeImageSourceFactory > GetNativeImageSourceFactory() +std::unique_ptr GetNativeImageSourceFactory() { // returns native image source factory - return std::unique_ptr< NativeImageSourceFactoryX >( new NativeImageSourceFactoryX() ); + return std::unique_ptr(new NativeImageSourceFactoryX()); } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.h b/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.h index 303d689..640e4bd 100644 --- a/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.h +++ b/dali/internal/imaging/ubuntu-x11/native-image-source-factory-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,21 +27,16 @@ namespace Internal { namespace Adaptor { - class NativeImageSourceFactoryX : public NativeImageSourceFactory { public: + std::unique_ptr CreateNativeImageSource(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) override; - std::unique_ptr< NativeImageSource > CreateNativeImageSource( uint32_t width, uint32_t height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) override; - - std::unique_ptr< NativeImageSourceQueue > CreateNativeImageSourceQueue( uint32_t width, uint32_t height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) override; - + std::unique_ptr CreateNativeImageSourceQueue(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) override; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H diff --git a/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.cpp b/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.cpp old mode 100755 new mode 100644 index d7dc6ed..bb41acd --- a/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.cpp +++ b/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,23 +19,21 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include #include +#include // INTERNAL INCLUDES +#include +#include #include #include -#include -#include namespace Dali { - namespace Internal { - namespace Adaptor { using Dali::Integration::PixelBuffer; @@ -43,38 +41,39 @@ using Dali::Integration::PixelBuffer; // Pieces needed to save compressed images (temporary location while plumbing): namespace { - - /** +/** * Free an allocated XImage on destruction. */ - struct XImageJanitor +struct XImageJanitor +{ + XImageJanitor(XImage* const pXImage) + : mXImage(pXImage) { - XImageJanitor( XImage* const pXImage ) : mXImage( pXImage ) - { - DALI_ASSERT_DEBUG(pXImage != 0 && "Null pointer to XImage."); - } + DALI_ASSERT_DEBUG(pXImage != 0 && "Null pointer to XImage."); + } - ~XImageJanitor() + ~XImageJanitor() + { + if(mXImage) { - if( mXImage ) + if(!XDestroyImage(mXImage)) { - if( !XDestroyImage(mXImage) ) - { - DALI_LOG_ERROR("XImage deallocation failure"); - } + DALI_LOG_ERROR("XImage deallocation failure"); } } - XImage* const mXImage; - private: - XImageJanitor( const XImageJanitor& rhs ); - XImageJanitor& operator = ( const XImageJanitor& rhs ); - }; -} + } + XImage* const mXImage; -NativeImageSourceX* NativeImageSourceX::New( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +private: + XImageJanitor(const XImageJanitor& rhs); + XImageJanitor& operator=(const XImageJanitor& rhs); +}; +} // namespace + +NativeImageSourceX* NativeImageSourceX::New(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - NativeImageSourceX* image = new NativeImageSourceX( width, height, depth, nativeImageSource ); - DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." ); + NativeImageSourceX* image = new NativeImageSourceX(width, height, depth, nativeImageSource); + DALI_ASSERT_DEBUG(image && "NativeImageSource allocation failed."); // 2nd phase construction if(image) //< Defensive in case we ever compile without exceptions. @@ -85,24 +84,24 @@ NativeImageSourceX* NativeImageSourceX::New( uint32_t width, uint32_t height, Da return image; } -NativeImageSourceX::NativeImageSourceX( uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) -: mWidth( width ), - mHeight( height ), - mOwnPixmap( true ), - mPixmap( 0 ), - mBlendingRequired( false ), - mColorDepth( depth ), - mEglImageKHR( NULL ), - mEglImageExtensions( NULL ) +NativeImageSourceX::NativeImageSourceX(uint32_t width, uint32_t height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) +: mWidth(width), + mHeight(height), + mOwnPixmap(true), + mPixmap(0), + mBlendingRequired(false), + mColorDepth(depth), + mEglImageKHR(NULL), + mEglImageExtensions(NULL) { - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() ); - auto eglGraphics = static_cast(graphics); + GraphicsInterface* graphics = &(Adaptor::GetImplementation(Adaptor::Get()).GetGraphicsInterface()); + auto eglGraphics = static_cast(graphics); mEglImageExtensions = eglGraphics->GetImageExtensions(); - DALI_ASSERT_DEBUG( mEglImageExtensions ); + DALI_ASSERT_DEBUG(mEglImageExtensions); // assign the pixmap mPixmap = GetPixmapFromAny(nativeImageSource); @@ -111,7 +110,7 @@ NativeImageSourceX::NativeImageSourceX( uint32_t width, uint32_t height, Dali::N void NativeImageSourceX::Initialize() { // if pixmap has been created outside of X11 Image we can return - if (mPixmap) + if(mPixmap) { // we don't own the pixmap mOwnPixmap = false; @@ -129,15 +128,15 @@ void NativeImageSourceX::Initialize() If depth = 8, Pixel::A8; If depth = 16, Pixel::RGB565; If depth = 32, Pixel::RGBA8888 */ - mBlendingRequired = ( depth == 32 || depth == 8 ); + mBlendingRequired = (depth == 32 || depth == 8); - mPixmap = ecore_x_pixmap_new( 0, mWidth, mHeight, depth ); + mPixmap = ecore_x_pixmap_new(0, mWidth, mHeight, depth); ecore_x_sync(); } NativeImageSourceX::~NativeImageSourceX() { - if (mOwnPixmap && mPixmap) + if(mOwnPixmap && mPixmap) { // Temporarily disable this as this causes a crash with EFL Version 1.24.0 //ecore_x_pixmap_free(mPixmap); @@ -154,19 +153,21 @@ bool NativeImageSourceX::GetPixels(std::vector& pixbuf, unsigned& { DALI_ASSERT_DEBUG(sizeof(unsigned) == 4); bool success = false; - width = mWidth; - height = mHeight; + width = mWidth; + height = mHeight; // Open a display connection - Display* displayConnection = XOpenDisplay( 0 ); - - XImageJanitor xImageJanitor( XGetImage( displayConnection, - mPixmap, - 0, 0, // x,y of subregion to extract. - width, height, // of subregion to extract. - 0xFFFFFFFF, - ZPixmap ) ); - XImage* const pXImage = xImageJanitor.mXImage; + Display* displayConnection = XOpenDisplay(0); + + XImageJanitor xImageJanitor(XGetImage(displayConnection, + mPixmap, + 0, + 0, // x,y of subregion to extract. + width, + height, // of subregion to extract. + 0xFFFFFFFF, + ZPixmap)); + XImage* const pXImage = xImageJanitor.mXImage; DALI_ASSERT_DEBUG(pXImage && "XImage (from pixmap) could not be retrieved from the server"); if(!pXImage) { @@ -184,23 +185,23 @@ bool NativeImageSourceX::GetPixels(std::vector& pixbuf, unsigned& case 24: { pixelFormat = Pixel::RGB888; - pixbuf.resize(width*height*3); + pixbuf.resize(width * height * 3); unsigned char* bufPtr = &pixbuf[0]; for(unsigned y = 0; y < height; ++y) { - for(unsigned x = 0; x < width; ++x, bufPtr+=3) + for(unsigned x = 0; x < width; ++x, bufPtr += 3) { - const unsigned pixel = XGetPixel(pXImage,x,y); + const unsigned pixel = XGetPixel(pXImage, x, y); // store as RGB - const unsigned blue = pixel & 0xFFU; - const unsigned green = (pixel >> 8) & 0xFFU; + const unsigned blue = pixel & 0xFFU; + const unsigned green = (pixel >> 8) & 0xFFU; const unsigned red = (pixel >> 16) & 0xFFU; - *bufPtr = red; - *(bufPtr+1) = green; - *(bufPtr+2) = blue; + *bufPtr = red; + *(bufPtr + 1) = green; + *(bufPtr + 2) = blue; } } success = true; @@ -212,22 +213,22 @@ bool NativeImageSourceX::GetPixels(std::vector& pixbuf, unsigned& { // Sweep through the image, doing a vertical flip, but handling each scanline as // an inlined intrinsic/builtin memcpy (should be fast): - pixbuf.resize(width*height*4); - unsigned * bufPtr = reinterpret_cast(&pixbuf[0]); + pixbuf.resize(width * height * 4); + unsigned* bufPtr = reinterpret_cast(&pixbuf[0]); const unsigned xDataLineSkip = pXImage->bytes_per_line; - const size_t copy_count = static_cast< size_t >( width ) * 4; - pixelFormat = Pixel::BGRA8888; + const size_t copy_count = static_cast(width) * 4; + pixelFormat = Pixel::BGRA8888; for(unsigned y = 0; y < height; ++y, bufPtr += width) { - const char * const in = pXImage->data + xDataLineSkip * y; + const char* const in = pXImage->data + xDataLineSkip * y; // Copy a whole scanline at a time: - DALI_ASSERT_DEBUG( size_t( bufPtr ) >= size_t( &pixbuf[0] )); - DALI_ASSERT_DEBUG( reinterpret_cast( bufPtr ) + copy_count <= reinterpret_cast( &pixbuf[pixbuf.size()] ) ); - DALI_ASSERT_DEBUG( in >= pXImage->data ); - DALI_ASSERT_DEBUG( in + copy_count <= pXImage->data + xDataLineSkip * height ); - __builtin_memcpy( bufPtr, in, copy_count ); + DALI_ASSERT_DEBUG(size_t(bufPtr) >= size_t(&pixbuf[0])); + DALI_ASSERT_DEBUG(reinterpret_cast(bufPtr) + copy_count <= reinterpret_cast(&pixbuf[pixbuf.size()])); + DALI_ASSERT_DEBUG(in >= pXImage->data); + DALI_ASSERT_DEBUG(in + copy_count <= pXImage->data + xDataLineSkip * height); + __builtin_memcpy(bufPtr, in, copy_count); } success = true; } @@ -254,21 +255,21 @@ bool NativeImageSourceX::GetPixels(std::vector& pixbuf, unsigned& { DALI_LOG_ERROR("Failed to get pixels from NativeImageSource.\n"); pixbuf.resize(0); - width = 0; + width = 0; height = 0; } // Close the display connection - XCloseDisplay( displayConnection ); + XCloseDisplay(displayConnection); return success; } -void NativeImageSourceX::SetSource( Any source ) +void NativeImageSourceX::SetSource(Any source) { - mPixmap = GetPixmapFromAny( source ); + mPixmap = GetPixmapFromAny(source); - if (mPixmap) + if(mPixmap) { // we don't own the pixmap mOwnPixmap = false; @@ -278,7 +279,7 @@ void NativeImageSourceX::SetSource( Any source ) } } -bool NativeImageSourceX::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) +bool NativeImageSourceX::IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) { return true; } @@ -286,16 +287,16 @@ bool NativeImageSourceX::IsColorDepthSupported( Dali::NativeImageSource::ColorDe bool NativeImageSourceX::CreateResource() { // if the image existed previously delete it. - if (mEglImageKHR != NULL) + if(mEglImageKHR != NULL) { DestroyResource(); } // casting from an unsigned int to a void *, which should then be cast back // to an unsigned int in the driver. - EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer > (mPixmap); + EGLClientBuffer eglBuffer = reinterpret_cast(mPixmap); - mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer ); + mEglImageKHR = mEglImageExtensions->CreateImageKHR(eglBuffer); return mEglImageKHR != NULL; } @@ -320,7 +321,7 @@ void NativeImageSourceX::PrepareTexture() int NativeImageSourceX::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const { - switch (depth) + switch(depth) { case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: { @@ -378,13 +379,13 @@ bool NativeImageSourceX::SourceChanged() const Ecore_X_Pixmap NativeImageSourceX::GetPixmapFromAny(Any pixmap) const { - if (pixmap.Empty()) + if(pixmap.Empty()) { return 0; } // see if it is of type x11 pixmap - if (pixmap.GetType() == typeid (Pixmap)) + if(pixmap.GetType() == typeid(Pixmap)) { // get the x pixmap type Pixmap xpixmap = AnyCast(pixmap); @@ -403,23 +404,22 @@ void NativeImageSourceX::GetPixmapDetails() int x, y; // get the width, height and depth - ecore_x_pixmap_geometry_get( mPixmap, &x, &y, reinterpret_cast< int* >( &mWidth ), reinterpret_cast< int* >( &mHeight ) ); + ecore_x_pixmap_geometry_get(mPixmap, &x, &y, reinterpret_cast(&mWidth), reinterpret_cast(&mHeight)); // set whether blending is required according to pixel format based on the depth /* default pixel format is RGB888 If depth = 8, Pixel::A8; If depth = 16, Pixel::RGB565; If depth = 32, Pixel::RGBA8888 */ - int depth = ecore_x_pixmap_depth_get(mPixmap); - mBlendingRequired = ( depth == 32 || depth == 8 ); + int depth = ecore_x_pixmap_depth_get(mPixmap); + mBlendingRequired = (depth == 32 || depth == 8); } -uint8_t* NativeImageSourceX::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) +uint8_t* NativeImageSourceX::AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) { return NULL; } - bool NativeImageSourceX::ReleaseBuffer() { return false; @@ -427,6 +427,6 @@ bool NativeImageSourceX::ReleaseBuffer() } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h b/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h old mode 100755 new mode 100644 index c905912..3c3dc1e --- a/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h +++ b/dali/internal/imaging/ubuntu-x11/native-image-source-impl-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,10 +30,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class EglImageExtensions; @@ -44,7 +42,6 @@ class EglImageExtensions; class NativeImageSourceX : public Internal::Adaptor::NativeImageSource { public: - /** * Create a new NativeImageSource internally. * Depending on hardware the width and height may have to be a power of two. @@ -54,10 +51,10 @@ public: * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceX* New( uint32_t width, - uint32_t height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + static NativeImageSourceX* New(uint32_t width, + uint32_t height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * @copydoc Dali::NativeImageSource::GetNativeImageSource() */ @@ -66,17 +63,17 @@ public: /** * @copydoc Dali::NativeImageSource::GetPixels() */ - bool GetPixels(std::vector &pixbuf, uint32_t &width, uint32_t &height, Pixel::Format& pixelFormat ) const override; + bool GetPixels(std::vector& pixbuf, uint32_t& width, uint32_t& height, Pixel::Format& pixelFormat) const override; /** * @copydoc Dali::NativeImageSource::SetSource( Any source ) */ - void SetSource( Any source ) override; + void SetSource(Any source) override; /** * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth ) */ - bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override; + bool IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) override; /** * destructor @@ -152,7 +149,6 @@ public: */ bool SourceChanged() const override; - /** * @copydoc Dali::NativeImageInterface::GetExtension() */ @@ -164,7 +160,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::AcquireBuffer() */ - uint8_t* AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) override; + uint8_t* AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) override; /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::ReleaseBuffer() @@ -172,7 +168,6 @@ public: bool ReleaseBuffer() override; private: - /** * Private constructor; @see NativeImageSource::New() * @param[in] width The width of the image. @@ -180,10 +175,10 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSource contains either: pixmap of type X11 Pixmap , a Ecore_X_Pixmap or is empty */ - NativeImageSourceX( uint32_t width, - uint32_t height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + NativeImageSourceX(uint32_t width, + uint32_t height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * 2nd phase construction. @@ -211,15 +206,14 @@ private: void GetPixmapDetails(); private: - - uint32_t mWidth; ///< image width - uint32_t mHeight; ///< image heights - bool mOwnPixmap; ///< Whether we created pixmap or not - Ecore_X_Pixmap mPixmap; ///< From Xlib - bool mBlendingRequired; ///< Whether blending is required - Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image - void* mEglImageKHR; ///< From EGL extension - EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions + uint32_t mWidth; ///< image width + uint32_t mHeight; ///< image heights + bool mOwnPixmap; ///< Whether we created pixmap or not + Ecore_X_Pixmap mPixmap; ///< From Xlib + bool mBlendingRequired; ///< Whether blending is required + Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image + void* mEglImageKHR; ///< From EGL extension + EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions }; } // namespace Adaptor diff --git a/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.cpp b/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.cpp index 98edeba..257e0f6 100644 --- a/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.cpp +++ b/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,39 +23,36 @@ #include // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { -#define TBM_SURFACE_QUEUE_SIZE 3 +#define TBM_SURFACE_QUEUE_SIZE 3 const char* FRAGMENT_PREFIX = "\n"; -const char* SAMPLER_TYPE = "sampler2D"; +const char* SAMPLER_TYPE = "sampler2D"; -} +} // namespace -NativeImageSourceQueueX* NativeImageSourceQueueX::New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +NativeImageSourceQueueX* NativeImageSourceQueueX::New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - NativeImageSourceQueueX* image = new NativeImageSourceQueueX( width, height, depth, nativeImageSourceQueue ); + NativeImageSourceQueueX* image = new NativeImageSourceQueueX(width, height, depth, nativeImageSourceQueue); return image; } -NativeImageSourceQueueX::NativeImageSourceQueueX( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) -: mWidth( width ), - mHeight( height ) +NativeImageSourceQueueX::NativeImageSourceQueueX(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) +: mWidth(width), + mHeight(height) { - DALI_LOG_ERROR( "NativeImageSourceQueueX::NativeImageSourceQueueX: Not supported\n" ); + DALI_LOG_ERROR("NativeImageSourceQueueX::NativeImageSourceQueueX: Not supported\n"); } NativeImageSourceQueueX::~NativeImageSourceQueueX() @@ -67,9 +64,9 @@ Any NativeImageSourceQueueX::GetNativeImageSourceQueue() const return Any(); } -void NativeImageSourceQueueX::SetSize( uint32_t width, uint32_t height ) +void NativeImageSourceQueueX::SetSize(uint32_t width, uint32_t height) { - mWidth = width; + mWidth = width; mHeight = height; } @@ -122,6 +119,6 @@ bool NativeImageSourceQueueX::SourceChanged() const } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.h b/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.h old mode 100755 new mode 100644 index 7bc1ce2..50a1452 --- a/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.h +++ b/dali/internal/imaging/ubuntu-x11/native-image-source-queue-impl-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_QUEUE_IMPL_X_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,23 +25,19 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class EglGraphics; class EglImageExtensions; /** * Dali internal NativeImageSourceQueue. */ -class NativeImageSourceQueueX: public Internal::Adaptor::NativeImageSourceQueue +class NativeImageSourceQueueX : public Internal::Adaptor::NativeImageSourceQueue { public: - /** * Create a new NativeImageSourceQueueX internally. * Depending on hardware the width and height may have to be a power of two. @@ -51,7 +47,7 @@ public: * @param[in] nativeImageSourceQueue contains tbm_surface_queue_h or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceQueueX* New( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + static NativeImageSourceQueueX* New(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); /** * @copydoc Dali::NativeImageSourceQueue::GetNativeImageSourceQueue() @@ -61,7 +57,7 @@ public: /** * @copydoc Dali::NativeImageSourceQueue::SetSize */ - void SetSize( uint32_t width, uint32_t height ) override; + void SetSize(uint32_t width, uint32_t height) override; /** * @copydoc Dali::NativeImageSourceQueue::IgnoreSourceImage @@ -151,7 +147,6 @@ public: } private: - /** * Private constructor; @see NativeImageSourceQueue::New() * @param[in] width The width of the image. @@ -159,13 +154,11 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSourceQueue contains tbm_surface_queue_h or is empty */ - NativeImageSourceQueueX( uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ); + NativeImageSourceQueueX(uint32_t width, uint32_t height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue); private: - - uint32_t mWidth; ///< image width - uint32_t mHeight; ///< image height - + uint32_t mWidth; ///< image width + uint32_t mHeight; ///< image height }; } // namespace Adaptor diff --git a/dali/internal/imaging/windows/curl-environment-win.cpp b/dali/internal/imaging/windows/curl-environment-win.cpp old mode 100755 new mode 100644 index 8e4dbed..06a0606 --- a/dali/internal/imaging/windows/curl-environment-win.cpp +++ b/dali/internal/imaging/windows/curl-environment-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,35 +16,32 @@ */ // EXTERNAL INCLUDES -#include #include +#include #undef TRANSPARENT #undef CopyMemory // INTERNAL INCLUDES -#include #include +#include #include #include namespace Dali { - namespace TizenPlatform { - -const int CONNECTION_TIMEOUT_SECONDS( 30L ); -const long VERBOSE_MODE = 0L; // 0 == off, 1 == on -const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on -const long EXCLUDE_HEADER = 0L; -const long INCLUDE_HEADER = 1L; -const long INCLUDE_BODY = 0L; -const long EXCLUDE_BODY = 1L; +const int CONNECTION_TIMEOUT_SECONDS(30L); +const long VERBOSE_MODE = 0L; // 0 == off, 1 == on +const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on +const long EXCLUDE_HEADER = 0L; +const long INCLUDE_HEADER = 1L; +const long INCLUDE_BODY = 0L; +const long EXCLUDE_BODY = 1L; namespace Network { - -} -} } +} // namespace TizenPlatform +} // namespace Dali diff --git a/dali/internal/imaging/windows/file-download-win.cpp b/dali/internal/imaging/windows/file-download-win.cpp old mode 100755 new mode 100644 index 3f7db68..10af2c2 --- a/dali/internal/imaging/windows/file-download-win.cpp +++ b/dali/internal/imaging/windows/file-download-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ #include // EXTERNAL INCLUDES +#include #include #include #include -#include // INTERNAL INCLUDES #include @@ -31,20 +31,17 @@ using namespace Dali::Integration; namespace Dali { - namespace TizenPlatform { - namespace // unnamed namespace { - -const int CONNECTION_TIMEOUT_SECONDS( 30L ); -const long VERBOSE_MODE = 0L; // 0 == off, 1 == on -const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on -const long EXCLUDE_HEADER = 0L; -const long INCLUDE_HEADER = 1L; -const long INCLUDE_BODY = 0L; -const long EXCLUDE_BODY = 1L; +const int CONNECTION_TIMEOUT_SECONDS(30L); +const long VERBOSE_MODE = 0L; // 0 == off, 1 == on +const long CLOSE_CONNECTION_ON_ERROR = 1L; // 0 == off, 1 == on +const long EXCLUDE_HEADER = 0L; +const long INCLUDE_HEADER = 1L; +const long INCLUDE_BODY = 0L; +const long EXCLUDE_BODY = 1L; /** * Curl library environment. Direct initialize ensures it's constructed before adaptor @@ -54,170 +51,166 @@ static Dali::TizenPlatform::Network::CurlEnvironment gCurlEnvironment; // Without a write function or a buffer (file descriptor) to write to, curl will pump out // header/body contents to stdout -size_t __cdecl DummyWrite(char *ptr, size_t size, size_t nmemb, void *userdata) +size_t __cdecl DummyWrite(char* ptr, size_t size, size_t nmemb, void* userdata) { return size * nmemb; } struct ChunkData { - std::vector< uint8_t > data; + std::vector data; }; -size_t __cdecl ChunkLoader(char *ptr, size_t size, size_t nmemb, void *userdata) +size_t __cdecl ChunkLoader(char* ptr, size_t size, size_t nmemb, void* userdata) { - std::vector* chunks = static_cast*>( userdata ); - int numBytes = size*nmemb; - if( chunks != nullptr ) + std::vector* chunks = static_cast*>(userdata); + int numBytes = size * nmemb; + if(chunks != nullptr) { - chunks->push_back( ChunkData() ); - ChunkData& chunkData = (*chunks)[chunks->size()-1]; - chunkData.data.reserve( numBytes ); - memcpy( chunkData.data.data(), ptr, numBytes ); + chunks->push_back(ChunkData()); + ChunkData& chunkData = (*chunks)[chunks->size() - 1]; + chunkData.data.reserve(numBytes); + memcpy(chunkData.data.data(), ptr, numBytes); } return numBytes; } -static size_t __cdecl WriteFunction( void *input, size_t uSize, size_t uCount, void *avg ) +static size_t __cdecl WriteFunction(void* input, size_t uSize, size_t uCount, void* avg) { - fwrite( (const char*)input, uSize, uCount, (FILE*)avg ); + fwrite((const char*)input, uSize, uCount, (FILE*)avg); return uSize * uCount; } -void InitWriteFunction( void* curlHandle ) +void InitWriteFunction(void* curlHandle) { - curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, WriteFunction ); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, WriteFunction); } -CURLcode DownloadFileDataWithSize( CURL* curlHandle, Dali::Vector& dataBuffer, size_t dataSize ) +CURLcode DownloadFileDataWithSize(CURL* curlHandle, Dali::Vector& dataBuffer, size_t dataSize) { - CURLcode result( CURLE_OK ); + CURLcode result(CURLE_OK); // create - Dali::Internal::Platform::FileWriter fileWriter( dataBuffer, dataSize ); - FILE* dataBufferFilePointer = fileWriter.GetFile(); - if( nullptr != dataBufferFilePointer ) + Dali::Internal::Platform::FileWriter fileWriter(dataBuffer, dataSize); + FILE* dataBufferFilePointer = fileWriter.GetFile(); + if(nullptr != dataBufferFilePointer) { // we only want the body which contains the file data - curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER ); - curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY ); + curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER); + curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY); // disable the write callback, and get curl to write directly into our data buffer - InitWriteFunction( curlHandle ); + InitWriteFunction(curlHandle); - curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer ); + curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, dataBufferFilePointer); // synchronous request of the body data - result = curl_easy_perform( curlHandle ); + result = curl_easy_perform(curlHandle); } return result; } -CURLcode DownloadFileDataByChunk( CURL* curlHandle, Dali::Vector& dataBuffer, size_t& dataSize ) +CURLcode DownloadFileDataByChunk(CURL* curlHandle, Dali::Vector& dataBuffer, size_t& dataSize) { // create - std::vector< ChunkData > chunks; + std::vector chunks; // we only want the body which contains the file data - curl_easy_setopt( curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER ); - curl_easy_setopt( curlHandle, CURLOPT_NOBODY, INCLUDE_BODY ); + curl_easy_setopt(curlHandle, CURLOPT_HEADER, EXCLUDE_HEADER); + curl_easy_setopt(curlHandle, CURLOPT_NOBODY, INCLUDE_BODY); // Enable the write callback. - curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader ); - curl_easy_setopt( curlHandle, CURLOPT_WRITEDATA, &chunks ); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, ChunkLoader); + curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &chunks); // synchronous request of the body data - CURLcode result = curl_easy_perform( curlHandle ); + CURLcode result = curl_easy_perform(curlHandle); // chunks should now contain all of the chunked data. Reassemble into a single vector dataSize = 0; - for( size_t i=0; i& dataBuffer, - size_t& dataSize, - size_t maximumAllowedSizeBytes ) +bool DownloadFile(CURL* curlHandle, + const std::string& url, + Dali::Vector& dataBuffer, + size_t& dataSize, + size_t maximumAllowedSizeBytes) { - CURLcode result( CURLE_OK ); - double size(0); + CURLcode result(CURLE_OK); + double size(0); // setup curl to download just the header so we can extract the content length - ConfigureCurlOptions( curlHandle, url ); + ConfigureCurlOptions(curlHandle, url); - curl_easy_setopt( curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite); + curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, DummyWrite); // perform the request to get the header - result = curl_easy_perform( curlHandle ); + result = curl_easy_perform(curlHandle); - if( result != CURLE_OK) + if(result != CURLE_OK) { - DALI_LOG_ERROR( "Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result ); + DALI_LOG_ERROR("Failed to download http header for \"%s\" with error code %d\n", url.c_str(), result); return false; } // get the content length, -1 == size is not known - curl_easy_getinfo( curlHandle,CURLINFO_CONTENT_LENGTH_DOWNLOAD , &size ); + curl_easy_getinfo(curlHandle, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size); - - if( size >= maximumAllowedSizeBytes ) + if(size >= maximumAllowedSizeBytes) { - DALI_LOG_ERROR( "File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str() ); + DALI_LOG_ERROR("File content length %f > max allowed %zu \"%s\" \n", size, maximumAllowedSizeBytes, url.c_str()); return false; } - else if( size > 0 ) + else if(size > 0) { // If we know the size up front, allocate once and avoid chunk copies. - dataSize = static_cast( size ); - result = DownloadFileDataWithSize( curlHandle, dataBuffer, dataSize ); + dataSize = static_cast(size); + result = DownloadFileDataWithSize(curlHandle, dataBuffer, dataSize); } else { - result = DownloadFileDataByChunk( curlHandle, dataBuffer, dataSize ); + result = DownloadFileDataByChunk(curlHandle, dataBuffer, dataSize); } - if( result != CURLE_OK ) + if(result != CURLE_OK) { - DALI_LOG_ERROR( "Failed to download image file \"%s\" with error code %d\n", url.c_str(), result ); + DALI_LOG_ERROR("Failed to download image file \"%s\" with error code %d\n", url.c_str(), result); return false; } return true; } - } // unnamed namespace - namespace Network { - CurlEnvironment::CurlEnvironment() { // Must be called before we attempt any loads. e.g. by using curl_easy_init() @@ -230,12 +223,12 @@ CurlEnvironment::~CurlEnvironment() curl_global_cleanup(); } -bool DownloadRemoteFileIntoMemory( const std::string& url, - Dali::Vector& dataBuffer, - size_t& dataSize, - size_t maximumAllowedSizeBytes ) +bool DownloadRemoteFileIntoMemory(const std::string& url, + Dali::Vector& dataBuffer, + size_t& dataSize, + size_t maximumAllowedSizeBytes) { - if( url.empty() ) + if(url.empty()) { DALI_LOG_WARNING("empty url requested \n"); return false; @@ -246,10 +239,10 @@ bool DownloadRemoteFileIntoMemory( const std::string& url, CURL* curlHandle = curl_easy_init(); - bool result = DownloadFile( curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes); + bool result = DownloadFile(curlHandle, url, dataBuffer, dataSize, maximumAllowedSizeBytes); // clean up session - curl_easy_cleanup( curlHandle ); + curl_easy_cleanup(curlHandle); return result; } diff --git a/dali/internal/imaging/windows/native-image-source-factory-win.cpp b/dali/internal/imaging/windows/native-image-source-factory-win.cpp old mode 100755 new mode 100644 index aa1662f..88511e3 --- a/dali/internal/imaging/windows/native-image-source-factory-win.cpp +++ b/dali/internal/imaging/windows/native-image-source-factory-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali { @@ -28,26 +28,23 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< NativeImageSource > NativeImageSourceFactoryWin::CreateNativeImageSource( unsigned int width, unsigned int height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +std::unique_ptr NativeImageSourceFactoryWin::CreateNativeImageSource(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - return std::unique_ptr< NativeImageSource >( NativeImageSourceWin::New( width, height, depth, nativeImageSource ) ); + return std::unique_ptr(NativeImageSourceWin::New(width, height, depth, nativeImageSource)); } -std::unique_ptr< NativeImageSourceQueue > NativeImageSourceFactoryWin::CreateNativeImageSourceQueue( unsigned int width, unsigned int height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) +std::unique_ptr NativeImageSourceFactoryWin::CreateNativeImageSourceQueue(unsigned int width, unsigned int height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) { - return std::unique_ptr< NativeImageSourceQueue >( nullptr ); + return std::unique_ptr(nullptr); } // this should be created from somewhere -std::unique_ptr< NativeImageSourceFactory > GetNativeImageSourceFactory() +std::unique_ptr GetNativeImageSourceFactory() { // returns native image source factory - return std::unique_ptr< NativeImageSourceFactoryWin >( new NativeImageSourceFactoryWin() ); + return std::unique_ptr(new NativeImageSourceFactoryWin()); } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/imaging/windows/native-image-source-factory-win.h b/dali/internal/imaging/windows/native-image-source-factory-win.h old mode 100755 new mode 100644 index d4f289a..e8b00b8 --- a/dali/internal/imaging/windows/native-image-source-factory-win.h +++ b/dali/internal/imaging/windows/native-image-source-factory-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,21 +27,16 @@ namespace Internal { namespace Adaptor { - class NativeImageSourceFactoryWin : public NativeImageSourceFactory { public: + std::unique_ptr CreateNativeImageSource(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) override; - std::unique_ptr< NativeImageSource > CreateNativeImageSource( unsigned int width, unsigned int height, - Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) override; - - std::unique_ptr< NativeImageSourceQueue > CreateNativeImageSourceQueue( unsigned int width, unsigned int height, - Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue ) override; - + std::unique_ptr CreateNativeImageSourceQueue(unsigned int width, unsigned int height, Dali::NativeImageSourceQueue::ColorDepth depth, Any nativeImageSourceQueue) override; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_NATIVE_IMAGE_SOURCE_FACTORY_X_H diff --git a/dali/internal/imaging/windows/native-image-source-impl-win.cpp b/dali/internal/imaging/windows/native-image-source-impl-win.cpp old mode 100755 new mode 100644 index ad4851b..02c5fdf --- a/dali/internal/imaging/windows/native-image-source-impl-win.cpp +++ b/dali/internal/imaging/windows/native-image-source-impl-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,26 +22,24 @@ #include // INTERNAL INCLUDES +#include +#include #include #include -#include #include -#include namespace Dali { - namespace Internal { - namespace Adaptor { using Dali::Integration::PixelBuffer; -NativeImageSourceWin* NativeImageSourceWin::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) +NativeImageSourceWin* NativeImageSourceWin::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) { - NativeImageSourceWin* image = new NativeImageSourceWin( width, height, depth, nativeImageSource ); - DALI_ASSERT_DEBUG( image && "NativeImageSource allocation failed." ); + NativeImageSourceWin* image = new NativeImageSourceWin(width, height, depth, nativeImageSource); + DALI_ASSERT_DEBUG(image && "NativeImageSource allocation failed."); // 2nd phase construction if(image) //< Defensive in case we ever compile without exceptions. @@ -52,24 +50,24 @@ NativeImageSourceWin* NativeImageSourceWin::New(unsigned int width, unsigned int return image; } -NativeImageSourceWin::NativeImageSourceWin( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource ) -: mWidth( width ), - mHeight( height ), - mOwnPixmap( true ), - mPixmap( 0 ), - mBlendingRequired( false ), - mColorDepth( depth ), - mEglImageKHR( NULL ), - mEglImageExtensions( NULL ) +NativeImageSourceWin::NativeImageSourceWin(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource) +: mWidth(width), + mHeight(height), + mOwnPixmap(true), + mPixmap(0), + mBlendingRequired(false), + mColorDepth(depth), + mEglImageKHR(NULL), + mEglImageExtensions(NULL) { - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - GraphicsInterface* graphics = &( Adaptor::GetImplementation( Adaptor::Get() ).GetGraphicsInterface() ); - auto eglGraphics = static_cast(graphics); + GraphicsInterface* graphics = &(Adaptor::GetImplementation(Adaptor::Get()).GetGraphicsInterface()); + auto eglGraphics = static_cast(graphics); mEglImageExtensions = eglGraphics->GetImageExtensions(); - DALI_ASSERT_DEBUG( mEglImageExtensions ); + DALI_ASSERT_DEBUG(mEglImageExtensions); // assign the pixmap mPixmap = GetPixmapFromAny(nativeImageSource); @@ -78,7 +76,7 @@ NativeImageSourceWin::NativeImageSourceWin( unsigned int width, unsigned int hei void NativeImageSourceWin::Initialize() { // if pixmap has been created outside of Windows Image we can return - if (mPixmap) + if(mPixmap) { // we don't own the pixmap mOwnPixmap = false; @@ -96,7 +94,7 @@ void NativeImageSourceWin::Initialize() If depth = 8, Pixel::A8; If depth = 16, Pixel::RGB565; If depth = 32, Pixel::RGBA8888 */ - mBlendingRequired = ( depth == 32 || depth == 8 ); + mBlendingRequired = (depth == 32 || depth == 8); } NativeImageSourceWin::~NativeImageSourceWin() @@ -112,17 +110,17 @@ bool NativeImageSourceWin::GetPixels(std::vector& pixbuf, unsigned& wid { DALI_ASSERT_DEBUG(sizeof(unsigned) == 4); bool success = false; - width = mWidth; - height = mHeight; + width = mWidth; + height = mHeight; return success; } -void NativeImageSourceWin::SetSource( Any source ) +void NativeImageSourceWin::SetSource(Any source) { - mPixmap = GetPixmapFromAny( source ); + mPixmap = GetPixmapFromAny(source); - if (mPixmap) + if(mPixmap) { // we don't own the pixmap mOwnPixmap = false; @@ -132,7 +130,7 @@ void NativeImageSourceWin::SetSource( Any source ) } } -bool NativeImageSourceWin::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) +bool NativeImageSourceWin::IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) { return true; } @@ -140,16 +138,16 @@ bool NativeImageSourceWin::IsColorDepthSupported( Dali::NativeImageSource::Color bool NativeImageSourceWin::CreateResource() { // if the image existed previously delete it. - if (mEglImageKHR != NULL) + if(mEglImageKHR != NULL) { DestroyResource(); } // casting from an unsigned int to a void *, which should then be cast back // to an unsigned int in the driver. - EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer > (mPixmap); + EGLClientBuffer eglBuffer = reinterpret_cast(mPixmap); - mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer ); + mEglImageKHR = mEglImageExtensions->CreateImageKHR(eglBuffer); return mEglImageKHR != NULL; } @@ -174,7 +172,7 @@ void NativeImageSourceWin::PrepareTexture() int NativeImageSourceWin::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const { - switch (depth) + switch(depth) { case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT: { @@ -206,13 +204,13 @@ int NativeImageSourceWin::GetPixelDepth(Dali::NativeImageSource::ColorDepth dept unsigned int NativeImageSourceWin::GetPixmapFromAny(Any pixmap) const { - if (pixmap.Empty()) + if(pixmap.Empty()) { return 0; } // see if it is of type Windows pixmap - if (pixmap.GetType() == typeid ( unsigned int )) + if(pixmap.GetType() == typeid(unsigned int)) { // get the Windows pixmap type unsigned int xpixmap = AnyCast(pixmap); @@ -255,12 +253,11 @@ bool NativeImageSourceWin::SourceChanged() const return false; } -uint8_t* NativeImageSourceWin::AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) +uint8_t* NativeImageSourceWin::AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) { return NULL; } - bool NativeImageSourceWin::ReleaseBuffer() { return false; @@ -268,6 +265,6 @@ bool NativeImageSourceWin::ReleaseBuffer() } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/imaging/windows/native-image-source-impl-win.h b/dali/internal/imaging/windows/native-image-source-impl-win.h old mode 100755 new mode 100644 index d8b13a0..e17503e --- a/dali/internal/imaging/windows/native-image-source-impl-win.h +++ b/dali/internal/imaging/windows/native-image-source-impl-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_NATIVE_IMAGE_SOURCE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class EglImageExtensions; @@ -39,7 +37,6 @@ class EglImageExtensions; class NativeImageSourceWin : public Internal::Adaptor::NativeImageSource { public: - /** * Create a new NativeImageSource internally. * Depending on hardware the width and height may have to be a power of two. @@ -49,10 +46,10 @@ public: * @param[in] nativeImageSource contains either: pixmap of type Win32 Pixmap , a WinPixmap or is empty * @return A smart-pointer to a newly allocated image. */ - static NativeImageSourceWin* New(unsigned int width, - unsigned int height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + static NativeImageSourceWin* New(unsigned int width, + unsigned int height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * @copydoc Dali::NativeImageSource::GetNativeImageSource() */ @@ -61,17 +58,17 @@ public: /** * @copydoc Dali::NativeImageSource::GetPixels() */ - bool GetPixels(std::vector &pixbuf, unsigned int &width, unsigned int &height, Pixel::Format& pixelFormat ) const override; + bool GetPixels(std::vector& pixbuf, unsigned int& width, unsigned int& height, Pixel::Format& pixelFormat) const override; /** * @copydoc Dali::NativeImageSource::SetSource( Any source ) */ - void SetSource( Any source ) override; + void SetSource(Any source) override; /** * @copydoc Dali::NativeImageSource::IsColorDepthSupported( ColorDepth colorDepth ) */ - bool IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth ) override; + bool IsColorDepthSupported(Dali::NativeImageSource::ColorDepth colorDepth) override; /** * destructor @@ -158,7 +155,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::AcquireBuffer() */ - uint8_t* AcquireBuffer( uint16_t& width, uint16_t& height, uint16_t& stride ) override; + uint8_t* AcquireBuffer(uint16_t& width, uint16_t& height, uint16_t& stride) override; /** * @copydoc Dali::Internal::Adaptor::NativeImageSource::ReleaseBuffer() @@ -166,7 +163,6 @@ public: bool ReleaseBuffer() override; private: - /** * Private constructor; @see NativeImageSource::New() * @param[in] width The width of the image. @@ -174,10 +170,10 @@ private: * @param[in] colour depth of the image. * @param[in] nativeImageSource contains either: pixmap of type Win32 Pixmap , a WinPixmap or is empty */ - NativeImageSourceWin(unsigned int width, - unsigned int height, - Dali::NativeImageSource::ColorDepth depth, - Any nativeImageSource); + NativeImageSourceWin(unsigned int width, + unsigned int height, + Dali::NativeImageSource::ColorDepth depth, + Any nativeImageSource); /** * 2nd phase construction. @@ -205,15 +201,14 @@ private: void GetPixmapDetails(); private: - - unsigned int mWidth; ///< image width - unsigned int mHeight; ///< image heights - bool mOwnPixmap; ///< Whether we created pixmap or not - unsigned int mPixmap; ///< From Windows - bool mBlendingRequired; ///< Whether blending is required - Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image - void* mEglImageKHR; ///< From EGL extension - EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions + unsigned int mWidth; ///< image width + unsigned int mHeight; ///< image heights + bool mOwnPixmap; ///< Whether we created pixmap or not + unsigned int mPixmap; ///< From Windows + bool mBlendingRequired; ///< Whether blending is required + Dali::NativeImageSource::ColorDepth mColorDepth; ///< color depth of image + void* mEglImageKHR; ///< From EGL extension + EglImageExtensions* mEglImageExtensions; ///< The EGL Image Extensions }; } // namespace Adaptor diff --git a/dali/internal/input/common/input-method-context-factory.h b/dali/internal/input/common/input-method-context-factory.h old mode 100755 new mode 100644 index f000748..cd9e185 --- a/dali/internal/input/common/input-method-context-factory.h +++ b/dali/internal/input/common/input-method-context-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_COMMON_INPUT_METHOD_CONTEXT_FACTORY_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,18 +26,16 @@ namespace Internal { namespace Adaptor { - namespace InputMethodContextFactory { - // Factory function creating new InputMethodContext // Symbol exists but may be overriden during linking -InputMethodContextPtr CreateInputMethodContext( Dali::Actor actor ); +InputMethodContextPtr CreateInputMethodContext(Dali::Actor actor); -} -} -} +} // namespace InputMethodContextFactory +} // namespace Adaptor +} // namespace Internal -} +} // namespace Dali #endif //DALI_INTERNAL_INPUT_COMMON_INPUT_METHOD_CONTEXT_FACTORY_H diff --git a/dali/internal/input/common/input-method-context-impl.cpp b/dali/internal/input/common/input-method-context-impl.cpp old mode 100755 new mode 100644 index 3598bd0..5f01d0a --- a/dali/internal/input/common/input-method-context-impl.cpp +++ b/dali/internal/input/common/input-method-context-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,22 +15,20 @@ * */ -#include +#include #include +#include #include -#include namespace Dali { namespace Internal { - namespace Adaptor { - -InputMethodContextPtr InputMethodContext::New( Dali::Actor actor ) +InputMethodContextPtr InputMethodContext::New(Dali::Actor actor) { - return Dali::Internal::Adaptor::InputMethodContextFactory::CreateInputMethodContext( actor ); + return Dali::Internal::Adaptor::InputMethodContextFactory::CreateInputMethodContext(actor); } const std::string& InputMethodContext::GetSurroundingText() const @@ -40,7 +38,7 @@ const std::string& InputMethodContext::GetSurroundingText() const } InputMethodContext::InputMethodContext() -: mBackupOperations( Operation::MAX_COUNT ) +: mBackupOperations(Operation::MAX_COUNT) { } @@ -49,15 +47,15 @@ void InputMethodContext::ApplyBackupOperations() // Items in mBackupOperations will be changed while the iteration OperationList copiedList = mBackupOperations; - for( auto& operation : copiedList ) + for(auto& operation : copiedList) { - if( operation ) + if(operation) { operation(); } } } -} -} -} +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/input/common/input-method-context-impl.h b/dali/internal/input/common/input-method-context-impl.h old mode 100755 new mode 100644 index 4125be2..eba7424 --- a/dali/internal/input/common/input-method-context-impl.h +++ b/dali/internal/input/common/input-method-context-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_COMMON_INPUT_METHOD_CONTEXT_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,154 +19,193 @@ */ // EXTERNAL INCLUDES -#include -#include +#include #include #include #include -#include +#include +#include // INTERNAL INCLUDES #include namespace Dali { - class RenderSurface; namespace Internal { - namespace Adaptor { class InputMethodContext; -typedef IntrusivePtr< InputMethodContext > InputMethodContextPtr; +typedef IntrusivePtr InputMethodContextPtr; using ImfContext = void; class InputMethodContext : public Dali::BaseObject { - public: - - using ActivatedSignalType = Dali::InputMethodContext::ActivatedSignalType; - using KeyboardEventSignalType = Dali::InputMethodContext::KeyboardEventSignalType; - using StatusSignalType = Dali::InputMethodContext::StatusSignalType; - using VoidSignalType = Dali::InputMethodContext::VoidSignalType; - using KeyboardTypeSignalType = Dali::InputMethodContext::KeyboardTypeSignalType; + using ActivatedSignalType = Dali::InputMethodContext::ActivatedSignalType; + using KeyboardEventSignalType = Dali::InputMethodContext::KeyboardEventSignalType; + using StatusSignalType = Dali::InputMethodContext::StatusSignalType; + using VoidSignalType = Dali::InputMethodContext::VoidSignalType; + using KeyboardTypeSignalType = Dali::InputMethodContext::KeyboardTypeSignalType; using LanguageChangedSignalType = Dali::InputMethodContext::LanguageChangedSignalType; using KeyboardResizedSignalType = Dali::InputMethodContext::KeyboardResizedSignalType; using ContentReceivedSignalType = Dali::InputMethodContext::ContentReceivedSignalType; public: - /** * Create a new input method context instance. */ - static InputMethodContextPtr New( Dali::Actor actor ); + static InputMethodContextPtr New(Dali::Actor actor); /** * Initialize the object. */ - virtual void Initialize() {} + virtual void Initialize() + { + } /** * Connect Callbacks required for InputMethodContext. * If you don't connect InputMethodContext callbacks, you can't get the key events. * The events are PreeditChanged, Commit, DeleteSurrounding and PrivateCommand. */ - virtual void ConnectCallbacks() {} + virtual void ConnectCallbacks() + { + } /** * Disconnect Callbacks attached to input method context. */ - virtual void DisconnectCallbacks() {} + virtual void DisconnectCallbacks() + { + } /** * @copydoc Dali::InputMethodContext::Finalize() */ - virtual void Finalize() {} + virtual void Finalize() + { + } /** * @copydoc Dali::InputMethodContext::Activate() */ - virtual void Activate() {} + virtual void Activate() + { + } /** * @copydoc Dali::InputMethodContext::Deactivate() */ - virtual void Deactivate() {} + virtual void Deactivate() + { + } /** * @copydoc Dali::InputMethodContext::Reset() */ - virtual void Reset() {} + virtual void Reset() + { + } /** * @copydoc Dali::InputMethodContext::GetContext() */ - virtual ImfContext* GetContext() { return nullptr; } + virtual ImfContext* GetContext() + { + return nullptr; + } /** * @copydoc Dali::InputMethodContext::RestoreAfterFocusLost() */ - virtual bool RestoreAfterFocusLost() const { return false; } + virtual bool RestoreAfterFocusLost() const + { + return false; + } /** * @copydoc Dali::InputMethodContext::SetRestoreAfterFocusLost() */ - virtual void SetRestoreAfterFocusLost( bool toggle ) {} + virtual void SetRestoreAfterFocusLost(bool toggle) + { + } /** * @copydoc Dali::InputMethodContext::PreEditChanged() */ - virtual void PreEditChanged( void *data, ImfContext* imfContext, void *eventInfo ) {} + virtual void PreEditChanged(void* data, ImfContext* imfContext, void* eventInfo) + { + } /** * @copydoc Dali::InputMethodContext::CommitReceived() */ - virtual void CommitReceived( void *data, ImfContext* imfContext, void *eventInfo ) {} + virtual void CommitReceived(void* data, ImfContext* imfContext, void* eventInfo) + { + } /** * @copydoc Dali::InputMethodContext::RetrieveSurrounding() */ /*Eina_Bool*/ - virtual bool RetrieveSurrounding( void *data, ImfContext* imfContext, char** text, int* cursorPosition ) { return false; } + virtual bool RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) + { + return false; + } /** * @copydoc Dali::InputMethodContext::DeleteSurrounding() */ - virtual void DeleteSurrounding( void *data, ImfContext* imfContext, void *eventInfo ) {} + virtual void DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) + { + } /** * @copydoc Dali::InputMethodContext::SendPrivateCommand() */ - virtual void SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) {} + virtual void SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) + { + } /** * @copydoc Dali::InputMethodContext::SendCommitContent() */ - virtual void SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) {} + virtual void SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) + { + } // Cursor related /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - virtual void NotifyCursorPosition() {} + virtual void NotifyCursorPosition() + { + } /** * @copydoc Dali::InputMethodContext::SetCursorPosition() */ - virtual void SetCursorPosition( unsigned int cursorPosition ) {} + virtual void SetCursorPosition(unsigned int cursorPosition) + { + } /** * @copydoc Dali::InputMethodContext::GetCursorPosition() */ - virtual unsigned int GetCursorPosition() const { return 0; } + virtual unsigned int GetCursorPosition() const + { + return 0; + } /** * @copydoc Dali::InputMethodContext::SetSurroundingText() */ - virtual void SetSurroundingText( const std::string& text ) {} + virtual void SetSurroundingText(const std::string& text) + { + } /** * @copydoc Dali::InputMethodContext::GetSurroundingText() @@ -176,147 +215,216 @@ public: /** * @copydoc Dali::InputMethodContext::NotifyTextInputMultiLine() */ - virtual void NotifyTextInputMultiLine( bool multiLine ) {} + virtual void NotifyTextInputMultiLine(bool multiLine) + { + } /** * @copydoc Dali::InputMethodContext::GetTextDirection() */ - virtual Dali::InputMethodContext::TextDirection GetTextDirection() { return Dali::InputMethodContext::TextDirection(); } + virtual Dali::InputMethodContext::TextDirection GetTextDirection() + { + return Dali::InputMethodContext::TextDirection(); + } /** * @copydoc Dali::InputMethodContext::GetInputMethodArea() */ - virtual Dali::Rect GetInputMethodArea() { return Dali::Rect(); } + virtual Dali::Rect GetInputMethodArea() + { + return Dali::Rect(); + } /** * @copydoc Dali::InputMethodContext::ApplyOptions() */ - virtual void ApplyOptions( const InputMethodOptions& options ) {} + virtual void ApplyOptions(const InputMethodOptions& options) + { + } /** * @copydoc Dali::InputMethodContext::SetInputPanelData() */ - virtual void SetInputPanelData( const std::string& data ) {} + virtual void SetInputPanelData(const std::string& data) + { + } /** * @copydoc Dali::InputMethodContext::GetInputPanelData() */ - virtual void GetInputPanelData( std::string& data ) {} + virtual void GetInputPanelData(std::string& data) + { + } /** * @copydoc Dali::InputMethodContext::GetInputPanelState() */ - virtual Dali::InputMethodContext::State GetInputPanelState() { return Dali::InputMethodContext::State(); } + virtual Dali::InputMethodContext::State GetInputPanelState() + { + return Dali::InputMethodContext::State(); + } /** * @copydoc Dali::InputMethodContext::SetReturnKeyState() */ - virtual void SetReturnKeyState( bool visible ) {} + virtual void SetReturnKeyState(bool visible) + { + } /** * @copydoc Dali::InputMethodContext::AutoEnableInputPanel() */ - virtual void AutoEnableInputPanel( bool enabled ) {} + virtual void AutoEnableInputPanel(bool enabled) + { + } /** * @copydoc Dali::InputMethodContext::ShowInputPanel() */ - virtual void ShowInputPanel() {} + virtual void ShowInputPanel() + { + } /** * @copydoc Dali::InputMethodContext::HideInputPanel() */ - virtual void HideInputPanel() {} + virtual void HideInputPanel() + { + } /** * @copydoc Dali::InputMethodContext::GetKeyboardType() */ - virtual Dali::InputMethodContext::KeyboardType GetKeyboardType() { return Dali::InputMethodContext::KeyboardType(); } + virtual Dali::InputMethodContext::KeyboardType GetKeyboardType() + { + return Dali::InputMethodContext::KeyboardType(); + } /** * @copydoc Dali::InputMethodContext::GetInputPanelLocale() */ - virtual std::string GetInputPanelLocale() { return std::string(); } + virtual std::string GetInputPanelLocale() + { + return std::string(); + } /** * @copydoc Dali::InputMethodContext::SetContentMIMETypes() */ - virtual void SetContentMIMETypes( const std::string& mimeTypes ) {} + virtual void SetContentMIMETypes(const std::string& mimeTypes) + { + } /** * @copydoc Dali::InputMethodContext::FilterEventKey() */ - virtual bool FilterEventKey( const Dali::KeyEvent& keyEvent ) { return false; } + virtual bool FilterEventKey(const Dali::KeyEvent& keyEvent) + { + return false; + } /** * @copydoc Dali::InputMethodContext::AllowTextPrediction() */ - virtual void AllowTextPrediction( bool prediction ) {} + virtual void AllowTextPrediction(bool prediction) + { + } /** * @copydoc Dali::InputMethodContext::IsTextPredictionAllowed() */ - virtual bool IsTextPredictionAllowed() const { return false; } + virtual bool IsTextPredictionAllowed() const + { + return false; + } /** * @copydoc Dali::InputMethodContext::SetInputPanelLanguage() */ - virtual void SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) {} + virtual void SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) + { + } /** * @copydoc Dali::InputMethodContext::GetInputPanelLanguage() */ - virtual Dali::InputMethodContext::InputPanelLanguage GetInputPanelLanguage() const { return Dali::InputMethodContext::InputPanelLanguage(); } + virtual Dali::InputMethodContext::InputPanelLanguage GetInputPanelLanguage() const + { + return Dali::InputMethodContext::InputPanelLanguage(); + } /** * @copydoc Dali::InputMethodContext::SetInputPanelPosition() */ - virtual void SetInputPanelPosition( unsigned int x, unsigned int y ) {} + virtual void SetInputPanelPosition(unsigned int x, unsigned int y) + { + } /** * @copydoc Dali::InputMethodContext::GetPreeditStyle() */ - virtual void GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const {} - -public: // Signals + virtual void GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const + { + } +public: // Signals /** * @copydoc Dali::InputMethodContext::ActivatedSignal() */ - ActivatedSignalType& ActivatedSignal() { return mActivatedSignal; } + ActivatedSignalType& ActivatedSignal() + { + return mActivatedSignal; + } /** * @copydoc Dali::InputMethodContext::EventReceivedSignal() */ - KeyboardEventSignalType& EventReceivedSignal() { return mEventSignal; } + KeyboardEventSignalType& EventReceivedSignal() + { + return mEventSignal; + } /** * @copydoc Dali::InputMethodContext::StatusChangedSignal() */ - StatusSignalType& StatusChangedSignal() { return mKeyboardStatusSignal; } + StatusSignalType& StatusChangedSignal() + { + return mKeyboardStatusSignal; + } /** * @copydoc Dali::InputMethodContext::ResizedSignal() */ - KeyboardResizedSignalType& ResizedSignal() { return mKeyboardResizeSignal; } + KeyboardResizedSignalType& ResizedSignal() + { + return mKeyboardResizeSignal; + } /** * @copydoc Dali::InputMethodContext::LanguageChangedSignal() */ - LanguageChangedSignalType& LanguageChangedSignal() { return mKeyboardLanguageChangedSignal; } + LanguageChangedSignalType& LanguageChangedSignal() + { + return mKeyboardLanguageChangedSignal; + } /** * @copydoc Dali::InputMethodContext::KeyboardTypeChangedSignal() */ - KeyboardTypeSignalType& KeyboardTypeChangedSignal() { return mKeyboardTypeChangedSignal; } + KeyboardTypeSignalType& KeyboardTypeChangedSignal() + { + return mKeyboardTypeChangedSignal; + } /** * @copydoc Dali::InputMethodContext::ContentReceivedSignal() */ - ContentReceivedSignalType& ContentReceivedSignal() { return mContentReceivedSignal; } + ContentReceivedSignalType& ContentReceivedSignal() + { + return mContentReceivedSignal; + } public: - /** * Constructor */ @@ -328,9 +436,8 @@ public: ~InputMethodContext() override = default; private: - - InputMethodContext( const InputMethodContext& ) = delete; - InputMethodContext& operator=( InputMethodContext& ) = delete; + InputMethodContext(const InputMethodContext&) = delete; + InputMethodContext& operator=(InputMethodContext&) = delete; protected: /** @@ -352,7 +459,7 @@ protected: }; }; - using OperationList = std::vector< std::function >; + using OperationList = std::vector >; /** * @brief Apply backup operations to the InputMethodContext @@ -360,21 +467,19 @@ protected: void ApplyBackupOperations(); protected: - - ActivatedSignalType mActivatedSignal; - KeyboardEventSignalType mEventSignal; - StatusSignalType mKeyboardStatusSignal; - KeyboardResizedSignalType mKeyboardResizeSignal; - LanguageChangedSignalType mKeyboardLanguageChangedSignal; - KeyboardTypeSignalType mKeyboardTypeChangedSignal; - ContentReceivedSignalType mContentReceivedSignal; - OperationList mBackupOperations; + ActivatedSignalType mActivatedSignal; + KeyboardEventSignalType mEventSignal; + StatusSignalType mKeyboardStatusSignal; + KeyboardResizedSignalType mKeyboardResizeSignal; + LanguageChangedSignalType mKeyboardLanguageChangedSignal; + KeyboardTypeSignalType mKeyboardTypeChangedSignal; + ContentReceivedSignalType mContentReceivedSignal; + OperationList mBackupOperations; public: - inline static Internal::Adaptor::InputMethodContext& GetImplementation(Dali::InputMethodContext& inputMethodContext) { - DALI_ASSERT_ALWAYS( inputMethodContext && "InputMethodContext handle is empty" ); + DALI_ASSERT_ALWAYS(inputMethodContext && "InputMethodContext handle is empty"); BaseObject& handle = inputMethodContext.GetBaseObject(); @@ -383,16 +488,14 @@ public: inline static const Internal::Adaptor::InputMethodContext& GetImplementation(const Dali::InputMethodContext& inputMethodContext) { - DALI_ASSERT_ALWAYS( inputMethodContext && "InputMethodContext handle is empty" ); + DALI_ASSERT_ALWAYS(inputMethodContext && "InputMethodContext handle is empty"); const BaseObject& handle = inputMethodContext.GetBaseObject(); return static_cast(handle); } - }; - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/input/common/key-grab.cpp b/dali/internal/input/common/key-grab.cpp index d7b07c2..7ac921f 100644 --- a/dali/internal/input/common/key-grab.cpp +++ b/dali/internal/input/common/key-grab.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,49 +23,44 @@ namespace Dali { - namespace KeyGrab { - -bool GrabKeyTopmost( Window window, Dali::KEY daliKey ) +bool GrabKeyTopmost(Window window, Dali::KEY daliKey) { - Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation( window ); - return windowImpl.GrabKey( daliKey, TOPMOST ); + Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation(window); + return windowImpl.GrabKey(daliKey, TOPMOST); } -bool UngrabKeyTopmost( Window window, Dali::KEY daliKey ) +bool UngrabKeyTopmost(Window window, Dali::KEY daliKey) { - Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation( window ); - return windowImpl.UngrabKey( daliKey ); + Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation(window); + return windowImpl.UngrabKey(daliKey); } -bool GrabKey( Window window, Dali::KEY daliKey, KeyGrabMode grabMode ) +bool GrabKey(Window window, Dali::KEY daliKey, KeyGrabMode grabMode) { - Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation( window ); - return windowImpl.GrabKey( daliKey, grabMode ); + Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation(window); + return windowImpl.GrabKey(daliKey, grabMode); } - -bool UngrabKey( Window window, Dali::KEY daliKey ) +bool UngrabKey(Window window, Dali::KEY daliKey) { - Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation( window ); - return windowImpl.UngrabKey( daliKey ); + Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation(window); + return windowImpl.UngrabKey(daliKey); } - -bool GrabKeyList( Window window, const Dali::Vector& daliKeyVector, const Dali::Vector& grabModeVector, Dali::Vector& returnVector) +bool GrabKeyList(Window window, const Dali::Vector& daliKeyVector, const Dali::Vector& grabModeVector, Dali::Vector& returnVector) { - Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation( window ); - return windowImpl.GrabKeyList( daliKeyVector, grabModeVector, returnVector ); + Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation(window); + return windowImpl.GrabKeyList(daliKeyVector, grabModeVector, returnVector); } -bool UngrabKeyList( Window window, const Dali::Vector& daliKeyVector, Dali::Vector& returnVector) +bool UngrabKeyList(Window window, const Dali::Vector& daliKeyVector, Dali::Vector& returnVector) { - Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation( window ); - return windowImpl.UngrabKeyList( daliKeyVector, returnVector ); + Dali::Internal::Adaptor::Window& windowImpl = Dali::GetImplementation(window); + return windowImpl.UngrabKeyList(daliKeyVector, returnVector); } } // namespace KeyGrab } // namespace Dali - diff --git a/dali/internal/input/common/key-impl.cpp b/dali/internal/input/common/key-impl.cpp index 49dd765..bcfd43c 100644 --- a/dali/internal/input/common/key-impl.cpp +++ b/dali/internal/input/common/key-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,24 +20,20 @@ // EXTERNAL INCLUDES #include -#include #include #include +#include #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace KeyLookup { - namespace { #if defined(DEBUG_ENABLED) @@ -45,62 +41,61 @@ Debug::Filter* gKeyExtensionLogFilter = Debug::Filter::New(Debug::NoLogging, fal #endif // Path for loading extension keys -const char* KEY_EXTENSION_PLUGIN_SO( "libdali2-key-extension.so" ); +const char* KEY_EXTENSION_PLUGIN_SO("libdali2-key-extension.so"); class KeyMap { - public: - - KeyMap(): - mExtensionKeyLookupTable(NULL), - mPlugin(NULL), - mHandle(NULL), - mCreateKeyExtensionPluginPtr(NULL), - mDestroyKeyExtensionPluginPtr(NULL), - mLookup( cmpString ), - mExtensionLookup( cmpString ), - mExtensionLookupCount(0), - mIsLookupTableInitialized( false ), - mIsExtensionLookupTableInitialized( false ) +public: + KeyMap() + : mExtensionKeyLookupTable(NULL), + mPlugin(NULL), + mHandle(NULL), + mCreateKeyExtensionPluginPtr(NULL), + mDestroyKeyExtensionPluginPtr(NULL), + mLookup(cmpString), + mExtensionLookup(cmpString), + mExtensionLookupCount(0), + mIsLookupTableInitialized(false), + mIsExtensionLookupTableInitialized(false) { } ~KeyMap() { - if( mHandle != NULL ) + if(mHandle != NULL) { - if( mDestroyKeyExtensionPluginPtr != NULL ) + if(mDestroyKeyExtensionPluginPtr != NULL) { - mDestroyKeyExtensionPluginPtr( mPlugin ); + mDestroyKeyExtensionPluginPtr(mPlugin); } - dlclose( mHandle ); + dlclose(mHandle); } } - int GetDaliKeyEnum( const char* keyName ) + int GetDaliKeyEnum(const char* keyName) { // If lookup table is not initialized, initialize lookup table - if( !mIsLookupTableInitialized ) + if(!mIsLookupTableInitialized) { InitializeLookupTable(); } - Lookup::const_iterator i = mLookup.find( keyName ); + Lookup::const_iterator i = mLookup.find(keyName); - if( i == mLookup.end() ) + if(i == mLookup.end()) { // If cannot find target, find it at the extension // If extension lookup table is not initialized, initialize extension lookup table - if( !mIsExtensionLookupTableInitialized ) + if(!mIsExtensionLookupTableInitialized) { InitializeExtensionLookupTable(); } // Find at extension - i = mExtensionLookup.find( keyName ); + i = mExtensionLookup.find(keyName); - if( i == mExtensionLookup.end() ) + if(i == mExtensionLookup.end()) { return -1; } @@ -115,31 +110,31 @@ class KeyMap } } - const char* GetKeyName( int daliKeyCode ) + const char* GetKeyName(int daliKeyCode) { // If lookup table is not initialized, initialize lookup table - if( !mIsLookupTableInitialized ) + if(!mIsLookupTableInitialized) { InitializeLookupTable(); } - for( size_t i = 0; i < KEY_LOOKUP_COUNT ; ++i ) + for(size_t i = 0; i < KEY_LOOKUP_COUNT; ++i) { - if( KeyLookupTable[i].daliKeyCode == daliKeyCode ) + if(KeyLookupTable[i].daliKeyCode == daliKeyCode) { return KeyLookupTable[i].keyName; } } // If extension lookup table is not initialized, initialize extension lookup table - if( !mIsExtensionLookupTableInitialized ) + if(!mIsExtensionLookupTableInitialized) { InitializeExtensionLookupTable(); } - for( size_t i = 0; i < mExtensionLookupCount ; ++i ) + for(size_t i = 0; i < mExtensionLookupCount; ++i) { - if( mExtensionKeyLookupTable[i].daliKeyCode == daliKeyCode ) + if(mExtensionKeyLookupTable[i].daliKeyCode == daliKeyCode) { return mExtensionKeyLookupTable[i].keyName; } @@ -148,28 +143,28 @@ class KeyMap return NULL; } - bool IsDeviceButton( const char* keyName ) + bool IsDeviceButton(const char* keyName) { // If lookup table is not initialized, initialize lookup table - if( !mIsLookupTableInitialized ) + if(!mIsLookupTableInitialized) { InitializeLookupTable(); } - Lookup::const_iterator i = mLookup.find( keyName ); - if( i == mLookup.end() ) + Lookup::const_iterator i = mLookup.find(keyName); + if(i == mLookup.end()) { // If cannot find target, find it at the extension. // If extension lookup table is not initialized, initialize extension lookup table - if( !mIsExtensionLookupTableInitialized ) + if(!mIsExtensionLookupTableInitialized) { InitializeExtensionLookupTable(); } // Find at extension - i = mExtensionLookup.find( keyName ); + i = mExtensionLookup.find(keyName); - if( i == mExtensionLookup.end() ) + if(i == mExtensionLookup.end()) { return false; } @@ -186,15 +181,13 @@ class KeyMap return false; } - - private: - +private: void InitializeLookupTable() { // create the lookup - for( size_t i = 0; i < KEY_LOOKUP_COUNT ; ++i ) + for(size_t i = 0; i < KEY_LOOKUP_COUNT; ++i) { - mLookup[ KeyLookupTable[i].keyName ] = DaliKeyType( KeyLookupTable[i].daliKeyCode, KeyLookupTable[i].deviceButton ); + mLookup[KeyLookupTable[i].keyName] = DaliKeyType(KeyLookupTable[i].daliKeyCode, KeyLookupTable[i].deviceButton); } mIsLookupTableInitialized = true; @@ -204,49 +197,49 @@ class KeyMap { // Try to load extension keys char* error = NULL; - mHandle = dlopen( KEY_EXTENSION_PLUGIN_SO, RTLD_NOW ); - error = dlerror(); + mHandle = dlopen(KEY_EXTENSION_PLUGIN_SO, RTLD_NOW); + error = dlerror(); - if( mHandle == NULL ) + if(mHandle == NULL) { - DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get handle from libdali2-key-extension.so\n" ); + DALI_LOG_INFO(gKeyExtensionLogFilter, Debug::General, "Failed to get handle from libdali2-key-extension.so\n"); return; } - if( error != NULL ) + if(error != NULL) { - DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "dlopen got error: %s \n", error ); + DALI_LOG_INFO(gKeyExtensionLogFilter, Debug::General, "dlopen got error: %s \n", error); return; } - mCreateKeyExtensionPluginPtr = reinterpret_cast< CreateKeyExtensionPluginFunction >( dlsym( mHandle, "CreateKeyExtensionPlugin" ) ); - if( mCreateKeyExtensionPluginPtr == NULL ) + mCreateKeyExtensionPluginPtr = reinterpret_cast(dlsym(mHandle, "CreateKeyExtensionPlugin")); + if(mCreateKeyExtensionPluginPtr == NULL) { - DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get CreateKeyExtensionPlugin function\n" ); + DALI_LOG_INFO(gKeyExtensionLogFilter, Debug::General, "Failed to get CreateKeyExtensionPlugin function\n"); return; } mPlugin = mCreateKeyExtensionPluginPtr(); - if( mPlugin == NULL ) + if(mPlugin == NULL) { - DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to create plugin object\n" ); + DALI_LOG_INFO(gKeyExtensionLogFilter, Debug::General, "Failed to create plugin object\n"); return; } - mDestroyKeyExtensionPluginPtr = reinterpret_cast< DestroyKeyExtensionPluginFunction >( dlsym( mHandle, "DestroyKeyExtensionPlugin" ) ); - if( mDestroyKeyExtensionPluginPtr == NULL ) + mDestroyKeyExtensionPluginPtr = reinterpret_cast(dlsym(mHandle, "DestroyKeyExtensionPlugin")); + if(mDestroyKeyExtensionPluginPtr == NULL) { - DALI_LOG_INFO( gKeyExtensionLogFilter, Debug::General, "Failed to get DestroyKeyExtensionPlugin function\n" ); + DALI_LOG_INFO(gKeyExtensionLogFilter, Debug::General, "Failed to get DestroyKeyExtensionPlugin function\n"); return; } mExtensionKeyLookupTable = mPlugin->GetKeyLookupTable(); - mExtensionLookupCount = mPlugin->GetKeyLookupTableCount(); + mExtensionLookupCount = mPlugin->GetKeyLookupTableCount(); // Add extension keys to lookup - for( size_t i = 0; i < mExtensionLookupCount ; ++i ) + for(size_t i = 0; i < mExtensionLookupCount; ++i) { - mExtensionLookup[ mExtensionKeyLookupTable[i].keyName ] = DaliKeyType( mExtensionKeyLookupTable[i].daliKeyCode, mExtensionKeyLookupTable[i].deviceButton ); + mExtensionLookup[mExtensionKeyLookupTable[i].keyName] = DaliKeyType(mExtensionKeyLookupTable[i].daliKeyCode, mExtensionKeyLookupTable[i].deviceButton); } mIsExtensionLookupTableInitialized = true; @@ -255,50 +248,52 @@ class KeyMap /** * compare function, to compare string by pointer */ - static bool cmpString( const char* a, const char* b) + static bool cmpString(const char* a, const char* b) { return strcmp(a, b) < 0; } - KeyExtensionPlugin::KeyLookup* mExtensionKeyLookupTable; ///< Lookup table for extension keys - Dali::KeyExtensionPlugin* mPlugin; ///< Key extension plugin handle - void* mHandle; ///< Handle for the loaded library - typedef Dali::KeyExtensionPlugin* (*CreateKeyExtensionPluginFunction)(); ///< Type of function pointer to get KeyExtensionPlugin object - typedef void (*DestroyKeyExtensionPluginFunction)( Dali::KeyExtensionPlugin* plugin ); ///< Type of function pointer to delete KeyExtensionPlugin object - CreateKeyExtensionPluginFunction mCreateKeyExtensionPluginPtr; ///< Function pointer to get KeyExtensionPlugin object - DestroyKeyExtensionPluginFunction mDestroyKeyExtensionPluginPtr; ///< Function pointer to delete KeyExtensionPlugin object + KeyExtensionPlugin::KeyLookup* mExtensionKeyLookupTable; ///< Lookup table for extension keys + Dali::KeyExtensionPlugin* mPlugin; ///< Key extension plugin handle + void* mHandle; ///< Handle for the loaded library + typedef Dali::KeyExtensionPlugin* (*CreateKeyExtensionPluginFunction)(); ///< Type of function pointer to get KeyExtensionPlugin object + typedef void (*DestroyKeyExtensionPluginFunction)(Dali::KeyExtensionPlugin* plugin); ///< Type of function pointer to delete KeyExtensionPlugin object + CreateKeyExtensionPluginFunction mCreateKeyExtensionPluginPtr; ///< Function pointer to get KeyExtensionPlugin object + DestroyKeyExtensionPluginFunction mDestroyKeyExtensionPluginPtr; ///< Function pointer to delete KeyExtensionPlugin object + + typedef std::pair DaliKeyType; + + typedef std::map Lookup; - typedef std::pair< int, bool > DaliKeyType; - typedef std::map Lookup; Lookup mLookup; Lookup mExtensionLookup; - size_t mExtensionLookupCount; ///< count of extension lookup table - bool mIsLookupTableInitialized; ///< flag for basic lookup table initialization - bool mIsExtensionLookupTableInitialized; ///< flag for extension lookup table initialization + size_t mExtensionLookupCount; ///< count of extension lookup table + bool mIsLookupTableInitialized; ///< flag for basic lookup table initialization + bool mIsExtensionLookupTableInitialized; ///< flag for extension lookup table initialization }; KeyMap globalKeyLookup; -} // un-named name space +} // namespace -bool IsKey( const Dali::KeyEvent& keyEvent, Dali::KEY daliKey) +bool IsKey(const Dali::KeyEvent& keyEvent, Dali::KEY daliKey) { - int key = globalKeyLookup.GetDaliKeyEnum( keyEvent.GetKeyName().c_str() ); + int key = globalKeyLookup.GetDaliKeyEnum(keyEvent.GetKeyName().c_str()); return daliKey == key; } -bool IsDeviceButton( const char* keyName ) +bool IsDeviceButton(const char* keyName) { - return globalKeyLookup.IsDeviceButton( keyName ); + return globalKeyLookup.IsDeviceButton(keyName); } -const char* GetKeyName( Dali::KEY daliKey ) +const char* GetKeyName(Dali::KEY daliKey) { - return globalKeyLookup.GetKeyName( daliKey ); + return globalKeyLookup.GetKeyName(daliKey); } -int GetDaliKeyCode( const char* keyName ) +int GetDaliKeyCode(const char* keyName) { - return globalKeyLookup.GetDaliKeyEnum( keyName ); + return globalKeyLookup.GetDaliKeyEnum(keyName); } } // namespace KeyLookup diff --git a/dali/internal/input/common/key-impl.h b/dali/internal/input/common/key-impl.h index 2bc22b6..8e3c9f4 100644 --- a/dali/internal/input/common/key-impl.h +++ b/dali/internal/input/common/key-impl.h @@ -2,7 +2,7 @@ #define DALI_KEY_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,58 +19,54 @@ */ // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Implementation of the Key matching */ namespace KeyLookup { - struct KeyLookup { - const char* keyName; ///< XF86 key name + const char* keyName; ///< XF86 key name const Dali::KEY daliKeyCode; ///< Dali key code - const bool deviceButton; ///< Whether the key is from a button on the device + const bool deviceButton; ///< Whether the key is from a button on the device }; -extern KeyLookup KeyLookupTable[]; +extern KeyLookup KeyLookupTable[]; extern const std::size_t KEY_LOOKUP_COUNT; /** * @copydoc Dali::IsKey() */ -bool IsKey( const Dali::KeyEvent& keyEvent, Dali::KEY daliKey ); +bool IsKey(const Dali::KeyEvent& keyEvent, Dali::KEY daliKey); /** * Check if a the given key name string is a button on the device itself. * @param keyName A pointer to the key name * @return true if the key is matched, false if not */ -bool IsDeviceButton( const char* keyName ); +bool IsDeviceButton(const char* keyName); /** * Get a key name from a dali key code. * @param daliKey The dali key code * @return The key name. NULL if the daliKey does not exist in the supported key lookup table. */ -const char* GetKeyName( Dali::KEY daliKey ); +const char* GetKeyName(Dali::KEY daliKey); /** * @copydoc Dali::DevelKey::GetDaliKeyCode() */ -int GetDaliKeyCode( const char* keyName ); +int GetDaliKeyCode(const char* keyName); } // namespace KeyLookup diff --git a/dali/internal/input/common/keyboard.cpp b/dali/internal/input/common/keyboard.cpp index 5731d39..6167de5 100644 --- a/dali/internal/input/common/keyboard.cpp +++ b/dali/internal/input/common/keyboard.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,21 +23,18 @@ namespace Dali { - namespace Keyboard { - -bool SetRepeatInfo( float rate, float delay ) +bool SetRepeatInfo(float rate, float delay) { - return Dali::Internal::Adaptor::WindowSystem::SetKeyboardRepeatInfo( rate, delay ); + return Dali::Internal::Adaptor::WindowSystem::SetKeyboardRepeatInfo(rate, delay); } -bool GetRepeatInfo( float& rate, float& delay ) +bool GetRepeatInfo(float& rate, float& delay) { - return Dali::Internal::Adaptor::WindowSystem::GetKeyboardRepeatInfo( rate, delay ); + return Dali::Internal::Adaptor::WindowSystem::GetKeyboardRepeatInfo(rate, delay); } } // namespace Keyboard } // namespace Dali - diff --git a/dali/internal/input/common/physical-keyboard-impl.cpp b/dali/internal/input/common/physical-keyboard-impl.cpp index ec7523a..1ace22c 100644 --- a/dali/internal/input/common/physical-keyboard-impl.cpp +++ b/dali/internal/input/common/physical-keyboard-impl.cpp @@ -25,22 +25,19 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - Dali::PhysicalKeyboard PhysicalKeyboard::New() { Dali::PhysicalKeyboard keyboardHandle; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { - keyboardHandle = Dali::PhysicalKeyboard( new PhysicalKeyboard() ); - service.Register( typeid( keyboardHandle ), keyboardHandle ); + keyboardHandle = Dali::PhysicalKeyboard(new PhysicalKeyboard()); + service.Register(typeid(keyboardHandle), keyboardHandle); } return keyboardHandle; @@ -51,13 +48,13 @@ Dali::PhysicalKeyboard PhysicalKeyboard::Get() Dali::PhysicalKeyboard keyboardHandle; Dali::SingletonService service = SingletonService::Get(); - if ( service ) + if(service) { - BaseHandle handle = service.GetSingleton( typeid( Dali::PhysicalKeyboard ) ); - if( handle ) + BaseHandle handle = service.GetSingleton(typeid(Dali::PhysicalKeyboard)); + if(handle) { // If so, downcast the handle of singleton to focus manager - keyboardHandle = Dali::PhysicalKeyboard( dynamic_cast< PhysicalKeyboard* >( handle.GetObjectPtr() ) ); + keyboardHandle = Dali::PhysicalKeyboard(dynamic_cast(handle.GetObjectPtr())); } } @@ -69,14 +66,14 @@ bool PhysicalKeyboard::IsAttached() const return mAttached; } -void PhysicalKeyboard::KeyReceived( bool fromPhysicalKeyboard ) +void PhysicalKeyboard::KeyReceived(bool fromPhysicalKeyboard) { - if ( mAttached != fromPhysicalKeyboard ) + if(mAttached != fromPhysicalKeyboard) { mAttached = fromPhysicalKeyboard; - Dali::PhysicalKeyboard handle( this ); - mStatusChangedSignal.Emit( handle ); + Dali::PhysicalKeyboard handle(this); + mStatusChangedSignal.Emit(handle); } } @@ -85,12 +82,12 @@ PhysicalKeyboard::~PhysicalKeyboard() } PhysicalKeyboard::PhysicalKeyboard() -: mAttached( false ) +: mAttached(false) { } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/input/common/physical-keyboard-impl.h b/dali/internal/input/common/physical-keyboard-impl.h index 4aa6181..d5ced2a 100644 --- a/dali/internal/input/common/physical-keyboard-impl.h +++ b/dali/internal/input/common/physical-keyboard-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_PHYSICAL_KEYBOARD_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,17 +26,13 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class PhysicalKeyboard : public BaseObject { public: - /** * Creates a new instance of the PhysicalKeyboard. */ @@ -57,27 +53,28 @@ public: * keyboard then the parameter should be true. * @param[in] fromPhysicalKeyboard true if received from a physical keyboard, false otherwise. */ - void KeyReceived( bool fromPhysicalKeyboard ); + void KeyReceived(bool fromPhysicalKeyboard); // Signals /** * @copydoc Dali::PhysicalKeyboard::StatusChangedSignal() */ - Dali::PhysicalKeyboard::PhysicalKeyboardSignalType& StatusChangedSignal() { return mStatusChangedSignal; } + Dali::PhysicalKeyboard::PhysicalKeyboardSignalType& StatusChangedSignal() + { + return mStatusChangedSignal; + } protected: - /** * A reference counted object may only be deleted by calling Unreference() */ ~PhysicalKeyboard() override; private: - // Undefined - PhysicalKeyboard( const PhysicalKeyboard& ); - PhysicalKeyboard& operator=( PhysicalKeyboard& ); + PhysicalKeyboard(const PhysicalKeyboard&); + PhysicalKeyboard& operator=(PhysicalKeyboard&); /** * Constructor @@ -85,9 +82,8 @@ private: PhysicalKeyboard(); private: - Dali::PhysicalKeyboard::PhysicalKeyboardSignalType mStatusChangedSignal; ///< Status changed signal - bool mAttached; ///< true if the physical keyboard is attached, false otherwise + bool mAttached; ///< true if the physical keyboard is attached, false otherwise }; } // namespace Adaptor @@ -96,22 +92,22 @@ private: // Helpers for public-api forwarding methods -inline static Internal::Adaptor::PhysicalKeyboard& GetImplementation( PhysicalKeyboard& keyboard ) +inline static Internal::Adaptor::PhysicalKeyboard& GetImplementation(PhysicalKeyboard& keyboard) { - DALI_ASSERT_ALWAYS( keyboard && "PhysicalKeyboard handle is empty" ); + DALI_ASSERT_ALWAYS(keyboard && "PhysicalKeyboard handle is empty"); BaseObject& handle = keyboard.GetBaseObject(); - return static_cast< Internal::Adaptor::PhysicalKeyboard& >( handle ); + return static_cast(handle); } -inline static const Internal::Adaptor::PhysicalKeyboard& GetImplementation( const PhysicalKeyboard& keyboard ) +inline static const Internal::Adaptor::PhysicalKeyboard& GetImplementation(const PhysicalKeyboard& keyboard) { - DALI_ASSERT_ALWAYS( keyboard && "PhysicalKeyboard handle is empty" ); + DALI_ASSERT_ALWAYS(keyboard && "PhysicalKeyboard handle is empty"); const BaseObject& handle = keyboard.GetBaseObject(); - return static_cast< const Internal::Adaptor::PhysicalKeyboard& >( handle ); + return static_cast(handle); } } // namespace Dali diff --git a/dali/internal/input/common/virtual-keyboard-impl.h b/dali/internal/input/common/virtual-keyboard-impl.h old mode 100755 new mode 100644 index da0fccb..f169807 --- a/dali/internal/input/common/virtual-keyboard-impl.h +++ b/dali/internal/input/common/virtual-keyboard-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_VIRTUAL_KEYBOARD_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,19 +23,15 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Implementation of the virtual keyboard namespace */ namespace VirtualKeyboard { - /** * @copydoc Dali::VirtualKeyboard::Show() */ @@ -54,12 +50,12 @@ bool IsVisible(); /** * @copydoc Dali::VirtualKeyboard::ApplySettings() */ -void ApplySettings( const Property::Map& settingsMap ); +void ApplySettings(const Property::Map& settingsMap); /** * @copydoc Dali::VirtualKeyboard::SetReturnKeyType() */ -void SetReturnKeyType( const Dali::InputMethod::ButtonAction::Type type ); +void SetReturnKeyType(const Dali::InputMethod::ButtonAction::Type type); /** * @copydoc Dali::VirtualKeyboard::GetReturnKeyType() diff --git a/dali/internal/input/generic/input-method-context-factory-generic.cpp b/dali/internal/input/generic/input-method-context-factory-generic.cpp index d952a8a..647609a 100644 --- a/dali/internal/input/generic/input-method-context-factory-generic.cpp +++ b/dali/internal/input/generic/input-method-context-factory-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,28 +24,24 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class InputMethodContext; namespace InputMethodContextFactory { - // InputMethodContext Factory to be implemented by the platform -InputMethodContextPtr CreateInputMethodContext( Dali::Actor actor ) +InputMethodContextPtr CreateInputMethodContext(Dali::Actor actor) { - return Dali::Internal::Adaptor::InputMethodContextGeneric::New( actor ); + return Dali::Internal::Adaptor::InputMethodContextGeneric::New(actor); } -} +} // namespace InputMethodContextFactory -} +} // namespace Adaptor -} +} // namespace Internal -} +} // namespace Dali diff --git a/dali/internal/input/generic/input-method-context-impl-generic.cpp b/dali/internal/input/generic/input-method-context-impl-generic.cpp index 43206c2..38003b8 100644 --- a/dali/internal/input/generic/input-method-context-impl-generic.cpp +++ b/dali/internal/input/generic/input-method-context-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,27 +26,24 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_INPUT_METHOD_CONTEXT"); #endif -} +} // namespace -InputMethodContextPtr InputMethodContextGeneric::New( Dali::Actor actor ) +InputMethodContextPtr InputMethodContextGeneric::New(Dali::Actor actor) { InputMethodContextPtr manager; - if( actor && Dali::Adaptor::IsAvailable() ) + if(actor && Dali::Adaptor::IsAvailable()) { - manager = new InputMethodContextGeneric( actor ); + manager = new InputMethodContextGeneric(actor); } return manager; @@ -54,13 +51,13 @@ InputMethodContextPtr InputMethodContextGeneric::New( Dali::Actor actor ) void InputMethodContextGeneric::Finalize() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::Finalize\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::Finalize\n"); DisconnectCallbacks(); } -InputMethodContextGeneric::InputMethodContextGeneric( Dali::Actor actor ) +InputMethodContextGeneric::InputMethodContextGeneric(Dali::Actor actor) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::InputMethodContextGeneric\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::InputMethodContextGeneric\n"); Initialize(); } @@ -71,241 +68,241 @@ InputMethodContextGeneric::~InputMethodContextGeneric() void InputMethodContextGeneric::Initialize() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::Initialize\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::Initialize\n"); } void InputMethodContextGeneric::ConnectCallbacks() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::ConnectCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::ConnectCallbacks\n"); } void InputMethodContextGeneric::DisconnectCallbacks() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::DisconnectCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::DisconnectCallbacks\n"); } void InputMethodContextGeneric::Activate() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::Activate\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::Activate\n"); } void InputMethodContextGeneric::Deactivate() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::Deactivate\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::Deactivate\n"); } void InputMethodContextGeneric::Reset() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::Reset\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::Reset\n"); } ImfContext* InputMethodContextGeneric::GetContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetContext\n"); return nullptr; } bool InputMethodContextGeneric::RestoreAfterFocusLost() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::RestoreAfterFocusLost\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::RestoreAfterFocusLost\n"); return false; } -void InputMethodContextGeneric::SetRestoreAfterFocusLost( bool toggle ) +void InputMethodContextGeneric::SetRestoreAfterFocusLost(bool toggle) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetRestoreAfterFocusLost\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetRestoreAfterFocusLost\n"); } -void InputMethodContextGeneric::PreEditChanged( void*, ImfContext* imfContext, void* event_info ) +void InputMethodContextGeneric::PreEditChanged(void*, ImfContext* imfContext, void* event_info) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::PreEditChanged\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::PreEditChanged\n"); } -void InputMethodContextGeneric::CommitReceived( void*, ImfContext* imfContext, void* event_info ) +void InputMethodContextGeneric::CommitReceived(void*, ImfContext* imfContext, void* event_info) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::CommitReceived\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::CommitReceived\n"); } -bool InputMethodContextGeneric::RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) +bool InputMethodContextGeneric::RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::RetrieveSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::RetrieveSurrounding\n"); return false; } -void InputMethodContextGeneric::DeleteSurrounding( void* data, ImfContext* imfContext, void* event_info ) +void InputMethodContextGeneric::DeleteSurrounding(void* data, ImfContext* imfContext, void* event_info) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::DeleteSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::DeleteSurrounding\n"); } -void InputMethodContextGeneric::SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextGeneric::SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SendPrivateCommand\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SendPrivateCommand\n"); } -void InputMethodContextGeneric::SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextGeneric::SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SendCommitContent\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SendCommitContent\n"); } void InputMethodContextGeneric::NotifyCursorPosition() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::NotifyCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::NotifyCursorPosition\n"); } -void InputMethodContextGeneric::SetCursorPosition( unsigned int cursorPosition ) +void InputMethodContextGeneric::SetCursorPosition(unsigned int cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetCursorPosition\n"); } unsigned int InputMethodContextGeneric::GetCursorPosition() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetCursorPosition\n"); return 0; } -void InputMethodContextGeneric::SetSurroundingText( const std::string& text ) +void InputMethodContextGeneric::SetSurroundingText(const std::string& text) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetSurroundingText\n"); } const std::string& InputMethodContextGeneric::GetSurroundingText() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetSurroundingText\n"); return ""; } -void InputMethodContextGeneric::NotifyTextInputMultiLine( bool multiLine ) +void InputMethodContextGeneric::NotifyTextInputMultiLine(bool multiLine) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::NotifyTextInputMultiLine\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::NotifyTextInputMultiLine\n"); } Dali::InputMethodContext::TextDirection InputMethodContextGeneric::GetTextDirection() { - Dali::InputMethodContext::TextDirection direction ( Dali::InputMethodContext::LEFT_TO_RIGHT ); + Dali::InputMethodContext::TextDirection direction(Dali::InputMethodContext::LEFT_TO_RIGHT); return direction; } Rect InputMethodContextGeneric::GetInputMethodArea() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputMethodArea\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputMethodArea\n"); int xPos, yPos, width, height; width = height = xPos = yPos = 0; - return Rect(xPos,yPos,width,height); + return Rect(xPos, yPos, width, height); } -void InputMethodContextGeneric::ApplyOptions( const InputMethodOptions& options ) +void InputMethodContextGeneric::ApplyOptions(const InputMethodOptions& options) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::ApplyOptions\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::ApplyOptions\n"); } -void InputMethodContextGeneric::SetInputPanelData( const std::string& data ) +void InputMethodContextGeneric::SetInputPanelData(const std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetInputPanelData\n"); } -void InputMethodContextGeneric::GetInputPanelData( std::string& data ) +void InputMethodContextGeneric::GetInputPanelData(std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputPanelData\n"); - data.assign( "" ); + data.assign(""); } Dali::InputMethodContext::State InputMethodContextGeneric::GetInputPanelState() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputPanelState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputPanelState\n"); return Dali::InputMethodContext::DEFAULT; } -void InputMethodContextGeneric::SetReturnKeyState( bool visible ) +void InputMethodContextGeneric::SetReturnKeyState(bool visible) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetReturnKeyState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetReturnKeyState\n"); } -void InputMethodContextGeneric::AutoEnableInputPanel( bool enabled ) +void InputMethodContextGeneric::AutoEnableInputPanel(bool enabled) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::AutoEnableInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::AutoEnableInputPanel\n"); } void InputMethodContextGeneric::ShowInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::ShowInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::ShowInputPanel\n"); } void InputMethodContextGeneric::HideInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::HideInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::HideInputPanel\n"); } Dali::InputMethodContext::KeyboardType InputMethodContextGeneric::GetKeyboardType() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetKeyboardType\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetKeyboardType\n"); return Dali::InputMethodContext::KeyboardType::SOFTWARE_KEYBOARD; } std::string InputMethodContextGeneric::GetInputPanelLocale() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputPanelLocale\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::GetInputPanelLocale\n"); std::string locale = ""; return locale; } -void InputMethodContextGeneric::SetContentMIMETypes( const std::string& mimeTypes ) +void InputMethodContextGeneric::SetContentMIMETypes(const std::string& mimeTypes) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetContentMIMETypes\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetContentMIMETypes\n"); } -bool InputMethodContextGeneric::FilterEventKey( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextGeneric::FilterEventKey(const Dali::KeyEvent& keyEvent) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::FilterEventKey\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::FilterEventKey\n"); return false; } -void InputMethodContextGeneric::AllowTextPrediction( bool prediction ) +void InputMethodContextGeneric::AllowTextPrediction(bool prediction) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::AllowTextPrediction\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::AllowTextPrediction\n"); } bool InputMethodContextGeneric::IsTextPredictionAllowed() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::IsTextPredictionAllowed\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::IsTextPredictionAllowed\n"); return false; } -void InputMethodContextGeneric::SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) +void InputMethodContextGeneric::SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextGeneric::SetInputPanelLanguage\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextGeneric::SetInputPanelLanguage\n"); } Dali::InputMethodContext::InputPanelLanguage InputMethodContextGeneric::GetInputPanelLanguage() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelLanguage\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelLanguage\n"); return Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC; } -void InputMethodContextGeneric::SetInputPanelPosition( unsigned int x, unsigned int y ) +void InputMethodContextGeneric::SetInputPanelPosition(unsigned int x, unsigned int y) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelPosition\n"); } -void InputMethodContextGeneric::GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const +void InputMethodContextGeneric::GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetPreeditStyle\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetPreeditStyle\n"); // Do Nothing } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/input/generic/input-method-context-impl-generic.h b/dali/internal/input/generic/input-method-context-impl-generic.h index 693d8de..ff83e50 100644 --- a/dali/internal/input/generic/input-method-context-impl-generic.h +++ b/dali/internal/input/generic/input-method-context-impl-generic.h @@ -2,7 +2,7 @@ #define __DALI_INTERNAL_INPUT_METHOD_CONTEXT_IMPL_GENERIC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Satisfies input API requirements for platforms without input method context support */ @@ -46,16 +43,15 @@ public: * @param[in] actor The actor that uses the new InputMethodContext instance. * @return InputMethodContext pointer */ - static InputMethodContextPtr New( Dali::Actor actor ); + static InputMethodContextPtr New(Dali::Actor actor); /** * Constructor * @param[in] actor The actor that uses the new InputMethodContext instance. */ - explicit InputMethodContextGeneric( Dali::Actor actor ); + explicit InputMethodContextGeneric(Dali::Actor actor); public: - /** * @brief Initializes member data. */ @@ -106,37 +102,37 @@ public: /** * @copydoc Dali::InputMethodContext::SetRestoreAfterFocusLost() */ - void SetRestoreAfterFocusLost( bool toggle ) override; + void SetRestoreAfterFocusLost(bool toggle) override; /** * @copydoc Dali::InputMethodContext::PreEditChanged() */ - void PreEditChanged( void* data, ImfContext* imfContext, void* eventInfo ) override; + void PreEditChanged(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - void CommitReceived( void* data, ImfContext* imfContext, void* eventInfo ) override; + void CommitReceived(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - bool RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) override; + bool RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) override; /** * @copydoc Dali::InputMethodContext::DeleteSurrounding() */ - void DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) override; + void DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::SendPrivateCommand() */ - void SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) override; + void SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::SendCommitContent() */ - void SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) override; + void SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) override; // Cursor related /** @@ -147,7 +143,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetCursorPosition() */ - void SetCursorPosition( unsigned int cursorPosition ) override; + void SetCursorPosition(unsigned int cursorPosition) override; /** * @copydoc Dali::InputMethodContext::GetCursorPosition() @@ -157,7 +153,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetSurroundingText() */ - void SetSurroundingText( const std::string& text ) override; + void SetSurroundingText(const std::string& text) override; /** * @copydoc Dali::InputMethodContext::GetSurroundingText() @@ -167,7 +163,7 @@ public: /** * @copydoc Dali::InputMethodContext::NotifyTextInputMultiLine() */ - void NotifyTextInputMultiLine( bool multiLine ) override; + void NotifyTextInputMultiLine(bool multiLine) override; /** * @copydoc Dali::InputMethodContext::GetTextDirection() @@ -182,17 +178,17 @@ public: /** * @copydoc Dali::InputMethodContext::ApplyOptions() */ - void ApplyOptions( const InputMethodOptions& options ) override; + void ApplyOptions(const InputMethodOptions& options) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelData() */ - void SetInputPanelData( const std::string& data ) override; + void SetInputPanelData(const std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelData() */ - void GetInputPanelData( std::string& data ) override; + void GetInputPanelData(std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelState() @@ -202,12 +198,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetReturnKeyState() */ - void SetReturnKeyState( bool visible ) override; + void SetReturnKeyState(bool visible) override; /** * @copydoc Dali::InputMethodContext::AutoEnableInputPanel() */ - void AutoEnableInputPanel( bool enabled ) override; + void AutoEnableInputPanel(bool enabled) override; /** * @copydoc Dali::InputMethodContext::ShowInputPanel() @@ -232,17 +228,17 @@ public: /** * @copydoc Dali::InputMethodContext::SetContentMIMETypes() */ - void SetContentMIMETypes( const std::string& mimeTypes ) override; + void SetContentMIMETypes(const std::string& mimeTypes) override; /** * @copydoc Dali::InputMethodContext::FilterEventKey() */ - bool FilterEventKey( const Dali::KeyEvent& keyEvent ) override; + bool FilterEventKey(const Dali::KeyEvent& keyEvent) override; /** * @copydoc Dali::InputMethodContext::AllowTextPrediction() */ - void AllowTextPrediction( bool prediction ) override; + void AllowTextPrediction(bool prediction) override; /** * @copydoc Dali::InputMethodContext::IsTextPredictionAllowed() @@ -252,7 +248,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelLanguage() */ - void SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) override; + void SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelLanguage() @@ -262,27 +258,25 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelPosition() */ - void SetInputPanelPosition( unsigned int x, unsigned int y ) override; + void SetInputPanelPosition(unsigned int x, unsigned int y) override; /** * @copydoc Dali::InputMethodContext::GetPreeditStyle() */ - void GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const override; + void GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const override; public: - /** * Destructor. */ virtual ~InputMethodContextGeneric(); private: - // Undefined copy constructor - InputMethodContextGeneric( const InputMethodContextGeneric& inputMethodContext) = delete; + InputMethodContextGeneric(const InputMethodContextGeneric& inputMethodContext) = delete; // Undefined assignment operator - InputMethodContextGeneric& operator=( const InputMethodContextGeneric& inputMethodContext ) = delete; + InputMethodContextGeneric& operator=(const InputMethodContextGeneric& inputMethodContext) = delete; }; } // namespace Adaptor diff --git a/dali/internal/input/generic/key-mapping-generic.cpp b/dali/internal/input/generic/key-mapping-generic.cpp index 0a7833e..b49d15a 100644 --- a/dali/internal/input/generic/key-mapping-generic.cpp +++ b/dali/internal/input/generic/key-mapping-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,14 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace KeyLookup { - // matches a DALI_KEY enum, to a key name +// clang-format off KeyLookup KeyLookupTable[]= { // more than one key name can be assigned to a single dali-key code @@ -88,8 +85,9 @@ KeyLookup KeyLookupTable[]= { "Control_R", static_cast( DevelKey::DALI_KEY_CONTROL_RIGHT ), false }, { "Return", static_cast( DevelKey::DALI_KEY_RETURN ), false } }; +// clang-format on -const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup )); +const std::size_t KEY_LOOKUP_COUNT = (sizeof(KeyLookupTable)) / (sizeof(KeyLookup)); } // namespace KeyLookup diff --git a/dali/internal/input/generic/virtual-keyboard-impl-generic.cpp b/dali/internal/input/generic/virtual-keyboard-impl-generic.cpp index 80994ec..00e276f 100644 --- a/dali/internal/input/generic/virtual-keyboard-impl-generic.cpp +++ b/dali/internal/input/generic/virtual-keyboard-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,72 +23,68 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace VirtualKeyboard { - namespace { #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_INPUT_METHOD_CONTEXT"); #endif -} +} // namespace void Show() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::Show\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::Show\n"); } void Hide() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::Hide\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::Hide\n"); } bool IsVisible() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::IsVisible\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::IsVisible\n"); return false; } -void ApplySettings( const Property::Map& settingsMap ) +void ApplySettings(const Property::Map& settingsMap) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::ApplySettings\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::ApplySettings\n"); } -void SetReturnKeyType( const InputMethod::ButtonAction::Type type ) +void SetReturnKeyType(const InputMethod::ButtonAction::Type type) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::SetReturnKeyType\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::SetReturnKeyType\n"); } Dali::InputMethod::ButtonAction::Type GetReturnKeyType() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::GetReturnKeyType\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::GetReturnKeyType\n"); return Dali::InputMethod::ButtonAction::DEFAULT; } -void EnablePrediction( const bool enable ) +void EnablePrediction(const bool enable) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::EnablePrediction\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::EnablePrediction\n"); } bool IsPredictionEnabled() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::IsPredictionEnabled\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::IsPredictionEnabled\n"); return false; } Rect GetSizeAndPosition() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::GetSizeAndPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::GetSizeAndPosition\n"); Rect ret; return ret; @@ -96,12 +92,12 @@ Rect GetSizeAndPosition() void RotateTo(int angle) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::RotateTo\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::RotateTo\n"); } Dali::VirtualKeyboard::TextDirection GetTextDirection() { - DALI_LOG_INFO( gLogFilter, Debug::General, "VirtualKeyboard::GetTextDirection\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VirtualKeyboard::GetTextDirection\n"); return Dali::VirtualKeyboard::LEFT_TO_RIGHT; } diff --git a/dali/internal/input/linux/dali-ecore-imf.h b/dali/internal/input/linux/dali-ecore-imf.h index 62aef33..dc0a333 100644 --- a/dali/internal/input/linux/dali-ecore-imf.h +++ b/dali/internal/input/linux/dali-ecore-imf.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_LINUX_DALI_ECORE_IMF_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_INPUT_LINUX_DALI_ECORE_IMF_H */ diff --git a/dali/internal/input/macos/input-method-context-factory-mac.cpp b/dali/internal/input/macos/input-method-context-factory-mac.cpp index 5a799c0..b8f0773 100644 --- a/dali/internal/input/macos/input-method-context-factory-mac.cpp +++ b/dali/internal/input/macos/input-method-context-factory-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ * */ -#include #include #include +#include namespace Dali { @@ -29,18 +29,15 @@ class InputMethodContext; namespace InputMethodContextFactory { - // InputMethodContext Factory to be implemented by the platform -InputMethodContextPtr CreateInputMethodContext( Dali::Actor actor ) +InputMethodContextPtr CreateInputMethodContext(Dali::Actor actor) { - return Dali::Internal::Adaptor::InputMethodContextCocoa::New( actor ); + return Dali::Internal::Adaptor::InputMethodContextCocoa::New(actor); } -} +} // namespace InputMethodContextFactory -} +} // namespace Adaptor - - -} -} +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/input/macos/input-method-context-impl-mac.cpp b/dali/internal/input/macos/input-method-context-impl-mac.cpp index ff4fc10..8c46548 100644 --- a/dali/internal/input/macos/input-method-context-impl-mac.cpp +++ b/dali/internal/input/macos/input-method-context-impl-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,42 +19,39 @@ #include // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES -#include #include #include #include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) -Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_INPUT_METHOD_CONTEXT" ); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_INPUT_METHOD_CONTEXT"); #endif -} +} // namespace -InputMethodContextPtr InputMethodContextCocoa::New( Dali::Actor actor ) +InputMethodContextPtr InputMethodContextCocoa::New(Dali::Actor actor) { InputMethodContextPtr manager; - if ( actor && Adaptor::IsAvailable() ) + if(actor && Adaptor::IsAvailable()) { - manager = new InputMethodContextCocoa( actor ); + manager = new InputMethodContextCocoa(actor); } return manager; @@ -64,14 +61,13 @@ void InputMethodContextCocoa::Finalize() { } -InputMethodContextCocoa::InputMethodContextCocoa( Dali::Actor actor ) -: mIMFCursorPosition( 0 ), +InputMethodContextCocoa::InputMethodContextCocoa(Dali::Actor actor) +: mIMFCursorPosition(0), mSurroundingText(), - mRestoreAfterFocusLost( false ), - mIdleCallbackConnected( false ) + mRestoreAfterFocusLost(false), + mIdleCallbackConnected(false) { - - actor.OnSceneSignal().Connect( this, &InputMethodContextCocoa::OnStaged ); + actor.OnSceneSignal().Connect(this, &InputMethodContextCocoa::OnStaged); } InputMethodContextCocoa::~InputMethodContextCocoa() @@ -106,12 +102,12 @@ void InputMethodContextCocoa::Deactivate() void InputMethodContextCocoa::Reset() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::Reset\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::Reset\n"); } ImfContext* InputMethodContextCocoa::GetContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetContext\n"); return NULL; } @@ -121,7 +117,7 @@ bool InputMethodContextCocoa::RestoreAfterFocusLost() const return mRestoreAfterFocusLost; } -void InputMethodContextCocoa::SetRestoreAfterFocusLost( bool toggle ) +void InputMethodContextCocoa::SetRestoreAfterFocusLost(bool toggle) { mRestoreAfterFocusLost = toggle; } @@ -131,26 +127,26 @@ void InputMethodContextCocoa::SetRestoreAfterFocusLost( bool toggle ) * We are still predicting what the user is typing. The latest string is what the InputMethodContext module thinks * the user wants to type. */ -void InputMethodContextCocoa::PreEditChanged( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextCocoa::PreEditChanged(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::PreEditChanged\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::PreEditChanged\n"); } -void InputMethodContextCocoa::CommitReceived( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextCocoa::CommitReceived(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::CommitReceived\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::CommitReceived\n"); - if ( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - const std::string keyString( static_cast( eventInfo ) ); + const std::string keyString(static_cast(eventInfo)); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::EventData eventData( Dali::InputMethodContext::COMMIT, keyString, 0, 0 ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, eventData ); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::EventData eventData(Dali::InputMethodContext::COMMIT, keyString, 0, 0); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, eventData); - if( callbackData.update ) + if(callbackData.update) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); + mIMFCursorPosition = static_cast(callbackData.cursorPosition); NotifyCursorPosition(); } @@ -162,25 +158,25 @@ void InputMethodContextCocoa::CommitReceived( void*, ImfContext* imfContext, voi * Here the InputMethodContext module wishes to know the string we are working with and where within the string the cursor is * We need to signal the application to tell us this information. */ -bool InputMethodContextCocoa::RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) +bool InputMethodContextCocoa::RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::RetrieveSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::RetrieveSurrounding\n"); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0 ); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, imfData); - if( callbackData.update ) + if(callbackData.update) { - if( text ) + if(text) { - *text = strdup( callbackData.currentText.c_str() ); + *text = strdup(callbackData.currentText.c_str()); } - if( cursorPosition ) + if(cursorPosition) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); - *cursorPosition = mIMFCursorPosition; + mIMFCursorPosition = static_cast(callbackData.cursorPosition); + *cursorPosition = mIMFCursorPosition; } } @@ -191,51 +187,51 @@ bool InputMethodContextCocoa::RetrieveSurrounding( void* data, ImfContext* imfCo * Called when an InputMethodContext delete surrounding event is received. * Here we tell the application that it should delete a certain range. */ -void InputMethodContextCocoa::DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextCocoa::DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::DeleteSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::DeleteSurrounding\n"); } void InputMethodContextCocoa::NotifyCursorPosition() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::NotifyCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::NotifyCursorPosition\n"); } -void InputMethodContextCocoa::SetCursorPosition( unsigned int cursorPosition ) +void InputMethodContextCocoa::SetCursorPosition(unsigned int cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetCursorPosition\n"); - mIMFCursorPosition = static_cast( cursorPosition ); + mIMFCursorPosition = static_cast(cursorPosition); } unsigned int InputMethodContextCocoa::GetCursorPosition() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetCursorPosition\n"); - return static_cast( mIMFCursorPosition ); + return static_cast(mIMFCursorPosition); } -void InputMethodContextCocoa::SetSurroundingText( const std::string& text ) +void InputMethodContextCocoa::SetSurroundingText(const std::string& text) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetSurroundingText\n"); mSurroundingText = text; } const std::string& InputMethodContextCocoa::GetSurroundingText() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetSurroundingText\n"); return mSurroundingText; } -void InputMethodContextCocoa::NotifyTextInputMultiLine( bool multiLine ) +void InputMethodContextCocoa::NotifyTextInputMultiLine(bool multiLine) { } Dali::InputMethodContext::TextDirection InputMethodContextCocoa::GetTextDirection() { - Dali::InputMethodContext::TextDirection direction ( Dali::InputMethodContext::LEFT_TO_RIGHT); + Dali::InputMethodContext::TextDirection direction(Dali::InputMethodContext::LEFT_TO_RIGHT); return direction; } @@ -246,63 +242,63 @@ Rect InputMethodContextCocoa::GetInputMethodArea() width = height = xPos = yPos = 0; - return Rect(xPos,yPos,width,height); + return Rect(xPos, yPos, width, height); } -void InputMethodContextCocoa::ApplyOptions( const InputMethodOptions& options ) +void InputMethodContextCocoa::ApplyOptions(const InputMethodOptions& options) { using namespace Dali::InputMethod::Category; int index; - if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) ) + if(mOptions.CompareAndSet(PANEL_LAYOUT, options, index)) { } - if ( mOptions.CompareAndSet(BUTTON_ACTION, options, index) ) + if(mOptions.CompareAndSet(BUTTON_ACTION, options, index)) { } - if ( mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index) ) + if(mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index)) { } - if ( mOptions.CompareAndSet(VARIATION, options, index) ) + if(mOptions.CompareAndSet(VARIATION, options, index)) { } } -void InputMethodContextCocoa::SetInputPanelData( const std::string& data ) +void InputMethodContextCocoa::SetInputPanelData(const std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetInputPanelData\n"); } -void InputMethodContextCocoa::GetInputPanelData( std::string& data ) +void InputMethodContextCocoa::GetInputPanelData(std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelData\n"); } Dali::InputMethodContext::State InputMethodContextCocoa::GetInputPanelState() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelState\n"); return Dali::InputMethodContext::DEFAULT; } -void InputMethodContextCocoa::SetReturnKeyState( bool visible ) +void InputMethodContextCocoa::SetReturnKeyState(bool visible) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetReturnKeyState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetReturnKeyState\n"); } -void InputMethodContextCocoa::AutoEnableInputPanel( bool enabled ) +void InputMethodContextCocoa::AutoEnableInputPanel(bool enabled) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::AutoEnableInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::AutoEnableInputPanel\n"); } void InputMethodContextCocoa::ShowInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::ShowInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::ShowInputPanel\n"); } void InputMethodContextCocoa::HideInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::HideInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::HideInputPanel\n"); } Dali::InputMethodContext::KeyboardType InputMethodContextCocoa::GetKeyboardType() @@ -312,81 +308,80 @@ Dali::InputMethodContext::KeyboardType InputMethodContextCocoa::GetKeyboardType( std::string InputMethodContextCocoa::GetInputPanelLocale() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelLocale\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelLocale\n"); std::string locale = ""; return locale; } -void InputMethodContextCocoa::SetContentMIMETypes( const std::string& mimeTypes ) +void InputMethodContextCocoa::SetContentMIMETypes(const std::string& mimeTypes) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetContentMIMETypes\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetContentMIMETypes\n"); } -bool InputMethodContextCocoa::FilterEventKey( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextCocoa::FilterEventKey(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); - if ( ! KeyLookup::IsDeviceButton( keyEvent.GetKeyName().c_str() )) + if(!KeyLookup::IsDeviceButton(keyEvent.GetKeyName().c_str())) { //check whether it's key down or key up event - if ( keyEvent.GetState() == Dali::KeyEvent::DOWN ) + if(keyEvent.GetState() == Dali::KeyEvent::DOWN) { - eventHandled = ProcessEventKeyDown( keyEvent ); + eventHandled = ProcessEventKeyDown(keyEvent); } - else if ( keyEvent.GetState() == Dali::KeyEvent::UP ) + else if(keyEvent.GetState() == Dali::KeyEvent::UP) { - eventHandled = ProcessEventKeyUp( keyEvent ); + eventHandled = ProcessEventKeyUp(keyEvent); } } return eventHandled; } -void InputMethodContextCocoa::SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) +void InputMethodContextCocoa::SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetInputPanelLanguage\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetInputPanelLanguage\n"); } Dali::InputMethodContext::InputPanelLanguage InputMethodContextCocoa::GetInputPanelLanguage() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelLanguage\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetInputPanelLanguage\n"); return Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC; } -void InputMethodContextCocoa::SetInputPanelPosition( unsigned int x, unsigned int y ) +void InputMethodContextCocoa::SetInputPanelPosition(unsigned int x, unsigned int y) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::SetInputPanelPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::SetInputPanelPosition\n"); } -void InputMethodContextCocoa::GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const +void InputMethodContextCocoa::GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextCocoa::GetPreeditStyle\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextCocoa::GetPreeditStyle\n"); attrs = mPreeditAttrs; } -bool InputMethodContextCocoa::ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextCocoa::ProcessEventKeyDown(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); return eventHandled; } -bool InputMethodContextCocoa::ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextCocoa::ProcessEventKeyUp(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); return eventHandled; } -void InputMethodContextCocoa::OnStaged( Dali::Actor actor ) +void InputMethodContextCocoa::OnStaged(Dali::Actor actor) { // Reset Finalize(); Initialize(); } -} // Adaptor - -} // Internal +} // namespace Adaptor -} // Dali +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/input/macos/input-method-context-impl-mac.h b/dali/internal/input/macos/input-method-context-impl-mac.h index 7e4b10b..a651c08 100644 --- a/dali/internal/input/macos/input-method-context-impl-mac.h +++ b/dali/internal/input/macos/input-method-context-impl-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,15 +26,12 @@ namespace Dali { - class RenderSurface; namespace Internal { - namespace Adaptor { - class InputMethodContextCocoa : public Dali::Internal::Adaptor::InputMethodContext, public Dali::ConnectionTracker { public: @@ -44,16 +41,15 @@ public: * @param[in] actor The actor that uses the new InputMethodContext instance. * @return InputMethodContext pointer */ - static InputMethodContextPtr New( Dali::Actor actor ); + static InputMethodContextPtr New(Dali::Actor actor); /** * Constructor * @param[in] win32Window, The window is created by application. */ - explicit InputMethodContextCocoa( Dali::Actor actor ); + explicit InputMethodContextCocoa(Dali::Actor actor); public: - /** * @brief Initializes member data. */ @@ -104,39 +100,41 @@ public: /** * @copydoc Dali::InputMethodContext::SetRestoreAfterFocusLost() */ - void SetRestoreAfterFocusLost( bool toggle ) override; + void SetRestoreAfterFocusLost(bool toggle) override; /** * @copydoc Dali::InputMethodContext::PreEditChanged() */ - void PreEditChanged( void* data, ImfContext* imfContext, void* eventInfo ) override; + void PreEditChanged(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - void CommitReceived( void* data, ImfContext* imfContext, void* eventInfo ) override; + void CommitReceived(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - bool RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) override; + bool RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) override; /** * @copydoc Dali::InputMethodContext::DeleteSurrounding() */ - void DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) override; + void DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::SendPrivateCommand() */ - void SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) override - {} + void SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) override + { + } /** * @copydoc Dali::InputMethodContext::SendCommitContent() */ - void SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) override - {} + void SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) override + { + } // Cursor related /** @@ -147,7 +145,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetCursorPosition() */ - void SetCursorPosition( unsigned int cursorPosition ) override; + void SetCursorPosition(unsigned int cursorPosition) override; /** * @copydoc Dali::InputMethodContext::GetCursorPosition() @@ -157,7 +155,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetSurroundingText() */ - void SetSurroundingText( const std::string& text ) override; + void SetSurroundingText(const std::string& text) override; /** * @copydoc Dali::InputMethodContext::GetSurroundingText() @@ -167,7 +165,7 @@ public: /** * @copydoc Dali::InputMethodContext::NotifyTextInputMultiLine() */ - void NotifyTextInputMultiLine( bool multiLine ) override; + void NotifyTextInputMultiLine(bool multiLine) override; /** * @copydoc Dali::InputMethodContext::GetTextDirection() @@ -182,17 +180,17 @@ public: /** * @copydoc Dali::InputMethodContext::ApplyOptions() */ - void ApplyOptions( const InputMethodOptions& options ) override; + void ApplyOptions(const InputMethodOptions& options) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelData() */ - void SetInputPanelData( const std::string& data ) override; + void SetInputPanelData(const std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelData() */ - void GetInputPanelData( std::string& data ) override; + void GetInputPanelData(std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelState() @@ -202,12 +200,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetReturnKeyState() */ - void SetReturnKeyState( bool visible ) override; + void SetReturnKeyState(bool visible) override; /** * @copydoc Dali::InputMethodContext::AutoEnableInputPanel() */ - void AutoEnableInputPanel( bool enabled ) override; + void AutoEnableInputPanel(bool enabled) override; /** * @copydoc Dali::InputMethodContext::ShowInputPanel() @@ -232,17 +230,17 @@ public: /** * @copydoc Dali::InputMethodContext::SetContentMIMETypes() */ - void SetContentMIMETypes( const std::string& mimeTypes ) override; + void SetContentMIMETypes(const std::string& mimeTypes) override; /** * @copydoc Dali::InputMethodContext::FilterEventKey() */ - bool FilterEventKey( const Dali::KeyEvent& keyEvent ) override; + bool FilterEventKey(const Dali::KeyEvent& keyEvent) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelLanguage() */ - void SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) override; + void SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelLanguage() @@ -252,22 +250,21 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelPosition() */ - void SetInputPanelPosition( unsigned int x, unsigned int y ) override; + void SetInputPanelPosition(unsigned int x, unsigned int y) override; /** * @copydoc Dali::InputMethodContext::GetPreeditStyle() */ - void GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const override; + void GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const override; private: - /** * @brief Process event key down, whether filter a key to isf. * * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyDown(const Dali::KeyEvent& keyEvent); /** * @brief Process event key up, whether filter a key to isf. @@ -275,35 +272,34 @@ private: * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyUp(const Dali::KeyEvent& keyEvent); /** * Called when the binded actor is added to a window. */ - void OnStaged( Dali::Actor actor ); + void OnStaged(Dali::Actor actor); public: - /** * Destructor. */ virtual ~InputMethodContextCocoa(); private: - // Undefined copy constructor - InputMethodContextCocoa( const InputMethodContextCocoa& inputMethodContext) = delete; + InputMethodContextCocoa(const InputMethodContextCocoa& inputMethodContext) = delete; // Undefined assignment operator - InputMethodContextCocoa& operator=( const InputMethodContextCocoa& inputMethodContext ) = delete; + InputMethodContextCocoa& operator=(const InputMethodContextCocoa& inputMethodContext) = delete; private: - int mIMFCursorPosition; + int mIMFCursorPosition; std::string mSurroundingText; - bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. - bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected. - InputMethodOptions mOptions; + bool mRestoreAfterFocusLost : 1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. + bool mIdleCallbackConnected : 1; ///< Whether the idle callback is already connected. + InputMethodOptions mOptions; + Dali::InputMethodContext::PreEditAttributeDataContainer mPreeditAttrs; ///< Stores preedit attribute data }; diff --git a/dali/internal/input/macos/key-mapping-mac.cpp b/dali/internal/input/macos/key-mapping-mac.cpp index 4c268cc..3c569c8 100644 --- a/dali/internal/input/macos/key-mapping-mac.cpp +++ b/dali/internal/input/macos/key-mapping-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ namespace Dali::Internal::Adaptor::KeyLookup { - // matches a DALI_KEY enum, to key name +// clang-format off KeyLookup KeyLookupTable[]= { { "Escape", DALI_KEY_ESCAPE, false }, @@ -36,7 +36,8 @@ KeyLookup KeyLookupTable[]= { "Delete", static_cast( DevelKey::DALI_KEY_DELETE ), false }, { "Control", static_cast( DevelKey::DALI_KEY_CONTROL_LEFT ), false }, }; +// clang-format on -const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup )); +const std::size_t KEY_LOOKUP_COUNT = (sizeof(KeyLookupTable)) / (sizeof(KeyLookup)); -} +} // namespace Dali::Internal::Adaptor::KeyLookup diff --git a/dali/internal/input/macos/virtual-keyboard-impl-mac.cpp b/dali/internal/input/macos/virtual-keyboard-impl-mac.cpp index cbe01df..3c992ea 100644 --- a/dali/internal/input/macos/virtual-keyboard-impl-mac.cpp +++ b/dali/internal/input/macos/virtual-keyboard-impl-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +20,12 @@ namespace Dali::Internal::Adaptor::VirtualKeyboard { - void Show() { } void Hide() { - } bool IsVisible() @@ -35,14 +33,12 @@ bool IsVisible() return false; } -void ApplySettings( const Property::Map& settingsMap ) +void ApplySettings(const Property::Map& settingsMap) { - } -void EnablePrediction( const bool enable ) +void EnablePrediction(const bool enable) { - } bool IsPredictionEnabled() @@ -83,7 +79,7 @@ void RotateTo(int angle) { } -void SetReturnKeyType( const InputMethod::ButtonAction::Type type ) +void SetReturnKeyType(const InputMethod::ButtonAction::Type type) { } diff --git a/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.cpp b/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.cpp old mode 100755 new mode 100644 index 3d56d24..f42b02e --- a/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.cpp +++ b/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -30,16 +30,12 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace VirtualKeyboard { - namespace { #if defined(DEBUG_ENABLED) @@ -49,32 +45,32 @@ Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VIR #define TOKEN_STRING(x) #x //forward declarations -void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value ); -void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value ); +void InputPanelGeometryChangedCallback(void* data, Ecore_IMF_Context* context, int value); +void InputPanelLanguageChangeCallback(void* data, Ecore_IMF_Context* context, int value); // Signals Dali::VirtualKeyboard::StatusSignalType gKeyboardStatusSignal; Dali::VirtualKeyboard::VoidSignalType gKeyboardResizeSignal; Dali::VirtualKeyboard::VoidSignalType gKeyboardLanguageChangedSignal; -void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value ) +void InputPanelStateChangeCallback(void* data, Ecore_IMF_Context* context, int value) { - switch (value) + switch(value) { case ECORE_IMF_INPUT_PANEL_STATE_SHOW: { - DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_SHOW\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_SHOW\n"); - gKeyboardStatusSignal.Emit( true ); + gKeyboardStatusSignal.Emit(true); break; } case ECORE_IMF_INPUT_PANEL_STATE_HIDE: { - DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_HIDE\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VKB ECORE_IMF_INPUT_PANEL_STATE_HIDE\n"); - gKeyboardStatusSignal.Emit( false ); + gKeyboardStatusSignal.Emit(false); break; } @@ -88,17 +84,17 @@ void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int } } -void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value ) +void InputPanelLanguageChangeCallback(void* data, Ecore_IMF_Context* context, int value) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelLanguageChangeCallback\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VKB InputPanelLanguageChangeCallback\n"); // Emit the signal that the language has changed gKeyboardLanguageChangedSignal.Emit(); } -void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value ) +void InputPanelGeometryChangedCallback(void* data, Ecore_IMF_Context* context, int value) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VKB InputPanelGeometryChangedCallback\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VKB InputPanelGeometryChangedCallback\n"); // Emit signal that the keyboard is resized gKeyboardResizeSignal.Emit(); @@ -106,71 +102,71 @@ void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, } // unnamed namespace -void ConnectCallbacks( Ecore_IMF_Context *imfContext ) +void ConnectCallbacks(Ecore_IMF_Context* imfContext) { - if( imfContext ) + if(imfContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VKB ConnectPanelCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VKB ConnectPanelCallbacks\n"); - ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, NULL ); - ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, NULL ); - ecore_imf_context_input_panel_event_callback_add( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, NULL ); + ecore_imf_context_input_panel_event_callback_add(imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, NULL); + ecore_imf_context_input_panel_event_callback_add(imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, NULL); + ecore_imf_context_input_panel_event_callback_add(imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, NULL); } } -void DisconnectCallbacks( Ecore_IMF_Context *imfContext ) +void DisconnectCallbacks(Ecore_IMF_Context* imfContext) { - if( imfContext ) + if(imfContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "VKB DisconnectPanelCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "VKB DisconnectPanelCallbacks\n"); - ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback ); - ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback ); - ecore_imf_context_input_panel_event_callback_del( imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback ); + ecore_imf_context_input_panel_event_callback_del(imfContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback); + ecore_imf_context_input_panel_event_callback_del(imfContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback); + ecore_imf_context_input_panel_event_callback_del(imfContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback); } } void Show() { - DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Show() is deprecated and will be removed from next release. Use InputMethodContext.Activate() instead.\n" ); + DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Show() is deprecated and will be removed from next release. Use InputMethodContext.Activate() instead.\n"); } void Hide() { - DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Hide() is deprecated and will be removed from next release. Use InputMethodContext.Deactivate() instead.\n" ); + DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: Hide() is deprecated and will be removed from next release. Use InputMethodContext.Deactivate() instead.\n"); } bool IsVisible() { - DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: IsVisible() is deprecated and will be removed from next release.\n" ); + DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: IsVisible() is deprecated and will be removed from next release.\n"); return false; } -void ApplySettings( const Property::Map& settingsMap ) +void ApplySettings(const Property::Map& settingsMap) { using namespace InputMethod; // Allows exclusion of namespace in TOKEN_STRING. - for ( unsigned long i = 0, count = settingsMap.Count(); i < count; ++i ) + for(unsigned long i = 0, count = settingsMap.Count(); i < count; ++i) { - Property::Key key = settingsMap.GetKeyAt( i ); - if( key.type == Property::Key::INDEX ) + Property::Key key = settingsMap.GetKeyAt(i); + if(key.type == Property::Key::INDEX) { continue; } Property::Value item = settingsMap.GetValue(i); - if ( key == TOKEN_STRING( BUTTON_ACTION ) ) + if(key == TOKEN_STRING(BUTTON_ACTION)) { - if ( item.GetType() == Property::INTEGER ) + if(item.GetType() == Property::INTEGER) { - int value = item.Get< int >(); - VirtualKeyboard::SetReturnKeyType( static_cast(value) ); + int value = item.Get(); + VirtualKeyboard::SetReturnKeyType(static_cast(value)); } } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "Provided Settings Key not supported\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Provided Settings Key not supported\n"); } } } @@ -188,15 +184,15 @@ Rect GetSizeAndPosition() { int xPos, yPos, width, height; - DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: GetSizeAndPosition() is deprecated and will be removed from next release. Use InputMethodContext.GetInputMethodArea() instead.\n" ); + DALI_LOG_WARNING_NOFN("DEPRECATION WARNING: GetSizeAndPosition() is deprecated and will be removed from next release. Use InputMethodContext.GetInputMethodArea() instead.\n"); width = height = xPos = yPos = 0; - return Rect(xPos,yPos,width,height); + return Rect(xPos, yPos, width, height); } Dali::VirtualKeyboard::TextDirection GetTextDirection() { - Dali::VirtualKeyboard::TextDirection direction ( Dali::VirtualKeyboard::LEFT_TO_RIGHT ); + Dali::VirtualKeyboard::TextDirection direction(Dali::VirtualKeyboard::LEFT_TO_RIGHT); return direction; } diff --git a/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.h b/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.h index 0226342..8ea3b90 100644 --- a/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.h +++ b/dali/internal/input/tizen-wayland/ecore-virtual-keyboard.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ECORE_VIRTUAL_KEYBOARD_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,32 +26,28 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Implementation of the virtual keyboard namespace */ namespace VirtualKeyboard { - /** * Connect the virtual keyboard callbacks. * To get the virtual keyboard callbacks then you have to connect these callback. * If you don't connect callbacks, you can't get virtual keyboard signals. * The signals are StatusChangedSignal, ResizedSignal and LanguageChangedSignal. */ -void ConnectCallbacks( Ecore_IMF_Context *imfContext ); +void ConnectCallbacks(Ecore_IMF_Context* imfContext); /** * Disconnect the virtual keyboard callbacks. * The signals are StatusChangedSignal, ResizedSignal and LanguageChangedSignal. */ -void DisconnectCallbacks( Ecore_IMF_Context *imfContext ); +void DisconnectCallbacks(Ecore_IMF_Context* imfContext); } // namespace VirtualKeyboard diff --git a/dali/internal/input/tizen-wayland/input-method-context-factory-ecore-wl.cpp b/dali/internal/input/tizen-wayland/input-method-context-factory-ecore-wl.cpp old mode 100755 new mode 100644 index a30e996..74a2e25 --- a/dali/internal/input/tizen-wayland/input-method-context-factory-ecore-wl.cpp +++ b/dali/internal/input/tizen-wayland/input-method-context-factory-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ * */ -#include #include #include +#include namespace Dali { @@ -29,18 +29,15 @@ class InputMethodContext; namespace InputMethodContextFactory { - // InputMethodContext Factory to be implemented by the platform -InputMethodContextPtr CreateInputMethodContext( Dali::Actor actor ) +InputMethodContextPtr CreateInputMethodContext(Dali::Actor actor) { - return Dali::Internal::Adaptor::InputMethodContextEcoreWl::New( actor ); -} - -} - + return Dali::Internal::Adaptor::InputMethodContextEcoreWl::New(actor); } +} // namespace InputMethodContextFactory +} // namespace Adaptor -} -} \ No newline at end of file +} // namespace Internal +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.cpp b/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.cpp old mode 100755 new mode 100644 index 36cb13a..c15f14b --- a/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.cpp +++ b/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,68 +28,63 @@ #include #endif -#include -#include -#include #include #include +#include +#include +#include // INTERNAL INCLUDES -#include #include #include #include #include #include +#include Ecore_IMF_Input_Panel_Layout panelLayoutMap[] = -{ - ECORE_IMF_INPUT_PANEL_LAYOUT_NORMAL, - ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBER, - ECORE_IMF_INPUT_PANEL_LAYOUT_EMAIL, - ECORE_IMF_INPUT_PANEL_LAYOUT_URL, - ECORE_IMF_INPUT_PANEL_LAYOUT_PHONENUMBER, - ECORE_IMF_INPUT_PANEL_LAYOUT_IP, - ECORE_IMF_INPUT_PANEL_LAYOUT_MONTH, - ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBERONLY, - ECORE_IMF_INPUT_PANEL_LAYOUT_HEX, - ECORE_IMF_INPUT_PANEL_LAYOUT_TERMINAL, - ECORE_IMF_INPUT_PANEL_LAYOUT_PASSWORD, - ECORE_IMF_INPUT_PANEL_LAYOUT_DATETIME, - ECORE_IMF_INPUT_PANEL_LAYOUT_EMOTICON, - ECORE_IMF_INPUT_PANEL_LAYOUT_VOICE -}; + { + ECORE_IMF_INPUT_PANEL_LAYOUT_NORMAL, + ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBER, + ECORE_IMF_INPUT_PANEL_LAYOUT_EMAIL, + ECORE_IMF_INPUT_PANEL_LAYOUT_URL, + ECORE_IMF_INPUT_PANEL_LAYOUT_PHONENUMBER, + ECORE_IMF_INPUT_PANEL_LAYOUT_IP, + ECORE_IMF_INPUT_PANEL_LAYOUT_MONTH, + ECORE_IMF_INPUT_PANEL_LAYOUT_NUMBERONLY, + ECORE_IMF_INPUT_PANEL_LAYOUT_HEX, + ECORE_IMF_INPUT_PANEL_LAYOUT_TERMINAL, + ECORE_IMF_INPUT_PANEL_LAYOUT_PASSWORD, + ECORE_IMF_INPUT_PANEL_LAYOUT_DATETIME, + ECORE_IMF_INPUT_PANEL_LAYOUT_EMOTICON, + ECORE_IMF_INPUT_PANEL_LAYOUT_VOICE}; Ecore_IMF_Autocapital_Type autoCapitalMap[] = -{ - ECORE_IMF_AUTOCAPITAL_TYPE_NONE, - ECORE_IMF_AUTOCAPITAL_TYPE_WORD, - ECORE_IMF_AUTOCAPITAL_TYPE_SENTENCE, - ECORE_IMF_AUTOCAPITAL_TYPE_ALLCHARACTER, + { + ECORE_IMF_AUTOCAPITAL_TYPE_NONE, + ECORE_IMF_AUTOCAPITAL_TYPE_WORD, + ECORE_IMF_AUTOCAPITAL_TYPE_SENTENCE, + ECORE_IMF_AUTOCAPITAL_TYPE_ALLCHARACTER, }; Ecore_IMF_Input_Panel_Return_Key_Type returnKeyTypeMap[] = -{ - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND, - ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN -}; + { + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND, + ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN}; namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) @@ -103,27 +98,27 @@ size_t Utf8SequenceLength(const unsigned char leadByte) { size_t length = 0; - if( ( leadByte & 0x80 ) == 0 ) //ASCII character (lead bit zero) + if((leadByte & 0x80) == 0) //ASCII character (lead bit zero) { length = 1; } - else if( ( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx + else if((leadByte & 0xe0) == 0xc0) //110x xxxx { length = 2; } - else if( ( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx + else if((leadByte & 0xf0) == 0xe0) //1110 xxxx { length = 3; } - else if( ( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx + else if((leadByte & 0xf8) == 0xf0) //1111 0xxx { length = 4; } - else if( ( leadByte & 0xfc ) == 0xf8 ) //1111 10xx + else if((leadByte & 0xfc) == 0xf8) //1111 10xx { length = 5; } - else if( ( leadByte & 0xfe ) == 0xfc ) //1111 110x + else if((leadByte & 0xfe) == 0xfc) //1111 110x { length = 6; } @@ -132,30 +127,30 @@ size_t Utf8SequenceLength(const unsigned char leadByte) } // Static function calls used by ecore 'c' style callback registration -void Commit( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void Commit(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - inputMethodContext->CommitReceived( data, imfContext, eventInfo ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + inputMethodContext->CommitReceived(data, imfContext, eventInfo); } } -void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void PreEdit(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - inputMethodContext->PreEditChanged( data, imfContext, eventInfo ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + inputMethodContext->PreEditChanged(data, imfContext, eventInfo); } } -Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition ) +Eina_Bool ImfRetrieveSurrounding(void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition) { - if ( data ) + if(data) { - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - return inputMethodContext->RetrieveSurrounding( data, imfContext, text, cursorPosition ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + return inputMethodContext->RetrieveSurrounding(data, imfContext, text, cursorPosition); } else { @@ -163,24 +158,24 @@ Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char } } -void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int value ) +void InputPanelStateChangeCallback(void* data, Ecore_IMF_Context* context, int value) { - if (!data) + if(!data) { return; } - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - switch (value) + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + switch(value) { case ECORE_IMF_INPUT_PANEL_STATE_SHOW: { - inputMethodContext->StatusChangedSignal().Emit( true ); + inputMethodContext->StatusChangedSignal().Emit(true); break; } case ECORE_IMF_INPUT_PANEL_STATE_HIDE: { - inputMethodContext->StatusChangedSignal().Emit( false ); + inputMethodContext->StatusChangedSignal().Emit(false); break; } @@ -193,48 +188,48 @@ void InputPanelStateChangeCallback( void* data, Ecore_IMF_Context* context, int } } -void InputPanelLanguageChangeCallback( void* data, Ecore_IMF_Context* context, int value ) +void InputPanelLanguageChangeCallback(void* data, Ecore_IMF_Context* context, int value) { - if (!data) + if(!data) { return; } - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); // Emit the signal that the language has changed inputMethodContext->LanguageChangedSignal().Emit(value); } -void InputPanelGeometryChangedCallback ( void *data, Ecore_IMF_Context *context, int value ) +void InputPanelGeometryChangedCallback(void* data, Ecore_IMF_Context* context, int value) { - if (!data) + if(!data) { return; } - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); // Emit signal that the keyboard is resized inputMethodContext->ResizedSignal().Emit(value); } -void InputPanelKeyboardTypeChangedCallback( void *data, Ecore_IMF_Context *context, int value ) +void InputPanelKeyboardTypeChangedCallback(void* data, Ecore_IMF_Context* context, int value) { - if( !data ) + if(!data) { return; } - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - switch (value) + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + switch(value) { case ECORE_IMF_INPUT_PANEL_SW_KEYBOARD_MODE: { // Emit Signal that the keyboard type is changed to Software Keyboard - inputMethodContext->KeyboardTypeChangedSignal().Emit( Dali::InputMethodContext::KeyboardType::SOFTWARE_KEYBOARD ); + inputMethodContext->KeyboardTypeChangedSignal().Emit(Dali::InputMethodContext::KeyboardType::SOFTWARE_KEYBOARD); break; } case ECORE_IMF_INPUT_PANEL_HW_KEYBOARD_MODE: { // Emit Signal that the keyboard type is changed to Hardware Keyboard - inputMethodContext->KeyboardTypeChangedSignal().Emit( Dali::InputMethodContext::KeyboardType::HARDWARE_KEYBOARD ); + inputMethodContext->KeyboardTypeChangedSignal().Emit(Dali::InputMethodContext::KeyboardType::HARDWARE_KEYBOARD); break; } } @@ -244,51 +239,51 @@ void InputPanelKeyboardTypeChangedCallback( void *data, Ecore_IMF_Context *conte * Called when an IMF delete surrounding event is received. * Here we tell the application that it should delete a certain range. */ -void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void ImfDeleteSurrounding(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - inputMethodContext->DeleteSurrounding( data, imfContext, eventInfo ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + inputMethodContext->DeleteSurrounding(data, imfContext, eventInfo); } } /** * Called when the input method sends a private command. */ -void PrivateCommand( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void PrivateCommand(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - inputMethodContext->SendPrivateCommand( data, imfContext, eventInfo ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + inputMethodContext->SendPrivateCommand(data, imfContext, eventInfo); } } /** * Called when the input method commits content, such as an image. */ -void CommitContent( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void CommitContent(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextEcoreWl* inputMethodContext = static_cast< InputMethodContextEcoreWl* >( data ); - inputMethodContext->SendCommitContent( data, imfContext, eventInfo ); + InputMethodContextEcoreWl* inputMethodContext = static_cast(data); + inputMethodContext->SendCommitContent(data, imfContext, eventInfo); } } -int GetWindowIdFromActor( Dali::Actor actor ) +int GetWindowIdFromActor(Dali::Actor actor) { int windowId = kUninitializedWindowId; - if( actor.GetProperty< bool >( Dali::Actor::Property::CONNECTED_TO_SCENE ) ) + if(actor.GetProperty(Dali::Actor::Property::CONNECTED_TO_SCENE)) { - Any nativeWindowHandle = Dali::Integration::SceneHolder::Get( actor ).GetNativeHandle(); + Any nativeWindowHandle = Dali::Integration::SceneHolder::Get(actor).GetNativeHandle(); #ifdef ECORE_WAYLAND2 - windowId = ecore_wl2_window_id_get( AnyCast< Ecore_Wl2_Window* >( nativeWindowHandle ) ); + windowId = ecore_wl2_window_id_get(AnyCast(nativeWindowHandle)); #else - windowId = ecore_wl_window_id_get( AnyCast< Ecore_Wl_Window* >( nativeWindowHandle ) ); + windowId = ecore_wl_window_id_get(AnyCast(nativeWindowHandle)); #endif } @@ -297,44 +292,44 @@ int GetWindowIdFromActor( Dali::Actor actor ) BaseHandle Create() { - return Dali::InputMethodContext::New( Dali::Actor() ); + return Dali::InputMethodContext::New(Dali::Actor()); } -Dali::TypeRegistration type( typeid(Dali::InputMethodContext), typeid(Dali::BaseHandle), Create ); +Dali::TypeRegistration type(typeid(Dali::InputMethodContext), typeid(Dali::BaseHandle), Create); } // unnamed namespace -InputMethodContextPtr InputMethodContextEcoreWl::New( Dali::Actor actor ) +InputMethodContextPtr InputMethodContextEcoreWl::New(Dali::Actor actor) { InputMethodContextPtr inputMethodContext; // Create instance only if the adaptor is available and the valid actor exists - if ( actor && Dali::Adaptor::IsAvailable() ) + if(actor && Dali::Adaptor::IsAvailable()) { - inputMethodContext = new InputMethodContextEcoreWl( actor ); + inputMethodContext = new InputMethodContextEcoreWl(actor); } return inputMethodContext; } void InputMethodContextEcoreWl::Finalize() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContext::Finalize\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContext::Finalize\n"); DisconnectCallbacks(); DeleteContext(); } -InputMethodContextEcoreWl::InputMethodContextEcoreWl( Dali::Actor actor ) +InputMethodContextEcoreWl::InputMethodContextEcoreWl(Dali::Actor actor) : mIMFContext(), - mIMFCursorPosition( 0 ), + mIMFCursorPosition(0), mSurroundingText(), - mRestoreAfterFocusLost( false ), - mIdleCallbackConnected( false ), - mWindowId( GetWindowIdFromActor( actor ) ) + mRestoreAfterFocusLost(false), + mIdleCallbackConnected(false), + mWindowId(GetWindowIdFromActor(actor)) { ecore_imf_init(); - actor.OnSceneSignal().Connect( this, &InputMethodContextEcoreWl::OnStaged ); + actor.OnSceneSignal().Connect(this, &InputMethodContextEcoreWl::OnStaged); } InputMethodContextEcoreWl::~InputMethodContextEcoreWl() @@ -352,40 +347,40 @@ void InputMethodContextEcoreWl::Initialize() void InputMethodContextEcoreWl::CreateContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContext::CreateContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContext::CreateContext\n"); - if( mWindowId == kUninitializedWindowId ) + if(mWindowId == kUninitializedWindowId) { return; } - const char *contextId = ecore_imf_context_default_id_get(); - if( contextId ) + const char* contextId = ecore_imf_context_default_id_get(); + if(contextId) { - mIMFContext = ecore_imf_context_add( contextId ); + mIMFContext = ecore_imf_context_add(contextId); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_client_window_set( mIMFContext, reinterpret_cast< void* >( mWindowId ) ); + ecore_imf_context_client_window_set(mIMFContext, reinterpret_cast(mWindowId)); } else { - DALI_LOG_WARNING( "InputMethodContext Unable to get IMFContext\n" ); + DALI_LOG_WARNING("InputMethodContext Unable to get IMFContext\n"); } } else { - DALI_LOG_WARNING( "InputMethodContext Unable to get IMFContext\n" ); + DALI_LOG_WARNING("InputMethodContext Unable to get IMFContext\n"); } } void InputMethodContextEcoreWl::DeleteContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::DeleteContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::DeleteContext\n"); - if ( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_del( mIMFContext ); + ecore_imf_context_del(mIMFContext); mIMFContext = NULL; } } @@ -393,41 +388,41 @@ void InputMethodContextEcoreWl::DeleteContext() // Callbacks for predicitive text support. void InputMethodContextEcoreWl::ConnectCallbacks() { - if ( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::ConnectCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::ConnectCallbacks\n"); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this ); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this ); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this ); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand, this ); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT_CONTENT, CommitContent, this ); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand, this); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_COMMIT_CONTENT, CommitContent, this); - ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, this ); - ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, this ); - ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, this ); - ecore_imf_context_input_panel_event_callback_add( mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback, this ); + ecore_imf_context_input_panel_event_callback_add(mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback, this); + ecore_imf_context_input_panel_event_callback_add(mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback, this); + ecore_imf_context_input_panel_event_callback_add(mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback, this); + ecore_imf_context_input_panel_event_callback_add(mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback, this); - ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this); + ecore_imf_context_retrieve_surrounding_callback_set(mIMFContext, ImfRetrieveSurrounding, this); } } void InputMethodContextEcoreWl::DisconnectCallbacks() { - if ( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::DisconnectCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::DisconnectCallbacks\n"); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit ); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit ); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding ); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand ); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT_CONTENT, CommitContent ); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_PRIVATE_COMMAND_SEND, PrivateCommand); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_COMMIT_CONTENT, CommitContent); - ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback ); - ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback ); - ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback ); - ecore_imf_context_input_panel_event_callback_del( mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback ); + ecore_imf_context_input_panel_event_callback_del(mIMFContext, ECORE_IMF_INPUT_PANEL_STATE_EVENT, InputPanelStateChangeCallback); + ecore_imf_context_input_panel_event_callback_del(mIMFContext, ECORE_IMF_INPUT_PANEL_LANGUAGE_EVENT, InputPanelLanguageChangeCallback); + ecore_imf_context_input_panel_event_callback_del(mIMFContext, ECORE_IMF_INPUT_PANEL_GEOMETRY_EVENT, InputPanelGeometryChangedCallback); + ecore_imf_context_input_panel_event_callback_del(mIMFContext, ECORE_IMF_INPUT_PANEL_KEYBOARD_MODE_EVENT, InputPanelKeyboardTypeChangedCallback); // We do not need to unset the retrieve surrounding callback. } @@ -438,26 +433,26 @@ void InputMethodContextEcoreWl::Activate() // Reset mIdleCallbackConnected mIdleCallbackConnected = false; - if ( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::Activate\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::Activate\n"); - ecore_imf_context_focus_in( mIMFContext ); + ecore_imf_context_focus_in(mIMFContext); // emit keyboard activated signal - Dali::InputMethodContext handle( this ); - mActivatedSignal.Emit( handle ); + Dali::InputMethodContext handle(this); + mActivatedSignal.Emit(handle); } } void InputMethodContextEcoreWl::Deactivate() { - if( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::Deactivate\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::Deactivate\n"); Reset(); - ecore_imf_context_focus_out( mIMFContext ); + ecore_imf_context_focus_out(mIMFContext); } // Reset mIdleCallbackConnected @@ -466,17 +461,17 @@ void InputMethodContextEcoreWl::Deactivate() void InputMethodContextEcoreWl::Reset() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::Reset\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::Reset\n"); - if ( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_reset( mIMFContext ); + ecore_imf_context_reset(mIMFContext); } } ImfContext* InputMethodContextEcoreWl::GetContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetContext\n"); return mIMFContext; } @@ -486,7 +481,7 @@ bool InputMethodContextEcoreWl::RestoreAfterFocusLost() const return mRestoreAfterFocusLost; } -void InputMethodContextEcoreWl::SetRestoreAfterFocusLost( bool toggle ) +void InputMethodContextEcoreWl::SetRestoreAfterFocusLost(bool toggle) { mRestoreAfterFocusLost = toggle; } @@ -496,15 +491,15 @@ void InputMethodContextEcoreWl::SetRestoreAfterFocusLost( bool toggle ) * We are still predicting what the user is typing. The latest string is what the InputMethodContext module thinks * the user wants to type. */ -void InputMethodContextEcoreWl::PreEditChanged( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextEcoreWl::PreEditChanged(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::PreEditChanged\n" ); - auto context = static_cast( imfContext ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::PreEditChanged\n"); + auto context = static_cast(imfContext); - char* preEditString( NULL ); - int cursorPosition( 0 ); + char* preEditString(NULL); + int cursorPosition(0); Eina_List* attrs = NULL; - Eina_List* l = NULL; + Eina_List* l = NULL; Ecore_IMF_Preedit_Attr* attr; @@ -512,34 +507,34 @@ void InputMethodContextEcoreWl::PreEditChanged( void*, ImfContext* imfContext, v // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string. // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string. - ecore_imf_context_preedit_string_with_attributes_get( context, &preEditString, &attrs, &cursorPosition ); + ecore_imf_context_preedit_string_with_attributes_get(context, &preEditString, &attrs, &cursorPosition); - if ( attrs ) + if(attrs) { // iterate through the list of attributes getting the type, start and end position. - for ( l = attrs, (attr = static_cast( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( attr = static_cast( eina_list_data_get(l) ) )) + for(l = attrs, (attr = static_cast(eina_list_data_get(l))); l; l = eina_list_next(l), (attr = static_cast(eina_list_data_get(l)))) { Dali::InputMethodContext::PreeditAttributeData data; data.startIndex = 0; - data.endIndex = 0; + data.endIndex = 0; size_t visualCharacterIndex = 0; - size_t byteIndex = 0; + size_t byteIndex = 0; // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ). char leadByte = preEditString[byteIndex]; - while( leadByte != '\0' ) + while(leadByte != '\0') { leadByte = preEditString[byteIndex]; // Update the character to get the number of its byte // attr->end_index is provided as a byte position not character and we need to know the character position. - const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character. - if( byteIndex <= attr->start_index ) + const size_t currentSequenceLength = Utf8SequenceLength(leadByte); // returns number of bytes used to represent character. + if(byteIndex <= attr->start_index) { - data.startIndex = visualCharacterIndex; + data.startIndex = visualCharacterIndex; } - if( byteIndex >= attr->end_index ) + if(byteIndex >= attr->end_index) { data.endIndex = visualCharacterIndex; break; @@ -548,11 +543,11 @@ void InputMethodContextEcoreWl::PreEditChanged( void*, ImfContext* imfContext, v else { byteIndex += currentSequenceLength; // jump to next character - visualCharacterIndex++; // increment character count so we know our position for when we get a match + visualCharacterIndex++; // increment character count so we know our position for when we get a match } } - switch( attr->preedit_type ) + switch(attr->preedit_type) { case ECORE_IMF_PREEDIT_TYPE_NONE: { @@ -600,48 +595,48 @@ void InputMethodContextEcoreWl::PreEditChanged( void*, ImfContext* imfContext, v break; } } - mPreeditAttrs.PushBack( data ); + mPreeditAttrs.PushBack(data); } } - if ( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::EventData eventData( Dali::InputMethodContext::PRE_EDIT, preEditString, cursorPosition, 0 ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, eventData ); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::EventData eventData(Dali::InputMethodContext::PRE_EDIT, preEditString, cursorPosition, 0); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, eventData); - if ( callbackData.update ) + if(callbackData.update) { - SetCursorPosition( callbackData.cursorPosition ); - SetSurroundingText( callbackData.currentText ); + SetCursorPosition(callbackData.cursorPosition); + SetSurroundingText(callbackData.currentText); NotifyCursorPosition(); } - if ( callbackData.preeditResetRequired ) + if(callbackData.preeditResetRequired) { Reset(); } } - free( preEditString ); + free(preEditString); } -void InputMethodContextEcoreWl::CommitReceived( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextEcoreWl::CommitReceived(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::CommitReceived\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::CommitReceived\n"); - if ( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - const std::string keyString( static_cast( eventInfo ) ); + const std::string keyString(static_cast(eventInfo)); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::EventData eventData( Dali::InputMethodContext::COMMIT, keyString, 0, 0 ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, eventData ); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::EventData eventData(Dali::InputMethodContext::COMMIT, keyString, 0, 0); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, eventData); - if( callbackData.update ) + if(callbackData.update) { - SetCursorPosition( callbackData.cursorPosition ); - SetSurroundingText( callbackData.currentText ); + SetCursorPosition(callbackData.cursorPosition); + SetSurroundingText(callbackData.currentText); NotifyCursorPosition(); } @@ -653,35 +648,35 @@ void InputMethodContextEcoreWl::CommitReceived( void*, ImfContext* imfContext, v * Here the InputMethodContext module wishes to know the string we are working with and where within the string the cursor is * We need to signal the application to tell us this information. */ -bool InputMethodContextEcoreWl::RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) +bool InputMethodContextEcoreWl::RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::RetrieveSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::RetrieveSurrounding\n"); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0 ); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, imfData); - if( callbackData.update ) + if(callbackData.update) { - if( cursorPosition ) + if(cursorPosition) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); - *cursorPosition = mIMFCursorPosition; + mIMFCursorPosition = static_cast(callbackData.cursorPosition); + *cursorPosition = mIMFCursorPosition; } - if( text ) + if(text) { const char* plainText = callbackData.currentText.c_str(); - if( plainText ) + if(plainText) { // The memory allocated by strdup() can be freed by ecore_imf_context_surrounding_get() internally. - *text = strdup( plainText ); + *text = strdup(plainText); // If the current input panel is password mode, dali should replace the plain text with '*' (Asterisk) character. - if( ( ecore_imf_context_input_hint_get( mIMFContext ) & ECORE_IMF_INPUT_HINT_SENSITIVE_DATA ) && *text ) + if((ecore_imf_context_input_hint_get(mIMFContext) & ECORE_IMF_INPUT_HINT_SENSITIVE_DATA) && *text) { - for( char* iter = *text; *iter; ++iter ) + for(char* iter = *text; *iter; ++iter) { *iter = '*'; } @@ -699,123 +694,120 @@ bool InputMethodContextEcoreWl::RetrieveSurrounding( void* data, ImfContext* imf * Called when an InputMethodContext delete surrounding event is received. * Here we tell the application that it should delete a certain range. */ -void InputMethodContextEcoreWl::DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextEcoreWl::DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::DeleteSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::DeleteSurrounding\n"); - if( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast( eventInfo ); + Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast(eventInfo); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::DELETE_SURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars ); - Dali::InputMethodContext handle( this ); - mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::DELETE_SURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars); + Dali::InputMethodContext handle(this); + mEventSignal.Emit(handle, imfData); } } /** * Called when the input method sends a private command. */ -void InputMethodContextEcoreWl::SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextEcoreWl::SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SendPrivateCommand\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SendPrivateCommand\n"); - if( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - const char* privateCommandSendEvent = static_cast( eventInfo ); + const char* privateCommandSendEvent = static_cast(eventInfo); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::PRIVATE_COMMAND, privateCommandSendEvent, 0, 0 ); - Dali::InputMethodContext handle( this ); - mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::PRIVATE_COMMAND, privateCommandSendEvent, 0, 0); + Dali::InputMethodContext handle(this); + mEventSignal.Emit(handle, imfData); } } /** * Called when the input method commits content, such as an image. */ -void InputMethodContextEcoreWl::SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextEcoreWl::SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SendCommitContent\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SendCommitContent\n"); - if( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - Ecore_IMF_Event_Commit_Content* commitContent = static_cast( eventInfo ); - if( commitContent ) + Ecore_IMF_Event_Commit_Content* commitContent = static_cast(eventInfo); + if(commitContent) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SendCommitContent commit content : %s, description : %s, mime type : %s\n", - commitContent->content_uri, commitContent->description, commitContent->mime_types ); - mContentReceivedSignal.Emit( commitContent->content_uri, commitContent->description, commitContent->mime_types ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SendCommitContent commit content : %s, description : %s, mime type : %s\n", commitContent->content_uri, commitContent->description, commitContent->mime_types); + mContentReceivedSignal.Emit(commitContent->content_uri, commitContent->description, commitContent->mime_types); } } } void InputMethodContextEcoreWl::NotifyCursorPosition() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::NotifyCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::NotifyCursorPosition\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition ); + ecore_imf_context_cursor_position_set(mIMFContext, mIMFCursorPosition); } } -void InputMethodContextEcoreWl::SetCursorPosition( unsigned int cursorPosition ) +void InputMethodContextEcoreWl::SetCursorPosition(unsigned int cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetCursorPosition\n"); - mIMFCursorPosition = static_cast( cursorPosition ); + mIMFCursorPosition = static_cast(cursorPosition); } unsigned int InputMethodContextEcoreWl::GetCursorPosition() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetCursorPosition\n"); - return static_cast( mIMFCursorPosition ); + return static_cast(mIMFCursorPosition); } -void InputMethodContextEcoreWl::SetSurroundingText( const std::string& text ) +void InputMethodContextEcoreWl::SetSurroundingText(const std::string& text) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetSurroundingText\n"); mSurroundingText = text; } const std::string& InputMethodContextEcoreWl::GetSurroundingText() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetSurroundingText\n"); return mSurroundingText; } -void InputMethodContextEcoreWl::NotifyTextInputMultiLine( bool multiLine ) +void InputMethodContextEcoreWl::NotifyTextInputMultiLine(bool multiLine) { - if( mIMFContext ) + if(mIMFContext) { Ecore_IMF_Input_Hints currentHint = ecore_imf_context_input_hint_get(mIMFContext); - ecore_imf_context_input_hint_set( mIMFContext, - static_cast< Ecore_IMF_Input_Hints >( multiLine ? - (currentHint | ECORE_IMF_INPUT_HINT_MULTILINE) : - (currentHint & ~ECORE_IMF_INPUT_HINT_MULTILINE))); + ecore_imf_context_input_hint_set(mIMFContext, + static_cast(multiLine ? (currentHint | ECORE_IMF_INPUT_HINT_MULTILINE) : (currentHint & ~ECORE_IMF_INPUT_HINT_MULTILINE))); } - mBackupOperations[Operation::NOTIFY_TEXT_INPUT_MULTILINE] = std::bind( &InputMethodContextEcoreWl::NotifyTextInputMultiLine, this, multiLine ); + mBackupOperations[Operation::NOTIFY_TEXT_INPUT_MULTILINE] = std::bind(&InputMethodContextEcoreWl::NotifyTextInputMultiLine, this, multiLine); } Dali::InputMethodContext::TextDirection InputMethodContextEcoreWl::GetTextDirection() { - Dali::InputMethodContext::TextDirection direction ( Dali::InputMethodContext::LEFT_TO_RIGHT ); + Dali::InputMethodContext::TextDirection direction(Dali::InputMethodContext::LEFT_TO_RIGHT); - if ( mIMFContext ) - { - char* locale( NULL ); - ecore_imf_context_input_panel_language_locale_get( mIMFContext, &locale ); + if(mIMFContext) + { + char* locale(NULL); + ecore_imf_context_input_panel_language_locale_get(mIMFContext, &locale); - if ( locale ) - { - direction = static_cast< Dali::InputMethodContext::TextDirection >( Locale::GetDirection( std::string( locale ) ) ); - free( locale ); - } + if(locale) + { + direction = static_cast(Locale::GetDirection(std::string(locale))); + free(locale); } + } return direction; } @@ -826,96 +818,96 @@ Rect InputMethodContextEcoreWl::GetInputMethodArea() width = height = xPos = yPos = 0; - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_geometry_get( mIMFContext, &xPos, &yPos, &width, &height ); + ecore_imf_context_input_panel_geometry_get(mIMFContext, &xPos, &yPos, &width, &height); } else { DALI_LOG_WARNING("VKB Unable to get IMFContext so GetSize unavailable\n"); - // return 0 as real size unknown. + // return 0 as real size unknown. } - return Rect(xPos,yPos,width,height); + return Rect(xPos, yPos, width, height); } -void InputMethodContextEcoreWl::ApplyOptions( const InputMethodOptions& options ) +void InputMethodContextEcoreWl::ApplyOptions(const InputMethodOptions& options) { using namespace Dali::InputMethod::Category; int index; - if( mIMFContext == NULL ) + if(mIMFContext == NULL) { DALI_LOG_WARNING("VKB Unable to excute ApplyOptions with Null ImfContext\n"); return; } - if( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) ) + if(mOptions.CompareAndSet(PANEL_LAYOUT, options, index)) { - ecore_imf_context_input_panel_layout_set( mIMFContext, panelLayoutMap[index] ); + ecore_imf_context_input_panel_layout_set(mIMFContext, panelLayoutMap[index]); // Sets the input hint which allows input methods to fine-tune their behavior. - if( panelLayoutMap[index] == ECORE_IMF_INPUT_PANEL_LAYOUT_PASSWORD ) + if(panelLayoutMap[index] == ECORE_IMF_INPUT_PANEL_LAYOUT_PASSWORD) { - ecore_imf_context_input_hint_set( mIMFContext, static_cast< Ecore_IMF_Input_Hints >( ecore_imf_context_input_hint_get( mIMFContext ) | ECORE_IMF_INPUT_HINT_SENSITIVE_DATA ) ); + ecore_imf_context_input_hint_set(mIMFContext, static_cast(ecore_imf_context_input_hint_get(mIMFContext) | ECORE_IMF_INPUT_HINT_SENSITIVE_DATA)); } else { - ecore_imf_context_input_hint_set( mIMFContext, static_cast< Ecore_IMF_Input_Hints >( ecore_imf_context_input_hint_get( mIMFContext ) & ~ECORE_IMF_INPUT_HINT_SENSITIVE_DATA ) ); + ecore_imf_context_input_hint_set(mIMFContext, static_cast(ecore_imf_context_input_hint_get(mIMFContext) & ~ECORE_IMF_INPUT_HINT_SENSITIVE_DATA)); } } - if( mOptions.CompareAndSet(BUTTON_ACTION, options, index) ) + if(mOptions.CompareAndSet(BUTTON_ACTION, options, index)) { - ecore_imf_context_input_panel_return_key_type_set( mIMFContext, returnKeyTypeMap[index] ); + ecore_imf_context_input_panel_return_key_type_set(mIMFContext, returnKeyTypeMap[index]); } - if( mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index) ) + if(mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index)) { - ecore_imf_context_autocapital_type_set( mIMFContext, autoCapitalMap[index] ); + ecore_imf_context_autocapital_type_set(mIMFContext, autoCapitalMap[index]); } - if( mOptions.CompareAndSet(VARIATION, options, index) ) + if(mOptions.CompareAndSet(VARIATION, options, index)) { - ecore_imf_context_input_panel_layout_variation_set( mIMFContext, index ); + ecore_imf_context_input_panel_layout_variation_set(mIMFContext, index); } } -void InputMethodContextEcoreWl::SetInputPanelData( const std::string& data ) +void InputMethodContextEcoreWl::SetInputPanelData(const std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetInputPanelData\n"); - if( mIMFContext ) + if(mIMFContext) { int length = data.length(); - ecore_imf_context_input_panel_imdata_set( mIMFContext, data.c_str(), length ); + ecore_imf_context_input_panel_imdata_set(mIMFContext, data.c_str(), length); } - mBackupOperations[Operation::SET_INPUT_PANEL_DATA] = std::bind( &InputMethodContextEcoreWl::SetInputPanelData, this, data ); + mBackupOperations[Operation::SET_INPUT_PANEL_DATA] = std::bind(&InputMethodContextEcoreWl::SetInputPanelData, this, data); } -void InputMethodContextEcoreWl::GetInputPanelData( std::string& data ) +void InputMethodContextEcoreWl::GetInputPanelData(std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelData\n"); - if( mIMFContext ) + if(mIMFContext) { - int length = 4096; // The max length is 4096 bytes - Dali::Vector< char > buffer; - buffer.Resize( length ); - ecore_imf_context_input_panel_imdata_get( mIMFContext, &buffer[0], &length ); - data = std::string( buffer.Begin(), buffer.End() ); + int length = 4096; // The max length is 4096 bytes + Dali::Vector buffer; + buffer.Resize(length); + ecore_imf_context_input_panel_imdata_get(mIMFContext, &buffer[0], &length); + data = std::string(buffer.Begin(), buffer.End()); } } Dali::InputMethodContext::State InputMethodContextEcoreWl::GetInputPanelState() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelState\n"); - if( mIMFContext ) + if(mIMFContext) { int value; - value = ecore_imf_context_input_panel_state_get( mIMFContext ); + value = ecore_imf_context_input_panel_state_get(mIMFContext); - switch (value) + switch(value) { case ECORE_IMF_INPUT_PANEL_STATE_SHOW: { @@ -944,60 +936,60 @@ Dali::InputMethodContext::State InputMethodContextEcoreWl::GetInputPanelState() return Dali::InputMethodContext::DEFAULT; } -void InputMethodContextEcoreWl::SetReturnKeyState( bool visible ) +void InputMethodContextEcoreWl::SetReturnKeyState(bool visible) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetReturnKeyState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetReturnKeyState\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_return_key_disabled_set( mIMFContext, !visible ); + ecore_imf_context_input_panel_return_key_disabled_set(mIMFContext, !visible); } - mBackupOperations[Operation::SET_RETURN_KEY_STATE] = std::bind( &InputMethodContextEcoreWl::SetReturnKeyState, this, visible ); + mBackupOperations[Operation::SET_RETURN_KEY_STATE] = std::bind(&InputMethodContextEcoreWl::SetReturnKeyState, this, visible); } -void InputMethodContextEcoreWl::AutoEnableInputPanel( bool enabled ) +void InputMethodContextEcoreWl::AutoEnableInputPanel(bool enabled) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::AutoEnableInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::AutoEnableInputPanel\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_enabled_set( mIMFContext, enabled ); + ecore_imf_context_input_panel_enabled_set(mIMFContext, enabled); } - mBackupOperations[Operation::AUTO_ENABLE_INPUT_PANEL] = std::bind( &InputMethodContextEcoreWl::AutoEnableInputPanel, this, enabled ); + mBackupOperations[Operation::AUTO_ENABLE_INPUT_PANEL] = std::bind(&InputMethodContextEcoreWl::AutoEnableInputPanel, this, enabled); } void InputMethodContextEcoreWl::ShowInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::ShowInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::ShowInputPanel\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_show( mIMFContext ); + ecore_imf_context_input_panel_show(mIMFContext); } } void InputMethodContextEcoreWl::HideInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::HideInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::HideInputPanel\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_hide( mIMFContext ); + ecore_imf_context_input_panel_hide(mIMFContext); } } Dali::InputMethodContext::KeyboardType InputMethodContextEcoreWl::GetKeyboardType() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetKeyboardType\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetKeyboardType\n"); - if( mIMFContext ) + if(mIMFContext) { int value; - value = ecore_imf_context_keyboard_mode_get( mIMFContext ); + value = ecore_imf_context_keyboard_mode_get(mIMFContext); - switch (value) + switch(value) { case ECORE_IMF_INPUT_PANEL_SW_KEYBOARD_MODE: { @@ -1017,115 +1009,115 @@ Dali::InputMethodContext::KeyboardType InputMethodContextEcoreWl::GetKeyboardTyp std::string InputMethodContextEcoreWl::GetInputPanelLocale() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelLocale\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelLocale\n"); std::string locale = ""; - if( mIMFContext ) + if(mIMFContext) { char* value = NULL; - ecore_imf_context_input_panel_language_locale_get( mIMFContext, &value ); + ecore_imf_context_input_panel_language_locale_get(mIMFContext, &value); - if( value ) + if(value) { - std::string valueCopy( value ); + std::string valueCopy(value); locale = valueCopy; // The locale string retrieved must be freed with free(). - free( value ); + free(value); } } return locale; } -void InputMethodContextEcoreWl::SetContentMIMETypes( const std::string& mimeTypes ) +void InputMethodContextEcoreWl::SetContentMIMETypes(const std::string& mimeTypes) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetContentMIMETypes\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetContentMIMETypes\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_mime_type_accept_set( mIMFContext, mimeTypes.c_str() ); + ecore_imf_context_mime_type_accept_set(mIMFContext, mimeTypes.c_str()); } - mBackupOperations[Operation::SET_CONTENT_MIME_TYPES] = std::bind( &InputMethodContextEcoreWl::SetContentMIMETypes, this, mimeTypes ); + mBackupOperations[Operation::SET_CONTENT_MIME_TYPES] = std::bind(&InputMethodContextEcoreWl::SetContentMIMETypes, this, mimeTypes); } -bool InputMethodContextEcoreWl::FilterEventKey( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextEcoreWl::FilterEventKey(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); // If a device key then skip ecore_imf_context_filter_event. - if ( ! KeyLookup::IsDeviceButton( keyEvent.GetKeyName().c_str() )) + if(!KeyLookup::IsDeviceButton(keyEvent.GetKeyName().c_str())) { //check whether it's key down or key up event - if ( keyEvent.GetState() == Dali::KeyEvent::DOWN ) + if(keyEvent.GetState() == Dali::KeyEvent::DOWN) { - eventHandled = ProcessEventKeyDown( keyEvent ); + eventHandled = ProcessEventKeyDown(keyEvent); } - else if ( keyEvent.GetState() == Dali::KeyEvent::UP ) + else if(keyEvent.GetState() == Dali::KeyEvent::UP) { - eventHandled = ProcessEventKeyUp( keyEvent ); + eventHandled = ProcessEventKeyUp(keyEvent); } } return eventHandled; } -void InputMethodContextEcoreWl::AllowTextPrediction( bool prediction ) +void InputMethodContextEcoreWl::AllowTextPrediction(bool prediction) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::AllowTextPrediction\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::AllowTextPrediction\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_prediction_allow_set( mIMFContext, prediction ); + ecore_imf_context_prediction_allow_set(mIMFContext, prediction); } - mBackupOperations[Operation::ALLOW_TEXT_PREDICTION] = std::bind( &InputMethodContextEcoreWl::AllowTextPrediction, this, prediction ); + mBackupOperations[Operation::ALLOW_TEXT_PREDICTION] = std::bind(&InputMethodContextEcoreWl::AllowTextPrediction, this, prediction); } bool InputMethodContextEcoreWl::IsTextPredictionAllowed() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::IsTextPredictionAllowed\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::IsTextPredictionAllowed\n"); bool prediction = false; - if( mIMFContext ) + if(mIMFContext) { - prediction = ecore_imf_context_prediction_allow_get( mIMFContext ); + prediction = ecore_imf_context_prediction_allow_get(mIMFContext); } return prediction; } -void InputMethodContextEcoreWl::SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) +void InputMethodContextEcoreWl::SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetInputPanelLanguage\n" ); - if( mIMFContext ) + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetInputPanelLanguage\n"); + if(mIMFContext) { - switch (language) + switch(language) { case Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC: { - ecore_imf_context_input_panel_language_set( mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_AUTOMATIC ); + ecore_imf_context_input_panel_language_set(mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_AUTOMATIC); break; } case Dali::InputMethodContext::InputPanelLanguage::ALPHABET: { - ecore_imf_context_input_panel_language_set( mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_ALPHABET ); + ecore_imf_context_input_panel_language_set(mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_ALPHABET); break; } } } - mBackupOperations[Operation::SET_INPUT_PANEL_LANGUAGE] = std::bind( &InputMethodContextEcoreWl::SetInputPanelLanguage, this, language ); + mBackupOperations[Operation::SET_INPUT_PANEL_LANGUAGE] = std::bind(&InputMethodContextEcoreWl::SetInputPanelLanguage, this, language); } Dali::InputMethodContext::InputPanelLanguage InputMethodContextEcoreWl::GetInputPanelLanguage() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelLanguage\n" ); - if( mIMFContext ) + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetInputPanelLanguage\n"); + if(mIMFContext) { int value; - value = ecore_imf_context_input_panel_language_get( mIMFContext ); + value = ecore_imf_context_input_panel_language_get(mIMFContext); - switch (value) + switch(value) { case ECORE_IMF_INPUT_PANEL_LANG_AUTOMATIC: { @@ -1142,56 +1134,56 @@ Dali::InputMethodContext::InputPanelLanguage InputMethodContextEcoreWl::GetInput return Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC; } -void InputMethodContextEcoreWl::SetInputPanelPosition( unsigned int x, unsigned int y ) +void InputMethodContextEcoreWl::SetInputPanelPosition(unsigned int x, unsigned int y) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetInputPanelPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::SetInputPanelPosition\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_position_set( mIMFContext, x, y ); + ecore_imf_context_input_panel_position_set(mIMFContext, x, y); } - mBackupOperations[Operation::SET_INPUT_PANEL_POSITION] = std::bind( &InputMethodContextEcoreWl::SetInputPanelPosition, this, x, y ); + mBackupOperations[Operation::SET_INPUT_PANEL_POSITION] = std::bind(&InputMethodContextEcoreWl::SetInputPanelPosition, this, x, y); } -void InputMethodContextEcoreWl::GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const +void InputMethodContextEcoreWl::GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetPreeditStyle\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextEcoreWl::GetPreeditStyle\n"); attrs = mPreeditAttrs; } -bool InputMethodContextEcoreWl::ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextEcoreWl::ProcessEventKeyDown(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); - if ( mIMFContext ) + bool eventHandled(false); + if(mIMFContext) { - Integration::KeyEvent integKeyEvent( keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast< Integration::KeyEvent::State >( keyEvent.GetState() ), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass() ); - std::string key = integKeyEvent.logicalKey; + Integration::KeyEvent integKeyEvent(keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast(keyEvent.GetState()), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass()); + std::string key = integKeyEvent.logicalKey; - std::string compose = integKeyEvent.compose; + std::string compose = integKeyEvent.compose; std::string deviceName = integKeyEvent.deviceName; // We're consuming key down event so we have to pass to InputMethodContext so that it can parse it as well. Ecore_IMF_Event_Key_Down ecoreKeyDownEvent; - ecoreKeyDownEvent.keyname = integKeyEvent.keyName.c_str(); - ecoreKeyDownEvent.key = key.c_str(); - ecoreKeyDownEvent.string = integKeyEvent.keyString.c_str(); - ecoreKeyDownEvent.compose = compose.c_str(); - ecoreKeyDownEvent.timestamp = integKeyEvent.time; - ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier( integKeyEvent.keyModifier ); - ecoreKeyDownEvent.locks = EcoreInputModifierToEcoreIMFLock( integKeyEvent.keyModifier ); - ecoreKeyDownEvent.dev_name = deviceName.c_str(); - ecoreKeyDownEvent.dev_class = static_cast ( integKeyEvent.deviceClass );//ECORE_IMF_DEVICE_CLASS_KEYBOARD; - ecoreKeyDownEvent.dev_subclass = static_cast ( integKeyEvent.deviceSubclass );//ECORE_IMF_DEVICE_SUBCLASS_NONE; + ecoreKeyDownEvent.keyname = integKeyEvent.keyName.c_str(); + ecoreKeyDownEvent.key = key.c_str(); + ecoreKeyDownEvent.string = integKeyEvent.keyString.c_str(); + ecoreKeyDownEvent.compose = compose.c_str(); + ecoreKeyDownEvent.timestamp = integKeyEvent.time; + ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier(integKeyEvent.keyModifier); + ecoreKeyDownEvent.locks = EcoreInputModifierToEcoreIMFLock(integKeyEvent.keyModifier); + ecoreKeyDownEvent.dev_name = deviceName.c_str(); + ecoreKeyDownEvent.dev_class = static_cast(integKeyEvent.deviceClass); //ECORE_IMF_DEVICE_CLASS_KEYBOARD; + ecoreKeyDownEvent.dev_subclass = static_cast(integKeyEvent.deviceSubclass); //ECORE_IMF_DEVICE_SUBCLASS_NONE; #if defined(ECORE_VERSION_MAJOR) && (ECORE_VERSION_MAJOR >= 1) && defined(ECORE_VERSION_MINOR) && (ECORE_VERSION_MINOR >= 22) ecoreKeyDownEvent.keycode = integKeyEvent.keyCode; // Ecore_IMF_Event structure has added 'keycode' variable since ecore_imf 1.22 version. -#endif // Since ecore_imf 1.22 version +#endif // Since ecore_imf 1.22 version // If the device is IME and the focused key is the direction keys, then we should send a key event to move a key cursor. - if ((integKeyEvent.deviceName == "ime") && ((!strncmp(integKeyEvent.keyName.c_str(), "Left", 4)) || - (!strncmp(integKeyEvent.keyName.c_str(), "Right", 5)) || - (!strncmp(integKeyEvent.keyName.c_str(), "Up", 2)) || - (!strncmp(integKeyEvent.keyName.c_str(), "Down", 4)))) + if((integKeyEvent.deviceName == "ime") && ((!strncmp(integKeyEvent.keyName.c_str(), "Left", 4)) || + (!strncmp(integKeyEvent.keyName.c_str(), "Right", 5)) || + (!strncmp(integKeyEvent.keyName.c_str(), "Up", 2)) || + (!strncmp(integKeyEvent.keyName.c_str(), "Down", 4)))) { eventHandled = 0; } @@ -1199,15 +1191,15 @@ bool InputMethodContextEcoreWl::ProcessEventKeyDown( const Dali::KeyEvent& keyEv { eventHandled = ecore_imf_context_filter_event(mIMFContext, ECORE_IMF_EVENT_KEY_DOWN, - reinterpret_cast( &ecoreKeyDownEvent ) ); + reinterpret_cast(&ecoreKeyDownEvent)); } // If the event has not been handled by InputMethodContext then check if we should reset our input method context - if (!eventHandled) + if(!eventHandled) { - if (!strcmp(integKeyEvent.keyName.c_str(), "Escape") || - !strcmp(integKeyEvent.keyName.c_str(), "Return") || - !strcmp(integKeyEvent.keyName.c_str(), "KP_Enter")) + if(!strcmp(integKeyEvent.keyName.c_str(), "Escape") || + !strcmp(integKeyEvent.keyName.c_str(), "Return") || + !strcmp(integKeyEvent.keyName.c_str(), "KP_Enter")) { ecore_imf_context_reset(mIMFContext); } @@ -1216,99 +1208,99 @@ bool InputMethodContextEcoreWl::ProcessEventKeyDown( const Dali::KeyEvent& keyEv return eventHandled; } -bool InputMethodContextEcoreWl::ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextEcoreWl::ProcessEventKeyUp(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); - if( mIMFContext ) + bool eventHandled(false); + if(mIMFContext) { - Integration::KeyEvent integKeyEvent( keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast< Integration::KeyEvent::State >( keyEvent.GetState() ), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass() ); - std::string key = integKeyEvent.logicalKey; + Integration::KeyEvent integKeyEvent(keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast(keyEvent.GetState()), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass()); + std::string key = integKeyEvent.logicalKey; - std::string compose = integKeyEvent.compose; + std::string compose = integKeyEvent.compose; std::string deviceName = integKeyEvent.deviceName; // We're consuming key up event so we have to pass to InputMethodContext so that it can parse it as well. Ecore_IMF_Event_Key_Up ecoreKeyUpEvent; - ecoreKeyUpEvent.keyname = integKeyEvent.keyName.c_str(); - ecoreKeyUpEvent.key = key.c_str(); - ecoreKeyUpEvent.string = integKeyEvent.keyString.c_str(); - ecoreKeyUpEvent.compose = compose.c_str(); - ecoreKeyUpEvent.timestamp = integKeyEvent.time; - ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier( integKeyEvent.keyModifier ); - ecoreKeyUpEvent.locks = EcoreInputModifierToEcoreIMFLock( integKeyEvent.keyModifier ); - ecoreKeyUpEvent.dev_name = deviceName.c_str(); - ecoreKeyUpEvent.dev_class = static_cast ( integKeyEvent.deviceClass );//ECORE_IMF_DEVICE_CLASS_KEYBOARD; - ecoreKeyUpEvent.dev_subclass = static_cast ( integKeyEvent.deviceSubclass );//ECORE_IMF_DEVICE_SUBCLASS_NONE; + ecoreKeyUpEvent.keyname = integKeyEvent.keyName.c_str(); + ecoreKeyUpEvent.key = key.c_str(); + ecoreKeyUpEvent.string = integKeyEvent.keyString.c_str(); + ecoreKeyUpEvent.compose = compose.c_str(); + ecoreKeyUpEvent.timestamp = integKeyEvent.time; + ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier(integKeyEvent.keyModifier); + ecoreKeyUpEvent.locks = EcoreInputModifierToEcoreIMFLock(integKeyEvent.keyModifier); + ecoreKeyUpEvent.dev_name = deviceName.c_str(); + ecoreKeyUpEvent.dev_class = static_cast(integKeyEvent.deviceClass); //ECORE_IMF_DEVICE_CLASS_KEYBOARD; + ecoreKeyUpEvent.dev_subclass = static_cast(integKeyEvent.deviceSubclass); //ECORE_IMF_DEVICE_SUBCLASS_NONE; #if defined(ECORE_VERSION_MAJOR) && (ECORE_VERSION_MAJOR >= 1) && defined(ECORE_VERSION_MINOR) && (ECORE_VERSION_MINOR >= 22) ecoreKeyUpEvent.keycode = integKeyEvent.keyCode; // Ecore_IMF_Event structure has added 'keycode' variable since ecore_imf 1.22 version. -#endif // Since ecore_imf 1.22 version +#endif // Since ecore_imf 1.22 version eventHandled = ecore_imf_context_filter_event(mIMFContext, ECORE_IMF_EVENT_KEY_UP, - reinterpret_cast( &ecoreKeyUpEvent ) ); + reinterpret_cast(&ecoreKeyUpEvent)); } return eventHandled; } -Ecore_IMF_Keyboard_Modifiers InputMethodContextEcoreWl::EcoreInputModifierToEcoreIMFModifier( unsigned int ecoreModifier ) +Ecore_IMF_Keyboard_Modifiers InputMethodContextEcoreWl::EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier) { - unsigned int modifier( ECORE_IMF_KEYBOARD_MODIFIER_NONE ); // If no other matches returns NONE. + unsigned int modifier(ECORE_IMF_KEYBOARD_MODIFIER_NONE); // If no other matches returns NONE. - if ( ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT ) // enums from ecore_input/Ecore_Input.h + if(ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT) // enums from ecore_input/Ecore_Input.h { - modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h + modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALT ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_ALT) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALT; } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_CTRL ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_CTRL) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_CTRL; } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_WIN ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_WIN) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_WIN; } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALTGR; } - return static_cast( modifier ); + return static_cast(modifier); } -Ecore_IMF_Keyboard_Locks InputMethodContextEcoreWl::EcoreInputModifierToEcoreIMFLock( unsigned int modifier ) +Ecore_IMF_Keyboard_Locks InputMethodContextEcoreWl::EcoreInputModifierToEcoreIMFLock(unsigned int modifier) { - unsigned int lock( ECORE_IMF_KEYBOARD_LOCK_NONE ); // If no other matches, returns NONE. + unsigned int lock(ECORE_IMF_KEYBOARD_LOCK_NONE); // If no other matches, returns NONE. - if( modifier & ECORE_EVENT_LOCK_NUM ) - { - lock |= ECORE_IMF_KEYBOARD_LOCK_NUM; // Num lock is active. - } + if(modifier & ECORE_EVENT_LOCK_NUM) + { + lock |= ECORE_IMF_KEYBOARD_LOCK_NUM; // Num lock is active. + } - if( modifier & ECORE_EVENT_LOCK_CAPS ) - { - lock |= ECORE_IMF_KEYBOARD_LOCK_CAPS; // Caps lock is active. - } + if(modifier & ECORE_EVENT_LOCK_CAPS) + { + lock |= ECORE_IMF_KEYBOARD_LOCK_CAPS; // Caps lock is active. + } - if( modifier & ECORE_EVENT_LOCK_SCROLL ) - { - lock |= ECORE_IMF_KEYBOARD_LOCK_SCROLL; // Scroll lock is active. - } + if(modifier & ECORE_EVENT_LOCK_SCROLL) + { + lock |= ECORE_IMF_KEYBOARD_LOCK_SCROLL; // Scroll lock is active. + } - return static_cast( lock ); + return static_cast(lock); } -void InputMethodContextEcoreWl::OnStaged( Dali::Actor actor ) +void InputMethodContextEcoreWl::OnStaged(Dali::Actor actor) { - int windowId = GetWindowIdFromActor( actor ); + int windowId = GetWindowIdFromActor(actor); - if( mWindowId != windowId ) + if(mWindowId != windowId) { mWindowId = windowId; @@ -1318,8 +1310,8 @@ void InputMethodContextEcoreWl::OnStaged( Dali::Actor actor ) } } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.h b/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.h old mode 100755 new mode 100644 index acde069..e133a42 --- a/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.h +++ b/dali/internal/input/tizen-wayland/input-method-context-impl-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_METHOD_CONTEXT_IMPL_ECORE_WL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,35 +22,31 @@ #include #include +#include #include #include -#include // INTERNAL INCLUDES #include namespace Dali { - class RenderSurface; namespace Internal { - namespace Adaptor { - class InputMethodContextEcoreWl : public Dali::Internal::Adaptor::InputMethodContext, public Dali::ConnectionTracker { public: - /** * @brief Creates a new InputMethodContext handle * * @param[in] actor The actor that uses the new InputMethodContext instance. * @return InputMethodContext pointer */ - static InputMethodContextPtr New( Dali::Actor actor ); + static InputMethodContextPtr New(Dali::Actor actor); /** * @brief Initializes member data. @@ -58,7 +54,6 @@ public: void Initialize() override; public: - /** * @copydoc Dali::InputMethodContext::Finalize() */ @@ -104,37 +99,37 @@ public: /** * @copydoc Dali::InputMethodContext::SetRestoreAfterFocusLost() */ - void SetRestoreAfterFocusLost( bool toggle ) override; + void SetRestoreAfterFocusLost(bool toggle) override; /** * @copydoc Dali::InputMethodContext::PreEditChanged() */ - void PreEditChanged( void *data, ImfContext *imfContext, void *eventInfo ) override; + void PreEditChanged(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - void CommitReceived( void *data, ImfContext *imfContext, void *eventInfo ) override; + void CommitReceived(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - bool RetrieveSurrounding( void *data, ImfContext *imfContext, char** text, int* cursorPosition ) override; + bool RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) override; /** * @copydoc Dali::InputMethodContext::DeleteSurrounding() */ - void DeleteSurrounding( void *data, ImfContext *imfContext, void *eventInfo ) override; + void DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) override; - /** + /** * @copydoc Dali::InputMethodContext::SendPrivateCommand() */ - void SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) override; + void SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::SendCommitContent() */ - void SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) override; + void SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) override; // Cursor related /** @@ -145,7 +140,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetCursorPosition() */ - void SetCursorPosition( unsigned int cursorPosition ) override; + void SetCursorPosition(unsigned int cursorPosition) override; /** * @copydoc Dali::InputMethodContext::GetCursorPosition() @@ -155,7 +150,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetSurroundingText() */ - void SetSurroundingText( const std::string& text ) override; + void SetSurroundingText(const std::string& text) override; /** * @copydoc Dali::InputMethodContext::GetSurroundingText() @@ -165,7 +160,7 @@ public: /** * @copydoc Dali::InputMethodContext::NotifyTextInputMultiLine() */ - void NotifyTextInputMultiLine( bool multiLine ) override; + void NotifyTextInputMultiLine(bool multiLine) override; /** * @copydoc Dali::InputMethodContext::GetTextDirection() @@ -180,17 +175,17 @@ public: /** * @copydoc Dali::InputMethodContext::ApplyOptions() */ - void ApplyOptions( const InputMethodOptions& options ) override; + void ApplyOptions(const InputMethodOptions& options) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelData() */ - void SetInputPanelData( const std::string& data ) override; + void SetInputPanelData(const std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelData() */ - void GetInputPanelData( std::string& data ) override; + void GetInputPanelData(std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelState() @@ -200,12 +195,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetReturnKeyState() */ - void SetReturnKeyState( bool visible ) override; + void SetReturnKeyState(bool visible) override; /** * @copydoc Dali::InputMethodContext::AutoEnableInputPanel() */ - void AutoEnableInputPanel( bool enabled ) override; + void AutoEnableInputPanel(bool enabled) override; /** * @copydoc Dali::InputMethodContext::ShowInputPanel() @@ -230,17 +225,17 @@ public: /** * @copydoc Dali::InputMethodContext::SetContentMIMETypes() */ - void SetContentMIMETypes( const std::string& mimeTypes ) override; + void SetContentMIMETypes(const std::string& mimeTypes) override; /** * @copydoc Dali::InputMethodContext::FilterEventKey() */ - bool FilterEventKey( const Dali::KeyEvent& keyEvent ) override; + bool FilterEventKey(const Dali::KeyEvent& keyEvent) override; /** * @copydoc Dali::InputMethodContext::AllowTextPrediction() */ - void AllowTextPrediction( bool prediction ) override; + void AllowTextPrediction(bool prediction) override; /** * @copydoc Dali::InputMethodContext::IsTextPredictionAllowed() @@ -250,7 +245,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelLanguage() */ - void SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) override; + void SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelLanguage() @@ -260,12 +255,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelPosition() */ - void SetInputPanelPosition( unsigned int x, unsigned int y ) override; + void SetInputPanelPosition(unsigned int x, unsigned int y) override; /** * @copydoc Dali::InputMethodContext::GetPreeditStyle() */ - void GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const override; + void GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const override; private: /** @@ -279,14 +274,13 @@ private: void DeleteContext(); private: - /** * @brief Process event key down, whether filter a key to isf. * * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyDown(const Dali::KeyEvent& keyEvent); /** * @brief Process event key up, whether filter a key to isf. @@ -294,7 +288,7 @@ private: * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyUp(const Dali::KeyEvent& keyEvent); /** * Ecore_Event_Modifier enums in Ecore_Input.h do not match Ecore_IMF_Keyboard_Modifiers in Ecore_IMF.h. @@ -302,25 +296,25 @@ private: * @param[in] ecoreModifier the Ecore_Event_Modifier input. * @return the Ecore_IMF_Keyboard_Modifiers output. */ - Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier( unsigned int ecoreModifier ); + Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier); /** * EcoreInputModifierToEcoreIMFLock function converts from Ecore_Event_Modifier to Ecore_IMF_Keyboard_Locks enums. * @param[in] modifier the Ecore_Event_Modifier input. * @return the Ecore_IMF_Keyboard_Locks output. */ - Ecore_IMF_Keyboard_Locks EcoreInputModifierToEcoreIMFLock( unsigned int modifier ); + Ecore_IMF_Keyboard_Locks EcoreInputModifierToEcoreIMFLock(unsigned int modifier); /** * Called when the binded actor is added to a window. */ - void OnStaged( Dali::Actor actor ); + void OnStaged(Dali::Actor actor); private: /** * @brief Constructor. */ - explicit InputMethodContextEcoreWl( Dali::Actor actor ); + explicit InputMethodContextEcoreWl(Dali::Actor actor); protected: /** @@ -330,27 +324,27 @@ protected: private: // Undefined copy constructor - explicit InputMethodContextEcoreWl( const InputMethodContextEcoreWl& inputMethodContext) = delete; + explicit InputMethodContextEcoreWl(const InputMethodContextEcoreWl& inputMethodContext) = delete; // Undefined assignment operator - InputMethodContextEcoreWl& operator=( const InputMethodContextEcoreWl& inputMethodContext ) = delete; + InputMethodContextEcoreWl& operator=(const InputMethodContextEcoreWl& inputMethodContext) = delete; private: Ecore_IMF_Context* mIMFContext; - int mIMFCursorPosition; - std::string mSurroundingText; + int mIMFCursorPosition; + std::string mSurroundingText; - bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. - bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected. + bool mRestoreAfterFocusLost : 1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. + bool mIdleCallbackConnected : 1; ///< Whether the idle callback is already connected. std::vector mKeyEvents; ///< Stores key events to be sent from idle call-back. - InputMethodOptions mOptions; + InputMethodOptions mOptions; + Dali::InputMethodContext::PreEditAttributeDataContainer mPreeditAttrs; ///< Stores preedit attribute data int mWindowId; }; - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/input/tizen-wayland/key-mapping-ecore-wl.cpp b/dali/internal/input/tizen-wayland/key-mapping-ecore-wl.cpp index 5135819..a48bf8a 100644 --- a/dali/internal/input/tizen-wayland/key-mapping-ecore-wl.cpp +++ b/dali/internal/input/tizen-wayland/key-mapping-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,14 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace KeyLookup { - // matches a DALI_KEY enum, to a key name +// clang-format off KeyLookup KeyLookupTable[]= { // more than one key name can be assigned to a single dali-key code @@ -90,8 +87,9 @@ KeyLookup KeyLookupTable[]= { "Control_R", static_cast( DevelKey::DALI_KEY_CONTROL_RIGHT ), false }, { "Return", static_cast( DevelKey::DALI_KEY_RETURN ), false } }; +// clang-format on -const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup )); +const std::size_t KEY_LOOKUP_COUNT = (sizeof(KeyLookupTable)) / (sizeof(KeyLookup)); } // namespace KeyLookup diff --git a/dali/internal/input/tizen-wayland/virtual-keyboard-impl-ecore-wl.cpp b/dali/internal/input/tizen-wayland/virtual-keyboard-impl-ecore-wl.cpp old mode 100755 new mode 100644 index 9fd2dcc..94ef279 --- a/dali/internal/input/tizen-wayland/virtual-keyboard-impl-ecore-wl.cpp +++ b/dali/internal/input/tizen-wayland/virtual-keyboard-impl-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include +#include // INTERNAL INCLUDES #include @@ -31,32 +31,38 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace VirtualKeyboard { - Dali::InputMethod::ButtonAction::Type gButtonActionFunction = Dali::InputMethod::ButtonAction::DEFAULT; -Ecore_IMF_Input_Panel_Return_Key_Type buttonActionMapping(Dali::InputMethod::ButtonAction::Type buttonAction ) +Ecore_IMF_Input_Panel_Return_Key_Type buttonActionMapping(Dali::InputMethod::ButtonAction::Type buttonAction) { - switch( buttonAction ) + switch(buttonAction) { - case InputMethod::ButtonAction::DEFAULT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; - case InputMethod::ButtonAction::DONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE; - case InputMethod::ButtonAction::GO: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO; - case InputMethod::ButtonAction::JOIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN; - case InputMethod::ButtonAction::LOGIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN; - case InputMethod::ButtonAction::NEXT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT; - case InputMethod::ButtonAction::SEARCH: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH; - case InputMethod::ButtonAction::SEND: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND; - case InputMethod::ButtonAction::SIGNIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN; - default: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; + case InputMethod::ButtonAction::DEFAULT: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; + case InputMethod::ButtonAction::DONE: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE; + case InputMethod::ButtonAction::GO: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO; + case InputMethod::ButtonAction::JOIN: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN; + case InputMethod::ButtonAction::LOGIN: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN; + case InputMethod::ButtonAction::NEXT: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT; + case InputMethod::ButtonAction::SEARCH: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH; + case InputMethod::ButtonAction::SEND: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND; + case InputMethod::ButtonAction::SIGNIN: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN; + default: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; } } @@ -64,7 +70,7 @@ void RotateTo(int angle) { } -void SetReturnKeyType( const InputMethod::ButtonAction::Type type ) +void SetReturnKeyType(const InputMethod::ButtonAction::Type type) { } diff --git a/dali/internal/input/ubuntu-x11/dali-ecore-input.h b/dali/internal/input/ubuntu-x11/dali-ecore-input.h index 4598b70..1de8091 100644 --- a/dali/internal/input/ubuntu-x11/dali-ecore-input.h +++ b/dali/internal/input/ubuntu-x11/dali-ecore-input.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_UBUNTU_X11_DALI_ECORE_INPUT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_INPUT_UBUNTU_X11_DALI_ECORE_INPUT_H */ diff --git a/dali/internal/input/ubuntu-x11/input-method-context-factory-x.cpp b/dali/internal/input/ubuntu-x11/input-method-context-factory-x.cpp old mode 100755 new mode 100644 index fb0fe9e..c11e66a --- a/dali/internal/input/ubuntu-x11/input-method-context-factory-x.cpp +++ b/dali/internal/input/ubuntu-x11/input-method-context-factory-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ * */ -#include #include #include +#include namespace Dali { @@ -29,18 +29,15 @@ class InputMethodContext; namespace InputMethodContextFactory { - // InputMethodContext Factory to be implemented by the platform -InputMethodContextPtr CreateInputMethodContext( Dali::Actor actor ) +InputMethodContextPtr CreateInputMethodContext(Dali::Actor actor) { - return Dali::Internal::Adaptor::InputMethodContextX::New( actor ); -} - -} - + return Dali::Internal::Adaptor::InputMethodContextX::New(actor); } +} // namespace InputMethodContextFactory +} // namespace Adaptor -} -} \ No newline at end of file +} // namespace Internal +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/input/ubuntu-x11/input-method-context-impl-x.cpp b/dali/internal/input/ubuntu-x11/input-method-context-impl-x.cpp old mode 100755 new mode 100644 index 58125ad..baa721e --- a/dali/internal/input/ubuntu-x11/input-method-context-impl-x.cpp +++ b/dali/internal/input/ubuntu-x11/input-method-context-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,12 @@ #include // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES -#include #include #include #include @@ -35,16 +34,14 @@ #include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) @@ -56,27 +53,27 @@ size_t Utf8SequenceLength(const unsigned char leadByte) { size_t length = 0; - if( ( leadByte & 0x80 ) == 0 ) //ASCII character (lead bit zero) + if((leadByte & 0x80) == 0) //ASCII character (lead bit zero) { length = 1; } - else if( ( leadByte & 0xe0 ) == 0xc0 ) //110x xxxx + else if((leadByte & 0xe0) == 0xc0) //110x xxxx { length = 2; } - else if( ( leadByte & 0xf0 ) == 0xe0 ) //1110 xxxx + else if((leadByte & 0xf0) == 0xe0) //1110 xxxx { length = 3; } - else if( ( leadByte & 0xf8 ) == 0xf0 ) //1111 0xxx + else if((leadByte & 0xf8) == 0xf0) //1111 0xxx { length = 4; } - else if( ( leadByte & 0xfc ) == 0xf8 ) //1111 10xx + else if((leadByte & 0xfc) == 0xf8) //1111 10xx { length = 5; } - else if( ( leadByte & 0xfe ) == 0xfc ) //1111 110x + else if((leadByte & 0xfe) == 0xfc) //1111 110x { length = 6; } @@ -85,30 +82,30 @@ size_t Utf8SequenceLength(const unsigned char leadByte) } // Static function calls used by ecore 'c' style callback registration -void Commit( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void Commit(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextX* inputMethodContext = static_cast< InputMethodContextX* >( data ); - inputMethodContext->CommitReceived( data, imfContext, eventInfo ); + InputMethodContextX* inputMethodContext = static_cast(data); + inputMethodContext->CommitReceived(data, imfContext, eventInfo); } } -void PreEdit( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void PreEdit(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextX* inputMethodContext = static_cast< InputMethodContextX* >( data ); - inputMethodContext->PreEditChanged( data, imfContext, eventInfo ); + InputMethodContextX* inputMethodContext = static_cast(data); + inputMethodContext->PreEditChanged(data, imfContext, eventInfo); } } -Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char** text, int* cursorPosition ) +Eina_Bool ImfRetrieveSurrounding(void* data, Ecore_IMF_Context* imfContext, char** text, int* cursorPosition) { - if ( data ) + if(data) { - InputMethodContextX* inputMethodContext = static_cast< InputMethodContextX* >( data ); - return inputMethodContext->RetrieveSurrounding( data, imfContext, text, cursorPosition ); + InputMethodContextX* inputMethodContext = static_cast(data); + return inputMethodContext->RetrieveSurrounding(data, imfContext, text, cursorPosition); } else { @@ -120,24 +117,24 @@ Eina_Bool ImfRetrieveSurrounding(void *data, Ecore_IMF_Context *imfContext, char * Called when an InputMethodContext delete surrounding event is received. * Here we tell the application that it should delete a certain range. */ -void ImfDeleteSurrounding( void *data, Ecore_IMF_Context *imfContext, void *eventInfo ) +void ImfDeleteSurrounding(void* data, Ecore_IMF_Context* imfContext, void* eventInfo) { - if ( data ) + if(data) { - InputMethodContextX* inputMethodContext = static_cast< InputMethodContextX* >( data ); - inputMethodContext->DeleteSurrounding( data, imfContext, eventInfo ); + InputMethodContextX* inputMethodContext = static_cast(data); + inputMethodContext->DeleteSurrounding(data, imfContext, eventInfo); } } } // unnamed namespace -InputMethodContextPtr InputMethodContextX::New( Dali::Actor actor ) +InputMethodContextPtr InputMethodContextX::New(Dali::Actor actor) { InputMethodContextPtr manager; - if( actor && Dali::Adaptor::IsAvailable() ) + if(actor && Dali::Adaptor::IsAvailable()) { - manager = new InputMethodContextX( actor ); + manager = new InputMethodContextX(actor); } return manager; @@ -145,23 +142,23 @@ InputMethodContextPtr InputMethodContextX::New( Dali::Actor actor ) void InputMethodContextX::Finalize() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::Finalize\n" ); - VirtualKeyboard::DisconnectCallbacks( mIMFContext ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::Finalize\n"); + VirtualKeyboard::DisconnectCallbacks(mIMFContext); DisconnectCallbacks(); DeleteContext(); } -InputMethodContextX::InputMethodContextX( Dali::Actor actor ) +InputMethodContextX::InputMethodContextX(Dali::Actor actor) : mIMFContext(), - mEcoreXwin( 0 ), - mIMFCursorPosition( 0 ), + mEcoreXwin(0), + mIMFCursorPosition(0), mSurroundingText(), - mRestoreAfterFocusLost( false ), - mIdleCallbackConnected( false ) + mRestoreAfterFocusLost(false), + mIdleCallbackConnected(false) { ecore_imf_init(); - actor.OnSceneSignal().Connect( this, &InputMethodContextX::OnStaged ); + actor.OnSceneSignal().Connect(this, &InputMethodContextX::OnStaged); } InputMethodContextX::~InputMethodContextX() @@ -174,45 +171,45 @@ void InputMethodContextX::Initialize() { CreateContext(); ConnectCallbacks(); - VirtualKeyboard::ConnectCallbacks( mIMFContext ); + VirtualKeyboard::ConnectCallbacks(mIMFContext); } void InputMethodContextX::CreateContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::CreateContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::CreateContext\n"); - if( !mEcoreXwin ) + if(!mEcoreXwin) { return; } - const char *contextId = ecore_imf_context_default_id_get(); - if( contextId ) + const char* contextId = ecore_imf_context_default_id_get(); + if(contextId) { - mIMFContext = ecore_imf_context_add( contextId ); + mIMFContext = ecore_imf_context_add(contextId); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_client_window_set( mIMFContext, reinterpret_cast( mEcoreXwin ) ); + ecore_imf_context_client_window_set(mIMFContext, reinterpret_cast(mEcoreXwin)); } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContext Unable to get IMFContext\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContext Unable to get IMFContext\n"); } } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContext Unable to get IMFContext\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContext Unable to get IMFContext\n"); } } void InputMethodContextX::DeleteContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::DeleteContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::DeleteContext\n"); - if ( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_del( mIMFContext ); + ecore_imf_context_del(mIMFContext); mIMFContext = NULL; } } @@ -220,27 +217,27 @@ void InputMethodContextX::DeleteContext() // Callbacks for predicitive text support. void InputMethodContextX::ConnectCallbacks() { - if ( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::ConnectCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::ConnectCallbacks\n"); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this ); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this ); - ecore_imf_context_event_callback_add( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this ); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit, this); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit, this); + ecore_imf_context_event_callback_add(mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding, this); - ecore_imf_context_retrieve_surrounding_callback_set( mIMFContext, ImfRetrieveSurrounding, this); + ecore_imf_context_retrieve_surrounding_callback_set(mIMFContext, ImfRetrieveSurrounding, this); } } void InputMethodContextX::DisconnectCallbacks() { - if ( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::DisconnectCallbacks\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::DisconnectCallbacks\n"); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit ); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit ); - ecore_imf_context_event_callback_del( mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding ); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_PREEDIT_CHANGED, PreEdit); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_COMMIT, Commit); + ecore_imf_context_event_callback_del(mIMFContext, ECORE_IMF_CALLBACK_DELETE_SURROUNDING, ImfDeleteSurrounding); // We do not need to unset the retrieve surrounding callback. } @@ -251,26 +248,26 @@ void InputMethodContextX::Activate() // Reset mIdleCallbackConnected mIdleCallbackConnected = false; - if ( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::Activate\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::Activate\n"); - ecore_imf_context_focus_in( mIMFContext ); + ecore_imf_context_focus_in(mIMFContext); // emit keyboard activated signal - Dali::InputMethodContext handle( this ); - mActivatedSignal.Emit( handle ); + Dali::InputMethodContext handle(this); + mActivatedSignal.Emit(handle); } } void InputMethodContextX::Deactivate() { - if( mIMFContext ) + if(mIMFContext) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::Deactivate\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::Deactivate\n"); Reset(); - ecore_imf_context_focus_out( mIMFContext ); + ecore_imf_context_focus_out(mIMFContext); } // Reset mIdleCallbackConnected @@ -279,17 +276,17 @@ void InputMethodContextX::Deactivate() void InputMethodContextX::Reset() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::Reset\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::Reset\n"); - if ( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_reset( mIMFContext ); + ecore_imf_context_reset(mIMFContext); } } ImfContext* InputMethodContextX::GetContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetContext\n"); return mIMFContext; } @@ -299,7 +296,7 @@ bool InputMethodContextX::RestoreAfterFocusLost() const return mRestoreAfterFocusLost; } -void InputMethodContextX::SetRestoreAfterFocusLost( bool toggle ) +void InputMethodContextX::SetRestoreAfterFocusLost(bool toggle) { mRestoreAfterFocusLost = toggle; } @@ -309,15 +306,15 @@ void InputMethodContextX::SetRestoreAfterFocusLost( bool toggle ) * We are still predicting what the user is typing. The latest string is what the InputMethodContext module thinks * the user wants to type. */ -void InputMethodContextX::PreEditChanged( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextX::PreEditChanged(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::PreEditChanged\n" ); - auto context = static_cast( imfContext ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::PreEditChanged\n"); + auto context = static_cast(imfContext); - char* preEditString( NULL ); - int cursorPosition( 0 ); + char* preEditString(NULL); + int cursorPosition(0); Eina_List* attrs = NULL; - Eina_List* l = NULL; + Eina_List* l = NULL; Ecore_IMF_Preedit_Attr* attr; @@ -325,34 +322,34 @@ void InputMethodContextX::PreEditChanged( void*, ImfContext* imfContext, void* e // Retrieves attributes as well as the string the cursor position offset from start of pre-edit string. // the attributes (attrs) is used in languages that use the soft arrows keys to insert characters into a current pre-edit string. - ecore_imf_context_preedit_string_with_attributes_get( context, &preEditString, &attrs, &cursorPosition ); + ecore_imf_context_preedit_string_with_attributes_get(context, &preEditString, &attrs, &cursorPosition); - if ( attrs ) + if(attrs) { // iterate through the list of attributes getting the type, start and end position. - for ( l = attrs, (attr = static_cast( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( attr = static_cast( eina_list_data_get(l) ) )) + for(l = attrs, (attr = static_cast(eina_list_data_get(l))); l; l = eina_list_next(l), (attr = static_cast(eina_list_data_get(l)))) { Dali::InputMethodContext::PreeditAttributeData data; data.startIndex = 0; - data.endIndex = 0; + data.endIndex = 0; size_t visualCharacterIndex = 0; - size_t byteIndex = 0; + size_t byteIndex = 0; // iterate through null terminated string checking each character's position against the given byte position ( attr->end_index ). char leadByte = preEditString[byteIndex]; - while( leadByte != '\0' ) + while(leadByte != '\0') { leadByte = preEditString[byteIndex]; // Update the character to get the number of its byte // attr->end_index is provided as a byte position not character and we need to know the character position. - const size_t currentSequenceLength = Utf8SequenceLength( leadByte ); // returns number of bytes used to represent character. - if( byteIndex <= attr->start_index ) + const size_t currentSequenceLength = Utf8SequenceLength(leadByte); // returns number of bytes used to represent character. + if(byteIndex <= attr->start_index) { - data.startIndex = visualCharacterIndex; + data.startIndex = visualCharacterIndex; } - if( byteIndex >= attr->end_index ) + if(byteIndex >= attr->end_index) { data.endIndex = visualCharacterIndex; break; @@ -361,11 +358,11 @@ void InputMethodContextX::PreEditChanged( void*, ImfContext* imfContext, void* e else { byteIndex += currentSequenceLength; // jump to next character - visualCharacterIndex++; // increment character count so we know our position for when we get a match + visualCharacterIndex++; // increment character count so we know our position for when we get a match } } - switch( attr->preedit_type ) + switch(attr->preedit_type) { case ECORE_IMF_PREEDIT_TYPE_NONE: { @@ -413,46 +410,46 @@ void InputMethodContextX::PreEditChanged( void*, ImfContext* imfContext, void* e break; } } - mPreeditAttrs.PushBack( data ); + mPreeditAttrs.PushBack(data); } } - if ( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::EventData eventData( Dali::InputMethodContext::PRE_EDIT, preEditString, cursorPosition, 0 ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, eventData ); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::EventData eventData(Dali::InputMethodContext::PRE_EDIT, preEditString, cursorPosition, 0); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, eventData); - if( callbackData.update ) + if(callbackData.update) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); + mIMFCursorPosition = static_cast(callbackData.cursorPosition); NotifyCursorPosition(); } - if( callbackData.preeditResetRequired ) + if(callbackData.preeditResetRequired) { Reset(); } } - free( preEditString ); + free(preEditString); } -void InputMethodContextX::CommitReceived( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextX::CommitReceived(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::CommitReceived\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::CommitReceived\n"); - if ( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - const std::string keyString( static_cast( eventInfo ) ); + const std::string keyString(static_cast(eventInfo)); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::EventData eventData( Dali::InputMethodContext::COMMIT, keyString, 0, 0 ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, eventData ); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::EventData eventData(Dali::InputMethodContext::COMMIT, keyString, 0, 0); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, eventData); - if( callbackData.update ) + if(callbackData.update) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); + mIMFCursorPosition = static_cast(callbackData.cursorPosition); NotifyCursorPosition(); } @@ -464,25 +461,25 @@ void InputMethodContextX::CommitReceived( void*, ImfContext* imfContext, void* e * Here the InputMethodContext module wishes to know the string we are working with and where within the string the cursor is * We need to signal the application to tell us this information. */ -bool InputMethodContextX::RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) +bool InputMethodContextX::RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::RetrieveSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::RetrieveSurrounding\n"); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0 ); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, imfData); - if( callbackData.update ) + if(callbackData.update) { - if( text ) + if(text) { - *text = strdup( callbackData.currentText.c_str() ); + *text = strdup(callbackData.currentText.c_str()); } - if( cursorPosition ) + if(cursorPosition) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); - *cursorPosition = mIMFCursorPosition; + mIMFCursorPosition = static_cast(callbackData.cursorPosition); + *cursorPosition = mIMFCursorPosition; } } @@ -493,21 +490,21 @@ bool InputMethodContextX::RetrieveSurrounding( void* data, ImfContext* imfContex * Called when an InputMethodContext delete surrounding event is received. * Here we tell the application that it should delete a certain range. */ -void InputMethodContextX::DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextX::DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::DeleteSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::DeleteSurrounding\n"); - if( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast( eventInfo ); + Ecore_IMF_Event_Delete_Surrounding* deleteSurroundingEvent = static_cast(eventInfo); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::DELETE_SURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars ); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::DELETE_SURROUNDING, std::string(), deleteSurroundingEvent->offset, deleteSurroundingEvent->n_chars); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, imfData); - if( callbackData.update ) + if(callbackData.update) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); + mIMFCursorPosition = static_cast(callbackData.cursorPosition); NotifyCursorPosition(); } @@ -516,61 +513,61 @@ void InputMethodContextX::DeleteSurrounding( void* data, ImfContext* imfContext, void InputMethodContextX::NotifyCursorPosition() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::NotifyCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::NotifyCursorPosition\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_cursor_position_set( mIMFContext, mIMFCursorPosition ); + ecore_imf_context_cursor_position_set(mIMFContext, mIMFCursorPosition); } } -void InputMethodContextX::SetCursorPosition( unsigned int cursorPosition ) +void InputMethodContextX::SetCursorPosition(unsigned int cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetCursorPosition\n"); - mIMFCursorPosition = static_cast( cursorPosition ); + mIMFCursorPosition = static_cast(cursorPosition); } unsigned int InputMethodContextX::GetCursorPosition() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetCursorPosition\n"); - return static_cast( mIMFCursorPosition ); + return static_cast(mIMFCursorPosition); } -void InputMethodContextX::SetSurroundingText( const std::string& text ) +void InputMethodContextX::SetSurroundingText(const std::string& text) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetSurroundingText\n"); mSurroundingText = text; } const std::string& InputMethodContextX::GetSurroundingText() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetSurroundingText\n"); return mSurroundingText; } -void InputMethodContextX::NotifyTextInputMultiLine( bool multiLine ) +void InputMethodContextX::NotifyTextInputMultiLine(bool multiLine) { } Dali::InputMethodContext::TextDirection InputMethodContextX::GetTextDirection() { - Dali::InputMethodContext::TextDirection direction ( Dali::InputMethodContext::LEFT_TO_RIGHT ); + Dali::InputMethodContext::TextDirection direction(Dali::InputMethodContext::LEFT_TO_RIGHT); - if ( mIMFContext ) - { - char* locale( NULL ); - ecore_imf_context_input_panel_language_locale_get( mIMFContext, &locale ); + if(mIMFContext) + { + char* locale(NULL); + ecore_imf_context_input_panel_language_locale_get(mIMFContext, &locale); - if ( locale ) - { - direction = static_cast< Dali::InputMethodContext::TextDirection >( Locale::GetDirection( std::string( locale ) ) ); - free( locale ); - } + if(locale) + { + direction = static_cast(Locale::GetDirection(std::string(locale))); + free(locale); } + } return direction; } @@ -581,79 +578,79 @@ Rect InputMethodContextX::GetInputMethodArea() width = height = xPos = yPos = 0; - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_geometry_get( mIMFContext, &xPos, &yPos, &width, &height ); + ecore_imf_context_input_panel_geometry_get(mIMFContext, &xPos, &yPos, &width, &height); } else { DALI_LOG_WARNING("VKB Unable to get InputMethodContext Context so GetSize unavailable\n"); } - return Rect(xPos,yPos,width,height); + return Rect(xPos, yPos, width, height); } -void InputMethodContextX::ApplyOptions( const InputMethodOptions& options ) +void InputMethodContextX::ApplyOptions(const InputMethodOptions& options) { using namespace Dali::InputMethod::Category; int index; - if (mIMFContext == NULL) + if(mIMFContext == NULL) { DALI_LOG_WARNING("VKB Unable to excute ApplyOptions with Null ImfContext\n"); return; } - if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) ) + if(mOptions.CompareAndSet(PANEL_LAYOUT, options, index)) { } - if ( mOptions.CompareAndSet(BUTTON_ACTION, options, index) ) + if(mOptions.CompareAndSet(BUTTON_ACTION, options, index)) { } - if ( mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index) ) + if(mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index)) { } - if ( mOptions.CompareAndSet(VARIATION, options, index) ) + if(mOptions.CompareAndSet(VARIATION, options, index)) { } } -void InputMethodContextX::SetInputPanelData( const std::string& data ) +void InputMethodContextX::SetInputPanelData(const std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelData\n"); - if( mIMFContext ) + if(mIMFContext) { int length = data.length(); - ecore_imf_context_input_panel_imdata_set( mIMFContext, data.c_str(), length ); + ecore_imf_context_input_panel_imdata_set(mIMFContext, data.c_str(), length); } } -void InputMethodContextX::GetInputPanelData( std::string& data ) +void InputMethodContextX::GetInputPanelData(std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelData\n"); - if( mIMFContext ) + if(mIMFContext) { - int length = 4096; // The max length is 4096 bytes - Dali::Vector< char > buffer; - buffer.Resize( length ); - ecore_imf_context_input_panel_imdata_get( mIMFContext, &buffer[0], &length ); - data = std::string( buffer.Begin(), buffer.End() ); + int length = 4096; // The max length is 4096 bytes + Dali::Vector buffer; + buffer.Resize(length); + ecore_imf_context_input_panel_imdata_get(mIMFContext, &buffer[0], &length); + data = std::string(buffer.Begin(), buffer.End()); } } Dali::InputMethodContext::State InputMethodContextX::GetInputPanelState() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelState\n"); - if( mIMFContext ) + if(mIMFContext) { int value; - value = ecore_imf_context_input_panel_state_get( mIMFContext ); + value = ecore_imf_context_input_panel_state_get(mIMFContext); - switch (value) + switch(value) { case ECORE_IMF_INPUT_PANEL_STATE_SHOW: { @@ -682,43 +679,43 @@ Dali::InputMethodContext::State InputMethodContextX::GetInputPanelState() return Dali::InputMethodContext::DEFAULT; } -void InputMethodContextX::SetReturnKeyState( bool visible ) +void InputMethodContextX::SetReturnKeyState(bool visible) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetReturnKeyState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetReturnKeyState\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_return_key_disabled_set( mIMFContext, !visible ); + ecore_imf_context_input_panel_return_key_disabled_set(mIMFContext, !visible); } } -void InputMethodContextX::AutoEnableInputPanel( bool enabled ) +void InputMethodContextX::AutoEnableInputPanel(bool enabled) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::AutoEnableInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::AutoEnableInputPanel\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_enabled_set( mIMFContext, enabled ); + ecore_imf_context_input_panel_enabled_set(mIMFContext, enabled); } } void InputMethodContextX::ShowInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::ShowInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::ShowInputPanel\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_show( mIMFContext ); + ecore_imf_context_input_panel_show(mIMFContext); } } void InputMethodContextX::HideInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::HideInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::HideInputPanel\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_input_panel_hide( mIMFContext ); + ecore_imf_context_input_panel_hide(mIMFContext); } } @@ -729,90 +726,90 @@ Dali::InputMethodContext::KeyboardType InputMethodContextX::GetKeyboardType() std::string InputMethodContextX::GetInputPanelLocale() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelLocale\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelLocale\n"); std::string locale = ""; - if( mIMFContext ) + if(mIMFContext) { char* value = NULL; - ecore_imf_context_input_panel_language_locale_get( mIMFContext, &value ); + ecore_imf_context_input_panel_language_locale_get(mIMFContext, &value); - if( value ) + if(value) { - std::string valueCopy( value ); + std::string valueCopy(value); locale = valueCopy; // The locale string retrieved must be freed with free(). - free( value ); + free(value); } } return locale; } -void InputMethodContextX::SetContentMIMETypes( const std::string& mimeTypes ) +void InputMethodContextX::SetContentMIMETypes(const std::string& mimeTypes) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetContentMIMETypes\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetContentMIMETypes\n"); // ecore_imf_context_mime_type_accept_set() is supported from ecore-imf 1.20.0 version. } -bool InputMethodContextX::FilterEventKey( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextX::FilterEventKey(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); // If a device key then skip ecore_imf_context_filter_event. - if ( ! KeyLookup::IsDeviceButton( keyEvent.GetKeyName().c_str() )) + if(!KeyLookup::IsDeviceButton(keyEvent.GetKeyName().c_str())) { //check whether it's key down or key up event - if ( keyEvent.GetState() == Dali::KeyEvent::DOWN ) + if(keyEvent.GetState() == Dali::KeyEvent::DOWN) { - eventHandled = ProcessEventKeyDown( keyEvent ); + eventHandled = ProcessEventKeyDown(keyEvent); } - else if ( keyEvent.GetState() == Dali::KeyEvent::UP ) + else if(keyEvent.GetState() == Dali::KeyEvent::UP) { - eventHandled = ProcessEventKeyUp( keyEvent ); + eventHandled = ProcessEventKeyUp(keyEvent); } } return eventHandled; } -void InputMethodContextX::AllowTextPrediction( bool prediction ) +void InputMethodContextX::AllowTextPrediction(bool prediction) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::AllowTextPrediction\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::AllowTextPrediction\n"); - if( mIMFContext ) + if(mIMFContext) { - ecore_imf_context_prediction_allow_set( mIMFContext, prediction ); + ecore_imf_context_prediction_allow_set(mIMFContext, prediction); } } bool InputMethodContextX::IsTextPredictionAllowed() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::IsTextPredictionAllowed\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::IsTextPredictionAllowed\n"); bool prediction = false; - if( mIMFContext ) + if(mIMFContext) { - prediction = ecore_imf_context_prediction_allow_get( mIMFContext ); + prediction = ecore_imf_context_prediction_allow_get(mIMFContext); } return prediction; } -void InputMethodContextX::SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) +void InputMethodContextX::SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelLanguage\n" ); - if( mIMFContext ) + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelLanguage\n"); + if(mIMFContext) { - switch (language) + switch(language) { case Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC: { - ecore_imf_context_input_panel_language_set( mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_AUTOMATIC ); + ecore_imf_context_input_panel_language_set(mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_AUTOMATIC); break; } case Dali::InputMethodContext::InputPanelLanguage::ALPHABET: { - ecore_imf_context_input_panel_language_set( mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_ALPHABET ); + ecore_imf_context_input_panel_language_set(mIMFContext, ECORE_IMF_INPUT_PANEL_LANG_ALPHABET); break; } } @@ -821,13 +818,13 @@ void InputMethodContextX::SetInputPanelLanguage( Dali::InputMethodContext::Input Dali::InputMethodContext::InputPanelLanguage InputMethodContextX::GetInputPanelLanguage() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelLanguage\n" ); - if( mIMFContext ) + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetInputPanelLanguage\n"); + if(mIMFContext) { int value; - value = ecore_imf_context_input_panel_language_get( mIMFContext ); + value = ecore_imf_context_input_panel_language_get(mIMFContext); - switch (value) + switch(value) { case ECORE_IMF_INPUT_PANEL_LANG_AUTOMATIC: { @@ -844,55 +841,55 @@ Dali::InputMethodContext::InputPanelLanguage InputMethodContextX::GetInputPanelL return Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC; } -void InputMethodContextX::SetInputPanelPosition( unsigned int x, unsigned int y ) +void InputMethodContextX::SetInputPanelPosition(unsigned int x, unsigned int y) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::SetInputPanelPosition\n"); // ecore_imf_context_input_panel_position_set() is supported from ecore-imf 1.21.0 version. } -void InputMethodContextX::GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const +void InputMethodContextX::GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextX::GetPreeditStyle\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextX::GetPreeditStyle\n"); attrs = mPreeditAttrs; } -bool InputMethodContextX::ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextX::ProcessEventKeyDown(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); - if ( mIMFContext ) + bool eventHandled(false); + if(mIMFContext) { - Integration::KeyEvent integKeyEvent( keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast< Integration::KeyEvent::State >( keyEvent.GetState() ), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass() ); - std::string key = integKeyEvent.logicalKey; + Integration::KeyEvent integKeyEvent(keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast(keyEvent.GetState()), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass()); + std::string key = integKeyEvent.logicalKey; std::string compose = integKeyEvent.compose; // We're consuming key down event so we have to pass to InputMethodContext so that it can parse it as well. Ecore_IMF_Event_Key_Down ecoreKeyDownEvent; - ecoreKeyDownEvent.keyname = integKeyEvent.keyName.c_str(); - ecoreKeyDownEvent.key = key.c_str(); - ecoreKeyDownEvent.string = integKeyEvent.keyString.c_str(); - ecoreKeyDownEvent.compose = compose.c_str(); + ecoreKeyDownEvent.keyname = integKeyEvent.keyName.c_str(); + ecoreKeyDownEvent.key = key.c_str(); + ecoreKeyDownEvent.string = integKeyEvent.keyString.c_str(); + ecoreKeyDownEvent.compose = compose.c_str(); ecoreKeyDownEvent.timestamp = integKeyEvent.time; - ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier( integKeyEvent.keyModifier ); - ecoreKeyDownEvent.locks = EcoreInputModifierToEcoreIMFLock( integKeyEvent.keyModifier ); + ecoreKeyDownEvent.modifiers = EcoreInputModifierToEcoreIMFModifier(integKeyEvent.keyModifier); + ecoreKeyDownEvent.locks = EcoreInputModifierToEcoreIMFLock(integKeyEvent.keyModifier); #if defined(ECORE_VERSION_MAJOR) && (ECORE_VERSION_MAJOR >= 1) && defined(ECORE_VERSION_MINOR) -#if (ECORE_VERSION_MINOR >= 14) - ecoreKeyDownEvent.dev_name = ""; - ecoreKeyDownEvent.dev_class = ECORE_IMF_DEVICE_CLASS_KEYBOARD; +#if(ECORE_VERSION_MINOR >= 14) + ecoreKeyDownEvent.dev_name = ""; + ecoreKeyDownEvent.dev_class = ECORE_IMF_DEVICE_CLASS_KEYBOARD; ecoreKeyDownEvent.dev_subclass = ECORE_IMF_DEVICE_SUBCLASS_NONE; #endif // Since ecore_imf 1.14 version -#if (ECORE_VERSION_MINOR >= 22) +#if(ECORE_VERSION_MINOR >= 22) ecoreKeyDownEvent.keycode = integKeyEvent.keyCode; #endif // Since ecore_imf 1.22 version #endif // Since ecore_imf Version 1 // If the device is IME and the focused key is the direction keys, then we should send a key event to move a key cursor. - if ((integKeyEvent.deviceName == "ime") && ((!strncmp(integKeyEvent.keyName.c_str(), "Left", 4)) || - (!strncmp(integKeyEvent.keyName.c_str(), "Right", 5)) || - (!strncmp(integKeyEvent.keyName.c_str(), "Up", 2)) || - (!strncmp(integKeyEvent.keyName.c_str(), "Down", 4)))) + if((integKeyEvent.deviceName == "ime") && ((!strncmp(integKeyEvent.keyName.c_str(), "Left", 4)) || + (!strncmp(integKeyEvent.keyName.c_str(), "Right", 5)) || + (!strncmp(integKeyEvent.keyName.c_str(), "Up", 2)) || + (!strncmp(integKeyEvent.keyName.c_str(), "Down", 4)))) { eventHandled = 0; } @@ -900,15 +897,15 @@ bool InputMethodContextX::ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ) { eventHandled = ecore_imf_context_filter_event(mIMFContext, ECORE_IMF_EVENT_KEY_DOWN, - reinterpret_cast( &ecoreKeyDownEvent )); + reinterpret_cast(&ecoreKeyDownEvent)); } // If the event has not been handled by InputMethodContext then check if we should reset our IMFcontext - if (!eventHandled) + if(!eventHandled) { - if (!strcmp(integKeyEvent.keyName.c_str(), "Escape") || - !strcmp(integKeyEvent.keyName.c_str(), "Return") || - !strcmp(integKeyEvent.keyName.c_str(), "KP_Enter")) + if(!strcmp(integKeyEvent.keyName.c_str(), "Escape") || + !strcmp(integKeyEvent.keyName.c_str(), "Return") || + !strcmp(integKeyEvent.keyName.c_str(), "KP_Enter")) { ecore_imf_context_reset(mIMFContext); } @@ -917,12 +914,12 @@ bool InputMethodContextX::ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ) return eventHandled; } -bool InputMethodContextX::ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextX::ProcessEventKeyUp(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); - if( mIMFContext ) + bool eventHandled(false); + if(mIMFContext) { - Integration::KeyEvent integKeyEvent( keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast< Integration::KeyEvent::State >( keyEvent.GetState() ), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass() ); + Integration::KeyEvent integKeyEvent(keyEvent.GetKeyName(), keyEvent.GetLogicalKey(), keyEvent.GetKeyString(), keyEvent.GetKeyCode(), keyEvent.GetKeyModifier(), keyEvent.GetTime(), static_cast(keyEvent.GetState()), keyEvent.GetCompose(), keyEvent.GetDeviceName(), keyEvent.GetDeviceClass(), keyEvent.GetDeviceSubclass()); std::string key = integKeyEvent.logicalKey; @@ -930,88 +927,88 @@ bool InputMethodContextX::ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ) // We're consuming key up event so we have to pass to InputMethodContext so that it can parse it as well. Ecore_IMF_Event_Key_Up ecoreKeyUpEvent; - ecoreKeyUpEvent.keyname = integKeyEvent.keyName.c_str(); - ecoreKeyUpEvent.key = key.c_str(); - ecoreKeyUpEvent.string = integKeyEvent.keyString.c_str(); - ecoreKeyUpEvent.compose = compose.c_str(); + ecoreKeyUpEvent.keyname = integKeyEvent.keyName.c_str(); + ecoreKeyUpEvent.key = key.c_str(); + ecoreKeyUpEvent.string = integKeyEvent.keyString.c_str(); + ecoreKeyUpEvent.compose = compose.c_str(); ecoreKeyUpEvent.timestamp = integKeyEvent.time; - ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier( integKeyEvent.keyModifier ); - ecoreKeyUpEvent.locks = EcoreInputModifierToEcoreIMFLock( integKeyEvent.keyModifier ); + ecoreKeyUpEvent.modifiers = EcoreInputModifierToEcoreIMFModifier(integKeyEvent.keyModifier); + ecoreKeyUpEvent.locks = EcoreInputModifierToEcoreIMFLock(integKeyEvent.keyModifier); #if defined(ECORE_VERSION_MAJOR) && (ECORE_VERSION_MAJOR >= 1) && defined(ECORE_VERSION_MINOR) -#if (ECORE_VERSION_MINOR >= 14) - ecoreKeyUpEvent.dev_name = ""; +#if(ECORE_VERSION_MINOR >= 14) + ecoreKeyUpEvent.dev_name = ""; #endif // Since ecore_imf 1.14 version -#if (ECORE_VERSION_MINOR >= 22) +#if(ECORE_VERSION_MINOR >= 22) ecoreKeyUpEvent.keycode = integKeyEvent.keyCode; #endif // Since ecore_imf 1.22 version #endif // Since ecore_imf Version 1 eventHandled = ecore_imf_context_filter_event(mIMFContext, ECORE_IMF_EVENT_KEY_UP, - reinterpret_cast( &ecoreKeyUpEvent )); + reinterpret_cast(&ecoreKeyUpEvent)); } return eventHandled; } -Ecore_IMF_Keyboard_Modifiers InputMethodContextX::EcoreInputModifierToEcoreIMFModifier( unsigned int ecoreModifier ) +Ecore_IMF_Keyboard_Modifiers InputMethodContextX::EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier) { - unsigned int modifier( ECORE_IMF_KEYBOARD_MODIFIER_NONE ); // If no other matches returns NONE. + unsigned int modifier(ECORE_IMF_KEYBOARD_MODIFIER_NONE); // If no other matches returns NONE. - if ( ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT ) // enums from ecore_input/Ecore_Input.h + if(ecoreModifier & ECORE_EVENT_MODIFIER_SHIFT) // enums from ecore_input/Ecore_Input.h { - modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h + modifier |= ECORE_IMF_KEYBOARD_MODIFIER_SHIFT; // enums from ecore_imf/ecore_imf.h } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALT ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_ALT) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALT; } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_CTRL ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_CTRL) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_CTRL; } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_WIN ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_WIN) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_WIN; } - if ( ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR ) + if(ecoreModifier & ECORE_EVENT_MODIFIER_ALTGR) { modifier |= ECORE_IMF_KEYBOARD_MODIFIER_ALTGR; } - return static_cast( modifier ); + return static_cast(modifier); } -Ecore_IMF_Keyboard_Locks InputMethodContextX::EcoreInputModifierToEcoreIMFLock( unsigned int modifier ) +Ecore_IMF_Keyboard_Locks InputMethodContextX::EcoreInputModifierToEcoreIMFLock(unsigned int modifier) { - unsigned int lock( ECORE_IMF_KEYBOARD_LOCK_NONE ); // If no other matches, returns NONE. + unsigned int lock(ECORE_IMF_KEYBOARD_LOCK_NONE); // If no other matches, returns NONE. - if( modifier & ECORE_EVENT_LOCK_NUM ) - { - lock |= ECORE_IMF_KEYBOARD_LOCK_NUM; // Num lock is active. - } + if(modifier & ECORE_EVENT_LOCK_NUM) + { + lock |= ECORE_IMF_KEYBOARD_LOCK_NUM; // Num lock is active. + } - if( modifier & ECORE_EVENT_LOCK_CAPS ) - { - lock |= ECORE_IMF_KEYBOARD_LOCK_CAPS; // Caps lock is active. - } + if(modifier & ECORE_EVENT_LOCK_CAPS) + { + lock |= ECORE_IMF_KEYBOARD_LOCK_CAPS; // Caps lock is active. + } - if( modifier & ECORE_EVENT_LOCK_SCROLL ) - { - lock |= ECORE_IMF_KEYBOARD_LOCK_SCROLL; // Scroll lock is active. - } + if(modifier & ECORE_EVENT_LOCK_SCROLL) + { + lock |= ECORE_IMF_KEYBOARD_LOCK_SCROLL; // Scroll lock is active. + } - return static_cast( lock ); + return static_cast(lock); } -void InputMethodContextX::OnStaged( Dali::Actor actor ) +void InputMethodContextX::OnStaged(Dali::Actor actor) { - Ecore_X_Window ecoreXwin( AnyCast< Ecore_X_Window >( Dali::Integration::SceneHolder::Get( actor ).GetNativeHandle() ) ); + Ecore_X_Window ecoreXwin(AnyCast(Dali::Integration::SceneHolder::Get(actor).GetNativeHandle())); - if( mEcoreXwin != ecoreXwin ) + if(mEcoreXwin != ecoreXwin) { mEcoreXwin = ecoreXwin; @@ -1021,8 +1018,8 @@ void InputMethodContextX::OnStaged( Dali::Actor actor ) } } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/input/ubuntu-x11/input-method-context-impl-x.h b/dali/internal/input/ubuntu-x11/input-method-context-impl-x.h old mode 100755 new mode 100644 index 9dbfaca..8727249 --- a/dali/internal/input/ubuntu-x11/input-method-context-impl-x.h +++ b/dali/internal/input/ubuntu-x11/input-method-context-impl-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_METHOD_CONTEXT_IMPL_X_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,15 +30,12 @@ namespace Dali { - class RenderSurface; namespace Internal { - namespace Adaptor { - class InputMethodContextX : public Dali::Internal::Adaptor::InputMethodContext, public Dali::ConnectionTracker { public: @@ -48,16 +45,15 @@ public: * @param[in] actor The actor that uses the new InputMethodContext instance. * @return InputMethodContext pointer */ - static InputMethodContextPtr New( Dali::Actor actor ); + static InputMethodContextPtr New(Dali::Actor actor); /** * Constructor * @param[in] actor The actor that uses the new InputMethodContext instance. */ - explicit InputMethodContextX( Dali::Actor actor ); + explicit InputMethodContextX(Dali::Actor actor); public: - /** * @brief Initializes member data. */ @@ -108,39 +104,41 @@ public: /** * @copydoc Dali::InputMethodContext::SetRestoreAfterFocusLost() */ - void SetRestoreAfterFocusLost( bool toggle ) override; + void SetRestoreAfterFocusLost(bool toggle) override; /** * @copydoc Dali::InputMethodContext::PreEditChanged() */ - void PreEditChanged( void* data, ImfContext* imfContext, void* eventInfo ) override; + void PreEditChanged(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - void CommitReceived( void* data, ImfContext* imfContext, void* eventInfo ) override; + void CommitReceived(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - bool RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) override; + bool RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) override; /** * @copydoc Dali::InputMethodContext::DeleteSurrounding() */ - void DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) override; + void DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::SendPrivateCommand() */ - void SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) override - {} + void SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) override + { + } /** * @copydoc Dali::InputMethodContext::SendCommitContent() */ - void SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) override - {} + void SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) override + { + } // Cursor related /** @@ -151,7 +149,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetCursorPosition() */ - void SetCursorPosition( unsigned int cursorPosition ) override; + void SetCursorPosition(unsigned int cursorPosition) override; /** * @copydoc Dali::InputMethodContext::GetCursorPosition() @@ -161,7 +159,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetSurroundingText() */ - void SetSurroundingText( const std::string& text ) override; + void SetSurroundingText(const std::string& text) override; /** * @copydoc Dali::InputMethodContext::GetSurroundingText() @@ -171,7 +169,7 @@ public: /** * @copydoc Dali::InputMethodContext::NotifyTextInputMultiLine() */ - void NotifyTextInputMultiLine( bool multiLine ) override; + void NotifyTextInputMultiLine(bool multiLine) override; /** * @copydoc Dali::InputMethodContext::GetTextDirection() @@ -186,17 +184,17 @@ public: /** * @copydoc Dali::InputMethodContext::ApplyOptions() */ - void ApplyOptions( const InputMethodOptions& options ) override; + void ApplyOptions(const InputMethodOptions& options) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelData() */ - void SetInputPanelData( const std::string& data ) override; + void SetInputPanelData(const std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelData() */ - void GetInputPanelData( std::string& data ) override; + void GetInputPanelData(std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelState() @@ -206,12 +204,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetReturnKeyState() */ - void SetReturnKeyState( bool visible ) override; + void SetReturnKeyState(bool visible) override; /** * @copydoc Dali::InputMethodContext::AutoEnableInputPanel() */ - void AutoEnableInputPanel( bool enabled ) override; + void AutoEnableInputPanel(bool enabled) override; /** * @copydoc Dali::InputMethodContext::ShowInputPanel() @@ -236,17 +234,17 @@ public: /** * @copydoc Dali::InputMethodContext::SetContentMIMETypes() */ - void SetContentMIMETypes( const std::string& mimeTypes ) override; + void SetContentMIMETypes(const std::string& mimeTypes) override; /** * @copydoc Dali::InputMethodContext::FilterEventKey() */ - bool FilterEventKey( const Dali::KeyEvent& keyEvent ) override; + bool FilterEventKey(const Dali::KeyEvent& keyEvent) override; /** * @copydoc Dali::InputMethodContext::AllowTextPrediction() */ - void AllowTextPrediction( bool prediction ) override; + void AllowTextPrediction(bool prediction) override; /** * @copydoc Dali::InputMethodContext::IsTextPredictionAllowed() @@ -256,7 +254,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelLanguage() */ - void SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) override; + void SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelLanguage() @@ -266,12 +264,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelPosition() */ - void SetInputPanelPosition( unsigned int x, unsigned int y ) override; + void SetInputPanelPosition(unsigned int x, unsigned int y) override; /** * @copydoc Dali::InputMethodContext::GetPreeditStyle() */ - void GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const override; + void GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const override; private: /** @@ -285,14 +283,13 @@ private: void DeleteContext(); private: - /** * @brief Process event key down, whether filter a key to isf. * * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyDown(const Dali::KeyEvent& keyEvent); /** * @brief Process event key up, whether filter a key to isf. @@ -300,7 +297,7 @@ private: * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyUp(const Dali::KeyEvent& keyEvent); /** * Ecore_Event_Modifier enums in Ecore_Input.h do not match Ecore_IMF_Keyboard_Modifiers in Ecore_IMF.h. @@ -308,44 +305,43 @@ private: * @param[in] ecoreModifier the Ecore_Event_Modifier input. * @return the Ecore_IMF_Keyboard_Modifiers output. */ - Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier( unsigned int ecoreModifier ); + Ecore_IMF_Keyboard_Modifiers EcoreInputModifierToEcoreIMFModifier(unsigned int ecoreModifier); /** * EcoreInputModifierToEcoreIMFLock function converts from Ecore_Event_Modifier to Ecore_IMF_Keyboard_Locks enums. * @param[in] modifier the Ecore_Event_Modifier input. * @return the Ecore_IMF_Keyboard_Locks output. */ - Ecore_IMF_Keyboard_Locks EcoreInputModifierToEcoreIMFLock( unsigned int modifier ); + Ecore_IMF_Keyboard_Locks EcoreInputModifierToEcoreIMFLock(unsigned int modifier); /** * Called when the binded actor is added to a window. */ - void OnStaged( Dali::Actor actor ); + void OnStaged(Dali::Actor actor); public: - /** * Destructor. */ virtual ~InputMethodContextX(); private: - // Undefined copy constructor - InputMethodContextX( const InputMethodContextX& inputMethodContext) = delete; + InputMethodContextX(const InputMethodContextX& inputMethodContext) = delete; // Undefined assignment operator - InputMethodContextX& operator=( const InputMethodContextX& inputMethodContext ) = delete; + InputMethodContextX& operator=(const InputMethodContextX& inputMethodContext) = delete; private: Ecore_IMF_Context* mIMFContext; - Ecore_X_Window mEcoreXwin; - int mIMFCursorPosition; - std::string mSurroundingText; + Ecore_X_Window mEcoreXwin; + int mIMFCursorPosition; + std::string mSurroundingText; + + bool mRestoreAfterFocusLost : 1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. + bool mIdleCallbackConnected : 1; ///< Whether the idle callback is already connected. + InputMethodOptions mOptions; - bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. - bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected. - InputMethodOptions mOptions; Dali::InputMethodContext::PreEditAttributeDataContainer mPreeditAttrs; ///< Stores preedit attribute data }; diff --git a/dali/internal/input/ubuntu-x11/key-mapping-x.cpp b/dali/internal/input/ubuntu-x11/key-mapping-x.cpp index a69ee10..b49d15a 100644 --- a/dali/internal/input/ubuntu-x11/key-mapping-x.cpp +++ b/dali/internal/input/ubuntu-x11/key-mapping-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,14 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace KeyLookup { - // matches a DALI_KEY enum, to a key name +// clang-format off KeyLookup KeyLookupTable[]= { // more than one key name can be assigned to a single dali-key code @@ -88,8 +85,9 @@ KeyLookup KeyLookupTable[]= { "Control_R", static_cast( DevelKey::DALI_KEY_CONTROL_RIGHT ), false }, { "Return", static_cast( DevelKey::DALI_KEY_RETURN ), false } }; +// clang-format on -const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup )); +const std::size_t KEY_LOOKUP_COUNT = (sizeof(KeyLookupTable)) / (sizeof(KeyLookup)); } // namespace KeyLookup diff --git a/dali/internal/input/ubuntu-x11/virtual-keyboard-impl-x.cpp b/dali/internal/input/ubuntu-x11/virtual-keyboard-impl-x.cpp old mode 100755 new mode 100644 index 2aa062d..1e01853 --- a/dali/internal/input/ubuntu-x11/virtual-keyboard-impl-x.cpp +++ b/dali/internal/input/ubuntu-x11/virtual-keyboard-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES #include @@ -31,32 +31,38 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace VirtualKeyboard { - Dali::InputMethod::ButtonAction::Type gButtonActionFunction = Dali::InputMethod::ButtonAction::DEFAULT; -Ecore_IMF_Input_Panel_Return_Key_Type buttonActionMapping(Dali::InputMethod::ButtonAction::Type buttonAction ) +Ecore_IMF_Input_Panel_Return_Key_Type buttonActionMapping(Dali::InputMethod::ButtonAction::Type buttonAction) { - switch( buttonAction ) + switch(buttonAction) { - case InputMethod::ButtonAction::DEFAULT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; - case InputMethod::ButtonAction::DONE: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE; - case InputMethod::ButtonAction::GO: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO; - case InputMethod::ButtonAction::JOIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN; - case InputMethod::ButtonAction::LOGIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN; - case InputMethod::ButtonAction::NEXT: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT; - case InputMethod::ButtonAction::SEARCH: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH; - case InputMethod::ButtonAction::SEND: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND; - case InputMethod::ButtonAction::SIGNIN: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN; - default: return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; + case InputMethod::ButtonAction::DEFAULT: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; + case InputMethod::ButtonAction::DONE: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DONE; + case InputMethod::ButtonAction::GO: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_GO; + case InputMethod::ButtonAction::JOIN: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_JOIN; + case InputMethod::ButtonAction::LOGIN: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_LOGIN; + case InputMethod::ButtonAction::NEXT: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_NEXT; + case InputMethod::ButtonAction::SEARCH: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEARCH; + case InputMethod::ButtonAction::SEND: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SEND; + case InputMethod::ButtonAction::SIGNIN: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_SIGNIN; + default: + return ECORE_IMF_INPUT_PANEL_RETURN_KEY_TYPE_DEFAULT; } } @@ -64,21 +70,24 @@ void RotateTo(int angle) { // Get focus window used by Keyboard and rotate it Display* display = XOpenDisplay(0); - if (display) + if(display) { ::Window focusWindow; - int revert; + int revert; // Get Focus window XGetInputFocus(display, &focusWindow, &revert); - ecore_x_window_prop_property_set( static_cast( focusWindow ), - ECORE_X_ATOM_E_ILLUME_ROTATE_WINDOW_ANGLE, - ECORE_X_ATOM_CARDINAL, 32, &angle, 1 ); + ecore_x_window_prop_property_set(static_cast(focusWindow), + ECORE_X_ATOM_E_ILLUME_ROTATE_WINDOW_ANGLE, + ECORE_X_ATOM_CARDINAL, + 32, + &angle, + 1); XCloseDisplay(display); } } -void SetReturnKeyType( const InputMethod::ButtonAction::Type type ) +void SetReturnKeyType(const InputMethod::ButtonAction::Type type) { } diff --git a/dali/internal/input/windows/input-method-context-factory-win.cpp b/dali/internal/input/windows/input-method-context-factory-win.cpp old mode 100755 new mode 100644 index 131bbb5..f368d94 --- a/dali/internal/input/windows/input-method-context-factory-win.cpp +++ b/dali/internal/input/windows/input-method-context-factory-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ * */ -#include #include #include +#include namespace Dali { @@ -29,18 +29,15 @@ class InputMethodContext; namespace InputMethodContextFactory { - // InputMethodContext Factory to be implemented by the platform -InputMethodContextPtr CreateInputMethodContext( Dali::Actor actor ) +InputMethodContextPtr CreateInputMethodContext(Dali::Actor actor) { - return Dali::Internal::Adaptor::InputMethodContextWin::New( actor ); -} - -} - + return Dali::Internal::Adaptor::InputMethodContextWin::New(actor); } +} // namespace InputMethodContextFactory +} // namespace Adaptor -} -} \ No newline at end of file +} // namespace Internal +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/input/windows/input-method-context-impl-win.cpp b/dali/internal/input/windows/input-method-context-impl-win.cpp old mode 100755 new mode 100644 index a26c90a..3308f60 --- a/dali/internal/input/windows/input-method-context-impl-win.cpp +++ b/dali/internal/input/windows/input-method-context-impl-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,42 +19,39 @@ #include // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES -#include #include #include #include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { #if defined(DEBUG_ENABLED) -Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_INPUT_METHOD_CONTEXT" ); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_INPUT_METHOD_CONTEXT"); #endif -} +} // namespace -InputMethodContextPtr InputMethodContextWin::New( Dali::Actor actor ) +InputMethodContextPtr InputMethodContextWin::New(Dali::Actor actor) { InputMethodContextPtr manager; - if ( actor && Adaptor::IsAvailable() ) + if(actor && Adaptor::IsAvailable()) { - manager = new InputMethodContextWin( actor ); + manager = new InputMethodContextWin(actor); } return manager; @@ -64,15 +61,14 @@ void InputMethodContextWin::Finalize() { } -InputMethodContextWin::InputMethodContextWin( Dali::Actor actor ) -: mWin32Window( 0 ), - mIMFCursorPosition( 0 ), +InputMethodContextWin::InputMethodContextWin(Dali::Actor actor) +: mWin32Window(0), + mIMFCursorPosition(0), mSurroundingText(), - mRestoreAfterFocusLost( false ), - mIdleCallbackConnected( false ) + mRestoreAfterFocusLost(false), + mIdleCallbackConnected(false) { - - actor.OnSceneSignal().Connect( this, &InputMethodContextWin::OnStaged ); + actor.OnSceneSignal().Connect(this, &InputMethodContextWin::OnStaged); } InputMethodContextWin::~InputMethodContextWin() @@ -82,18 +78,18 @@ InputMethodContextWin::~InputMethodContextWin() void InputMethodContextWin::Initialize() { - CreateContext( mWin32Window ); + CreateContext(mWin32Window); ConnectCallbacks(); } -void InputMethodContextWin::CreateContext( WinWindowHandle winHandle ) +void InputMethodContextWin::CreateContext(WinWindowHandle winHandle) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::CreateContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::CreateContext\n"); } void InputMethodContextWin::DeleteContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::DeleteContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::DeleteContext\n"); } // Callbacks for predicitive text support. @@ -118,12 +114,12 @@ void InputMethodContextWin::Deactivate() void InputMethodContextWin::Reset() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::Reset\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::Reset\n"); } ImfContext* InputMethodContextWin::GetContext() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetContext\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetContext\n"); return NULL; } @@ -133,7 +129,7 @@ bool InputMethodContextWin::RestoreAfterFocusLost() const return mRestoreAfterFocusLost; } -void InputMethodContextWin::SetRestoreAfterFocusLost( bool toggle ) +void InputMethodContextWin::SetRestoreAfterFocusLost(bool toggle) { mRestoreAfterFocusLost = toggle; } @@ -143,26 +139,26 @@ void InputMethodContextWin::SetRestoreAfterFocusLost( bool toggle ) * We are still predicting what the user is typing. The latest string is what the InputMethodContext module thinks * the user wants to type. */ -void InputMethodContextWin::PreEditChanged( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextWin::PreEditChanged(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::PreEditChanged\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::PreEditChanged\n"); } -void InputMethodContextWin::CommitReceived( void*, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextWin::CommitReceived(void*, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::CommitReceived\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::CommitReceived\n"); - if ( Dali::Adaptor::IsAvailable() ) + if(Dali::Adaptor::IsAvailable()) { - const std::string keyString( static_cast( eventInfo ) ); + const std::string keyString(static_cast(eventInfo)); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::EventData eventData( Dali::InputMethodContext::COMMIT, keyString, 0, 0 ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, eventData ); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::EventData eventData(Dali::InputMethodContext::COMMIT, keyString, 0, 0); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, eventData); - if( callbackData.update ) + if(callbackData.update) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); + mIMFCursorPosition = static_cast(callbackData.cursorPosition); NotifyCursorPosition(); } @@ -174,25 +170,25 @@ void InputMethodContextWin::CommitReceived( void*, ImfContext* imfContext, void* * Here the InputMethodContext module wishes to know the string we are working with and where within the string the cursor is * We need to signal the application to tell us this information. */ -bool InputMethodContextWin::RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) +bool InputMethodContextWin::RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::RetrieveSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::RetrieveSurrounding\n"); - Dali::InputMethodContext::EventData imfData( Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0 ); - Dali::InputMethodContext handle( this ); - Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit( handle, imfData ); + Dali::InputMethodContext::EventData imfData(Dali::InputMethodContext::GET_SURROUNDING, std::string(), 0, 0); + Dali::InputMethodContext handle(this); + Dali::InputMethodContext::CallbackData callbackData = mEventSignal.Emit(handle, imfData); - if( callbackData.update ) + if(callbackData.update) { - if( text ) + if(text) { - *text = strdup( callbackData.currentText.c_str() ); + *text = strdup(callbackData.currentText.c_str()); } - if( cursorPosition ) + if(cursorPosition) { - mIMFCursorPosition = static_cast( callbackData.cursorPosition ); - *cursorPosition = mIMFCursorPosition; + mIMFCursorPosition = static_cast(callbackData.cursorPosition); + *cursorPosition = mIMFCursorPosition; } } @@ -203,51 +199,51 @@ bool InputMethodContextWin::RetrieveSurrounding( void* data, ImfContext* imfCont * Called when an InputMethodContext delete surrounding event is received. * Here we tell the application that it should delete a certain range. */ -void InputMethodContextWin::DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) +void InputMethodContextWin::DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::DeleteSurrounding\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::DeleteSurrounding\n"); } void InputMethodContextWin::NotifyCursorPosition() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::NotifyCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::NotifyCursorPosition\n"); } -void InputMethodContextWin::SetCursorPosition( unsigned int cursorPosition ) +void InputMethodContextWin::SetCursorPosition(unsigned int cursorPosition) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetCursorPosition\n"); - mIMFCursorPosition = static_cast( cursorPosition ); + mIMFCursorPosition = static_cast(cursorPosition); } unsigned int InputMethodContextWin::GetCursorPosition() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetCursorPosition\n"); - return static_cast( mIMFCursorPosition ); + return static_cast(mIMFCursorPosition); } -void InputMethodContextWin::SetSurroundingText( const std::string& text ) +void InputMethodContextWin::SetSurroundingText(const std::string& text) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetSurroundingText\n"); mSurroundingText = text; } const std::string& InputMethodContextWin::GetSurroundingText() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetSurroundingText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetSurroundingText\n"); return mSurroundingText; } -void InputMethodContextWin::NotifyTextInputMultiLine( bool multiLine ) +void InputMethodContextWin::NotifyTextInputMultiLine(bool multiLine) { } Dali::InputMethodContext::TextDirection InputMethodContextWin::GetTextDirection() { - Dali::InputMethodContext::TextDirection direction ( Dali::InputMethodContext::LEFT_TO_RIGHT ); + Dali::InputMethodContext::TextDirection direction(Dali::InputMethodContext::LEFT_TO_RIGHT); return direction; } @@ -258,63 +254,63 @@ Rect InputMethodContextWin::GetInputMethodArea() width = height = xPos = yPos = 0; - return Rect(xPos,yPos,width,height); + return Rect(xPos, yPos, width, height); } -void InputMethodContextWin::ApplyOptions( const InputMethodOptions& options ) +void InputMethodContextWin::ApplyOptions(const InputMethodOptions& options) { using namespace Dali::InputMethod::Category; int index; - if ( mOptions.CompareAndSet(PANEL_LAYOUT, options, index) ) + if(mOptions.CompareAndSet(PANEL_LAYOUT, options, index)) { } - if ( mOptions.CompareAndSet(BUTTON_ACTION, options, index) ) + if(mOptions.CompareAndSet(BUTTON_ACTION, options, index)) { } - if ( mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index) ) + if(mOptions.CompareAndSet(AUTO_CAPITALIZE, options, index)) { } - if ( mOptions.CompareAndSet(VARIATION, options, index) ) + if(mOptions.CompareAndSet(VARIATION, options, index)) { } } -void InputMethodContextWin::SetInputPanelData( const std::string& data ) +void InputMethodContextWin::SetInputPanelData(const std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetInputPanelData\n"); } -void InputMethodContextWin::GetInputPanelData( std::string& data ) +void InputMethodContextWin::GetInputPanelData(std::string& data) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelData\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelData\n"); } Dali::InputMethodContext::State InputMethodContextWin::GetInputPanelState() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelState\n"); return Dali::InputMethodContext::DEFAULT; } -void InputMethodContextWin::SetReturnKeyState( bool visible ) +void InputMethodContextWin::SetReturnKeyState(bool visible) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetReturnKeyState\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetReturnKeyState\n"); } -void InputMethodContextWin::AutoEnableInputPanel( bool enabled ) +void InputMethodContextWin::AutoEnableInputPanel(bool enabled) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::AutoEnableInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::AutoEnableInputPanel\n"); } void InputMethodContextWin::ShowInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::ShowInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::ShowInputPanel\n"); } void InputMethodContextWin::HideInputPanel() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::HideInputPanel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::HideInputPanel\n"); } Dali::InputMethodContext::KeyboardType InputMethodContextWin::GetKeyboardType() @@ -324,76 +320,76 @@ Dali::InputMethodContext::KeyboardType InputMethodContextWin::GetKeyboardType() std::string InputMethodContextWin::GetInputPanelLocale() { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelLocale\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelLocale\n"); std::string locale = ""; return locale; } -void InputMethodContextWin::SetContentMIMETypes( const std::string& mimeTypes ) +void InputMethodContextWin::SetContentMIMETypes(const std::string& mimeTypes) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetContentMIMETypes\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetContentMIMETypes\n"); } -bool InputMethodContextWin::FilterEventKey( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextWin::FilterEventKey(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); - if ( ! KeyLookup::IsDeviceButton( keyEvent.GetKeyName().c_str() )) + if(!KeyLookup::IsDeviceButton(keyEvent.GetKeyName().c_str())) { //check whether it's key down or key up event - if ( keyEvent.GetState() == Dali::KeyEvent::DOWN ) + if(keyEvent.GetState() == Dali::KeyEvent::DOWN) { - eventHandled = ProcessEventKeyDown( keyEvent ); + eventHandled = ProcessEventKeyDown(keyEvent); } - else if ( keyEvent.GetState() == Dali::KeyEvent::UP ) + else if(keyEvent.GetState() == Dali::KeyEvent::UP) { - eventHandled = ProcessEventKeyUp( keyEvent ); + eventHandled = ProcessEventKeyUp(keyEvent); } } return eventHandled; } -void InputMethodContextWin::SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) +void InputMethodContextWin::SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetInputPanelLanguage\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetInputPanelLanguage\n"); } Dali::InputMethodContext::InputPanelLanguage InputMethodContextWin::GetInputPanelLanguage() const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelLanguage\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetInputPanelLanguage\n"); return Dali::InputMethodContext::InputPanelLanguage::AUTOMATIC; } -void InputMethodContextWin::SetInputPanelPosition( unsigned int x, unsigned int y ) +void InputMethodContextWin::SetInputPanelPosition(unsigned int x, unsigned int y) { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::SetInputPanelPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::SetInputPanelPosition\n"); } -void InputMethodContextWin::GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const +void InputMethodContextWin::GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "InputMethodContextWin::GetPreeditStyle\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "InputMethodContextWin::GetPreeditStyle\n"); attrs = mPreeditAttrs; } -bool InputMethodContextWin::ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextWin::ProcessEventKeyDown(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); return eventHandled; } -bool InputMethodContextWin::ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ) +bool InputMethodContextWin::ProcessEventKeyUp(const Dali::KeyEvent& keyEvent) { - bool eventHandled( false ); + bool eventHandled(false); return eventHandled; } -void InputMethodContextWin::OnStaged( Dali::Actor actor ) +void InputMethodContextWin::OnStaged(Dali::Actor actor) { - WinWindowHandle winWindow( AnyCast< WinWindowHandle >( Dali::Integration::SceneHolder::Get( actor ).GetNativeHandle() ) ); + WinWindowHandle winWindow(AnyCast(Dali::Integration::SceneHolder::Get(actor).GetNativeHandle())); - if( mWin32Window != winWindow ) + if(mWin32Window != winWindow) { mWin32Window = winWindow; @@ -403,9 +399,8 @@ void InputMethodContextWin::OnStaged( Dali::Actor actor ) } } -} // Adaptor - -} // Internal +} // namespace Adaptor -} // Dali +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/input/windows/input-method-context-impl-win.h b/dali/internal/input/windows/input-method-context-impl-win.h old mode 100755 new mode 100644 index 58b91b3..e89a502 --- a/dali/internal/input/windows/input-method-context-impl-win.h +++ b/dali/internal/input/windows/input-method-context-impl-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_INPUT_METHOD_CONTEXT_IMPL_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,15 +28,12 @@ namespace Dali { - class RenderSurface; namespace Internal { - namespace Adaptor { - class InputMethodContextWin : public Dali::Internal::Adaptor::InputMethodContext, public Dali::ConnectionTracker { public: @@ -46,16 +43,15 @@ public: * @param[in] actor The actor that uses the new InputMethodContext instance. * @return InputMethodContext pointer */ - static InputMethodContextPtr New( Dali::Actor actor ); + static InputMethodContextPtr New(Dali::Actor actor); /** * Constructor * @param[in] win32Window, The window is created by application. */ - explicit InputMethodContextWin( Dali::Actor actor ); + explicit InputMethodContextWin(Dali::Actor actor); public: - /** * @brief Initializes member data. */ @@ -106,39 +102,41 @@ public: /** * @copydoc Dali::InputMethodContext::SetRestoreAfterFocusLost() */ - void SetRestoreAfterFocusLost( bool toggle ) override; + void SetRestoreAfterFocusLost(bool toggle) override; /** * @copydoc Dali::InputMethodContext::PreEditChanged() */ - void PreEditChanged( void* data, ImfContext* imfContext, void* eventInfo ) override; + void PreEditChanged(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - void CommitReceived( void* data, ImfContext* imfContext, void* eventInfo ) override; + void CommitReceived(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::NotifyCursorPosition() */ - bool RetrieveSurrounding( void* data, ImfContext* imfContext, char** text, int* cursorPosition ) override; + bool RetrieveSurrounding(void* data, ImfContext* imfContext, char** text, int* cursorPosition) override; /** * @copydoc Dali::InputMethodContext::DeleteSurrounding() */ - void DeleteSurrounding( void* data, ImfContext* imfContext, void* eventInfo ) override; + void DeleteSurrounding(void* data, ImfContext* imfContext, void* eventInfo) override; /** * @copydoc Dali::InputMethodContext::SendPrivateCommand() */ - void SendPrivateCommand( void* data, ImfContext* imfContext, void* eventInfo ) override - {} + void SendPrivateCommand(void* data, ImfContext* imfContext, void* eventInfo) override + { + } /** * @copydoc Dali::InputMethodContext::SendCommitContent() */ - void SendCommitContent( void* data, ImfContext* imfContext, void* eventInfo ) override - {} + void SendCommitContent(void* data, ImfContext* imfContext, void* eventInfo) override + { + } // Cursor related /** @@ -149,7 +147,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetCursorPosition() */ - void SetCursorPosition( unsigned int cursorPosition ) override; + void SetCursorPosition(unsigned int cursorPosition) override; /** * @copydoc Dali::InputMethodContext::GetCursorPosition() @@ -159,7 +157,7 @@ public: /** * @copydoc Dali::InputMethodContext::SetSurroundingText() */ - void SetSurroundingText( const std::string& text ) override; + void SetSurroundingText(const std::string& text) override; /** * @copydoc Dali::InputMethodContext::GetSurroundingText() @@ -169,7 +167,7 @@ public: /** * @copydoc Dali::InputMethodContext::NotifyTextInputMultiLine() */ - void NotifyTextInputMultiLine( bool multiLine ) override; + void NotifyTextInputMultiLine(bool multiLine) override; /** * @copydoc Dali::InputMethodContext::GetTextDirection() @@ -184,17 +182,17 @@ public: /** * @copydoc Dali::InputMethodContext::ApplyOptions() */ - void ApplyOptions( const InputMethodOptions& options ) override; + void ApplyOptions(const InputMethodOptions& options) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelData() */ - void SetInputPanelData( const std::string& data ) override; + void SetInputPanelData(const std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelData() */ - void GetInputPanelData( std::string& data ) override; + void GetInputPanelData(std::string& data) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelState() @@ -204,12 +202,12 @@ public: /** * @copydoc Dali::InputMethodContext::SetReturnKeyState() */ - void SetReturnKeyState( bool visible ) override; + void SetReturnKeyState(bool visible) override; /** * @copydoc Dali::InputMethodContext::AutoEnableInputPanel() */ - void AutoEnableInputPanel( bool enabled ) override; + void AutoEnableInputPanel(bool enabled) override; /** * @copydoc Dali::InputMethodContext::ShowInputPanel() @@ -234,17 +232,17 @@ public: /** * @copydoc Dali::InputMethodContext::SetContentMIMETypes() */ - void SetContentMIMETypes( const std::string& mimeTypes ) override; + void SetContentMIMETypes(const std::string& mimeTypes) override; /** * @copydoc Dali::InputMethodContext::FilterEventKey() */ - bool FilterEventKey( const Dali::KeyEvent& keyEvent ) override; + bool FilterEventKey(const Dali::KeyEvent& keyEvent) override; /** * @copydoc Dali::InputMethodContext::SetInputPanelLanguage() */ - void SetInputPanelLanguage( Dali::InputMethodContext::InputPanelLanguage language ) override; + void SetInputPanelLanguage(Dali::InputMethodContext::InputPanelLanguage language) override; /** * @copydoc Dali::InputMethodContext::GetInputPanelLanguage() @@ -254,19 +252,19 @@ public: /** * @copydoc Dali::InputMethodContext::SetInputPanelPosition() */ - void SetInputPanelPosition( unsigned int x, unsigned int y ) override; + void SetInputPanelPosition(unsigned int x, unsigned int y) override; /** * @copydoc Dali::InputMethodContext::GetPreeditStyle() */ - void GetPreeditStyle( Dali::InputMethodContext::PreEditAttributeDataContainer& attrs ) const override; + void GetPreeditStyle(Dali::InputMethodContext::PreEditAttributeDataContainer& attrs) const override; private: /** * Context created the first time and kept until deleted. * @param[in] win32Window, The window is created by application. */ - void CreateContext( WinWindowHandle win32Window ); + void CreateContext(WinWindowHandle win32Window); /** * @copydoc Dali::InputMethodContext::DeleteContext() @@ -274,14 +272,13 @@ private: void DeleteContext(); private: - /** * @brief Process event key down, whether filter a key to isf. * * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyDown( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyDown(const Dali::KeyEvent& keyEvent); /** * @brief Process event key up, whether filter a key to isf. @@ -289,36 +286,35 @@ private: * @param[in] keyEvent The event key to be handled. * @return Whether the event key is handled. */ - bool ProcessEventKeyUp( const Dali::KeyEvent& keyEvent ); + bool ProcessEventKeyUp(const Dali::KeyEvent& keyEvent); /** * Called when the binded actor is added to a window. */ - void OnStaged( Dali::Actor actor ); + void OnStaged(Dali::Actor actor); public: - /** * Destructor. */ virtual ~InputMethodContextWin(); private: - // Undefined copy constructor - InputMethodContextWin( const InputMethodContextWin& inputMethodContext) = delete; + InputMethodContextWin(const InputMethodContextWin& inputMethodContext) = delete; // Undefined assignment operator - InputMethodContextWin& operator=( const InputMethodContextWin& inputMethodContext ) = delete; + InputMethodContextWin& operator=(const InputMethodContextWin& inputMethodContext) = delete; private: WinWindowHandle mWin32Window; - int mIMFCursorPosition; - std::string mSurroundingText; + int mIMFCursorPosition; + std::string mSurroundingText; + + bool mRestoreAfterFocusLost : 1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. + bool mIdleCallbackConnected : 1; ///< Whether the idle callback is already connected. + InputMethodOptions mOptions; - bool mRestoreAfterFocusLost:1; ///< Whether the keyboard needs to be restored (activated ) after focus regained. - bool mIdleCallbackConnected:1; ///< Whether the idle callback is already connected. - InputMethodOptions mOptions; Dali::InputMethodContext::PreEditAttributeDataContainer mPreeditAttrs; ///< Stores preedit attribute data }; diff --git a/dali/internal/input/windows/key-mapping-win.cpp b/dali/internal/input/windows/key-mapping-win.cpp old mode 100755 new mode 100644 index 9b855bd..1766501 --- a/dali/internal/input/windows/key-mapping-win.cpp +++ b/dali/internal/input/windows/key-mapping-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,14 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace KeyLookup { - // matches a DALI_KEY enum, to key name +// clang-format off KeyLookup KeyLookupTable[]= { // more than one key name can be assigned to a single dali-key code @@ -51,8 +48,9 @@ KeyLookup KeyLookupTable[]= { "Control_L", static_cast( DevelKey::DALI_KEY_CONTROL_LEFT ), false }, { "Control_R", static_cast( DevelKey::DALI_KEY_CONTROL_RIGHT ), false } }; +// clang-format on -const std::size_t KEY_LOOKUP_COUNT = (sizeof( KeyLookupTable ))/ (sizeof( KeyLookup )); +const std::size_t KEY_LOOKUP_COUNT = (sizeof(KeyLookupTable)) / (sizeof(KeyLookup)); } // namespace KeyLookup diff --git a/dali/internal/input/windows/virtual-keyboard-impl-win.cpp b/dali/internal/input/windows/virtual-keyboard-impl-win.cpp index c0958fa..1528072 100644 --- a/dali/internal/input/windows/virtual-keyboard-impl-win.cpp +++ b/dali/internal/input/windows/virtual-keyboard-impl-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace VirtualKeyboard { void Show() @@ -35,7 +32,6 @@ void Show() void Hide() { - } bool IsVisible() @@ -43,14 +39,12 @@ bool IsVisible() return false; } -void ApplySettings( const Property::Map& settingsMap ) +void ApplySettings(const Property::Map& settingsMap) { - } -void EnablePrediction( const bool enable ) +void EnablePrediction(const bool enable) { - } bool IsPredictionEnabled() @@ -91,7 +85,7 @@ void RotateTo(int angle) { } -void SetReturnKeyType( const InputMethod::ButtonAction::Type type ) +void SetReturnKeyType(const InputMethod::ButtonAction::Type type) { } diff --git a/dali/internal/legacy/common/tizen-platform-abstraction.cpp b/dali/internal/legacy/common/tizen-platform-abstraction.cpp index d3bfb15..89a44c3 100644 --- a/dali/internal/legacy/common/tizen-platform-abstraction.cpp +++ b/dali/internal/legacy/common/tizen-platform-abstraction.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,43 +19,41 @@ #include // EXTERNAL INCLUDES -#include -#include -#include -#include #include +#include #include #include +#include +#include +#include // INTERNAL INCLUDES +#include #include #include -#include #include -#include +#include namespace Dali { - namespace TizenPlatform { - struct TizenPlatformAbstraction::TimerCallback : ConnectionTracker { - Dali::Timer mTimer; - TizenPlatformAbstraction* mOwner; - std::unique_ptr< CallbackBase > mCallback; - const uint32_t mIdNumber; + Dali::Timer mTimer; + TizenPlatformAbstraction* mOwner; + std::unique_ptr mCallback; + const uint32_t mIdNumber; static uint32_t sNextTimerId; TimerCallback(TizenPlatformAbstraction* owner, CallbackBase* callback, uint32_t ms) : mTimer(Dali::Timer::New(ms)), mOwner(owner), - mCallback( std::unique_ptr< CallbackBase >( callback ) ), + mCallback(std::unique_ptr(callback)), mIdNumber(++sNextTimerId) { - mTimer.TickSignal().Connect( this, &TimerCallback::Tick ); + mTimer.TickSignal().Connect(this, &TimerCallback::Tick); mTimer.Start(); } ~TimerCallback() @@ -72,7 +70,7 @@ struct TizenPlatformAbstraction::TimerCallback : ConnectionTracker uint32_t TizenPlatformAbstraction::TimerCallback::sNextTimerId = 0; TizenPlatformAbstraction::TizenPlatformAbstraction() -: mDataStoragePath( "" ), +: mDataStoragePath(""), mTimerPairsWaiting(), mTimerPairsSpent() @@ -83,43 +81,43 @@ TizenPlatformAbstraction::~TizenPlatformAbstraction() { } -ImageDimensions TizenPlatformAbstraction::GetClosestImageSize( const std::string& filename, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ) +ImageDimensions TizenPlatformAbstraction::GetClosestImageSize(const std::string& filename, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection) { - return ImageLoader::GetClosestImageSize( filename, size, fittingMode, samplingMode, orientationCorrection ); + return ImageLoader::GetClosestImageSize(filename, size, fittingMode, samplingMode, orientationCorrection); } -ImageDimensions TizenPlatformAbstraction::GetClosestImageSize( Integration::ResourcePointer resourceBuffer, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ) +ImageDimensions TizenPlatformAbstraction::GetClosestImageSize(Integration::ResourcePointer resourceBuffer, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection) { - return ImageLoader::GetClosestImageSize( resourceBuffer, size, fittingMode, samplingMode, orientationCorrection ); + return ImageLoader::GetClosestImageSize(resourceBuffer, size, fittingMode, samplingMode, orientationCorrection); } Integration::ResourcePointer TizenPlatformAbstraction::LoadImageSynchronously(const Integration::BitmapResourceType& resource, const std::string& resourcePath) { - return ImageLoader::LoadImageSynchronously( resource, resourcePath ); + return ImageLoader::LoadImageSynchronously(resource, resourcePath); } -Integration::BitmapPtr TizenPlatformAbstraction::DecodeBuffer( const Integration::BitmapResourceType& resource, uint8_t * buffer, size_t size ) +Integration::BitmapPtr TizenPlatformAbstraction::DecodeBuffer(const Integration::BitmapResourceType& resource, uint8_t* buffer, size_t size) { - Integration::BitmapPtr resultBitmap; + Integration::BitmapPtr resultBitmap; Dali::Devel::PixelBuffer bitmap; - Dali::Internal::Platform::FileReader fileReader( buffer, size ); - FILE * const fp = fileReader.GetFile(); - if( fp ) + Dali::Internal::Platform::FileReader fileReader(buffer, size); + FILE* const fp = fileReader.GetFile(); + if(fp) { - bool result = ImageLoader::ConvertStreamToBitmap( resource, "", fp, bitmap ); - if ( !result || !bitmap ) + bool result = ImageLoader::ConvertStreamToBitmap(resource, "", fp, bitmap); + if(!result || !bitmap) { bitmap.Reset(); - DALI_LOG_WARNING( "Unable to decode bitmap supplied as in-memory blob.\n" ); + DALI_LOG_WARNING("Unable to decode bitmap supplied as in-memory blob.\n"); } else { @@ -129,16 +127,15 @@ Integration::BitmapPtr TizenPlatformAbstraction::DecodeBuffer( const Integration auto retval = Integration::Bitmap::New(profile, Dali::ResourcePolicy::OWNED_DISCARD); retval->GetPackedPixelsProfile()->ReserveBuffer( - bitmap.GetPixelFormat(), - bitmap.GetWidth(), - bitmap.GetHeight(), - bitmap.GetWidth(), - bitmap.GetHeight() - ); + bitmap.GetPixelFormat(), + bitmap.GetWidth(), + bitmap.GetHeight(), + bitmap.GetWidth(), + bitmap.GetHeight()); auto& impl = Dali::GetImplementation(bitmap); - std::copy( impl.GetBuffer(), impl.GetBuffer()+impl.GetBufferSize(), retval->GetBuffer()); + std::copy(impl.GetBuffer(), impl.GetBuffer() + impl.GetBufferSize(), retval->GetBuffer()); resultBitmap.Reset(retval); } } @@ -146,7 +143,7 @@ Integration::BitmapPtr TizenPlatformAbstraction::DecodeBuffer( const Integration return resultBitmap; } -bool TizenPlatformAbstraction::LoadShaderBinaryFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const +bool TizenPlatformAbstraction::LoadShaderBinaryFile(const std::string& filename, Dali::Vector& buffer) const { bool result = false; @@ -156,22 +153,22 @@ bool TizenPlatformAbstraction::LoadShaderBinaryFile( const std::string& filename // First check the system location where shaders are stored at install time: path = DALI_SHADERBIN_DIR; path += filename; - result = Dali::FileLoader::ReadFile( path, buffer ); + result = Dali::FileLoader::ReadFile(path, buffer); // Fallback to the cache of shaders stored after previous runtime compilations: // On desktop this looks in the current working directory that the app was launched from. - if( result == false ) + if(result == false) { path = mDataStoragePath; path += filename; - result = Dali::FileLoader::ReadFile( path, buffer ); + result = Dali::FileLoader::ReadFile(path, buffer); } #endif return result; } -bool TizenPlatformAbstraction::SaveShaderBinaryFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) const +bool TizenPlatformAbstraction::SaveShaderBinaryFile(const std::string& filename, const unsigned char* buffer, unsigned int numBytes) const { bool result = false; @@ -181,35 +178,33 @@ bool TizenPlatformAbstraction::SaveShaderBinaryFile( const std::string& filename // On desktop this looks in the current working directory that the app was launched from. std::string path = mDataStoragePath; path += filename; - result = SaveFile( path, buffer, numBytes ); + result = SaveFile(path, buffer, numBytes); #endif return result; } -void TizenPlatformAbstraction::SetDataStoragePath( const std::string& path ) +void TizenPlatformAbstraction::SetDataStoragePath(const std::string& path) { mDataStoragePath = path; } -uint32_t TizenPlatformAbstraction::StartTimer( uint32_t milliseconds, CallbackBase* callback ) +uint32_t TizenPlatformAbstraction::StartTimer(uint32_t milliseconds, CallbackBase* callback) { TimerCallback* timerCallbackPtr = new TimerCallback(this, callback, milliseconds); // Stick it in the list - mTimerPairsWaiting.push_back( std::unique_ptr< TimerCallback >( timerCallbackPtr ) ); + mTimerPairsWaiting.push_back(std::unique_ptr(timerCallbackPtr)); return timerCallbackPtr->mIdNumber; } -void TizenPlatformAbstraction::CancelTimer ( uint32_t timerId ) +void TizenPlatformAbstraction::CancelTimer(uint32_t timerId) { auto iter = std::remove_if( - mTimerPairsWaiting.begin(), mTimerPairsWaiting.end(), - [&timerId]( std::unique_ptr< TimerCallback >& timerCallbackPtr ) - { - if( timerCallbackPtr->mIdNumber == timerId ) + mTimerPairsWaiting.begin(), mTimerPairsWaiting.end(), [&timerId](std::unique_ptr& timerCallbackPtr) { + if(timerCallbackPtr->mIdNumber == timerId) { timerCallbackPtr->mTimer.Stop(); return true; @@ -218,54 +213,49 @@ void TizenPlatformAbstraction::CancelTimer ( uint32_t timerId ) { return false; } - } - ); + }); - mTimerPairsWaiting.erase( iter, mTimerPairsWaiting.end() ); + mTimerPairsWaiting.erase(iter, mTimerPairsWaiting.end()); } void TizenPlatformAbstraction::RunTimerFunction(TimerCallback& timerPtr) { - CallbackBase::Execute( *timerPtr.mCallback ); + CallbackBase::Execute(*timerPtr.mCallback); - std::vector< std::unique_ptr< TimerCallback > >::iterator timerIter = std::find_if( mTimerPairsWaiting.begin(), mTimerPairsWaiting.end(), - [&]( std::unique_ptr< TimerCallback >& p ) - { return p.get() == &timerPtr;} ); + std::vector >::iterator timerIter = std::find_if(mTimerPairsWaiting.begin(), mTimerPairsWaiting.end(), [&](std::unique_ptr& p) { return p.get() == &timerPtr; }); - if( timerIter == std::end(mTimerPairsWaiting) ) + if(timerIter == std::end(mTimerPairsWaiting)) { DALI_ASSERT_DEBUG(false); } // ...and move it - std::move(timerIter, timerIter+1, std::back_inserter(mTimerPairsSpent)); + std::move(timerIter, timerIter + 1, std::back_inserter(mTimerPairsSpent)); - mTimerPairsWaiting.erase(timerIter, timerIter+1); + mTimerPairsWaiting.erase(timerIter, timerIter + 1); - Dali::Adaptor::Get().AddIdle( MakeCallback( this, &TizenPlatformAbstraction::CleanupTimers ), false ); + Dali::Adaptor::Get().AddIdle(MakeCallback(this, &TizenPlatformAbstraction::CleanupTimers), false); } - void TizenPlatformAbstraction::CleanupTimers() { mTimerPairsSpent.clear(); } - TizenPlatformAbstraction* CreatePlatformAbstraction() { return new TizenPlatformAbstraction(); } -bool SaveFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) +bool SaveFile(const std::string& filename, const unsigned char* buffer, unsigned int numBytes) { - DALI_ASSERT_DEBUG( 0 != filename.length()); + DALI_ASSERT_DEBUG(0 != filename.length()); bool result = false; std::filebuf buf; buf.open(filename.c_str(), std::ios::out | std::ios_base::trunc | std::ios::binary); - if( buf.is_open() ) + if(buf.is_open()) { std::ostream stream(&buf); @@ -275,7 +265,7 @@ bool SaveFile( const std::string& filename, const unsigned char * buffer, unsign // write contents of buffer to the file stream.write(reinterpret_cast(buffer), length); - if( !stream.bad() ) + if(!stream.bad()) { result = true; } @@ -284,6 +274,6 @@ bool SaveFile( const std::string& filename, const unsigned char * buffer, unsign return result; } -} // namespace TizenPlatform +} // namespace TizenPlatform -} // namespace Dali +} // namespace Dali diff --git a/dali/internal/legacy/common/tizen-platform-abstraction.h b/dali/internal/legacy/common/tizen-platform-abstraction.h index 9f501d7..995ca78 100644 --- a/dali/internal/legacy/common/tizen-platform-abstraction.h +++ b/dali/internal/legacy/common/tizen-platform-abstraction.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_ABSTRACTION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,16 +22,14 @@ #include #include - // EXTERNAL INCLUDES +#include #include -#include #include -#include +#include namespace Dali { - class CallbackBase; namespace TizenPlatform @@ -43,9 +41,7 @@ class ResourceLoader; */ class TizenPlatformAbstraction : public Integration::PlatformAbstraction { - public: // Construction & Destruction - /** * Constructor */ @@ -57,24 +53,23 @@ public: // Construction & Destruction ~TizenPlatformAbstraction() override; public: // PlatformAbstraction overrides - /** * @copydoc PlatformAbstraction::GetClosestImageSize() */ - ImageDimensions GetClosestImageSize( const std::string& filename, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ) override; + ImageDimensions GetClosestImageSize(const std::string& filename, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection) override; /** * @copydoc PlatformAbstraction::GetClosestImageSize() */ - ImageDimensions GetClosestImageSize( Integration::ResourcePointer resourceBuffer, - ImageDimensions size, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection ) override; + ImageDimensions GetClosestImageSize(Integration::ResourcePointer resourceBuffer, + ImageDimensions size, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection) override; /** * @copydoc PlatformAbstraction::LoadImageSynchronously() @@ -84,33 +79,33 @@ public: // PlatformAbstraction overrides /** * @copydoc PlatformAbstraction::DecodeBuffer() */ - Integration::BitmapPtr DecodeBuffer( const Integration::BitmapResourceType& resource, uint8_t * buffer, size_t size ) override; + Integration::BitmapPtr DecodeBuffer(const Integration::BitmapResourceType& resource, uint8_t* buffer, size_t size) override; /** * @copydoc PlatformAbstraction::LoadShaderBinaryFile() */ - bool LoadShaderBinaryFile( const std::string& filename, Dali::Vector< unsigned char >& buffer ) const override; + bool LoadShaderBinaryFile(const std::string& filename, Dali::Vector& buffer) const override; /** * @copydoc PlatformAbstraction::SaveShaderBinaryFile() */ - bool SaveShaderBinaryFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes ) const override; + bool SaveShaderBinaryFile(const std::string& filename, const unsigned char* buffer, unsigned int numBytes) const override; /** * @copydoc PlatformAbstraction::StartTimer() */ - uint32_t StartTimer( uint32_t milliseconds, CallbackBase* callback ) override; + uint32_t StartTimer(uint32_t milliseconds, CallbackBase* callback) override; /** * @copydoc PlatformAbstraction::CancelTimer() */ - void CancelTimer ( uint32_t timerId ) override; + void CancelTimer(uint32_t timerId) override; /** * Sets path for data/resource storage. * @param[in] path data/resource storage path */ - void SetDataStoragePath( const std::string& path ); + void SetDataStoragePath(const std::string& path); /** * Clears the timers that have completed @@ -118,7 +113,6 @@ public: // PlatformAbstraction overrides void CleanupTimers(); private: - struct TimerCallback; /* @@ -126,13 +120,13 @@ private: */ void RunTimerFunction(TimerCallback& timerPtr); - TizenPlatformAbstraction( const TizenPlatformAbstraction& ); ///< Undefined - TizenPlatformAbstraction& operator=( const TizenPlatformAbstraction& ); ///< Undefined + TizenPlatformAbstraction(const TizenPlatformAbstraction&); ///< Undefined + TizenPlatformAbstraction& operator=(const TizenPlatformAbstraction&); ///< Undefined std::string mDataStoragePath; - std::vector< std::unique_ptr< TimerCallback > > mTimerPairsWaiting; - std::vector< std::unique_ptr< TimerCallback > > mTimerPairsSpent; + std::vector > mTimerPairsWaiting; + std::vector > mTimerPairsSpent; }; /** @@ -148,10 +142,10 @@ TizenPlatformAbstraction* CreatePlatformAbstraction(); * @param numBytes to store * @return true if successful, false otherwise */ -bool SaveFile( const std::string& filename, const unsigned char * buffer, unsigned int numBytes ); +bool SaveFile(const std::string& filename, const unsigned char* buffer, unsigned int numBytes); -} // namespace TizenPlatform +} // namespace TizenPlatform -} // namespace Dali +} // namespace Dali #endif // DALI_TIZEN_PLATFORM_ABSTRACTION_H diff --git a/dali/internal/legacy/tizen/data-compression.cpp b/dali/internal/legacy/tizen/data-compression.cpp index 42c2f55..b3db241 100644 --- a/dali/internal/legacy/tizen/data-compression.cpp +++ b/dali/internal/legacy/tizen/data-compression.cpp @@ -25,7 +25,6 @@ namespace TizenPlatform { namespace DataCompression { - std::size_t GetMaximumRleCompressedSize(const std::size_t inputLength) { // RLE has worst case scenerio of double the input data @@ -34,8 +33,7 @@ std::size_t GetMaximumRleCompressedSize(const std::size_t inputLength) // we also encode the original size into the stream to check // the decode buffers are big enough and for corruption - return (inputLength * 2) + 4; // 4 bytes is space for size - + return (inputLength * 2) + 4; // 4 bytes is space for size } // Run length encode a byte stream, consisting of byte values. @@ -48,97 +46,96 @@ std::size_t GetMaximumRleCompressedSize(const std::size_t inputLength) // 2, 5 // First 4 bytes are the size of the decoded data // -void EncodeRle( const unsigned char* input, - const std::size_t inputLength, - unsigned char* output, - const std::size_t outputLength, - std::size_t& encodedSize) +void EncodeRle(const unsigned char* input, + const std::size_t inputLength, + unsigned char* output, + const std::size_t outputLength, + std::size_t& encodedSize) { - DALI_ASSERT_DEBUG( outputLength >= GetMaximumRleCompressedSize( inputLength )); + DALI_ASSERT_DEBUG(outputLength >= GetMaximumRleCompressedSize(inputLength)); unsigned int index(0); unsigned int runLength(0); encodedSize = 0; // encode the input length in the first 4 bytes. - output[ encodedSize++ ] = inputLength & 0xFF; - output[ encodedSize++ ] = (inputLength >> 8) & 0xFF; - output[ encodedSize++ ] = (inputLength >> 16) & 0xFF; - output[ encodedSize++ ] = (inputLength >> 24) & 0xFF; + output[encodedSize++] = inputLength & 0xFF; + output[encodedSize++] = (inputLength >> 8) & 0xFF; + output[encodedSize++] = (inputLength >> 16) & 0xFF; + output[encodedSize++] = (inputLength >> 24) & 0xFF; - while( index < inputLength ) + while(index < inputLength) { - unsigned char curChar = input[ index ]; - runLength = 1; + unsigned char curChar = input[index]; + runLength = 1; - if( ( (index + 1) == inputLength ) // is more data available - || input[index + 1] != curChar ) // character doesn't match + if(((index + 1) == inputLength) // is more data available + || input[index + 1] != curChar) // character doesn't match { // we out of data, or the next character doesn't match (run of zero) index++; } else { - while( ( (index+1) < inputLength ) && - ( input[index + 1] == curChar ) && - ( runLength < 0xFF ) ) + while(((index + 1) < inputLength) && + (input[index + 1] == curChar) && + (runLength < 0xFF)) { runLength++; index++; } index++; } - output[ encodedSize++ ] = runLength; - output[ encodedSize++ ] = curChar; - + output[encodedSize++] = runLength; + output[encodedSize++] = curChar; } } -bool DecodeRle( const unsigned char* input, - const std::size_t inputLength, - unsigned char* output, - const std::size_t outputLength, - std::size_t& decodedSize) +bool DecodeRle(const unsigned char* input, + const std::size_t inputLength, + unsigned char* output, + const std::size_t outputLength, + std::size_t& decodedSize) { unsigned int index(0); unsigned int outputIndex(0); // there should be at least 4 bytes for the size field - if( inputLength < 4) + if(inputLength < 4) { DALI_LOG_ERROR("input buffer too small\n"); return false; } - decodedSize = input[ index++ ] ; - decodedSize|= input[ index++ ]<<8 ; - decodedSize|= input[ index++ ]<<16 ; - decodedSize|= input[ index++ ]<<24 ; + decodedSize = input[index++]; + decodedSize |= input[index++] << 8; + decodedSize |= input[index++] << 16; + decodedSize |= input[index++] << 24; // check the decoded data will fit in to - if( outputLength < decodedSize ) + if(outputLength < decodedSize) { - DALI_LOG_ERROR("buffer too small, buffer size =%d, data size = %d \n",outputLength, decodedSize); + DALI_LOG_ERROR("buffer too small, buffer size =%d, data size = %d \n", outputLength, decodedSize); return false; } - while( (index+1)< inputLength ) + while((index + 1) < inputLength) { // read the value and the run length - unsigned char runLength = input[ index++ ]; - unsigned char value = input[ index++ ]; + unsigned char runLength = input[index++]; + unsigned char value = input[index++]; - if( (runLength + outputIndex) > decodedSize) + if((runLength + outputIndex) > decodedSize) { - DALI_LOG_ERROR( "corrupted RLE data\n" ); + DALI_LOG_ERROR("corrupted RLE data\n"); // corrupted return false; } // set the value run Length times - memset( &output[ outputIndex ], value, runLength * sizeof( unsigned char) ); - outputIndex+= runLength; + memset(&output[outputIndex], value, runLength * sizeof(unsigned char)); + outputIndex += runLength; } - if( outputIndex != decodedSize) + if(outputIndex != decodedSize) { DALI_LOG_ERROR(" RLE data size missmatch\n"); return false; @@ -147,7 +144,7 @@ bool DecodeRle( const unsigned char* input, return true; } -} // DataCompression +} // namespace DataCompression } // namespace TizenPlatform diff --git a/dali/internal/legacy/tizen/data-compression.h b/dali/internal/legacy/tizen/data-compression.h index ddbcf8c..9906ede 100644 --- a/dali/internal/legacy/tizen/data-compression.h +++ b/dali/internal/legacy/tizen/data-compression.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_DATA_COMPRESSION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,12 @@ * */ - namespace Dali { namespace TizenPlatform { namespace DataCompression { - /** * Return the maximum size of a buffer required to hold a number of bytes. * Required because compressing data, can end up being bigger @@ -42,11 +40,11 @@ std::size_t GetMaximumRleCompressedSize(const std::size_t inputSize); * @param outputLength size of the output buffer in bytes * @param encodedSize number of bytes written to outputBuffer */ -void EncodeRle( const unsigned char* input, - const std::size_t inputLength, - unsigned char* output, - const std::size_t outputLength, - std::size_t &encodedSize ); +void EncodeRle(const unsigned char* input, + const std::size_t inputLength, + unsigned char* output, + const std::size_t outputLength, + std::size_t& encodedSize); /** * RLE Decodes an array of data. @@ -56,12 +54,11 @@ void EncodeRle( const unsigned char* input, * @param[in] outputLength size of output data in bytes * @param[out] decodedSize the number of bytes decoded into outputBuffer */ -bool DecodeRle( const unsigned char* input, - const std::size_t inputLength, - unsigned char* output, - const std::size_t outputLength, - std::size_t& decodedSize); - +bool DecodeRle(const unsigned char* input, + const std::size_t inputLength, + unsigned char* output, + const std::size_t outputLength, + std::size_t& decodedSize); } // namespace DataCompression diff --git a/dali/internal/legacy/tizen/image-encoder.h b/dali/internal/legacy/tizen/image-encoder.h index 96145ab..c954279 100644 --- a/dali/internal/legacy/tizen/image-encoder.h +++ b/dali/internal/legacy/tizen/image-encoder.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_IMAGE_ENCODER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ namespace Dali { - /** * Used file format */ diff --git a/dali/internal/legacy/tizen/platform-capabilities.h b/dali/internal/legacy/tizen/platform-capabilities.h index 403414e..7d77236 100644 --- a/dali/internal/legacy/tizen/platform-capabilities.h +++ b/dali/internal/legacy/tizen/platform-capabilities.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_PLATFORM_CAPABILITIES_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,8 @@ namespace Dali { - namespace TizenPlatform { - /** * Returns true if non power of two textures are supported. */ @@ -42,13 +40,13 @@ inline bool SupportsNonPowerOfTwoTextures() /** * Returns the size that a textures dimension should have for a specific image size. */ -inline unsigned int GetTextureDimension( unsigned int size ) +inline unsigned int GetTextureDimension(unsigned int size) { #ifdef NON_POWER_OF_TWO_TEXTURES return size; #else #error "NPOT are standard in GLES 2.0 if mipmaps are not used, they are standard with mipmaps and no restrictions in GLES 3.0, requiring them simplifies image handling code." - return NextPowerOfTwo( size ); + return NextPowerOfTwo(size); #endif } diff --git a/dali/internal/network/common/automation.cpp b/dali/internal/network/common/automation.cpp index 7c5be2b..0666232 100644 --- a/dali/internal/network/common/automation.cpp +++ b/dali/internal/network/common/automation.cpp @@ -1,6 +1,6 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,38 +20,36 @@ #include // EXTERNAL INCLUDES -#include -#include -#include -#include #include +#include +#include +#include +#include -using Dali::Property; using Dali::Matrix; using Dali::Matrix3; +using Dali::Property; -namespace // un-named namespace +namespace // un-named namespace { - const unsigned int MAX_SET_PROPERTY_STRING_LENGTH = 256; ///< maximum length of a set property command class JsonPropertyValue { public: - JsonPropertyValue( const std::string& str ) + JsonPropertyValue(const std::string& str) { std::size_t strLength = str.length(); - mString.reserve( strLength ); - for( std::size_t i = 0; i < strLength; ++i ) + mString.reserve(strLength); + for(std::size_t i = 0; i < strLength; ++i) { const char c = str[i]; - if( (c != '[') && c != ']') + if((c != '[') && c != ']') { - mString.push_back( c ); + mString.push_back(c); } } - } std::string GetString() const { @@ -59,11 +57,11 @@ public: } float GetFloat() const { - return atof( mString.c_str() ); + return atof(mString.c_str()); } int GetInt() { - return atoi( mString.c_str() ); + return atoi(mString.c_str()); } bool GetBoolean() { @@ -74,8 +72,8 @@ public: { Dali::Vector2 vec2; - int count = sscanf( mString.c_str(),"%f,%f",&vec2.x,&vec2.y ); - if( count != 2 ) + int count = sscanf(mString.c_str(), "%f,%f", &vec2.x, &vec2.y); + if(count != 2) { DALI_LOG_ERROR("Bad format\n"); } @@ -86,8 +84,8 @@ public: { Dali::Vector3 vec3; - int count = sscanf( mString.c_str(),"%f,%f,%f",&vec3.x,&vec3.y,&vec3.z ); - if( count != 3 ) + int count = sscanf(mString.c_str(), "%f,%f,%f", &vec3.x, &vec3.y, &vec3.z); + if(count != 3) { DALI_LOG_ERROR("Bad format\n"); } @@ -98,8 +96,8 @@ public: { Dali::Vector4 vec4; - int count = sscanf( mString.c_str(),"%f,%f,%f,%f", &vec4.x, &vec4.y, &vec4.z, &vec4.w ); - if( count != 4 ) + int count = sscanf(mString.c_str(), "%f,%f,%f,%f", &vec4.x, &vec4.y, &vec4.z, &vec4.w); + if(count != 4) { DALI_LOG_ERROR("Bad format\n"); } @@ -108,91 +106,89 @@ public: private: std::string mString; - }; -void SetProperty( Dali::Handle handle, int propertyId, JsonPropertyValue& propertyValue ) +void SetProperty(Dali::Handle handle, int propertyId, JsonPropertyValue& propertyValue) { - Dali::Property::Type type = handle.GetPropertyType( propertyId ); - switch( type ) - { - case Dali::Property::FLOAT: + Dali::Property::Type type = handle.GetPropertyType(propertyId); + switch(type) { - float val = propertyValue.GetFloat(); - handle.SetProperty( propertyId, Dali::Property::Value( val ) ); - break; - } - case Dali::Property::INTEGER: - { - int val = propertyValue.GetInt(); - handle.SetProperty( propertyId, Dali::Property::Value( val ) ); - break; - } - case Dali::Property::BOOLEAN: - { - bool val = propertyValue.GetBoolean(); - handle.SetProperty( propertyId, Dali::Property::Value( val ) ); - break; - } - case Dali::Property::STRING: - { - std::string str = propertyValue.GetString(); - handle.SetProperty( propertyId, Dali::Property::Value( str ) ); - break; - } - case Dali::Property::VECTOR2: - { - Dali::Vector2 val = propertyValue.GetVector2(); - handle.SetProperty( propertyId, Dali::Property::Value( val ) ); - break; - } - case Dali::Property::VECTOR3: - { - Dali::Vector3 val = propertyValue.GetVector3(); - handle.SetProperty( propertyId, Dali::Property::Value( val ) ); - break; - } - case Dali::Property::VECTOR4: - { - Dali::Vector4 val = propertyValue.GetVector4(); - handle.SetProperty( propertyId, Dali::Property::Value( val ) ); - break; - } - default: - { - break; - } + case Dali::Property::FLOAT: + { + float val = propertyValue.GetFloat(); + handle.SetProperty(propertyId, Dali::Property::Value(val)); + break; + } + case Dali::Property::INTEGER: + { + int val = propertyValue.GetInt(); + handle.SetProperty(propertyId, Dali::Property::Value(val)); + break; + } + case Dali::Property::BOOLEAN: + { + bool val = propertyValue.GetBoolean(); + handle.SetProperty(propertyId, Dali::Property::Value(val)); + break; + } + case Dali::Property::STRING: + { + std::string str = propertyValue.GetString(); + handle.SetProperty(propertyId, Dali::Property::Value(str)); + break; + } + case Dali::Property::VECTOR2: + { + Dali::Vector2 val = propertyValue.GetVector2(); + handle.SetProperty(propertyId, Dali::Property::Value(val)); + break; + } + case Dali::Property::VECTOR3: + { + Dali::Vector3 val = propertyValue.GetVector3(); + handle.SetProperty(propertyId, Dali::Property::Value(val)); + break; + } + case Dali::Property::VECTOR4: + { + Dali::Vector4 val = propertyValue.GetVector4(); + handle.SetProperty(propertyId, Dali::Property::Value(val)); + break; + } + default: + { + break; + } } } -int SetProperties( const std::string& setPropertyMessage ) +int SetProperties(const std::string& setPropertyMessage) { - std::istringstream iss( setPropertyMessage ); - std::string token; - getline( iss, token, '|' ); // swallow command name - while( getline( iss, token, '|' ) ) + std::istringstream iss(setPropertyMessage); + std::string token; + getline(iss, token, '|'); // swallow command name + while(getline(iss, token, '|')) { std::string actorId, propName, propValue; - if( token.compare( "---" ) != 0 ) + if(token.compare("---") != 0) { - std::istringstream propss( token ); - getline( propss, actorId, ';' ); - getline( propss, propName, ';' ); - getline( propss, propValue ); + std::istringstream propss(token); + getline(propss, actorId, ';'); + getline(propss, propName, ';'); + getline(propss, propValue); Dali::Actor root = Dali::Stage::GetCurrent().GetRootLayer(); - int id = atoi( actorId.c_str() ); - Dali::Actor a = root.FindChildById( id ); - if( a ) + int id = atoi(actorId.c_str()); + Dali::Actor a = root.FindChildById(id); + if(a) { // lookup by name for custom properties - int propId = a.GetPropertyIndex( propName ); - if( propId > 0 ) + int propId = a.GetPropertyIndex(propName); + if(propId > 0) { - JsonPropertyValue pv( propValue ); - SetProperty( a, propId, pv ); + JsonPropertyValue pv(propValue); + SetProperty(a, propId, pv); } - } } } @@ -200,74 +196,72 @@ int SetProperties( const std::string& setPropertyMessage ) return 0; } - -void MatrixToStream( Property::Value value, std::ostream& o ) +void MatrixToStream(Property::Value value, std::ostream& o) { - Matrix m4(false); + Matrix m4(false); Matrix3 m3; - if( value.Get(m4) ) + if(value.Get(m4)) { float* matrix = m4.AsFloat(); - o << "[ [" << matrix[0] << ", " << matrix[1] << ", " << matrix[2] << ", " << matrix[3] << "], " - << "[" << matrix[4] << ", " << matrix[5] << ", " << matrix[6] << ", " << matrix[7] << "], " + o << "[ [" << matrix[0] << ", " << matrix[1] << ", " << matrix[2] << ", " << matrix[3] << "], " + << "[" << matrix[4] << ", " << matrix[5] << ", " << matrix[6] << ", " << matrix[7] << "], " << "[" << matrix[8] << ", " << matrix[9] << ", " << matrix[10] << ", " << matrix[11] << "], " << "[" << matrix[12] << ", " << matrix[13] << ", " << matrix[14] << ", " << matrix[15] << "] ]"; } - else if( value.Get(m3) ) + else if(value.Get(m3)) { float* matrix = m3.AsFloat(); - o << "[ [" << matrix[0] << ", " << matrix[1] << ", " << matrix[2] << "], " - << "[" << matrix[3] << ", " << matrix[4] << ", " << matrix[5] << "], " - << "[" << matrix[6] << ", " << matrix[7] << ", " << matrix[8] << "] ]"; + o << "[ [" << matrix[0] << ", " << matrix[1] << ", " << matrix[2] << "], " + << "[" << matrix[3] << ", " << matrix[4] << ", " << matrix[5] << "], " + << "[" << matrix[6] << ", " << matrix[7] << ", " << matrix[8] << "] ]"; } } +}; // namespace -}; // un-named namespace - -inline std::string Quote( const std::string& in ) +inline std::string Quote(const std::string& in) { - return (std::string( "\"" ) + in + std::string( "\"" )); + return (std::string("\"") + in + std::string("\"")); } template -std::string ToString( T i ) +std::string ToString(T i) { std::stringstream ss; - std::string s; + std::string s; ss << i; s = ss.str(); return s; } -std::string GetPropertyValueString( Dali::Handle handle, int propertyIndex ) +std::string GetPropertyValueString(Dali::Handle handle, int propertyIndex) { std::ostringstream valueStream; - if( propertyIndex != Dali::Property::INVALID_INDEX ) + if(propertyIndex != Dali::Property::INVALID_INDEX) { - Dali::Property::Value value = handle.GetProperty( propertyIndex ); + Dali::Property::Value value = handle.GetProperty(propertyIndex); - if( value.GetType() == Dali::Property::STRING ) + if(value.GetType() == Dali::Property::STRING) { // Escape the string (to ensure valid json) // Write out quotes, escapes and control characters using unicode syntax \uXXXX std::ostringstream unescapedValue; unescapedValue << value; - std::string valueString = unescapedValue.str(); + std::string valueString = unescapedValue.str(); std::ostringstream escapedValue; - for( std::string::iterator c = valueString.begin() ; c != valueString.end(); ++c ) + for(std::string::iterator c = valueString.begin(); c != valueString.end(); ++c) { - if( *c == '"' ) + if(*c == '"') { escapedValue << "\\\""; } - else if( *c == '\\' ) + else if(*c == '\\') { escapedValue << "\\\\"; } - else if( '\x00' <= *c && *c <= '\x1f' ) + else if('\x00' <= *c && *c <= '\x1f') { escapedValue << "\\u" << std::hex << std::setw(4) << std::setfill('0') << int(*c); } @@ -278,9 +272,9 @@ std::string GetPropertyValueString( Dali::Handle handle, int propertyIndex ) } valueStream << escapedValue.str(); } - else if( value.GetType() == Dali::Property::MATRIX || value.GetType() == Dali::Property::MATRIX3 ) + else if(value.GetType() == Dali::Property::MATRIX || value.GetType() == Dali::Property::MATRIX3) { - MatrixToStream( value, valueStream ); + MatrixToStream(value, valueStream); } else { @@ -296,94 +290,109 @@ std::string GetPropertyValueString( Dali::Handle handle, int propertyIndex ) } // currently rotations are output in Euler format ( may change) -void AppendPropertyNameAndValue( Dali::Handle handle, int propertyIndex, std::ostringstream& outputStream) +void AppendPropertyNameAndValue(Dali::Handle handle, int propertyIndex, std::ostringstream& outputStream) { // get the property name and the value as a string - std::string propertyName( handle.GetPropertyName( propertyIndex ) ); + std::string propertyName(handle.GetPropertyName(propertyIndex)); // Apply quotes around the property name - outputStream << "\"" << propertyName << "\"" << ","; + outputStream << "\"" << propertyName << "\"" + << ","; // Convert value to a string - std::string valueString = GetPropertyValueString( handle, propertyIndex ); + std::string valueString = GetPropertyValueString(handle, propertyIndex); outputStream << "\"" << valueString << "\""; } -void AppendRendererPropertyNameAndValue( Dali::Renderer renderer, int rendererIndex, const std::string& name, std::ostringstream& outputStream) +void AppendRendererPropertyNameAndValue(Dali::Renderer renderer, int rendererIndex, const std::string& name, std::ostringstream& outputStream) { - outputStream << ",[\"renderer[" << rendererIndex << "]." << name << "\"" << ","; - std::string valueString = GetPropertyValueString( renderer, renderer.GetPropertyIndex( name ) ); + outputStream << ",[\"renderer[" << rendererIndex << "]." << name << "\"" + << ","; + std::string valueString = GetPropertyValueString(renderer, renderer.GetPropertyIndex(name)); outputStream << "\"" << valueString << "\"]"; } -bool ExcludeProperty( int propIndex ) +bool ExcludeProperty(int propIndex) { - return (propIndex == Dali::Actor::Property::NAME || - - // all of these are repeat properties of values in vectors.... - // We don't really need these in the UI - propIndex == Dali::Actor::Property::ANCHOR_POINT_X || propIndex == Dali::Actor::Property::ANCHOR_POINT_Y || propIndex == Dali::Actor::Property::ANCHOR_POINT_Z || propIndex == Dali::Actor::Property::PARENT_ORIGIN_X - || propIndex == Dali::Actor::Property::PARENT_ORIGIN_Y || propIndex == Dali::Actor::Property::PARENT_ORIGIN_Z || propIndex == Dali::Actor::Property::COLOR_RED || propIndex == Dali::Actor::Property::COLOR_GREEN - || propIndex == Dali::Actor::Property::COLOR_BLUE || propIndex == Dali::Actor::Property::COLOR_ALPHA|| propIndex == Dali::Actor::Property::POSITION_X || propIndex == Dali::Actor::Property::POSITION_Y - || propIndex == Dali::Actor::Property::POSITION_Z|| propIndex == Dali::Actor::Property::SIZE_WIDTH|| propIndex == Dali::Actor::Property::SIZE_HEIGHT || propIndex == Dali::Actor::Property::SCALE_X || propIndex == Dali::Actor::Property::SCALE_Y - || propIndex == Dali::Actor::Property::SCALE_Z || propIndex == Dali::Actor::Property::SIZE_DEPTH); + // all of these are repeat properties of values in vectors.... + // We don't really need these in the UI + return (propIndex == Dali::Actor::Property::NAME || + propIndex == Dali::Actor::Property::ANCHOR_POINT_X || + propIndex == Dali::Actor::Property::ANCHOR_POINT_Y || + propIndex == Dali::Actor::Property::ANCHOR_POINT_Z || + propIndex == Dali::Actor::Property::PARENT_ORIGIN_X || + propIndex == Dali::Actor::Property::PARENT_ORIGIN_Y || + propIndex == Dali::Actor::Property::PARENT_ORIGIN_Z || + propIndex == Dali::Actor::Property::COLOR_RED || + propIndex == Dali::Actor::Property::COLOR_GREEN || + propIndex == Dali::Actor::Property::COLOR_BLUE || + propIndex == Dali::Actor::Property::COLOR_ALPHA || + propIndex == Dali::Actor::Property::POSITION_X || + propIndex == Dali::Actor::Property::POSITION_Y || + propIndex == Dali::Actor::Property::POSITION_Z || + propIndex == Dali::Actor::Property::SIZE_WIDTH || + propIndex == Dali::Actor::Property::SIZE_HEIGHT || + propIndex == Dali::Actor::Property::SCALE_X || + propIndex == Dali::Actor::Property::SCALE_Y || + propIndex == Dali::Actor::Property::SCALE_Z || + propIndex == Dali::Actor::Property::SIZE_DEPTH); } -std::string DumpJson( Dali::Actor actor, int level ) +std::string DumpJson(Dali::Actor actor, int level) { // All the information about this actor std::ostringstream msg; - msg << "{ " << Quote( "Name" ) << " : " << Quote( actor.GetProperty< std::string >( Actor::Property::NAME ) ) << ", " << Quote( "level" ) << " : " << level << ", " << Quote( "id" ) << " : " << actor.GetId() << ", " << Quote( "IsVisible" ) - << " : " << actor.GetCurrentProperty< bool >( Actor::Property::VISIBLE ) << ", " << Quote( "IsSensitive" ) << " : " << actor.GetProperty< bool >( Actor::Property::SENSITIVE ); + msg << "{ " << Quote("Name") << " : " << Quote(actor.GetProperty(Actor::Property::NAME)) << ", " << Quote("level") << " : " << level << ", " << Quote("id") << " : " << actor.GetId() << ", " << Quote("IsVisible") + << " : " << actor.GetCurrentProperty(Actor::Property::VISIBLE) << ", " << Quote("IsSensitive") << " : " << actor.GetProperty(Actor::Property::SENSITIVE); - msg << ", " << Quote( "properties" ) << ": [ "; + msg << ", " << Quote("properties") << ": [ "; Dali::Property::IndexContainer indices; - actor.GetPropertyIndices( indices ); + actor.GetPropertyIndices(indices); - Dali::Property::IndexContainer::Iterator iter = indices.Begin(); - int numCustom = 0; - for( ; iter != indices.End() ; iter++ ) + Dali::Property::IndexContainer::Iterator iter = indices.Begin(); + int numCustom = 0; + for(; iter != indices.End(); iter++) { int i = *iter; - if( !ExcludeProperty( i ) ) + if(!ExcludeProperty(i)) { - if( numCustom++ != 0 ) + if(numCustom++ != 0) { msg << ", "; } msg << "["; - AppendPropertyNameAndValue( actor, i,msg ); + AppendPropertyNameAndValue(actor, i, msg); msg << "]"; } } - if( actor.GetRendererCount() > 0 ) + if(actor.GetRendererCount() > 0) { - for( unsigned int i=0; i MAX_SET_PROPERTY_STRING_LENGTH ) + if(message.length() > MAX_SET_PROPERTY_STRING_LENGTH) { DALI_LOG_ERROR("SetProperty message length too long, size = %ul\n", message.length()); return; } - SetProperties( message ); + SetProperties(message); } -void DumpScene( unsigned int clientId, ClientSendDataInterface* sendData ) +void DumpScene(unsigned int clientId, ClientSendDataInterface* sendData) { - char buf[32]; - std::string json = GetActorTree(); - int length = json.length(); - snprintf( buf, 32, "%d\n", length ); - std::string header( buf ); + char buf[32]; + std::string json = GetActorTree(); + int length = json.length(); + snprintf(buf, 32, "%d\n", length); + std::string header(buf); json = buf + json; - sendData->SendData( json.c_str(), json.length(), clientId ); + sendData->SendData(json.c_str(), json.length(), clientId); } } // namespace Automation -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali diff --git a/dali/internal/network/common/automation.h b/dali/internal/network/common/automation.h index 4420153..c675001 100644 --- a/dali/internal/network/common/automation.h +++ b/dali/internal/network/common/automation.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_AUTOMATION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ * */ - // EXTERNAL INCLUDES #include @@ -27,13 +26,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief The automation functions allow a way to control Dali via a network socket. * @@ -49,29 +45,26 @@ namespace Adaptor */ namespace Automation { - /** * @brief Sets properties on an Actor. * No ClientSendDataInterface required, as no response is sent back * @param[in] message set property message */ -void SetProperty( const std::string& message ); - +void SetProperty(const std::string& message); /** * @brief Dumps the actor tree to the client * @param[in] clientId unique network client id * @param[in] sendData interface to transmit data to the client */ -void DumpScene( unsigned int clientId, ClientSendDataInterface* sendData ); - +void DumpScene(unsigned int clientId, ClientSendDataInterface* sendData); } // namespace Automation -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif diff --git a/dali/internal/network/common/client-send-data-interface.h b/dali/internal/network/common/client-send-data-interface.h index 9908bf5..18a5899 100644 --- a/dali/internal/network/common/client-send-data-interface.h +++ b/dali/internal/network/common/client-send-data-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_CLIENT_SEND_DATA_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,31 +20,25 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Abstract interface used to transmit data to a client */ class ClientSendDataInterface { public: - /** * @brief Sends data to the client * @param[in] data pointer to some data * @param[in] bufferSizeInBytes how big the buffer is in bytes * @param[in] clientId unique client id to send the data to */ - virtual void SendData( const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId ) = 0; - + virtual void SendData(const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId) = 0; protected: - /** * @brief Constructor */ @@ -60,20 +54,17 @@ protected: } private: - // Undefined copy constructor. - ClientSendDataInterface( const ClientSendDataInterface& ); + ClientSendDataInterface(const ClientSendDataInterface&); // Undefined assignment operator. - ClientSendDataInterface& operator=( const ClientSendDataInterface& ); - + ClientSendDataInterface& operator=(const ClientSendDataInterface&); }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_CLIENT_SEND_DATA_INTERFACE_H diff --git a/dali/internal/network/common/network-performance-client.cpp b/dali/internal/network/common/network-performance-client.cpp index 1185c95..836f2ba 100644 --- a/dali/internal/network/common/network-performance-client.cpp +++ b/dali/internal/network/common/network-performance-client.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,33 +23,27 @@ #include // INTERNAL INCLUDES -#include -#include #include - +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { const float MICROSECONDS_TO_SECOND = 1e-6; -const char UNKNOWN_CMD[]= "Command or parameter invalid, type help for list of commands\n"; - +const char UNKNOWN_CMD[] = "Command or parameter invalid, type help for list of commands\n"; /** * helper class to store data along with the automation callback. */ -class AutomationCallback: public CallbackBase +class AutomationCallback : public CallbackBase { public: - /** * instead of using templates, or having different callback classes for each callback * we use a command id that decides which static function to call on the Automation class. @@ -61,85 +55,84 @@ public: DUMP_SCENE }; - AutomationCallback( unsigned int clientId, ClientSendDataInterface& sendDataInterface ) - :CallbackBase( reinterpret_cast< void* >( this ), + AutomationCallback(unsigned int clientId, ClientSendDataInterface& sendDataInterface) + : CallbackBase(reinterpret_cast(this), NULL, // we get the dispatcher to call function directly - reinterpret_cast< CallbackBase::Dispatcher>( &AutomationCallback::Dispatcher) ), - mSendDataInterface( sendDataInterface ), - mCommandId( UNKNOWN_COMMAND ), - mClientId( clientId ) - {} + reinterpret_cast(&AutomationCallback::Dispatcher)), + mSendDataInterface(sendDataInterface), + mCommandId(UNKNOWN_COMMAND), + mClientId(clientId) + { + } - void AssignSetPropertyCommand( std::string setPropertyCommand ) + void AssignSetPropertyCommand(std::string setPropertyCommand) { - mCommandId = SET_PROPERTY; + mCommandId = SET_PROPERTY; mPropertyCommand = setPropertyCommand; } void AssignDumpSceneCommand() { - mCommandId = DUMP_SCENE; + mCommandId = DUMP_SCENE; } void RunCallback() { - switch( mCommandId ) + switch(mCommandId) { case SET_PROPERTY: { - Automation::SetProperty( mPropertyCommand ); + Automation::SetProperty(mPropertyCommand); break; } case DUMP_SCENE: { - Automation::DumpScene( mClientId, &mSendDataInterface); + Automation::DumpScene(mClientId, &mSendDataInterface); break; } default: { - DALI_ASSERT_DEBUG( 0 && "Unknown command"); + DALI_ASSERT_DEBUG(0 && "Unknown command"); break; } } } - static void Dispatcher( CallbackBase& base ) + static void Dispatcher(CallbackBase& base) { - AutomationCallback& automationCallback( static_cast< AutomationCallback& >( base) ); + AutomationCallback& automationCallback(static_cast(base)); automationCallback.RunCallback(); } private: - - std::string mPropertyCommand; ///< property command - ClientSendDataInterface& mSendDataInterface; ///< Abstract client send data interface - CommandId mCommandId; ///< command id - const unsigned int mClientId; ///< client id + std::string mPropertyCommand; ///< property command + ClientSendDataInterface& mSendDataInterface; ///< Abstract client send data interface + CommandId mCommandId; ///< command id + const unsigned int mClientId; ///< client id }; } // unnamed namespace -NetworkPerformanceClient::NetworkPerformanceClient( pthread_t* thread, - SocketInterface *socket, - unsigned int clientId, - ClientSendDataInterface& sendDataInterface, - SocketFactoryInterface& socketFactory ) -: mThread( thread ), - mSocket( socket ), - mMarkerBitmask( PerformanceMarker::FILTERING_DISABLED ), - mSendDataInterface( sendDataInterface ), - mSocketFactoryInterface( socketFactory ), - mClientId( clientId ), +NetworkPerformanceClient::NetworkPerformanceClient(pthread_t* thread, + SocketInterface* socket, + unsigned int clientId, + ClientSendDataInterface& sendDataInterface, + SocketFactoryInterface& socketFactory) +: mThread(thread), + mSocket(socket), + mMarkerBitmask(PerformanceMarker::FILTERING_DISABLED), + mSendDataInterface(sendDataInterface), + mSocketFactoryInterface(socketFactory), + mClientId(clientId), mConsoleClient(false) { - } NetworkPerformanceClient::~NetworkPerformanceClient() { - if( mSocket->SocketIsOpen() ) + if(mSocket->SocketIsOpen()) { mSocket->CloseSocket(); } - mSocketFactoryInterface.DestroySocket( mSocket ); + mSocketFactoryInterface.DestroySocket(mSocket); } unsigned int NetworkPerformanceClient::GetId() const @@ -152,31 +145,27 @@ SocketInterface& NetworkPerformanceClient::GetSocket() return *mSocket; } -bool NetworkPerformanceClient::WriteSocket( const void* buffer, unsigned int bufferSizeInBytes ) +bool NetworkPerformanceClient::WriteSocket(const void* buffer, unsigned int bufferSizeInBytes) { - return mSocket->Write( buffer, bufferSizeInBytes ); + return mSocket->Write(buffer, bufferSizeInBytes); } -bool NetworkPerformanceClient::TransmitMarker( const PerformanceMarker& marker, const char* const description ) +bool NetworkPerformanceClient::TransmitMarker(const PerformanceMarker& marker, const char* const description) { - if( ! marker.IsFilterEnabled( mMarkerBitmask ) ) + if(!marker.IsFilterEnabled(mMarkerBitmask)) { return true; } - if( mConsoleClient ) + if(mConsoleClient) { // write out the time stamp - char buffer[64]; + char buffer[64]; double usec = marker.GetTimeStamp().microseconds; - int size = snprintf( buffer, sizeof(buffer),"%.6f (seconds), %s\n", - usec * MICROSECONDS_TO_SECOND, - description ); - - return mSocket->Write( buffer, size ); + int size = snprintf(buffer, sizeof(buffer), "%.6f (seconds), %s\n", usec * MICROSECONDS_TO_SECOND, description); + return mSocket->Write(buffer, size); } - // todo serialize the data return false; } @@ -191,27 +180,27 @@ pthread_t* NetworkPerformanceClient::GetThread() return mThread; } -void NetworkPerformanceClient::ProcessCommand( char* buffer, unsigned int bufferSizeInBytes ) +void NetworkPerformanceClient::ProcessCommand(char* buffer, unsigned int bufferSizeInBytes) { // if connected via console, then strip off the carriage return, and switch to console mode - if( buffer[ bufferSizeInBytes - 1] == '\n') + if(buffer[bufferSizeInBytes - 1] == '\n') { - buffer[ bufferSizeInBytes - 1] = 0; - mConsoleClient = true; + buffer[bufferSizeInBytes - 1] = 0; + mConsoleClient = true; } - unsigned int param(0); - std::string stringParam; - PerformanceProtocol::CommandId commandId( PerformanceProtocol::UNKNOWN_COMMAND ); + unsigned int param(0); + std::string stringParam; + PerformanceProtocol::CommandId commandId(PerformanceProtocol::UNKNOWN_COMMAND); - bool ok = PerformanceProtocol::GetCommandId( buffer, bufferSizeInBytes, commandId, param, stringParam ); - if( !ok ) + bool ok = PerformanceProtocol::GetCommandId(buffer, bufferSizeInBytes, commandId, param, stringParam); + if(!ok) { - WriteSocket( UNKNOWN_CMD, sizeof(UNKNOWN_CMD) ); + WriteSocket(UNKNOWN_CMD, sizeof(UNKNOWN_CMD)); return; } std::string response; - switch( commandId ) + switch(commandId) { case PerformanceProtocol::HELP_MESSAGE: { @@ -221,19 +210,19 @@ void NetworkPerformanceClient::ProcessCommand( char* buffer, unsigned int buffer case PerformanceProtocol::ENABLE_TIME_MARKER_BIT_MASK: { - mMarkerBitmask = static_cast< PerformanceMarker::MarkerFilter >( param ); - response = "enable time marker "; + mMarkerBitmask = static_cast(param); + response = "enable time marker "; break; } case PerformanceProtocol::DUMP_SCENE_GRAPH: { // this needs to be run on the main thread, use the trigger event.... - AutomationCallback* callback = new AutomationCallback( mClientId, mSendDataInterface ); + AutomationCallback* callback = new AutomationCallback(mClientId, mSendDataInterface); callback->AssignDumpSceneCommand(); // create a trigger event that automatically deletes itself after the callback has run in the main thread - TriggerEventInterface *interface = TriggerEventFactory::CreateTriggerEvent( callback, TriggerEventInterface::DELETE_AFTER_TRIGGER ); + TriggerEventInterface* interface = TriggerEventFactory::CreateTriggerEvent(callback, TriggerEventInterface::DELETE_AFTER_TRIGGER); // asynchronous call, the call back will be run sometime later on the main thread interface->Trigger(); @@ -243,11 +232,11 @@ void NetworkPerformanceClient::ProcessCommand( char* buffer, unsigned int buffer case PerformanceProtocol::SET_PROPERTIES: { // this needs to be run on the main thread, use the trigger event.... - AutomationCallback* callback = new AutomationCallback( mClientId, mSendDataInterface ); - callback->AssignSetPropertyCommand( stringParam ); + AutomationCallback* callback = new AutomationCallback(mClientId, mSendDataInterface); + callback->AssignSetPropertyCommand(stringParam); // create a trigger event that automatically deletes itself after the callback has run in the main thread - TriggerEventInterface *interface = TriggerEventFactory::CreateTriggerEvent( callback, TriggerEventInterface::DELETE_AFTER_TRIGGER ); + TriggerEventInterface* interface = TriggerEventFactory::CreateTriggerEvent(callback, TriggerEventInterface::DELETE_AFTER_TRIGGER); // asynchronous call, the call back will be run sometime later on the main thread interface->Trigger(); @@ -258,7 +247,7 @@ void NetworkPerformanceClient::ProcessCommand( char* buffer, unsigned int buffer case PerformanceProtocol::ENABLE_METRIC: case PerformanceProtocol::DISABLE_METRIC: { - response="Metrics currently not supported"; + response = "Metrics currently not supported"; break; } default: @@ -267,21 +256,19 @@ void NetworkPerformanceClient::ProcessCommand( char* buffer, unsigned int buffer break; } } - if( ! response.empty() ) + if(!response.empty()) { // add a carriage return for console clients - if( mConsoleClient ) + if(mConsoleClient) { - response+="\n"; + response += "\n"; } - WriteSocket( response.c_str(), response.length() ); + WriteSocket(response.c_str(), response.length()); } } - +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali diff --git a/dali/internal/network/common/network-performance-client.h b/dali/internal/network/common/network-performance-client.h index c196b86..a3d93dd 100644 --- a/dali/internal/network/common/network-performance-client.h +++ b/dali/internal/network/common/network-performance-client.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_CLIENT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,21 +22,17 @@ #include // INTERNAL INCLUDES -#include +#include #include #include -#include - +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Network Performance client * @@ -58,7 +54,6 @@ namespace Adaptor class NetworkPerformanceClient { public: - /** * @brief Constructor * @param thread thread pointer @@ -67,11 +62,11 @@ public: * @param sendDataInterface used to send data to the socket from main thread * @param SocketFactoryInterface used to delete the socket when the client is destroyed */ - NetworkPerformanceClient( pthread_t* thread, - SocketInterface *socket, - unsigned int clientId, - ClientSendDataInterface& sendDataInterface, - SocketFactoryInterface& socketFactory ); + NetworkPerformanceClient(pthread_t* thread, + SocketInterface* socket, + unsigned int clientId, + ClientSendDataInterface& sendDataInterface, + SocketFactoryInterface& socketFactory); /** * @brief Destructor @@ -92,20 +87,20 @@ public: * @brief Write data to a socket. Can be called from any thread * @copydoc Dali::SocketInterface::Send */ - bool WriteSocket( const void* buffer, unsigned int bufferSizeInBytes ); + bool WriteSocket(const void* buffer, unsigned int bufferSizeInBytes); /** * @brief Process a command * @param buffer pointer to command data * @param bufferSizeInBytes how big the buffer is in bytes */ - void ProcessCommand( char* buffer, unsigned int bufferSizeInBytes ); + void ProcessCommand(char* buffer, unsigned int bufferSizeInBytes); /** * @brief Write a marker to the socket, if this client is filtering this marker. * @param marker */ - bool TransmitMarker( const PerformanceMarker& marker, const char* const description ); + bool TransmitMarker(const PerformanceMarker& marker, const char* const description); /** * @brief If the client is waiting inside a select statement, this will cause it @@ -120,22 +115,19 @@ public: pthread_t* GetThread(); private: - - pthread_t* mThread; ///< thread for the client - SocketInterface* mSocket; ///< socket interface - PerformanceMarker::MarkerFilter mMarkerBitmask; ///< What markers are currently filtered - ClientSendDataInterface& mSendDataInterface; ///< used to send data to a client from the main event thread - SocketFactoryInterface& mSocketFactoryInterface; ///< used to delete the socket - unsigned int mClientId; ///< unique client id - bool mConsoleClient; ///< if connected via a console then all responses are in ASCII, not binary packed data. - + pthread_t* mThread; ///< thread for the client + SocketInterface* mSocket; ///< socket interface + PerformanceMarker::MarkerFilter mMarkerBitmask; ///< What markers are currently filtered + ClientSendDataInterface& mSendDataInterface; ///< used to send data to a client from the main event thread + SocketFactoryInterface& mSocketFactoryInterface; ///< used to delete the socket + unsigned int mClientId; ///< unique client id + bool mConsoleClient; ///< if connected via a console then all responses are in ASCII, not binary packed data. }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_CLIENT_H diff --git a/dali/internal/network/common/network-performance-protocol.cpp b/dali/internal/network/common/network-performance-protocol.cpp index 5b28773..5c23e84 100644 --- a/dali/internal/network/common/network-performance-protocol.cpp +++ b/dali/internal/network/common/network-performance-protocol.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,19 +21,16 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include namespace Dali { - namespace PerformanceProtocol { - namespace { - /** * Command parameter type */ @@ -49,32 +46,35 @@ enum PARAMETER_TYPE */ struct CommandInfo { - CommandId cmdId; - CommandString cmdString; + CommandId cmdId; + CommandString cmdString; PARAMETER_TYPE paramType; }; /** * Command lookup table */ +// clang-format off CommandInfo CommandLookup[]= { - { HELP_MESSAGE , "help" ,NO_PARAMS }, - { ENABLE_METRIC , "enable_metric" ,UNSIGNED_INT }, - { DISABLE_METRIC , "disable_metric" ,UNSIGNED_INT }, - { LIST_METRICS_AVAILABLE , "list_metrics" ,NO_PARAMS }, - { ENABLE_TIME_MARKER_BIT_MASK, "set_marker", UNSIGNED_INT }, - { DUMP_SCENE_GRAPH , "dump_scene" ,NO_PARAMS }, - { SET_PROPERTIES , "set_properties" ,STRING }, - { UNKNOWN_COMMAND , "unknown" ,NO_PARAMS } + {HELP_MESSAGE, "help", NO_PARAMS }, + {ENABLE_METRIC, "enable_metric", UNSIGNED_INT}, + {DISABLE_METRIC, "disable_metric", UNSIGNED_INT}, + {LIST_METRICS_AVAILABLE, "list_metrics", NO_PARAMS }, + {ENABLE_TIME_MARKER_BIT_MASK, "set_marker", UNSIGNED_INT}, + {DUMP_SCENE_GRAPH, "dump_scene", NO_PARAMS }, + {SET_PROPERTIES, "set_properties", STRING }, + {UNKNOWN_COMMAND, "unknown", NO_PARAMS } }; -const unsigned int CommandLookupLength = sizeof( CommandLookup ) /sizeof( CommandInfo ); +// clang-format on +const unsigned int CommandLookupLength = sizeof(CommandLookup) / sizeof(CommandInfo); -#define GREEN "\033[01;32m" -#define NORMAL "\e[m" +#define GREEN "\033[01;32m" +#define NORMAL "\e[m" #define PARAM "\033[22;32m" #define YELLOW "\033[01;33m" +// clang-format off const char* const helpMsg = YELLOW "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" @@ -97,7 +97,7 @@ const char* const helpMsg = GREEN " set_properties " PARAM "|178;Size;[ 144.0, 144.0, 144.0 ]|178;Color;[ 1.0, 1,0, 1.0 ]|\n" "\n" GREEN " dump_scene" NORMAL " - dump the current scene in json format\n"; - +// clang-format off } // un-named namespace bool GetCommandId( const char* const commandString, unsigned int lengthInBytes, CommandId& commandId, unsigned int& intParam, std::string& stringParam ) diff --git a/dali/internal/network/common/network-performance-protocol.h b/dali/internal/network/common/network-performance-protocol.h index ce6e467..a5123b2 100644 --- a/dali/internal/network/common/network-performance-protocol.h +++ b/dali/internal/network/common/network-performance-protocol.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_PROTOCOL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,29 +23,26 @@ namespace Dali { - namespace PerformanceProtocol { - -const unsigned int MAX_COMMAND_STRING_LENGTH = 256; ///< maximum length of a command including null terminator +const unsigned int MAX_COMMAND_STRING_LENGTH = 256; ///< maximum length of a command including null terminator /** * @brief List of commands id's */ enum CommandId { - HELP_MESSAGE = 0, ///< help message - ENABLE_METRIC = 1, ///< enable metric - DISABLE_METRIC = 2, ///< disable metric - LIST_METRICS_AVAILABLE = 3, ///< list metrics that are available + HELP_MESSAGE = 0, ///< help message + ENABLE_METRIC = 1, ///< enable metric + DISABLE_METRIC = 2, ///< disable metric + LIST_METRICS_AVAILABLE = 3, ///< list metrics that are available ENABLE_TIME_MARKER_BIT_MASK = 4, ///< bit mask of time markers to enable - SET_PROPERTIES = 5, ///< set property - DUMP_SCENE_GRAPH = 6, ///< dump the scene graph - UNKNOWN_COMMAND = 4096 + SET_PROPERTIES = 5, ///< set property + DUMP_SCENE_GRAPH = 6, ///< dump the scene graph + UNKNOWN_COMMAND = 4096 }; - -typedef char CommandString[ MAX_COMMAND_STRING_LENGTH ]; +typedef char CommandString[MAX_COMMAND_STRING_LENGTH]; /** * @brief given a command id, get the command string @@ -53,7 +50,7 @@ typedef char CommandString[ MAX_COMMAND_STRING_LENGTH ]; * @param[out] commandString command string * @return true on success, false on failure */ -bool GetCommandString( CommandId commandId, CommandString& commandString ); +bool GetCommandString(CommandId commandId, CommandString& commandString); /** * @brief given a command string, get the command id and an integer parameter if it exists @@ -64,11 +61,11 @@ bool GetCommandString( CommandId commandId, CommandString& commandString ); * @param[out] stringParam string parameter * @param true on success, false on failure */ -bool GetCommandId( const char* const commandString, - unsigned int lengthInBytes, - CommandId& commandId, - unsigned int& intParam, - std::string& stringParam); +bool GetCommandId(const char* const commandString, + unsigned int lengthInBytes, + CommandId& commandId, + unsigned int& intParam, + std::string& stringParam); /** * @return the protocol help message for console users diff --git a/dali/internal/network/common/network-performance-server.cpp b/dali/internal/network/common/network-performance-server.cpp index 1f048d0..804ad6a 100644 --- a/dali/internal/network/common/network-performance-server.cpp +++ b/dali/internal/network/common/network-performance-server.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,26 +18,22 @@ // CLASS HEADER #include - // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // un-named namespace { -const unsigned int SERVER_PORT = 3031; -const unsigned int MAXIMUM_PORTS_TO_TRY = 10; ///< if port in use, try up to SERVER_PORT + 10 -const unsigned int CONNECTION_BACKLOG = 2; ///< maximum length of the queue of pending connections. -const unsigned int SOCKET_READ_BUFFER_SIZE = 4096; -typedef Vector< NetworkPerformanceClient*> ClientList; +const unsigned int SERVER_PORT = 3031; +const unsigned int MAXIMUM_PORTS_TO_TRY = 10; ///< if port in use, try up to SERVER_PORT + 10 +const unsigned int CONNECTION_BACKLOG = 2; ///< maximum length of the queue of pending connections. +const unsigned int SOCKET_READ_BUFFER_SIZE = 4096; +typedef Vector ClientList; /** * POD passed to client thread on startup @@ -47,17 +43,17 @@ struct ClientThreadInfo NetworkPerformanceServer* server; NetworkPerformanceClient* client; }; -} - -NetworkPerformanceServer::NetworkPerformanceServer( AdaptorInternalServices& adaptorServices, - const EnvironmentOptions& logOptions ) -: mSocketFactory( adaptorServices.GetSocketFactoryInterface() ), - mLogOptions( logOptions ), - mServerThread( 0 ), - mListeningSocket( NULL ), - mClientUniqueId( 0 ), - mClientCount( 0 ), - mLogFunctionInstalled( false ) +} // namespace + +NetworkPerformanceServer::NetworkPerformanceServer(AdaptorInternalServices& adaptorServices, + const EnvironmentOptions& logOptions) +: mSocketFactory(adaptorServices.GetSocketFactoryInterface()), + mLogOptions(logOptions), + mServerThread(0), + mListeningSocket(NULL), + mClientUniqueId(0), + mClientCount(0), + mLogFunctionInstalled(false) { } @@ -65,7 +61,7 @@ NetworkPerformanceServer::~NetworkPerformanceServer() { Stop(); - if( mLogFunctionInstalled ) + if(mLogFunctionInstalled) { mLogOptions.UnInstallLogFunction(); } @@ -74,52 +70,51 @@ NetworkPerformanceServer::~NetworkPerformanceServer() void NetworkPerformanceServer::Start() { // start a thread to listen for incoming connection requests - if (! mServerThread ) + if(!mServerThread) { - if( mListeningSocket ) + if(mListeningSocket) { - mSocketFactory.DestroySocket( mListeningSocket ); + mSocketFactory.DestroySocket(mListeningSocket); } - mListeningSocket = mSocketFactory.NewSocket( SocketInterface::TCP); - mListeningSocket->ReuseAddress( true ); + mListeningSocket = mSocketFactory.NewSocket(SocketInterface::TCP); + mListeningSocket->ReuseAddress(true); - bool bound = false; + bool bound = false; unsigned int basePort = 0; // try a small range of ports, so if multiple Dali apps are running you can select // which one to connect to - while( !bound && ( basePort < MAXIMUM_PORTS_TO_TRY )) + while(!bound && (basePort < MAXIMUM_PORTS_TO_TRY)) { - bound = mListeningSocket->Bind( SERVER_PORT + basePort ); - if( !bound ) + bound = mListeningSocket->Bind(SERVER_PORT + basePort); + if(!bound) { basePort++; } } - if(!bound ) + if(!bound) { DALI_LOG_ERROR("Failed to bind to a port \n"); return; } - mListeningSocket->Listen( CONNECTION_BACKLOG ); + mListeningSocket->Listen(CONNECTION_BACKLOG); // start a thread which will block waiting for new connections - int error = pthread_create( &mServerThread, NULL, ConnectionListenerFunc, this ); - DALI_ASSERT_ALWAYS( !error && "pthread create failed" ); - - Dali::Integration::Log::LogMessage(Integration::Log::DebugInfo, "~~~ NetworkPerformanceServer started on port %d ~~~ \n", SERVER_PORT + basePort); + int error = pthread_create(&mServerThread, NULL, ConnectionListenerFunc, this); + DALI_ASSERT_ALWAYS(!error && "pthread create failed"); + Dali::Integration::Log::LogMessage(Integration::Log::DebugInfo, "~~~ NetworkPerformanceServer started on port %d ~~~ \n", SERVER_PORT + basePort); } } void NetworkPerformanceServer::Stop() { - if( !mServerThread ) + if(!mServerThread) { return; } - if( mListeningSocket ) + if(mListeningSocket) { // close the server thread to prevent any new connections mListeningSocket->ExitSelect(); @@ -127,62 +122,61 @@ void NetworkPerformanceServer::Stop() // wait for the thread to exit. void* exitValue; - pthread_join( mServerThread, &exitValue ); + pthread_join(mServerThread, &exitValue); - if( mListeningSocket ) + if(mListeningSocket) { // close the socket mListeningSocket->CloseSocket(); } - mSocketFactory.DestroySocket( mListeningSocket ); + mSocketFactory.DestroySocket(mListeningSocket); mListeningSocket = NULL; // this will tell all client threads to quit StopClients(); - } bool NetworkPerformanceServer::IsRunning() const { - if (mServerThread ) + if(mServerThread) { return true; } return false; } -void NetworkPerformanceServer::ClientThread( NetworkPerformanceClient* client ) +void NetworkPerformanceServer::ClientThread(NetworkPerformanceClient* client) { mClientCount++; - SocketInterface& socket( client->GetSocket() ); + SocketInterface& socket(client->GetSocket()); - for( ;; ) + for(;;) { SocketInterface::SelectReturn ret = socket.Select(); - if( ret == SocketInterface::DATA_AVAILABLE ) + if(ret == SocketInterface::DATA_AVAILABLE) { - // Read - char buffer[ SOCKET_READ_BUFFER_SIZE ]; - unsigned int bytesRead; + // Read + char buffer[SOCKET_READ_BUFFER_SIZE]; + unsigned int bytesRead; - bool ok = socket.Read( buffer, sizeof( buffer ) , bytesRead); - if( ok && ( bytesRead > 0) ) + bool ok = socket.Read(buffer, sizeof(buffer), bytesRead); + if(ok && (bytesRead > 0)) { - client->ProcessCommand( buffer, bytesRead ); + client->ProcessCommand(buffer, bytesRead); } - else // if bytesRead == 0, then client closed connection, if ok == false then an error + else // if bytesRead == 0, then client closed connection, if ok == false then an error { - DeleteClient( client ); + DeleteClient(client); return; } } else // ret == QUIT or ERROR { - DeleteClient( client); + DeleteClient(client); return; } } @@ -191,35 +185,34 @@ void NetworkPerformanceServer::ClientThread( NetworkPerformanceClient* client ) void NetworkPerformanceServer::ConnectionListener() { // install Dali logging function for this thread - if( !mLogFunctionInstalled ) + if(!mLogFunctionInstalled) { mLogOptions.InstallLogFunction(); mLogFunctionInstalled = true; } - for( ;; ) + for(;;) { // this will block, waiting for a client to connect // or for mListeningSocket->ExitSelect() to be called SocketInterface::SelectReturn ret = mListeningSocket->Select(); - if( ret == SocketInterface::DATA_AVAILABLE ) + if(ret == SocketInterface::DATA_AVAILABLE) { SocketInterface* clientSocket = mListeningSocket->Accept(); // new connection made, spawn a thread to handle it pthread_t* clientThread = new pthread_t(); - NetworkPerformanceClient* client = AddClient( clientSocket, clientThread ); + NetworkPerformanceClient* client = AddClient(clientSocket, clientThread); ClientThreadInfo* info = new ClientThreadInfo; - info->client = client; - info->server = this; - - int error = pthread_create( clientThread, NULL, ClientThreadFunc, info ); - DALI_ASSERT_ALWAYS( !error && "pthread create failed" ); + info->client = client; + info->server = this; + int error = pthread_create(clientThread, NULL, ClientThreadFunc, info); + DALI_ASSERT_ALWAYS(!error && "pthread create failed"); } else // ret == SocketInterface::QUIT or SocketInterface::ERROR { @@ -228,42 +221,42 @@ void NetworkPerformanceServer::ConnectionListener() } } -void* NetworkPerformanceServer::ClientThreadFunc( void* data ) +void* NetworkPerformanceServer::ClientThreadFunc(void* data) { - ClientThreadInfo* info = static_cast( data ); - info->server->ClientThread( info->client ); + ClientThreadInfo* info = static_cast(data); + info->server->ClientThread(info->client); delete info; return NULL; } -NetworkPerformanceClient* NetworkPerformanceServer::AddClient( SocketInterface* clientSocket, pthread_t* clientThread ) +NetworkPerformanceClient* NetworkPerformanceServer::AddClient(SocketInterface* clientSocket, pthread_t* clientThread) { // This function is only called from the listening thread - NetworkPerformanceClient* client= new NetworkPerformanceClient( clientThread, + NetworkPerformanceClient* client = new NetworkPerformanceClient(clientThread, clientSocket, mClientUniqueId++, *this, mSocketFactory); // protect the mClients list which can be accessed from multiple threads. - Mutex::ScopedLock lock( mClientListMutex ); + Mutex::ScopedLock lock(mClientListMutex); - mClients.PushBack( client ); + mClients.PushBack(client); return client; } -void NetworkPerformanceServer::DeleteClient( NetworkPerformanceClient* client ) +void NetworkPerformanceServer::DeleteClient(NetworkPerformanceClient* client) { // protect the mClients list while modifying - Mutex::ScopedLock lock( mClientListMutex ); + Mutex::ScopedLock lock(mClientListMutex); // remove from the list, and delete it - for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter ) + for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter) { - if( (*iter) == client ) + if((*iter) == client) { - mClients.Erase( iter ); + mClients.Erase(iter); delete client; // if there server is shutting down, it waits for client count to hit zero @@ -274,50 +267,49 @@ void NetworkPerformanceServer::DeleteClient( NetworkPerformanceClient* client ) } } -void NetworkPerformanceServer::SendData( const char* const data, unsigned int bufferSizeInBytes,unsigned int clientId ) +void NetworkPerformanceServer::SendData(const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId) { - if( ! mClientCount ) + if(!mClientCount) { return; } // prevent clients been added / deleted while transmiting data - Mutex::ScopedLock lock( mClientListMutex ); + Mutex::ScopedLock lock(mClientListMutex); - for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter ) + for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter) { NetworkPerformanceClient* client = (*iter); - if( client->GetId() == clientId ) + if(client->GetId() == clientId) { - client->WriteSocket(data ,bufferSizeInBytes); + client->WriteSocket(data, bufferSizeInBytes); return; } } } -void NetworkPerformanceServer::TransmitMarker( const PerformanceMarker& marker, const char* const description ) +void NetworkPerformanceServer::TransmitMarker(const PerformanceMarker& marker, const char* const description) { - if( ! IsRunning() ) + if(!IsRunning()) { return; } // prevent clients been added / deleted while transmiting data - Mutex::ScopedLock lock( mClientListMutex ); + Mutex::ScopedLock lock(mClientListMutex); - for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter ) + for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter) { NetworkPerformanceClient* client = (*iter); - client->TransmitMarker( marker, description ); + client->TransmitMarker(marker, description); } } - void NetworkPerformanceServer::StopClients() { // prevent clients been added / deleted while stopping all clients - Mutex::ScopedLock lock( mClientListMutex ); + Mutex::ScopedLock lock(mClientListMutex); - for( ClientList::Iterator iter = mClients.Begin(); iter != mClients.End() ; ++iter ) + for(ClientList::Iterator iter = mClients.Begin(); iter != mClients.End(); ++iter) { NetworkPerformanceClient* client = (*iter); // stop the client from waiting for new commands, and exit from it's thread @@ -325,8 +317,8 @@ void NetworkPerformanceServer::StopClients() } } -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali diff --git a/dali/internal/network/common/network-performance-server.h b/dali/internal/network/common/network-performance-server.h index 301d395..2896f90 100644 --- a/dali/internal/network/common/network-performance-server.h +++ b/dali/internal/network/common/network-performance-server.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,24 +19,21 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - class SocketInterface; class PerformanceMarker; @@ -60,16 +57,13 @@ class PerformanceMarker; */ class NetworkPerformanceServer : public ClientSendDataInterface { - public: - /** * @brief Constructor * @param[in] adaptorServices adaptor internal services * @param[in] logOptions log options */ - NetworkPerformanceServer( AdaptorInternalServices& adaptorServices, const EnvironmentOptions& logOptions ); - + NetworkPerformanceServer(AdaptorInternalServices& adaptorServices, const EnvironmentOptions& logOptions); /** * @brief Start the server, to be called form Dali main thread @@ -95,29 +89,27 @@ public: * @pre Can be called from any thread * */ - void TransmitMarker( const PerformanceMarker& marker, const char* const description ); + void TransmitMarker(const PerformanceMarker& marker, const char* const description); /** * Destructor */ - ~NetworkPerformanceServer(); - -protected: // ClientSendDataInterface + ~NetworkPerformanceServer(); +protected: // ClientSendDataInterface /** * @copydoc ClientSendDataInterface::ClientSendDataInterface() */ - void SendData( const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId ) override; + void SendData(const char* const data, unsigned int bufferSizeInBytes, unsigned int clientId) override; private: - /** * Helper for the thread calling the entry function. * @param[in] This A pointer to the current RenderThread object */ - static void* ConnectionListenerFunc( void* This ) + static void* ConnectionListenerFunc(void* This) { - ( static_cast( This ) )->ConnectionListener(); + (static_cast(This))->ConnectionListener(); return NULL; } @@ -125,13 +117,13 @@ private: * Helper for the thread calling the entry function. * @param[in] This A pointer to the current RenderThread object */ - static void* ClientThreadFunc( void* data ); + static void* ClientThreadFunc(void* data); /** * @brief Client thread function * @param client network client object */ - void ClientThread( NetworkPerformanceClient* client ); + void ClientThread(NetworkPerformanceClient* client); /** * @brief Stop all client threads @@ -149,34 +141,32 @@ private: * @param clientThread client thread * @return client */ - NetworkPerformanceClient* AddClient( SocketInterface* clientSocket, pthread_t* clientThread ); + NetworkPerformanceClient* AddClient(SocketInterface* clientSocket, pthread_t* clientThread); /** * @brief Delete a client from the client list * @param client network client */ - void DeleteClient( NetworkPerformanceClient* client ); - - NetworkPerformanceServer( const NetworkPerformanceServer& ); ///< undefined copy constructor - NetworkPerformanceServer& operator=( const NetworkPerformanceServer& ); ///< undefined assignment operator - - SocketFactoryInterface& mSocketFactory; ///< used to create sockets - const EnvironmentOptions& mLogOptions; ///< log options - Dali::Vector< NetworkPerformanceClient* > mClients; ///< list of connected clients - pthread_t mServerThread; ///< thread that listens for new connections - SocketInterface* mListeningSocket; ///< socket used to listen for new connections - Dali::Mutex mClientListMutex; ///< mutex - unsigned int mClientUniqueId; ///< increments for every client connection - volatile unsigned int mClientCount; ///< client count - bool mLogFunctionInstalled; ///< whether the log function is installed - + void DeleteClient(NetworkPerformanceClient* client); + + NetworkPerformanceServer(const NetworkPerformanceServer&); ///< undefined copy constructor + NetworkPerformanceServer& operator=(const NetworkPerformanceServer&); ///< undefined assignment operator + + SocketFactoryInterface& mSocketFactory; ///< used to create sockets + const EnvironmentOptions& mLogOptions; ///< log options + Dali::Vector mClients; ///< list of connected clients + pthread_t mServerThread; ///< thread that listens for new connections + SocketInterface* mListeningSocket; ///< socket used to listen for new connections + Dali::Mutex mClientListMutex; ///< mutex + unsigned int mClientUniqueId; ///< increments for every client connection + volatile unsigned int mClientCount; ///< client count + bool mLogFunctionInstalled; ///< whether the log function is installed }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif //DALI_INTERNAL_ADAPTOR_NETWORK_PERFORMANCE_SERVER_H diff --git a/dali/internal/network/common/socket-factory-interface.h b/dali/internal/network/common/socket-factory-interface.h index 4819e94..2a92763 100644 --- a/dali/internal/network/common/socket-factory-interface.h +++ b/dali/internal/network/common/socket-factory-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,33 +26,30 @@ namespace Internal { namespace Adaptor { - /** * @brief abstract class to create and destroy sockets */ class SocketFactoryInterface { public: - /** * @brief Create a new socket * @param protocol network protocol * @return true on success, false on failure */ - virtual SocketInterface* NewSocket( SocketInterface::Protocol protocol ) = 0; + virtual SocketInterface* NewSocket(SocketInterface::Protocol protocol) = 0; - /** + /** * @brief destroy a socket * @param[in] socket socket to destroy */ - virtual void DestroySocket( SocketInterface* socket ) = 0; + virtual void DestroySocket(SocketInterface* socket) = 0; protected: - /** * @brief Constructor */ - SocketFactoryInterface( ) + SocketFactoryInterface() { } @@ -64,19 +61,15 @@ protected: } private: - // Undefined copy constructor. - SocketFactoryInterface( const SocketFactoryInterface& ); + SocketFactoryInterface(const SocketFactoryInterface&); // Undefined assignment operator. - SocketFactoryInterface& operator=( const SocketFactoryInterface& ); - + SocketFactoryInterface& operator=(const SocketFactoryInterface&); }; - - -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_BASE_SOCKET_FACTORY_INTERFACE_H diff --git a/dali/internal/network/common/socket-factory.cpp b/dali/internal/network/common/socket-factory.cpp index f35ce2c..fb57fe9 100644 --- a/dali/internal/network/common/socket-factory.cpp +++ b/dali/internal/network/common/socket-factory.cpp @@ -22,26 +22,23 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -SocketInterface* SocketFactory::NewSocket( SocketInterface::Protocol protocol ) +SocketInterface* SocketFactory::NewSocket(SocketInterface::Protocol protocol) { - return new Socket( protocol ); + return new Socket(protocol); } -void SocketFactory::DestroySocket( SocketInterface* socketInterface ) +void SocketFactory::DestroySocket(SocketInterface* socketInterface) { - Socket* socket( static_cast( socketInterface )); + Socket* socket(static_cast(socketInterface)); delete socket; } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/network/common/socket-factory.h b/dali/internal/network/common/socket-factory.h index d202ea7..a243ffd 100644 --- a/dali/internal/network/common/socket-factory.h +++ b/dali/internal/network/common/socket-factory.h @@ -1,7 +1,7 @@ #ifndef DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H #define DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,25 +21,20 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief concrete implementation of the socket factory interface */ class SocketFactory : public SocketFactoryInterface { public: - - /** * @brief Constructor */ - SocketFactory( ) + SocketFactory() { } @@ -53,19 +48,18 @@ public: /** * @copydoc SocketFactoryInterface::NewSocket() */ - SocketInterface* NewSocket( SocketInterface::Protocol protocol ) override; + SocketInterface* NewSocket(SocketInterface::Protocol protocol) override; /** * @copydoc SocketFactoryInterface::DestroySocket() */ - void DestroySocket( SocketInterface* socket ) override; - + void DestroySocket(SocketInterface* socket) override; }; -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_SOCKET_FACTORY_H diff --git a/dali/internal/network/common/socket-impl.cpp b/dali/internal/network/common/socket-impl.cpp index f2d94eb..a6d1bfa 100644 --- a/dali/internal/network/common/socket-impl.cpp +++ b/dali/internal/network/common/socket-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,13 @@ #include // EXTERNAL INCLUDES +#include +#include +#include #include -#include #include -#include -#include +#include #include -#include // Sockets enums like INADDR_ANY use C-Casts #pragma GCC diagnostic push @@ -37,34 +37,33 @@ namespace Internal { namespace Adaptor { - namespace { -const unsigned int MAX_SOCKET_DATA_WRITE_SIZE = 1024 * 1024 * 10 ; // limit maximum size to write to 10 MB +const unsigned int MAX_SOCKET_DATA_WRITE_SIZE = 1024 * 1024 * 10; // limit maximum size to write to 10 MB } -Socket::Socket( Protocol protocol , int fileDescriptor ) -:mSocketFileDescriptor( fileDescriptor ), - mBound(false), - mListening(false), - mQuitPipeCreated(false), - mBlocked(false) +Socket::Socket(Protocol protocol, int fileDescriptor) +: mSocketFileDescriptor(fileDescriptor), + mBound(false), + mListening(false), + mQuitPipeCreated(false), + mBlocked(false) { - int addressFamily( AF_INET ); - int netProtocol( IPPROTO_TCP ); - int type( SOCK_STREAM ); // for TCP + int addressFamily(AF_INET); + int netProtocol(IPPROTO_TCP); + int type(SOCK_STREAM); // for TCP - if( protocol == UDP ) + if(protocol == UDP) { - type = SOCK_DGRAM; + type = SOCK_DGRAM; netProtocol = IPPROTO_UDP; } - if( mSocketFileDescriptor == -1) + if(mSocketFileDescriptor == -1) { - mSocketFileDescriptor = socket( addressFamily,type, netProtocol); - if( mSocketFileDescriptor == -1 ) + mSocketFileDescriptor = socket(addressFamily, type, netProtocol); + if(mSocketFileDescriptor == -1) { - DALI_LOG_ERROR( "Unable to create socket\n" ); + DALI_LOG_ERROR("Unable to create socket\n"); } } else @@ -76,7 +75,7 @@ Socket::Socket( Protocol protocol , int fileDescriptor ) Socket::~Socket() { - if( SocketIsOpen() ) + if(SocketIsOpen()) { CloseSocket(); } @@ -89,19 +88,18 @@ bool Socket::SocketIsOpen() const bool Socket::CloseSocket() { - - if( ! SocketIsOpen() ) + if(!SocketIsOpen()) { DALI_LOG_ERROR("Socket already closed or is invalid \n"); return false; } - int ret = close( mSocketFileDescriptor ); + int ret = close(mSocketFileDescriptor); mSocketFileDescriptor = -1; - mListening = false; - mBound = false; + mListening = false; + mBound = false; - if( ret == -1 ) + if(ret == -1) { DALI_LOG_ERROR("Socket close failed\n"); return false; @@ -109,28 +107,28 @@ bool Socket::CloseSocket() return true; } -bool Socket::Bind( uint16_t port ) +bool Socket::Bind(uint16_t port) { - if( ! SocketIsOpen() || mBound ) + if(!SocketIsOpen() || mBound) { - DALI_LOG_ERROR("Socket is invalid, or already bound\n"); - return false; + DALI_LOG_ERROR("Socket is invalid, or already bound\n"); + return false; } struct sockaddr_in serverAddress; - memset( &serverAddress, 0, sizeof(serverAddress) ); - serverAddress.sin_family = AF_INET; // internet - serverAddress.sin_port = htons( port ); // host-to-net short (16-bit) translation - serverAddress.sin_addr.s_addr = htonl( INADDR_ANY ); // binds the socket to all available interfaces + memset(&serverAddress, 0, sizeof(serverAddress)); + serverAddress.sin_family = AF_INET; // internet + serverAddress.sin_port = htons(port); // host-to-net short (16-bit) translation + serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); // binds the socket to all available interfaces - int ret = bind( mSocketFileDescriptor, - reinterpret_cast< struct sockaddr* >( &serverAddress ), - sizeof(serverAddress)); + int ret = bind(mSocketFileDescriptor, + reinterpret_cast(&serverAddress), + sizeof(serverAddress)); - if( ret == -1 ) + if(ret == -1) { char buf[512]; - DALI_LOG_ERROR( "bind failed for port %d %s \n", port, strerror_r( errno, buf, 512 ) ); + DALI_LOG_ERROR("bind failed for port %d %s \n", port, strerror_r(errno, buf, 512)); return false; } @@ -139,16 +137,16 @@ bool Socket::Bind( uint16_t port ) return true; } -bool Socket::Listen( int blacklog) +bool Socket::Listen(int blacklog) { - if( ! mBound || mListening ) + if(!mBound || mListening) { DALI_LOG_ERROR("socket is not bound, or already opened for listening\n"); return false; } - int ret = listen( mSocketFileDescriptor, blacklog); + int ret = listen(mSocketFileDescriptor, blacklog); - if( ret == -1 ) + if(ret == -1) { DALI_LOG_ERROR("Listen failed\n"); return false; @@ -161,7 +159,7 @@ bool Socket::Listen( int blacklog) SocketInterface* Socket::Accept() const { - if( !mListening ) + if(!mListening) { DALI_LOG_ERROR("socket is not being listened to\n"); return NULL; @@ -171,27 +169,27 @@ SocketInterface* Socket::Accept() const socklen_t addressLength(sizeof(sockaddr_in)); - int clientFileDescriptor = accept( mSocketFileDescriptor, &clientAddress, &addressLength); - if( clientFileDescriptor == -1 ) + int clientFileDescriptor = accept(mSocketFileDescriptor, &clientAddress, &addressLength); + if(clientFileDescriptor == -1) { - DALI_LOG_ERROR("Accept failed\n"); - return NULL; + DALI_LOG_ERROR("Accept failed\n"); + return NULL; } // create a new socket, only TCP supports connections - Socket* client = new Socket( TCP, clientFileDescriptor ); + Socket* client = new Socket(TCP, clientFileDescriptor); return client; } bool Socket::CreateQuitPipe() { - if( !mQuitPipeCreated ) + if(!mQuitPipeCreated) { // create a pipe file descriptor to be able to break from the Select statement // - int ret = pipe( mQuitPipe ); - if( ret != 0) + int ret = pipe(mQuitPipe); + if(ret != 0) { DALI_LOG_ERROR("Pipe creation failed\n"); return false; @@ -202,47 +200,47 @@ bool Socket::CreateQuitPipe() } void Socket::DeleteQuitPipe() { - if( mQuitPipeCreated ) + if(mQuitPipeCreated) { - close( mQuitPipe[0] ); - close( mQuitPipe[1] ); + close(mQuitPipe[0]); + close(mQuitPipe[1]); } } SocketInterface::SelectReturn Socket::Select() { bool ok = CreateQuitPipe(); - if( !ok ) + if(!ok) { return ERROR; } - fd_set readFileDescriptors, exceptFileDescriptors; + fd_set readFileDescriptors, exceptFileDescriptors; FD_ZERO(&readFileDescriptors); FD_ZERO(&exceptFileDescriptors); - FD_SET(mSocketFileDescriptor,&readFileDescriptors ); - FD_SET(mQuitPipe[0],&readFileDescriptors ); + FD_SET(mSocketFileDescriptor, &readFileDescriptors); + FD_SET(mQuitPipe[0], &readFileDescriptors); - FD_SET(mSocketFileDescriptor,&exceptFileDescriptors); + FD_SET(mSocketFileDescriptor, &exceptFileDescriptors); - unsigned int maxFd = mQuitPipe[0] > mSocketFileDescriptor ? mQuitPipe[0]: mSocketFileDescriptor; + unsigned int maxFd = mQuitPipe[0] > mSocketFileDescriptor ? mQuitPipe[0] : mSocketFileDescriptor; - for( ;; ) + for(;;) { // this will block waiting for file descriptors - int ret = select( maxFd+1, &readFileDescriptors, NULL, &exceptFileDescriptors, NULL ); - if( ret == -1 ) + int ret = select(maxFd + 1, &readFileDescriptors, NULL, &exceptFileDescriptors, NULL); + if(ret == -1) { DALI_LOG_ERROR("select failed\n"); return ERROR; } - else if ( FD_ISSET( mQuitPipe[0] , &readFileDescriptors )) + else if(FD_ISSET(mQuitPipe[0], &readFileDescriptors)) { // ExitSelect() called return QUIT; } - else if ( FD_ISSET( mSocketFileDescriptor, &readFileDescriptors )) + else if(FD_ISSET(mSocketFileDescriptor, &readFileDescriptors)) { // socket data received return DATA_AVAILABLE; @@ -253,12 +251,12 @@ SocketInterface::SelectReturn Socket::Select() void Socket::ExitSelect() { - if( mQuitPipeCreated ) + if(mQuitPipeCreated) { // write a single character to the pipe (can be anything) - char c = ' '; - int ret = write( mQuitPipe[1], &c, 1); - if( ret < 1 ) + char c = ' '; + int ret = write(mQuitPipe[1], &c, 1); + if(ret < 1) { DALI_LOG_ERROR("ExitSelect failed!\n"); } @@ -266,9 +264,9 @@ void Socket::ExitSelect() } } -bool Socket::ReuseAddress( bool reUse ) +bool Socket::ReuseAddress(bool reUse) { - if( ! SocketIsOpen() | mBound ) + if(!SocketIsOpen() | mBound) { DALI_LOG_ERROR("Socket is invalid or already bound \n"); return false; @@ -276,31 +274,31 @@ bool Socket::ReuseAddress( bool reUse ) int reUseInteger = reUse; // convert it to an int - int ret = setsockopt( mSocketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &reUseInteger, sizeof(reUseInteger)); - if( ret == -1 ) + int ret = setsockopt(mSocketFileDescriptor, SOL_SOCKET, SO_REUSEADDR, &reUseInteger, sizeof(reUseInteger)); + if(ret == -1) { char buf[512]; - DALI_LOG_ERROR( "SO_REUSEADDR option failed %s \n", strerror_r( errno, buf, 512 ) ); + DALI_LOG_ERROR("SO_REUSEADDR option failed %s \n", strerror_r(errno, buf, 512)); return false; } return true; } -bool Socket::SetBufferSize( SocketInterface::BufferType type, unsigned int size ) +bool Socket::SetBufferSize(SocketInterface::BufferType type, unsigned int size) { - if( ! SocketIsOpen() || mBound ) + if(!SocketIsOpen() || mBound) { DALI_LOG_ERROR("Socket is invalid or already bound \n"); return false; } int option = SO_RCVBUF; - if( type == SocketInterface::SEND_BUFFER ) + if(type == SocketInterface::SEND_BUFFER) { option = SO_SNDBUF; } - int ret = setsockopt( mSocketFileDescriptor, SOL_SOCKET,option,&size,sizeof(size)); - if( ret == -1 ) + int ret = setsockopt(mSocketFileDescriptor, SOL_SOCKET, option, &size, sizeof(size)); + if(ret == -1) { DALI_LOG_ERROR("SO_RCVBUF / SO_SNDBUF option failed \n"); return false; @@ -308,31 +306,31 @@ bool Socket::SetBufferSize( SocketInterface::BufferType type, unsigned int size return true; } -bool Socket::Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead ) +bool Socket::Read(void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead) { bytesRead = 0; - if( !SocketIsOpen() ) + if(!SocketIsOpen()) { DALI_LOG_ERROR("Socket is invalid \n"); return false; } - bytesRead = read( mSocketFileDescriptor, buffer, bufferSizeInBytes ); + bytesRead = read(mSocketFileDescriptor, buffer, bufferSizeInBytes); return true; } -bool Socket::Write( const void* buffer, unsigned int bufferSizeInBytes ) +bool Socket::Write(const void* buffer, unsigned int bufferSizeInBytes) { - if( !SocketIsOpen() ) + if(!SocketIsOpen()) { DALI_LOG_ERROR("Socket is invalid \n"); return false; } // check we don't try to write more than 10MB ( this can be increased if required) - if( bufferSizeInBytes > MAX_SOCKET_DATA_WRITE_SIZE ) + if(bufferSizeInBytes > MAX_SOCKET_DATA_WRITE_SIZE) { DALI_LOG_ERROR("Writing %d bytes exceeds MAX_SOCKET_DATA_WRITE_SIZE of %d bytes \n", bufferSizeInBytes, MAX_SOCKET_DATA_WRITE_SIZE); return false; @@ -342,13 +340,13 @@ bool Socket::Write( const void* buffer, unsigned int bufferSizeInBytes ) // write isn't guaranteed to write the entire buffer in one go - while( bytesWritten != static_cast< int>(bufferSizeInBytes)) + while(bytesWritten != static_cast(bufferSizeInBytes)) { - const char* byteBuffer = static_cast( buffer ); - byteBuffer+=bytesWritten; + const char* byteBuffer = static_cast(buffer); + byteBuffer += bytesWritten; - int ret = write( mSocketFileDescriptor, byteBuffer, bufferSizeInBytes - bytesWritten ); - if( ret < 1) + int ret = write(mSocketFileDescriptor, byteBuffer, bufferSizeInBytes - bytesWritten); + if(ret < 1) { DALI_LOG_ERROR("Socket writer error \n"); return false; @@ -361,10 +359,10 @@ bool Socket::Write( const void* buffer, unsigned int bufferSizeInBytes ) return true; } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali #pragma GCC diagnostic pop diff --git a/dali/internal/network/common/socket-impl.h b/dali/internal/network/common/socket-impl.h index be017e9..2724899 100644 --- a/dali/internal/network/common/socket-impl.h +++ b/dali/internal/network/common/socket-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Concrete implementation of a socket under Linux. * @@ -37,13 +34,12 @@ namespace Adaptor class Socket : public SocketInterface { public: - /** * @brief Constructor * @param protocol network protocol * @param fileDescriptor option file descriptor if the socket is already open */ - Socket( Protocol protocol , int fileDescriptor = -1 ); + Socket(Protocol protocol, int fileDescriptor = -1); /** * @copydoc Dali::Internal::Adaptor::SocketIsOpen() @@ -58,22 +54,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::SocketInterface::Bind */ - bool Bind( uint16_t port ) override; + bool Bind(uint16_t port) override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::Listen */ - bool Listen( int blacklog) override; + bool Listen(int blacklog) override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::Accept */ - SocketInterface* Accept() const override; + SocketInterface* Accept() const override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::Select */ - SelectReturn Select( ) override; + SelectReturn Select() override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::ExitSelect @@ -83,23 +79,23 @@ public: /** * @copydoc Dali::Internal::Adaptor::SocketInterface::Recieve */ - bool Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead ) override; + bool Read(void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead) override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::Send */ - bool Write( const void* buffer, unsigned int bufferLength ) override; + bool Write(const void* buffer, unsigned int bufferLength) override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::ReuseAddress */ - bool ReuseAddress( bool reUse ) override; + bool ReuseAddress(bool reUse) override; /** * @copydoc Dali::Internal::Adaptor::SocketInterface::SetBufferSize * */ - bool SetBufferSize( SocketInterface::BufferType type, unsigned int bufferSizeInBytes ) override; + bool SetBufferSize(SocketInterface::BufferType type, unsigned int bufferSizeInBytes) override; /** * @brief Virtual destructor @@ -107,8 +103,6 @@ public: virtual ~Socket(); private: - - /** * @brief Helper to create the quit pipe */ @@ -119,20 +113,18 @@ private: */ void DeleteQuitPipe(); - int mSocketFileDescriptor; ///< file descriptor - int mQuitPipe[2]; ///< Pipe to inform Select to quit. - bool mBound:1; ///< whether the socket is bound - bool mListening:1; ///< whether the socket is being listen to - bool mQuitPipeCreated:1; ///< whether the quit pipe has been created - bool mBlocked:1; ///< whether the socket is blocked waiting for a connection + int mSocketFileDescriptor; ///< file descriptor + int mQuitPipe[2]; ///< Pipe to inform Select to quit. + bool mBound : 1; ///< whether the socket is bound + bool mListening : 1; ///< whether the socket is being listen to + bool mQuitPipeCreated : 1; ///< whether the quit pipe has been created + bool mBlocked : 1; ///< whether the socket is blocked waiting for a connection }; +} // namespace Adaptor +} // namespace Internal -} // Adaptor - -} // Internal - -} // Dali +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_SOCKET_IMPL_H diff --git a/dali/internal/network/common/socket-interface.h b/dali/internal/network/common/socket-interface.h index 6f0dabd..296f16b 100644 --- a/dali/internal/network/common/socket-interface.h +++ b/dali/internal/network/common/socket-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_BASE_SOCKET_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ namespace Internal { namespace Adaptor { - /** * @brief Abstract socket interface. * The typical usage is: @@ -53,14 +52,13 @@ namespace Adaptor class SocketInterface { public: - /** * @brief Protocol type */ enum Protocol { - TCP, ///< Reliable, connection oriented - UDP, ///< Connection less, no guarantees of packet delivery, ordering + TCP, ///< Reliable, connection oriented + UDP, ///< Connection less, no guarantees of packet delivery, ordering }; /** @@ -80,14 +78,14 @@ public: * @param[in] port network port * @return true on success, false on failure */ - virtual bool Bind( uint16_t port ) = 0; + virtual bool Bind(uint16_t port) = 0; /** * @brief Indicate a willingness to accept incoming connection requests * @param[in] backlog maximum length of the queue of pending connections. * @return true on success, false on failure */ - virtual bool Listen( int blacklog) = 0; + virtual bool Listen(int blacklog) = 0; /** * @brief Wait for connection request and make connection @@ -100,9 +98,9 @@ public: */ enum SelectReturn { - DATA_AVAILABLE, ///< Data is available to read - QUIT, ///< ExitSelect() has been called on the socket - ERROR ///< Socket error + DATA_AVAILABLE, ///< Data is available to read + QUIT, ///< ExitSelect() has been called on the socket + ERROR ///< Socket error }; /** @@ -128,7 +126,7 @@ public: * @param[out] bytesRead number of bytes read * @return true on success, false on failure */ - virtual bool Read( void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead ) = 0; + virtual bool Read(void* buffer, unsigned int bufferSizeInBytes, unsigned int& bytesRead) = 0; /** * @brief Send data to the socket @@ -136,7 +134,7 @@ public: * @param[in] bufferSizeInBytes buffer size in write * @return true on success, false on failure */ - virtual bool Write( const void* buffer, unsigned int bufferSizeInBytes ) = 0; + virtual bool Write(const void* buffer, unsigned int bufferSizeInBytes) = 0; // // Common socket options. Please add more as required. @@ -147,15 +145,15 @@ public: * @param[in] reuse flag. * @return true on success, false on failure */ - virtual bool ReuseAddress( bool reUse ) = 0; + virtual bool ReuseAddress(bool reUse) = 0; /** * @brief Socket buffer type */ enum BufferType { - SEND_BUFFER, ///< (SO_SNDBUF) Send buffer size - RECIEVE_BUFFER ///< (SO_RCVBUF) Size of buffer allocated to hold data arriving to the socket + SEND_BUFFER, ///< (SO_SNDBUF) Send buffer size + RECIEVE_BUFFER ///< (SO_RCVBUF) Size of buffer allocated to hold data arriving to the socket }; /** @@ -164,14 +162,13 @@ public: * @param[in] size buffer size * @return true on success, false on failure */ - virtual bool SetBufferSize( BufferType type, unsigned int size ) = 0; + virtual bool SetBufferSize(BufferType type, unsigned int size) = 0; protected: - /** * @brief Constructor */ - SocketInterface( ) + SocketInterface() { } @@ -183,18 +180,15 @@ protected: } private: - // Undefined copy constructor. - SocketInterface( const SocketInterface& ); + SocketInterface(const SocketInterface&); // Undefined assignment operator. - SocketInterface& operator=( const SocketInterface& ); - + SocketInterface& operator=(const SocketInterface&); }; - -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_BASE_SOCKET_INTERFACE_H diff --git a/dali/internal/network/common/trace-interface.h b/dali/internal/network/common/trace-interface.h index 026a29a..c20ed13 100644 --- a/dali/internal/network/common/trace-interface.h +++ b/dali/internal/network/common/trace-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_BASE_TRACE_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,19 +21,15 @@ // EXTERNAL INCLUDES #include - // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Abstract Tracing Interface. * Used to log trace messages. @@ -42,18 +38,15 @@ namespace Adaptor */ class TraceInterface { - public: - /** * Write a trace message * @param marker performance marker * @param traceMessage trace message */ - virtual void Trace( const PerformanceMarker& marker, const std::string& traceMessage ) = 0; + virtual void Trace(const PerformanceMarker& marker, const std::string& traceMessage) = 0; protected: - /** * Constructor */ @@ -69,16 +62,16 @@ protected: } // Undefined copy constructor. - TraceInterface( const TraceInterface& ); + TraceInterface(const TraceInterface&); // Undefined assignment operator. - TraceInterface& operator=( const TraceInterface& ); + TraceInterface& operator=(const TraceInterface&); }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_BASE_TRACE_INTERFACE_H diff --git a/dali/internal/offscreen/common/offscreen-application-impl.cpp b/dali/internal/offscreen/common/offscreen-application-impl.cpp index 396dbc4..634d69f 100644 --- a/dali/internal/offscreen/common/offscreen-application-impl.cpp +++ b/dali/internal/offscreen/common/offscreen-application-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,37 +19,34 @@ #include // INTERNAL INCLUDES -#include -#include -#include #include #include +#include +#include +#include namespace Dali { - namespace Internal { - using RenderMode = Dali::OffscreenApplication::RenderMode; -IntrusivePtr< OffscreenApplication > OffscreenApplication::New( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, RenderMode renderMode ) +IntrusivePtr OffscreenApplication::New(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, RenderMode renderMode) { - IntrusivePtr< OffscreenApplication > offscreenApplication = new OffscreenApplication( width, height, surface, isTranslucent, renderMode ); + IntrusivePtr offscreenApplication = new OffscreenApplication(width, height, surface, isTranslucent, renderMode); return offscreenApplication; } -OffscreenApplication::OffscreenApplication( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, RenderMode renderMode ) +OffscreenApplication::OffscreenApplication(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, RenderMode renderMode) { // Generate a default window - IntrusivePtr< Internal::OffscreenWindow > impl = Internal::OffscreenWindow::New( width, height, surface, isTranslucent ); - mDefaultWindow = Dali::OffscreenWindow( impl.Get() ); + IntrusivePtr impl = Internal::OffscreenWindow::New(width, height, surface, isTranslucent); + mDefaultWindow = Dali::OffscreenWindow(impl.Get()); - mAdaptor.reset( Dali::Internal::Adaptor::Adaptor::New( Dali::Integration::SceneHolder( impl.Get() ), impl->GetSurface(), NULL, - renderMode == RenderMode::AUTO ? Dali::Internal::Adaptor::ThreadMode::NORMAL : Dali::Internal::Adaptor::ThreadMode::RUN_IF_REQUESTED ) ); + mAdaptor.reset(Dali::Internal::Adaptor::Adaptor::New(Dali::Integration::SceneHolder(impl.Get()), impl->GetSurface(), NULL, renderMode == RenderMode::AUTO ? Dali::Internal::Adaptor::ThreadMode::NORMAL : Dali::Internal::Adaptor::ThreadMode::RUN_IF_REQUESTED)); // Initialize default window - impl->Initialize( true ); + impl->Initialize(true); } void OffscreenApplication::Start() @@ -57,7 +54,7 @@ void OffscreenApplication::Start() // Start the adaptor mAdaptor->Start(); - Dali::OffscreenApplication handle( this ); + Dali::OffscreenApplication handle(this); mInitSignal.Emit(); mAdaptor->NotifySceneCreated(); } @@ -67,7 +64,7 @@ void OffscreenApplication::Stop() // Stop the adaptor mAdaptor->Stop(); - Dali::OffscreenApplication handle( this ); + Dali::OffscreenApplication handle(this); mTerminateSignal.Emit(); } diff --git a/dali/internal/offscreen/common/offscreen-application-impl.h b/dali/internal/offscreen/common/offscreen-application-impl.h index 22c5f9e..b9b7c8c 100644 --- a/dali/internal/offscreen/common/offscreen-application-impl.h +++ b/dali/internal/offscreen/common/offscreen-application-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_OFFSCREEN_APPLICATION_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES #include @@ -34,14 +34,12 @@ class Adaptor; namespace Internal { - /** * Implementation of the OffscreenApplication class. */ class OffscreenApplication : public BaseObject { public: - using OffscreenApplicationSignalType = Dali::OffscreenApplication::OffscreenApplicationSignalType; /** @@ -52,10 +50,9 @@ public: * @param[in] isTranslucent Whether the OffscreenWindow is translucent or not * @param[in] renderMode The RenderMode of the OffscreenApplication */ - static IntrusivePtr New( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, Dali::OffscreenApplication::RenderMode renderMode); + static IntrusivePtr New(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, Dali::OffscreenApplication::RenderMode renderMode); public: - /** * Destructor */ @@ -81,8 +78,7 @@ public: */ void RenderOnce(); -public: // Signals - +public: // Signals /** * @copydoc Dali::OffscreenApplication::InitSignal() */ @@ -108,38 +104,38 @@ private: * @param[in] isTranslucent Whether the OffscreenWindow is translucent or not * @param[in] renderMode The RenderMode of the OffscreenApplication */ - OffscreenApplication( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, Dali::OffscreenApplication::RenderMode renderMode ); + OffscreenApplication(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent, Dali::OffscreenApplication::RenderMode renderMode); // Undefined - OffscreenApplication( const OffscreenApplication& ) = delete; - OffscreenApplication& operator=( OffscreenApplication& ) = delete; - OffscreenApplication& operator=( const OffscreenApplication& ) = delete; - OffscreenApplication& operator=( OffscreenApplication&& ) = delete; + OffscreenApplication(const OffscreenApplication&) = delete; + OffscreenApplication& operator=(OffscreenApplication&) = delete; + OffscreenApplication& operator=(const OffscreenApplication&) = delete; + OffscreenApplication& operator=(OffscreenApplication&&) = delete; private: - std::unique_ptr< Dali::Adaptor > mAdaptor; - Dali::OffscreenWindow mDefaultWindow; + std::unique_ptr mAdaptor; + Dali::OffscreenWindow mDefaultWindow; - OffscreenApplicationSignalType mInitSignal; - OffscreenApplicationSignalType mTerminateSignal; + OffscreenApplicationSignalType mInitSignal; + OffscreenApplicationSignalType mTerminateSignal; }; -inline OffscreenApplication& GetImplementation( Dali::OffscreenApplication& offscreenApplication ) +inline OffscreenApplication& GetImplementation(Dali::OffscreenApplication& offscreenApplication) { - DALI_ASSERT_ALWAYS( offscreenApplication && "OffscreenApplication handle is empty" ); + DALI_ASSERT_ALWAYS(offscreenApplication && "OffscreenApplication handle is empty"); BaseObject& handle = offscreenApplication.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } -inline const OffscreenApplication& GetImplementation( const Dali::OffscreenApplication& offscreenApplication ) +inline const OffscreenApplication& GetImplementation(const Dali::OffscreenApplication& offscreenApplication) { - DALI_ASSERT_ALWAYS( offscreenApplication && "OffscreenApplication handle is empty" ); + DALI_ASSERT_ALWAYS(offscreenApplication && "OffscreenApplication handle is empty"); const BaseObject& handle = offscreenApplication.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } } // namespace Internal diff --git a/dali/internal/offscreen/common/offscreen-window-impl.cpp b/dali/internal/offscreen/common/offscreen-window-impl.cpp index ab818ad..ed34e15 100644 --- a/dali/internal/offscreen/common/offscreen-window-impl.cpp +++ b/dali/internal/offscreen/common/offscreen-window-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,40 +23,38 @@ // INTERNAL INCLUDES #include -#include #include +#include #include #include namespace Dali { - namespace Internal { - -OffscreenWindow* OffscreenWindow::New( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent ) +OffscreenWindow* OffscreenWindow::New(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent) { - OffscreenWindow* window = new OffscreenWindow( width, height, surface, isTranslucent ); + OffscreenWindow* window = new OffscreenWindow(width, height, surface, isTranslucent); return window; } -OffscreenWindow::OffscreenWindow( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent ) +OffscreenWindow::OffscreenWindow(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent) : mRenderNotification() { // Create surface - mSurface = std::unique_ptr< RenderSurfaceInterface >( CreateNativeSurface( SurfaceSize( width, height ), surface, isTranslucent ) ); + mSurface = std::unique_ptr(CreateNativeSurface(SurfaceSize(width, height), surface, isTranslucent)); } -void OffscreenWindow::Initialize( bool isDefaultWindow ) +void OffscreenWindow::Initialize(bool isDefaultWindow) { - if( isDefaultWindow ) + if(isDefaultWindow) { Initialize(); return; } - Dali::Integration::SceneHolder sceneHolderHandler = Dali::Integration::SceneHolder( this ); - Dali::Adaptor::Get().AddWindow( sceneHolderHandler ); + Dali::Integration::SceneHolder sceneHolderHandler = Dali::Integration::SceneHolder(this); + Dali::Adaptor::Get().AddWindow(sceneHolderHandler); Initialize(); } @@ -66,26 +64,26 @@ void OffscreenWindow::Initialize() // Connect callback to be notified when the surface is rendered TriggerEventFactory triggerEventFactory; - mRenderNotification = std::unique_ptr< TriggerEventInterface >( triggerEventFactory.CreateTriggerEvent( MakeCallback( this, &OffscreenWindow::OnPostRender ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER ) ); + mRenderNotification = std::unique_ptr(triggerEventFactory.CreateTriggerEvent(MakeCallback(this, &OffscreenWindow::OnPostRender), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER)); NativeRenderSurface* surface = GetNativeRenderSurface(); - if( !surface ) + if(!surface) { return; } - surface->SetRenderNotification( mRenderNotification.get() ); + surface->SetRenderNotification(mRenderNotification.get()); } OffscreenWindow::~OffscreenWindow() { NativeRenderSurface* surface = GetNativeRenderSurface(); - if( surface ) + if(surface) { // To prevent notification triggering in NativeRenderSurface::PostRender while deleting SceneHolder - surface->SetRenderNotification( nullptr ); + surface->SetRenderNotification(nullptr); } } @@ -94,35 +92,35 @@ uint32_t OffscreenWindow::GetLayerCount() const return mScene.GetLayerCount(); } -Dali::Layer OffscreenWindow::GetLayer( uint32_t depth ) const +Dali::Layer OffscreenWindow::GetLayer(uint32_t depth) const { - return mScene.GetLayer( depth ); + return mScene.GetLayer(depth); } OffscreenWindow::WindowSize OffscreenWindow::GetSize() const { Size size = mScene.GetSize(); - return OffscreenWindow::WindowSize( static_cast( size.width ), static_cast( size.height ) ); + return OffscreenWindow::WindowSize(static_cast(size.width), static_cast(size.height)); } Dali::Any OffscreenWindow::GetNativeHandle() const { NativeRenderSurface* surface = GetNativeRenderSurface(); - DALI_ASSERT_ALWAYS( surface && "surface handle is empty" ); + DALI_ASSERT_ALWAYS(surface && "surface handle is empty"); return surface->GetNativeRenderable(); } NativeRenderSurface* OffscreenWindow::GetNativeRenderSurface() const { - return dynamic_cast< NativeRenderSurface* >( mSurface.get() ); + return dynamic_cast(mSurface.get()); } void OffscreenWindow::OnPostRender() { - Dali::OffscreenWindow handle( this ); - mPostRenderSignal.Emit( handle, GetNativeHandle() ); + Dali::OffscreenWindow handle(this); + mPostRenderSignal.Emit(handle, GetNativeHandle()); } OffscreenWindow::PostRenderSignalType& OffscreenWindow::PostRenderSignal() diff --git a/dali/internal/offscreen/common/offscreen-window-impl.h b/dali/internal/offscreen/common/offscreen-window-impl.h index 95a7c55..ee564e9 100644 --- a/dali/internal/offscreen/common/offscreen-window-impl.h +++ b/dali/internal/offscreen/common/offscreen-window-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_OFFSCREEN_WINDOW_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES #include @@ -36,7 +36,6 @@ class TriggerEventInterface; namespace Internal { - /** * Implementation of the OffscreenWindow class. */ @@ -44,7 +43,7 @@ class OffscreenWindow : public Dali::Internal::Adaptor::SceneHolder, public ConnectionTracker { public: - using WindowSize = Dali::OffscreenWindow::WindowSize; + using WindowSize = Dali::OffscreenWindow::WindowSize; using PostRenderSignalType = Dali::OffscreenWindow::PostRenderSignalType; /** @@ -55,12 +54,11 @@ public: * @param[in] surface The native surface handle of your platform * @param[in] isTranslucent Whether the OffscreenWindow is translucent or not */ - static OffscreenWindow* New( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent ); + static OffscreenWindow* New(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent); OffscreenWindow() = default; public: - /** * Destructor */ @@ -74,7 +72,7 @@ public: /** * @copydoc Dali::OffscreenWindow::GetLayer */ - Dali::Layer GetLayer( uint32_t depth ) const; + Dali::Layer GetLayer(uint32_t depth) const; /** * @copydoc Dali::OffscreenWindow::GetSize @@ -90,10 +88,9 @@ public: * @brief Initialize the OffscreenWindow * @param[in] isDefaultWindow Whether the OffscreenWindow is a default one or not */ - void Initialize( bool isDefaultWindow ); - -public: // Signals + void Initialize(bool isDefaultWindow); +public: // Signals /** * @copydoc Dali::OffscreenWindow::PostRenderSignal */ @@ -112,8 +109,7 @@ private: NativeRenderSurface* GetNativeRenderSurface() const; private: - - /** + /** * Private constructor * * @param[in] width The initial width of the OffscreenWindow @@ -121,11 +117,11 @@ private: * @param[in] surface The native surface handle * @param[in] isTranslucent Whether the OffscreenWindow is translucent or not */ - OffscreenWindow( uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent ); + OffscreenWindow(uint16_t width, uint16_t height, Dali::Any surface, bool isTranslucent); // Undefined - OffscreenWindow( const OffscreenWindow& ); - OffscreenWindow& operator=( OffscreenWindow& ); + OffscreenWindow(const OffscreenWindow&); + OffscreenWindow& operator=(OffscreenWindow&); /* * @brief Initialize the OffscreenWindow (for internal use) @@ -133,27 +129,26 @@ private: void Initialize(); private: - - std::unique_ptr< TriggerEventInterface > mRenderNotification; - PostRenderSignalType mPostRenderSignal; + std::unique_ptr mRenderNotification; + PostRenderSignalType mPostRenderSignal; }; -inline OffscreenWindow& GetImplementation( Dali::OffscreenWindow& offscreenWindow ) +inline OffscreenWindow& GetImplementation(Dali::OffscreenWindow& offscreenWindow) { - DALI_ASSERT_ALWAYS( offscreenWindow && "Dali::OffscreenWindow handle is empty" ); + DALI_ASSERT_ALWAYS(offscreenWindow && "Dali::OffscreenWindow handle is empty"); BaseObject& handle = offscreenWindow.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } -inline const OffscreenWindow& GetImplementation( const Dali::OffscreenWindow& offscreenWindow ) +inline const OffscreenWindow& GetImplementation(const Dali::OffscreenWindow& offscreenWindow) { - DALI_ASSERT_ALWAYS( offscreenWindow && "Dali::OffscreenWindow handle is empty" ); + DALI_ASSERT_ALWAYS(offscreenWindow && "Dali::OffscreenWindow handle is empty"); const BaseObject& handle = offscreenWindow.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } } // namespace Internal diff --git a/dali/internal/sensor/common/tilt-sensor-factory.cpp b/dali/internal/sensor/common/tilt-sensor-factory.cpp index f5245b3..f283385 100644 --- a/dali/internal/sensor/common/tilt-sensor-factory.cpp +++ b/dali/internal/sensor/common/tilt-sensor-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,9 +15,9 @@ * */ +#include #include #include -#include namespace Dali { @@ -25,7 +25,6 @@ namespace Internal { namespace Adaptor { - namespace TiltSensorFactory { __attribute__((weak)) Dali::Internal::Adaptor::TiltSensor* Create() @@ -40,14 +39,14 @@ Dali::TiltSensor Get() Dali::SingletonService service(SingletonService::Get()); - if (service) + if(service) { // Check whether the keyboard focus manager is already created Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::TiltSensor)); - if (handle) + if(handle) { // If so, downcast the handle of singleton to keyboard focus manager - sensor = Dali::TiltSensor(dynamic_cast< TiltSensor * >( handle.GetObjectPtr())); + sensor = Dali::TiltSensor(dynamic_cast(handle.GetObjectPtr())); } else { @@ -59,10 +58,10 @@ Dali::TiltSensor Get() } return sensor; } -} +} // namespace TiltSensorFactory -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/sensor/common/tilt-sensor-factory.h b/dali/internal/sensor/common/tilt-sensor-factory.h index fe7ec28..3722035 100644 --- a/dali/internal/sensor/common/tilt-sensor-factory.h +++ b/dali/internal/sensor/common/tilt-sensor-factory.h @@ -2,7 +2,7 @@ #define DALI_SENSOR_COMMON_TILT_SENSOR_FACTORY_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ class TiltSensor; namespace TiltSensorFactory { - /** * Creates new instance of tilt sensor implementation * @return pointer to tilt sensor implementation instance @@ -43,7 +42,7 @@ Dali::Internal::Adaptor::TiltSensor* Create(); */ Dali::TiltSensor Get(); -} // TiltSensorFactory +} // namespace TiltSensorFactory } // namespace Adaptor diff --git a/dali/internal/sensor/common/tilt-sensor-impl.cpp b/dali/internal/sensor/common/tilt-sensor-impl.cpp index 79627be..f3ff87c 100644 --- a/dali/internal/sensor/common/tilt-sensor-impl.cpp +++ b/dali/internal/sensor/common/tilt-sensor-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - TiltSensor::TiltSensor() = default; TiltSensor::~TiltSensor() = default; @@ -37,7 +34,6 @@ bool TiltSensor::Start() void TiltSensor::Stop() { - } bool TiltSensor::IsStarted() const @@ -60,17 +56,14 @@ Quaternion TiltSensor::GetRotation() const return Quaternion::IDENTITY; } - TiltSensor::TiltedSignalType& TiltSensor::TiltedSignal() { static TiltSensor::TiltedSignalType signal; return signal; } - void TiltSensor::SetUpdateFrequency(float frequencyHertz) { - } float TiltSensor::GetUpdateFrequency() const @@ -80,7 +73,6 @@ float TiltSensor::GetUpdateFrequency() const void TiltSensor::SetRotationThreshold(Radian rotationThreshold) { - } /** @@ -100,7 +92,7 @@ Radian TiltSensor::GetRotationThreshold() const * @return True if the signal was connected. * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor. */ -bool TiltSensor::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool TiltSensor::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { return false; } diff --git a/dali/internal/sensor/common/tilt-sensor-impl.h b/dali/internal/sensor/common/tilt-sensor-impl.h index e2473f8..5d234ed 100644 --- a/dali/internal/sensor/common/tilt-sensor-impl.h +++ b/dali/internal/sensor/common/tilt-sensor-impl.h @@ -2,7 +2,7 @@ #define DALI_SENSOR_COMMON_TILT_SENSOR_IMPL_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,26 +22,22 @@ #include // INTERNAL INCLUDES -#include #include +#include #include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * TiltSensor provides pitch & roll values when the device is tilted. */ class TiltSensor : public Dali::BaseObject { public: - /** * Constructor */ @@ -92,7 +88,7 @@ public: /** * @copydoc Dali::TiltSensor::SetUpdateFrequency() */ - virtual void SetUpdateFrequency( float frequencyHertz ); + virtual void SetUpdateFrequency(float frequencyHertz); /** * @copydoc Dali::TiltSensor::GetUpdateFrequency() @@ -118,7 +114,7 @@ public: * @return True if the signal was connected. * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor. */ - static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ); + static bool DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor); }; } // namespace Adaptor @@ -127,7 +123,7 @@ public: inline Internal::Adaptor::TiltSensor& GetImplementation(Dali::TiltSensor& sensor) { - DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" ); + DALI_ASSERT_ALWAYS(sensor && "TiltSensor handle is empty"); BaseObject& handle = sensor.GetBaseObject(); @@ -136,7 +132,7 @@ inline Internal::Adaptor::TiltSensor& GetImplementation(Dali::TiltSensor& sensor inline const Internal::Adaptor::TiltSensor& GetImplementation(const Dali::TiltSensor& sensor) { - DALI_ASSERT_ALWAYS( sensor && "TiltSensor handle is empty" ); + DALI_ASSERT_ALWAYS(sensor && "TiltSensor handle is empty"); const BaseObject& handle = sensor.GetBaseObject(); diff --git a/dali/internal/sensor/tizen/tilt-sensor-factory-tizen.cpp b/dali/internal/sensor/tizen/tilt-sensor-factory-tizen.cpp index 76a1dcd..adff222 100644 --- a/dali/internal/sensor/tizen/tilt-sensor-factory-tizen.cpp +++ b/dali/internal/sensor/tizen/tilt-sensor-factory-tizen.cpp @@ -19,25 +19,21 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TiltSensorFactory { - Dali::Internal::Adaptor::TiltSensor* Create() { return Dali::Internal::Adaptor::TiltSensorTizen::New(); } -} // TiltSensorFactory +} // namespace TiltSensorFactory -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali \ No newline at end of file +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.cpp b/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.cpp index 13d3336..ef0d75d 100644 --- a/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.cpp +++ b/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,22 +16,22 @@ */ // CLASS HEADER -#include #include +#include // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include namespace // unnamed namespace { const char* const SIGNAL_TILTED = "tilted"; -const float MAX_ORIENTATION_ROLL_VALUE = 90.f; +const float MAX_ORIENTATION_ROLL_VALUE = 90.f; const float MAX_ORIENTATION_PITCH_VALUE = 180.f; -const float MAX_ACCELEROMETER_VALUE = 9.8f; +const float MAX_ACCELEROMETER_VALUE = 9.8f; // Type Registration Dali::BaseHandle Create() @@ -39,25 +39,22 @@ Dali::BaseHandle Create() return Dali::Internal::Adaptor::TiltSensorFactory::Get(); } -Dali::TypeRegistration typeRegistration( typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), Create ); +Dali::TypeRegistration typeRegistration(typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), Create); -Dali::SignalConnectorType signalConnector1( typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal ); +Dali::SignalConnectorType signalConnector1(typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal); } // unnamed namespace namespace Dali { - namespace Internal { - namespace Adaptor { - #ifdef SENSOR_ENABLED -static void sensor_changed_cb (sensor_h sensor, sensor_event_s *event, void *user_data) +static void sensor_changed_cb(sensor_h sensor, sensor_event_s* event, void* user_data) { - TiltSensorTizen* tiltSensor = reinterpret_cast< TiltSensorTizen* >( user_data ); + TiltSensorTizen* tiltSensor = reinterpret_cast(user_data); if(tiltSensor) { @@ -119,9 +116,9 @@ bool TiltSensorTizen::Connect() Disconnect(); } - const int interval = 1000/mFrequencyHertz; + const int interval = 1000 / mFrequencyHertz; - int ret = 0; + int ret = 0; bool isSupported = false; // try to use Orientation sensor at first for less power consumption. @@ -203,20 +200,20 @@ void TiltSensorTizen::Disconnect() sensor_listener_stop(mSensorListener); sensor_destroy_listener(mSensorListener); #endif - mSensor = NULL; + mSensor = NULL; mSensorListener = NULL; - mState = DISCONNECTED; + mState = DISCONNECTED; } } } bool TiltSensorTizen::Start() { - if( mSensorListener && ( mState == CONNECTED || mState == STOPPED ) ) + if(mSensorListener && (mState == CONNECTED || mState == STOPPED)) { #ifdef SENSOR_ENABLED int ret = 0; - ret = sensor_listener_start(mSensorListener); + ret = sensor_listener_start(mSensorListener); if(ret != SENSOR_ERROR_NONE) { DALI_LOG_ERROR("sensor_listener_start() failed : %s\n", get_sensor_error_string(ret).c_str()); @@ -230,7 +227,7 @@ bool TiltSensorTizen::Start() } else { - if( mState == STARTED ) + if(mState == STARTED) { DALI_LOG_ERROR("TiltSensor is already started. Current state [%d]\n", mState); } @@ -249,7 +246,7 @@ void TiltSensorTizen::Stop() #ifdef SENSOR_ENABLED if(mSensorListener && mState == STARTED) { - sensor_listener_stop( mSensorListener ); + sensor_listener_stop(mSensorListener); mState = STOPPED; } #endif @@ -257,7 +254,7 @@ void TiltSensorTizen::Stop() bool TiltSensorTizen::IsStarted() const { - return ( mSensorListener && mState == STARTED ); + return (mSensorListener && mState == STARTED); } float TiltSensorTizen::GetRoll() const @@ -280,18 +277,18 @@ TiltSensor::TiltedSignalType& TiltSensorTizen::TiltedSignal() return mTiltedSignal; } -void TiltSensorTizen::SetUpdateFrequency( float frequencyHertz ) +void TiltSensorTizen::SetUpdateFrequency(float frequencyHertz) { - DALI_ASSERT_ALWAYS( frequencyHertz > 0.0f && "Frequency must have a positive value" ); + DALI_ASSERT_ALWAYS(frequencyHertz > 0.0f && "Frequency must have a positive value"); - if ( fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz) ) + if(fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz)) { mFrequencyHertz = frequencyHertz; #ifdef SENSOR_ENABLED if(mSensorListener) { - const int interval = 1000/mFrequencyHertz; + const int interval = 1000 / mFrequencyHertz; sensor_listener_set_interval(mSensorListener, interval); } #endif @@ -313,14 +310,14 @@ Radian TiltSensorTizen::GetRotationThreshold() const return mRotationThreshold; } -bool TiltSensorTizen::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool TiltSensorTizen::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - bool connected( true ); - TiltSensor* sensor = dynamic_cast( object ); + bool connected(true); + TiltSensor* sensor = dynamic_cast(object); - if( sensor && SIGNAL_TILTED == signalName ) + if(sensor && SIGNAL_TILTED == signalName) { - sensor->TiltedSignal().Connect( tracker, functor ); + sensor->TiltedSignal().Connect(tracker, functor); } else { @@ -333,34 +330,34 @@ bool TiltSensorTizen::DoConnectSignal( BaseObject* object, ConnectionTrackerInte TiltSensorTizen::TiltSensorTizen() : mState(DISCONNECTED), - mFrequencyHertz( Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY ), - mSensor( NULL ), - mSensorListener( NULL ), - mRoll( 0.0f ), - mPitch( 0.0f ), - mRotation( Radian(0.0f), Vector3::YAXIS ), - mRotationThreshold( 0.0f ) + mFrequencyHertz(Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY), + mSensor(NULL), + mSensorListener(NULL), + mRoll(0.0f), + mPitch(0.0f), + mRotation(Radian(0.0f), Vector3::YAXIS), + mRotationThreshold(0.0f) { // connect sensor Connect(); } #ifdef SENSOR_ENABLED -void TiltSensorTizen::Update(sensor_event_s *event) +void TiltSensorTizen::Update(sensor_event_s* event) { - Radian newRoll( 0.0f ); - Radian newPitch( 0.0f ); + Radian newRoll(0.0f); + Radian newPitch(0.0f); Quaternion newRotation; if(mSensorType == SENSOR_ORIENTATION) { - newRoll = Clamp( float(event->values[2] / MAX_ORIENTATION_ROLL_VALUE) /* -90 < roll < 90 */, -1.0f/*min*/, 1.0f/*max*/ ); - newPitch = Clamp( float(event->values[1] / MAX_ORIENTATION_PITCH_VALUE) /* -180 < pitch < 180 */, -1.0f/*min*/, 1.0f/*max*/ ); + newRoll = Clamp(float(event->values[2] / MAX_ORIENTATION_ROLL_VALUE) /* -90 < roll < 90 */, -1.0f /*min*/, 1.0f /*max*/); + newPitch = Clamp(float(event->values[1] / MAX_ORIENTATION_PITCH_VALUE) /* -180 < pitch < 180 */, -1.0f /*min*/, 1.0f /*max*/); } else if(mSensorType == SENSOR_ACCELEROMETER) { - newRoll = Clamp( float(event->values[0] / MAX_ACCELEROMETER_VALUE), -1.0f/*min*/, 1.0f/*max*/ ); - newPitch = Clamp( float(event->values[1] / MAX_ACCELEROMETER_VALUE), -1.0f/*min*/, 1.0f/*max*/ ); + newRoll = Clamp(float(event->values[0] / MAX_ACCELEROMETER_VALUE), -1.0f /*min*/, 1.0f /*max*/); + newPitch = Clamp(float(event->values[1] / MAX_ACCELEROMETER_VALUE), -1.0f /*min*/, 1.0f /*max*/); } else { @@ -368,23 +365,23 @@ void TiltSensorTizen::Update(sensor_event_s *event) return; } - newRotation = Quaternion( Radian( newRoll * Math::PI * -0.5f ), Vector3::YAXIS ) * - Quaternion( Radian( newPitch * Math::PI * -0.5f ), Vector3::XAXIS ); + newRotation = Quaternion(Radian(newRoll * Math::PI * -0.5f), Vector3::YAXIS) * + Quaternion(Radian(newPitch * Math::PI * -0.5f), Vector3::XAXIS); Radian angle(Quaternion::AngleBetween(newRotation, mRotation)); // If the change in value is more than the threshold then emit tilted signal. - if( angle >= mRotationThreshold ) + if(angle >= mRotationThreshold) { - mRoll = newRoll; - mPitch = newPitch; + mRoll = newRoll; + mPitch = newPitch; mRotation = newRotation; // emit signal - if ( !mTiltedSignal.Empty() ) + if(!mTiltedSignal.Empty()) { - Dali::TiltSensor handle( this ); - mTiltedSignal.Emit( handle ); + Dali::TiltSensor handle(this); + mTiltedSignal.Emit(handle); } } } diff --git a/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.h b/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.h index b2f3963..3780d61 100644 --- a/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.h +++ b/dali/internal/sensor/tizen/tilt-sensor-impl-tizen.h @@ -2,7 +2,7 @@ #define DALI_SENSOR_TIZEN_TILT_SENSOR_IMPL_TIZEN_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,30 +24,26 @@ #define SENSOR_ENABLED #endif -#include -#include #include +#include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * TiltSensorTizen provides pitch & roll values when the device is tilted. */ class TiltSensorTizen : public Dali::Internal::Adaptor::TiltSensor { public: - typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType; /** @@ -94,7 +90,7 @@ public: /** * @copydoc Dali::TiltSensor::SetUpdateFrequency() */ - void SetUpdateFrequency( float frequencyHertz ) override; + void SetUpdateFrequency(float frequencyHertz) override; /** * @copydoc Dali::TiltSensor::GetUpdateFrequency() @@ -120,7 +116,7 @@ public: * @return True if the signal was connected. * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor. */ - static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ); + static bool DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor); /** * Update sensor data @@ -128,12 +124,10 @@ public: * @param[in] event sensor event data */ #ifdef SENSOR_ENABLED - void Update(sensor_event_s *event); + void Update(sensor_event_s* event); #endif - private: - enum State { DISCONNECTED, @@ -172,17 +166,17 @@ private: float mFrequencyHertz; #ifdef SENSOR_ENABLED - sensor_type_e mSensorType; - sensor_h mSensor; + sensor_type_e mSensorType; + sensor_h mSensor; sensor_listener_h mSensorListener; #else - int mSensorType; + int mSensorType; int* mSensor; int* mSensorListener; #endif - float mRoll; - float mPitch; + float mRoll; + float mPitch; Quaternion mRotation; Radian mRotationThreshold; diff --git a/dali/internal/sensor/ubuntu/tilt-sensor-factory-ubuntu.cpp b/dali/internal/sensor/ubuntu/tilt-sensor-factory-ubuntu.cpp index 3471167..b37d675 100644 --- a/dali/internal/sensor/ubuntu/tilt-sensor-factory-ubuntu.cpp +++ b/dali/internal/sensor/ubuntu/tilt-sensor-factory-ubuntu.cpp @@ -25,16 +25,15 @@ namespace Adaptor { namespace TiltSensorFactory { - Dali::Internal::Adaptor::TiltSensor* Create() { return Dali::Internal::Adaptor::TiltSensorUbuntu::New(); } -} // TiltSensorFactory +} // namespace TiltSensorFactory -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali \ No newline at end of file +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.cpp b/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.cpp index 9a2b5ea..691de78 100644 --- a/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.cpp +++ b/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.cpp @@ -16,17 +16,16 @@ */ // CLASS HEADER -#include #include +#include // EXTERNAL INCLUDES -#include -#include #include +#include +#include namespace // unnamed namespace { - const char* const SIGNAL_TILTED = "tilted"; const int NUMBER_OF_SAMPLES = 10; @@ -39,21 +38,18 @@ Dali::BaseHandle GetInstance() return Dali::Internal::Adaptor::TiltSensorFactory::Get(); } -Dali::TypeRegistration typeRegistration( typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), GetInstance ); +Dali::TypeRegistration typeRegistration(typeid(Dali::TiltSensor), typeid(Dali::BaseHandle), GetInstance); -Dali::SignalConnectorType signalConnector1( typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal ); +Dali::SignalConnectorType signalConnector1(typeRegistration, SIGNAL_TILTED, Dali::Internal::Adaptor::TiltSensor::DoConnectSignal); } // unnamed namespace namespace Dali { - namespace Internal { - namespace Adaptor { - TiltSensorUbuntu* TiltSensorUbuntu::New() { return new TiltSensorUbuntu(); @@ -69,16 +65,16 @@ bool TiltSensorUbuntu::Start() // Make sure sensor API is responding bool success = Update(); - if ( success ) + if(success) { - if ( !mTimer ) + if(!mTimer) { - mTimer = Dali::Timer::New( 1000.0f / mFrequencyHertz ); - mTimer.TickSignal().Connect( mTimerSlot, &TiltSensorUbuntu::Update ); + mTimer = Dali::Timer::New(1000.0f / mFrequencyHertz); + mTimer.TickSignal().Connect(mTimerSlot, &TiltSensorUbuntu::Update); } - if ( mTimer && - !mTimer.IsRunning() ) + if(mTimer && + !mTimer.IsRunning()) { mTimer.Start(); } @@ -89,7 +85,7 @@ bool TiltSensorUbuntu::Start() void TiltSensorUbuntu::Stop() { - if ( mTimer ) + if(mTimer) { mTimer.Stop(); mTimer.Reset(); @@ -98,7 +94,7 @@ void TiltSensorUbuntu::Stop() bool TiltSensorUbuntu::IsStarted() const { - return ( mTimer && mTimer.IsRunning() ); + return (mTimer && mTimer.IsRunning()); } float TiltSensorUbuntu::GetRoll() const @@ -121,17 +117,17 @@ TiltSensor::TiltedSignalType& TiltSensorUbuntu::TiltedSignal() return mTiltedSignal; } -void TiltSensorUbuntu::SetUpdateFrequency( float frequencyHertz ) +void TiltSensorUbuntu::SetUpdateFrequency(float frequencyHertz) { - DALI_ASSERT_ALWAYS( frequencyHertz > 0.0f && "Frequency must have a positive value" ); + DALI_ASSERT_ALWAYS(frequencyHertz > 0.0f && "Frequency must have a positive value"); - if ( fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz) ) + if(fabsf(mFrequencyHertz - frequencyHertz) >= GetRangedEpsilon(mFrequencyHertz, frequencyHertz)) { mFrequencyHertz = frequencyHertz; - if ( mTimer ) + if(mTimer) { - mTimer.SetInterval( 1000.0f / mFrequencyHertz ); + mTimer.SetInterval(1000.0f / mFrequencyHertz); } } } @@ -151,14 +147,14 @@ Radian TiltSensorUbuntu::GetRotationThreshold() const return mRotationThreshold; } -bool TiltSensorUbuntu::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool TiltSensorUbuntu::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - bool connected( true ); - TiltSensor* sensor = dynamic_cast( object ); + bool connected(true); + TiltSensor* sensor = dynamic_cast(object); - if( sensor && ( SIGNAL_TILTED == signalName ) ) + if(sensor && (SIGNAL_TILTED == signalName)) { - sensor->TiltedSignal().Connect( tracker, functor ); + sensor->TiltedSignal().Connect(tracker, functor); } else { @@ -170,36 +166,36 @@ bool TiltSensorUbuntu::DoConnectSignal( BaseObject* object, ConnectionTrackerInt } TiltSensorUbuntu::TiltSensorUbuntu() -: mFrequencyHertz( Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY ), - mTimerSlot( this ), - mSensorFrameworkHandle( -1 ), - mRoll( 0.0f ), - mPitch( 0.0f ), - mRotation( Dali::ANGLE_0, Vector3::YAXIS ), - mRotationThreshold( 0.0f ) +: mFrequencyHertz(Dali::TiltSensor::DEFAULT_UPDATE_FREQUENCY), + mTimerSlot(this), + mSensorFrameworkHandle(-1), + mRoll(0.0f), + mPitch(0.0f), + mRotation(Dali::ANGLE_0, Vector3::YAXIS), + mRotationThreshold(0.0f) { - mRollValues.resize( NUMBER_OF_SAMPLES, 0.0f ); - mPitchValues.resize( NUMBER_OF_SAMPLES, 0.0f ); + mRollValues.resize(NUMBER_OF_SAMPLES, 0.0f); + mPitchValues.resize(NUMBER_OF_SAMPLES, 0.0f); } bool TiltSensorUbuntu::Update() { - float newRoll = 0.0f; - float newPitch = 0.0f; + float newRoll = 0.0f; + float newPitch = 0.0f; Quaternion newRotation; Radian angle(Quaternion::AngleBetween(newRotation, mRotation)); // If the change in value is more than the threshold then emit tilted signal. - if( angle > mRotationThreshold ) + if(angle > mRotationThreshold) { - mRoll = newRoll; - mPitch = newPitch; + mRoll = newRoll; + mPitch = newPitch; mRotation = newRotation; - if ( !mTiltedSignal.Empty() ) + if(!mTiltedSignal.Empty()) { - Dali::TiltSensor handle( this ); - mTiltedSignal.Emit( handle ); + Dali::TiltSensor handle(this); + mTiltedSignal.Emit(handle); } } diff --git a/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.h b/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.h index f516b29..c06fdc4 100644 --- a/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.h +++ b/dali/internal/sensor/ubuntu/tilt-sensor-impl-ubuntu.h @@ -19,30 +19,26 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include #include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * TiltSensor provides pitch & roll values when the device is tilted. */ class TiltSensorUbuntu : public Dali::Internal::Adaptor::TiltSensor { public: - typedef Dali::TiltSensor::TiltedSignalType TiltedSignalType; /** @@ -89,7 +85,7 @@ public: /** * @copydoc Dali::TiltSensor::SetUpdateFrequency() */ - void SetUpdateFrequency( float frequencyHertz ) override; + void SetUpdateFrequency(float frequencyHertz) override; /** * @copydoc Dali::TiltSensor::GetUpdateFrequency() @@ -115,10 +111,9 @@ public: * @return True if the signal was connected. * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor. */ - static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ); + static bool DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor); private: - /** * Private constructor; see also TiltSensor::New() */ @@ -141,15 +136,14 @@ private: TiltSensorUbuntu& operator=(TiltSensorUbuntu&) = delete; private: - - float mFrequencyHertz; - Dali::Timer mTimer; - SlotDelegate< TiltSensorUbuntu > mTimerSlot; + float mFrequencyHertz; + Dali::Timer mTimer; + SlotDelegate mTimerSlot; int mSensorFrameworkHandle; - float mRoll; - float mPitch; + float mRoll; + float mPitch; Quaternion mRotation; Radian mRotationThreshold; diff --git a/dali/internal/styling/common/style-monitor-impl.cpp b/dali/internal/styling/common/style-monitor-impl.cpp index 8e93285..3e9000d 100644 --- a/dali/internal/styling/common/style-monitor-impl.cpp +++ b/dali/internal/styling/common/style-monitor-impl.cpp @@ -21,24 +21,20 @@ // EXTERNAL INCLUDES #include #include -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - #if defined(DEBUG_ENABLED) Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_STYLE_MONITOR"); #endif @@ -48,12 +44,12 @@ Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New * @param[in] fontClient handle to font client * @param[out] fontFamily string representing font family */ -void GetSystemDefaultFontFamily( TextAbstraction::FontClient& fontClient, std::string& fontFamily ) +void GetSystemDefaultFontFamily(TextAbstraction::FontClient& fontClient, std::string& fontFamily) { TextAbstraction::FontDescription defaultFontDescription; - if ( fontClient ) + if(fontClient) { - fontClient.GetDefaultPlatformFontDescription( defaultFontDescription ); + fontClient.GetDefaultPlatformFontDescription(defaultFontDescription); fontFamily = defaultFontDescription.family; } } @@ -64,20 +60,20 @@ Dali::StyleMonitor StyleMonitor::Get() { Dali::StyleMonitor styleMonitor; - Dali::SingletonService service( SingletonService::Get() ); - if( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::StyleMonitor ) ); - if( handle ) + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::StyleMonitor)); + if(handle) { // If so, downcast the handle - styleMonitor = Dali::StyleMonitor( dynamic_cast< StyleMonitor* >( handle.GetObjectPtr() ) ); + styleMonitor = Dali::StyleMonitor(dynamic_cast(handle.GetObjectPtr())); } else { - styleMonitor = Dali::StyleMonitor( new StyleMonitor() ); - service.Register( typeid( styleMonitor ), styleMonitor ); + styleMonitor = Dali::StyleMonitor(new StyleMonitor()); + service.Register(typeid(styleMonitor), styleMonitor); } } @@ -88,8 +84,8 @@ StyleMonitor::StyleMonitor() : mDefaultFontSize(-1) { mFontClient = TextAbstraction::FontClient::Get(); - GetSystemDefaultFontFamily( mFontClient, mDefaultFontFamily ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::StyleMonitor::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str() ); + GetSystemDefaultFontFamily(mFontClient, mDefaultFontFamily); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "StyleMonitor::StyleMonitor::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str()); mDefaultFontSize = mFontClient.GetDefaultFontSize(); } @@ -97,18 +93,18 @@ StyleMonitor::~StyleMonitor() { } -void StyleMonitor::StyleChanged( StyleChange::Type styleChange ) +void StyleMonitor::StyleChanged(StyleChange::Type styleChange) { - switch ( styleChange ) + switch(styleChange) { case StyleChange::DEFAULT_FONT_CHANGE: { - if ( mFontClient ) + if(mFontClient) { mFontClient.ResetSystemDefaults(); - GetSystemDefaultFontFamily( mFontClient, mDefaultFontFamily ); + GetSystemDefaultFontFamily(mFontClient, mDefaultFontFamily); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::StyleChanged::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "StyleMonitor::StyleChanged::DefaultFontFamily(%s)\n", mDefaultFontFamily.c_str()); break; } @@ -150,18 +146,18 @@ const std::string& StyleMonitor::GetTheme() const void StyleMonitor::SetTheme(const std::string& path) { mUserDefinedThemeFilePath = path; - EmitStyleChangeSignal( StyleChange::THEME_CHANGE ); + EmitStyleChangeSignal(StyleChange::THEME_CHANGE); } -bool StyleMonitor::LoadThemeFile( const std::string& filename, std::string& output ) +bool StyleMonitor::LoadThemeFile(const std::string& filename, std::string& output) { - bool retval( false ); + bool retval(false); - std::streampos bufferSize = 0; + std::streampos bufferSize = 0; Dali::Vector fileBuffer; - if( Dali::FileLoader::ReadFile( filename, bufferSize, fileBuffer, FileLoader::FileType::BINARY ) ) + if(Dali::FileLoader::ReadFile(filename, bufferSize, fileBuffer, FileLoader::FileType::BINARY)) { - output.assign( &fileBuffer[0], bufferSize ); + output.assign(&fileBuffer[0], bufferSize); retval = true; } @@ -173,13 +169,13 @@ Dali::StyleMonitor::StyleChangeSignalType& StyleMonitor::StyleChangeSignal() return mStyleChangeSignal; } -void StyleMonitor::EmitStyleChangeSignal( StyleChange::Type styleChange ) +void StyleMonitor::EmitStyleChangeSignal(StyleChange::Type styleChange) { - if( !mStyleChangeSignal.Empty() ) + if(!mStyleChangeSignal.Empty()) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "StyleMonitor::EmitStyleChangeSignal\n" ); - Dali::StyleMonitor handle( this ); - mStyleChangeSignal.Emit( handle, styleChange ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "StyleMonitor::EmitStyleChangeSignal\n"); + Dali::StyleMonitor handle(this); + mStyleChangeSignal.Emit(handle, styleChange); } } diff --git a/dali/internal/styling/common/style-monitor-impl.h b/dali/internal/styling/common/style-monitor-impl.h index 2528def..14f8fb5 100644 --- a/dali/internal/styling/common/style-monitor-impl.h +++ b/dali/internal/styling/common/style-monitor-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_STYLE_MONITOR_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,22 +19,19 @@ */ // EXTERNAL INCLUDES -#include -#include #include +#include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * This holds the platform's style information. * It provides a signal when any aspect of the default style changes on the device. @@ -42,7 +39,6 @@ namespace Adaptor class StyleMonitor : public BaseObject { public: - // Creation & Destruction /** @@ -62,7 +58,7 @@ public: * Informs the Style Monitor that the style has changed. * @param[in] styleChange The details of the change. */ - void StyleChanged( StyleChange::Type styleChange ); + void StyleChanged(StyleChange::Type styleChange); // Style Information @@ -94,7 +90,7 @@ public: /** * @copydoc Dali::StyleMonitor::LoadThemeFile() */ - bool LoadThemeFile( const std::string& filename, std::string& output ); + bool LoadThemeFile(const std::string& filename, std::string& output); // Signals @@ -104,29 +100,26 @@ public: Dali::StyleMonitor::StyleChangeSignalType& StyleChangeSignal(); protected: - /** * Virtual Destructor. */ ~StyleMonitor() override; private: - /** * Emit the style change signal. * @param[in] styleChange The details of the style change */ - inline void EmitStyleChangeSignal( StyleChange::Type styleChange ); + inline void EmitStyleChangeSignal(StyleChange::Type styleChange); private: - Dali::StyleMonitor::StyleChangeSignalType mStyleChangeSignal; ///< Emitted when the style changes TextAbstraction::FontClient mFontClient; - std::string mDefaultFontFamily; ///< The system default font family - std::string mDefaultFontStyle; ///< The default font style - std::string mUserDefinedThemeFilePath; ///< String containing the user defined theme file path - int mDefaultFontSize; ///< The default accessibility font size e.g. 0 is smallest + std::string mDefaultFontFamily; ///< The system default font family + std::string mDefaultFontStyle; ///< The default font style + std::string mUserDefinedThemeFilePath; ///< String containing the user defined theme file path + int mDefaultFontSize; ///< The default accessibility font size e.g. 0 is smallest }; } // namespace Adaptor diff --git a/dali/internal/system/android/callback-manager-android.cpp b/dali/internal/system/android/callback-manager-android.cpp index 7cb1952..2d45b43 100644 --- a/dali/internal/system/android/callback-manager-android.cpp +++ b/dali/internal/system/android/callback-manager-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,36 +19,32 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Structure contains the callback function and control options */ struct CallbackData { - /** * Constructor */ - CallbackData( CallbackBase* callback, bool hasReturnValue ) - : mIdleId( 0 ), - mCallback( callback ), - mRemoveFromContainerFunction( NULL ), - mHasReturnValue( hasReturnValue ) + CallbackData(CallbackBase* callback, bool hasReturnValue) + : mIdleId(0), + mCallback(callback), + mRemoveFromContainerFunction(NULL), + mHasReturnValue(hasReturnValue) { } /** @@ -60,28 +56,27 @@ struct CallbackData delete mRemoveFromContainerFunction; } - unsigned int mIdleId; - CallbackBase* mCallback; ///< call back - CallbackBase* mRemoveFromContainerFunction; ///< Called to remove the callbackdata from the callback container - bool mHasReturnValue; ///< true if the callback function has a return value. + unsigned int mIdleId; + CallbackBase* mCallback; ///< call back + CallbackBase* mRemoveFromContainerFunction; ///< Called to remove the callbackdata from the callback container + bool mHasReturnValue; ///< true if the callback function has a return value. }; namespace { - /** * Called from the main thread while idle. */ -bool IdleCallback(void *data) +bool IdleCallback(void* data) { - bool ret = false; - CallbackData *callbackData = static_cast< CallbackData * >( data ); + bool ret = false; + CallbackData* callbackData = static_cast(data); - if( callbackData->mHasReturnValue ) + if(callbackData->mHasReturnValue) { // run the function - bool retValue = CallbackBase::ExecuteReturn< bool >( *callbackData->mCallback ); - if( retValue ) + bool retValue = CallbackBase::ExecuteReturn(*callbackData->mCallback); + if(retValue) { // keep the callback ret = true; @@ -89,7 +84,7 @@ bool IdleCallback(void *data) else { // remove callback data from the container - CallbackBase::Execute( *callbackData->mRemoveFromContainerFunction, callbackData ); + CallbackBase::Execute(*callbackData->mRemoveFromContainerFunction, callbackData); // delete our data delete callbackData; @@ -98,10 +93,10 @@ bool IdleCallback(void *data) else { // remove callback data from the container - CallbackBase::Execute( *callbackData->mRemoveFromContainerFunction, callbackData ); + CallbackBase::Execute(*callbackData->mRemoveFromContainerFunction, callbackData); // run the function - CallbackBase::Execute( *callbackData->mCallback ); + CallbackBase::Execute(*callbackData->mCallback); // delete our data delete callbackData; @@ -113,14 +108,13 @@ bool IdleCallback(void *data) } // unnamed namespace AndroidCallbackManager::AndroidCallbackManager() - : mRunning( false ) +: mRunning(false) { } - void AndroidCallbackManager::Start() { - DALI_ASSERT_DEBUG( mRunning == false ); + DALI_ASSERT_DEBUG(mRunning == false); mRunning = true; } @@ -128,44 +122,43 @@ void AndroidCallbackManager::Start() void AndroidCallbackManager::Stop() { // make sure we're not called twice - DALI_ASSERT_DEBUG( mRunning == true ); + DALI_ASSERT_DEBUG(mRunning == true); RemoveAllCallbacks(); mRunning = false; - } -bool AndroidCallbackManager::AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) +bool AndroidCallbackManager::AddIdleCallback(CallbackBase* callback, bool hasReturnValue) { - if( !mRunning ) + if(!mRunning) { return false; } - CallbackData* callbackData = new CallbackData( callback, hasReturnValue ); - callbackData->mRemoveFromContainerFunction = MakeCallback( this, &AndroidCallbackManager::RemoveCallbackFromContainer ); - callbackData->mIdleId = AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).AddIdle( 0, callbackData, IdleCallback ); + CallbackData* callbackData = new CallbackData(callback, hasReturnValue); + callbackData->mRemoveFromContainerFunction = MakeCallback(this, &AndroidCallbackManager::RemoveCallbackFromContainer); + callbackData->mIdleId = AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).AddIdle(0, callbackData, IdleCallback); // add the call back to the container - mCallbackContainer.push_front( callbackData ); + mCallbackContainer.push_front(callbackData); return true; } -void AndroidCallbackManager::RemoveIdleCallback( CallbackBase* callback ) +void AndroidCallbackManager::RemoveIdleCallback(CallbackBase* callback) { - for( CallbackList::iterator it = mCallbackContainer.begin(), - endIt = mCallbackContainer.end(); - it != endIt; - ++it ) + for(CallbackList::iterator it = mCallbackContainer.begin(), + endIt = mCallbackContainer.end(); + it != endIt; + ++it) { CallbackData* data = *it; - if( data->mCallback == callback ) + if(data->mCallback == callback) { // remove callback data from the container. - CallbackBase::Execute( *data->mRemoveFromContainerFunction, data ); - AndroidFramework::GetFramework( AndroidFramework::Get() ).RemoveIdle( data->mIdleId ); + CallbackBase::Execute(*data->mRemoveFromContainerFunction, data); + AndroidFramework::GetFramework(AndroidFramework::Get()).RemoveIdle(data->mIdleId); return; } } @@ -182,54 +175,54 @@ void AndroidCallbackManager::ClearIdleCallbacks() // @todo To be implemented. } -bool AndroidCallbackManager::AddIdleEntererCallback( CallbackBase* callback ) +bool AndroidCallbackManager::AddIdleEntererCallback(CallbackBase* callback) { - if( !mRunning ) + if(!mRunning) { return false; } - CallbackData* callbackData = new CallbackData( callback, true ); + CallbackData* callbackData = new CallbackData(callback, true); - callbackData->mRemoveFromContainerFunction = MakeCallback( this, &AndroidCallbackManager::RemoveCallbackFromContainer ); - callbackData->mIdleId = AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).AddIdle( 0, callbackData, IdleCallback ); + callbackData->mRemoveFromContainerFunction = MakeCallback(this, &AndroidCallbackManager::RemoveCallbackFromContainer); + callbackData->mIdleId = AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).AddIdle(0, callbackData, IdleCallback); // add the call back to the container - mCallbackContainer.push_front( callbackData ); + mCallbackContainer.push_front(callbackData); return true; } -void AndroidCallbackManager::RemoveIdleEntererCallback( CallbackBase* callback ) +void AndroidCallbackManager::RemoveIdleEntererCallback(CallbackBase* callback) { - for( CallbackList::iterator it = mCallbackContainer.begin(), - endIt = mCallbackContainer.end(); - it != endIt; - ++it ) + for(CallbackList::iterator it = mCallbackContainer.begin(), + endIt = mCallbackContainer.end(); + it != endIt; + ++it) { CallbackData* data = *it; - if( data->mCallback == callback ) + if(data->mCallback == callback) { // remove callback data from the container. - CallbackBase::Execute( *data->mRemoveFromContainerFunction, data ); - AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).RemoveIdle( data->mIdleId ); + CallbackBase::Execute(*data->mRemoveFromContainerFunction, data); + AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).RemoveIdle(data->mIdleId); return; } } } -void AndroidCallbackManager::RemoveCallbackFromContainer( CallbackData *callbackData ) +void AndroidCallbackManager::RemoveCallbackFromContainer(CallbackData* callbackData) { - mCallbackContainer.remove( callbackData ); + mCallbackContainer.remove(callbackData); } void AndroidCallbackManager::RemoveAllCallbacks() { // always called from main thread - for( CallbackList::iterator iter = mCallbackContainer.begin(); iter != mCallbackContainer.end(); ++iter ) + for(CallbackList::iterator iter = mCallbackContainer.begin(); iter != mCallbackContainer.end(); ++iter) { CallbackData* data = (*iter); - AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).RemoveIdle( data->mIdleId ); + AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).RemoveIdle(data->mIdleId); delete data; } mCallbackContainer.clear(); @@ -246,5 +239,3 @@ CallbackManager* CallbackManager::New() } // namespace Internal } // namespace Dali - - diff --git a/dali/internal/system/android/callback-manager-android.h b/dali/internal/system/android/callback-manager-android.h index 5e153a8..fceaabc 100644 --- a/dali/internal/system/android/callback-manager-android.h +++ b/dali/internal/system/android/callback-manager-android.h @@ -2,7 +2,7 @@ #define __DALI_ANDROID_CALLBACK_MANAGER_H__ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,16 +24,12 @@ // INTERNAL INCLUDES #include - namespace Dali { - namespace Internal { - namespace Adaptor { - struct CallbackData; /** @@ -41,87 +37,83 @@ struct CallbackData; */ class AndroidCallbackManager : public CallbackManager { - public: - - /** + /** * @brief constructor */ - AndroidCallbackManager(); + AndroidCallbackManager(); - /** + /** * @brief destructor */ - ~AndroidCallbackManager() = default; + ~AndroidCallbackManager() = default; - /** + /** * @copydoc CallbackManager::AddIdleCallback() */ - bool AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) override; + bool AddIdleCallback(CallbackBase* callback, bool hasReturnValue) override; - /** + /** * @copydoc CallbackManager::RemoveIdleCallback() */ - void RemoveIdleCallback( CallbackBase* callback ) override; + void RemoveIdleCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::ProcessIdle() */ - bool ProcessIdle() override; + bool ProcessIdle() override; - /** + /** * @copydoc CallbackManager::ProcessIdle() */ - void ClearIdleCallbacks() override; + void ClearIdleCallbacks() override; - /** + /** * @copydoc CallbackManager::AddIdleEntererCallback() */ - bool AddIdleEntererCallback( CallbackBase* callback ) override; + bool AddIdleEntererCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::RemoveIdleEntererCallback() */ - void RemoveIdleEntererCallback( CallbackBase* callback ) override; + void RemoveIdleEntererCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::Start() */ - void Start() override; + void Start() override; - /** + /** * @copydoc CallbackManager::Stop() */ - void Stop() override; + void Stop() override; private: - - /** + /** * @brief Remove all idle call backs that are pending * Called by Stop() * Always called from the main thread */ - void RemoveAllCallbacks(); + void RemoveAllCallbacks(); - /** + /** * @brief Removes a single call back from the container * Always called from main thread * @param callbackData callback data */ - void RemoveCallbackFromContainer(CallbackData *callbackData); + void RemoveCallbackFromContainer(CallbackData* callbackData); - /** + /** * @brief Remove a standard call back from ecore * Always called from main thread * @param callbackData callback data */ - void RemoveStandardCallback(CallbackData *callbackData); - + void RemoveStandardCallback(CallbackData* callbackData); - typedef std::list CallbackList; + typedef std::list CallbackList; - bool mRunning; ///< flag is set to true if when running - CallbackList mCallbackContainer; ///< container of live idle callbacks + bool mRunning; ///< flag is set to true if when running + CallbackList mCallbackContainer; ///< container of live idle callbacks }; } // namespace Adaptor diff --git a/dali/internal/system/android/file-descriptor-monitor-android.cpp b/dali/internal/system/android/file-descriptor-monitor-android.cpp index b15b339..6f4c464 100644 --- a/dali/internal/system/android/file-descriptor-monitor-android.cpp +++ b/dali/internal/system/android/file-descriptor-monitor-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,23 +26,20 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Using Impl to hide away Android specific members */ struct FileDescriptorMonitor::Impl { // Construction - Impl( int fileDescriptor, CallbackBase* callback, int eventBitmask ) - : mCallback( callback ), - mFileDescriptor( fileDescriptor ), - mEventsToMonitor( eventBitmask ) + Impl(int fileDescriptor, CallbackBase* callback, int eventBitmask) + : mCallback(callback), + mFileDescriptor(fileDescriptor), + mEventsToMonitor(eventBitmask) { } @@ -53,57 +50,53 @@ struct FileDescriptorMonitor::Impl // Data CallbackBase* mCallback; - int mFileDescriptor; - int mEventsToMonitor; + int mFileDescriptor; + int mEventsToMonitor; // Static Methods /** * Called when the file descriptor receives an event. */ - static int EventDispatch( int fd, int events, void* data ) + static int EventDispatch(int fd, int events, void* data) { Impl* impl = reinterpret_cast(data); // if we want read events, check to see if a read event is available int type = FileDescriptorMonitor::FD_NO_EVENT; - if( impl->mEventsToMonitor & ALOOPER_EVENT_INPUT ) + if(impl->mEventsToMonitor & ALOOPER_EVENT_INPUT) { - type = FileDescriptorMonitor::FD_READABLE; - } // check if we want write events - if( impl->mEventsToMonitor & ALOOPER_EVENT_OUTPUT ) + if(impl->mEventsToMonitor & ALOOPER_EVENT_OUTPUT) { - type |= FileDescriptorMonitor::FD_WRITABLE; - } // if there is an event, execute the callback - if( type != FileDescriptorMonitor::FD_NO_EVENT ) + if(type != FileDescriptorMonitor::FD_NO_EVENT) { - CallbackBase::Execute( *impl->mCallback, static_cast< FileDescriptorMonitor::EventType >( type ), impl->mFileDescriptor ); + CallbackBase::Execute(*impl->mCallback, static_cast(type), impl->mFileDescriptor); } return 1; // Continue receiving callbacks } }; -FileDescriptorMonitor::FileDescriptorMonitor( int fileDescriptor, CallbackBase* callback, int eventBitmask ) +FileDescriptorMonitor::FileDescriptorMonitor(int fileDescriptor, CallbackBase* callback, int eventBitmask) { mImpl = new Impl(fileDescriptor, callback, eventBitmask); - if (fileDescriptor >= 0) + if(fileDescriptor >= 0) { int events = 0; - if( eventBitmask & FD_READABLE) + if(eventBitmask & FD_READABLE) { events = ALOOPER_EVENT_INPUT; } - if( eventBitmask & FD_WRITABLE) + if(eventBitmask & FD_WRITABLE) { events |= ALOOPER_EVENT_OUTPUT; } @@ -111,21 +104,21 @@ FileDescriptorMonitor::FileDescriptorMonitor( int fileDescriptor, CallbackBase* mImpl->mEventsToMonitor = events; ALooper* looper = ALooper_forThread(); - if( looper ) + if(looper) { - ALooper_addFd( looper, fileDescriptor, ALOOPER_POLL_CALLBACK, events, &Impl::EventDispatch, mImpl ); + ALooper_addFd(looper, fileDescriptor, ALOOPER_POLL_CALLBACK, events, &Impl::EventDispatch, mImpl); } } } FileDescriptorMonitor::~FileDescriptorMonitor() { - if( mImpl->mFileDescriptor ) + if(mImpl->mFileDescriptor) { ALooper* looper = ALooper_forThread(); - if( looper ) + if(looper) { - ALooper_removeFd( looper, mImpl->mFileDescriptor ); + ALooper_removeFd(looper, mImpl->mFileDescriptor); } } @@ -138,4 +131,3 @@ FileDescriptorMonitor::~FileDescriptorMonitor() } // namespace Internal } // namespace Dali - diff --git a/dali/internal/system/android/logging-android.cpp b/dali/internal/system/android/logging-android.cpp index 0518c51..634d0b9 100644 --- a/dali/internal/system/android/logging-android.cpp +++ b/dali/internal/system/android/logging-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,8 @@ namespace Dali { - namespace TizenPlatform { - void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& message) { const char* DALI_TAG = "DALI"; diff --git a/dali/internal/system/android/shared-file-operations-android.cpp b/dali/internal/system/android/shared-file-operations-android.cpp index 763b7bb..3888e66 100644 --- a/dali/internal/system/android/shared-file-operations-android.cpp +++ b/dali/internal/system/android/shared-file-operations-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,34 +19,31 @@ #include // EXTERNAL INCLUDES -#include #include +#include #include #include namespace Dali { - namespace Internal { - namespace Adaptor { - -int SharedFile::Open( const char* filename, int size, int oflag, mode_t mode ) +int SharedFile::Open(const char* filename, int size, int oflag, mode_t mode) { - int fileDescriptor = open( ASHMEM_NAME_DEF, oflag ); - if( mFileDescriptor >= 0 ) + int fileDescriptor = open(ASHMEM_NAME_DEF, oflag); + if(mFileDescriptor >= 0) { - ioctl( mFileDescriptor, ASHMEM_SET_NAME, filename ); - ioctl( mFileDescriptor, ASHMEM_SET_SIZE, size ); + ioctl(mFileDescriptor, ASHMEM_SET_NAME, filename); + ioctl(mFileDescriptor, ASHMEM_SET_SIZE, size); } return mFileDescriptor; } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/system/android/system-settings-android.cpp b/dali/internal/system/android/system-settings-android.cpp index 3eb6045..bdeadae 100644 --- a/dali/internal/system/android/system-settings-android.cpp +++ b/dali/internal/system/android/system-settings-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,19 +22,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - int GetElmAccessActionOver() { return 0; } -int GetLongPressTime( int defaultTime ) +int GetLongPressTime(int defaultTime) { return defaultTime; } diff --git a/dali/internal/system/android/timer-impl-android.cpp b/dali/internal/system/android/timer-impl-android.cpp index 62f06d3..333228d 100644 --- a/dali/internal/system/android/timer-impl-android.cpp +++ b/dali/internal/system/android/timer-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,43 +22,38 @@ #include // INTERNAL INCLUDES +#include #include #include -#include #include - namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - // Copied from x server static unsigned int GetCurrentMilliSeconds() { struct timeval tv; - struct timespec tp; + struct timespec tp; static clockid_t clockid; - if (!clockid) + if(!clockid) { #ifdef CLOCK_MONOTONIC_COARSE - if (clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 && - (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0) + if(clock_getres(CLOCK_MONOTONIC_COARSE, &tp) == 0 && + (tp.tv_nsec / 1000) <= 1000 && clock_gettime(CLOCK_MONOTONIC_COARSE, &tp) == 0) { clockid = CLOCK_MONOTONIC_COARSE; } else #endif - if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) + if(clock_gettime(CLOCK_MONOTONIC, &tp) == 0) { clockid = CLOCK_MONOTONIC; } @@ -67,7 +62,7 @@ static unsigned int GetCurrentMilliSeconds() clockid = ~0L; } } - if (clockid != ~0L && clock_gettime(clockid, &tp) == 0) + if(clockid != ~0L && clock_gettime(clockid, &tp) == 0) { return (tp.tv_sec * 1000) + (tp.tv_nsec / 1000000L); } @@ -76,34 +71,34 @@ static unsigned int GetCurrentMilliSeconds() return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } -} +} // namespace struct Timer::Impl { - Impl( unsigned int milliSec ) - : mInterval( milliSec ), - mStartTimestamp( 0 ), - mPauseTimestamp( 0 ), - mRunning( false ), - mId( 0 ) + Impl(unsigned int milliSec) + : mInterval(milliSec), + mStartTimestamp(0), + mPauseTimestamp(0), + mRunning(false), + mId(0) { } unsigned int mInterval; unsigned int mStartTimestamp; unsigned int mPauseTimestamp; - bool mRunning; + bool mRunning; unsigned int mId; }; -TimerPtr Timer::New( unsigned int milliSec ) +TimerPtr Timer::New(unsigned int milliSec) { - TimerPtr timer( new Timer( milliSec ) ); + TimerPtr timer(new Timer(milliSec)); return timer; } -Timer::Timer( unsigned int milliSec ) -: mImpl( new Impl( milliSec ) ) +Timer::Timer(unsigned int milliSec) +: mImpl(new Impl(milliSec)) { } @@ -113,10 +108,10 @@ Timer::~Timer() delete mImpl; } -bool TimerCallback( void *data ) +bool TimerCallback(void* data) { - Timer* timer = static_cast( data ); - if( timer->IsRunning() ) + Timer* timer = static_cast(data); + if(timer->IsRunning()) { return timer->Tick(); } @@ -127,26 +122,26 @@ bool TimerCallback( void *data ) void Timer::Start() { // Timer should be used in the event thread - DALI_ASSERT_DEBUG( Adaptor::IsAvailable() ); + DALI_ASSERT_DEBUG(Adaptor::IsAvailable()); - if( mImpl->mRunning ) + if(mImpl->mRunning) { Stop(); } - mImpl->mId = AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).AddIdle( mImpl->mInterval, this, TimerCallback ); - mImpl->mRunning = true; + mImpl->mId = AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).AddIdle(mImpl->mInterval, this, TimerCallback); + mImpl->mRunning = true; mImpl->mStartTimestamp = GetCurrentMilliSeconds(); } void Timer::Stop() { // Timer should be used in the event thread - DALI_ASSERT_DEBUG( Adaptor::IsAvailable() ); + DALI_ASSERT_DEBUG(Adaptor::IsAvailable()); - if( mImpl->mId != 0 ) + if(mImpl->mId != 0) { - AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).RemoveIdle( mImpl->mId ); + AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).RemoveIdle(mImpl->mId); mImpl->mStartTimestamp = 0; mImpl->mPauseTimestamp = 0; } @@ -157,12 +152,12 @@ void Timer::Stop() void Timer::Pause() { // Timer should be used in the event thread - DALI_ASSERT_DEBUG( Adaptor::IsAvailable() ); + DALI_ASSERT_DEBUG(Adaptor::IsAvailable()); - if( mImpl->mRunning ) + if(mImpl->mRunning) { mImpl->mPauseTimestamp = GetCurrentMilliSeconds(); - AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).RemoveIdle( mImpl->mId ); + AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).RemoveIdle(mImpl->mId); mImpl->mId = 0; } } @@ -170,30 +165,30 @@ void Timer::Pause() void Timer::Resume() { // Timer should be used in the event thread - DALI_ASSERT_DEBUG( Adaptor::IsAvailable() ); + DALI_ASSERT_DEBUG(Adaptor::IsAvailable()); - if( mImpl->mRunning && mImpl->mId == 0 ) + if(mImpl->mRunning && mImpl->mId == 0) { unsigned int newInterval = 0; unsigned int runningTime = mImpl->mPauseTimestamp - mImpl->mStartTimestamp; - if( mImpl->mInterval > runningTime ) + if(mImpl->mInterval > runningTime) { newInterval = mImpl->mInterval - runningTime; } mImpl->mStartTimestamp = GetCurrentMilliSeconds() - runningTime; mImpl->mPauseTimestamp = 0; - mImpl->mId = AndroidFramework::GetFramework( Dali::Integration::AndroidFramework::Get() ).AddIdle( newInterval, this, TimerCallback ); + mImpl->mId = AndroidFramework::GetFramework(Dali::Integration::AndroidFramework::Get()).AddIdle(newInterval, this, TimerCallback); } } -void Timer::SetInterval( unsigned int interval, bool restart ) +void Timer::SetInterval(unsigned int interval, bool restart) { // stop existing timer Stop(); mImpl->mInterval = interval; - if( restart ) + if(restart) { // start new tick Start(); @@ -208,23 +203,23 @@ unsigned int Timer::GetInterval() const bool Timer::Tick() { // Guard against destruction during signal emission - Dali::Timer handle( this ); + Dali::Timer handle(this); - bool retVal( false ); + bool retVal(false); // Override with new signal if used - if( !mTickSignal.Empty() ) + if(!mTickSignal.Empty()) { retVal = mTickSignal.Emit(); // Timer stops if return value is false - if (retVal == false) + if(retVal == false) { Stop(); } else { - retVal = true; // continue emission + retVal = true; // continue emission } } else // no callbacks registered @@ -244,7 +239,7 @@ Dali::Timer::TimerSignalType& Timer::TickSignal() void Timer::ResetTimerData() { mImpl->mRunning = false; - mImpl->mId = 0; + mImpl->mId = 0; } bool Timer::IsRunning() const diff --git a/dali/internal/system/android/widget-application-impl-android.cpp b/dali/internal/system/android/widget-application-impl-android.cpp index be5da40..65d95a6 100644 --- a/dali/internal/system/android/widget-application-impl-android.cpp +++ b/dali/internal/system/android/widget-application-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,27 +16,24 @@ */ // CLASS HEADER -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - WidgetApplicationPtr WidgetApplicationAndroid::New( - int* argc, - char **argv[], + int* argc, + char** argv[], const std::string& stylesheet) { - return new WidgetApplicationAndroid(argc, argv, stylesheet ); + return new WidgetApplicationAndroid(argc, argv, stylesheet); } -WidgetApplicationAndroid::WidgetApplicationAndroid( int* argc, char** argv[], const std::string& stylesheet ) +WidgetApplicationAndroid::WidgetApplicationAndroid(int* argc, char** argv[], const std::string& stylesheet) : WidgetApplication(argc, argv, stylesheet) { DALI_LOG_ERROR("WidgetApplication is not implemented in Android profile.\n"); @@ -44,7 +41,7 @@ WidgetApplicationAndroid::WidgetApplicationAndroid( int* argc, char** argv[], co WidgetApplicationAndroid::~WidgetApplicationAndroid() = default; -void WidgetApplicationAndroid::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) +void WidgetApplicationAndroid::RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) { } @@ -57,12 +54,12 @@ namespace WidgetApplicationFactory * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ -WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet ) +WidgetApplicationPtr Create(int* argc, char** argv[], const std::string& stylesheet) { - return WidgetApplicationAndroid::New( argc, argv, stylesheet ); + return WidgetApplicationAndroid::New(argc, argv, stylesheet); } -} // namespace Factory +} // namespace WidgetApplicationFactory } // namespace Adaptor diff --git a/dali/internal/system/android/widget-application-impl-android.h b/dali/internal/system/android/widget-application-impl-android.h index ffb4e87..7e93d98 100644 --- a/dali/internal/system/android/widget-application-impl-android.h +++ b/dali/internal/system/android/widget-application-impl-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_ANDROID_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,19 +29,16 @@ class Widget; namespace Internal { - namespace Adaptor { - /** * Implementation of the WidgetApplicationAndroid class. */ class WidgetApplicationAndroid : public WidgetApplication { public: - - typedef std::pair CreateWidgetFunctionPair; - typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer; + typedef std::pair CreateWidgetFunctionPair; + typedef std::vector CreateWidgetFunctionContainer; /** * Create a new widget application @@ -49,24 +46,22 @@ public: * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet ); + static WidgetApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet); public: - /** * @copydoc Dali::WidgetApplication::RegisterWidgetCreator() */ - void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) override; + void RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) override; protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - WidgetApplicationAndroid( int* argc, char **argv[], const std::string& stylesheet ); + WidgetApplicationAndroid(int* argc, char** argv[], const std::string& stylesheet); /** * Destructor diff --git a/dali/internal/system/common/abort-handler.cpp b/dali/internal/system/common/abort-handler.cpp index 696570e..99beaf8 100644 --- a/dali/internal/system/common/abort-handler.cpp +++ b/dali/internal/system/common/abort-handler.cpp @@ -27,17 +27,16 @@ namespace Internal { namespace Adaptor { - AbortHandler* AbortHandler::gInstance(NULL); -AbortHandler::AbortHandler( CallbackBase* callback ) -: mSignalMask( 0 ), - mCallback( callback ) +AbortHandler::AbortHandler(CallbackBase* callback) +: mSignalMask(0), + mCallback(callback) { - DALI_ASSERT_ALWAYS( gInstance == NULL && "Only one instance of abort handler allowed" ); + DALI_ASSERT_ALWAYS(gInstance == NULL && "Only one instance of abort handler allowed"); gInstance = this; - memset( mSignalOldHandlers, 0, sizeof(SignalHandlerFuncPtr) * (_NSIG-1)); + memset(mSignalOldHandlers, 0, sizeof(SignalHandlerFuncPtr) * (_NSIG - 1)); } AbortHandler::~AbortHandler() @@ -45,32 +44,32 @@ AbortHandler::~AbortHandler() delete mCallback; int signum; - for ( signum = 1; signum < _NSIG; signum++ ) + for(signum = 1; signum < _NSIG; signum++) { - if ( mSignalMask & (1ULL << (signum-1) ) ) + if(mSignalMask & (1ULL << (signum - 1))) { // set signals back to default handling - signal( signum, mSignalOldHandlers[signum-1] ); + signal(signum, mSignalOldHandlers[signum - 1]); } } gInstance = NULL; } -bool AbortHandler::AbortOnSignal( int signum ) +bool AbortHandler::AbortOnSignal(int signum) { bool status = false; - if ( signum < _NSIG ) + if(signum < _NSIG) { - SignalHandlerFuncPtr signalHandlerPrevious = signal( signum, &AbortHandler::SignalHandler ); + SignalHandlerFuncPtr signalHandlerPrevious = signal(signum, &AbortHandler::SignalHandler); // SIG_ERR is a macro with C cast #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - if ( SIG_ERR != signalHandlerPrevious ) + if(SIG_ERR != signalHandlerPrevious) { - mSignalOldHandlers[signum-1] = signalHandlerPrevious; - mSignalMask |= ( 1ULL << (signum-1) ); + mSignalOldHandlers[signum - 1] = signalHandlerPrevious; + mSignalMask |= (1ULL << (signum - 1)); status = true; } } @@ -78,17 +77,17 @@ bool AbortHandler::AbortOnSignal( int signum ) return status; } -void AbortHandler::SignalHandler( int signum ) +void AbortHandler::SignalHandler(int signum) { - if( gInstance ) + if(gInstance) { - if( gInstance->mCallback ) + if(gInstance->mCallback) { - CallbackBase::Execute( *gInstance->mCallback ); + CallbackBase::Execute(*gInstance->mCallback); } } } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/system/common/abort-handler.h b/dali/internal/system/common/abort-handler.h old mode 100755 new mode 100644 index f012cdd..f89d5de --- a/dali/internal/system/common/abort-handler.h +++ b/dali/internal/system/common/abort-handler.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_ABORT_HANDLER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -35,7 +35,6 @@ namespace Internal { namespace Adaptor { - /** * Class to listen to system signals and trigger an abort callback * when they occur. @@ -53,7 +52,7 @@ public: * @param[in] callback The function to call when abort signals occur * @note The ownership of callback is passed onto this class. */ - AbortHandler( CallbackBase* callback ); + AbortHandler(CallbackBase* callback); /** * Destructor @@ -65,14 +64,14 @@ public: * @param[in] signum The signal number (from signum.h) * @return true if the signal handler was installed ok */ - bool AbortOnSignal( int signum ); + bool AbortOnSignal(int signum); private: /** * Signal handler - Called when signal is received. * Stops the application. */ - static void SignalHandler( int signum ); + static void SignalHandler(int signum); /** * Default constructor - undefined @@ -90,15 +89,15 @@ private: AbortHandler& operator=(const AbortHandler& rhs); private: - using SignalHandlerFuncPtr = void( * )( int ); + using SignalHandlerFuncPtr = void (*)(int); // _NSIG comes from the signal.h linux system header, defining the number of signals. - SignalHandlerFuncPtr mSignalOldHandlers[_NSIG-1]; - unsigned long long mSignalMask; + SignalHandlerFuncPtr mSignalOldHandlers[_NSIG - 1]; + unsigned long long mSignalMask; - CallbackBase* mCallback; + CallbackBase* mCallback; - static AbortHandler* gInstance; + static AbortHandler* gInstance; }; } // Namespace Adaptor diff --git a/dali/internal/system/common/atomics.h b/dali/internal/system/common/atomics.h index 9462c8d..3d01c6a 100644 --- a/dali/internal/system/common/atomics.h +++ b/dali/internal/system/common/atomics.h @@ -32,7 +32,6 @@ namespace Dali { namespace Internal { - /** * @brief Atomic write to an aligned memory location in cacheable memory. * @@ -46,9 +45,9 @@ namespace Internal * aligned to a 4 byte boundary. * @param value A value to assign to the memory location in address. */ -inline void AtomicWriteToCacheableAlignedAddress( volatile uint32_t * const address, const uint32_t value ) +inline void AtomicWriteToCacheableAlignedAddress(volatile uint32_t* const address, const uint32_t value) { - DALI_ASSERT_DEBUG( ptrdiff_t(address) % 4 == 0 && "Address must be 32 bit aligned" ); + DALI_ASSERT_DEBUG(ptrdiff_t(address) % 4 == 0 && "Address must be 32 bit aligned"); *address = value; } @@ -64,9 +63,9 @@ inline void AtomicWriteToCacheableAlignedAddress( volatile uint32_t * const addr * aligned to a 4 byte boundary. * @return The value stored at the memory location in address. */ -inline uint32_t AtomicReadFromCacheableAlignedAddress( const volatile uint32_t * const address ) +inline uint32_t AtomicReadFromCacheableAlignedAddress(const volatile uint32_t* const address) { - DALI_ASSERT_DEBUG( ptrdiff_t(address) % 4 == 0 && "Address must be 32 bit aligned" ); + DALI_ASSERT_DEBUG(ptrdiff_t(address) % 4 == 0 && "Address must be 32 bit aligned"); return *address; } diff --git a/dali/internal/system/common/callback-manager.h b/dali/internal/system/common/callback-manager.h index a368d49..2a26eb4 100644 --- a/dali/internal/system/common/callback-manager.h +++ b/dali/internal/system/common/callback-manager.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_CALLBACK_MANAGER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,32 +26,29 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Abstract interface to install call backs in to an applications main loop. */ class CallbackManager { - public: - - /** + /** * Create a new call back interface */ - static CallbackManager* New(); + static CallbackManager* New(); - /** + /** * Virtual destructor */ - virtual ~CallbackManager() {} + virtual ~CallbackManager() + { + } - /** + /** * @brief Adds a @p callback to be run on idle. * @note Must be called from the main thread only. * @@ -71,9 +68,9 @@ public: * * @return true on success */ - virtual bool AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) = 0; + virtual bool AddIdleCallback(CallbackBase* callback, bool hasReturnValue) = 0; - /** + /** * @brief Removes a previously added @p callback. * @note Must be called from main thread only. * @@ -81,21 +78,21 @@ public: * * @param[in] callback The callback to be removed. */ - virtual void RemoveIdleCallback( CallbackBase* callback ) = 0; + virtual void RemoveIdleCallback(CallbackBase* callback) = 0; - /** + /** * @brief Processes the idle callbacks. * * @return whether a DALi callback has been processed. */ - virtual bool ProcessIdle() = 0; + virtual bool ProcessIdle() = 0; - /** + /** * @brief Clears the container of callbacks. */ - virtual void ClearIdleCallbacks() = 0; + virtual void ClearIdleCallbacks() = 0; - /** + /** * @brief Adds a @p callback to be run when entering an idle state. * @note Must be called from the main thread only. * @@ -109,9 +106,9 @@ public: * * @return true on success */ - virtual bool AddIdleEntererCallback( CallbackBase* callback ) = 0; + virtual bool AddIdleEntererCallback(CallbackBase* callback) = 0; - /** + /** * @brief Removes a previously added the idle enterer callback. * @note Must be called from main thread only. * @@ -119,35 +116,34 @@ public: * * @param[in] callback The callback to be removed. */ - virtual void RemoveIdleEntererCallback( CallbackBase* callback ) = 0; + virtual void RemoveIdleEntererCallback(CallbackBase* callback) = 0; - /** + /** * Starts the callback manager. */ - virtual void Start() = 0; + virtual void Start() = 0; - /** + /** * Stop the callback manager and can remove all pending callbacks synchronously. * This call will synchronise with the main loop and not return * until all call backs have been deleted. */ - virtual void Stop() = 0; + virtual void Stop() = 0; protected: - - /** + /** * constructor */ - CallbackManager() {} + CallbackManager() + { + } private: + // Undefined copy constructor. + CallbackManager(const CallbackManager&); - // Undefined copy constructor. - CallbackManager( const CallbackManager& ); - - // Undefined assignment operator. - CallbackManager& operator=( const CallbackManager& ); - + // Undefined assignment operator. + CallbackManager& operator=(const CallbackManager&); }; } // namespace Adaptor diff --git a/dali/internal/system/common/capture-impl.cpp b/dali/internal/system/common/capture-impl.cpp index 7f0fa9b..8273d09 100644 --- a/dali/internal/system/common/capture-impl.cpp +++ b/dali/internal/system/common/capture-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,16 +19,16 @@ #include // EXTERNAL INCLUDES -#include -#include +#include #include #include -#include +#include +#include // INTERNAL INCLUDES -#include #include #include +#include namespace { @@ -37,29 +37,26 @@ unsigned int TIME_OUT_DURATION = 1000; namespace Dali { - namespace Internal { - namespace Adaptor { - Capture::Capture() -: mQuality( DEFAULT_QUALITY ), +: mQuality(DEFAULT_QUALITY), mTimer(), mPath(), - mNativeImageSourcePtr( NULL ), - mFileSave( false ) + mNativeImageSourcePtr(NULL), + mFileSave(false) { } -Capture::Capture( Dali::CameraActor cameraActor ) -: mQuality( DEFAULT_QUALITY ), - mCameraActor( cameraActor ), +Capture::Capture(Dali::CameraActor cameraActor) +: mQuality(DEFAULT_QUALITY), + mCameraActor(cameraActor), mTimer(), mPath(), - mNativeImageSourcePtr( NULL ), - mFileSave( false ) + mNativeImageSourcePtr(NULL), + mFileSave(false) { } @@ -75,20 +72,20 @@ CapturePtr Capture::New() return pWorker; } -CapturePtr Capture::New( Dali::CameraActor cameraActor ) +CapturePtr Capture::New(Dali::CameraActor cameraActor) { - CapturePtr pWorker = new Capture( cameraActor ); + CapturePtr pWorker = new Capture(cameraActor); return pWorker; } -void Capture::Start( Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string &path, const Dali::Vector4& clearColor, const uint32_t quality ) +void Capture::Start(Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string& path, const Dali::Vector4& clearColor, const uint32_t quality) { mQuality = quality; - Start( source, position, size, path, clearColor ); + Start(source, position, size, path, clearColor); } -void Capture::Start( Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string &path, const Dali::Vector4& clearColor ) +void Capture::Start(Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string& path, const Dali::Vector4& clearColor) { DALI_ASSERT_ALWAYS(path.size() > 4 && "Path is invalid."); @@ -96,7 +93,7 @@ void Capture::Start( Dali::Actor source, const Dali::Vector2& position, const Da Reference(); mPath = path; - if( mPath.size() > 0 ) + if(mPath.size() > 0) { mFileSave = true; } @@ -104,10 +101,10 @@ void Capture::Start( Dali::Actor source, const Dali::Vector2& position, const Da DALI_ASSERT_ALWAYS(source && "Source is NULL."); UnsetResources(); - SetupResources( position, size, clearColor, source ); + SetupResources(position, size, clearColor, source); } -void Capture::SetImageQuality( uint32_t quality ) +void Capture::SetImageQuality(uint32_t quality) { mQuality = quality; } @@ -122,7 +119,7 @@ Dali::Capture::CaptureFinishedSignalType& Capture::FinishedSignal() return mFinishedSignal; } -void Capture::CreateNativeImageSource( const Vector2& size ) +void Capture::CreateNativeImageSource(const Vector2& size) { Dali::Adaptor& adaptor = Dali::Adaptor::Get(); @@ -131,7 +128,7 @@ void Capture::CreateNativeImageSource( const Vector2& size ) DALI_ASSERT_ALWAYS(!mNativeImageSourcePtr && "NativeImageSource is already created."); // create the NativeImageSource object with our surface - mNativeImageSourcePtr = Dali::NativeImageSource::New( size.width, size.height, Dali::NativeImageSource::COLOR_DEPTH_DEFAULT ); + mNativeImageSourcePtr = Dali::NativeImageSource::New(size.width, size.height, Dali::NativeImageSource::COLOR_DEPTH_DEFAULT); } void Capture::DeleteNativeImageSource() @@ -150,12 +147,12 @@ void Capture::CreateFrameBuffer() DALI_ASSERT_ALWAYS(!mFrameBuffer && "FrameBuffer is already created."); - mNativeTexture = Dali::Texture::New( *mNativeImageSourcePtr ); + mNativeTexture = Dali::Texture::New(*mNativeImageSourcePtr); // Create a FrameBuffer object with depth attachments. - mFrameBuffer = Dali::FrameBuffer::New( mNativeTexture.GetWidth(), mNativeTexture.GetHeight(), Dali::FrameBuffer::Attachment::DEPTH ); + mFrameBuffer = Dali::FrameBuffer::New(mNativeTexture.GetWidth(), mNativeTexture.GetHeight(), Dali::FrameBuffer::Attachment::DEPTH); // Add a color attachment to the FrameBuffer object. - mFrameBuffer.AttachColorTexture( mNativeTexture ); + mFrameBuffer.AttachColorTexture(mNativeTexture); } void Capture::DeleteFrameBuffer() @@ -171,12 +168,12 @@ bool Capture::IsFrameBufferCreated() return mFrameBuffer; } -void Capture::SetupRenderTask( const Dali::Vector2& position, const Dali::Vector2& size, Dali::Actor source, const Dali::Vector4& clearColor ) +void Capture::SetupRenderTask(const Dali::Vector2& position, const Dali::Vector2& size, Dali::Actor source, const Dali::Vector4& clearColor) { DALI_ASSERT_ALWAYS(source && "Source is empty."); - Dali::Window window = DevelWindow::Get( source ); - if( !window ) + Dali::Window window = DevelWindow::Get(source); + if(!window) { DALI_LOG_ERROR("The source is not added on the window\n"); return; @@ -184,39 +181,39 @@ void Capture::SetupRenderTask( const Dali::Vector2& position, const Dali::Vector mSource = source; - if( !mCameraActor ) + if(!mCameraActor) { - mCameraActor = Dali::CameraActor::New( size ); + mCameraActor = Dali::CameraActor::New(size); // Because input position and size are for 2 dimentional area, // default z-directional position of the camera is required to be used for the new camera position. - float cameraDefaultZPosition = mCameraActor.GetProperty( Dali::Actor::Property::POSITION_Z ); - Vector2 positionTransition = position + size / 2; - mCameraActor.SetProperty( Dali::Actor::Property::POSITION, Vector3( positionTransition.x, positionTransition.y, cameraDefaultZPosition ) ); - mCameraActor.SetProperty( Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - mCameraActor.SetProperty( Dali::Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + float cameraDefaultZPosition = mCameraActor.GetProperty(Dali::Actor::Property::POSITION_Z); + Vector2 positionTransition = position + size / 2; + mCameraActor.SetProperty(Dali::Actor::Property::POSITION, Vector3(positionTransition.x, positionTransition.y, cameraDefaultZPosition)); + mCameraActor.SetProperty(Dali::Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + mCameraActor.SetProperty(Dali::Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); } - window.Add( mCameraActor ); + window.Add(mCameraActor); DALI_ASSERT_ALWAYS(mFrameBuffer && "Framebuffer is NULL."); DALI_ASSERT_ALWAYS(!mRenderTask && "RenderTask is already created."); Dali::RenderTaskList taskList = window.GetRenderTaskList(); - mRenderTask = taskList.CreateTask(); - mRenderTask.SetRefreshRate( Dali::RenderTask::REFRESH_ONCE ); - mRenderTask.SetSourceActor( source ); - mRenderTask.SetCameraActor( mCameraActor ); - mRenderTask.SetScreenToFrameBufferFunction( Dali::RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION ); - mRenderTask.SetFrameBuffer( mFrameBuffer ); - mRenderTask.SetClearColor( clearColor ); - mRenderTask.SetClearEnabled( true ); - mRenderTask.SetProperty( Dali::RenderTask::Property::REQUIRES_SYNC, true ); - mRenderTask.FinishedSignal().Connect( this, &Capture::OnRenderFinished ); - mRenderTask.GetCameraActor().SetInvertYAxis( true ); - - mTimer = Dali::Timer::New( TIME_OUT_DURATION ); - mTimer.TickSignal().Connect( this, &Capture::OnTimeOut ); + mRenderTask = taskList.CreateTask(); + mRenderTask.SetRefreshRate(Dali::RenderTask::REFRESH_ONCE); + mRenderTask.SetSourceActor(source); + mRenderTask.SetCameraActor(mCameraActor); + mRenderTask.SetScreenToFrameBufferFunction(Dali::RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION); + mRenderTask.SetFrameBuffer(mFrameBuffer); + mRenderTask.SetClearColor(clearColor); + mRenderTask.SetClearEnabled(true); + mRenderTask.SetProperty(Dali::RenderTask::Property::REQUIRES_SYNC, true); + mRenderTask.FinishedSignal().Connect(this, &Capture::OnRenderFinished); + mRenderTask.GetCameraActor().SetInvertYAxis(true); + + mTimer = Dali::Timer::New(TIME_OUT_DURATION); + mTimer.TickSignal().Connect(this, &Capture::OnTimeOut); mTimer.Start(); } @@ -229,11 +226,11 @@ void Capture::UnsetRenderTask() mCameraActor.Unparent(); mCameraActor.Reset(); - DALI_ASSERT_ALWAYS( mRenderTask && "RenderTask is NULL." ); + DALI_ASSERT_ALWAYS(mRenderTask && "RenderTask is NULL."); - Dali::Window window = DevelWindow::Get( mSource ); + Dali::Window window = DevelWindow::Get(mSource); Dali::RenderTaskList taskList = window.GetRenderTaskList(); - taskList.RemoveTask( mRenderTask ); + taskList.RemoveTask(mRenderTask); mRenderTask.Reset(); mSource.Reset(); } @@ -243,45 +240,45 @@ bool Capture::IsRenderTaskSetup() return mCameraActor && mRenderTask; } -void Capture::SetupResources( const Dali::Vector2& position, const Dali::Vector2& size, const Dali::Vector4& clearColor, Dali::Actor source ) +void Capture::SetupResources(const Dali::Vector2& position, const Dali::Vector2& size, const Dali::Vector4& clearColor, Dali::Actor source) { - CreateNativeImageSource( size ); + CreateNativeImageSource(size); CreateFrameBuffer(); - SetupRenderTask( position, size, source, clearColor ); + SetupRenderTask(position, size, source, clearColor); } void Capture::UnsetResources() { - if( IsRenderTaskSetup() ) + if(IsRenderTaskSetup()) { UnsetRenderTask(); } - if( IsFrameBufferCreated() ) + if(IsFrameBufferCreated()) { DeleteFrameBuffer(); } } -void Capture::OnRenderFinished( Dali::RenderTask& task ) +void Capture::OnRenderFinished(Dali::RenderTask& task) { Dali::Capture::FinishState state = Dali::Capture::FinishState::SUCCEEDED; mTimer.Stop(); - if( mFileSave ) + if(mFileSave) { - if( !SaveFile() ) + if(!SaveFile()) { state = Dali::Capture::FinishState::FAILED; - DALI_LOG_ERROR( "Fail to Capture Path[%s]", mPath.c_str() ); + DALI_LOG_ERROR("Fail to Capture Path[%s]", mPath.c_str()); } } - Dali::Capture handle( this ); - mFinishedSignal.Emit( handle, state ); + Dali::Capture handle(this); + mFinishedSignal.Emit(handle, state); UnsetResources(); @@ -293,8 +290,8 @@ bool Capture::OnTimeOut() { Dali::Capture::FinishState state = Dali::Capture::FinishState::FAILED; - Dali::Capture handle( this ); - mFinishedSignal.Emit( handle, state ); + Dali::Capture handle(this); + mFinishedSignal.Emit(handle, state); UnsetResources(); @@ -308,11 +305,11 @@ bool Capture::SaveFile() { DALI_ASSERT_ALWAYS(mNativeImageSourcePtr && "mNativeImageSourcePtr is NULL"); - return Dali::DevelNativeImageSource::EncodeToFile( *mNativeImageSourcePtr, mPath, mQuality ); + return Dali::DevelNativeImageSource::EncodeToFile(*mNativeImageSourcePtr, mPath, mQuality); } -} // End of namespace Adaptor +} // End of namespace Adaptor -} // End of namespace Internal +} // End of namespace Internal -} // End of namespace Dali +} // End of namespace Dali diff --git a/dali/internal/system/common/capture-impl.h b/dali/internal/system/common/capture-impl.h index 00281e1..c8595c4 100644 --- a/dali/internal/system/common/capture-impl.h +++ b/dali/internal/system/common/capture-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_CAPTURE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,36 +19,32 @@ */ // EXTERNAL INCLUDES -#include -#include -#include #include +#include #include -#include #include +#include +#include +#include // INTERNAL INCLUDES -#include -#include #include #include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - class Capture; typedef IntrusivePtr CapturePtr; class Capture : public BaseObject, public ConnectionTracker { public: - static constexpr uint32_t DEFAULT_QUALITY = 100; /** @@ -56,7 +52,7 @@ public: */ Capture(); - Capture( Dali::CameraActor cameraActor ); + Capture(Dali::CameraActor cameraActor); /** * @copydoc Dali::Capture::New @@ -66,22 +62,22 @@ public: /** * @copydoc Dali::Capture::New */ - static CapturePtr New( Dali::CameraActor cameraActor ); + static CapturePtr New(Dali::CameraActor cameraActor); /** * @copydoc Dali::Capture::Start */ - void Start( Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string &path, const Dali::Vector4& clearColor, const uint32_t quality ); + void Start(Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string& path, const Dali::Vector4& clearColor, const uint32_t quality); /** * @copydoc Dali::Capture::Start */ - void Start( Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string &path, const Dali::Vector4& clearColor ); + void Start(Dali::Actor source, const Dali::Vector2& position, const Dali::Vector2& size, const std::string& path, const Dali::Vector4& clearColor); /** * @copydoc Dali::Capture::SetImageQuality */ - void SetImageQuality( uint32_t quality ); + void SetImageQuality(uint32_t quality); /** * @copydoc Dali::Capture::GetNativeImageSource @@ -94,7 +90,6 @@ public: Dali::Capture::CaptureFinishedSignalType& FinishedSignal(); protected: - /** * @brief A reference counted object may only be deleted by calling Unreference() */ @@ -104,7 +99,7 @@ private: /** * @brief Create native image source. */ - void CreateNativeImageSource( const Dali::Vector2& size ); + void CreateNativeImageSource(const Dali::Vector2& size); /** * @brief Delete native image source. @@ -144,7 +139,7 @@ private: * @param[in] source sub-scene tree to be captured. * @param[in] clearColor background color */ - void SetupRenderTask( const Dali::Vector2& position, const Dali::Vector2& size, Dali::Actor source, const Dali::Vector4& clearColor ); + void SetupRenderTask(const Dali::Vector2& position, const Dali::Vector2& size, Dali::Actor source, const Dali::Vector4& clearColor); /** * @brief Unset render task. @@ -167,7 +162,7 @@ private: * @param[in] clearColor color to clear background surface. * @param[in] source sub-scene tree to be captured. */ - void SetupResources( const Dali::Vector2& position, const Dali::Vector2& size, const Dali::Vector4& clearColor, Dali::Actor source ); + void SetupResources(const Dali::Vector2& position, const Dali::Vector2& size, const Dali::Vector4& clearColor, Dali::Actor source); /** * @brief Unset resources for capture. @@ -179,7 +174,7 @@ private: * * @param[in] task is used for capture. */ - void OnRenderFinished( Dali::RenderTask& task ); + void OnRenderFinished(Dali::RenderTask& task); /** * @brief Callback when timer is finished. @@ -196,50 +191,49 @@ private: bool SaveFile(); private: - // Undefined - Capture( const Capture& ); + Capture(const Capture&); // Undefined - Capture& operator=( const Capture& rhs ); + Capture& operator=(const Capture& rhs); private: - uint32_t mQuality; - Dali::Texture mNativeTexture; - Dali::FrameBuffer mFrameBuffer; - Dali::RenderTask mRenderTask; - Dali::Actor mSource; - Dali::CameraActor mCameraActor; - Dali::Timer mTimer; ///< For timeout. - Dali::Capture::CaptureFinishedSignalType mFinishedSignal; - std::string mPath; - Dali::NativeImageSourcePtr mNativeImageSourcePtr; ///< pointer to surface image - bool mFileSave; + uint32_t mQuality; + Dali::Texture mNativeTexture; + Dali::FrameBuffer mFrameBuffer; + Dali::RenderTask mRenderTask; + Dali::Actor mSource; + Dali::CameraActor mCameraActor; + Dali::Timer mTimer; ///< For timeout. + Dali::Capture::CaptureFinishedSignalType mFinishedSignal; + std::string mPath; + Dali::NativeImageSourcePtr mNativeImageSourcePtr; ///< pointer to surface image + bool mFileSave; }; -} // End of namespace Adaptor -} // End of namespace Internal +} // End of namespace Adaptor +} // End of namespace Internal // Helpers for public-api forwarding methods -inline Internal::Adaptor::Capture& GetImpl( Dali::Capture& captureWorker) +inline Internal::Adaptor::Capture& GetImpl(Dali::Capture& captureWorker) { - DALI_ASSERT_ALWAYS( captureWorker && "Capture handle is empty" ); + DALI_ASSERT_ALWAYS(captureWorker && "Capture handle is empty"); BaseObject& handle = captureWorker.GetBaseObject(); - return static_cast< Internal::Adaptor::Capture& >( handle ); + return static_cast(handle); } -inline const Internal::Adaptor::Capture& GetImpl( const Dali::Capture& captureWorker ) +inline const Internal::Adaptor::Capture& GetImpl(const Dali::Capture& captureWorker) { - DALI_ASSERT_ALWAYS( captureWorker && "Capture handle is empty" ); + DALI_ASSERT_ALWAYS(captureWorker && "Capture handle is empty"); const BaseObject& handle = captureWorker.GetBaseObject(); - return static_cast< const Internal::Adaptor::Capture& >( handle ); + return static_cast(handle); } -} // End of namespace Dali +} // End of namespace Dali #endif // DALI_INTERNAL_CAPTURE_H diff --git a/dali/internal/system/common/color-controller-impl.cpp b/dali/internal/system/common/color-controller-impl.cpp index 242696d..d2921ca 100644 --- a/dali/internal/system/common/color-controller-impl.cpp +++ b/dali/internal/system/common/color-controller-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,43 +19,40 @@ #include // EXTERNAL INCLUDES -#include +#include #include #include -#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { -const char* COLOR_CONTROLLER_PLUGIN_SO( "libdali2-color-controller-plugin.so" ); +const char* COLOR_CONTROLLER_PLUGIN_SO("libdali2-color-controller-plugin.so"); } Dali::ColorController ColorController::Get() { Dali::ColorController colorController; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::ColorController ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::ColorController)); if(handle) { // If so, downcast the handle - colorController = Dali::ColorController( dynamic_cast< ColorController* >( handle.GetObjectPtr() ) ); + colorController = Dali::ColorController(dynamic_cast(handle.GetObjectPtr())); } else { - colorController = Dali::ColorController( new ColorController( ) ); - service.Register( typeid( colorController ), colorController ); + colorController = Dali::ColorController(new ColorController()); + service.Register(typeid(colorController), colorController); } } @@ -63,70 +60,70 @@ Dali::ColorController ColorController::Get() } ColorController::ColorController() -: mLibHandle( NULL ), - mPlugin( NULL ), - mCreateColorControllerPtr( NULL ) +: mLibHandle(NULL), + mPlugin(NULL), + mCreateColorControllerPtr(NULL) { Initialize(); } ColorController::~ColorController() { - if( mPlugin ) + if(mPlugin) { delete mPlugin; mPlugin = NULL; - if( mLibHandle && dlclose( mLibHandle ) ) + if(mLibHandle && dlclose(mLibHandle)) { - DALI_LOG_ERROR( "Error closing color controller plugin library: %s\n", dlerror() ); + DALI_LOG_ERROR("Error closing color controller plugin library: %s\n", dlerror()); } } } void ColorController::Initialize() { - mLibHandle = dlopen( COLOR_CONTROLLER_PLUGIN_SO, RTLD_LAZY ); + mLibHandle = dlopen(COLOR_CONTROLLER_PLUGIN_SO, RTLD_LAZY); char* error = dlerror(); - if( mLibHandle == NULL || error != NULL ) + if(mLibHandle == NULL || error != NULL) { - DALI_LOG_ERROR( "ColorController::Initialize: dlopen error [%s]\n", error ); + DALI_LOG_ERROR("ColorController::Initialize: dlopen error [%s]\n", error); return; } // load plugin - mCreateColorControllerPtr = reinterpret_cast< CreateColorControllerFunction >( dlsym( mLibHandle, "CreateColorControllerPlugin" ) ); + mCreateColorControllerPtr = reinterpret_cast(dlsym(mLibHandle, "CreateColorControllerPlugin")); error = dlerror(); - if( mCreateColorControllerPtr == NULL || error != NULL ) + if(mCreateColorControllerPtr == NULL || error != NULL) { - DALI_LOG_ERROR( "ColorController::Initialize: Cannot load symbol CreateColorControllerPlugin(): %s\n", error ); + DALI_LOG_ERROR("ColorController::Initialize: Cannot load symbol CreateColorControllerPlugin(): %s\n", error); return; } mPlugin = mCreateColorControllerPtr(); - if( !mPlugin ) + if(!mPlugin) { DALI_LOG_ERROR("ColorController::Initialize: Plugin creation failed\n"); return; } } -bool ColorController::RetrieveColor( const std::string& colorCode, Vector4& colorValue ) +bool ColorController::RetrieveColor(const std::string& colorCode, Vector4& colorValue) { - if( mPlugin ) + if(mPlugin) { - return mPlugin->RetrieveColor( colorCode, colorValue ); + return mPlugin->RetrieveColor(colorCode, colorValue); } return false; } -bool ColorController::RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor) +bool ColorController::RetrieveColor(const std::string& colorCode, Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor) { - if( mPlugin ) + if(mPlugin) { - return mPlugin->RetrieveColor( colorCode, textColor, textOutlineColor, textShadowColor ); + return mPlugin->RetrieveColor(colorCode, textColor, textOutlineColor, textShadowColor); } return false; } diff --git a/dali/internal/system/common/color-controller-impl.h b/dali/internal/system/common/color-controller-impl.h index 0efca0a..1ccca54 100644 --- a/dali/internal/system/common/color-controller-impl.h +++ b/dali/internal/system/common/color-controller-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_COLOR_CONTROLLER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,25 +22,21 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Implementation of ColorController */ class ColorController : public BaseObject { public: - /** * Constructor. */ @@ -54,16 +50,15 @@ public: /** * @copydoc Dali::ColorController::RetrieveColor(const std::string&, Vector4&) */ - bool RetrieveColor( const std::string& colorCode, Vector4& colorValue ); + bool RetrieveColor(const std::string& colorCode, Vector4& colorValue); /** * @copydoc Dali::ColorController::RetrieveColor(const std::string&, Vector4&, Vector4&, Vector4&) */ - bool RetrieveColor( const std::string& colorCode , Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor); + bool RetrieveColor(const std::string& colorCode, Vector4& textColor, Vector4& textOutlineColor, Vector4& textShadowColor); private: - - /** + /** * @brief Initialize */ void Initialize(); @@ -75,14 +70,12 @@ protected: ~ColorController() override; private: - using CreateColorControllerFunction = Dali::ColorControllerPlugin* (*)(); - void* mLibHandle; ///< Handle for the loaded library - Dali::ColorControllerPlugin* mPlugin; ///< Plugin handle - - CreateColorControllerFunction mCreateColorControllerPtr; ///< Function pointer called in adaptor to create a plugin instance + void* mLibHandle; ///< Handle for the loaded library + Dali::ColorControllerPlugin* mPlugin; ///< Plugin handle + CreateColorControllerFunction mCreateColorControllerPtr; ///< Function pointer called in adaptor to create a plugin instance }; } // namespace Adaptor diff --git a/dali/internal/system/common/command-line-options.cpp b/dali/internal/system/common/command-line-options.cpp index 52c9412..d22da15 100644 --- a/dali/internal/system/common/command-line-options.cpp +++ b/dali/internal/system/common/command-line-options.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,40 +28,36 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { struct Argument { - const char * const opt; - const char * const optDescription; + const char* const opt; + const char* const optDescription; void Print() { const std::ios_base::fmtflags flags = std::cout.flags(); std::cout << std::left << " --"; - std::cout.width( 18 ); + std::cout.width(18); std::cout << opt; std::cout << optDescription; std::cout << std::endl; - std::cout.flags( flags ); + std::cout.flags(flags); } }; Argument EXPECTED_ARGS[] = -{ - { "width", "Stage Width" }, - { "height", "Stage Height" }, - { "dpi", "Emulated DPI" }, - { "help", "Help" }, - { NULL, NULL } -}; + { + {"width", "Stage Width"}, + {"height", "Stage Height"}, + {"dpi", "Emulated DPI"}, + {"help", "Help"}, + {NULL, NULL}}; enum Option { @@ -71,13 +67,13 @@ enum Option OPTION_HELP }; -typedef Dali::Vector< int32_t > UnhandledContainer; +typedef Dali::Vector UnhandledContainer; void ShowHelp() { std::cout << "Available options:" << std::endl; Argument* arg = EXPECTED_ARGS; - while ( arg->opt ) + while(arg->opt) { arg->Print(); ++arg; @@ -86,51 +82,51 @@ void ShowHelp() } // unnamed namespace -CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) +CommandLineOptions::CommandLineOptions(int32_t* argc, char** argv[]) : stageWidth(0), stageHeight(0) { // Exit gracefully if no arguments provided - if ( !argc || !argv ) + if(!argc || !argv) { return; } - if ( *argc > 1 ) + if(*argc > 1) { // We do not want to print out errors. - int32_t origOptErrValue( opterr ); + int32_t origOptErrValue(opterr); opterr = 0; - int32_t help( 0 ); + int32_t help(0); - const struct option options[]= - { - { EXPECTED_ARGS[OPTION_STAGE_WIDTH].opt, required_argument, NULL, 'w' }, // "--width" - { EXPECTED_ARGS[OPTION_STAGE_HEIGHT].opt, required_argument, NULL, 'h' }, // "--height" - { EXPECTED_ARGS[OPTION_DPI].opt, required_argument, NULL, 'd' }, // "--dpi" - { EXPECTED_ARGS[OPTION_HELP].opt, no_argument, &help, '?' }, // "--help" - { 0, 0, 0, 0 } // end of options - }; + const struct option options[] = + { + {EXPECTED_ARGS[OPTION_STAGE_WIDTH].opt, required_argument, NULL, 'w'}, // "--width" + {EXPECTED_ARGS[OPTION_STAGE_HEIGHT].opt, required_argument, NULL, 'h'}, // "--height" + {EXPECTED_ARGS[OPTION_DPI].opt, required_argument, NULL, 'd'}, // "--dpi" + {EXPECTED_ARGS[OPTION_HELP].opt, no_argument, &help, '?'}, // "--help" + {0, 0, 0, 0} // end of options + }; - int32_t shortOption( 0 ); - int32_t optionIndex( 0 ); + int32_t shortOption(0); + int32_t optionIndex(0); const char* optString = "-w:h:d:"; // The '-' ensures that argv is NOT permuted - bool optionProcessed( false ); + bool optionProcessed(false); UnhandledContainer unhandledOptions; // We store indices of options we do not handle here do { - shortOption = getopt_long( *argc, *argv, optString, options, &optionIndex ); + shortOption = getopt_long(*argc, *argv, optString, options, &optionIndex); - switch ( shortOption ) + switch(shortOption) { case 0: { // Check if we want help - if ( help ) + if(help) { ShowHelp(); optionProcessed = true; @@ -140,9 +136,9 @@ CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) case 'w': { - if ( optarg ) + if(optarg) { - stageWidth = atoi( optarg ); + stageWidth = atoi(optarg); optionProcessed = true; } break; @@ -150,9 +146,9 @@ CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) case 'h': { - if ( optarg ) + if(optarg) { - stageHeight = atoi( optarg ); + stageHeight = atoi(optarg); optionProcessed = true; } break; @@ -160,9 +156,9 @@ CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) case 'd': { - if ( optarg ) + if(optarg) { - stageDPI.assign( optarg ); + stageDPI.assign(optarg); optionProcessed = true; } break; @@ -176,24 +172,24 @@ CommandLineOptions::CommandLineOptions(int32_t *argc, char **argv[]) default: { - unhandledOptions.PushBack( optind - 1 ); + unhandledOptions.PushBack(optind - 1); break; } } - } while ( shortOption != -1 ); + } while(shortOption != -1); // Take out the options we have processed - if ( optionProcessed ) + if(optionProcessed) { - if ( unhandledOptions.Count() > 0 ) + if(unhandledOptions.Count() > 0) { - int32_t index( 1 ); + int32_t index(1); // Overwrite the argv with the values from the unhandled indices const UnhandledContainer::ConstIterator endIter = unhandledOptions.End(); - for ( UnhandledContainer::Iterator iter = unhandledOptions.Begin(); iter != endIter; ++iter ) + for(UnhandledContainer::Iterator iter = unhandledOptions.Begin(); iter != endIter; ++iter) { - (*argv)[ index++ ] = (*argv)[ *iter ]; + (*argv)[index++] = (*argv)[*iter]; } *argc = unhandledOptions.Count() + 1; // +1 for the program name } diff --git a/dali/internal/system/common/command-line-options.h b/dali/internal/system/common/command-line-options.h index 5277ffd..a56b95d 100644 --- a/dali/internal/system/common/command-line-options.h +++ b/dali/internal/system/common/command-line-options.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_COMMAND_LINE_OPTIONS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,15 @@ */ // EXTERNAL INCLUDES -#include #include // int32_t +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Parses the passed command line arguments and sets the values stored within this * class appropriately. @@ -49,24 +46,22 @@ namespace Adaptor struct CommandLineOptions { public: - /** * Constructor * @param[in,out] argc The number of arguments * @param[in,out] argv The argument list * @note Supported options are stripped from argv, and argc is updated appropriately. */ - CommandLineOptions( int32_t *argc, char **argv[] ); + CommandLineOptions(int32_t* argc, char** argv[]); /** * Destructor */ ~CommandLineOptions(); -public: // Command line parsed values - - int32_t stageWidth; ///< The width of the stage required. 0 if not set. - int32_t stageHeight; ///< The height of the stage required. 0 if not set. +public: // Command line parsed values + int32_t stageWidth; ///< The width of the stage required. 0 if not set. + int32_t stageHeight; ///< The height of the stage required. 0 if not set. std::string stageDPI; ///< DPI stored as hxv, where h is horizontal DPI and v is vertical DPI }; diff --git a/dali/internal/system/common/configuration-manager.cpp b/dali/internal/system/common/configuration-manager.cpp index 0276761..dcac08b 100644 --- a/dali/internal/system/common/configuration-manager.cpp +++ b/dali/internal/system/common/configuration-manager.cpp @@ -70,18 +70,18 @@ void ConfigurationManager::RetrieveKeysFromConfigFile(const std::string& configF if(stream.rdbuf()->in_avail()) { std::string line; - while( std::getline( stream, line ) ) + while(std::getline(stream, line)) { - line.erase( line.find_last_not_of( " \t\r\n" ) + 1 ); - line.erase( 0, line.find_first_not_of( " \t\r\n" ) ); - if( '#' == *( line.cbegin() ) || line == "" ) + line.erase(line.find_last_not_of(" \t\r\n") + 1); + line.erase(0, line.find_first_not_of(" \t\r\n")); + if('#' == *(line.cbegin()) || line == "") { continue; } std::istringstream subStream(line); - std::string name; - std::string value; + std::string name; + std::string value; std::getline(subStream, name, ' '); if(!mMaxTextureSizeCached && name == DALI_ENV_MAX_TEXTURE_SIZE) { @@ -154,7 +154,7 @@ uint32_t ConfigurationManager::GetShadingLanguageVersion() } // Query from graphics and save the cache - mShaderLanguageVersion = mGraphics->GetShaderLanguageVersion(); + mShaderLanguageVersion = mGraphics->GetShaderLanguageVersion(); mShaderLanguageVersionCached = true; Dali::FileStream configFile(mSystemCacheFilePath, Dali::FileStream::READ | Dali::FileStream::APPEND | Dali::FileStream::TEXT); diff --git a/dali/internal/system/common/core-event-interface.h b/dali/internal/system/common/core-event-interface.h index d2240e1..c1c8579 100644 --- a/dali/internal/system/common/core-event-interface.h +++ b/dali/internal/system/common/core-event-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_CORE_EVENT_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ namespace Dali { - namespace Integration { struct Event; @@ -28,10 +27,8 @@ struct Event; namespace Internal { - namespace Adaptor { - /** * This interface should be used by adaptor components to send events to Core. * This is preferable to using Core directly i.e. so there is a common place for measuring performance. @@ -39,7 +36,6 @@ namespace Adaptor class CoreEventInterface { public: - /** * Queue an event with Core. * @param[in] event The new event. @@ -52,17 +48,18 @@ public: virtual void ProcessCoreEvents() = 0; protected: - /** * Protected virtual destructor */ - virtual ~CoreEventInterface() {} + virtual ~CoreEventInterface() + { + } }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_CORE_EVENT_INTERFACE_H diff --git a/dali/internal/system/common/environment-options.cpp b/dali/internal/system/common/environment-options.cpp index 996dbd9..8fec77f 100644 --- a/dali/internal/system/common/environment-options.cpp +++ b/dali/internal/system/common/environment-options.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,33 +19,30 @@ #include // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { -const unsigned int DEFAULT_STATISTICS_LOG_FREQUENCY = 2; -const int DEFAULT_MULTI_SAMPLING_LEVEL = -1; -const bool DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING = true; -const bool DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING = true; -const bool DEFAULT_PARTIAL_UPDATE_REQUIRED_SETTING = true; +const unsigned int DEFAULT_STATISTICS_LOG_FREQUENCY = 2; +const int DEFAULT_MULTI_SAMPLING_LEVEL = -1; +const bool DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING = true; +const bool DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING = true; +const bool DEFAULT_PARTIAL_UPDATE_REQUIRED_SETTING = true; -unsigned int GetEnvironmentVariable( const char* variable, unsigned int defaultValue ) +unsigned int GetEnvironmentVariable(const char* variable, unsigned int defaultValue) { const char* variableParameter = std::getenv(variable); @@ -54,11 +51,11 @@ unsigned int GetEnvironmentVariable( const char* variable, unsigned int defaultV return intValue; } -bool GetEnvironmentVariable( const char* variable, int& intValue ) +bool GetEnvironmentVariable(const char* variable, int& intValue) { const char* variableParameter = std::getenv(variable); - if( !variableParameter ) + if(!variableParameter) { return false; } @@ -67,11 +64,11 @@ bool GetEnvironmentVariable( const char* variable, int& intValue ) return true; } -bool GetEnvironmentVariable( const char* variable, float& floatValue ) +bool GetEnvironmentVariable(const char* variable, float& floatValue) { const char* variableParameter = std::getenv(variable); - if( !variableParameter ) + if(!variableParameter) { return false; } @@ -82,7 +79,7 @@ bool GetEnvironmentVariable( const char* variable, float& floatValue ) void SetFromEnvironmentVariable(const char* variable, std::string& stringValue) { - const char * charValue = std::getenv( variable ); + const char* charValue = std::getenv(variable); if(charValue) { stringValue = charValue; @@ -136,7 +133,7 @@ struct ClampBetweenZeroAndOne void operator()(float value) { - value = Clamp(value, 0.0f, 1.0f); + value = Clamp(value, 0.0f, 1.0f); mMemberValue = value; } @@ -161,17 +158,20 @@ struct GreaterThan } unsigned int& mMemberValue; - const int mGreaterThanValue; + const int mGreaterThanValue; }; /// Provides a functor which sets the member to 1 if if the environment variable value is not zero struct EnableIfNonZero { - EnableIfNonZero(int& memberValue) : mMemberValue(memberValue) {} + EnableIfNonZero(int& memberValue) + : mMemberValue(memberValue) + { + } void operator()(int value) { - mMemberValue = ( value == 0 ) ? 0 : 1; + mMemberValue = (value == 0) ? 0 : 1; } int& mMemberValue; @@ -180,11 +180,14 @@ struct EnableIfNonZero /// Provides a functor which sets the member to false if the environment variable value is not zero struct DisableIfNonZero { - DisableIfNonZero(bool& memberValue) : mMemberValue(memberValue) {} + DisableIfNonZero(bool& memberValue) + : mMemberValue(memberValue) + { + } void operator()(int value) { - if( value > 0 ) + if(value > 0) { mMemberValue = false; } @@ -193,56 +196,55 @@ struct DisableIfNonZero bool& mMemberValue; }; - } // unnamed namespace EnvironmentOptions::EnvironmentOptions() -: mLogFunction( NULL ), +: mLogFunction(NULL), mWindowName(), mWindowClassName(), - mNetworkControl( 0 ), - mFpsFrequency( 0 ), - mUpdateStatusFrequency( 0 ), - mObjectProfilerInterval( 0 ), - mPerformanceStatsLevel( 0 ), - mPerformanceStatsFrequency( DEFAULT_STATISTICS_LOG_FREQUENCY ), - mPerformanceTimeStampOutput( 0 ), - mPanGestureLoggingLevel( 0 ), - mWindowWidth( 0u ), - mWindowHeight( 0u ), - mRenderRefreshRate( 1u ), - mMaxTextureSize( 0 ), - mRenderToFboInterval( 0u ), - mPanGesturePredictionMode( -1 ), - mPanGesturePredictionAmount( -1 ), ///< only sets value in pan gesture if greater than 0 - mPanGestureMaxPredictionAmount( -1 ), - mPanGestureMinPredictionAmount( -1 ), - mPanGesturePredictionAmountAdjustment( -1 ), - mPanGestureSmoothingMode( -1 ), - mPanGestureSmoothingAmount( -1.0f ), - mPanGestureUseActualTimes( -1 ), - mPanGestureInterpolationTimeRange( -1 ), - mPanGestureScalarOnlyPredictionEnabled( -1 ), - mPanGestureTwoPointPredictionEnabled( -1 ), - mPanGestureTwoPointInterpolatePastTime( -1 ), - mPanGestureTwoPointVelocityBias( -1.0f ), - mPanGestureTwoPointAccelerationBias( -1.0f ), - mPanGestureMultitapSmoothingRange( -1 ), - mPanMinimumDistance( -1 ), - mPanMinimumEvents( -1 ), - mPinchMinimumDistance( -1.0f ), - mPinchMinimumTouchEvents( -1 ), - mPinchMinimumTouchEventsAfterStart( -1 ), - mRotationMinimumTouchEvents( -1 ), - mRotationMinimumTouchEventsAfterStart( -1 ), - mLongPressMinimumHoldingTime( -1 ), - mGlesCallTime( 0 ), - mMultiSamplingLevel( DEFAULT_MULTI_SAMPLING_LEVEL ), - mThreadingMode( ThreadingMode::COMBINED_UPDATE_RENDER ), - mGlesCallAccumulate( false ), - mDepthBufferRequired( DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING ), - mStencilBufferRequired( DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING ), - mPartialUpdateRequired( DEFAULT_PARTIAL_UPDATE_REQUIRED_SETTING ) + mNetworkControl(0), + mFpsFrequency(0), + mUpdateStatusFrequency(0), + mObjectProfilerInterval(0), + mPerformanceStatsLevel(0), + mPerformanceStatsFrequency(DEFAULT_STATISTICS_LOG_FREQUENCY), + mPerformanceTimeStampOutput(0), + mPanGestureLoggingLevel(0), + mWindowWidth(0u), + mWindowHeight(0u), + mRenderRefreshRate(1u), + mMaxTextureSize(0), + mRenderToFboInterval(0u), + mPanGesturePredictionMode(-1), + mPanGesturePredictionAmount(-1), ///< only sets value in pan gesture if greater than 0 + mPanGestureMaxPredictionAmount(-1), + mPanGestureMinPredictionAmount(-1), + mPanGesturePredictionAmountAdjustment(-1), + mPanGestureSmoothingMode(-1), + mPanGestureSmoothingAmount(-1.0f), + mPanGestureUseActualTimes(-1), + mPanGestureInterpolationTimeRange(-1), + mPanGestureScalarOnlyPredictionEnabled(-1), + mPanGestureTwoPointPredictionEnabled(-1), + mPanGestureTwoPointInterpolatePastTime(-1), + mPanGestureTwoPointVelocityBias(-1.0f), + mPanGestureTwoPointAccelerationBias(-1.0f), + mPanGestureMultitapSmoothingRange(-1), + mPanMinimumDistance(-1), + mPanMinimumEvents(-1), + mPinchMinimumDistance(-1.0f), + mPinchMinimumTouchEvents(-1), + mPinchMinimumTouchEventsAfterStart(-1), + mRotationMinimumTouchEvents(-1), + mRotationMinimumTouchEventsAfterStart(-1), + mLongPressMinimumHoldingTime(-1), + mGlesCallTime(0), + mMultiSamplingLevel(DEFAULT_MULTI_SAMPLING_LEVEL), + mThreadingMode(ThreadingMode::COMBINED_UPDATE_RENDER), + mGlesCallAccumulate(false), + mDepthBufferRequired(DEFAULT_DEPTH_BUFFER_REQUIRED_SETTING), + mStencilBufferRequired(DEFAULT_STENCIL_BUFFER_REQUIRED_SETTING), + mPartialUpdateRequired(DEFAULT_PARTIAL_UPDATE_REQUIRED_SETTING) { ParseEnvironmentOptions(); } @@ -251,27 +253,27 @@ EnvironmentOptions::~EnvironmentOptions() { } -void EnvironmentOptions::CreateTraceManager( PerformanceInterface* performanceInterface ) +void EnvironmentOptions::CreateTraceManager(PerformanceInterface* performanceInterface) { - mTraceManager = TraceManagerFactory::CreateTraceFactory( performanceInterface ); + mTraceManager = TraceManagerFactory::CreateTraceFactory(performanceInterface); } void EnvironmentOptions::InstallTraceFunction() const { - if( mTraceManager ) + if(mTraceManager) { mTraceManager->Initialise(); } } -void EnvironmentOptions::SetLogFunction( const Dali::Integration::Log::LogFunction& logFunction ) +void EnvironmentOptions::SetLogFunction(const Dali::Integration::Log::LogFunction& logFunction) { mLogFunction = logFunction; } void EnvironmentOptions::InstallLogFunction() const { - Dali::Integration::Log::InstallLogFunction( mLogFunction ); + Dali::Integration::Log::InstallLogFunction(mLogFunction); } void EnvironmentOptions::UnInstallLogFunction() const @@ -488,9 +490,9 @@ unsigned int EnvironmentOptions::GetRenderToFboInterval() const bool EnvironmentOptions::PerformanceServerRequired() const { - return ( ( GetPerformanceStatsLoggingOptions() > 0) || - ( GetPerformanceTimeStampOutput() > 0 ) || - ( GetNetworkControlMode() > 0) ); + return ((GetPerformanceStatsLoggingOptions() > 0) || + (GetPerformanceTimeStampOutput() > 0) || + (GetNetworkControlMode() > 0)); } bool EnvironmentOptions::DepthBufferRequired() const @@ -511,22 +513,21 @@ bool EnvironmentOptions::PartialUpdateRequired() const void EnvironmentOptions::ParseEnvironmentOptions() { // get logging options - mFpsFrequency = GetEnvironmentVariable( DALI_ENV_FPS_TRACKING, 0 ); - mUpdateStatusFrequency = GetEnvironmentVariable( DALI_ENV_UPDATE_STATUS_INTERVAL, 0 ); - mObjectProfilerInterval = GetEnvironmentVariable( DALI_ENV_OBJECT_PROFILER_INTERVAL, 0 ); - mPerformanceStatsLevel = GetEnvironmentVariable( DALI_ENV_LOG_PERFORMANCE_STATS, 0 ); - mPerformanceStatsFrequency = GetEnvironmentVariable( DALI_ENV_LOG_PERFORMANCE_STATS_FREQUENCY, 0 ); - mPerformanceTimeStampOutput = GetEnvironmentVariable( DALI_ENV_PERFORMANCE_TIMESTAMP_OUTPUT, 0 ); - mNetworkControl = GetEnvironmentVariable( DALI_ENV_NETWORK_CONTROL, 0 ); - mPanGestureLoggingLevel = GetEnvironmentVariable( DALI_ENV_LOG_PAN_GESTURE, 0 ); + mFpsFrequency = GetEnvironmentVariable(DALI_ENV_FPS_TRACKING, 0); + mUpdateStatusFrequency = GetEnvironmentVariable(DALI_ENV_UPDATE_STATUS_INTERVAL, 0); + mObjectProfilerInterval = GetEnvironmentVariable(DALI_ENV_OBJECT_PROFILER_INTERVAL, 0); + mPerformanceStatsLevel = GetEnvironmentVariable(DALI_ENV_LOG_PERFORMANCE_STATS, 0); + mPerformanceStatsFrequency = GetEnvironmentVariable(DALI_ENV_LOG_PERFORMANCE_STATS_FREQUENCY, 0); + mPerformanceTimeStampOutput = GetEnvironmentVariable(DALI_ENV_PERFORMANCE_TIMESTAMP_OUTPUT, 0); + mNetworkControl = GetEnvironmentVariable(DALI_ENV_NETWORK_CONTROL, 0); + mPanGestureLoggingLevel = GetEnvironmentVariable(DALI_ENV_LOG_PAN_GESTURE, 0); SetFromEnvironmentVariable(DALI_ENV_PAN_PREDICTION_MODE, mPanGesturePredictionMode); SetFromEnvironmentVariable(DALI_ENV_PAN_PREDICTION_AMOUNT, MinimumZero(mPanGesturePredictionAmount)); SetFromEnvironmentVariable(DALI_ENV_PAN_MIN_PREDICTION_AMOUNT, MinimumZero(mPanGestureMinPredictionAmount)); SetFromEnvironmentVariable(DALI_ENV_PAN_MAX_PREDICTION_AMOUNT, - [&](int maxPredictionAmount) - { - if( mPanGestureMinPredictionAmount > -1 && maxPredictionAmount < mPanGestureMinPredictionAmount ) + [&](int maxPredictionAmount) { + if(mPanGestureMinPredictionAmount > -1 && maxPredictionAmount < mPanGestureMinPredictionAmount) { // maximum amount should not be smaller than minimum amount maxPredictionAmount = mPanGestureMinPredictionAmount; @@ -560,22 +561,21 @@ void EnvironmentOptions::ParseEnvironmentOptions() SetFromEnvironmentVariable(DALI_GLES_CALL_ACCUMULATE, [&](int glesCallAccumulate) { mGlesCallAccumulate = glesCallAccumulate != 0; }); int windowWidth(0), windowHeight(0); - if ( GetEnvironmentVariable( DALI_WINDOW_WIDTH, windowWidth ) && GetEnvironmentVariable( DALI_WINDOW_HEIGHT, windowHeight ) ) + if(GetEnvironmentVariable(DALI_WINDOW_WIDTH, windowWidth) && GetEnvironmentVariable(DALI_WINDOW_HEIGHT, windowHeight)) { - mWindowWidth = windowWidth; + mWindowWidth = windowWidth; mWindowHeight = windowHeight; } - SetFromEnvironmentVariable(DALI_WINDOW_NAME, mWindowName ); + SetFromEnvironmentVariable(DALI_WINDOW_NAME, mWindowName); SetFromEnvironmentVariable(DALI_WINDOW_CLASS_NAME, mWindowClassName); SetFromEnvironmentVariable(DALI_THREADING_MODE, - [&](int threadingMode) - { - switch( threadingMode ) + [&](int threadingMode) { + switch(threadingMode) { case ThreadingMode::COMBINED_UPDATE_RENDER: { - mThreadingMode = static_cast< ThreadingMode::Type >( threadingMode ); + mThreadingMode = static_cast(threadingMode); break; } } @@ -587,14 +587,13 @@ void EnvironmentOptions::ParseEnvironmentOptions() SetFromEnvironmentVariable(DALI_ENV_MAX_TEXTURE_SIZE, GreaterThan(mMaxTextureSize, 0)); - mRenderToFboInterval = GetEnvironmentVariable( DALI_RENDER_TO_FBO, 0u ); + mRenderToFboInterval = GetEnvironmentVariable(DALI_RENDER_TO_FBO, 0u); SetFromEnvironmentVariable(DALI_ENV_DISABLE_DEPTH_BUFFER, - [&](int depthBufferRequired) - { - if( depthBufferRequired > 0 ) + [&](int depthBufferRequired) { + if(depthBufferRequired > 0) { - mDepthBufferRequired = false; + mDepthBufferRequired = false; mStencilBufferRequired = false; // Disable stencil buffer as well } }); @@ -603,8 +602,8 @@ void EnvironmentOptions::ParseEnvironmentOptions() SetFromEnvironmentVariable(DALI_ENV_DISABLE_PARTIAL_UPDATE, DisableIfNonZero(mPartialUpdateRequired)); } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/system/common/environment-options.h b/dali/internal/system/common/environment-options.h index 547adfa..0b4e44c 100644 --- a/dali/internal/system/common/environment-options.h +++ b/dali/internal/system/common/environment-options.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -43,7 +43,6 @@ class PerformanceInterface; class EnvironmentOptions : public Dali::LogFactoryInterface { public: - /** * Constructor */ @@ -58,7 +57,7 @@ public: * Create a TraceManager which is used for tracing. * @param PerformanceInterface for using network logging for tracing on Ubuntu */ - void CreateTraceManager( PerformanceInterface* performanceInterface ); + void CreateTraceManager(PerformanceInterface* performanceInterface); /** * Initialize TraceManager by installing Trace function. @@ -68,7 +67,7 @@ public: /** * @param logFunction logging function */ - void SetLogFunction( const Dali::Integration::Log::LogFunction& logFunction ); + void SetLogFunction(const Dali::Integration::Log::LogFunction& logFunction); /** * Install the log function for the current thread. @@ -322,19 +321,18 @@ public: bool PartialUpdateRequired() const; /// Deleted copy constructor. - EnvironmentOptions( const EnvironmentOptions& ) = delete; + EnvironmentOptions(const EnvironmentOptions&) = delete; /// Deleted move constructor. - EnvironmentOptions( const EnvironmentOptions&& ) = delete; + EnvironmentOptions(const EnvironmentOptions&&) = delete; /// Deleted assignment operator. - EnvironmentOptions& operator=( const EnvironmentOptions& ) = delete; + EnvironmentOptions& operator=(const EnvironmentOptions&) = delete; /// Deleted move assignment operator. - EnvironmentOptions& operator=( const EnvironmentOptions&& ) = delete; + EnvironmentOptions& operator=(const EnvironmentOptions&&) = delete; private: // Internal - /** * Parses the environment options. * Called from the constructor @@ -342,58 +340,63 @@ private: // Internal void ParseEnvironmentOptions(); private: // Data - Dali::Integration::Log::LogFunction mLogFunction; - std::string mWindowName; ///< name of the window - std::string mWindowClassName; ///< name of the class the window belongs to - unsigned int mNetworkControl; ///< whether network control is enabled - unsigned int mFpsFrequency; ///< how often fps is logged out in seconds - unsigned int mUpdateStatusFrequency; ///< how often update status is logged out in frames - unsigned int mObjectProfilerInterval; ///< how often object counts are logged out in seconds - unsigned int mPerformanceStatsLevel; ///< performance statistics logging bitmask - unsigned int mPerformanceStatsFrequency; ///< performance statistics logging frequency (seconds) - unsigned int mPerformanceTimeStampOutput; ///< performance time stamp output ( bitmask) - unsigned int mPanGestureLoggingLevel; ///< pan-gesture log level - unsigned int mWindowWidth; ///< width of the window - unsigned int mWindowHeight; ///< height of the window - unsigned int mRenderRefreshRate; ///< render refresh rate - unsigned int mMaxTextureSize; ///< The maximum texture size that GL can handle - unsigned int mRenderToFboInterval; ///< The number of frames that are going to be rendered into the Frame Buffer Object but the last one which is going to be rendered into the Frame Buffer. - int mPanGesturePredictionMode; ///< prediction mode for pan gestures - int mPanGesturePredictionAmount; ///< prediction amount for pan gestures - int mPanGestureMaxPredictionAmount; ///< maximum prediction amount for pan gestures - int mPanGestureMinPredictionAmount; ///< minimum prediction amount for pan gestures - int mPanGesturePredictionAmountAdjustment; ///< adjustment of prediction amount for pan gestures - int mPanGestureSmoothingMode; ///< prediction mode for pan gestures - float mPanGestureSmoothingAmount; ///< prediction amount for pan gestures - int mPanGestureUseActualTimes; ///< Disable to optionally override actual times if they make results worse. - int mPanGestureInterpolationTimeRange; ///< Time into past history (ms) to use points to interpolate the first point. - int mPanGestureScalarOnlyPredictionEnabled; ///< If enabled, prediction is done using velocity alone (no integration or acceleration). - int mPanGestureTwoPointPredictionEnabled; ///< If enabled, a second interpolated point is predicted and combined with the first to get more stable values. - int mPanGestureTwoPointInterpolatePastTime; ///< The target time in the past to generate the second interpolated point. - float mPanGestureTwoPointVelocityBias; ///< The ratio of first and second interpolated points to use for velocity. 0.0f = 100% of first point. 1.0f = 100% of second point. - float mPanGestureTwoPointAccelerationBias; ///< The ratio of first and second interpolated points to use for acceleration. 0.0f = 100% of first point. 1.0f = 100% of second point. - int mPanGestureMultitapSmoothingRange; ///< The range in time (ms) of points in the history to smooth the final output against. - int mPanMinimumDistance; ///< minimum distance required before pan starts - int mPanMinimumEvents; ///< minimum events required before pan starts - float mPinchMinimumDistance; ///< minimum number of pixels moved before a pinch starts - int mPinchMinimumTouchEvents; ///< minimum events required before a pinch starts - int mPinchMinimumTouchEventsAfterStart; ///< minimum events required after a pinch started - int mRotationMinimumTouchEvents; ///< minimum events required before a rotation starts - int mRotationMinimumTouchEventsAfterStart; ///< minimum events required after a rotation started - int mLongPressMinimumHoldingTime; ///< minimum holding time required to be recognized as a long press gesture (millisecond) - int mGlesCallTime; ///< time in seconds between status updates - int mMultiSamplingLevel; ///< The number of samples required in multisample buffers - ThreadingMode::Type mThreadingMode; ///< threading mode - bool mGlesCallAccumulate; ///< Whether or not to accumulate gles call statistics - bool mDepthBufferRequired; ///< Whether the depth buffer is required - bool mStencilBufferRequired; ///< Whether the stencil buffer is required - bool mPartialUpdateRequired; ///< Whether the partial update is required - std::unique_ptr mTraceManager; ///< TraceManager + + std::string mWindowName; ///< name of the window + std::string mWindowClassName; ///< name of the class the window belongs to + + unsigned int mNetworkControl; ///< whether network control is enabled + unsigned int mFpsFrequency; ///< how often fps is logged out in seconds + unsigned int mUpdateStatusFrequency; ///< how often update status is logged out in frames + unsigned int mObjectProfilerInterval; ///< how often object counts are logged out in seconds + unsigned int mPerformanceStatsLevel; ///< performance statistics logging bitmask + unsigned int mPerformanceStatsFrequency; ///< performance statistics logging frequency (seconds) + unsigned int mPerformanceTimeStampOutput; ///< performance time stamp output ( bitmask) + unsigned int mPanGestureLoggingLevel; ///< pan-gesture log level + unsigned int mWindowWidth; ///< width of the window + unsigned int mWindowHeight; ///< height of the window + unsigned int mRenderRefreshRate; ///< render refresh rate + unsigned int mMaxTextureSize; ///< The maximum texture size that GL can handle + unsigned int mRenderToFboInterval; ///< The number of frames that are going to be rendered into the Frame Buffer Object but the last one which is going to be rendered into the Frame Buffer. + + int mPanGesturePredictionMode; ///< prediction mode for pan gestures + int mPanGesturePredictionAmount; ///< prediction amount for pan gestures + int mPanGestureMaxPredictionAmount; ///< maximum prediction amount for pan gestures + int mPanGestureMinPredictionAmount; ///< minimum prediction amount for pan gestures + int mPanGesturePredictionAmountAdjustment; ///< adjustment of prediction amount for pan gestures + int mPanGestureSmoothingMode; ///< prediction mode for pan gestures + float mPanGestureSmoothingAmount; ///< prediction amount for pan gestures + int mPanGestureUseActualTimes; ///< Disable to optionally override actual times if they make results worse. + int mPanGestureInterpolationTimeRange; ///< Time into past history (ms) to use points to interpolate the first point. + int mPanGestureScalarOnlyPredictionEnabled; ///< If enabled, prediction is done using velocity alone (no integration or acceleration). + int mPanGestureTwoPointPredictionEnabled; ///< If enabled, a second interpolated point is predicted and combined with the first to get more stable values. + int mPanGestureTwoPointInterpolatePastTime; ///< The target time in the past to generate the second interpolated point. + float mPanGestureTwoPointVelocityBias; ///< The ratio of first and second interpolated points to use for velocity. 0.0f = 100% of first point. 1.0f = 100% of second point. + float mPanGestureTwoPointAccelerationBias; ///< The ratio of first and second interpolated points to use for acceleration. 0.0f = 100% of first point. 1.0f = 100% of second point. + int mPanGestureMultitapSmoothingRange; ///< The range in time (ms) of points in the history to smooth the final output against. + int mPanMinimumDistance; ///< minimum distance required before pan starts + int mPanMinimumEvents; ///< minimum events required before pan starts + float mPinchMinimumDistance; ///< minimum number of pixels moved before a pinch starts + int mPinchMinimumTouchEvents; ///< minimum events required before a pinch starts + int mPinchMinimumTouchEventsAfterStart; ///< minimum events required after a pinch started + int mRotationMinimumTouchEvents; ///< minimum events required before a rotation starts + int mRotationMinimumTouchEventsAfterStart; ///< minimum events required after a rotation started + int mLongPressMinimumHoldingTime; ///< minimum holding time required to be recognized as a long press gesture (millisecond) + int mGlesCallTime; ///< time in seconds between status updates + int mMultiSamplingLevel; ///< The number of samples required in multisample buffers + + ThreadingMode::Type mThreadingMode; ///< threading mode + + bool mGlesCallAccumulate; ///< Whether or not to accumulate gles call statistics + bool mDepthBufferRequired; ///< Whether the depth buffer is required + bool mStencilBufferRequired; ///< Whether the stencil buffer is required + bool mPartialUpdateRequired; ///< Whether the partial update is required + + std::unique_ptr mTraceManager; ///< TraceManager }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_ENVIRONMENT_OPTIONS_H diff --git a/dali/internal/system/common/environment-variables.h b/dali/internal/system/common/environment-variables.h old mode 100755 new mode 100644 index 542afba..022cd14 --- a/dali/internal/system/common/environment-variables.h +++ b/dali/internal/system/common/environment-variables.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_ENVIRONMENT_VARIABLES_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * What performance statistics are logged out to dlog * see StatisticsLogOptions in performance-interface.h for values @@ -59,44 +56,44 @@ namespace Adaptor // Pan-Gesture configuration: // Prediction Modes 1 & 2: -#define DALI_ENV_PAN_PREDICTION_MODE "DALI_PAN_PREDICTION_MODE" -#define DALI_ENV_PAN_PREDICTION_AMOUNT "DALI_PAN_PREDICTION_AMOUNT" -#define DALI_ENV_PAN_SMOOTHING_MODE "DALI_PAN_SMOOTHING_MODE" +#define DALI_ENV_PAN_PREDICTION_MODE "DALI_PAN_PREDICTION_MODE" +#define DALI_ENV_PAN_PREDICTION_AMOUNT "DALI_PAN_PREDICTION_AMOUNT" +#define DALI_ENV_PAN_SMOOTHING_MODE "DALI_PAN_SMOOTHING_MODE" // Prediction Mode 1: -#define DALI_ENV_PAN_MAX_PREDICTION_AMOUNT "DALI_PAN_MAX_PREDICTION_AMOUNT" -#define DALI_ENV_PAN_MIN_PREDICTION_AMOUNT "DALI_PAN_MIN_PREDICTION_AMOUNT" -#define DALI_ENV_PAN_PREDICTION_AMOUNT_ADJUSTMENT "DALI_PAN_PREDICTION_AMOUNT_ADJUSTMENT" -#define DALI_ENV_PAN_SMOOTHING_AMOUNT "DALI_PAN_SMOOTHING_AMOUNT" +#define DALI_ENV_PAN_MAX_PREDICTION_AMOUNT "DALI_PAN_MAX_PREDICTION_AMOUNT" +#define DALI_ENV_PAN_MIN_PREDICTION_AMOUNT "DALI_PAN_MIN_PREDICTION_AMOUNT" +#define DALI_ENV_PAN_PREDICTION_AMOUNT_ADJUSTMENT "DALI_PAN_PREDICTION_AMOUNT_ADJUSTMENT" +#define DALI_ENV_PAN_SMOOTHING_AMOUNT "DALI_PAN_SMOOTHING_AMOUNT" // Prediction Mode 2: -#define DALI_ENV_PAN_USE_ACTUAL_TIMES "DALI_PAN_USE_ACTUAL_TIMES" -#define DALI_ENV_PAN_INTERPOLATION_TIME_RANGE "DALI_PAN_INTERPOLATION_TIME_RANGE" -#define DALI_ENV_PAN_SCALAR_ONLY_PREDICTION_ENABLED "DALI_PAN_SCALAR_ONLY_PREDICTION_ENABLED" -#define DALI_ENV_PAN_TWO_POINT_PREDICTION_ENABLED "DALI_PAN_TWO_POINT_PREDICTION_ENABLED" -#define DALI_ENV_PAN_TWO_POINT_PAST_INTERPOLATE_TIME "DALI_PAN_TWO_POINT_PAST_INTERPOLATE_TIME" -#define DALI_ENV_PAN_TWO_POINT_VELOCITY_BIAS "DALI_PAN_TWO_POINT_VELOCITY_BIAS" -#define DALI_ENV_PAN_TWO_POINT_ACCELERATION_BIAS "DALI_PAN_TWO_POINT_ACCELERATION_BIAS" -#define DALI_ENV_PAN_MULTITAP_SMOOTHING_RANGE "DALI_PAN_MULTITAP_SMOOTHING_RANGE" +#define DALI_ENV_PAN_USE_ACTUAL_TIMES "DALI_PAN_USE_ACTUAL_TIMES" +#define DALI_ENV_PAN_INTERPOLATION_TIME_RANGE "DALI_PAN_INTERPOLATION_TIME_RANGE" +#define DALI_ENV_PAN_SCALAR_ONLY_PREDICTION_ENABLED "DALI_PAN_SCALAR_ONLY_PREDICTION_ENABLED" +#define DALI_ENV_PAN_TWO_POINT_PREDICTION_ENABLED "DALI_PAN_TWO_POINT_PREDICTION_ENABLED" +#define DALI_ENV_PAN_TWO_POINT_PAST_INTERPOLATE_TIME "DALI_PAN_TWO_POINT_PAST_INTERPOLATE_TIME" +#define DALI_ENV_PAN_TWO_POINT_VELOCITY_BIAS "DALI_PAN_TWO_POINT_VELOCITY_BIAS" +#define DALI_ENV_PAN_TWO_POINT_ACCELERATION_BIAS "DALI_PAN_TWO_POINT_ACCELERATION_BIAS" +#define DALI_ENV_PAN_MULTITAP_SMOOTHING_RANGE "DALI_PAN_MULTITAP_SMOOTHING_RANGE" // Pan-Gesture miscellaneous: -#define DALI_ENV_LOG_PAN_GESTURE "DALI_LOG_PAN_GESTURE" -#define DALI_ENV_PAN_MINIMUM_DISTANCE "DALI_PAN_MINIMUM_DISTANCE" -#define DALI_ENV_PAN_MINIMUM_EVENTS "DALI_PAN_MINIMUM_EVENTS" +#define DALI_ENV_LOG_PAN_GESTURE "DALI_LOG_PAN_GESTURE" +#define DALI_ENV_PAN_MINIMUM_DISTANCE "DALI_PAN_MINIMUM_DISTANCE" +#define DALI_ENV_PAN_MINIMUM_EVENTS "DALI_PAN_MINIMUM_EVENTS" // Pinch-Gesture -#define DALI_ENV_PINCH_MINIMUM_DISTANCE "DALI_PINCH_MINIMUM_DISTANCE" -#define DALI_ENV_PINCH_MINIMUM_TOUCH_EVENTS "DALI_PINCH_MINIMUM_TOUCH_EVENTS" -#define DALI_ENV_PINCH_MINIMUM_TOUCH_EVENTS_AFTER_START "DALI_PINCH_MINIMUM_TOUCH_EVENTS_AFTER_START" +#define DALI_ENV_PINCH_MINIMUM_DISTANCE "DALI_PINCH_MINIMUM_DISTANCE" +#define DALI_ENV_PINCH_MINIMUM_TOUCH_EVENTS "DALI_PINCH_MINIMUM_TOUCH_EVENTS" +#define DALI_ENV_PINCH_MINIMUM_TOUCH_EVENTS_AFTER_START "DALI_PINCH_MINIMUM_TOUCH_EVENTS_AFTER_START" // Rotation-Gesture -#define DALI_ENV_ROTATION_MINIMUM_TOUCH_EVENTS "DALI_ROTATION_MINIMUM_TOUCH_EVENTS" -#define DALI_ENV_ROTATION_MINIMUM_TOUCH_EVENTS_AFTER_START "DALI_ROTATION_MINIMUM_TOUCH_EVENTS_AFTER_START" +#define DALI_ENV_ROTATION_MINIMUM_TOUCH_EVENTS "DALI_ROTATION_MINIMUM_TOUCH_EVENTS" +#define DALI_ENV_ROTATION_MINIMUM_TOUCH_EVENTS_AFTER_START "DALI_ROTATION_MINIMUM_TOUCH_EVENTS_AFTER_START" /** * The minimum holding time required to be recognized as a long press gesture (milliseconds) */ -#define DALI_ENV_LONG_PRESS_MINIMUM_HOLDING_TIME "DALI_LONG_PRESS_MINIMUM_HOLDING_TIME" +#define DALI_ENV_LONG_PRESS_MINIMUM_HOLDING_TIME "DALI_LONG_PRESS_MINIMUM_HOLDING_TIME" #define DALI_GLES_CALL_TIME "DALI_GLES_CALL_TIME" diff --git a/dali/internal/system/common/file-closer.h b/dali/internal/system/common/file-closer.h old mode 100755 new mode 100644 index 27c30ac..fca9d12 --- a/dali/internal/system/common/file-closer.h +++ b/dali/internal/system/common/file-closer.h @@ -1,7 +1,7 @@ #ifndef DALI_INTERNAL_PLATFORM_FILECLOSER_H #define DALI_INTERNAL_PLATFORM_FILECLOSER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,67 +29,65 @@ namespace Internal { namespace Platform { - /** * Opens files and closes them later even if an exception is thrown. */ class FileCloser { protected: // prevent this class being directly instantiated - /** * @brief Construct a FileCloser guarding a new FILE* for accessing the path passed in. */ - FileCloser( const char* const filename, const char* const mode ) + FileCloser(const char* const filename, const char* const mode) { - DALI_ASSERT_DEBUG( filename != 0 && "Can't open a null filename." ); - DALI_ASSERT_DEBUG( mode != 0 && "Null mode is undefined behaviour in spec." ); + DALI_ASSERT_DEBUG(filename != 0 && "Can't open a null filename."); + DALI_ASSERT_DEBUG(mode != 0 && "Null mode is undefined behaviour in spec."); Dali::FileLoader::FileType fileType = Dali::FileLoader::FileType::TEXT; const char* modeStr = mode; - while( *modeStr ) + while(*modeStr) { - switch ( *modeStr ) + switch(*modeStr) { - case 'r': - break; - case 'b': - fileType = FileLoader::FileType::BINARY; - break; - // Still has to use fopen for append and write modes - case 'a': - case 'w': - case '+': - mFile = fopen( filename, mode ); - return; - default: - break; + case 'r': + break; + case 'b': + fileType = FileLoader::FileType::BINARY; + break; + // Still has to use fopen for append and write modes + case 'a': + case 'w': + case '+': + mFile = fopen(filename, mode); + return; + default: + break; } ++modeStr; } std::streampos bufferSize = 0; - if( !Dali::FileLoader::ReadFile( filename, bufferSize, mFileBuffer, fileType ) ) + if(!Dali::FileLoader::ReadFile(filename, bufferSize, mFileBuffer, fileType)) { mFile = nullptr; } else { - mFile = fmemopen( &mFileBuffer[0], bufferSize, mode ); + mFile = fmemopen(&mFileBuffer[0], bufferSize, mode); } } /** * @brief Construct a FileCloser guarding a FILE* for reading out of the memory buffer passed in. */ - FileCloser( uint8_t* buffer, size_t dataSize, const char* const mode ) - : mFile( fmemopen( buffer, dataSize, mode) ) + FileCloser(uint8_t* buffer, size_t dataSize, const char* const mode) + : mFile(fmemopen(buffer, dataSize, mode)) { } - FileCloser( Dali::Vector& vector, size_t dataSize, const char * const mode ) + FileCloser(Dali::Vector& vector, size_t dataSize, const char* const mode) { // Resize the buffer to ensure any null that gets written by // fmemopen is written past the end of any data that is written to the buffer. @@ -98,33 +96,33 @@ protected: // prevent this class being directly instantiated // null if binary mode is specified). size_t bufferSize = dataSize; ++bufferSize; - vector.Resize( bufferSize ); + vector.Resize(bufferSize); - void * const buffer = &vector[0]; - mFile = fmemopen( buffer, bufferSize, mode ); + void* const buffer = &vector[0]; + mFile = fmemopen(buffer, bufferSize, mode); - DALI_ASSERT_DEBUG( buffer != 0 && "Cant open file on null buffer." ); - DALI_ASSERT_DEBUG( dataSize > 0 && "Pointless to open file on empty buffer." ); - DALI_ASSERT_DEBUG( mode != 0 && "Null mode is undefined behaviour in spec." ); + DALI_ASSERT_DEBUG(buffer != 0 && "Cant open file on null buffer."); + DALI_ASSERT_DEBUG(dataSize > 0 && "Pointless to open file on empty buffer."); + DALI_ASSERT_DEBUG(mode != 0 && "Null mode is undefined behaviour in spec."); - if( mFile == 0 ) + if(mFile == 0) { - DALI_LOG_WARNING( "File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", static_cast(buffer), static_cast(dataSize), mode ); + DALI_LOG_WARNING("File open failed for memory buffer at location: \"%p\", of size: \"%u\", in mode: \"%s\".\n", static_cast(buffer), static_cast(dataSize), mode); } } - /** + /** * @brief Destroy the FileCloser and clean up its FILE*. */ ~FileCloser() { - if( mFile != 0 ) + if(mFile != 0) { - const int closeFailed = fclose( mFile ); + const int closeFailed = fclose(mFile); - if ( closeFailed ) + if(closeFailed) { - DALI_LOG_WARNING( "File close failed for FILE: \"%p\".\n", static_cast(mFile) ); + DALI_LOG_WARNING("File close failed for FILE: \"%p\".\n", static_cast(mFile)); } mFile = 0; } @@ -140,15 +138,14 @@ public: } private: - // Undefined - FileCloser( const FileCloser& fileCloser ); + FileCloser(const FileCloser& fileCloser); // Undefined - FileCloser& operator=( const FileCloser& fileCloser ); + FileCloser& operator=(const FileCloser& fileCloser); private: - FILE* mFile; + FILE* mFile; Dali::Vector mFileBuffer; }; diff --git a/dali/internal/system/common/file-descriptor-monitor.h b/dali/internal/system/common/file-descriptor-monitor.h index a6aa316..a22f07a 100644 --- a/dali/internal/system/common/file-descriptor-monitor.h +++ b/dali/internal/system/common/file-descriptor-monitor.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_FILE_DESCRIPTOR_MONITOR_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ namespace Dali { - namespace Integration { class Core; @@ -31,10 +30,8 @@ class Core; namespace Internal { - namespace Adaptor { - /** * @brief Monitors the given file descriptor and whenever anything is written to it, the provided * callback is called @@ -42,7 +39,6 @@ namespace Adaptor class FileDescriptorMonitor { public: - /** * @brief Bitmask of file descriptor event types */ @@ -87,7 +83,7 @@ public: * readable or writable even when it isn’t. The developer should check for handle EAGAIN or equivalent * when reading from or write to the fd. */ - FileDescriptorMonitor( int fileDescriptor, CallbackBase* callback, int eventBitmask ); + FileDescriptorMonitor(int fileDescriptor, CallbackBase* callback, int eventBitmask); /** * Destructor @@ -95,12 +91,11 @@ public: ~FileDescriptorMonitor(); private: - // Undefined - FileDescriptorMonitor( const FileDescriptorMonitor& fileDescriptorMonitor ); + FileDescriptorMonitor(const FileDescriptorMonitor& fileDescriptorMonitor); // Undefined - FileDescriptorMonitor& operator=( const FileDescriptorMonitor& fileDescriptorMonitor ); + FileDescriptorMonitor& operator=(const FileDescriptorMonitor& fileDescriptorMonitor); private: struct Impl; diff --git a/dali/internal/system/common/file-reader.h b/dali/internal/system/common/file-reader.h index 0b87fe3..031ad2d 100644 --- a/dali/internal/system/common/file-reader.h +++ b/dali/internal/system/common/file-reader.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_PORTABLE_FILE_READER_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,27 +28,26 @@ namespace Internal { namespace Platform { - class FileReader : public FileStream { public: - FileReader( const std::string& filename ) - : FileStream( filename, FileStream::READ | FileStream::BINARY ) + FileReader(const std::string& filename) + : FileStream(filename, FileStream::READ | FileStream::BINARY) { } - FileReader( Dali::Vector& vector ) - : FileStream( &vector[0], vector.Size(), FileStream::READ | FileStream::BINARY ) + FileReader(Dali::Vector& vector) + : FileStream(&vector[0], vector.Size(), FileStream::READ | FileStream::BINARY) { } - FileReader( Dali::Vector& vector, size_t dataSize ) - : FileStream( &vector[0], dataSize, FileStream::READ | FileStream::BINARY ) + FileReader(Dali::Vector& vector, size_t dataSize) + : FileStream(&vector[0], dataSize, FileStream::READ | FileStream::BINARY) { } - FileReader( uint8_t* data, size_t dataSize ) - : FileStream( data, dataSize, FileStream::READ | FileStream::BINARY ) + FileReader(uint8_t* data, size_t dataSize) + : FileStream(data, dataSize, FileStream::READ | FileStream::BINARY) { } }; diff --git a/dali/internal/system/common/file-writer.h b/dali/internal/system/common/file-writer.h index 6bc0c0c..1dcbc9a 100644 --- a/dali/internal/system/common/file-writer.h +++ b/dali/internal/system/common/file-writer.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_PORTABLE_FILE_WRITER_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ namespace Internal { namespace Platform { - class FileWriter : public FileStream { public: @@ -38,8 +37,8 @@ public: * @param[in,out] vector The vector to write to * @param[in] dataSize the amount of data to be written */ - FileWriter( Dali::Vector& vector, size_t dataSize ) - : FileStream( vector, dataSize, FileStream::WRITE | FileStream::BINARY ) + FileWriter(Dali::Vector& vector, size_t dataSize) + : FileStream(vector, dataSize, FileStream::WRITE | FileStream::BINARY) { } }; diff --git a/dali/internal/system/common/fps-tracker.cpp b/dali/internal/system/common/fps-tracker.cpp index a146d3e..8cb6bb3 100644 --- a/dali/internal/system/common/fps-tracker.cpp +++ b/dali/internal/system/common/fps-tracker.cpp @@ -19,47 +19,44 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { -const char* DALI_TEMP_UPDATE_FPS_FILE( "/tmp/dalifps.txt" ); +const char* DALI_TEMP_UPDATE_FPS_FILE("/tmp/dalifps.txt"); } // unnamed namespace -FpsTracker::FpsTracker( const EnvironmentOptions& environmentOptions ) -: mFpsTrackingSeconds( fabsf( environmentOptions.GetFrameRateLoggingFrequency() ) ), - mFrameCount( 0.0f ), - mElapsedTime( 0.0f ) +FpsTracker::FpsTracker(const EnvironmentOptions& environmentOptions) +: mFpsTrackingSeconds(fabsf(environmentOptions.GetFrameRateLoggingFrequency())), + mFrameCount(0.0f), + mElapsedTime(0.0f) { } FpsTracker::~FpsTracker() { - if( mFpsTrackingSeconds > 0.f ) + if(mFpsTrackingSeconds > 0.f) { OutputFPSRecord(); } } -void FpsTracker::Track( float secondsFromLastFrame ) +void FpsTracker::Track(float secondsFromLastFrame) { - if( mFpsTrackingSeconds > 0.f ) + if(mFpsTrackingSeconds > 0.f) { - if ( mElapsedTime < mFpsTrackingSeconds ) + if(mElapsedTime < mFpsTrackingSeconds) { mElapsedTime += secondsFromLastFrame; mFrameCount += 1.f; @@ -67,7 +64,7 @@ void FpsTracker::Track( float secondsFromLastFrame ) else { OutputFPSRecord(); - mFrameCount = 0.f; + mFrameCount = 0.f; mElapsedTime = 0.f; } } @@ -81,29 +78,29 @@ bool FpsTracker::Enabled() const void FpsTracker::OutputFPSRecord() { float fps = mFrameCount / mElapsedTime; - DALI_LOG_FPS("Frame count %.0f, elapsed time %.1fs, FPS: %.2f\n", mFrameCount, mElapsedTime, fps ); + DALI_LOG_FPS("Frame count %.0f, elapsed time %.1fs, FPS: %.2f\n", mFrameCount, mElapsedTime, fps); struct stat fileStat; // Check file path - if( lstat( DALI_TEMP_UPDATE_FPS_FILE, &fileStat ) != 0 ) + if(lstat(DALI_TEMP_UPDATE_FPS_FILE, &fileStat) != 0) { return; } - if( !S_ISREG( fileStat.st_mode ) ) + if(!S_ISREG(fileStat.st_mode)) { return; } // Dumps out the frame rate. - FILE* outfile = fopen( DALI_TEMP_UPDATE_FPS_FILE, "w" ); - if( outfile ) + FILE* outfile = fopen(DALI_TEMP_UPDATE_FPS_FILE, "w"); + if(outfile) { char fpsString[10]; - snprintf(fpsString,sizeof(fpsString),"%.2f \n", fps ); - fputs( fpsString, outfile ); // ignore the error on purpose - fclose( outfile ); + snprintf(fpsString, sizeof(fpsString), "%.2f \n", fps); + fputs(fpsString, outfile); // ignore the error on purpose + fclose(outfile); } } diff --git a/dali/internal/system/common/fps-tracker.h b/dali/internal/system/common/fps-tracker.h index c943247..d0c1f95 100644 --- a/dali/internal/system/common/fps-tracker.h +++ b/dali/internal/system/common/fps-tracker.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_FPS_TRACKER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class EnvironmentOptions; /** @@ -37,12 +34,11 @@ class EnvironmentOptions; class FpsTracker { public: - /** * Create the FPS Tracker. * @param[in] environmentOptions environment options */ - FpsTracker( const EnvironmentOptions& environmentOptions ); + FpsTracker(const EnvironmentOptions& environmentOptions); /** * Non-virtual destructor; UpdateThread is not suitable as a base class. @@ -62,7 +58,6 @@ public: bool Enabled() const; private: - /** * Output the FPS information * when the FSP tracking is enabled, @@ -70,11 +65,10 @@ private: */ void OutputFPSRecord(); -private: // Data - - float mFpsTrackingSeconds; ///< fps tracking time length in seconds - float mFrameCount; ///< how many frames occurred during tracking period - float mElapsedTime; ///< time elapsed from previous fps tracking output +private: // Data + float mFpsTrackingSeconds; ///< fps tracking time length in seconds + float mFrameCount; ///< how many frames occurred during tracking period + float mElapsedTime; ///< time elapsed from previous fps tracking output }; } // namespace Adaptor diff --git a/dali/internal/system/common/frame-time-stamp.cpp b/dali/internal/system/common/frame-time-stamp.cpp index 47ccce8..58f6b2c 100644 --- a/dali/internal/system/common/frame-time-stamp.cpp +++ b/dali/internal/system/common/frame-time-stamp.cpp @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - FrameTimeStamp::FrameTimeStamp() : frame(0), microseconds(0), @@ -37,20 +34,20 @@ FrameTimeStamp::FrameTimeStamp() FrameTimeStamp::FrameTimeStamp(unsigned int frame, uint64_t microseconds, unsigned int bufferIndex) -: frame( frame ), - microseconds( microseconds ), - bufferIndex( bufferIndex ) +: frame(frame), + microseconds(microseconds), + bufferIndex(bufferIndex) { } -FrameTimeStamp::FrameTimeStamp( unsigned int bufferIndex ) -: frame( 0 ), - microseconds( 0 ), - bufferIndex( bufferIndex ) +FrameTimeStamp::FrameTimeStamp(unsigned int bufferIndex) +: frame(0), + microseconds(0), + bufferIndex(bufferIndex) { } -unsigned int FrameTimeStamp::MicrosecondDiff( const FrameTimeStamp& start,const FrameTimeStamp& end ) +unsigned int FrameTimeStamp::MicrosecondDiff(const FrameTimeStamp& start, const FrameTimeStamp& end) { return end.microseconds - start.microseconds; } @@ -60,4 +57,3 @@ unsigned int FrameTimeStamp::MicrosecondDiff( const FrameTimeStamp& start,const } // namespace Internal } // namespace Dali - diff --git a/dali/internal/system/common/frame-time-stamp.h b/dali/internal/system/common/frame-time-stamp.h index 0fa2397..daf8ced 100644 --- a/dali/internal/system/common/frame-time-stamp.h +++ b/dali/internal/system/common/frame-time-stamp.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_FRAME_TIME_STAMP_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,52 +23,48 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Simple structure to hold information about an event in time * within Dali. For example when rendering started. */ struct FrameTimeStamp { + static const unsigned int BUFFER_NOT_USED = 2; ///< no index buffer was used - static const unsigned int BUFFER_NOT_USED = 2; ///< no index buffer was used - - /** + /** * Constructor */ - FrameTimeStamp(); + FrameTimeStamp(); - /** + /** * Constructor * @param frame the frame number * @param microseconds the time from a monotonic clock * @param bufferIndex double buffered index used for performing an update / render */ - FrameTimeStamp( unsigned int frame, uint64_t microseconds, unsigned int bufferIndex = BUFFER_NOT_USED ); + FrameTimeStamp(unsigned int frame, uint64_t microseconds, unsigned int bufferIndex = BUFFER_NOT_USED); - /** + /** * Constructor * @param bufferIndex double buffered index used for performing an update / render */ - FrameTimeStamp( unsigned int bufferIndex ); + FrameTimeStamp(unsigned int bufferIndex); - /** + /** * @param start start time * @param end end time * @return difference in microseconds between two time stamps */ - static unsigned int MicrosecondDiff( const FrameTimeStamp& start,const FrameTimeStamp& end ); + static unsigned int MicrosecondDiff(const FrameTimeStamp& start, const FrameTimeStamp& end); - unsigned int frame; ///< Frame number ( not always available) - uint64_t microseconds; ///< Microsecond time stamp - unsigned int bufferIndex; ///< The double buffered index used for performing an update / render - }; + unsigned int frame; ///< Frame number ( not always available) + uint64_t microseconds; ///< Microsecond time stamp + unsigned int bufferIndex; ///< The double buffered index used for performing an update / render +}; } // namespace Adaptor } // namespace Internal @@ -76,4 +72,3 @@ struct FrameTimeStamp } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_FRAME_TIME_STAMP_H - diff --git a/dali/internal/system/common/frame-time-stats.cpp b/dali/internal/system/common/frame-time-stats.cpp index 115e124..7364921 100644 --- a/dali/internal/system/common/frame-time-stats.cpp +++ b/dali/internal/system/common/frame-time-stats.cpp @@ -23,23 +23,20 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { -const float EPSILON = 0.9f; // rolling average = (average * epsilon) + (current * epsilon) +const float EPSILON = 0.9f; // rolling average = (average * epsilon) + (current * epsilon) const float ONE_OVER_MICROSECONDS_TO_SECONDS = 1.f / 1000000.f; ///< microseconds per second -} +} // namespace FrameTimeStats::FrameTimeStats() -: mTotal( 0.f) +: mTotal(0.f) { - mSamples.Reserve( 16 ); // Fill out a little to avoid early reallocations + mSamples.Reserve(16); // Fill out a little to avoid early reallocations Reset(); } @@ -48,21 +45,21 @@ FrameTimeStats::~FrameTimeStats() { } -void FrameTimeStats::StartTime( const FrameTimeStamp& timeStamp ) +void FrameTimeStats::StartTime(const FrameTimeStamp& timeStamp) { // check to make sure we don't get 2 start times in a row - if( mTimeState != WAITING_FOR_START_TIME ) + if(mTimeState != WAITING_FOR_START_TIME) { Reset(); } - mStart = timeStamp; + mStart = timeStamp; mTimeState = WAITING_FOR_END_TIME; } -void FrameTimeStats::EndTime( const FrameTimeStamp& timeStamp ) +void FrameTimeStats::EndTime(const FrameTimeStamp& timeStamp) { - if( mTimeState != WAITING_FOR_END_TIME ) + if(mTimeState != WAITING_FOR_END_TIME) { Reset(); return; @@ -72,24 +69,24 @@ void FrameTimeStats::EndTime( const FrameTimeStamp& timeStamp ) mRunCount++; // frame time in seconds - unsigned int elapsedTime = FrameTimeStamp::MicrosecondDiff( mStart, timeStamp); + unsigned int elapsedTime = FrameTimeStamp::MicrosecondDiff(mStart, timeStamp); - mSamples.PushBack( elapsedTime ); + mSamples.PushBack(elapsedTime); // if the min and max times haven't been set, do that now. - if( !mMinMaxTimeSet ) + if(!mMinMaxTimeSet) { - mMin = elapsedTime; - mMax = elapsedTime; + mMin = elapsedTime; + mMax = elapsedTime; mMinMaxTimeSet = true; } else { - if (elapsedTime < mMin) + if(elapsedTime < mMin) { - mMin= elapsedTime; + mMin = elapsedTime; } - else if (elapsedTime > mMax) + else if(elapsedTime > mMax) { mMax = elapsedTime; } @@ -100,12 +97,12 @@ void FrameTimeStats::EndTime( const FrameTimeStamp& timeStamp ) void FrameTimeStats::Reset() { - mTimeState = WAITING_FOR_START_TIME; + mTimeState = WAITING_FOR_START_TIME; mMinMaxTimeSet = false; - mMin = 0.f; - mMax = 0.f; - mRunCount = 0; - mStart = FrameTimeStamp(); + mMin = 0.f; + mMax = 0.f; + mRunCount = 0; + mStart = FrameTimeStamp(); mSamples.Clear(); } @@ -129,13 +126,13 @@ unsigned int FrameTimeStats::GetRunCount() const return mRunCount; } -void FrameTimeStats::CalculateMean( float& meanOut, float& standardDeviationOut ) const +void FrameTimeStats::CalculateMean(float& meanOut, float& standardDeviationOut) const { - if( mSamples.Size() > 0 ) + if(mSamples.Size() > 0) { // Mean unsigned int sum = 0; - for( Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it ) + for(Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it) { unsigned int value = *it; @@ -146,7 +143,7 @@ void FrameTimeStats::CalculateMean( float& meanOut, float& standardDeviationOut // Variance float variance = 0.0f; - for( Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it ) + for(Samples::ConstIterator it = mSamples.Begin(), itEnd = mSamples.End(); it != itEnd; ++it) { unsigned int value = *it; @@ -158,19 +155,18 @@ void FrameTimeStats::CalculateMean( float& meanOut, float& standardDeviationOut variance /= mSamples.Size(); // Standard deviation - standardDeviationOut = sqrtf( variance ); + standardDeviationOut = sqrtf(variance); meanOut *= ONE_OVER_MICROSECONDS_TO_SECONDS; standardDeviationOut *= ONE_OVER_MICROSECONDS_TO_SECONDS; } else { - meanOut = 0.0f; + meanOut = 0.0f; standardDeviationOut = 0.0f; } } - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/system/common/frame-time-stats.h b/dali/internal/system/common/frame-time-stats.h index 5d15c1e..359822a 100644 --- a/dali/internal/system/common/frame-time-stats.h +++ b/dali/internal/system/common/frame-time-stats.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,16 +22,12 @@ #include #include - namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Used to get statistics about time stamps over a period of time. * E.g. the min, max, total and average time spent inside two markers, @@ -53,69 +49,67 @@ struct FrameTimeStats * Timer start time * @param timeStamp time stamp */ - void StartTime( const FrameTimeStamp& timeStamp ); + void StartTime(const FrameTimeStamp& timeStamp); - /** + /** * Timer end time * @param timeStamp time stamp */ - void EndTime( const FrameTimeStamp& timeStamp ); + void EndTime(const FrameTimeStamp& timeStamp); - /** + /** * Reset all internal counters / state except total time. */ - void Reset(); + void Reset(); - /** + /** * @return maximum time in seconds */ - float GetMaxTime() const; + float GetMaxTime() const; - /** + /** * @return minimum time in seconds */ - float GetMinTime() const; + float GetMinTime() const; - /** + /** * @return total time in second */ - float GetTotalTime() const; + float GetTotalTime() const; - /** + /** * Get how many times the timer has been started /stopped */ - unsigned int GetRunCount() const; + unsigned int GetRunCount() const; - /** + /** * Calculate the mean and standard deviation * * @param[out] mean The return mean value * @param[out] standardDeviation The return standard deviation value */ - void CalculateMean( float& meanOut, float& standardDeviationOut ) const; + void CalculateMean(float& meanOut, float& standardDeviationOut) const; private: - - /** + /** * internal time state. */ - enum TimeState - { - WAITING_FOR_START_TIME, ///< waiting for start time marker - WAITING_FOR_END_TIME ///< waiting for end time marker - }; - - typedef Dali::Vector< unsigned int > Samples; - Samples mSamples; - - unsigned int mMin; ///< current minimum value in microseconds - unsigned int mMax; ///< current maximum value in microseconds - unsigned int mTotal; ///< current total in in microseconds - unsigned int mRunCount; ///< how many times the timer has been start / stopped - FrameTimeStamp mStart; ///< start time stamp, to calculate the diff - TimeState mTimeState:1; ///< time state - bool mMinMaxTimeSet:1; ///< whether the min-max values have been configured - + enum TimeState + { + WAITING_FOR_START_TIME, ///< waiting for start time marker + WAITING_FOR_END_TIME ///< waiting for end time marker + }; + + typedef Dali::Vector Samples; + Samples mSamples; + + unsigned int mMin; ///< current minimum value in microseconds + unsigned int mMax; ///< current maximum value in microseconds + unsigned int mTotal; ///< current total in in microseconds + unsigned int mRunCount; ///< how many times the timer has been start / stopped + FrameTimeStamp mStart; ///< start time stamp, to calculate the diff + TimeState mTimeState : 1; ///< time state + bool mMinMaxTimeSet : 1; ///< whether the min-max values have been configured }; } // namespace Adaptor @@ -125,4 +119,3 @@ private: } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_FRAME_TIME_STATS_H - diff --git a/dali/internal/system/common/kernel-trace.cpp b/dali/internal/system/common/kernel-trace.cpp index baa7039..0b87432 100644 --- a/dali/internal/system/common/kernel-trace.cpp +++ b/dali/internal/system/common/kernel-trace.cpp @@ -28,30 +28,27 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { const char* TRACE_MARKER_FILE = "/sys/kernel/debug/tracing/trace_marker"; -const char* SPI_PREFIX = "SPI_EV_DALI_"; ///< prefix to let the SPI tool know it should read the trace -}// un-named name space +const char* SPI_PREFIX = "SPI_EV_DALI_"; ///< prefix to let the SPI tool know it should read the trace +} // namespace KernelTrace::KernelTrace() -: mFileDescriptor( 0 ), - mLoggedError( false ) +: mFileDescriptor(0), + mLoggedError(false) { } KernelTrace::~KernelTrace() { - if( mFileDescriptor ) + if(mFileDescriptor) { - close( mFileDescriptor ); + close(mFileDescriptor); } } @@ -68,46 +65,44 @@ KernelTrace::~KernelTrace() // If the message did not get added to the trace, then check you have write permissions to the trace_marker file. // // -void KernelTrace::Trace( const PerformanceMarker& marker, const std::string& traceMessage ) +void KernelTrace::Trace(const PerformanceMarker& marker, const std::string& traceMessage) { // Open the trace_marker file - if( mFileDescriptor == 0 ) + if(mFileDescriptor == 0) { - mFileDescriptor = open( TRACE_MARKER_FILE , O_WRONLY); - if( mFileDescriptor == -1 ) + mFileDescriptor = open(TRACE_MARKER_FILE, O_WRONLY); + if(mFileDescriptor == -1) { // we want to keep trying to open it, so it will start working if someone fixes // the permissions on the trace marker mFileDescriptor = 0; // first time we fail to open the file, log an error - if( !mLoggedError ) + if(!mLoggedError) { mLoggedError = true; DALI_LOG_ERROR("Failed to open /sys/kernel/debug/tracing/trace_marker for writing please check file permissions.\n"); } - } } - if( mFileDescriptor > 0 ) + if(mFileDescriptor > 0) { - std::string msg( SPI_PREFIX ); - msg+=traceMessage; + std::string msg(SPI_PREFIX); + msg += traceMessage; - int ret = write( mFileDescriptor, msg.c_str(), msg.length() ); - // if it failed then close the file description and try again next time we trace - if( ret < 0 ) - { - close( mFileDescriptor ); - mFileDescriptor = 0; - } + int ret = write(mFileDescriptor, msg.c_str(), msg.length()); + // if it failed then close the file description and try again next time we trace + if(ret < 0) + { + close(mFileDescriptor); + mFileDescriptor = 0; + } } } -} // namespace Internal - } // namespace Adaptor -} // namespace Dali +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/system/common/kernel-trace.h b/dali/internal/system/common/kernel-trace.h index 644c6f9..e80e120 100644 --- a/dali/internal/system/common/kernel-trace.h +++ b/dali/internal/system/common/kernel-trace.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Concrete Kernel Tracing Interface. * Used to log trace messages to the kernel using ftrace. @@ -37,7 +34,6 @@ namespace Adaptor class KernelTrace : public TraceInterface { public: - /** * Constructor */ @@ -51,19 +47,17 @@ public: /** * @copydoc KernelTracerInterface::KernelTrace() */ - void Trace( const PerformanceMarker& marker, const std::string& traceMessage ) override; + void Trace(const PerformanceMarker& marker, const std::string& traceMessage) override; private: - - int mFileDescriptor; - bool mLoggedError:1; - + int mFileDescriptor; + bool mLoggedError : 1; }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_KERNEL_TRACE_H diff --git a/dali/internal/system/common/locale-utils.cpp b/dali/internal/system/common/locale-utils.cpp old mode 100755 new mode 100644 index e61c30b..56475e8 --- a/dali/internal/system/common/locale-utils.cpp +++ b/dali/internal/system/common/locale-utils.cpp @@ -20,26 +20,22 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace Locale { - namespace { - struct LocaleDirectionInfo { - const char * locale; - const char * name; + const char* locale; + const char* name; Locale::Direction direction; }; +// clang-format off const LocaleDirectionInfo LOCALE_DIRECTION_LOOKUP_TABLE[] = { { "af", "Afrikaans", Locale::LEFT_TO_RIGHT }, @@ -142,18 +138,19 @@ const LocaleDirectionInfo LOCALE_DIRECTION_LOOKUP_TABLE[] = { NULL, NULL, Locale::LEFT_TO_RIGHT } }; +// clang-format on } // unnamed namespace -Locale::Direction GetDirection( const std::string& locale ) +Locale::Direction GetDirection(const std::string& locale) { - Locale::Direction direction( Locale::LEFT_TO_RIGHT ); + Locale::Direction direction(Locale::LEFT_TO_RIGHT); - if ( !locale.empty() && locale.size() > 2 ) + if(!locale.empty() && locale.size() > 2) { - for ( const LocaleDirectionInfo* iter = &LOCALE_DIRECTION_LOOKUP_TABLE[0]; iter->locale; ++iter ) + for(const LocaleDirectionInfo* iter = &LOCALE_DIRECTION_LOOKUP_TABLE[0]; iter->locale; ++iter) { - if ( !locale.compare( 0, 2, iter->locale ) ) + if(!locale.compare(0, 2, iter->locale)) { direction = iter->direction; break; diff --git a/dali/internal/system/common/locale-utils.h b/dali/internal/system/common/locale-utils.h index 9e82c55..5b407b3 100644 --- a/dali/internal/system/common/locale-utils.h +++ b/dali/internal/system/common/locale-utils.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_LOCALE_UTILS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,23 +23,19 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace Locale { - enum Direction { LEFT_TO_RIGHT, RIGHT_TO_LEFT, }; -Locale::Direction GetDirection( const std::string& locale ); +Locale::Direction GetDirection(const std::string& locale); } // namespace Locale diff --git a/dali/internal/system/common/logging.h b/dali/internal/system/common/logging.h index 6f07e2a..8ccad8b 100644 --- a/dali/internal/system/common/logging.h +++ b/dali/internal/system/common/logging.h @@ -2,7 +2,7 @@ #define DALI_TIZEN_LOGGING_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ #include - namespace Dali { - namespace TizenPlatform { - /** * @copydoc Dali::Integration::Log:LogMessage */ diff --git a/dali/internal/system/common/object-profiler.cpp b/dali/internal/system/common/object-profiler.cpp index 6651190..4be76bd 100644 --- a/dali/internal/system/common/object-profiler.cpp +++ b/dali/internal/system/common/object-profiler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 20207 Samsung Electronics Co., Ltd. + * Copyright (c) 20217 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ #include // EXTERNAL INCLUDES -#include #include #include -#include #include +#include #include +#include using std::string; using namespace Dali::Integration::Profiling; @@ -35,19 +35,18 @@ namespace Internal { namespace Adaptor { - -ObjectProfiler::ObjectProfiler( Dali::ObjectRegistry objectRegistry, uint32_t timeInterval ) -: mObjectRegistry( objectRegistry ) +ObjectProfiler::ObjectProfiler(Dali::ObjectRegistry objectRegistry, uint32_t timeInterval) +: mObjectRegistry(objectRegistry) { // This class must be created after the Stage; this means it doesn't count the initial objects // that are created by the stage (base layer, default camera actor) - mTimer = Dali::Timer::New( timeInterval * 1000 ); - mTimer.TickSignal().Connect( this, &ObjectProfiler::OnTimeout ); + mTimer = Dali::Timer::New(timeInterval * 1000); + mTimer.TickSignal().Connect(this, &ObjectProfiler::OnTimeout); mTimer.Start(); - mObjectRegistry.ObjectCreatedSignal().Connect( this, &ObjectProfiler::OnObjectCreated ); - mObjectRegistry.ObjectDestroyedSignal().Connect( this, &ObjectProfiler::OnObjectDestroyed ); + mObjectRegistry.ObjectCreatedSignal().Connect(this, &ObjectProfiler::OnObjectCreated); + mObjectRegistry.ObjectDestroyedSignal().Connect(this, &ObjectProfiler::OnObjectDestroyed); } ObjectProfiler::~ObjectProfiler() @@ -56,18 +55,16 @@ ObjectProfiler::~ObjectProfiler() void ObjectProfiler::DisplayInstanceCounts() { - for( auto&& element : mInstanceCountContainer ) + for(auto&& element : mInstanceCountContainer) { - std::size_t memorySize = GetMemorySize( element.first, element.second ); - if( memorySize > 0 ) + std::size_t memorySize = GetMemorySize(element.first, element.second); + if(memorySize > 0) { - LogMessage( Debug::DebugInfo, "%-30s: % 4d Memory MemorySize: ~% 6.1f kB\n", - element.first.c_str(), element.second, memorySize / 1024.0f ); + LogMessage(Debug::DebugInfo, "%-30s: % 4d Memory MemorySize: ~% 6.1f kB\n", element.first.c_str(), element.second, memorySize / 1024.0f); } else { - LogMessage( Debug::DebugInfo, "%-30s: % 4d\n", - element.first.c_str(), element.second ); + LogMessage(Debug::DebugInfo, "%-30s: % 4d\n", element.first.c_str(), element.second); } } LogMessage(Debug::DebugInfo, "\n"); @@ -82,7 +79,7 @@ bool ObjectProfiler::OnTimeout() void ObjectProfiler::OnObjectCreated(BaseHandle handle) { string theType = handle.GetTypeName(); - if( theType.empty() ) + if(theType.empty()) { DALI_LOG_ERROR("Object created from an unregistered type\n"); theType = ""; @@ -91,18 +88,18 @@ void ObjectProfiler::OnObjectCreated(BaseHandle handle) mInstanceTypes.push_back(InstanceTypePair(&handle.GetBaseObject(), theType)); bool found = false; - for( auto&& element : mInstanceCountContainer ) + for(auto&& element : mInstanceCountContainer) { - if( element.first == theType ) + if(element.first == theType) { element.second++; found = true; } } - if( !found ) + if(!found) { - InstanceCountPair instanceCount( theType, 1 ); - mInstanceCountContainer.emplace_back( instanceCount ); + InstanceCountPair instanceCount(theType, 1); + mInstanceCountContainer.emplace_back(instanceCount); } } @@ -111,29 +108,28 @@ void ObjectProfiler::OnObjectDestroyed(const Dali::RefObject* object) const BaseObject* baseObject = static_cast(object); const auto end = mInstanceTypes.end(); - for( auto iter = mInstanceTypes.begin(); iter != end; ++iter ) + for(auto iter = mInstanceTypes.begin(); iter != end; ++iter) { - if( iter->first == baseObject ) + if(iter->first == baseObject) { const auto& theType = iter->second; - if( !theType.empty() ) + if(!theType.empty()) { - auto&& countIter = std::find_if( mInstanceCountContainer.begin(), - mInstanceCountContainer.end(), - [theType] ( const InstanceCountPair& instance ) - { return instance.first == theType; } ); - if( countIter != mInstanceCountContainer.end() ) + auto&& countIter = std::find_if(mInstanceCountContainer.begin(), + mInstanceCountContainer.end(), + [theType](const InstanceCountPair& instance) { return instance.first == theType; }); + if(countIter != mInstanceCountContainer.end()) { (*countIter).second--; } } - mInstanceTypes.erase( iter ); + mInstanceTypes.erase(iter); return; } } } -std::size_t ObjectProfiler::GetMemorySize( const std::string& name, uint32_t count ) +std::size_t ObjectProfiler::GetMemorySize(const std::string& name, uint32_t count) { struct MemoryMemorySize { @@ -142,22 +138,22 @@ std::size_t ObjectProfiler::GetMemorySize( const std::string& name, uint32_t cou }; MemoryMemorySize memoryMemorySizes[] = { - { "Animation", ANIMATION_MEMORY_SIZE }, - { "Constraint", CONSTRAINT_MEMORY_SIZE }, - { "Actor", ACTOR_MEMORY_SIZE }, - { "Layer", LAYER_MEMORY_SIZE }, - { "CameraActor", CAMERA_ACTOR_MEMORY_SIZE }, - { "Renderer", RENDERER_MEMORY_SIZE }, - { "Geometry", GEOMETRY_MEMORY_SIZE }, - { "PropertyBuffer", PROPERTY_BUFFER_MEMORY_SIZE }, - { "TextureSet", TEXTURE_SET_MEMORY_SIZE }, - { "Sampler", SAMPLER_MEMORY_SIZE }, - { "Shader", SHADER_MEMORY_SIZE }, + {"Animation", ANIMATION_MEMORY_SIZE}, + {"Constraint", CONSTRAINT_MEMORY_SIZE}, + {"Actor", ACTOR_MEMORY_SIZE}, + {"Layer", LAYER_MEMORY_SIZE}, + {"CameraActor", CAMERA_ACTOR_MEMORY_SIZE}, + {"Renderer", RENDERER_MEMORY_SIZE}, + {"Geometry", GEOMETRY_MEMORY_SIZE}, + {"PropertyBuffer", PROPERTY_BUFFER_MEMORY_SIZE}, + {"TextureSet", TEXTURE_SET_MEMORY_SIZE}, + {"Sampler", SAMPLER_MEMORY_SIZE}, + {"Shader", SHADER_MEMORY_SIZE}, }; - for( size_t i=0; i // uint32_t -#include // size_t #include #include #include #include +#include // size_t +#include // uint32_t // INTERNAL INCLUDES #include @@ -35,20 +35,18 @@ namespace Internal { namespace Adaptor { - /** * Class to profile the number of instances of Objects in the system */ class ObjectProfiler : public ConnectionTracker { public: - /** * Constructor * @param objectRegistry The objectRegistry * @param timeInterval to specify the frequency of reporting */ - ObjectProfiler( Dali::ObjectRegistry objectRegistry, uint32_t timeInterval ); + ObjectProfiler(Dali::ObjectRegistry objectRegistry, uint32_t timeInterval); /** * Destructor @@ -70,32 +68,31 @@ private: * Callback used when objects are created. Increases instance count for that object type * @param[in] handle of the created object */ - void OnObjectCreated( BaseHandle handle ); + void OnObjectCreated(BaseHandle handle); /** * Callback used when objects are created. Decreases instance count for that object type * @param[in] object The object being destroyed */ - void OnObjectDestroyed( const Dali::RefObject* object ); + void OnObjectDestroyed(const Dali::RefObject* object); /** * Get the memory size of the given object */ - std::size_t GetMemorySize( const std::string& name, uint32_t count ); + std::size_t GetMemorySize(const std::string& name, uint32_t count); private: + using InstanceCountPair = std::pair; + using InstanceTypePair = std::pair; - using InstanceCountPair = std::pair< const std::string, uint32_t >; - using InstanceTypePair = std::pair< BaseObject*, std::string >; - - Dali::ObjectRegistry mObjectRegistry; - Dali::Timer mTimer; - std::vector< InstanceCountPair > mInstanceCountContainer; - std::vector< InstanceTypePair > mInstanceTypes; + Dali::ObjectRegistry mObjectRegistry; + Dali::Timer mTimer; + std::vector mInstanceCountContainer; + std::vector mInstanceTypes; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_ADAPTOR_OBJECT_PROFILER_H diff --git a/dali/internal/system/common/performance-interface-factory.cpp b/dali/internal/system/common/performance-interface-factory.cpp index 80426ee..5ec8e6a 100644 --- a/dali/internal/system/common/performance-interface-factory.cpp +++ b/dali/internal/system/common/performance-interface-factory.cpp @@ -23,22 +23,17 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - PerformanceInterface* PerformanceInterfaceFactory::CreateInterface( - AdaptorInternalServices& adaptorServices, - const EnvironmentOptions& environmentOptions ) + AdaptorInternalServices& adaptorServices, + const EnvironmentOptions& environmentOptions) { - return new PerformanceServer( adaptorServices, environmentOptions ); + return new PerformanceServer(adaptorServices, environmentOptions); } - - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/system/common/performance-interface-factory.h b/dali/internal/system/common/performance-interface-factory.h index 85e63ac..a1c5c62 100644 --- a/dali/internal/system/common/performance-interface-factory.h +++ b/dali/internal/system/common/performance-interface-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Performance interface factory class * @@ -41,22 +38,20 @@ namespace Adaptor class PerformanceInterfaceFactory { public: - /** * Create a new concrete implementation of the performance interface. * @param adaptorServices adaptor internal services * @param environmentOptions environment options * @return pointer to a new performance interface */ - static PerformanceInterface* CreateInterface( AdaptorInternalServices& adaptorServices, - const EnvironmentOptions& environmentOptions ); - + static PerformanceInterface* CreateInterface(AdaptorInternalServices& adaptorServices, + const EnvironmentOptions& environmentOptions); }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_FACTORY_H diff --git a/dali/internal/system/common/performance-interface.h b/dali/internal/system/common/performance-interface.h index d1db387..19c3e1a 100644 --- a/dali/internal/system/common/performance-interface.h +++ b/dali/internal/system/common/performance-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_BASE_PERFORMANCE_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Abstract Performance Interface. * Used by the Adaptor to store performance metrics. @@ -35,8 +32,7 @@ namespace Adaptor class PerformanceInterface { public: - - typedef unsigned short ContextId; ///< Type to represent a context ID + typedef unsigned short ContextId; ///< Type to represent a context ID /** * bitmask of statistics logging options. @@ -49,11 +45,11 @@ public: */ enum StatisticsLogOptions { - DISABLED = 0, - LOG_EVERYTHING = 1 << 0, ///< Bit 0 (1), log all statistics to the DALi log - LOG_UPDATE_RENDER = 1 << 1, ///< Bit 1 (2), log update and render statistics to the DALi log - LOG_EVENT_PROCESS = 1 << 2, ///< Bit 2 (4), log event task statistics to the DALi log - LOG_CUSTOM_MARKERS = 1 << 3, ///< Bit 3 (8), log custom marker statistics to the DALi log + DISABLED = 0, + LOG_EVERYTHING = 1 << 0, ///< Bit 0 (1), log all statistics to the DALi log + LOG_UPDATE_RENDER = 1 << 1, ///< Bit 1 (2), log update and render statistics to the DALi log + LOG_EVENT_PROCESS = 1 << 2, ///< Bit 2 (4), log event task statistics to the DALi log + LOG_CUSTOM_MARKERS = 1 << 3, ///< Bit 3 (8), log custom marker statistics to the DALi log }; /** @@ -72,11 +68,11 @@ public: */ enum TimeStampOutput { - NO_TIME_STAMP_OUTPUT = 0, - OUTPUT_DALI_LOG = 1 << 0, ///< Bit 0 (1), log markers to DALi log - OUTPUT_KERNEL_TRACE = 1 << 1, ///< Bit 1 (2), log makers to kernel trace - OUTPUT_SYSTEM_TRACE = 1 << 2, ///< Bit 2 (4), log markers to system trace - OUTPUT_NETWORK = 1 << 3, ///< Bit 3 (8), log markers to network client + NO_TIME_STAMP_OUTPUT = 0, + OUTPUT_DALI_LOG = 1 << 0, ///< Bit 0 (1), log markers to DALi log + OUTPUT_KERNEL_TRACE = 1 << 1, ///< Bit 1 (2), log makers to kernel trace + OUTPUT_SYSTEM_TRACE = 1 << 2, ///< Bit 2 (4), log markers to system trace + OUTPUT_NETWORK = 1 << 3, ///< Bit 3 (8), log markers to network client }; /** @@ -86,30 +82,32 @@ public: */ enum MarkerType { - VSYNC = 0, ///< V-Sync - UPDATE_START , ///< Update start - UPDATE_END , ///< Update end - RENDER_START , ///< Render start - RENDER_END , ///< Render end - SWAP_START , ///< SwapBuffers Start - SWAP_END , ///< SwapBuffers End + VSYNC = 0, ///< V-Sync + UPDATE_START, ///< Update start + UPDATE_END, ///< Update end + RENDER_START, ///< Render start + RENDER_END, ///< Render end + SWAP_START, ///< SwapBuffers Start + SWAP_END, ///< SwapBuffers End PROCESS_EVENTS_START, ///< Process events start (e.g. touch event) PROCESS_EVENTS_END, ///< Process events end - PAUSED , ///< Pause start - RESUME , ///< Resume start - START , ///< The start of custom tracking + PAUSED, ///< Pause start + RESUME, ///< Resume start + START, ///< The start of custom tracking END ///< The end of custom tracking }; /** * Constructor. */ - PerformanceInterface() {} + PerformanceInterface() + { + } /** * Virtual destructor */ - virtual ~PerformanceInterface() {}; + virtual ~PerformanceInterface(){}; /** * @brief Add a new context with a given name @@ -117,14 +115,14 @@ public: * @param[in] name The name of the context * @return Return the unique id for this context */ - virtual ContextId AddContext( const char* name ) = 0; + virtual ContextId AddContext(const char* name) = 0; /** * @brief Remove a context from use * * @param[in] contextId The ID of the context to remove */ - virtual void RemoveContext( ContextId contextId ) = 0; + virtual void RemoveContext(ContextId contextId) = 0; /** * @brief Add a performance marker @@ -132,7 +130,7 @@ public: * The default context 0 Event/Update/Render is assumed. * @param[in] markerType performance marker type */ - virtual void AddMarker( MarkerType markerType ) = 0; + virtual void AddMarker(MarkerType markerType) = 0; /** * @brief Add a performance marker for a used defined context @@ -140,7 +138,7 @@ public: * @param[in] markerType performance marker type * @param[in] contextId The context of the marker. This must be one generated by AddContext. */ - virtual void AddMarker( MarkerType markerType, ContextId contextId ) = 0; + virtual void AddMarker(MarkerType markerType, ContextId contextId) = 0; /** * @brief Set the logging level and frequency @@ -148,14 +146,14 @@ public: * @param[in] timeStampOutput 0 = disabled, > 0 bitmask of TimeStampOutput options. * @param[in] logFrequency how often to log out in seconds */ - virtual void SetLogging( unsigned int statisticsLogOptions, unsigned int timeStampOutput, unsigned int logFrequency) = 0; + virtual void SetLogging(unsigned int statisticsLogOptions, unsigned int timeStampOutput, unsigned int logFrequency) = 0; /** * @brief Set the logging frequency for an individual context * * @param[in] logFrequency how often to log out in seconds */ - virtual void SetLoggingFrequency( unsigned int logFrequency, ContextId contextId ) = 0; + virtual void SetLoggingFrequency(unsigned int logFrequency, ContextId contextId) = 0; /** * @brief Set logging on or off for a particular context @@ -163,22 +161,20 @@ public: * @param[in] enable Enable logging or not * @param[in] contextId The id of the context to log. This must be one generated by AddContext. */ - virtual void EnableLogging( bool enable, ContextId contextId ) = 0; + virtual void EnableLogging(bool enable, ContextId contextId) = 0; private: - // Undefined copy constructor. - PerformanceInterface( const PerformanceInterface& ); + PerformanceInterface(const PerformanceInterface&); // Undefined assignment operator. - PerformanceInterface& operator=( const PerformanceInterface& ); - + PerformanceInterface& operator=(const PerformanceInterface&); }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif diff --git a/dali/internal/system/common/performance-logger-impl.cpp b/dali/internal/system/common/performance-logger-impl.cpp index adb4283..0d62686 100644 --- a/dali/internal/system/common/performance-logger-impl.cpp +++ b/dali/internal/system/common/performance-logger-impl.cpp @@ -23,21 +23,17 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - PerformanceInterface* GetPerformanceInterface() { - if( Adaptor::IsAvailable() ) + if(Adaptor::IsAvailable()) { - return Internal::Adaptor::Adaptor::GetImplementation( Adaptor::Get() ).GetPerformanceInterface(); + return Internal::Adaptor::Adaptor::GetImplementation(Adaptor::Get()).GetPerformanceInterface(); } return NULL; @@ -45,38 +41,38 @@ PerformanceInterface* GetPerformanceInterface() } // Anonymous namespace -PerformanceLoggerPtr PerformanceLogger::New( const char* name ) +PerformanceLoggerPtr PerformanceLogger::New(const char* name) { - PerformanceLoggerPtr logger = new PerformanceLogger( name ); + PerformanceLoggerPtr logger = new PerformanceLogger(name); return logger; } -PerformanceLogger::PerformanceLogger( const char* name ) -: mContext( 0 ) +PerformanceLogger::PerformanceLogger(const char* name) +: mContext(0) { PerformanceInterface* performance = GetPerformanceInterface(); - if( performance ) + if(performance) { - mContext = performance->AddContext( name ); + mContext = performance->AddContext(name); } } PerformanceLogger::~PerformanceLogger() { PerformanceInterface* performance = GetPerformanceInterface(); - if( performance ) + if(performance) { - performance->RemoveContext( mContext ); + performance->RemoveContext(mContext); } } -void PerformanceLogger::AddMarker( Dali::PerformanceLogger::Marker markerType ) +void PerformanceLogger::AddMarker(Dali::PerformanceLogger::Marker markerType) { PerformanceInterface* performance = GetPerformanceInterface(); - if( performance ) + if(performance) { PerformanceInterface::MarkerType newMarkerType = PerformanceInterface::START; - switch( markerType ) + switch(markerType) { case Dali::PerformanceLogger::START_EVENT: { @@ -90,25 +86,25 @@ void PerformanceLogger::AddMarker( Dali::PerformanceLogger::Marker markerType ) } } - performance->AddMarker( newMarkerType, mContext ); + performance->AddMarker(newMarkerType, mContext); } } -void PerformanceLogger::SetLoggingFrequency( unsigned int logFrequency) +void PerformanceLogger::SetLoggingFrequency(unsigned int logFrequency) { PerformanceInterface* performance = GetPerformanceInterface(); - if( performance ) + if(performance) { - performance->SetLoggingFrequency( logFrequency, mContext ); + performance->SetLoggingFrequency(logFrequency, mContext); } } -void PerformanceLogger::EnableLogging( bool enable ) +void PerformanceLogger::EnableLogging(bool enable) { PerformanceInterface* performance = GetPerformanceInterface(); - if( performance ) + if(performance) { - performance->EnableLogging( enable, mContext ); + performance->EnableLogging(enable, mContext); } } diff --git a/dali/internal/system/common/performance-logger-impl.h b/dali/internal/system/common/performance-logger-impl.h index cd7498f..080ebd4 100644 --- a/dali/internal/system/common/performance-logger-impl.h +++ b/dali/internal/system/common/performance-logger-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_PERFORMANCE_LOGGER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,18 +22,15 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - class PerformanceLogger; typedef IntrusivePtr PerformanceLoggerPtr; @@ -44,20 +41,19 @@ typedef IntrusivePtr PerformanceLoggerPtr; class PerformanceLogger : public BaseObject { public: - /** * @brief Create a new logger * * @param[in] name The name of the logger. This needs to be a compile-time literal and alive for the whole lifetime of the performance logger. * @return a new logger */ - static PerformanceLoggerPtr New( const char* name ); + static PerformanceLoggerPtr New(const char* name); /** * Constructor * @param[in] name The name to assing to the logger */ - PerformanceLogger( const char* name ); + PerformanceLogger(const char* name); /** * Destructor. @@ -69,52 +65,49 @@ public: * * @param markerType Performance marker type */ - void AddMarker( Dali::PerformanceLogger::Marker markerType ); + void AddMarker(Dali::PerformanceLogger::Marker markerType); /** * Set the logging frequency * * @param logFrequency how often to log out in seconds */ - void SetLoggingFrequency( unsigned int logFrequency); + void SetLoggingFrequency(unsigned int logFrequency); /** * Set logging on or off for this logger * * @param[in] enable Enable logging or not */ - void EnableLogging( bool enable ); + void EnableLogging(bool enable); private: // Implementation - // not implemented - PerformanceLogger( const PerformanceLogger& ); - PerformanceLogger& operator=( const PerformanceLogger& ); + PerformanceLogger(const PerformanceLogger&); + PerformanceLogger& operator=(const PerformanceLogger&); private: - - PerformanceInterface::ContextId mContext; ///< Context of this logger - + PerformanceInterface::ContextId mContext; ///< Context of this logger }; // Helpers for public-api forwarding methods -inline static Internal::Adaptor::PerformanceLogger& GetImplementation( Dali::PerformanceLogger& logger ) +inline static Internal::Adaptor::PerformanceLogger& GetImplementation(Dali::PerformanceLogger& logger) { - DALI_ASSERT_ALWAYS( logger && "PerformanceLogger handle is empty" ); + DALI_ASSERT_ALWAYS(logger && "PerformanceLogger handle is empty"); BaseObject& handle = logger.GetBaseObject(); - return static_cast< Internal::Adaptor::PerformanceLogger& >( handle ); + return static_cast(handle); } -inline static const Internal::Adaptor::PerformanceLogger& GetImplementation( const Dali::PerformanceLogger& logger ) +inline static const Internal::Adaptor::PerformanceLogger& GetImplementation(const Dali::PerformanceLogger& logger) { - DALI_ASSERT_ALWAYS( logger && "PerformanceLogger handle is empty" ); + DALI_ASSERT_ALWAYS(logger && "PerformanceLogger handle is empty"); const BaseObject& handle = logger.GetBaseObject(); - return static_cast< const Internal::Adaptor::PerformanceLogger& >( handle ); + return static_cast(handle); } } // namespace Adaptor diff --git a/dali/internal/system/common/performance-marker.cpp b/dali/internal/system/common/performance-marker.cpp index e5e0cdd..1e89ba7 100644 --- a/dali/internal/system/common/performance-marker.cpp +++ b/dali/internal/system/common/performance-marker.cpp @@ -21,91 +21,83 @@ // EXTERNAL INCLUDES #include - - namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - struct NamePair { - PerformanceInterface::MarkerType type; - const char* const name; - PerformanceMarker::MarkerFilter group; + PerformanceInterface::MarkerType type; + const char* const name; + PerformanceMarker::MarkerFilter group; PerformanceMarker::MarkerEventType eventType; }; +// clang-format off const NamePair MARKER_LOOKUP[] = { // timed event names must be postfixed with with _START and _END // this is to allow tracers to extract the event name by removing the _START, _END strings // - { PerformanceInterface::VSYNC , "V_SYNC" , PerformanceMarker::V_SYNC_EVENTS, PerformanceMarker::SINGLE_EVENT }, - { PerformanceInterface::UPDATE_START , "UPDATE_START" , PerformanceMarker::UPDATE, PerformanceMarker::START_TIMED_EVENT }, - { PerformanceInterface::UPDATE_END , "UPDATE_END" , PerformanceMarker::UPDATE, PerformanceMarker::END_TIMED_EVENT }, - { PerformanceInterface::RENDER_START , "RENDER_START" , PerformanceMarker::RENDER, PerformanceMarker::START_TIMED_EVENT }, - { PerformanceInterface::RENDER_END , "RENDER_END" , PerformanceMarker::RENDER, PerformanceMarker::END_TIMED_EVENT }, - { PerformanceInterface::SWAP_START , "SWAP_START" , PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::START_TIMED_EVENT }, - { PerformanceInterface::SWAP_END , "SWAP_END" , PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::END_TIMED_EVENT }, - { PerformanceInterface::PROCESS_EVENTS_START, "PROCESS_EVENT_START" , PerformanceMarker::EVENT_PROCESS, PerformanceMarker::START_TIMED_EVENT }, - { PerformanceInterface::PROCESS_EVENTS_END, "PROCESS_EVENT_END" , PerformanceMarker::EVENT_PROCESS, PerformanceMarker::END_TIMED_EVENT }, - { PerformanceInterface::PAUSED , "PAUSED" , PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT }, - { PerformanceInterface::RESUME , "RESUMED" , PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT }, - { PerformanceInterface::START , "START" , PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::START_TIMED_EVENT }, - { PerformanceInterface::END , "END" , PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::END_TIMED_EVENT } + {PerformanceInterface::VSYNC, "V_SYNC", PerformanceMarker::V_SYNC_EVENTS, PerformanceMarker::SINGLE_EVENT }, + {PerformanceInterface::UPDATE_START, "UPDATE_START", PerformanceMarker::UPDATE, PerformanceMarker::START_TIMED_EVENT}, + {PerformanceInterface::UPDATE_END, "UPDATE_END", PerformanceMarker::UPDATE, PerformanceMarker::END_TIMED_EVENT }, + {PerformanceInterface::RENDER_START, "RENDER_START", PerformanceMarker::RENDER, PerformanceMarker::START_TIMED_EVENT}, + {PerformanceInterface::RENDER_END, "RENDER_END", PerformanceMarker::RENDER, PerformanceMarker::END_TIMED_EVENT }, + {PerformanceInterface::SWAP_START, "SWAP_START", PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::START_TIMED_EVENT}, + {PerformanceInterface::SWAP_END, "SWAP_END", PerformanceMarker::SWAP_BUFFERS, PerformanceMarker::END_TIMED_EVENT }, + {PerformanceInterface::PROCESS_EVENTS_START, "PROCESS_EVENT_START", PerformanceMarker::EVENT_PROCESS, PerformanceMarker::START_TIMED_EVENT}, + {PerformanceInterface::PROCESS_EVENTS_END, "PROCESS_EVENT_END", PerformanceMarker::EVENT_PROCESS, PerformanceMarker::END_TIMED_EVENT }, + {PerformanceInterface::PAUSED, "PAUSED", PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT }, + {PerformanceInterface::RESUME, "RESUMED", PerformanceMarker::LIFE_CYCLE_EVENTS, PerformanceMarker::SINGLE_EVENT }, + {PerformanceInterface::START, "START", PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::START_TIMED_EVENT}, + {PerformanceInterface::END, "END", PerformanceMarker::CUSTOM_EVENTS, PerformanceMarker::END_TIMED_EVENT } }; -} // un-named namespace - - +// clang-format on +} // namespace -PerformanceMarker::PerformanceMarker( PerformanceInterface::MarkerType type ) -:mType(type) +PerformanceMarker::PerformanceMarker(PerformanceInterface::MarkerType type) +: mType(type) { } -PerformanceMarker::PerformanceMarker( PerformanceInterface::MarkerType type, FrameTimeStamp frameInfo ) -:mType(type), - mTimeStamp(frameInfo) +PerformanceMarker::PerformanceMarker(PerformanceInterface::MarkerType type, FrameTimeStamp frameInfo) +: mType(type), + mTimeStamp(frameInfo) { } -const char* PerformanceMarker::GetName( ) const +const char* PerformanceMarker::GetName() const { - return MARKER_LOOKUP[ mType ].name; + return MARKER_LOOKUP[mType].name; } PerformanceMarker::MarkerEventType PerformanceMarker::GetEventType() const { - return MARKER_LOOKUP[ mType ].eventType; + return MARKER_LOOKUP[mType].eventType; } PerformanceMarker::MarkerFilter PerformanceMarker::GetFilterType() const { - return MARKER_LOOKUP[ mType ].group; + return MARKER_LOOKUP[mType].group; } -unsigned int PerformanceMarker::MicrosecondDiff( const PerformanceMarker& start,const PerformanceMarker& end ) +unsigned int PerformanceMarker::MicrosecondDiff(const PerformanceMarker& start, const PerformanceMarker& end) { - return FrameTimeStamp::MicrosecondDiff( start.mTimeStamp, end.mTimeStamp ); + return FrameTimeStamp::MicrosecondDiff(start.mTimeStamp, end.mTimeStamp); } -bool PerformanceMarker::IsFilterEnabled( MarkerFilter filter ) const +bool PerformanceMarker::IsFilterEnabled(MarkerFilter filter) const { - return (filter & MARKER_LOOKUP[ mType ].group); + return (filter & MARKER_LOOKUP[mType].group); } - } // namespace Adaptor } // namespace Internal } // namespace Dali - diff --git a/dali/internal/system/common/performance-marker.h b/dali/internal/system/common/performance-marker.h index e4cae4a..2b334f8 100644 --- a/dali/internal/system/common/performance-marker.h +++ b/dali/internal/system/common/performance-marker.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_PERFORMANCE_MARKER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,41 +19,36 @@ */ // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Marker used to record an event with a time stamp in Dali */ class PerformanceMarker { public: - - /** * Bitmask used to filter different types of markers based * on what group they belong to. */ enum MarkerFilter { - FILTERING_DISABLED = 0, ///< disabled - V_SYNC_EVENTS = 1 << 0, ///< v-sync - UPDATE = 1 << 1, ///< update start / end - RENDER = 1 << 2, ///< render start / end - EVENT_PROCESS = 1 << 3, ///< process events start / end - SWAP_BUFFERS = 1 << 4, ///< swap buffers start / end - LIFE_CYCLE_EVENTS = 1 << 5, ///< pause / resume - RESOURCE_EVENTS = 1 << 6, ///< resource events - CUSTOM_EVENTS = 1 << 7 + FILTERING_DISABLED = 0, ///< disabled + V_SYNC_EVENTS = 1 << 0, ///< v-sync + UPDATE = 1 << 1, ///< update start / end + RENDER = 1 << 2, ///< render start / end + EVENT_PROCESS = 1 << 3, ///< process events start / end + SWAP_BUFFERS = 1 << 4, ///< swap buffers start / end + LIFE_CYCLE_EVENTS = 1 << 5, ///< pause / resume + RESOURCE_EVENTS = 1 << 6, ///< resource events + CUSTOM_EVENTS = 1 << 7 }; /** @@ -61,25 +56,24 @@ public: */ enum MarkerEventType { - SINGLE_EVENT, ///< event is something that has no duration associated with it - START_TIMED_EVENT, ///< start of a timed event - END_TIMED_EVENT ///< end of a timed event + SINGLE_EVENT, ///< event is something that has no duration associated with it + START_TIMED_EVENT, ///< start of a timed event + END_TIMED_EVENT ///< end of a timed event }; - /** * @brief Constructor * @param[in] type marker type */ - PerformanceMarker( PerformanceInterface::MarkerType type ); + PerformanceMarker(PerformanceInterface::MarkerType type); /** * @brief Constructor * @param[in] type marker type * @param[in] time time stamp */ - PerformanceMarker( PerformanceInterface::MarkerType type, FrameTimeStamp time ); + PerformanceMarker(PerformanceInterface::MarkerType type, FrameTimeStamp time); /** * @return the time stamp @@ -107,28 +101,26 @@ public: */ MarkerFilter GetFilterType() const; - /** * @return marker name */ - const char* GetName( ) const; + const char* GetName() const; /** * @param start the start marker * @param end the end marker * @return difference in microseconds between two markers */ - static unsigned int MicrosecondDiff( const PerformanceMarker& start, const PerformanceMarker& end ); + static unsigned int MicrosecondDiff(const PerformanceMarker& start, const PerformanceMarker& end); /** * @return if a marker is enabled as part of a group */ - bool IsFilterEnabled( MarkerFilter filter ) const; -private: - - PerformanceInterface::MarkerType mType; ///< marker type - FrameTimeStamp mTimeStamp; ///< frame time stamp + bool IsFilterEnabled(MarkerFilter filter) const; +private: + PerformanceInterface::MarkerType mType; ///< marker type + FrameTimeStamp mTimeStamp; ///< frame time stamp }; } // namespace Adaptor diff --git a/dali/internal/system/common/performance-server.cpp b/dali/internal/system/common/performance-server.cpp index 6b73864..21f77a6 100644 --- a/dali/internal/system/common/performance-server.cpp +++ b/dali/internal/system/common/performance-server.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,43 +27,40 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { const unsigned int NANOSECONDS_PER_MICROSECOND = 1000u; -const float MICROSECONDS_TO_SECOND = 1e-6; +const float MICROSECONDS_TO_SECOND = 1e-6; } // unnamed namespace -PerformanceServer::PerformanceServer( AdaptorInternalServices& adaptorServices, - const EnvironmentOptions& environmentOptions) -: mEnvironmentOptions( environmentOptions ), - mKernelTrace( adaptorServices.GetKernelTraceInterface() ), - mSystemTrace( adaptorServices.GetSystemTraceInterface() ), +PerformanceServer::PerformanceServer(AdaptorInternalServices& adaptorServices, + const EnvironmentOptions& environmentOptions) +: mEnvironmentOptions(environmentOptions), + mKernelTrace(adaptorServices.GetKernelTraceInterface()), + mSystemTrace(adaptorServices.GetSystemTraceInterface()), mLogMutex(), #if defined(NETWORK_LOGGING_ENABLED) - mNetworkServer( adaptorServices, environmentOptions ), - mNetworkControlEnabled( mEnvironmentOptions.GetNetworkControlMode()), + mNetworkServer(adaptorServices, environmentOptions), + mNetworkControlEnabled(mEnvironmentOptions.GetNetworkControlMode()), #endif - mStatContextManager( *this ), - mStatisticsLogBitmask( 0 ), - mPerformanceOutputBitmask( 0 ), - mLoggingEnabled( false ), - mLogFunctionInstalled( false ) + mStatContextManager(*this), + mStatisticsLogBitmask(0), + mPerformanceOutputBitmask(0), + mLoggingEnabled(false), + mLogFunctionInstalled(false) { - SetLogging( mEnvironmentOptions.GetPerformanceStatsLoggingOptions(), - mEnvironmentOptions.GetPerformanceTimeStampOutput(), - mEnvironmentOptions.GetPerformanceStatsLoggingFrequency()); + SetLogging(mEnvironmentOptions.GetPerformanceStatsLoggingOptions(), + mEnvironmentOptions.GetPerformanceTimeStampOutput(), + mEnvironmentOptions.GetPerformanceStatsLoggingFrequency()); #if defined(NETWORK_LOGGING_ENABLED) - if( mNetworkControlEnabled ) + if(mNetworkControlEnabled) { - mLoggingEnabled = true; + mLoggingEnabled = true; mNetworkServer.Start(); } #endif @@ -72,28 +69,28 @@ PerformanceServer::PerformanceServer( AdaptorInternalServices& adaptorServices, PerformanceServer::~PerformanceServer() { #if defined(NETWORK_LOGGING_ENABLED) - if( mNetworkControlEnabled ) + if(mNetworkControlEnabled) { mNetworkServer.Stop(); } #endif - if( mLogFunctionInstalled ) + if(mLogFunctionInstalled) { mEnvironmentOptions.UnInstallLogFunction(); } } -void PerformanceServer::SetLogging( unsigned int statisticsLogOptions, - unsigned int timeStampOutput, - unsigned int logFrequency ) +void PerformanceServer::SetLogging(unsigned int statisticsLogOptions, + unsigned int timeStampOutput, + unsigned int logFrequency) { - mStatisticsLogBitmask = statisticsLogOptions; + mStatisticsLogBitmask = statisticsLogOptions; mPerformanceOutputBitmask = timeStampOutput; - mStatContextManager.SetLoggingLevel( mStatisticsLogBitmask, logFrequency); + mStatContextManager.SetLoggingLevel(mStatisticsLogBitmask, logFrequency); - if( ( mStatisticsLogBitmask == 0) && ( mPerformanceOutputBitmask == 0 )) + if((mStatisticsLogBitmask == 0) && (mPerformanceOutputBitmask == 0)) { mLoggingEnabled = false; } @@ -103,68 +100,68 @@ void PerformanceServer::SetLogging( unsigned int statisticsLogOptions, } } -void PerformanceServer::SetLoggingFrequency( unsigned int logFrequency, ContextId contextId ) +void PerformanceServer::SetLoggingFrequency(unsigned int logFrequency, ContextId contextId) { - mStatContextManager.SetLoggingFrequency( logFrequency, contextId ); + mStatContextManager.SetLoggingFrequency(logFrequency, contextId); } -void PerformanceServer::EnableLogging( bool enable, ContextId contextId ) +void PerformanceServer::EnableLogging(bool enable, ContextId contextId) { - mStatContextManager.EnableLogging( enable, contextId ); + mStatContextManager.EnableLogging(enable, contextId); } -PerformanceInterface::ContextId PerformanceServer::AddContext( const char* name ) +PerformanceInterface::ContextId PerformanceServer::AddContext(const char* name) { // for adding custom contexts - return mStatContextManager.AddContext( name, PerformanceMarker::CUSTOM_EVENTS ); + return mStatContextManager.AddContext(name, PerformanceMarker::CUSTOM_EVENTS); } -void PerformanceServer::RemoveContext( ContextId contextId ) +void PerformanceServer::RemoveContext(ContextId contextId) { - mStatContextManager.RemoveContext( contextId ); + mStatContextManager.RemoveContext(contextId); } -void PerformanceServer::AddMarker( MarkerType markerType, ContextId contextId ) +void PerformanceServer::AddMarker(MarkerType markerType, ContextId contextId) { // called only for custom markers - if( !mLoggingEnabled ) + if(!mLoggingEnabled) { return; } // Get the time stamp uint64_t timeStamp = 0; - TimeService::GetNanoseconds( timeStamp ); + TimeService::GetNanoseconds(timeStamp); timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds // Create a marker - PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) ); + PerformanceMarker marker(markerType, FrameTimeStamp(0, timeStamp)); // get the marker description for this context, e.g SIZE_NEGOTIATION_START - const char* const description = mStatContextManager.GetMarkerDescription( markerType, contextId ); + const char* const description = mStatContextManager.GetMarkerDescription(markerType, contextId); // log it - LogMarker( marker, description ); + LogMarker(marker, description); // Add custom marker to statistics context manager - mStatContextManager.AddCustomMarker( marker, contextId ); + mStatContextManager.AddCustomMarker(marker, contextId); } -void PerformanceServer::AddMarker( MarkerType markerType ) +void PerformanceServer::AddMarker(MarkerType markerType) { // called only for internal markers - if( !mLoggingEnabled ) + if(!mLoggingEnabled) { return; } - if( markerType == VSYNC ) + if(markerType == VSYNC) { // make sure log function is installed, note this will be called only from v-sync thread // if the v-sync thread has already installed one, it won't make any difference. - if( ! mLogFunctionInstalled ) + if(!mLogFunctionInstalled) { mEnvironmentOptions.InstallLogFunction(); mLogFunctionInstalled = true; @@ -173,67 +170,64 @@ void PerformanceServer::AddMarker( MarkerType markerType ) // Get the time uint64_t timeStamp = 0; - TimeService::GetNanoseconds( timeStamp ); + TimeService::GetNanoseconds(timeStamp); timeStamp /= NANOSECONDS_PER_MICROSECOND; // Convert to microseconds // Create a marker - PerformanceMarker marker( markerType, FrameTimeStamp( 0, timeStamp ) ); + PerformanceMarker marker(markerType, FrameTimeStamp(0, timeStamp)); // log it - LogMarker(marker, marker.GetName() ); + LogMarker(marker, marker.GetName()); // Add internal marker to statistics context manager - mStatContextManager.AddInternalMarker( marker ); - + mStatContextManager.AddInternalMarker(marker); } -void PerformanceServer::LogContextStatistics( const char* const text ) +void PerformanceServer::LogContextStatistics(const char* const text) { - Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, text ); + Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, text); } -void PerformanceServer::LogMarker( const PerformanceMarker& marker, const char* const description ) +void PerformanceServer::LogMarker(const PerformanceMarker& marker, const char* const description) { #if defined(NETWORK_LOGGING_ENABLED) // log to the network ( this is thread safe ) - if( mNetworkControlEnabled ) + if(mNetworkControlEnabled) { - mNetworkServer.TransmitMarker( marker, description ); + mNetworkServer.TransmitMarker(marker, description); } #endif // log to kernel trace - if( mPerformanceOutputBitmask & OUTPUT_KERNEL_TRACE ) + if(mPerformanceOutputBitmask & OUTPUT_KERNEL_TRACE) { // Kernel tracing implementation may not be thread safe - Mutex::ScopedLock lock( mLogMutex ); + Mutex::ScopedLock lock(mLogMutex); // description will be something like UPDATE_START or UPDATE_END - mKernelTrace.Trace( marker, description ); + mKernelTrace.Trace(marker, description); } // log to system trace - if( mPerformanceOutputBitmask & OUTPUT_SYSTEM_TRACE ) + if(mPerformanceOutputBitmask & OUTPUT_SYSTEM_TRACE) { // System tracing implementation may not be thread safe - Mutex::ScopedLock lock( mLogMutex ); + Mutex::ScopedLock lock(mLogMutex); - mSystemTrace.Trace( marker, description ); + mSystemTrace.Trace(marker, description); } // log to Dali log ( this is thread safe ) - if ( mPerformanceOutputBitmask & OUTPUT_DALI_LOG ) + if(mPerformanceOutputBitmask & OUTPUT_DALI_LOG) { - Integration::Log::LogMessage( Dali::Integration::Log::DebugInfo, - "%.6f (seconds), %s\n", - float( marker.GetTimeStamp().microseconds ) * MICROSECONDS_TO_SECOND, - description ); - + Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, + "%.6f (seconds), %s\n", + float(marker.GetTimeStamp().microseconds) * MICROSECONDS_TO_SECOND, + description); } } +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali diff --git a/dali/internal/system/common/performance-server.h b/dali/internal/system/common/performance-server.h index 74b1c0d..f4aaf15 100644 --- a/dali/internal/system/common/performance-server.h +++ b/dali/internal/system/common/performance-server.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_PERFORMANCE_SERVER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,25 +19,22 @@ */ // EXTERNAL INCLDUES -#include #include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include #include #include namespace Dali { - namespace Internal { - namespace Adaptor { - class EnvironmentOptions; class StatContext; /** @@ -48,14 +45,13 @@ class StatContext; class PerformanceServer : public PerformanceInterface, public StatContextLogInterface { public: - /** * @brief Constructor * @param[in] adaptorServices adaptor internal services * @param[in] environmentOptions environment options */ - PerformanceServer( AdaptorInternalServices& adaptorServices, - const EnvironmentOptions& environmentOptions ); + PerformanceServer(AdaptorInternalServices& adaptorServices, + const EnvironmentOptions& environmentOptions); /** * Destructor @@ -65,81 +61,77 @@ public: /** * @copydoc PerformanceLogger::AddContext() */ - ContextId AddContext( const char* name ) override; + ContextId AddContext(const char* name) override; /** * @copydoc PerformanceLogger::RemoveContext() */ - void RemoveContext( ContextId contextId ) override; + void RemoveContext(ContextId contextId) override; /** * @copydoc PerformanceInterface::AddMarker( MarkerType markerType ) */ - void AddMarker( MarkerType markerType ) override; + void AddMarker(MarkerType markerType) override; /** * @copydoc PerformanceLogger::AddMarker( MarkerType markerType, ContextId contextId ) */ - void AddMarker( MarkerType markerType, ContextId contextId ) override; + void AddMarker(MarkerType markerType, ContextId contextId) override; /** * @copydoc PerformanceInterface::SetLogging() */ - virtual void SetLogging( unsigned int statisticsLogOptions, - unsigned int timeStampOutput, - unsigned int logFrequency ); + virtual void SetLogging(unsigned int statisticsLogOptions, + unsigned int timeStampOutput, + unsigned int logFrequency); /** * @copydoc PerformanceLogger::SetLoggingFrequency() */ - void SetLoggingFrequency( unsigned int logFrequency, ContextId contextId ) override; + void SetLoggingFrequency(unsigned int logFrequency, ContextId contextId) override; /** * @copydoc PerformanceLogger::EnableLogging() */ - void EnableLogging( bool enable, ContextId contextId ) override; + void EnableLogging(bool enable, ContextId contextId) override; public: //StatLogInterface - /** * @copydoc StatLogInterface::LogContextStatistics() */ - void LogContextStatistics( const char* const text ) override; + void LogContextStatistics(const char* const text) override; private: - /** * @brief log the marker out to kernel/ DALi log * @param[in] marker performance marker * @param[in] description marker description */ - void LogMarker( const PerformanceMarker& marker, const char* const description ); + void LogMarker(const PerformanceMarker& marker, const char* const description); private: - - const EnvironmentOptions& mEnvironmentOptions; ///< environment options - TraceInterface& mKernelTrace; ///< kernel trace interface - TraceInterface& mSystemTrace; ///< system trace interface - Dali::Mutex mLogMutex; ///< mutex + const EnvironmentOptions& mEnvironmentOptions; ///< environment options + TraceInterface& mKernelTrace; ///< kernel trace interface + TraceInterface& mSystemTrace; ///< system trace interface + Dali::Mutex mLogMutex; ///< mutex #if defined(NETWORK_LOGGING_ENABLED) - NetworkPerformanceServer mNetworkServer; ///< network server - bool mNetworkControlEnabled; ///< Whether network control is enabled + NetworkPerformanceServer mNetworkServer; ///< network server + bool mNetworkControlEnabled; ///< Whether network control is enabled #endif - StatContextManager mStatContextManager; ///< Stat context manager - unsigned int mStatisticsLogBitmask; ///< statistics log level - unsigned int mPerformanceOutputBitmask; ///< performance marker output + StatContextManager mStatContextManager; ///< Stat context manager + unsigned int mStatisticsLogBitmask; ///< statistics log level + unsigned int mPerformanceOutputBitmask; ///< performance marker output - bool mLoggingEnabled:1; ///< whether logging update / render to a log is enabled - bool mLogFunctionInstalled:1; ///< whether the log function is installed + bool mLoggingEnabled : 1; ///< whether logging update / render to a log is enabled + bool mLogFunctionInstalled : 1; ///< whether the log function is installed }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_PERFORMANCE_SERVER_H diff --git a/dali/internal/system/common/shared-file.cpp b/dali/internal/system/common/shared-file.cpp index 32613d8..acec053 100644 --- a/dali/internal/system/common/shared-file.cpp +++ b/dali/internal/system/common/shared-file.cpp @@ -19,32 +19,30 @@ #include // EXTERNAL INCLUDES -#include -#include +#include #include #include -#include -#include #include #include +#include +#include +#include #include - namespace Dali { namespace Internal { namespace Adaptor { - SharedFile* SharedFile::New(const char* filename, int size, bool isSystem) { - SharedFile *sf = NULL; + SharedFile* sf = NULL; sf = new SharedFile; - bool opened = sf->OpenFile( filename, size, isSystem ); - if( !opened ) + bool opened = sf->OpenFile(filename, size, isSystem); + if(!opened) { delete sf; sf = NULL; @@ -67,22 +65,22 @@ SharedFile::~SharedFile() void SharedFile::Close() { - if( mAddress != NULL ) + if(mAddress != NULL) { - munmap( mAddress, mSize ); + munmap(mAddress, mSize); mAddress = NULL; } - if( mFileDescriptor >= 0 ) + if(mFileDescriptor >= 0) { - close( mFileDescriptor ); + close(mFileDescriptor); mFileDescriptor = -1; } } unsigned char* SharedFile::GetAddress() { - return static_cast( mAddress ); + return static_cast(mAddress); } bool SharedFile::OpenFile(const char* filename, int size, bool isSystem) @@ -92,24 +90,24 @@ bool SharedFile::OpenFile(const char* filename, int size, bool isSystem) mode_t mode; mode = S_IRUSR | S_IWUSR; - if( isSystem ) + if(isSystem) { mode |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; } - mFileDescriptor = Open( filename, size, O_RDONLY, mode ); + mFileDescriptor = Open(filename, size, O_RDONLY, mode); - if( mFileDescriptor >= 0 ) + if(mFileDescriptor >= 0) { mFilename = filename; - mSize = size; - mAddress = mmap( NULL, mSize, PROT_READ, MAP_SHARED, mFileDescriptor, 0 ); + mSize = size; + mAddress = mmap(NULL, mSize, PROT_READ, MAP_SHARED, mFileDescriptor, 0); // MAP_FAILED is a macro with C cast #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - if( mAddress != MAP_FAILED ) + if(mAddress != MAP_FAILED) { opened = true; } @@ -118,6 +116,6 @@ bool SharedFile::OpenFile(const char* filename, int size, bool isSystem) return opened; } -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/system/common/shared-file.h b/dali/internal/system/common/shared-file.h index 7abe53a..28e9323 100644 --- a/dali/internal/system/common/shared-file.h +++ b/dali/internal/system/common/shared-file.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_SHARED_FILE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -28,7 +28,6 @@ namespace Internal { namespace Adaptor { - class SharedFile { public: @@ -36,7 +35,7 @@ public: * Open an existing shared file for read/write * @return The shared file, or NULL if a file could not be opened and mapped. */ - static SharedFile* New( const char* filename, int size, bool isSystem ); + static SharedFile* New(const char* filename, int size, bool isSystem); /** * Constructor @@ -52,13 +51,13 @@ public: * Opens a file descriptor to shared memory segment * @return The file descriptor */ - int Open( const char* filename, int size, int oflag, mode_t mode ); + int Open(const char* filename, int size, int oflag, mode_t mode); /** * Opens a file for read/write * @return true if opened, false on error. */ - bool OpenFile( const char* filename, int size, bool isSystem ); + bool OpenFile(const char* filename, int size, bool isSystem); /** * Close the shared file @@ -78,8 +77,8 @@ private: std::string mFilename; }; -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_SHARED_FILE_H diff --git a/dali/internal/system/common/sound-player-impl.cpp b/dali/internal/system/common/sound-player-impl.cpp index 572747d..e662742 100644 --- a/dali/internal/system/common/sound-player-impl.cpp +++ b/dali/internal/system/common/sound-player-impl.cpp @@ -19,21 +19,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { - const char* const SIGNAL_SOUND_PLAY_FINISHED = "soundPlayFinished"; // Type Registration @@ -42,15 +38,15 @@ Dali::BaseHandle GetInstance() return SoundPlayer::Get(); } -Dali::TypeRegistration SOUND_PLAYER_TYPE( typeid(Dali::SoundPlayer), typeid(Dali::BaseHandle), GetInstance ); +Dali::TypeRegistration SOUND_PLAYER_TYPE(typeid(Dali::SoundPlayer), typeid(Dali::BaseHandle), GetInstance); -Dali::SignalConnectorType SIGNAL_CONNECTOR_1( SOUND_PLAYER_TYPE, SIGNAL_SOUND_PLAY_FINISHED, Dali::Internal::Adaptor::SoundPlayer::DoConnectSignal ); +Dali::SignalConnectorType SIGNAL_CONNECTOR_1(SOUND_PLAYER_TYPE, SIGNAL_SOUND_PLAY_FINISHED, Dali::Internal::Adaptor::SoundPlayer::DoConnectSignal); } // unnamed namespace Dali::SoundPlayer SoundPlayer::New() { - Dali::SoundPlayer player = Dali::SoundPlayer( new SoundPlayer() ); + Dali::SoundPlayer player = Dali::SoundPlayer(new SoundPlayer()); return player; } @@ -58,34 +54,34 @@ Dali::SoundPlayer SoundPlayer::Get() { Dali::SoundPlayer player; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::SoundPlayer ) ); - if ( handle ) + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::SoundPlayer)); + if(handle) { // If so, downcast the handle - player = Dali::SoundPlayer( dynamic_cast< SoundPlayer* >( handle.GetObjectPtr() ) ); + player = Dali::SoundPlayer(dynamic_cast(handle.GetObjectPtr())); } else { - player = Dali::SoundPlayer( New() ); - service.Register( typeid( player ), player ); + player = Dali::SoundPlayer(New()); + service.Register(typeid(player), player); } } return player; } -int SoundPlayer::PlaySound( const std::string fileName ) +int SoundPlayer::PlaySound(const std::string fileName) { - return mPlugin.PlaySound( fileName ); + return mPlugin.PlaySound(fileName); } -void SoundPlayer::Stop( int handle ) +void SoundPlayer::Stop(int handle) { - mPlugin.StopSound( handle ); + mPlugin.StopSound(handle); } SoundPlayer::SoundPlayFinishedSignalType& SoundPlayer::SoundPlayFinishedSignal() @@ -93,14 +89,14 @@ SoundPlayer::SoundPlayFinishedSignalType& SoundPlayer::SoundPlayFinishedSignal() return mSoundPlayFinishedSignal; } -bool SoundPlayer::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool SoundPlayer::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - bool connected( true ); - SoundPlayer* player = dynamic_cast( object ); + bool connected(true); + SoundPlayer* player = dynamic_cast(object); - if( player && ( SIGNAL_SOUND_PLAY_FINISHED == signalName ) ) + if(player && (SIGNAL_SOUND_PLAY_FINISHED == signalName)) { - player->SoundPlayFinishedSignal().Connect( tracker, functor ); + player->SoundPlayFinishedSignal().Connect(tracker, functor); } else { @@ -112,7 +108,7 @@ bool SoundPlayer::DoConnectSignal( BaseObject* object, ConnectionTrackerInterfac } SoundPlayer::SoundPlayer() -: mPlugin( FeedbackPluginProxy::DEFAULT_OBJECT_NAME ) +: mPlugin(FeedbackPluginProxy::DEFAULT_OBJECT_NAME) { } @@ -124,10 +120,10 @@ void SoundPlayer::EmitSoundPlayFinishedSignal() { // Emit SoundPlayFinished signal - if ( !mSoundPlayFinishedSignal.Empty() ) + if(!mSoundPlayFinishedSignal.Empty()) { - Dali::SoundPlayer handle( this ); - mSoundPlayFinishedSignal.Emit( handle ); + Dali::SoundPlayer handle(this); + mSoundPlayFinishedSignal.Emit(handle); } } diff --git a/dali/internal/system/common/sound-player-impl.h b/dali/internal/system/common/sound-player-impl.h index a68b260..230cbee 100644 --- a/dali/internal/system/common/sound-player-impl.h +++ b/dali/internal/system/common/sound-player-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_SOUND_PLAYER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -28,21 +28,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Plays haptic effects. */ class SoundPlayer : public Dali::BaseObject { - public: - typedef Dali::SoundPlayer::SoundPlayFinishedSignalType SoundPlayFinishedSignalType; /** @@ -81,10 +76,9 @@ public: * @return True if the signal was connected. * @post If a signal was connected, ownership of functor was passed to CallbackBase. Otherwise the caller is responsible for deleting the unused functor. */ - static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ); + static bool DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor); private: - /** * Private Constructor; see also soundPlayer::New() * @param[in] soundPlayer The public sound player class @@ -108,8 +102,7 @@ private: SoundPlayer& operator=(SoundPlayer&); private: - - FeedbackPluginProxy mPlugin; + FeedbackPluginProxy mPlugin; SoundPlayFinishedSignalType mSoundPlayFinishedSignal; }; @@ -117,12 +110,11 @@ private: } // namespace Internal - // Helpers for public-api forwarding methods inline Internal::Adaptor::SoundPlayer& GetImplementation(Dali::SoundPlayer& player) { - DALI_ASSERT_ALWAYS( player && "SoundPlayer handle is empty" ); + DALI_ASSERT_ALWAYS(player && "SoundPlayer handle is empty"); BaseObject& handle = player.GetBaseObject(); @@ -131,7 +123,7 @@ inline Internal::Adaptor::SoundPlayer& GetImplementation(Dali::SoundPlayer& play inline const Internal::Adaptor::SoundPlayer& GetImplementation(const Dali::SoundPlayer& player) { - DALI_ASSERT_ALWAYS( player && "SoundPlayer handle is empty" ); + DALI_ASSERT_ALWAYS(player && "SoundPlayer handle is empty"); const BaseObject& handle = player.GetBaseObject(); diff --git a/dali/internal/system/common/stat-context-log-interface.h b/dali/internal/system/common/stat-context-log-interface.h index 0da1345..c994a04 100644 --- a/dali/internal/system/common/stat-context-log-interface.h +++ b/dali/internal/system/common/stat-context-log-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_STATISTICS_STAT_CONTEXT_LOG_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,29 +20,23 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Abstract interface used to log statistics data */ class StatContextLogInterface { public: - /** * @brief Used to log statistics out * @param[in] text log the text */ - virtual void LogContextStatistics( const char* const text) = 0; - + virtual void LogContextStatistics(const char* const text) = 0; protected: - /** * @brief Constructor */ @@ -58,20 +52,17 @@ protected: } private: - // Undefined copy constructor. - StatContextLogInterface( const StatContextLogInterface& ); + StatContextLogInterface(const StatContextLogInterface&); // Undefined assignment operator. - StatContextLogInterface& operator=( const StatContextLogInterface& ); - + StatContextLogInterface& operator=(const StatContextLogInterface&); }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_STATISTICS_STAT_CONTEXT_LOG_INTERFACE_H diff --git a/dali/internal/system/common/stat-context-manager.cpp b/dali/internal/system/common/stat-context-manager.cpp index c6972e2..24e7028 100644 --- a/dali/internal/system/common/stat-context-manager.cpp +++ b/dali/internal/system/common/stat-context-manager.cpp @@ -23,121 +23,115 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { -const char* const UPDATE_CONTEXT_NAME = "Update"; -const char* const RENDER_CONTEXT_NAME = "Render"; -const char* const EVENT_CONTEXT_NAME = "Event"; +const char* const UPDATE_CONTEXT_NAME = "Update"; +const char* const RENDER_CONTEXT_NAME = "Render"; +const char* const EVENT_CONTEXT_NAME = "Event"; const unsigned int DEFAULT_LOG_FREQUENCY = 2; -} +} // namespace -StatContextManager::StatContextManager( StatContextLogInterface& logInterface ) -: mLogInterface( logInterface ), - mNextContextId( 0 ), +StatContextManager::StatContextManager(StatContextLogInterface& logInterface) +: mLogInterface(logInterface), + mNextContextId(0), mStatisticsLogBitmask(0), - mLogFrequency( DEFAULT_LOG_FREQUENCY ) + mLogFrequency(DEFAULT_LOG_FREQUENCY) { - mStatContexts.Reserve(4); // intially reserve enough for 3 internal + 1 custom // Add defaults - mUpdateStats = AddContext( UPDATE_CONTEXT_NAME, PerformanceMarker::UPDATE ); - mRenderStats = AddContext( RENDER_CONTEXT_NAME, PerformanceMarker::RENDER ); - mEventStats = AddContext( EVENT_CONTEXT_NAME, PerformanceMarker::EVENT_PROCESS ); - + mUpdateStats = AddContext(UPDATE_CONTEXT_NAME, PerformanceMarker::UPDATE); + mRenderStats = AddContext(RENDER_CONTEXT_NAME, PerformanceMarker::RENDER); + mEventStats = AddContext(EVENT_CONTEXT_NAME, PerformanceMarker::EVENT_PROCESS); } StatContextManager::~StatContextManager() { - for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it ) + for(StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it) { StatContext* context = *it; delete context; } mStatContexts.Clear(); } -PerformanceInterface::ContextId StatContextManager::AddContext( const char* const name, - PerformanceMarker::MarkerFilter type ) +PerformanceInterface::ContextId StatContextManager::AddContext(const char* const name, + PerformanceMarker::MarkerFilter type) { unsigned int contextId = mNextContextId++; - DALI_ASSERT_DEBUG( NULL == GetContext( contextId ) ); + DALI_ASSERT_DEBUG(NULL == GetContext(contextId)); // logging enabled by default - StatContext* statContext = new StatContext( contextId, name, type, mLogFrequency , mLogInterface ); + StatContext* statContext = new StatContext(contextId, name, type, mLogFrequency, mLogInterface); // check to see if custom markers are enabled - if( ! ( mStatisticsLogBitmask & PerformanceInterface::LOG_CUSTOM_MARKERS ) ) + if(!(mStatisticsLogBitmask & PerformanceInterface::LOG_CUSTOM_MARKERS)) { - statContext->EnableLogging( false ); + statContext->EnableLogging(false); } - mStatContexts.PushBack( statContext ); + mStatContexts.PushBack(statContext); return contextId; } -void StatContextManager::AddInternalMarker( const PerformanceMarker& marker ) +void StatContextManager::AddInternalMarker(const PerformanceMarker& marker) { // log to the stat contexts, can be called from multiple threads so we // protect the data - Mutex::ScopedLock lock( mDataMutex ); - for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it ) + Mutex::ScopedLock lock(mDataMutex); + for(StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it) { StatContext* context = *it; - context->ProcessInternalMarker( marker ); + context->ProcessInternalMarker(marker); } } -void StatContextManager::AddCustomMarker( const PerformanceMarker& marker, PerformanceInterface::ContextId contextId ) +void StatContextManager::AddCustomMarker(const PerformanceMarker& marker, PerformanceInterface::ContextId contextId) { // log to the stat contexts, can be called from multiple threads so we // protect the data - Mutex::ScopedLock lock( mDataMutex ); - StatContext* context = GetContext( contextId ); - if( context ) + Mutex::ScopedLock lock(mDataMutex); + StatContext* context = GetContext(contextId); + if(context) { - context->ProcessCustomMarker( marker ); + context->ProcessCustomMarker(marker); } } -void StatContextManager::RemoveContext(PerformanceInterface::ContextId contextId ) +void StatContextManager::RemoveContext(PerformanceInterface::ContextId contextId) { - for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it ) + for(StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it) { StatContext* context = *it; - if( context->GetId() == contextId ) + if(context->GetId() == contextId) { delete context; - mStatContexts.Erase( it ); + mStatContexts.Erase(it); return; } } } - -void StatContextManager::EnableLogging( bool enable, PerformanceInterface::ContextId contextId ) +void StatContextManager::EnableLogging(bool enable, PerformanceInterface::ContextId contextId) { - StatContext* context = GetContext( contextId ); - if( context ) + StatContext* context = GetContext(contextId); + if(context) { - context->EnableLogging( enable ); + context->EnableLogging(enable); } } -void StatContextManager::SetLoggingLevel( unsigned int statisticsLogOptions, unsigned int logFrequency) +void StatContextManager::SetLoggingLevel(unsigned int statisticsLogOptions, unsigned int logFrequency) { mStatisticsLogBitmask = statisticsLogOptions; - if( mStatisticsLogBitmask == PerformanceInterface::LOG_EVERYTHING ) + if(mStatisticsLogBitmask == PerformanceInterface::LOG_EVERYTHING) { mStatisticsLogBitmask = 0xFFFFFFFF; // enable everything } @@ -146,62 +140,61 @@ void StatContextManager::SetLoggingLevel( unsigned int statisticsLogOptions, un // currently uses DALI_LOG_PERFORMANCE_STATS_FREQ environment variable to determine to log frequency // if it's not set it will be zero - if( mLogFrequency == 0 ) + if(mLogFrequency == 0) { mLogFrequency = DEFAULT_LOG_FREQUENCY; } - EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mUpdateStats ); - EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mRenderStats ); - EnableLogging( mStatisticsLogBitmask & PerformanceInterface::LOG_EVENT_PROCESS, mEventStats ); + EnableLogging(mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mUpdateStats); + EnableLogging(mStatisticsLogBitmask & PerformanceInterface::LOG_UPDATE_RENDER, mRenderStats); + EnableLogging(mStatisticsLogBitmask & PerformanceInterface::LOG_EVENT_PROCESS, mEventStats); - for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it ) + for(StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it) { - StatContext* context = *it; - context->SetLogFrequency( mLogFrequency ); + StatContext* context = *it; + context->SetLogFrequency(mLogFrequency); } } -void StatContextManager::SetLoggingFrequency( unsigned int logFrequency, - PerformanceInterface::ContextId contextId ) +void StatContextManager::SetLoggingFrequency(unsigned int logFrequency, + PerformanceInterface::ContextId contextId) { - StatContext* context = GetContext( contextId ); - if( context ) + StatContext* context = GetContext(contextId); + if(context) { - if( logFrequency == 0 ) + if(logFrequency == 0) { logFrequency = DEFAULT_LOG_FREQUENCY; } - context->SetLogFrequency( logFrequency ); + context->SetLogFrequency(logFrequency); } } const char* StatContextManager::GetContextName(PerformanceInterface::ContextId contextId) const { StatContext* context = GetContext(contextId); - if( context ) + if(context) { return context->GetName(); } return "context not found"; } -const char* StatContextManager::GetMarkerDescription( PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId ) const +const char* StatContextManager::GetMarkerDescription(PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId) const { StatContext* context = GetContext(contextId); - if( context ) + if(context) { - return context->GetMarkerDescription( type ); + return context->GetMarkerDescription(type); } return "context not found"; } - -StatContext* StatContextManager::GetContext( PerformanceInterface::ContextId contextId ) const +StatContext* StatContextManager::GetContext(PerformanceInterface::ContextId contextId) const { - for( StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it ) + for(StatContexts::Iterator it = mStatContexts.Begin(), itEnd = mStatContexts.End(); it != itEnd; ++it) { StatContext* context = *it; - if( context->GetId() == contextId ) + if(context->GetId() == contextId) { return context; } @@ -210,11 +203,8 @@ StatContext* StatContextManager::GetContext( PerformanceInterface::ContextId con return NULL; } +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali - - diff --git a/dali/internal/system/common/stat-context-manager.h b/dali/internal/system/common/stat-context-manager.h index e1521a3..9f82ab5 100644 --- a/dali/internal/system/common/stat-context-manager.h +++ b/dali/internal/system/common/stat-context-manager.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,20 +22,16 @@ #include // INTERNAL INCLUDES +#include #include #include -#include - namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Class to manage StatContext objects. * @@ -52,119 +48,113 @@ namespace Adaptor */ class StatContextManager { - public: - - /** + /** * @brief Constructor * @param[in] logInterface interface to log statistics to */ - StatContextManager( StatContextLogInterface& logInterface ); + StatContextManager(StatContextLogInterface& logInterface); - /** + /** * @brief destructor, not intended as a bass class */ - ~StatContextManager(); + ~StatContextManager(); - /** + /** * @brief Add a context * @param[in] name Name of the context to print in console * @param[in] type the type of events to filter ( e.g. event, update, render or custom) * @return The ID to give the context */ - PerformanceInterface::ContextId AddContext( const char* const name, PerformanceMarker::MarkerFilter type ); + PerformanceInterface::ContextId AddContext(const char* const name, PerformanceMarker::MarkerFilter type); - /** + /** * @brief Remove a context * @param[in] contextId id of the context to remove */ - void RemoveContext(PerformanceInterface::ContextId contextId ); + void RemoveContext(PerformanceInterface::ContextId contextId); - /** + /** * @brief Add an internal marker (e.g. v-sync, update, render markers) * @param[in] marker the marker to add */ - void AddInternalMarker( const PerformanceMarker& marker ); + void AddInternalMarker(const PerformanceMarker& marker); - /** + /** * @brief Add a custom marker defined by the application * @param[in] marker the marker to add * @param[in] contextId the context the custom marker is designed for */ - void AddCustomMarker( const PerformanceMarker& marker , PerformanceInterface::ContextId contextId ); + void AddCustomMarker(const PerformanceMarker& marker, PerformanceInterface::ContextId contextId); - /** + /** * @brief Get the nane of a context * @param[in] contextId id of the context to get the name * @return context name */ - const char* GetContextName( PerformanceInterface::ContextId contextId ) const; + const char* GetContextName(PerformanceInterface::ContextId contextId) const; - /** + /** * @brief Get the full description of a marker for this context * @param[in] type marker type, for a customer marker this will be either START or END * @param[in] contextId id of the context to get the name * @return marker description in relation to this context */ - const char* GetMarkerDescription( PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId ) const; - + const char* GetMarkerDescription(PerformanceInterface::MarkerType type, PerformanceInterface::ContextId contextId) const; - /** + /** * @brief enable / disable logging for a context * @param[in] enable whether to enable logging * @param[in] contextId the context to configure */ - void EnableLogging( bool enable, PerformanceInterface::ContextId contextId ); + void EnableLogging(bool enable, PerformanceInterface::ContextId contextId); - /** + /** * @brief set global logging level and frequency. * @param[in] statisticsLogOptions log options * @param[in] logFrequency frequency in seconds */ - void SetLoggingLevel( unsigned int statisticsLogOptions, unsigned int logFrequency); + void SetLoggingLevel(unsigned int statisticsLogOptions, unsigned int logFrequency); - /** + /** * @brief Set the frequency of logging for an individual context * @param[in] logFrequency log frequency in seconds * @param[in] contextId the context to configure */ - void SetLoggingFrequency( unsigned int logFrequency, PerformanceInterface::ContextId contextId ); + void SetLoggingFrequency(unsigned int logFrequency, PerformanceInterface::ContextId contextId); - private: +private: + StatContextManager(const StatContextManager&); ///< Undefined + StatContextManager& operator=(const StatContextManager&); ///< Undefined - StatContextManager( const StatContextManager& ); ///< Undefined - StatContextManager& operator=( const StatContextManager& ); ///< Undefined + typedef Dali::Vector StatContexts; - typedef Dali::Vector< StatContext* > StatContexts; - - /** + /** * @brief helper * @param[in] contextId the context to get * @return context */ - StatContext* GetContext( PerformanceInterface::ContextId contextId ) const; + StatContext* GetContext(PerformanceInterface::ContextId contextId) const; - Dali::Mutex mDataMutex; ///< mutex - StatContexts mStatContexts; ///< The list of stat contexts - StatContextLogInterface& mLogInterface; ///< Log interface + Dali::Mutex mDataMutex; ///< mutex + StatContexts mStatContexts; ///< The list of stat contexts + StatContextLogInterface& mLogInterface; ///< Log interface - PerformanceInterface::ContextId mNextContextId; ///< The next valid context ID + PerformanceInterface::ContextId mNextContextId; ///< The next valid context ID - // Some defaults contexts - PerformanceInterface::ContextId mUpdateStats; ///< update time statistics - PerformanceInterface::ContextId mRenderStats; ///< render time statistics - PerformanceInterface::ContextId mEventStats; ///< event time statistics + // Some defaults contexts + PerformanceInterface::ContextId mUpdateStats; ///< update time statistics + PerformanceInterface::ContextId mRenderStats; ///< render time statistics + PerformanceInterface::ContextId mEventStats; ///< event time statistics - unsigned int mStatisticsLogBitmask; ///< statistics log bitmask - unsigned int mLogFrequency; ///< log frequency + unsigned int mStatisticsLogBitmask; ///< statistics log bitmask + unsigned int mLogFrequency; ///< log frequency }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_MANAGER_H - diff --git a/dali/internal/system/common/stat-context.cpp b/dali/internal/system/common/stat-context.cpp index 7a7a674..178880f 100644 --- a/dali/internal/system/common/stat-context.cpp +++ b/dali/internal/system/common/stat-context.cpp @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include @@ -27,47 +26,44 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - #define TIME_FMT "%0.2f ms" // 2 decimal places, e.g. 5.34 ms #define TOTAL_TIME_FMT "%0.1f secs" // 1 decimal place, e.g. 4.5 seconds namespace { -const unsigned int MILLISECONDS_PER_SECOND = 1000; ///< 1000 milliseconds per second -const char* const UNKNOWN_CONTEXT_NAME = "UNKNOWN_CONTEXT_NAME"; +const unsigned int MILLISECONDS_PER_SECOND = 1000; ///< 1000 milliseconds per second +const char* const UNKNOWN_CONTEXT_NAME = "UNKNOWN_CONTEXT_NAME"; const unsigned int MICROSECONDS_PER_SECOND = 1000000; ///< 1000000 microseconds per second -const unsigned int CONTEXT_LOG_SIZE = 120; +const unsigned int CONTEXT_LOG_SIZE = 120; -} +} // namespace -StatContext::StatContext( unsigned int id, - const char* const contextName, - PerformanceMarker::MarkerFilter contextType, - unsigned int logFrequencySeconds, - StatContextLogInterface& logInterface ) +StatContext::StatContext(unsigned int id, + const char* const contextName, + PerformanceMarker::MarkerFilter contextType, + unsigned int logFrequencySeconds, + StatContextLogInterface& logInterface) : mInitialMarker(PerformanceInterface::VSYNC), - mName( contextName ), - mLogInterface( logInterface ), - mNamePlusStart( std::string(contextName) + "_START" ), - mNamePlusEnd( std::string(contextName) + "_END" ), - mId( id ), - mLogFrequencyMicroseconds( logFrequencySeconds * MICROSECONDS_PER_SECOND ), - mFilterType( contextType ), - mLoggingEnabled( true ), - mInitialMarkerSet( false ) -{ - mTempLogBuffer = new char[ CONTEXT_LOG_SIZE ]; + mName(contextName), + mLogInterface(logInterface), + mNamePlusStart(std::string(contextName) + "_START"), + mNamePlusEnd(std::string(contextName) + "_END"), + mId(id), + mLogFrequencyMicroseconds(logFrequencySeconds * MICROSECONDS_PER_SECOND), + mFilterType(contextType), + mLoggingEnabled(true), + mInitialMarkerSet(false) +{ + mTempLogBuffer = new char[CONTEXT_LOG_SIZE]; } StatContext::~StatContext() { - delete []mTempLogBuffer; + delete[] mTempLogBuffer; } unsigned int StatContext::GetId() const { @@ -79,109 +75,107 @@ const char* StatContext::GetName() const return mName; } -const char* StatContext::GetMarkerDescription( PerformanceInterface::MarkerType type ) const +const char* StatContext::GetMarkerDescription(PerformanceInterface::MarkerType type) const { - if( type == PerformanceInterface::START ) + if(type == PerformanceInterface::START) { return mNamePlusStart.c_str(); } - else if( type == PerformanceInterface::END ) + else if(type == PerformanceInterface::END) { return mNamePlusEnd.c_str(); } return UNKNOWN_CONTEXT_NAME; } -void StatContext::SetLogFrequency( unsigned int logFrequencySeconds ) +void StatContext::SetLogFrequency(unsigned int logFrequencySeconds) { mLogFrequencyMicroseconds = logFrequencySeconds * MICROSECONDS_PER_SECOND; } -void StatContext::EnableLogging( bool enableLogging ) +void StatContext::EnableLogging(bool enableLogging) { mLoggingEnabled = enableLogging; } -void StatContext::ProcessCustomMarker( const PerformanceMarker& marker ) +void StatContext::ProcessCustomMarker(const PerformanceMarker& marker) { // this marker has come from the application PerformanceLogger API - RecordMarker( marker); + RecordMarker(marker); } -void StatContext::ProcessInternalMarker( const PerformanceMarker& marker ) +void StatContext::ProcessInternalMarker(const PerformanceMarker& marker) { // this marker has come from DALi internal not the application // see if this context is for update, render or event - if( marker.IsFilterEnabled( mFilterType )) - { - RecordMarker( marker ); - } - // V_SYNC is always processed - if( marker.GetType() == PerformanceInterface::VSYNC ) - { - FrameTick( marker ); - } + if(marker.IsFilterEnabled(mFilterType)) + { + RecordMarker(marker); + } + // V_SYNC is always processed + if(marker.GetType() == PerformanceInterface::VSYNC) + { + FrameTick(marker); + } } -void StatContext::RecordMarker( const PerformanceMarker& marker ) +void StatContext::RecordMarker(const PerformanceMarker& marker) { - if( marker.GetEventType() == PerformanceMarker::START_TIMED_EVENT ) + if(marker.GetEventType() == PerformanceMarker::START_TIMED_EVENT) { - mStats.StartTime( marker.GetTimeStamp() ); + mStats.StartTime(marker.GetTimeStamp()); } - else if( marker.GetEventType() == PerformanceMarker::END_TIMED_EVENT ) + else if(marker.GetEventType() == PerformanceMarker::END_TIMED_EVENT) { - mStats.EndTime( marker.GetTimeStamp() ); + mStats.EndTime(marker.GetTimeStamp()); } } -void StatContext::FrameTick( const PerformanceMarker& marker ) +void StatContext::FrameTick(const PerformanceMarker& marker) { // wait until we've got some data - if( ! mInitialMarkerSet ) + if(!mInitialMarkerSet) { - mInitialMarker = marker; + mInitialMarker = marker; mInitialMarkerSet = true; return; } // log out every mLogFrequency. // check difference between first and last frame - unsigned int microseconds = PerformanceMarker::MicrosecondDiff( mInitialMarker, marker ); + unsigned int microseconds = PerformanceMarker::MicrosecondDiff(mInitialMarker, marker); - if( microseconds < mLogFrequencyMicroseconds ) + if(microseconds < mLogFrequencyMicroseconds) { return; } - if( mLoggingEnabled ) + if(mLoggingEnabled) { LogMarker(); } - mStats.Reset(); // reset data for statistics - mInitialMarkerSet = false; // need to restart the timer - + mStats.Reset(); // reset data for statistics + mInitialMarkerSet = false; // need to restart the timer } void StatContext::LogMarker() { float mean, standardDeviation; - mStats.CalculateMean( mean, standardDeviation ); - - snprintf( mTempLogBuffer, CONTEXT_LOG_SIZE, "%s, min " TIME_FMT ", max " TIME_FMT ", total (" TOTAL_TIME_FMT "), avg " TIME_FMT ", std dev " TIME_FMT "\n", - mName ? mName : UNKNOWN_CONTEXT_NAME, - mStats.GetMinTime() * MILLISECONDS_PER_SECOND, - mStats.GetMaxTime() * MILLISECONDS_PER_SECOND, - mStats.GetTotalTime(), - mean * MILLISECONDS_PER_SECOND, - standardDeviation * MILLISECONDS_PER_SECOND ); - - mLogInterface.LogContextStatistics( mTempLogBuffer ); - + mStats.CalculateMean(mean, standardDeviation); + + snprintf(mTempLogBuffer, + CONTEXT_LOG_SIZE, + "%s, min " TIME_FMT ", max " TIME_FMT ", total (" TOTAL_TIME_FMT "), avg " TIME_FMT ", std dev " TIME_FMT "\n", + mName ? mName : UNKNOWN_CONTEXT_NAME, + mStats.GetMinTime() * MILLISECONDS_PER_SECOND, + mStats.GetMaxTime() * MILLISECONDS_PER_SECOND, + mStats.GetTotalTime(), + mean * MILLISECONDS_PER_SECOND, + standardDeviation * MILLISECONDS_PER_SECOND); + + mLogInterface.LogContextStatistics(mTempLogBuffer); } - +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali diff --git a/dali/internal/system/common/stat-context.h b/dali/internal/system/common/stat-context.h index 2209b25..fc1a3b0 100644 --- a/dali/internal/system/common/stat-context.h +++ b/dali/internal/system/common/stat-context.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,30 +22,25 @@ #include // INTERNAL INCLUDES -#include #include #include +#include #include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Stores and prints statistics for a particular logging context. * */ class StatContext { - public: - - /** + /** * @brief Constructor * * @param[in] id The ID to give the context @@ -55,116 +50,109 @@ public: * @param[in] logInterface interface to log out to * */ - StatContext( unsigned int id, - const char* const contextName, - PerformanceMarker::MarkerFilter contextType, - unsigned int logFrequencySeconds, - StatContextLogInterface& logInterface ); - + StatContext(unsigned int id, + const char* const contextName, + PerformanceMarker::MarkerFilter contextType, + unsigned int logFrequencySeconds, + StatContextLogInterface& logInterface); - /** + /** * @brief Non-virtual destructor, not intended as a base class */ - ~StatContext(); + ~StatContext(); - /** + /** * @return Return the context ID */ - unsigned int GetId() const; + unsigned int GetId() const; - /** + /** * @return the context name */ - const char* GetName() const; + const char* GetName() const; - /** + /** * * For logging we want to output the name of the context with either * START / END appended to the end. E.g. MY_MARKER_START * @param[in] type marker type, for a customer marker this will be either START or END * @return the full description for a marker */ - const char* GetMarkerDescription( PerformanceInterface::MarkerType type ) const; + const char* GetMarkerDescription(PerformanceInterface::MarkerType type) const; - /** + /** * @brief Set the frequency for logging * * @param[in] logFrequencySeconds The log frequency to set in seconds */ - void SetLogFrequency( unsigned int logFrequencySeconds ); + void SetLogFrequency(unsigned int logFrequencySeconds); - /** + /** * @brief enable/disable logging * * @param[in] enableLogging Flag to spePerformancecify enabling/disabling */ - void EnableLogging( bool enableLogging ); + void EnableLogging(bool enableLogging); - /** + /** * @brief Process a custom marker from the application * * @param[in] marker The marker to log */ - void ProcessCustomMarker( const PerformanceMarker& marker ); + void ProcessCustomMarker(const PerformanceMarker& marker); - /** + /** * @brief Process a internal marker from DALi (V_SYNC/ UPDATE /RENDER/ EVENT ) * * @param[in] marker The marker to log */ - void ProcessInternalMarker( const PerformanceMarker& marker ); + void ProcessInternalMarker(const PerformanceMarker& marker); - private: - - /** +private: + /** * @brief Record marker * * @param[in] marker to record */ - void RecordMarker( const PerformanceMarker& marker ); + void RecordMarker(const PerformanceMarker& marker); - /** + /** * @brief Called when V-SYNC occurs to indicate a frame tick * @param[in] marker the marker containing a v-sync */ - void FrameTick( const PerformanceMarker& marker ); + void FrameTick(const PerformanceMarker& marker); - /** + /** * @brief Helper to print to console */ - void LogMarker(); - - - private: - - StatContext(); ///< undefined default constructor - - StatContext( const StatContext& ); ///< undefined copy constructor - - StatContext& operator=( const StatContext& ); ///< undefined assignment operator - - private: - - PerformanceMarker mInitialMarker; ///< Used to store initial time - FrameTimeStats mStats; ///< Frame time stats to accumulate - const char* const mName; ///< Name of the context - char* mTempLogBuffer; ///< Temporary log buffer - StatContextLogInterface& mLogInterface; ///< Log interface - const std::string mNamePlusStart; ///< Name of the context + _START - const std::string mNamePlusEnd; ///< Name of the context + _END - unsigned int mId; ///< The ID of the context - unsigned int mLogFrequencyMicroseconds; ///< if logging is enabled, what frequency to log out at in micro-seconds - PerformanceMarker::MarkerFilter mFilterType; ///< type of events the context is filtering - bool mLoggingEnabled:1; ///< Whether to print the log for this context or not - bool mInitialMarkerSet:1; ///< Whether the initial marker has been set - + void LogMarker(); + +private: + StatContext(); ///< undefined default constructor + + StatContext(const StatContext&); ///< undefined copy constructor + + StatContext& operator=(const StatContext&); ///< undefined assignment operator + +private: + PerformanceMarker mInitialMarker; ///< Used to store initial time + FrameTimeStats mStats; ///< Frame time stats to accumulate + const char* const mName; ///< Name of the context + char* mTempLogBuffer; ///< Temporary log buffer + StatContextLogInterface& mLogInterface; ///< Log interface + const std::string mNamePlusStart; ///< Name of the context + _START + const std::string mNamePlusEnd; ///< Name of the context + _END + unsigned int mId; ///< The ID of the context + unsigned int mLogFrequencyMicroseconds; ///< if logging is enabled, what frequency to log out at in micro-seconds + PerformanceMarker::MarkerFilter mFilterType; ///< type of events the context is filtering + bool mLoggingEnabled : 1; ///< Whether to print the log for this context or not + bool mInitialMarkerSet : 1; ///< Whether the initial marker has been set }; +} // namespace Adaptor } // namespace Internal -} // namespace Adaptor - } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_STAT_CONTEXT_H diff --git a/dali/internal/system/common/system-settings.h b/dali/internal/system/common/system-settings.h index 174ad9b..1fd4ea8 100644 --- a/dali/internal/system/common/system-settings.h +++ b/dali/internal/system/common/system-settings.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_SYSTEM_SETTINGS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +20,12 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - // Get SYSTEM_SETTINGS_KEY_TAP_AND_HOLD_DELAY from system setting if available -int GetLongPressTime( int defaultTime ); +int GetLongPressTime(int defaultTime); // Get ELM_ACCESS_ACTION_OVER from Elementary if available int GetElmAccessActionOver(); diff --git a/dali/internal/system/common/system-trace.cpp b/dali/internal/system/common/system-trace.cpp index 73a98d2..9431467 100644 --- a/dali/internal/system/common/system-trace.cpp +++ b/dali/internal/system/common/system-trace.cpp @@ -19,8 +19,8 @@ #include // EXTERNAL HEADERS -#include #include +#include // INTERNAL HEADERS #include @@ -34,54 +34,50 @@ namespace { const int TTRACE_TAG_GRAPHICS = 1; -void traceAsyncBegin(int tag, int cookie, const char *name, ...) +void traceAsyncBegin(int tag, int cookie, const char* name, ...) { - Debug::LogMessage(Debug::DebugInfo, "AsyncBegin: %s : cookie %d\n", name, cookie ); + Debug::LogMessage(Debug::DebugInfo, "AsyncBegin: %s : cookie %d\n", name, cookie); } -void traceAsyncEnd(int tag, int cookie, const char *name, ...) +void traceAsyncEnd(int tag, int cookie, const char* name, ...) { - Debug::LogMessage(Debug::DebugInfo, "AsyncEnd: %s : cookie %d\n", name, cookie ); + Debug::LogMessage(Debug::DebugInfo, "AsyncEnd: %s : cookie %d\n", name, cookie); } -void traceMark(int tag, const char *name, ...) +void traceMark(int tag, const char* name, ...) { Debug::LogMessage(Debug::DebugInfo, "Marker: %s \n", name); } -} // un-named namespace +} // namespace #endif namespace { - -int GetCookie( const std::string& description, std::string& markerName ) +int GetCookie(const std::string& description, std::string& markerName) { // description holds the marker name and postfix of _START or _END std::size_t pos = description.find("_START"); - if( pos == std::string::npos ) + if(pos == std::string::npos) { pos = description.find("_END"); } - if( !pos ) + if(!pos) { // if this asserts then check the postfix strings in StatContext.cpp for // custom markers and performance-marker.cpp for built-in markers DALI_ASSERT_DEBUG(0); } - markerName = description.substr( 0, pos ); + markerName = description.substr(0, pos); - std::size_t hash = Dali::CalculateHash( markerName.c_str() ); - return static_cast( hash ); -} + std::size_t hash = Dali::CalculateHash(markerName.c_str()); + return static_cast(hash); } +} // namespace namespace Dali { - namespace Internal { - namespace Adaptor { - SystemTrace::SystemTrace() { } @@ -89,34 +85,33 @@ SystemTrace::~SystemTrace() { } -void SystemTrace::Trace( const PerformanceMarker& marker, const std::string& traceMessage ) +void SystemTrace::Trace(const PerformanceMarker& marker, const std::string& traceMessage) { PerformanceMarker::MarkerEventType eventType = marker.GetEventType(); - if( eventType == PerformanceMarker::SINGLE_EVENT ) + if(eventType == PerformanceMarker::SINGLE_EVENT) { - traceMark( TTRACE_TAG_GRAPHICS, traceMessage.c_str() ); + traceMark(TTRACE_TAG_GRAPHICS, traceMessage.c_str()); return; } // DALi is multi-threaded so timed events will occur asynchronously std::string markerName; - int cookie = GetCookie(traceMessage, markerName ); + int cookie = GetCookie(traceMessage, markerName); - if( eventType == PerformanceMarker::START_TIMED_EVENT ) + if(eventType == PerformanceMarker::START_TIMED_EVENT) { - traceAsyncBegin( TTRACE_TAG_GRAPHICS, cookie, markerName.c_str() ); + traceAsyncBegin(TTRACE_TAG_GRAPHICS, cookie, markerName.c_str()); } else { - traceAsyncEnd( TTRACE_TAG_GRAPHICS, cookie, markerName.c_str() ); + traceAsyncEnd(TTRACE_TAG_GRAPHICS, cookie, markerName.c_str()); } } -} // namespace Internal - } // namespace Adaptor -} // namespace Dali +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/system/common/system-trace.h b/dali/internal/system/common/system-trace.h index 17014ee..b55f817 100644 --- a/dali/internal/system/common/system-trace.h +++ b/dali/internal/system/common/system-trace.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Concrete System Tracing Interface. * Used to log trace messages to the system using ttrace @@ -37,7 +34,6 @@ namespace Adaptor class SystemTrace : public TraceInterface { public: - /** * Constructor */ @@ -51,14 +47,13 @@ public: /** * @copydoc KernelTracerInterface::KernelTrace() */ - void Trace( const PerformanceMarker& marker, const std::string& traceMessage ) override; - + void Trace(const PerformanceMarker& marker, const std::string& traceMessage) override; }; -} // namespace Internal - } // namespace Adaptor +} // namespace Internal + } // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_SYSTEM_TRACE_H diff --git a/dali/internal/system/common/thread-controller.cpp b/dali/internal/system/common/thread-controller.cpp index 31a5a24..54633bd 100644 --- a/dali/internal/system/common/thread-controller.cpp +++ b/dali/internal/system/common/thread-controller.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,27 +19,24 @@ #include // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - -ThreadController::ThreadController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode ) -: mThreadControllerInterface( NULL ) +ThreadController::ThreadController(AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode) +: mThreadControllerInterface(NULL) { - switch( environmentOptions.GetThreadingMode() ) + switch(environmentOptions.GetThreadingMode()) { case ThreadingMode::COMBINED_UPDATE_RENDER: { - mThreadControllerInterface = new CombinedUpdateRenderController( adaptorInterfaces, environmentOptions, threadMode ); + mThreadControllerInterface = new CombinedUpdateRenderController(adaptorInterfaces, environmentOptions, threadMode); break; } } @@ -80,19 +77,19 @@ void ThreadController::RequestUpdate() mThreadControllerInterface->RequestUpdate(); } -void ThreadController::RequestUpdateOnce( UpdateMode updateMode ) +void ThreadController::RequestUpdateOnce(UpdateMode updateMode) { - mThreadControllerInterface->RequestUpdateOnce( updateMode ); + mThreadControllerInterface->RequestUpdateOnce(updateMode); } -void ThreadController::ReplaceSurface( Dali::RenderSurfaceInterface* newSurface ) +void ThreadController::ReplaceSurface(Dali::RenderSurfaceInterface* newSurface) { - mThreadControllerInterface->ReplaceSurface( newSurface ); + mThreadControllerInterface->ReplaceSurface(newSurface); } -void ThreadController::DeleteSurface( Dali::RenderSurfaceInterface* surface ) +void ThreadController::DeleteSurface(Dali::RenderSurfaceInterface* surface) { - mThreadControllerInterface->DeleteSurface( surface ); + mThreadControllerInterface->DeleteSurface(surface); } void ThreadController::ResizeSurface() @@ -105,19 +102,19 @@ void ThreadController::WaitForGraphicsInitialization() mThreadControllerInterface->WaitForGraphicsInitialization(); } -void ThreadController::SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender ) +void ThreadController::SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender) { - mThreadControllerInterface->SetRenderRefreshRate( numberOfVSyncsPerRender ); + mThreadControllerInterface->SetRenderRefreshRate(numberOfVSyncsPerRender); } -void ThreadController::SetPreRenderCallback( CallbackBase* callback ) +void ThreadController::SetPreRenderCallback(CallbackBase* callback) { - mThreadControllerInterface->SetPreRenderCallback( callback ); + mThreadControllerInterface->SetPreRenderCallback(callback); } -void ThreadController::AddSurface( Dali::RenderSurfaceInterface* newSurface ) +void ThreadController::AddSurface(Dali::RenderSurfaceInterface* newSurface) { - mThreadControllerInterface->AddSurface( newSurface ); + mThreadControllerInterface->AddSurface(newSurface); } } // namespace Adaptor diff --git a/dali/internal/system/common/thread-controller.h b/dali/internal/system/common/thread-controller.h index d51e57d..ba58948 100644 --- a/dali/internal/system/common/thread-controller.h +++ b/dali/internal/system/common/thread-controller.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_THREAD_CONTROLLER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,15 +24,12 @@ namespace Dali { - class RenderSurfaceInterface; namespace Internal { - namespace Adaptor { - enum class UpdateMode; enum class ThreadMode; @@ -46,11 +43,10 @@ class ThreadControllerInterface; class ThreadController { public: - /** * Constructor */ - ThreadController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode ); + ThreadController(AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode); /** * Non virtual destructor. Not intended as base class. @@ -103,20 +99,20 @@ public: * * @param updateMode The update mode (i.e. either update and render, or update and upload without rendering) */ - void RequestUpdateOnce( UpdateMode updateMode ); + void RequestUpdateOnce(UpdateMode updateMode); /** * @brief Replaces the surface. * * @param surface new surface */ - void ReplaceSurface( Dali::RenderSurfaceInterface* surface ); + void ReplaceSurface(Dali::RenderSurfaceInterface* surface); /** * Deletes the surface. * @param surface The surface to be deleted */ - void DeleteSurface( Dali::RenderSurfaceInterface* surface ); + void DeleteSurface(Dali::RenderSurfaceInterface* surface); /** * Resize the surface. @@ -131,30 +127,28 @@ public: /** * @copydoc Dali::Adaptor::SetRenderRefreshRate() */ - void SetRenderRefreshRate( unsigned int numberOfVSyncsPerRender ); + void SetRenderRefreshRate(unsigned int numberOfVSyncsPerRender); /** * @copydoc Dali::Adaptor::SetPreRenderCallback */ - void SetPreRenderCallback( CallbackBase* callback ); + void SetPreRenderCallback(CallbackBase* callback); /** * @brief Adds the new surface. * * @param surface new surface */ - void AddSurface( Dali::RenderSurfaceInterface* surface ); + void AddSurface(Dali::RenderSurfaceInterface* surface); private: - // Undefined copy constructor. - ThreadController( const ThreadController& ) = delete; + ThreadController(const ThreadController&) = delete; // Undefined assignment operator. - ThreadController& operator=( const ThreadController& ) = delete; + ThreadController& operator=(const ThreadController&) = delete; private: - ThreadControllerInterface* mThreadControllerInterface; }; diff --git a/dali/internal/system/common/time-service.cpp b/dali/internal/system/common/time-service.cpp index c0bc646..6b77ffc 100644 --- a/dali/internal/system/common/time-service.cpp +++ b/dali/internal/system/common/time-service.cpp @@ -24,17 +24,13 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TimeService { - -void GetNanoseconds( uint64_t& timeInNanoseconds ) +void GetNanoseconds(uint64_t& timeInNanoseconds) { // Get the time of a monotonic clock since its epoch. auto epoch = std::chrono::steady_clock::now().time_since_epoch(); @@ -54,14 +50,13 @@ uint32_t GetMilliSeconds() return static_cast(duration.count()); } - -void SleepUntil( uint64_t timeInNanoseconds ) +void SleepUntil(uint64_t timeInNanoseconds) { - using Clock = std::chrono::steady_clock; + using Clock = std::chrono::steady_clock; using TimePoint = std::chrono::time_point; const Clock::duration duration = std::chrono::nanoseconds(timeInNanoseconds); - const TimePoint timePoint(duration); + const TimePoint timePoint(duration); std::this_thread::sleep_until(timePoint); } diff --git a/dali/internal/system/common/time-service.h b/dali/internal/system/common/time-service.h index 7f55328..bce7e5f 100644 --- a/dali/internal/system/common/time-service.h +++ b/dali/internal/system/common/time-service.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TIME_SERVICE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,16 +22,12 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TimeService { - /** * @brief Get the monotonic time since the clock's epoch. * @@ -39,7 +35,7 @@ namespace TimeService * * @note The maximum value timeInNanoseconds can hold is 0xFFFFFFFFFFFFFFFF which is 1.844674407e+19. Therefore, this can overflow after approximately 584 years. */ -void GetNanoseconds( uint64_t& timeInNanoseconds ); +void GetNanoseconds(uint64_t& timeInNanoseconds); /** * @brief Get the monotonic time since the clock's epoch. @@ -59,7 +55,7 @@ uint32_t GetMilliSeconds(); * * @note The maximum value timeInNanoseconds can hold is 0xFFFFFFFFFFFFFFFF which is 1.844674407e+19. Therefore, this can overflow after approximately 584 years. */ -void SleepUntil( uint64_t timeInNanoseconds ); +void SleepUntil(uint64_t timeInNanoseconds); } // namespace TimeService diff --git a/dali/internal/system/common/timer-impl.h b/dali/internal/system/common/timer-impl.h index f631585..ab86d83 100644 --- a/dali/internal/system/common/timer-impl.h +++ b/dali/internal/system/common/timer-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TIMER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,16 +22,14 @@ #include // INTERNAL INCLUDES -#include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { class Timer; @@ -44,13 +42,13 @@ typedef IntrusivePtr TimerPtr; class Timer : public BaseObject, public TimerInterface { public: - static TimerPtr New( unsigned int milliSec ); + static TimerPtr New(unsigned int milliSec); /** * Constructor * @param[in] milliSec Interval in milliseconds. */ - Timer( unsigned int milliSec ); + Timer(unsigned int milliSec); /** * Destructor. @@ -58,7 +56,6 @@ public: virtual ~Timer(); public: - /** * @copydoc Dali::Timer::Start() */ @@ -82,7 +79,7 @@ public: /** * @copydoc Dali::Timer::SetInterval() */ - void SetInterval( unsigned int interval, bool restart ) override; + void SetInterval(unsigned int interval, bool restart) override; /** * @copydoc Dali::Timer::GetInterval() @@ -100,14 +97,12 @@ public: bool Tick(); public: // Signals - Dali::Timer::TimerSignalType& TickSignal(); private: // Implementation - // not implemented - Timer( const Timer& ); - Timer& operator=( const Timer& ); + Timer(const Timer&); + Timer& operator=(const Timer&); /** * Resets any stored timer data. @@ -115,7 +110,6 @@ private: // Implementation void ResetTimerData(); private: // Data - Dali::Timer::TimerSignalType mTickSignal; // To hide away implementation details diff --git a/dali/internal/system/common/timer-interface.h b/dali/internal/system/common/timer-interface.h index f75afdf..c6106cb 100644 --- a/dali/internal/system/common/timer-interface.h +++ b/dali/internal/system/common/timer-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ADAPTOR_BASE_TIMER_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ namespace Internal { namespace Adaptor { - /** * Interface for a timer class */ @@ -54,7 +53,7 @@ public: /** * @copydoc Dali::Timer::SetInterval() */ - virtual void SetInterval( unsigned int intervalInMilliseconds, bool restart ) = 0; + virtual void SetInterval(unsigned int intervalInMilliseconds, bool restart) = 0; /** * @copydoc Dali::Timer::GetInterval() @@ -70,12 +69,13 @@ protected: /** * Virtual protected destructor, no deletion through this interface */ - virtual ~TimerInterface() { } + virtual ~TimerInterface() + { + } }; - -} // Adaptor -} // Internal -} // Dali +} // namespace Adaptor +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_ADAPTOR_BASE_TIMER_INTERFACE_H diff --git a/dali/internal/system/common/trigger-event-factory.cpp b/dali/internal/system/common/trigger-event-factory.cpp index 242be5d..4663c92 100644 --- a/dali/internal/system/common/trigger-event-factory.cpp +++ b/dali/internal/system/common/trigger-event-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,14 @@ namespace Dali { - -TriggerEventInterface* TriggerEventFactory::CreateTriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ) +TriggerEventInterface* TriggerEventFactory::CreateTriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options) { - return new Internal::Adaptor::TriggerEvent( callback, options ); + return new Internal::Adaptor::TriggerEvent(callback, options); } -void TriggerEventFactory::DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface ) +void TriggerEventFactory::DestroyTriggerEvent(TriggerEventInterface* triggerEventInterface) { - Internal::Adaptor::TriggerEvent* triggerEvent( static_cast(triggerEventInterface) ); + Internal::Adaptor::TriggerEvent* triggerEvent(static_cast(triggerEventInterface)); delete triggerEvent; } diff --git a/dali/internal/system/common/trigger-event.cpp b/dali/internal/system/common/trigger-event.cpp index 78044b4..1f94e51 100644 --- a/dali/internal/system/common/trigger-event.cpp +++ b/dali/internal/system/common/trigger-event.cpp @@ -30,25 +30,22 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -TriggerEvent::TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ) -: mFileDescriptorMonitor( NULL ), - mCallback( callback ), - mFileDescriptor( -1 ), - mOptions( options ) +TriggerEvent::TriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options) +: mFileDescriptorMonitor(NULL), + mCallback(callback), + mFileDescriptor(-1), + mOptions(options) { // Create accompanying file descriptor. mFileDescriptor = eventfd(0, EFD_NONBLOCK); - if (mFileDescriptor >= 0) + if(mFileDescriptor >= 0) { // Now Monitor the created event file descriptor - mFileDescriptorMonitor = new FileDescriptorMonitor( mFileDescriptor, MakeCallback( this, &TriggerEvent::Triggered ), FileDescriptorMonitor::FD_READABLE ); + mFileDescriptorMonitor = new FileDescriptorMonitor(mFileDescriptor, MakeCallback(this, &TriggerEvent::Triggered), FileDescriptorMonitor::FD_READABLE); } else { @@ -61,7 +58,7 @@ TriggerEvent::~TriggerEvent() delete mFileDescriptorMonitor; delete mCallback; - if (mFileDescriptor >= 0) + if(mFileDescriptor >= 0) { close(mFileDescriptor); mFileDescriptor = 0; @@ -70,16 +67,16 @@ TriggerEvent::~TriggerEvent() void TriggerEvent::Trigger() { - if (mFileDescriptor >= 0) + if(mFileDescriptor >= 0) { // Increment event counter by 1. // Writing to the file descriptor triggers the Dispatch() method in the other thread // (if in multi-threaded environment). uint64_t data = 1; - int size = write(mFileDescriptor, &data, sizeof(uint64_t)); + int size = write(mFileDescriptor, &data, sizeof(uint64_t)); - if (size != sizeof(uint64_t)) + if(size != sizeof(uint64_t)) { DALI_LOG_ERROR("Unable to write to UpdateEvent File descriptor\n"); } @@ -90,28 +87,28 @@ void TriggerEvent::Trigger() } } -void TriggerEvent::Triggered( FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor ) +void TriggerEvent::Triggered(FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor) { - if( !( eventBitMask & FileDescriptorMonitor::FD_READABLE ) ) + if(!(eventBitMask & FileDescriptorMonitor::FD_READABLE)) { - DALI_ASSERT_ALWAYS( 0 && "Trigger event file descriptor error"); + DALI_ASSERT_ALWAYS(0 && "Trigger event file descriptor error"); return; } // Reading from the file descriptor resets the event counter, we can ignore the count. uint64_t receivedData; - size_t size; + size_t size; size = read(mFileDescriptor, &receivedData, sizeof(uint64_t)); - if (size != sizeof(uint64_t)) + if(size != sizeof(uint64_t)) { DALI_LOG_WARNING("Unable to read to UpdateEvent File descriptor\n"); } // Call the connected callback - CallbackBase::Execute( *mCallback ); + CallbackBase::Execute(*mCallback); //check if we should delete ourselves after the trigger - if( mOptions == TriggerEventInterface::DELETE_AFTER_TRIGGER ) + if(mOptions == TriggerEventInterface::DELETE_AFTER_TRIGGER) { delete this; } diff --git a/dali/internal/system/common/trigger-event.h b/dali/internal/system/common/trigger-event.h index 04e7835..51221a5 100644 --- a/dali/internal/system/common/trigger-event.h +++ b/dali/internal/system/common/trigger-event.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRIGGER_EVENT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,20 +22,16 @@ #include // INTERNAL INCLUDES -#include #include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - - /** * The TriggerEvent class is used to send events between threads. For example, this can be used * to wake up one thread from another thread. @@ -49,7 +45,6 @@ namespace Adaptor class TriggerEvent : public TriggerEventInterface { public: - /** * Constructor * Creates an event file descriptor and starts a GSource which reads from the file @@ -59,7 +54,7 @@ public: * @param[in] options Trigger event options. * @note The ownership of callback is taken by this class. */ - TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ); + TriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options); /** * Destructor @@ -67,7 +62,6 @@ public: ~TriggerEvent(); public: - /** * Triggers the event. * @@ -76,23 +70,20 @@ public: void Trigger(); private: - /** * @brief Called when our event file descriptor has been written to. * @param[in] eventBitMask bit mask of events that occured on the file descriptor * @param[in] fileDescriptor The file descriptor */ - void Triggered( FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor ); + void Triggered(FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor); private: - struct Source; private: - - FileDescriptorMonitor* mFileDescriptorMonitor; - CallbackBase* mCallback; - int mFileDescriptor; + FileDescriptorMonitor* mFileDescriptorMonitor; + CallbackBase* mCallback; + int mFileDescriptor; TriggerEventInterface::Options mOptions; }; diff --git a/dali/internal/system/common/update-status-logger.cpp b/dali/internal/system/common/update-status-logger.cpp index d238b0a..c2abeba 100644 --- a/dali/internal/system/common/update-status-logger.cpp +++ b/dali/internal/system/common/update-status-logger.cpp @@ -19,24 +19,21 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - -UpdateStatusLogger::UpdateStatusLogger( const EnvironmentOptions& environmentOptions ) -: mStatusLogInterval( environmentOptions.GetUpdateStatusLoggingFrequency() ), - mStatusLogCount( 0u ) +UpdateStatusLogger::UpdateStatusLogger(const EnvironmentOptions& environmentOptions) +: mStatusLogInterval(environmentOptions.GetUpdateStatusLoggingFrequency()), + mStatusLogCount(0u) { } @@ -44,43 +41,43 @@ UpdateStatusLogger::~UpdateStatusLogger() { } -void UpdateStatusLogger::Log( unsigned int keepUpdatingStatus ) +void UpdateStatusLogger::Log(unsigned int keepUpdatingStatus) { - if ( mStatusLogInterval ) + if(mStatusLogInterval) { std::string oss; - if ( !(++mStatusLogCount % mStatusLogInterval) ) + if(!(++mStatusLogCount % mStatusLogInterval)) { oss = "UpdateStatusLogging keepUpdating: "; - oss += (keepUpdatingStatus ? "true":"false"); + oss += (keepUpdatingStatus ? "true" : "false"); - if ( keepUpdatingStatus ) + if(keepUpdatingStatus) { oss += " because: "; } - if ( keepUpdatingStatus & Integration::KeepUpdating::STAGE_KEEP_RENDERING ) + if(keepUpdatingStatus & Integration::KeepUpdating::STAGE_KEEP_RENDERING) { oss += " "; } - if ( keepUpdatingStatus & Integration::KeepUpdating::ANIMATIONS_RUNNING ) + if(keepUpdatingStatus & Integration::KeepUpdating::ANIMATIONS_RUNNING) { - oss += " "; + oss += " "; } - if ( keepUpdatingStatus & Integration::KeepUpdating::MONITORING_PERFORMANCE ) + if(keepUpdatingStatus & Integration::KeepUpdating::MONITORING_PERFORMANCE) { oss += " "; } - if ( keepUpdatingStatus & Integration::KeepUpdating::RENDER_TASK_SYNC ) + if(keepUpdatingStatus & Integration::KeepUpdating::RENDER_TASK_SYNC) { oss += " "; } - DALI_LOG_UPDATE_STATUS( "%s\n", oss.c_str()); + DALI_LOG_UPDATE_STATUS("%s\n", oss.c_str()); } } } diff --git a/dali/internal/system/common/update-status-logger.h b/dali/internal/system/common/update-status-logger.h index 094a7b3..12b18ef 100644 --- a/dali/internal/system/common/update-status-logger.h +++ b/dali/internal/system/common/update-status-logger.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_UPDATE_STATUS_LOGGER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class EnvironmentOptions; /** @@ -39,12 +36,11 @@ class EnvironmentOptions; class UpdateStatusLogger { public: - /** * Create the update-status-logger. * @param[in] environmentOptions environment options */ - UpdateStatusLogger( const EnvironmentOptions& environmentOptions ); + UpdateStatusLogger(const EnvironmentOptions& environmentOptions); /** * Non-virtual destructor; UpdateThread is not suitable as a base class. @@ -55,12 +51,11 @@ public: * Optionally output the update thread status. * @param[in] keepUpdatingStatus Whether the update-thread requested further updates. */ - void Log( unsigned int keepUpdatingStatus ); - -private: // Data + void Log(unsigned int keepUpdatingStatus); - unsigned int mStatusLogInterval; ///< Interval in frames between status debug prints - unsigned int mStatusLogCount; ///< Used to count frames between status debug prints +private: // Data + unsigned int mStatusLogInterval; ///< Interval in frames between status debug prints + unsigned int mStatusLogCount; ///< Used to count frames between status debug prints }; } // namespace Adaptor diff --git a/dali/internal/system/common/widget-application-impl.cpp b/dali/internal/system/common/widget-application-impl.cpp index da34463..c77c4ef 100644 --- a/dali/internal/system/common/widget-application-impl.cpp +++ b/dali/internal/system/common/widget-application-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,15 @@ */ // CLASS HEADER -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - // factory function, must be implemented namespace WidgetApplicationFactory { @@ -37,20 +34,20 @@ namespace WidgetApplicationFactory * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ -WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet ); +WidgetApplicationPtr Create(int* argc, char** argv[], const std::string& stylesheet); -} // namespace Factory +} // namespace WidgetApplicationFactory WidgetApplicationPtr WidgetApplication::New( - int* argc, - char **argv[], + int* argc, + char** argv[], const std::string& stylesheet) { //WidgetApplicationPtr //widgetApplication( new WidgetApplication (argc, argv, stylesheet ) ); - return WidgetApplicationFactory::Create( argc, argv, stylesheet ); + return WidgetApplicationFactory::Create(argc, argv, stylesheet); } -WidgetApplication::WidgetApplication( int* argc, char** argv[], const std::string& stylesheet ) +WidgetApplication::WidgetApplication(int* argc, char** argv[], const std::string& stylesheet) : Application(argc, argv, stylesheet, Dali::WidgetApplication::OPAQUE, PositionSize(), Framework::WIDGET) { DALI_LOG_ERROR("WidgetApplication is not implemented in UBUNTU profile.\n"); @@ -60,7 +57,7 @@ WidgetApplication::~WidgetApplication() { } -void WidgetApplication::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) +void WidgetApplication::RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) { } diff --git a/dali/internal/system/common/widget-application-impl.h b/dali/internal/system/common/widget-application-impl.h index d490166..32079ca 100644 --- a/dali/internal/system/common/widget-application-impl.h +++ b/dali/internal/system/common/widget-application-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ namespace Internal { namespace Adaptor { - typedef IntrusivePtr WidgetApplicationPtr; /** @@ -41,9 +40,8 @@ typedef IntrusivePtr WidgetApplicationPtr; class WidgetApplication : public Application { public: - - typedef std::pair CreateWidgetFunctionPair; - typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer; + typedef std::pair CreateWidgetFunctionPair; + typedef std::vector CreateWidgetFunctionContainer; /** * Create a new widget application @@ -51,24 +49,22 @@ public: * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet ); + static WidgetApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet); public: - /** * @copydoc Dali::WidgetApplication::RegisterWidgetCreator() */ - virtual void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ); + virtual void RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction); protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - WidgetApplication( int* argc, char **argv[], const std::string& stylesheet ); + WidgetApplication(int* argc, char** argv[], const std::string& stylesheet); /** * Destructor diff --git a/dali/internal/system/common/widget-controller.h b/dali/internal/system/common/widget-controller.h index 508463a..99b8995 100644 --- a/dali/internal/system/common/widget-controller.h +++ b/dali/internal/system/common/widget-controller.h @@ -2,7 +2,7 @@ #define DALI_WIDGET_CONTROLLER_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { /** @@ -38,11 +36,10 @@ namespace Adaptor class Widget::Impl : public Dali::ConnectionTracker { public: - /** * Set content information to widget framework */ - virtual void SetContentInfo( const std::string& contentInfo ) = 0; + virtual void SetContentInfo(const std::string& contentInfo) = 0; }; } // namespace Adaptor diff --git a/dali/internal/system/generic/shared-file-operations-generic.cpp b/dali/internal/system/generic/shared-file-operations-generic.cpp index 1a87966..a5cf79a 100644 --- a/dali/internal/system/generic/shared-file-operations-generic.cpp +++ b/dali/internal/system/generic/shared-file-operations-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,25 +19,22 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - -int SharedFile::Open( const char* filename, int size, int oflag, mode_t mode ) +int SharedFile::Open(const char* filename, int size, int oflag, mode_t mode) { - return shm_open( filename, oflag, mode ); + return shm_open(filename, oflag, mode); } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/system/linux/callback-manager-ecore.cpp b/dali/internal/system/linux/callback-manager-ecore.cpp index ade2f19..3c2e478 100644 --- a/dali/internal/system/linux/callback-manager-ecore.cpp +++ b/dali/internal/system/linux/callback-manager-ecore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,31 +25,26 @@ // INTERNAL INCLUDES - namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Structure contains the callback function and control options */ struct CallbackData { - /** * Constructor */ - CallbackData( CallbackBase* callback, bool hasReturnValue ) - : mCallback( callback ), - mRemoveFromContainerFunction( NULL ), - mIdler( NULL ), - mIdleEnterer( NULL ), - mHasReturnValue( hasReturnValue ) + CallbackData(CallbackBase* callback, bool hasReturnValue) + : mCallback(callback), + mRemoveFromContainerFunction(NULL), + mIdler(NULL), + mIdleEnterer(NULL), + mHasReturnValue(hasReturnValue) { } /** @@ -61,29 +56,28 @@ struct CallbackData delete mRemoveFromContainerFunction; } - CallbackBase* mCallback; ///< call back - CallbackBase* mRemoveFromContainerFunction; ///< Called to remove the callbackdata from the callback container - Ecore_Idler* mIdler; ///< ecore idler - Ecore_Idle_Enterer* mIdleEnterer; ///< ecore idle enterer - bool mHasReturnValue; ///< true if the callback function has a return value. + CallbackBase* mCallback; ///< call back + CallbackBase* mRemoveFromContainerFunction; ///< Called to remove the callbackdata from the callback container + Ecore_Idler* mIdler; ///< ecore idler + Ecore_Idle_Enterer* mIdleEnterer; ///< ecore idle enterer + bool mHasReturnValue; ///< true if the callback function has a return value. }; namespace { - /** * Called from the main thread while idle. */ -Eina_Bool IdleCallback(void *data) +Eina_Bool IdleCallback(void* data) { - Eina_Bool ret = ECORE_CALLBACK_CANCEL; // CALLBACK Cancel will delete the idler so we don't need to call ecore_idler_del - CallbackData *callbackData = static_cast< CallbackData * >( data ); + Eina_Bool ret = ECORE_CALLBACK_CANCEL; // CALLBACK Cancel will delete the idler so we don't need to call ecore_idler_del + CallbackData* callbackData = static_cast(data); - if( callbackData->mHasReturnValue ) + if(callbackData->mHasReturnValue) { // run the function - bool retValue = CallbackBase::ExecuteReturn< bool >( *callbackData->mCallback ); - if( retValue ) + bool retValue = CallbackBase::ExecuteReturn(*callbackData->mCallback); + if(retValue) { // keep the callback ret = ECORE_CALLBACK_RENEW; @@ -91,7 +85,7 @@ Eina_Bool IdleCallback(void *data) else { // remove callback data from the container - CallbackBase::Execute( *callbackData->mRemoveFromContainerFunction, callbackData ); + CallbackBase::Execute(*callbackData->mRemoveFromContainerFunction, callbackData); // delete our data delete callbackData; @@ -100,10 +94,10 @@ Eina_Bool IdleCallback(void *data) else { // remove callback data from the container - CallbackBase::Execute( *callbackData->mRemoveFromContainerFunction, callbackData ); + CallbackBase::Execute(*callbackData->mRemoveFromContainerFunction, callbackData); // run the function - CallbackBase::Execute( *callbackData->mCallback ); + CallbackBase::Execute(*callbackData->mCallback); // delete our data delete callbackData; @@ -115,14 +109,13 @@ Eina_Bool IdleCallback(void *data) } // unnamed namespace EcoreCallbackManager::EcoreCallbackManager() -:mRunning(false) +: mRunning(false) { } - void EcoreCallbackManager::Start() { - DALI_ASSERT_DEBUG( mRunning == false ); + DALI_ASSERT_DEBUG(mRunning == false); mRunning = true; } @@ -130,51 +123,50 @@ void EcoreCallbackManager::Start() void EcoreCallbackManager::Stop() { // make sure we're not called twice - DALI_ASSERT_DEBUG( mRunning == true ); + DALI_ASSERT_DEBUG(mRunning == true); RemoveAllCallbacks(); mRunning = false; - } -bool EcoreCallbackManager::AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) +bool EcoreCallbackManager::AddIdleCallback(CallbackBase* callback, bool hasReturnValue) { - if( !mRunning ) + if(!mRunning) { return false; } - CallbackData* callbackData = new CallbackData( callback, hasReturnValue ); + CallbackData* callbackData = new CallbackData(callback, hasReturnValue); - callbackData->mRemoveFromContainerFunction = MakeCallback( this, &EcoreCallbackManager::RemoveCallbackFromContainer ); + callbackData->mRemoveFromContainerFunction = MakeCallback(this, &EcoreCallbackManager::RemoveCallbackFromContainer); // add the call back to the container mCallbackContainer.push_front(callbackData); // add the idler - callbackData->mIdler = ecore_idler_add( IdleCallback, callbackData); + callbackData->mIdler = ecore_idler_add(IdleCallback, callbackData); - DALI_ASSERT_ALWAYS( ( callbackData->mIdler != NULL ) && "Idle method not created" ); + DALI_ASSERT_ALWAYS((callbackData->mIdler != NULL) && "Idle method not created"); return true; } -void EcoreCallbackManager::RemoveIdleCallback( CallbackBase* callback ) +void EcoreCallbackManager::RemoveIdleCallback(CallbackBase* callback) { - for( CallbackList::iterator it = mCallbackContainer.begin(), - endIt = mCallbackContainer.end(); - it != endIt; - ++it ) + for(CallbackList::iterator it = mCallbackContainer.begin(), + endIt = mCallbackContainer.end(); + it != endIt; + ++it) { CallbackData* data = *it; - if( data->mCallback == callback ) + if(data->mCallback == callback) { // remove callback data from the container. - CallbackBase::Execute( *data->mRemoveFromContainerFunction, data ); + CallbackBase::Execute(*data->mRemoveFromContainerFunction, data); - ecore_idler_del( data->mIdler ); + ecore_idler_del(data->mIdler); // delete our data delete data; @@ -195,43 +187,43 @@ void EcoreCallbackManager::ClearIdleCallbacks() // @todo To be implemented. } -bool EcoreCallbackManager::AddIdleEntererCallback( CallbackBase* callback ) +bool EcoreCallbackManager::AddIdleEntererCallback(CallbackBase* callback) { - if( !mRunning ) + if(!mRunning) { return false; } - CallbackData* callbackData = new CallbackData( callback, true ); + CallbackData* callbackData = new CallbackData(callback, true); - callbackData->mRemoveFromContainerFunction = MakeCallback( this, &EcoreCallbackManager::RemoveCallbackFromContainer ); + callbackData->mRemoveFromContainerFunction = MakeCallback(this, &EcoreCallbackManager::RemoveCallbackFromContainer); // add the call back to the container - mCallbackContainer.push_front( callbackData ); + mCallbackContainer.push_front(callbackData); // add the idler - callbackData->mIdleEnterer = ecore_idle_enterer_add( IdleCallback, callbackData ); + callbackData->mIdleEnterer = ecore_idle_enterer_add(IdleCallback, callbackData); - DALI_ASSERT_ALWAYS( ( callbackData->mIdleEnterer != NULL ) && "Idle method not created" ); + DALI_ASSERT_ALWAYS((callbackData->mIdleEnterer != NULL) && "Idle method not created"); return true; } -void EcoreCallbackManager::RemoveIdleEntererCallback( CallbackBase* callback ) +void EcoreCallbackManager::RemoveIdleEntererCallback(CallbackBase* callback) { - for( CallbackList::iterator it = mCallbackContainer.begin(), - endIt = mCallbackContainer.end(); - it != endIt; - ++it ) + for(CallbackList::iterator it = mCallbackContainer.begin(), + endIt = mCallbackContainer.end(); + it != endIt; + ++it) { CallbackData* data = *it; - if( data->mCallback == callback ) + if(data->mCallback == callback) { // remove callback data from the container. - CallbackBase::Execute( *data->mRemoveFromContainerFunction, data ); + CallbackBase::Execute(*data->mRemoveFromContainerFunction, data); - ecore_idle_enterer_del( data->mIdleEnterer ); + ecore_idle_enterer_del(data->mIdleEnterer); // delete our data delete data; @@ -241,7 +233,7 @@ void EcoreCallbackManager::RemoveIdleEntererCallback( CallbackBase* callback ) } } -void EcoreCallbackManager::RemoveCallbackFromContainer(CallbackData *callbackData) +void EcoreCallbackManager::RemoveCallbackFromContainer(CallbackData* callbackData) { mCallbackContainer.remove(callbackData); } @@ -249,17 +241,17 @@ void EcoreCallbackManager::RemoveCallbackFromContainer(CallbackData *callbackDat void EcoreCallbackManager::RemoveAllCallbacks() { // always called from main thread - for( CallbackList::iterator iter = mCallbackContainer.begin(); iter != mCallbackContainer.end(); ++iter) + for(CallbackList::iterator iter = mCallbackContainer.begin(); iter != mCallbackContainer.end(); ++iter) { CallbackData* data = (*iter); - if( data->mIdler ) + if(data->mIdler) { - ecore_idler_del( data->mIdler ); + ecore_idler_del(data->mIdler); } - else if( data->mIdleEnterer ) + else if(data->mIdleEnterer) { - ecore_idle_enterer_del( data->mIdleEnterer ); + ecore_idle_enterer_del(data->mIdleEnterer); } delete data; diff --git a/dali/internal/system/linux/callback-manager-ecore.h b/dali/internal/system/linux/callback-manager-ecore.h index 2e4b90b..a76d5ce 100644 --- a/dali/internal/system/linux/callback-manager-ecore.h +++ b/dali/internal/system/linux/callback-manager-ecore.h @@ -2,7 +2,7 @@ #define DALI_ECORE_CALLBACK_MANAGER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,16 +24,12 @@ // INTERNAL INCLUDES #include - namespace Dali { - namespace Internal { - namespace Adaptor { - struct CallbackData; /** @@ -41,89 +37,85 @@ struct CallbackData; */ class EcoreCallbackManager : public CallbackManager { - public: - - /** + /** * @brief constructor */ - EcoreCallbackManager(); + EcoreCallbackManager(); - /** + /** * @brief destructor */ - ~EcoreCallbackManager() - { - } + ~EcoreCallbackManager() + { + } - /** + /** * @copydoc CallbackManager::AddIdleCallback() */ - bool AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) override; + bool AddIdleCallback(CallbackBase* callback, bool hasReturnValue) override; - /** + /** * @copydoc CallbackManager::RemoveIdleCallback() */ - void RemoveIdleCallback( CallbackBase* callback ) override; + void RemoveIdleCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::ProcessIdle() */ - bool ProcessIdle() override; + bool ProcessIdle() override; - /** + /** * @copydoc CallbackManager::ProcessIdle() */ - void ClearIdleCallbacks() override; + void ClearIdleCallbacks() override; - /** + /** * @copydoc CallbackManager::AddIdleEntererCallback() */ - bool AddIdleEntererCallback( CallbackBase* callback ) override; + bool AddIdleEntererCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::RemoveIdleEntererCallback() */ - void RemoveIdleEntererCallback( CallbackBase* callback ) override; + void RemoveIdleEntererCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::Start() */ - void Start() override; + void Start() override; - /** + /** * @copydoc CallbackManager::Stop() */ - void Stop() override; + void Stop() override; private: - - /** + /** * @brief Remove all idle call backs that are pending * Called by Stop() * Always called from the main thread */ - void RemoveAllCallbacks(); + void RemoveAllCallbacks(); - /** + /** * @brief Removes a single call back from the container * Always called from main thread * @param callbackData callback data */ - void RemoveCallbackFromContainer(CallbackData *callbackData); + void RemoveCallbackFromContainer(CallbackData* callbackData); - /** + /** * @brief Remove a standard call back from ecore * Always called from main thread * @param callbackData callback data */ - void RemoveStandardCallback(CallbackData *callbackData); - + void RemoveStandardCallback(CallbackData* callbackData); - typedef std::list CallbackList; + typedef std::list CallbackList; - bool mRunning; ///< flag is set to true if when running - CallbackList mCallbackContainer; ///< container of live idle callbacks + bool mRunning; ///< flag is set to true if when running + CallbackList mCallbackContainer; ///< container of live idle callbacks }; } // namespace Adaptor diff --git a/dali/internal/system/linux/dali-ecore-x.h b/dali/internal/system/linux/dali-ecore-x.h index e9c0cd9..728abdd 100644 --- a/dali/internal/system/linux/dali-ecore-x.h +++ b/dali/internal/system/linux/dali-ecore-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_SYSTEM_LINUX_DALI_ECORE_X_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_SYSTEM_LINUX_DALI_ECORE_X_H */ diff --git a/dali/internal/system/linux/dali-ecore.h b/dali/internal/system/linux/dali-ecore.h index 61fb714..3c0a28c 100644 --- a/dali/internal/system/linux/dali-ecore.h +++ b/dali/internal/system/linux/dali-ecore.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_SYSTEM_LINUX_DALI_ECORE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_SYSTEM_LINUX_DALI_ECORE_H */ diff --git a/dali/internal/system/linux/dali-elementary.h b/dali/internal/system/linux/dali-elementary.h index 1621aff..7ce3506 100644 --- a/dali/internal/system/linux/dali-elementary.h +++ b/dali/internal/system/linux/dali-elementary.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_SYSTEM_LINUX_DALI_ELEMENTARY_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,4 @@ #pragma GCC system_header #include - - #endif /* DALI_INTERNAL_SYSTEM_LINUX_DALI_ELEMENTARY_H */ diff --git a/dali/internal/system/linux/file-descriptor-monitor-ecore.cpp b/dali/internal/system/linux/file-descriptor-monitor-ecore.cpp index 83d63f4..35eb5c0 100644 --- a/dali/internal/system/linux/file-descriptor-monitor-ecore.cpp +++ b/dali/internal/system/linux/file-descriptor-monitor-ecore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,24 +26,21 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Using Impl to hide away EFL specific members */ struct FileDescriptorMonitor::Impl { // Construction - Impl( int fileDescriptor, CallbackBase* callback, int eventsToMonitor) - : mFileDescriptor( fileDescriptor ), - mEventsToMonitor( eventsToMonitor ), - mCallback( callback ), - mHandler( NULL ) + Impl(int fileDescriptor, CallbackBase* callback, int eventsToMonitor) + : mFileDescriptor(fileDescriptor), + mEventsToMonitor(eventsToMonitor), + mCallback(callback), + mHandler(NULL) { } @@ -53,9 +50,9 @@ struct FileDescriptorMonitor::Impl } // Data - int mFileDescriptor; - int mEventsToMonitor; ///< what file descriptor events to monitor - CallbackBase* mCallback; + int mFileDescriptor; + int mEventsToMonitor; ///< what file descriptor events to monitor + CallbackBase* mCallback; Ecore_Fd_Handler* mHandler; // Static Methods @@ -63,74 +60,73 @@ struct FileDescriptorMonitor::Impl /** * Called when the file descriptor receives an event. */ - static Eina_Bool EventDispatch(void* data, Ecore_Fd_Handler *handler) + static Eina_Bool EventDispatch(void* data, Ecore_Fd_Handler* handler) { Impl* impl = reinterpret_cast(data); // if we want read events, check to see if a read event is available int type = FileDescriptorMonitor::FD_NO_EVENT; - if( ecore_main_fd_handler_active_get( handler, ECORE_FD_ERROR) ) + if(ecore_main_fd_handler_active_get(handler, ECORE_FD_ERROR)) { - CallbackBase::Execute( *impl->mCallback, FileDescriptorMonitor::FD_ERROR, impl->mFileDescriptor ); + CallbackBase::Execute(*impl->mCallback, FileDescriptorMonitor::FD_ERROR, impl->mFileDescriptor); DALI_LOG_ERROR("ECORE_FD_ERROR occurred on %d\n", impl->mFileDescriptor); return ECORE_CALLBACK_CANCEL; } - if( impl->mEventsToMonitor & ECORE_FD_READ ) + if(impl->mEventsToMonitor & ECORE_FD_READ) { - if (ecore_main_fd_handler_active_get( handler, ECORE_FD_READ)) + if(ecore_main_fd_handler_active_get(handler, ECORE_FD_READ)) { type = FileDescriptorMonitor::FD_READABLE; } } // check if we want write events - if( impl->mEventsToMonitor & ECORE_FD_WRITE ) + if(impl->mEventsToMonitor & ECORE_FD_WRITE) { - if (ecore_main_fd_handler_active_get( handler, ECORE_FD_WRITE)) + if(ecore_main_fd_handler_active_get(handler, ECORE_FD_WRITE)) { type |= FileDescriptorMonitor::FD_WRITABLE; } } // if there is an event, execute the callback - if( type != FileDescriptorMonitor::FD_NO_EVENT ) + if(type != FileDescriptorMonitor::FD_NO_EVENT) { - CallbackBase::Execute( *impl->mCallback, static_cast< FileDescriptorMonitor::EventType >(type ), impl->mFileDescriptor ); + CallbackBase::Execute(*impl->mCallback, static_cast(type), impl->mFileDescriptor); } return ECORE_CALLBACK_RENEW; } }; -FileDescriptorMonitor::FileDescriptorMonitor( int fileDescriptor, CallbackBase* callback, int eventBitmask) +FileDescriptorMonitor::FileDescriptorMonitor(int fileDescriptor, CallbackBase* callback, int eventBitmask) { mImpl = new Impl(fileDescriptor, callback, eventBitmask); - if (fileDescriptor < 1) + if(fileDescriptor < 1) { - DALI_ASSERT_ALWAYS( 0 && "Invalid File descriptor"); + DALI_ASSERT_ALWAYS(0 && "Invalid File descriptor"); return; } int events = 0; - if( eventBitmask & FD_READABLE) + if(eventBitmask & FD_READABLE) { events = ECORE_FD_READ; } - if( eventBitmask & FD_WRITABLE) + if(eventBitmask & FD_WRITABLE) { events |= ECORE_FD_WRITE; } mImpl->mEventsToMonitor = events; - mImpl->mHandler = ecore_main_fd_handler_add( fileDescriptor, static_cast( events ), &Impl::EventDispatch, mImpl, NULL, NULL ); - + mImpl->mHandler = ecore_main_fd_handler_add(fileDescriptor, static_cast(events), &Impl::EventDispatch, mImpl, NULL, NULL); } FileDescriptorMonitor::~FileDescriptorMonitor() { - if (mImpl->mHandler) + if(mImpl->mHandler) { ecore_main_fd_handler_del(mImpl->mHandler); } diff --git a/dali/internal/system/linux/timer-impl-ecore.cpp b/dali/internal/system/linux/timer-impl-ecore.cpp index 7ebea28..b06945a 100644 --- a/dali/internal/system/linux/timer-impl-ecore.cpp +++ b/dali/internal/system/linux/timer-impl-ecore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,17 +26,14 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - // LOCAL STUFF namespace { -Eina_Bool TimerSourceFunc (void *data) +Eina_Bool TimerSourceFunc(void* data) { Timer* timer = static_cast(data); @@ -51,23 +48,23 @@ Eina_Bool TimerSourceFunc (void *data) */ struct Timer::Impl { - Impl( unsigned int milliSec ) + Impl(unsigned int milliSec) : mId(NULL), mInterval(milliSec) { } - Ecore_Timer * mId; + Ecore_Timer* mId; unsigned int mInterval; }; -TimerPtr Timer::New( unsigned int milliSec ) +TimerPtr Timer::New(unsigned int milliSec) { - TimerPtr timer( new Timer( milliSec ) ); + TimerPtr timer(new Timer(milliSec)); return timer; } -Timer::Timer( unsigned int milliSec ) +Timer::Timer(unsigned int milliSec) : mImpl(new Impl(milliSec)) { } @@ -81,20 +78,20 @@ Timer::~Timer() void Timer::Start() { // Timer should be used in the event thread - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); if(mImpl->mId != NULL) { Stop(); } - double interval = static_cast ( mImpl->mInterval ) / 1000.0f; - mImpl->mId = ecore_timer_add( interval, reinterpret_cast( TimerSourceFunc ), this ); + double interval = static_cast(mImpl->mInterval) / 1000.0f; + mImpl->mId = ecore_timer_add(interval, reinterpret_cast(TimerSourceFunc), this); } void Timer::Stop() { // Timer should be used in the event thread - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); ResetTimerData(); } @@ -102,32 +99,32 @@ void Timer::Stop() void Timer::Pause() { // Timer should be used in the event thread - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - if( mImpl->mId != NULL ) + if(mImpl->mId != NULL) { - ecore_timer_freeze( mImpl->mId ); + ecore_timer_freeze(mImpl->mId); } } void Timer::Resume() { // Timer should be used in the event thread - DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() ); + DALI_ASSERT_ALWAYS(Adaptor::IsAvailable()); - if( mImpl->mId != NULL ) + if(mImpl->mId != NULL) { - ecore_timer_thaw( mImpl->mId ); + ecore_timer_thaw(mImpl->mId); } } -void Timer::SetInterval( unsigned int interval, bool restart ) +void Timer::SetInterval(unsigned int interval, bool restart) { // stop existing timer Stop(); mImpl->mInterval = interval; - if( restart ) + if(restart) { // start new tick Start(); @@ -142,23 +139,23 @@ unsigned int Timer::GetInterval() const bool Timer::Tick() { // Guard against destruction during signal emission - Dali::Timer handle( this ); + Dali::Timer handle(this); - bool retVal( false ); + bool retVal(false); // Override with new signal if used - if( !mTickSignal.Empty() ) + if(!mTickSignal.Empty()) { retVal = mTickSignal.Emit(); // Timer stops if return value is false - if (retVal == false) + if(retVal == false) { Stop(); } else { - retVal = true; // continue emission + retVal = true; // continue emission } } else // no callbacks registered @@ -177,7 +174,7 @@ Dali::Timer::TimerSignalType& Timer::TickSignal() void Timer::ResetTimerData() { - if (mImpl->mId != NULL) + if(mImpl->mId != NULL) { ecore_timer_del(mImpl->mId); mImpl->mId = NULL; diff --git a/dali/internal/system/macos/callback-manager-mac.h b/dali/internal/system/macos/callback-manager-mac.h index e55ec96..b454af6 100644 --- a/dali/internal/system/macos/callback-manager-mac.h +++ b/dali/internal/system/macos/callback-manager-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ namespace Dali::Internal::Adaptor { - /** * @brief Cocoa Implementation of CallbackManager */ @@ -34,12 +33,12 @@ public: /** * @copydoc CallbackManager::AddIdleCallback() */ - bool AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) override; + bool AddIdleCallback(CallbackBase* callback, bool hasReturnValue) override; /** * @caopydoc CallbackManager::RemoveIdleCallback */ - void RemoveIdleCallback( CallbackBase* callback ) override; + void RemoveIdleCallback(CallbackBase* callback) override; /** * @copydoc CallbackManager::ProcessIdle @@ -54,12 +53,12 @@ public: /** * @copydoc CallbackManager::AddIdleEntererCallback */ - bool AddIdleEntererCallback( CallbackBase* callback ) override; + bool AddIdleEntererCallback(CallbackBase* callback) override; /** * @copydoc CallbackManager::RemoveIdleEntererCallback */ - void RemoveIdleEntererCallback( CallbackBase* callback ) override; + void RemoveIdleEntererCallback(CallbackBase* callback) override; /** * @copydoc CallbackManager::Start @@ -75,7 +74,7 @@ public: private: std::unique_ptr mImpl; - bool mRunning; + bool mRunning; }; -} +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/system/macos/file-descriptor-monitor-macos.cpp b/dali/internal/system/macos/file-descriptor-monitor-macos.cpp index 75d5a39..983a39f 100644 --- a/dali/internal/system/macos/file-descriptor-monitor-macos.cpp +++ b/dali/internal/system/macos/file-descriptor-monitor-macos.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,13 @@ namespace Dali::Internal::Adaptor { - FileDescriptorMonitor::FileDescriptorMonitor(int fileDescriptor, CallbackBase* callback, int eventBitmask) { DALI_LOG_WARNING("Implementation missing for macOS"); } FileDescriptorMonitor::~FileDescriptorMonitor() -{} +{ +} -} // Dali::Internal::Adaptor +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/system/macos/timer-impl-mac.cpp b/dali/internal/system/macos/timer-impl-mac.cpp index d3dfd3b..f6544ee 100644 --- a/dali/internal/system/macos/timer-impl-mac.cpp +++ b/dali/internal/system/macos/timer-impl-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,23 +21,26 @@ namespace Dali::Internal::Adaptor { - - /** * Struct to hide away macOS implementation details */ struct Timer::Impl { - Impl(Timer *parent, unsigned int milliSec) - : mTimer(CreateTimer(parent, milliSec)) {} + Impl(Timer* parent, unsigned int milliSec) + : mTimer(CreateTimer(parent, milliSec)) + { + } - ~Impl() { Stop(); } + ~Impl() + { + Stop(); + } - static void TimerProc(CFRunLoopTimerRef timer, void *info); + static void TimerProc(CFRunLoopTimerRef timer, void* info); void Start(); void Stop(); - void Reset(Timer *parent, unsigned int milliSec); + void Reset(Timer* parent, unsigned int milliSec); unsigned int GetInterval() const noexcept { @@ -50,20 +53,20 @@ struct Timer::Impl } private: - CFRef CreateTimer(Timer *parent, unsigned int milliSec); + CFRef CreateTimer(Timer* parent, unsigned int milliSec); CFRef mTimer; }; -void Timer::Impl::TimerProc(CFRunLoopTimerRef timer, void *info) +void Timer::Impl::TimerProc(CFRunLoopTimerRef timer, void* info) { - auto *pTimer = static_cast(info); + auto* pTimer = static_cast(info); pTimer->Tick(); } void Timer::Impl::Start() { - if (!IsRunning()) + if(!IsRunning()) { auto runLoop = CFRunLoopGetMain(); CFRunLoopAddTimer(runLoop, mTimer.get(), kCFRunLoopDefaultMode); @@ -72,7 +75,7 @@ void Timer::Impl::Start() void Timer::Impl::Stop() { - if (IsRunning()) + if(IsRunning()) { CFRunLoopTimerContext context; CFRunLoopTimerGetContext(mTimer.get(), &context); @@ -89,12 +92,11 @@ void Timer::Impl::Stop() 0, 0, TimerProc, - &context - )); + &context)); } } -void Timer::Impl::Reset(Timer *parent, unsigned int milliSec) +void Timer::Impl::Reset(Timer* parent, unsigned int milliSec) { Stop(); mTimer = CreateTimer(parent, milliSec); @@ -102,34 +104,34 @@ void Timer::Impl::Reset(Timer *parent, unsigned int milliSec) } CFRef -Timer::Impl::CreateTimer(Timer *parent, unsigned int milliSec) +Timer::Impl::CreateTimer(Timer* parent, unsigned int milliSec) { - const auto interval = static_cast(milliSec) / 1000; - const auto fireDate = CFAbsoluteTimeGetCurrent() + interval; + const auto interval = static_cast(milliSec) / 1000; + const auto fireDate = CFAbsoluteTimeGetCurrent() + interval; CFRunLoopTimerContext context = - { - .version = 0, - .info = parent, - .retain = nullptr, - .release = nullptr, - }; + { + .version = 0, + .info = parent, + .retain = nullptr, + .release = nullptr, + }; return MakeRef(CFRunLoopTimerCreate( kCFAllocatorDefault, - fireDate, interval, + fireDate, + interval, 0, 0, TimerProc, - &context - )); + &context)); } -TimerPtr Timer::New( unsigned int milliSec ) +TimerPtr Timer::New(unsigned int milliSec) { - return new Timer( milliSec ); + return new Timer(milliSec); } -Timer::Timer( unsigned int milliSec ) +Timer::Timer(unsigned int milliSec) : mImpl(new Impl(this, milliSec)) { } @@ -155,15 +157,13 @@ void Timer::Stop() void Timer::Pause() { - } void Timer::Resume() { - } -void Timer::SetInterval( unsigned int interval, bool restart ) +void Timer::SetInterval(unsigned int interval, bool restart) { mImpl->Reset(this, interval); } @@ -176,23 +176,23 @@ unsigned int Timer::GetInterval() const bool Timer::Tick() { // Guard against destruction during signal emission - Dali::Timer handle( this ); + Dali::Timer handle(this); - bool retVal( false ); + bool retVal(false); // Override with new signal if used - if( !mTickSignal.Empty() ) + if(!mTickSignal.Empty()) { retVal = mTickSignal.Emit(); // Timer stops if return value is false - if (retVal == false) + if(retVal == false) { Stop(); } else { - retVal = true; // continue emission + retVal = true; // continue emission } } else // no callbacks registered @@ -215,4 +215,3 @@ bool Timer::IsRunning() const } } // namespace Dali::Internal::Adaptor - diff --git a/dali/internal/system/macos/trigger-event.h b/dali/internal/system/macos/trigger-event.h index 9f80d4d..a41e0bd 100644 --- a/dali/internal/system/macos/trigger-event.h +++ b/dali/internal/system/macos/trigger-event.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,18 +21,16 @@ #include // INTERNAL INCLUDES -#include #include +#include #include namespace Dali::Internal::Adaptor { - class TriggerEvent : public TriggerEventInterface { public: - /** * Constructor * Creates an event file descriptor and starts a GSource which reads from the file @@ -42,7 +40,7 @@ public: * @param[in] options Trigger event options. * @note The ownership of callback is taken by this class. */ - TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ); + TriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options); /** * Triggers the event. @@ -54,7 +52,6 @@ public: struct Impl; private: - /** * @brief Called when our event file descriptor has been written to. * @param[in] eventBitMask bit mask of events that occured on the file descriptor @@ -62,7 +59,7 @@ private: void Triggered(); std::unique_ptr mCallback; - std::unique_ptr mImpl; + std::unique_ptr mImpl; }; } // namespace Dali::Internal::Adaptor diff --git a/dali/internal/system/macos/widget-application-impl-mac.cpp b/dali/internal/system/macos/widget-application-impl-mac.cpp index cecf303..4bc9bc9 100644 --- a/dali/internal/system/macos/widget-application-impl-mac.cpp +++ b/dali/internal/system/macos/widget-application-impl-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,31 +16,27 @@ */ // CLASS HEADER -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - WidgetApplicationPtr WidgetApplicationCocoa::New( - int* argc, - char **argv[], + int* argc, + char** argv[], const std::string& stylesheet) { - return new WidgetApplicationCocoa(argc, argv, stylesheet ); + return new WidgetApplicationCocoa(argc, argv, stylesheet); } WidgetApplicationCocoa::WidgetApplicationCocoa( - int* argc, - char** argv[], - const std::string& stylesheet -) + int* argc, + char** argv[], + const std::string& stylesheet) : WidgetApplication(argc, argv, stylesheet) { DALI_LOG_ERROR("WidgetApplication is not implemented in MACOS profile.\n"); @@ -51,9 +47,8 @@ WidgetApplicationCocoa::~WidgetApplicationCocoa() } void WidgetApplicationCocoa::RegisterWidgetCreatingFunction( - const std::string& widgetName, - Dali::WidgetApplication::CreateWidgetFunction createFunction -) + const std::string& widgetName, + Dali::WidgetApplication::CreateWidgetFunction createFunction) { } @@ -66,12 +61,12 @@ namespace WidgetApplicationFactory * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ -WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet ) +WidgetApplicationPtr Create(int* argc, char** argv[], const std::string& stylesheet) { - return WidgetApplicationCocoa::New( argc, argv, stylesheet ); + return WidgetApplicationCocoa::New(argc, argv, stylesheet); } -} // namespace Factory +} // namespace WidgetApplicationFactory } // namespace Adaptor diff --git a/dali/internal/system/macos/widget-application-impl-mac.h b/dali/internal/system/macos/widget-application-impl-mac.h index a126df3..444933c 100644 --- a/dali/internal/system/macos/widget-application-impl-mac.h +++ b/dali/internal/system/macos/widget-application-impl-mac.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ // INTERNAL INCLUDES #include -#include +#include #include namespace Dali @@ -29,23 +29,20 @@ class Widget; namespace Internal { - namespace Adaptor { - /** * Implementation of the WidgetApplicationCocoa class. */ class WidgetApplicationCocoa : public WidgetApplication { public: - typedef std::pair< const std::string, - Dali::WidgetApplication::CreateWidgetFunction - > CreateWidgetFunctionPair; + Dali::WidgetApplication::CreateWidgetFunction> + CreateWidgetFunctionPair; - typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer; + typedef std::vector CreateWidgetFunctionContainer; /** * Create a new widget application @@ -54,30 +51,26 @@ public: * @param[in] stylesheet The path to user defined theme file */ static WidgetApplicationPtr New( - int* argc, - char **argv[], - const std::string& stylesheet - ); + int* argc, + char** argv[], + const std::string& stylesheet); public: - /** * @copydoc Dali::WidgetApplication::RegisterWidgetCreator() */ void RegisterWidgetCreatingFunction( - const std::string& widgetName, - Dali::WidgetApplication::CreateWidgetFunction createFunction - ) override; + const std::string& widgetName, + Dali::WidgetApplication::CreateWidgetFunction createFunction) override; protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - WidgetApplicationCocoa( int* argc, char **argv[], const std::string& stylesheet ); + WidgetApplicationCocoa(int* argc, char** argv[], const std::string& stylesheet); /** * Destructor diff --git a/dali/internal/system/tizen-wayland/logging-tizen.cpp b/dali/internal/system/tizen-wayland/logging-tizen.cpp index 6638450..4ed6814 100644 --- a/dali/internal/system/tizen-wayland/logging-tizen.cpp +++ b/dali/internal/system/tizen-wayland/logging-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ namespace Dali { - namespace TizenPlatform { - void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& message) { const char* DALI_TAG = "DALI"; @@ -50,7 +48,6 @@ void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& messag break; } #pragma GCC diagnostic pop - } } // namespace TizenPlatform diff --git a/dali/internal/system/tizen-wayland/system-settings-tizen.cpp b/dali/internal/system/tizen-wayland/system-settings-tizen.cpp index aa1e48f..ea151a3 100644 --- a/dali/internal/system/tizen-wayland/system-settings-tizen.cpp +++ b/dali/internal/system/tizen-wayland/system-settings-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,14 +23,11 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -int GetLongPressTime( int defaultTime ) +int GetLongPressTime(int defaultTime) { return defaultTime; } diff --git a/dali/internal/system/tizen-wayland/tizen-wearable/watch-time.cpp b/dali/internal/system/tizen-wayland/tizen-wearable/watch-time.cpp index 345f0f4..4cf39d9 100644 --- a/dali/internal/system/tizen-wayland/tizen-wearable/watch-time.cpp +++ b/dali/internal/system/tizen-wayland/tizen-wearable/watch-time.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,25 +26,24 @@ namespace Dali { - struct WatchTime::Impl { - Impl(void *time_handle) + Impl(void* time_handle) : mTimeHandle(time_handle) { } - void *mTimeHandle; + void* mTimeHandle; }; -WatchTime::WatchTime(void *time_handle) +WatchTime::WatchTime(void* time_handle) { mImpl = new Impl(time_handle); } WatchTime::~WatchTime() { - if( mImpl ) + if(mImpl) { delete mImpl; mImpl = NULL; @@ -55,7 +54,9 @@ WatchTime::~WatchTime() WatchTime::WatchTime() { - watch_time_h watch_time = {0,}; + watch_time_h watch_time = { + 0, + }; watch_time_get_current_time(&watch_time); mImpl = new Impl(watch_time); @@ -167,7 +168,7 @@ bool WatchTime::GetDaylightSavingTimeStatus() const #else WatchTime::WatchTime() - :mImpl(NULL) +: mImpl(NULL) { } diff --git a/dali/internal/system/tizen-wayland/widget-application-impl-tizen.cpp b/dali/internal/system/tizen-wayland/widget-application-impl-tizen.cpp index ff22534..227284a 100644 --- a/dali/internal/system/tizen-wayland/widget-application-impl-tizen.cpp +++ b/dali/internal/system/tizen-wayland/widget-application-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ #include // INTERNAL INCLUDE -#include -#include #include #include #include +#include +#include // EXTERNAL INCLUDES #include @@ -31,16 +31,13 @@ namespace Dali { - namespace Internal { - namespace { - -int OnInstanceInit(widget_base_instance_h instanceHandle, bundle *content, int w, int h, void *classData) +int OnInstanceInit(widget_base_instance_h instanceHandle, bundle* content, int w, int h, void* classData) { - char *id; + char* id; widget_base_context_get_id(instanceHandle, &id); widget_base_class_on_create(instanceHandle, content, w, h); @@ -48,15 +45,15 @@ int OnInstanceInit(widget_base_instance_h instanceHandle, bundle *content, int w Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast(classData); Dali::Window window; - if( application->GetWidgetCount() == 0) + if(application->GetWidgetCount() == 0) { window = application->GetWindow(); - DALI_LOG_RELEASE_INFO("Widget Instance use default Window(win:%p), so it need to bind widget (%dx%d) (id:%s) \n",window, w, h, std::string(id).c_str()); + DALI_LOG_RELEASE_INFO("Widget Instance use default Window(win:%p), so it need to bind widget (%dx%d) (id:%s) \n", window, w, h, std::string(id).c_str()); } else { - window = Dali::Window::New(PositionSize(0,0,w,h) ,"", false); - if( window ) + window = Dali::Window::New(PositionSize(0, 0, w, h), "", false); + if(window) { DALI_LOG_RELEASE_INFO("Widget Instance create new Window (win:%p, cnt:%d) (%dx%d) (id:%s )\n", window, application->GetWidgetCount(), w, h, std::string(id).c_str()); } @@ -70,46 +67,46 @@ int OnInstanceInit(widget_base_instance_h instanceHandle, bundle *content, int w Any nativeHandle = window.GetNativeHandle(); #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Window * wlWindow = AnyCast( nativeHandle ); + Ecore_Wl2_Window* wlWindow = AnyCast(nativeHandle); #else - Ecore_Wl_Window * wlWindow = AnyCast( nativeHandle ); + Ecore_Wl_Window* wlWindow = AnyCast(nativeHandle); #endif - widget_base_context_window_bind( instanceHandle, id, wlWindow ); - window.SetSize( Dali::Window::WindowSize( w, h ) ); + widget_base_context_window_bind(instanceHandle, id, wlWindow); + window.SetSize(Dali::Window::WindowSize(w, h)); - Dali::Internal::Adaptor::WidgetApplication::CreateWidgetFunctionPair pair = application->GetWidgetCreatingFunctionPair(std::string(id)); - Dali::WidgetApplication::CreateWidgetFunction createFunction = pair.second; + Dali::Internal::Adaptor::WidgetApplication::CreateWidgetFunctionPair pair = application->GetWidgetCreatingFunctionPair(std::string(id)); + Dali::WidgetApplication::CreateWidgetFunction createFunction = pair.second; - Dali::Widget widgetInstance = createFunction( pair.first ); - application->AddWidget( instanceHandle, widgetInstance , window ); + Dali::Widget widgetInstance = createFunction(pair.first); + application->AddWidget(instanceHandle, widgetInstance, window); - Dali::Internal::Adaptor::Widget::Impl *widgetImpl = new Dali::Internal::Adaptor::WidgetImplTizen(instanceHandle); - Internal::Adaptor::GetImplementation(widgetInstance).SetImpl( widgetImpl ); + Dali::Internal::Adaptor::Widget::Impl* widgetImpl = new Dali::Internal::Adaptor::WidgetImplTizen(instanceHandle); + Internal::Adaptor::GetImplementation(widgetInstance).SetImpl(widgetImpl); std::string encodedContentString = ""; - if( bundle_get_count( content ) ) + if(bundle_get_count(content)) { - bundle_raw *bundleRaw; - int len; + bundle_raw* bundleRaw; + int len; bundle_encode(content, &bundleRaw, &len); - char* encodedContent = reinterpret_cast< char* >( bundleRaw ); - encodedContentString = std::string( encodedContent ); + char* encodedContent = reinterpret_cast(bundleRaw); + encodedContentString = std::string(encodedContent); free(bundleRaw); } - Internal::Adaptor::GetImplementation(widgetInstance).OnCreate( encodedContentString, window ); + Internal::Adaptor::GetImplementation(widgetInstance).OnCreate(encodedContentString, window); return 0; } -int OnInstanceDestroy(widget_base_instance_h instanceHandle, widget_base_destroy_type_e reason, bundle *content, void *classData) +int OnInstanceDestroy(widget_base_instance_h instanceHandle, widget_base_destroy_type_e reason, bundle* content, void* classData) { Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast(classData); // Get Dali::Widget instance. - Dali::Widget widgetInstance = application->GetWidget( instanceHandle ); + Dali::Widget widgetInstance = application->GetWidget(instanceHandle); Dali::Widget::Termination destroyReason = Dali::Widget::Termination::TEMPORARY; @@ -120,116 +117,115 @@ int OnInstanceDestroy(widget_base_instance_h instanceHandle, widget_base_destroy std::string encodedContentString = ""; - if( bundle_get_count( content ) ) + if(bundle_get_count(content)) { - bundle_raw *bundleRaw; - int len; + bundle_raw* bundleRaw; + int len; bundle_encode(content, &bundleRaw, &len); - char* encodedContent = reinterpret_cast< char* >( bundleRaw ); + char* encodedContent = reinterpret_cast(bundleRaw); encodedContentString = std::string(encodedContent); free(bundleRaw); } - Internal::Adaptor::GetImplementation(widgetInstance).OnTerminate( encodedContentString, destroyReason ); + Internal::Adaptor::GetImplementation(widgetInstance).OnTerminate(encodedContentString, destroyReason); widget_base_class_on_destroy(instanceHandle, reason, content); - application->DeleteWidget( instanceHandle ); + application->DeleteWidget(instanceHandle); return 0; } -int OnInstancePause(widget_base_instance_h instanceHandle, void *classData) +int OnInstancePause(widget_base_instance_h instanceHandle, void* classData) { widget_base_class_on_pause(instanceHandle); Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast(classData); // Get Dali::Widget instance. - Dali::Widget widgetInstance = application->GetWidget( instanceHandle ); + Dali::Widget widgetInstance = application->GetWidget(instanceHandle); Internal::Adaptor::GetImplementation(widgetInstance).OnPause(); return 0; } -int OnInstanceResume(widget_base_instance_h instanceHandle, void *classData) +int OnInstanceResume(widget_base_instance_h instanceHandle, void* classData) { widget_base_class_on_resume(instanceHandle); Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast(classData); // Get Dali::Widget instance. - Dali::Widget widgetInstance = application->GetWidget( instanceHandle ); + Dali::Widget widgetInstance = application->GetWidget(instanceHandle); Internal::Adaptor::GetImplementation(widgetInstance).OnResume(); return 0; } -int OnInstanceResize(widget_base_instance_h instanceHandle, int w, int h, void *classData) +int OnInstanceResize(widget_base_instance_h instanceHandle, int w, int h, void* classData) { widget_base_class_on_resize(instanceHandle, w, h); Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast(classData); // Get Dali::Widget instance. - Dali::Widget widgetInstance = application->GetWidget( instanceHandle ); - Dali::Window window = application->GetWindowFromWidget( instanceHandle ); - window.SetSize( Dali::Window::WindowSize(w, h) ); + Dali::Widget widgetInstance = application->GetWidget(instanceHandle); + Dali::Window window = application->GetWindowFromWidget(instanceHandle); + window.SetSize(Dali::Window::WindowSize(w, h)); Internal::Adaptor::GetImplementation(widgetInstance).OnResize(window); return 0; } -int OnInstanceUpdate(widget_base_instance_h instanceHandle, bundle *content, int force, void *classData) +int OnInstanceUpdate(widget_base_instance_h instanceHandle, bundle* content, int force, void* classData) { widget_base_class_on_update(instanceHandle, content, force); Dali::Internal::Adaptor::WidgetApplicationTizen* application = static_cast(classData); // Get Dali::Widget instance. - Dali::Widget widgetInstance = application->GetWidget( instanceHandle ); + Dali::Widget widgetInstance = application->GetWidget(instanceHandle); std::string encodedContentString = ""; - if( bundle_get_count( content ) ) + if(bundle_get_count(content)) { - bundle_raw *bundleRaw; - int len; + bundle_raw* bundleRaw; + int len; bundle_encode(content, &bundleRaw, &len); - char* encodedContent = reinterpret_cast< char* >( bundleRaw ); + char* encodedContent = reinterpret_cast(bundleRaw); encodedContentString = std::string(encodedContent); free(bundleRaw); } - Internal::Adaptor::GetImplementation(widgetInstance).OnUpdate( encodedContentString, force ); + Internal::Adaptor::GetImplementation(widgetInstance).OnUpdate(encodedContentString, force); return 0; } unsigned int GetEnvWidgetRenderRefreshRate() { - const char* envVariable = std::getenv( DALI_WIDGET_REFRESH_RATE ); + const char* envVariable = std::getenv(DALI_WIDGET_REFRESH_RATE); - return envVariable ? std::atoi( envVariable ) : 1u; // Default 60 fps + return envVariable ? std::atoi(envVariable) : 1u; // Default 60 fps } } // anonymous namespace namespace Adaptor { - WidgetApplicationPtr WidgetApplicationTizen::New( - int* argc, - char **argv[], + int* argc, + char** argv[], const std::string& stylesheet) { - return new WidgetApplicationTizen(argc, argv, stylesheet ); + return new WidgetApplicationTizen(argc, argv, stylesheet); } -WidgetApplicationTizen::WidgetApplicationTizen( int* argc, char** argv[], const std::string& stylesheet ) -:WidgetApplication(argc, argv, stylesheet) +WidgetApplicationTizen::WidgetApplicationTizen(int* argc, char** argv[], const std::string& stylesheet) +: WidgetApplication(argc, argv, stylesheet) { } @@ -237,54 +233,53 @@ WidgetApplicationTizen::~WidgetApplicationTizen() { } - -void WidgetApplicationTizen::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) +void WidgetApplicationTizen::RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) { - AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair(widgetName, createFunction) ); + AddWidgetCreatingFunctionPair(CreateWidgetFunctionPair(widgetName, createFunction)); // Register widget class to widget framework widget_base_class cls = widget_base_class_get_default(); - cls.ops.create = OnInstanceInit; - cls.ops.destroy = OnInstanceDestroy; - cls.ops.pause = OnInstancePause; - cls.ops.resume = OnInstanceResume; - cls.ops.resize = OnInstanceResize; - cls.ops.update = OnInstanceUpdate; + cls.ops.create = OnInstanceInit; + cls.ops.destroy = OnInstanceDestroy; + cls.ops.pause = OnInstancePause; + cls.ops.resume = OnInstanceResume; + cls.ops.resize = OnInstanceResize; + cls.ops.update = OnInstanceUpdate; widget_base_class_add(cls, widgetName.c_str(), this); } -void WidgetApplicationTizen::AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair ) +void WidgetApplicationTizen::AddWidgetCreatingFunctionPair(CreateWidgetFunctionPair pair) { - mCreateWidgetFunctionContainer.push_back( pair ); + mCreateWidgetFunctionContainer.push_back(pair); } -WidgetApplicationTizen::CreateWidgetFunctionPair WidgetApplicationTizen::GetWidgetCreatingFunctionPair( const std::string& widgetName ) +WidgetApplicationTizen::CreateWidgetFunctionPair WidgetApplicationTizen::GetWidgetCreatingFunctionPair(const std::string& widgetName) { - int idx = widgetName.find(":"); - std::string widgetID = widgetName.substr( idx + 1 ); - for( CreateWidgetFunctionContainer::const_iterator iter = mCreateWidgetFunctionContainer.begin(); iter != mCreateWidgetFunctionContainer.end(); ++iter ) + int idx = widgetName.find(":"); + std::string widgetID = widgetName.substr(idx + 1); + for(CreateWidgetFunctionContainer::const_iterator iter = mCreateWidgetFunctionContainer.begin(); iter != mCreateWidgetFunctionContainer.end(); ++iter) { - if( widgetID.compare((*iter).first) == 0) + if(widgetID.compare((*iter).first) == 0) { return *iter; } } - return CreateWidgetFunctionPair( "", NULL ); + return CreateWidgetFunctionPair("", NULL); } -void WidgetApplicationTizen::AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget , Dali::Window window ) +void WidgetApplicationTizen::AddWidget(widget_base_instance_h widgetBaseInstance, Dali::Widget widget, Dali::Window window) { - mWidgetInstanceContainer.push_back( WidgetInstancePair(widgetBaseInstance, widget) ); - mWindowInstanceContainer.push_back( WindowInstancePair(widgetBaseInstance, window) ); + mWidgetInstanceContainer.push_back(WidgetInstancePair(widgetBaseInstance, widget)); + mWindowInstanceContainer.push_back(WindowInstancePair(widgetBaseInstance, window)); } -Dali::Widget WidgetApplicationTizen::GetWidget( widget_base_instance_h widgetBaseInstance ) const +Dali::Widget WidgetApplicationTizen::GetWidget(widget_base_instance_h widgetBaseInstance) const { - for( auto&& iter : mWidgetInstanceContainer ) + for(auto&& iter : mWidgetInstanceContainer) { - if( (iter).first == widgetBaseInstance ) + if((iter).first == widgetBaseInstance) { return (iter).second; } @@ -292,13 +287,12 @@ Dali::Widget WidgetApplicationTizen::GetWidget( widget_base_instance_h widgetBas return Dali::Widget(); } -void WidgetApplicationTizen::DeleteWidget( widget_base_instance_h widgetBaseInstance ) +void WidgetApplicationTizen::DeleteWidget(widget_base_instance_h widgetBaseInstance) { // Delete WidgetInstance - auto widgetInstance = std::find_if( mWidgetInstanceContainer.begin(), - mWidgetInstanceContainer.end(), - [widgetBaseInstance]( WidgetInstancePair pair ) - { return (pair.first == widgetBaseInstance); } ); + auto widgetInstance = std::find_if(mWidgetInstanceContainer.begin(), + mWidgetInstanceContainer.end(), + [widgetBaseInstance](WidgetInstancePair pair) { return (pair.first == widgetBaseInstance); }); if(widgetInstance != mWidgetInstanceContainer.end()) { @@ -306,10 +300,9 @@ void WidgetApplicationTizen::DeleteWidget( widget_base_instance_h widgetBaseInst } // Delete WindowInstance - auto windowInstance = std::find_if( mWindowInstanceContainer.begin(), - mWindowInstanceContainer.end(), - [widgetBaseInstance]( WindowInstancePair pair ) - { return (pair.first == widgetBaseInstance); } ); + auto windowInstance = std::find_if(mWindowInstanceContainer.begin(), + mWindowInstanceContainer.end(), + [widgetBaseInstance](WindowInstancePair pair) { return (pair.first == widgetBaseInstance); }); if(windowInstance != mWindowInstanceContainer.end()) { @@ -317,11 +310,11 @@ void WidgetApplicationTizen::DeleteWidget( widget_base_instance_h widgetBaseInst } } -Dali::Window WidgetApplicationTizen::GetWindowFromWidget( widget_base_instance_h widgetBaseInstance ) const +Dali::Window WidgetApplicationTizen::GetWindowFromWidget(widget_base_instance_h widgetBaseInstance) const { - for( auto&& iter : mWindowInstanceContainer ) + for(auto&& iter : mWindowInstanceContainer) { - if( (iter).first == widgetBaseInstance ) + if((iter).first == widgetBaseInstance) { Dali::Window ret = (iter).second; return ret; @@ -339,7 +332,7 @@ void WidgetApplicationTizen::OnInit() { WidgetApplication::OnInit(); - Dali::Adaptor::Get().SetRenderRefreshRate( GetEnvWidgetRenderRefreshRate() ); + Dali::Adaptor::Get().SetRenderRefreshRate(GetEnvWidgetRenderRefreshRate()); } // factory function, must be implemented @@ -351,12 +344,12 @@ namespace WidgetApplicationFactory * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ -Dali::Internal::Adaptor::WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet ) +Dali::Internal::Adaptor::WidgetApplicationPtr Create(int* argc, char** argv[], const std::string& stylesheet) { - return WidgetApplicationTizen::New( argc, argv, stylesheet ); + return WidgetApplicationTizen::New(argc, argv, stylesheet); } -} // namespace Factory +} // namespace WidgetApplicationFactory } // namespace Adaptor diff --git a/dali/internal/system/tizen-wayland/widget-application-impl-tizen.h b/dali/internal/system/tizen-wayland/widget-application-impl-tizen.h index cab11aa..f2462bd 100644 --- a/dali/internal/system/tizen-wayland/widget-application-impl-tizen.h +++ b/dali/internal/system/tizen-wayland/widget-application-impl-tizen.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIDGET_APPLICATION_TIZEN_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ #include // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { @@ -32,10 +32,8 @@ class Widget; namespace Internal { - namespace Adaptor { - class WidgetApplication; typedef IntrusivePtr WidgetApplicationPtr; @@ -45,9 +43,8 @@ typedef IntrusivePtr WidgetApplicationPtr; class WidgetApplicationTizen : public WidgetApplication { public: - - typedef std::pair CreateWidgetFunctionPair; - typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer; + typedef std::pair CreateWidgetFunctionPair; + typedef std::vector CreateWidgetFunctionContainer; /** * Create a new widget application @@ -55,7 +52,7 @@ public: * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet ); + static WidgetApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet); public: /** @@ -66,37 +63,37 @@ public: /** * @copydoc Dali::WidgetApplication::RegisterWidgetCreator() */ - void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) override; + void RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) override; /** * Add widget name - CreateWidgetFunction pair to container. */ - void AddWidgetCreatingFunctionPair( CreateWidgetFunctionPair pair ); + void AddWidgetCreatingFunctionPair(CreateWidgetFunctionPair pair); /** * Find and get CreateWidgetFunctionPair in container by widget name. */ - CreateWidgetFunctionPair GetWidgetCreatingFunctionPair( const std::string& widgetName ); + CreateWidgetFunctionPair GetWidgetCreatingFunctionPair(const std::string& widgetName); /** * Add widget_base_instance_h - Widget instance pair to container. */ - void AddWidget( widget_base_instance_h widgetBaseInstance, Dali::Widget widget , Dali::Window window ); + void AddWidget(widget_base_instance_h widgetBaseInstance, Dali::Widget widget, Dali::Window window); /** * Find and get Widget instance in container by widget_base_instance_h. */ - Dali::Widget GetWidget( widget_base_instance_h widgetBaseInstance ) const; + Dali::Widget GetWidget(widget_base_instance_h widgetBaseInstance) const; /** * Delete widget_base_instance_h - Widget instance pair in container. */ - void DeleteWidget( widget_base_instance_h widgetBaseInstance ); + void DeleteWidget(widget_base_instance_h widgetBaseInstance); /** * Find and get Window instance in container by widget_base_instance_h. */ - Dali::Window GetWindowFromWidget( widget_base_instance_h widgetBaseInstance ) const; + Dali::Window GetWindowFromWidget(widget_base_instance_h widgetBaseInstance) const; /** * Get the number of created widget. @@ -104,14 +101,13 @@ public: int32_t GetWidgetCount(); protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - WidgetApplicationTizen( int* argc, char **argv[], const std::string& stylesheet ); + WidgetApplicationTizen(int* argc, char** argv[], const std::string& stylesheet); /** * Destructor @@ -122,16 +118,15 @@ protected: WidgetApplicationTizen& operator=(Application&) = delete; private: + typedef std::pair WidgetInstancePair; + typedef std::vector WidgetInstanceContainer; - typedef std::pair< widget_base_instance_h, Dali::Widget > WidgetInstancePair; - typedef std::vector< WidgetInstancePair > WidgetInstanceContainer; - - CreateWidgetFunctionContainer mCreateWidgetFunctionContainer; - WidgetInstanceContainer mWidgetInstanceContainer; + CreateWidgetFunctionContainer mCreateWidgetFunctionContainer; + WidgetInstanceContainer mWidgetInstanceContainer; - typedef std::pair< widget_base_instance_h, Dali::Window > WindowInstancePair; - typedef std::vector< WindowInstancePair > WindowInstanceContainer; - WindowInstanceContainer mWindowInstanceContainer; + typedef std::pair WindowInstancePair; + typedef std::vector WindowInstanceContainer; + WindowInstanceContainer mWindowInstanceContainer; }; } // namespace Adaptor diff --git a/dali/internal/system/tizen-wayland/widget-controller-tizen.cpp b/dali/internal/system/tizen-wayland/widget-controller-tizen.cpp index b6344c2..d4c4498 100644 --- a/dali/internal/system/tizen-wayland/widget-controller-tizen.cpp +++ b/dali/internal/system/tizen-wayland/widget-controller-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,15 +24,13 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -WidgetImplTizen::WidgetImplTizen( widget_base_instance_h instanceHandle ) -: Widget::Impl(), mInstanceHandle( instanceHandle ) +WidgetImplTizen::WidgetImplTizen(widget_base_instance_h instanceHandle) +: Widget::Impl(), + mInstanceHandle(instanceHandle) { } @@ -40,19 +38,18 @@ WidgetImplTizen::~WidgetImplTizen() { } -void WidgetImplTizen::SetContentInfo( const std::string& contentInfo ) +void WidgetImplTizen::SetContentInfo(const std::string& contentInfo) { - bundle *contentBundle; - bundle_raw *contentBundleRaw = reinterpret_cast< bundle_raw* >( const_cast(contentInfo.c_str()) ); - int len = contentInfo.length(); - contentBundle = bundle_decode(contentBundleRaw, len); + bundle* contentBundle; + bundle_raw* contentBundleRaw = reinterpret_cast(const_cast(contentInfo.c_str())); + int len = contentInfo.length(); + contentBundle = bundle_decode(contentBundleRaw, len); - widget_base_context_set_content_info( mInstanceHandle, contentBundle ); + widget_base_context_set_content_info(mInstanceHandle, contentBundle); - bundle_free( contentBundle ); + bundle_free(contentBundle); } - } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/system/tizen-wayland/widget-controller-tizen.h b/dali/internal/system/tizen-wayland/widget-controller-tizen.h index c9a58d4..de6ae1d 100644 --- a/dali/internal/system/tizen-wayland/widget-controller-tizen.h +++ b/dali/internal/system/tizen-wayland/widget-controller-tizen.h @@ -2,7 +2,7 @@ #define DALI_WIDGET_CONTROLLER_TIZEN_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,29 +23,25 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Holds the Implementation for the internal WidgetImpl class */ class WidgetImplTizen : public Widget::Impl { public: - /** * Constructor */ - WidgetImplTizen( widget_base_instance_h instanceHandle ); + WidgetImplTizen(widget_base_instance_h instanceHandle); /** * Destructor @@ -53,14 +49,12 @@ public: ~WidgetImplTizen() override; public: - /** * Set content information to widget framework */ - void SetContentInfo( const std::string& contentInfo ) override; + void SetContentInfo(const std::string& contentInfo) override; private: - widget_base_instance_h mInstanceHandle; }; diff --git a/dali/internal/system/ubuntu-x11/logging-x.cpp b/dali/internal/system/ubuntu-x11/logging-x.cpp index 9244e99..570d67f 100644 --- a/dali/internal/system/ubuntu-x11/logging-x.cpp +++ b/dali/internal/system/ubuntu-x11/logging-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,13 @@ namespace Dali { - namespace TizenPlatform { - void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& message) { const char* DALI_TAG = "DALI"; - const char *format = NULL; + const char* format = NULL; switch(level) { case Dali::Integration::Log::DebugInfo: @@ -48,7 +46,6 @@ void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& messag break; } printf(format, DALI_TAG, message.c_str()); - } } // namespace TizenPlatform diff --git a/dali/internal/system/ubuntu-x11/system-settings-x.cpp b/dali/internal/system/ubuntu-x11/system-settings-x.cpp index e0b9b57..bfaca6a 100644 --- a/dali/internal/system/ubuntu-x11/system-settings-x.cpp +++ b/dali/internal/system/ubuntu-x11/system-settings-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,19 +20,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - int GetElmAccessActionOver() { return 0; } -int GetLongPressTime( int defaultTime ) +int GetLongPressTime(int defaultTime) { return defaultTime; } diff --git a/dali/internal/system/ubuntu-x11/widget-application-impl-x.cpp b/dali/internal/system/ubuntu-x11/widget-application-impl-x.cpp index a9738d1..7502746 100644 --- a/dali/internal/system/ubuntu-x11/widget-application-impl-x.cpp +++ b/dali/internal/system/ubuntu-x11/widget-application-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,27 +16,24 @@ */ // CLASS HEADER -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - WidgetApplicationPtr WidgetApplicationUbuntu::New( - int* argc, - char **argv[], + int* argc, + char** argv[], const std::string& stylesheet) { - return new WidgetApplicationUbuntu(argc, argv, stylesheet ); + return new WidgetApplicationUbuntu(argc, argv, stylesheet); } -WidgetApplicationUbuntu::WidgetApplicationUbuntu( int* argc, char** argv[], const std::string& stylesheet ) +WidgetApplicationUbuntu::WidgetApplicationUbuntu(int* argc, char** argv[], const std::string& stylesheet) : WidgetApplication(argc, argv, stylesheet) { DALI_LOG_ERROR("WidgetApplication is not implemented in UBUNTU profile.\n"); @@ -46,8 +43,7 @@ WidgetApplicationUbuntu::~WidgetApplicationUbuntu() { } - -void WidgetApplicationUbuntu::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) +void WidgetApplicationUbuntu::RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) { } @@ -60,12 +56,12 @@ namespace WidgetApplicationFactory * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ -WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet ) +WidgetApplicationPtr Create(int* argc, char** argv[], const std::string& stylesheet) { - return WidgetApplicationUbuntu::New( argc, argv, stylesheet ); + return WidgetApplicationUbuntu::New(argc, argv, stylesheet); } -} // namespace Factory +} // namespace WidgetApplicationFactory } // namespace Adaptor diff --git a/dali/internal/system/ubuntu-x11/widget-application-impl-x.h b/dali/internal/system/ubuntu-x11/widget-application-impl-x.h index 2154bc9..30ee74e 100644 --- a/dali/internal/system/ubuntu-x11/widget-application-impl-x.h +++ b/dali/internal/system/ubuntu-x11/widget-application-impl-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_UBUNTU_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,19 +29,16 @@ class Widget; namespace Internal { - namespace Adaptor { - /** * Implementation of the WidgetApplicationUbuntu class. */ class WidgetApplicationUbuntu : public WidgetApplication { public: - - typedef std::pair CreateWidgetFunctionPair; - typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer; + typedef std::pair CreateWidgetFunctionPair; + typedef std::vector CreateWidgetFunctionContainer; /** * Create a new widget application @@ -49,24 +46,22 @@ public: * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet ); + static WidgetApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet); public: - /** * @copydoc Dali::WidgetApplication::RegisterWidgetCreator() */ - void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) override; + void RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) override; protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - WidgetApplicationUbuntu( int* argc, char **argv[], const std::string& stylesheet ); + WidgetApplicationUbuntu(int* argc, char** argv[], const std::string& stylesheet); /** * Destructor diff --git a/dali/internal/system/ubuntu-x11/widget-controller-x.cpp b/dali/internal/system/ubuntu-x11/widget-controller-x.cpp index 3c1806a..dc40cdd 100644 --- a/dali/internal/system/ubuntu-x11/widget-controller-x.cpp +++ b/dali/internal/system/ubuntu-x11/widget-controller-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - WidgetImplUbuntu::WidgetImplUbuntu() { } @@ -35,7 +32,7 @@ WidgetImplUbuntu::~WidgetImplUbuntu() { } -void WidgetImplUbuntu::SetContentInfo( const std::string& contentInfo ) +void WidgetImplUbuntu::SetContentInfo(const std::string& contentInfo) { } diff --git a/dali/internal/system/ubuntu-x11/widget-controller-x.h b/dali/internal/system/ubuntu-x11/widget-controller-x.h index 20eef3d..685e52a 100644 --- a/dali/internal/system/ubuntu-x11/widget-controller-x.h +++ b/dali/internal/system/ubuntu-x11/widget-controller-x.h @@ -2,7 +2,7 @@ #define DALI_WIDGET_CONTROLLER_UBUNTU_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { /** @@ -38,7 +36,6 @@ namespace Adaptor class WidgetImplUbuntu : public Widget::Impl { public: - /** * Constructor */ @@ -50,11 +47,10 @@ public: ~WidgetImplUbuntu() override; public: - /** * Set content information to widget framework */ - void SetContentInfo( const std::string& contentInfo ) override; + void SetContentInfo(const std::string& contentInfo) override; }; } // namespace Adaptor diff --git a/dali/internal/system/windows/callback-manager-win.cpp b/dali/internal/system/windows/callback-manager-win.cpp old mode 100755 new mode 100644 index 27f9465..84a1279 --- a/dali/internal/system/windows/callback-manager-win.cpp +++ b/dali/internal/system/windows/callback-manager-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,55 +19,52 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - WinCallbackManager::WinCallbackManager() -:mRunning(false) +: mRunning(false) { } void WinCallbackManager::Start() { - DALI_ASSERT_DEBUG( mRunning == false ); + DALI_ASSERT_DEBUG(mRunning == false); mRunning = true; } void WinCallbackManager::Stop() { // make sure we're not called twice - DALI_ASSERT_DEBUG( mRunning == true ); + DALI_ASSERT_DEBUG(mRunning == true); mRunning = false; } -bool WinCallbackManager::AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) +bool WinCallbackManager::AddIdleCallback(CallbackBase* callback, bool hasReturnValue) { - if( !mRunning ) + if(!mRunning) { return false; } mCallbacks.insert(callback); - WindowsPlatform::PostWinThreadMessage( WIN_CALLBACK_EVENT, reinterpret_cast(callback), 0 ); + WindowsPlatform::PostWinThreadMessage(WIN_CALLBACK_EVENT, reinterpret_cast(callback), 0); return true; } -void WinCallbackManager::RemoveIdleCallback( CallbackBase* callback ) +void WinCallbackManager::RemoveIdleCallback(CallbackBase* callback) { //Wait for deal } @@ -76,7 +73,7 @@ bool WinCallbackManager::ProcessIdle() { const bool idleProcessed = !mCallbacks.empty(); - for (CallbackBase* cb : mCallbacks) + for(CallbackBase* cb : mCallbacks) { Dali::CallbackBase::Execute(*cb); } @@ -90,14 +87,13 @@ void WinCallbackManager::ClearIdleCallbacks() mCallbacks.clear(); } -bool WinCallbackManager::AddIdleEntererCallback( CallbackBase* callback ) +bool WinCallbackManager::AddIdleEntererCallback(CallbackBase* callback) { - return AddIdleCallback( callback, true ); + return AddIdleCallback(callback, true); } -void WinCallbackManager::RemoveIdleEntererCallback( CallbackBase* callback ) +void WinCallbackManager::RemoveIdleEntererCallback(CallbackBase* callback) { - } // Creates a concrete interface for CallbackManager diff --git a/dali/internal/system/windows/callback-manager-win.h b/dali/internal/system/windows/callback-manager-win.h old mode 100755 new mode 100644 index eed550f..3915ec4 --- a/dali/internal/system/windows/callback-manager-win.h +++ b/dali/internal/system/windows/callback-manager-win.h @@ -2,7 +2,7 @@ #define DALI_WIN_CALLBACK_MANAGER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { /** @@ -38,40 +36,40 @@ namespace Adaptor */ class WinCallbackManager : public CallbackManager { - public: - - /** + /** * @brief constructor */ - WinCallbackManager(); + WinCallbackManager(); - /** + /** * @brief destructor */ - ~WinCallbackManager(){} + ~WinCallbackManager() + { + } - /** + /** * @copydoc CallbackManager::AddIdleCallback() */ - bool AddIdleCallback( CallbackBase* callback, bool hasReturnValue ) override; + bool AddIdleCallback(CallbackBase* callback, bool hasReturnValue) override; - /** + /** * @copydoc CallbackManager::RemoveIdleCallback() */ - void RemoveIdleCallback( CallbackBase* callback ) override; + void RemoveIdleCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::ProcessIdle() */ - bool ProcessIdle() override; + bool ProcessIdle() override; - /** + /** * @copydoc CallbackManager::ClearIdleCallbacks() */ - void ClearIdleCallbacks() override; + void ClearIdleCallbacks() override; - /** + /** * @brief Adds a @p callback to be run when entering an idle state. * @note Must be called from the main thread only. * @@ -85,9 +83,9 @@ public: * * @return true on success */ - bool AddIdleEntererCallback( CallbackBase* callback ) override; + bool AddIdleEntererCallback(CallbackBase* callback) override; - /** + /** * @brief Removes a previously added the idle enterer callback. * @note Must be called from main thread only. * @@ -95,21 +93,21 @@ public: * * @param[in] callback The callback to be removed. */ - void RemoveIdleEntererCallback( CallbackBase* callback ) override; + void RemoveIdleEntererCallback(CallbackBase* callback) override; - /** + /** * @copydoc CallbackManager::Start() */ - void Start() override; + void Start() override; - /** + /** * @copydoc CallbackManager::Stop() */ - void Stop() override; + void Stop() override; private: - std::set mCallbacks; - bool mRunning; ///< flag is set to true if when running + std::set mCallbacks; + bool mRunning; ///< flag is set to true if when running }; } // namespace Adaptor diff --git a/dali/internal/system/windows/file-descriptor-monitor-windows.cpp b/dali/internal/system/windows/file-descriptor-monitor-windows.cpp index 09e0eea..d937daa 100644 --- a/dali/internal/system/windows/file-descriptor-monitor-windows.cpp +++ b/dali/internal/system/windows/file-descriptor-monitor-windows.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,23 +23,21 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - FileDescriptorMonitor::FileDescriptorMonitor(int fileDescriptor, CallbackBase* callback, int eventBitmask) { DALI_LOG_WARNING("Implementation missing for MS Windows"); } FileDescriptorMonitor::~FileDescriptorMonitor() -{} +{ +} -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/system/windows/logging-win.cpp b/dali/internal/system/windows/logging-win.cpp index 9244e99..570d67f 100644 --- a/dali/internal/system/windows/logging-win.cpp +++ b/dali/internal/system/windows/logging-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,13 @@ namespace Dali { - namespace TizenPlatform { - void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& message) { const char* DALI_TAG = "DALI"; - const char *format = NULL; + const char* format = NULL; switch(level) { case Dali::Integration::Log::DebugInfo: @@ -48,7 +46,6 @@ void LogMessage(Dali::Integration::Log::DebugPriority level, std::string& messag break; } printf(format, DALI_TAG, message.c_str()); - } } // namespace TizenPlatform diff --git a/dali/internal/system/windows/system-settings-win.cpp b/dali/internal/system/windows/system-settings-win.cpp old mode 100755 new mode 100644 index 3cf5f2c..c4d82b3 --- a/dali/internal/system/windows/system-settings-win.cpp +++ b/dali/internal/system/windows/system-settings-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,21 +20,18 @@ namespace Dali { - namespace Internal { - namespace Adaptor { +int GetLongPressTime(int defaultTime) +{ + return defaultTime; +} -int GetLongPressTime( int defaultTime ) -{ - return defaultTime; -} - -int GetElmAccessActionOver() -{ - return 0; +int GetElmAccessActionOver() +{ + return 0; } } // namespace Adaptor diff --git a/dali/internal/system/windows/timer-impl-win.cpp b/dali/internal/system/windows/timer-impl-win.cpp old mode 100755 new mode 100644 index 6b71c56..8462ab2 --- a/dali/internal/system/windows/timer-impl-win.cpp +++ b/dali/internal/system/windows/timer-impl-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,30 +23,27 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - // LOCAL STUFF namespace { -bool TimerSourceFunc (void *data) +bool TimerSourceFunc(void* data) { Timer* timer = static_cast(data); return timer->Tick(); } -} +} // namespace /** * Struct to hide away Windows implementation details */ struct Timer::Impl { - Impl( unsigned int milliSec ) : - mId(-1), + Impl(unsigned int milliSec) + : mId(-1), mInterval(milliSec) { } @@ -56,13 +53,13 @@ struct Timer::Impl unsigned int mInterval; }; -TimerPtr Timer::New( unsigned int milliSec ) +TimerPtr Timer::New(unsigned int milliSec) { - TimerPtr timer( new Timer( milliSec ) ); + TimerPtr timer(new Timer(milliSec)); return timer; } -Timer::Timer( unsigned int milliSec ) +Timer::Timer(unsigned int milliSec) : mImpl(new Impl(milliSec)) { } @@ -78,34 +75,32 @@ Timer::~Timer() void Timer::Start() { - if( 0 > mImpl->mId ) + if(0 > mImpl->mId) { - mImpl->mId = WindowsPlatform::SetTimer( mImpl->mInterval, TimerSourceFunc, this ); + mImpl->mId = WindowsPlatform::SetTimer(mImpl->mInterval, TimerSourceFunc, this); } } void Timer::Stop() { - if( 0 <= mImpl->mId ) + if(0 <= mImpl->mId) { - WindowsPlatform::KillTimer( mImpl->mId ); + WindowsPlatform::KillTimer(mImpl->mId); mImpl->mId = -1; } } void Timer::Pause() { - } void Timer::Resume() { - } -void Timer::SetInterval( unsigned int interval, bool restart ) +void Timer::SetInterval(unsigned int interval, bool restart) { - if( true == restart ) + if(true == restart) { // stop existing timer Stop(); @@ -127,23 +122,23 @@ unsigned int Timer::GetInterval() const bool Timer::Tick() { // Guard against destruction during signal emission - Dali::Timer handle( this ); + Dali::Timer handle(this); - bool retVal( false ); + bool retVal(false); // Override with new signal if used - if( !mTickSignal.Empty() ) + if(!mTickSignal.Empty()) { retVal = mTickSignal.Emit(); // Timer stops if return value is false - if (retVal == false) + if(retVal == false) { Stop(); } else { - retVal = true; // continue emission + retVal = true; // continue emission } } else // no callbacks registered @@ -170,4 +165,3 @@ bool Timer::IsRunning() const } // namespace Internal } // namespace Dali - diff --git a/dali/internal/system/windows/trigger-event-factory.cpp b/dali/internal/system/windows/trigger-event-factory.cpp old mode 100755 new mode 100644 index 2631202..ffda950 --- a/dali/internal/system/windows/trigger-event-factory.cpp +++ b/dali/internal/system/windows/trigger-event-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,14 @@ namespace Dali { - -TriggerEventInterface* TriggerEventFactory::CreateTriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ) +TriggerEventInterface* TriggerEventFactory::CreateTriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options) { - return new Internal::Adaptor::TriggerEvent( callback, options ); + return new Internal::Adaptor::TriggerEvent(callback, options); } -void TriggerEventFactory::DestroyTriggerEvent( TriggerEventInterface* triggerEventInterface ) +void TriggerEventFactory::DestroyTriggerEvent(TriggerEventInterface* triggerEventInterface) { - Internal::Adaptor::TriggerEvent* triggerEvent( static_cast(triggerEventInterface) ); + Internal::Adaptor::TriggerEvent* triggerEvent(static_cast(triggerEventInterface)); delete triggerEvent; } diff --git a/dali/internal/system/windows/trigger-event.cpp b/dali/internal/system/windows/trigger-event.cpp old mode 100755 new mode 100644 index 66221cb..314621d --- a/dali/internal/system/windows/trigger-event.cpp +++ b/dali/internal/system/windows/trigger-event.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,27 +29,24 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -TriggerEvent::TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ) -: mCallback( callback ), - mThreadID( -1 ), - mOptions( options ) +TriggerEvent::TriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options) +: mCallback(callback), + mThreadID(-1), + mOptions(options) { // Create accompanying file descriptor. mThreadID = WindowsPlatform::GetCurrentThreadId(); - if ( mThreadID < 0) + if(mThreadID < 0) { DALI_LOG_ERROR("Unable to create TriggerEvent File descriptor\n"); } - mSelfCallback = MakeCallback( this, &TriggerEvent::Triggered ); + mSelfCallback = MakeCallback(this, &TriggerEvent::Triggered); } TriggerEvent::~TriggerEvent() @@ -57,7 +54,7 @@ TriggerEvent::~TriggerEvent() delete mCallback; delete mSelfCallback; - if ( mThreadID >= 0) + if(mThreadID >= 0) { mThreadID = 0; } @@ -65,12 +62,12 @@ TriggerEvent::~TriggerEvent() void TriggerEvent::Trigger() { - if ( mThreadID >= 0) + if(mThreadID >= 0) { // Increment event counter by 1. // Writing to the file descriptor triggers the Dispatch() method in the other thread // (if in multi-threaded environment). - WindowsPlatform::PostWinThreadMessage( WIN_CALLBACK_EVENT, reinterpret_cast( mSelfCallback ), 0, mThreadID ); + WindowsPlatform::PostWinThreadMessage(WIN_CALLBACK_EVENT, reinterpret_cast(mSelfCallback), 0, mThreadID); } else { @@ -81,10 +78,10 @@ void TriggerEvent::Trigger() void TriggerEvent::Triggered() { // Call the connected callback - CallbackBase::Execute( *mCallback ); + CallbackBase::Execute(*mCallback); //check if we should delete ourselves after the trigger - if( mOptions == TriggerEventInterface::DELETE_AFTER_TRIGGER ) + if(mOptions == TriggerEventInterface::DELETE_AFTER_TRIGGER) { delete this; } diff --git a/dali/internal/system/windows/trigger-event.h b/dali/internal/system/windows/trigger-event.h old mode 100755 new mode 100644 index 6bf2264..292f0ad --- a/dali/internal/system/windows/trigger-event.h +++ b/dali/internal/system/windows/trigger-event.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRIGGER_EVENT_IMPL_H /* -* Copyright (c) 2019 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,22 +22,18 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - class TriggerEvent : public TriggerEventInterface { public: - /** * Constructor * Creates an event file descriptor and starts a GSource which reads from the file @@ -47,7 +43,7 @@ public: * @param[in] options Trigger event options. * @note The ownership of callback is taken by this class. */ - TriggerEvent( CallbackBase* callback, TriggerEventInterface::Options options ); + TriggerEvent(CallbackBase* callback, TriggerEventInterface::Options options); /** * Destructor @@ -55,7 +51,6 @@ public: ~TriggerEvent(); public: - /** * Triggers the event. * @@ -64,7 +59,6 @@ public: void Trigger(); private: - /** * @brief Called when our event file descriptor has been written to. * @param[in] eventBitMask bit mask of events that occured on the file descriptor @@ -72,10 +66,9 @@ private: void Triggered(); private: - - CallbackBase* mCallback; - CallbackBase* mSelfCallback; - int32_t mThreadID; + CallbackBase* mCallback; + CallbackBase* mSelfCallback; + int32_t mThreadID; TriggerEventInterface::Options mOptions; }; diff --git a/dali/internal/system/windows/widget-application-impl-win.cpp b/dali/internal/system/windows/widget-application-impl-win.cpp old mode 100755 new mode 100644 index 57c38ee..da883da --- a/dali/internal/system/windows/widget-application-impl-win.cpp +++ b/dali/internal/system/windows/widget-application-impl-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,27 +16,24 @@ */ // CLASS HEADER -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - WidgetApplicationPtr WidgetApplicationWin::New( - int* argc, - char **argv[], + int* argc, + char** argv[], const std::string& stylesheet) { - return new WidgetApplicationWin(argc, argv, stylesheet ); + return new WidgetApplicationWin(argc, argv, stylesheet); } -WidgetApplicationWin::WidgetApplicationWin( int* argc, char** argv[], const std::string& stylesheet ) +WidgetApplicationWin::WidgetApplicationWin(int* argc, char** argv[], const std::string& stylesheet) : WidgetApplication(argc, argv, stylesheet) { DALI_LOG_ERROR("WidgetApplication is not implemented in UBUNTU profile.\n"); @@ -46,8 +43,7 @@ WidgetApplicationWin::~WidgetApplicationWin() { } - -void WidgetApplicationWin::RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) +void WidgetApplicationWin::RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) { } @@ -60,12 +56,12 @@ namespace WidgetApplicationFactory * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ -WidgetApplicationPtr Create( int* argc, char **argv[], const std::string& stylesheet ) +WidgetApplicationPtr Create(int* argc, char** argv[], const std::string& stylesheet) { - return WidgetApplicationWin::New( argc, argv, stylesheet ); + return WidgetApplicationWin::New(argc, argv, stylesheet); } -} // namespace Factory +} // namespace WidgetApplicationFactory } // namespace Adaptor diff --git a/dali/internal/system/windows/widget-application-impl-win.h b/dali/internal/system/windows/widget-application-impl-win.h old mode 100755 new mode 100644 index fd3b1ab..aab4077 --- a/dali/internal/system/windows/widget-application-impl-win.h +++ b/dali/internal/system/windows/widget-application-impl-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIDGET_APPLICATION_IMPL_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ // INTERNAL INCLUDES #include -#include +#include #include namespace Dali @@ -29,19 +29,16 @@ class Widget; namespace Internal { - namespace Adaptor { - /** * Implementation of the WidgetApplicationWin class. */ class WidgetApplicationWin : public WidgetApplication { public: - - typedef std::pair CreateWidgetFunctionPair; - typedef std::vector< CreateWidgetFunctionPair > CreateWidgetFunctionContainer; + typedef std::pair CreateWidgetFunctionPair; + typedef std::vector CreateWidgetFunctionContainer; /** * Create a new widget application @@ -49,24 +46,22 @@ public: * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - static WidgetApplicationPtr New( int* argc, char **argv[], const std::string& stylesheet ); + static WidgetApplicationPtr New(int* argc, char** argv[], const std::string& stylesheet); public: - /** * @copydoc Dali::WidgetApplication::RegisterWidgetCreator() */ - void RegisterWidgetCreatingFunction( const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction ) override; + void RegisterWidgetCreatingFunction(const std::string& widgetName, Dali::WidgetApplication::CreateWidgetFunction createFunction) override; protected: - /** * Private Constructor * @param[in] argc A pointer to the number of arguments * @param[in] argv A pointer to the argument list * @param[in] stylesheet The path to user defined theme file */ - WidgetApplicationWin( int* argc, char **argv[], const std::string& stylesheet ); + WidgetApplicationWin(int* argc, char** argv[], const std::string& stylesheet); /** * Destructor diff --git a/dali/internal/system/windows/widget-controller-win.cpp b/dali/internal/system/windows/widget-controller-win.cpp old mode 100755 new mode 100644 index e98e29c..7dd6686 --- a/dali/internal/system/windows/widget-controller-win.cpp +++ b/dali/internal/system/windows/widget-controller-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - WidgetImplWin::WidgetImplWin() { } @@ -35,7 +32,7 @@ WidgetImplWin::~WidgetImplWin() { } -void WidgetImplWin::SetContentInfo( const std::string& contentInfo ) +void WidgetImplWin::SetContentInfo(const std::string& contentInfo) { } diff --git a/dali/internal/system/windows/widget-controller-win.h b/dali/internal/system/windows/widget-controller-win.h old mode 100755 new mode 100644 index c19de62..63fe4e4 --- a/dali/internal/system/windows/widget-controller-win.h +++ b/dali/internal/system/windows/widget-controller-win.h @@ -2,7 +2,7 @@ #define DALI_WIDGET_CONTROLLER_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { /** @@ -38,7 +36,6 @@ namespace Adaptor class WidgetImplWin : public Widget::Impl { public: - /** * Constructor */ @@ -50,11 +47,10 @@ public: ~WidgetImplWin() override; public: - /** * Set content information to widget framework */ - void SetContentInfo( const std::string& contentInfo ) override; + void SetContentInfo(const std::string& contentInfo) override; }; } // namespace Adaptor diff --git a/dali/internal/text/text-abstraction/bidirectional-support-impl.cpp b/dali/internal/text/text-abstraction/bidirectional-support-impl.cpp old mode 100755 new mode 100644 index 7142ada..e6b9cd8 --- a/dali/internal/text/text-abstraction/bidirectional-support-impl.cpp +++ b/dali/internal/text/text-abstraction/bidirectional-support-impl.cpp @@ -19,78 +19,75 @@ #include // EXTERNAL INCLUDES -#include -#include -#include #include +#include +#include +#include namespace Dali { - namespace TextAbstraction { - namespace Internal { - namespace { - typedef unsigned char BidiDirection; +typedef unsigned char BidiDirection; - // Internal charcter's direction. - const BidiDirection LEFT_TO_RIGHT = 0u; - const BidiDirection NEUTRAL = 1u; - const BidiDirection RIGHT_TO_LEFT = 2u; +// Internal charcter's direction. +const BidiDirection LEFT_TO_RIGHT = 0u; +const BidiDirection NEUTRAL = 1u; +const BidiDirection RIGHT_TO_LEFT = 2u; - /** +/** * @param[in] paragraphDirection The FriBiDi paragraph's direction. * * @return Whether the paragraph is right to left. */ - bool GetBidiParagraphDirection( FriBidiParType paragraphDirection ) +bool GetBidiParagraphDirection(FriBidiParType paragraphDirection) +{ + switch(paragraphDirection) { - switch( paragraphDirection ) + case FRIBIDI_PAR_RTL: // Right-To-Left paragraph. + case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph. { - case FRIBIDI_PAR_RTL: // Right-To-Left paragraph. - case FRIBIDI_PAR_WRTL: // Weak Right To Left paragraph. - { - return true; - } - case FRIBIDI_PAR_LTR: // Left-To-Right paragraph. - case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph. - case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph. - { - return false; - } + return true; + } + case FRIBIDI_PAR_LTR: // Left-To-Right paragraph. + case FRIBIDI_PAR_ON: // DirectiOn-Neutral paragraph. + case FRIBIDI_PAR_WLTR: // Weak Left To Right paragraph. + { + return false; } - - return false; } - BidiDirection GetBidiCharacterDirection( FriBidiCharType characterDirection ) + return false; +} + +BidiDirection GetBidiCharacterDirection(FriBidiCharType characterDirection) +{ + switch(characterDirection) { - switch( characterDirection ) + case FRIBIDI_TYPE_LTR: // Left-To-Right letter. { - case FRIBIDI_TYPE_LTR: // Left-To-Right letter. - { - return LEFT_TO_RIGHT; - } - case FRIBIDI_TYPE_AL: // Arabic Letter. - case FRIBIDI_TYPE_RTL: // Right-To-Left letter. - { - return RIGHT_TO_LEFT; - } - case FRIBIDI_TYPE_AN: // Arabic Numeral. - case FRIBIDI_TYPE_ES: // European number Separator. - case FRIBIDI_TYPE_ET: // European number Terminator. - case FRIBIDI_TYPE_EN: // European Numeral. - default : - { - return NEUTRAL; - } + return LEFT_TO_RIGHT; + } + case FRIBIDI_TYPE_AL: // Arabic Letter. + case FRIBIDI_TYPE_RTL: // Right-To-Left letter. + { + return RIGHT_TO_LEFT; + } + case FRIBIDI_TYPE_AN: // Arabic Numeral. + case FRIBIDI_TYPE_ES: // European number Separator. + case FRIBIDI_TYPE_ET: // European number Terminator. + case FRIBIDI_TYPE_EN: // European Numeral. + default: + { + return NEUTRAL; } } } +} // namespace struct BidirectionalSupport::Plugin { @@ -99,176 +96,175 @@ struct BidirectionalSupport::Plugin */ struct BidirectionalInfo { - FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...) - FriBidiLevel* embeddedLevels; ///< Embedded levels. - FriBidiParType paragraphDirection; ///< The paragraph's direction. + FriBidiCharType* characterTypes; ///< The type of each character (right, left, neutral, ...) + FriBidiLevel* embeddedLevels; ///< Embedded levels. + FriBidiParType paragraphDirection; ///< The paragraph's direction. }; Plugin() : mParagraphBidirectionalInfo(), mFreeIndices() - {} + { + } ~Plugin() { // free all resources. - for( Vector::Iterator it = mParagraphBidirectionalInfo.Begin(), - endIt = mParagraphBidirectionalInfo.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = mParagraphBidirectionalInfo.Begin(), + endIt = mParagraphBidirectionalInfo.End(); + it != endIt; + ++it) { BidirectionalInfo* info = *it; - free( info->embeddedLevels ); - free( info->characterTypes ); + free(info->embeddedLevels); + free(info->characterTypes); delete info; } } - BidiInfoIndex CreateInfo( const Character* const paragraph, - Length numberOfCharacters, - bool matchSystemLanguageDirection, - LayoutDirection::Type layoutDirection ) + BidiInfoIndex CreateInfo(const Character* const paragraph, + Length numberOfCharacters, + bool matchSystemLanguageDirection, + LayoutDirection::Type layoutDirection) { // Reserve memory for the paragraph's bidirectional info. BidirectionalInfo* bidirectionalInfo = new BidirectionalInfo(); - bidirectionalInfo->characterTypes = reinterpret_cast( malloc( numberOfCharacters * sizeof( FriBidiCharType ) ) ); - if( !bidirectionalInfo->characterTypes ) + bidirectionalInfo->characterTypes = reinterpret_cast(malloc(numberOfCharacters * sizeof(FriBidiCharType))); + if(!bidirectionalInfo->characterTypes) { delete bidirectionalInfo; return 0; } - bidirectionalInfo->embeddedLevels = reinterpret_cast( malloc( numberOfCharacters * sizeof( FriBidiLevel ) ) ); - if( !bidirectionalInfo->embeddedLevels ) + bidirectionalInfo->embeddedLevels = reinterpret_cast(malloc(numberOfCharacters * sizeof(FriBidiLevel))); + if(!bidirectionalInfo->embeddedLevels) { - free( bidirectionalInfo->characterTypes ); + free(bidirectionalInfo->characterTypes); delete bidirectionalInfo; return 0; } // Retrieve the type of each character.. - fribidi_get_bidi_types( paragraph, numberOfCharacters, bidirectionalInfo->characterTypes ); + fribidi_get_bidi_types(paragraph, numberOfCharacters, bidirectionalInfo->characterTypes); // Retrieve the paragraph's direction. - bidirectionalInfo->paragraphDirection = matchSystemLanguageDirection == true ? - ( layoutDirection == LayoutDirection::RIGHT_TO_LEFT ? FRIBIDI_PAR_RTL : FRIBIDI_PAR_LTR ) : - ( fribidi_get_par_direction( bidirectionalInfo->characterTypes, numberOfCharacters ) ); + bidirectionalInfo->paragraphDirection = matchSystemLanguageDirection == true ? (layoutDirection == LayoutDirection::RIGHT_TO_LEFT ? FRIBIDI_PAR_RTL : FRIBIDI_PAR_LTR) : (fribidi_get_par_direction(bidirectionalInfo->characterTypes, numberOfCharacters)); // Retrieve the embedding levels. - if (fribidi_get_par_embedding_levels( bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels ) == 0) + if(fribidi_get_par_embedding_levels(bidirectionalInfo->characterTypes, numberOfCharacters, &bidirectionalInfo->paragraphDirection, bidirectionalInfo->embeddedLevels) == 0) { - free( bidirectionalInfo->characterTypes ); + free(bidirectionalInfo->characterTypes); delete bidirectionalInfo; return 0; } // Store the bidirectional info and return the index. BidiInfoIndex index = 0u; - if( 0u != mFreeIndices.Count() ) + if(0u != mFreeIndices.Count()) { Vector::Iterator it = mFreeIndices.End() - 1u; index = *it; - mFreeIndices.Remove( it ); + mFreeIndices.Remove(it); - *( mParagraphBidirectionalInfo.Begin() + index ) = bidirectionalInfo; + *(mParagraphBidirectionalInfo.Begin() + index) = bidirectionalInfo; } else { - index = static_cast( mParagraphBidirectionalInfo.Count() ); + index = static_cast(mParagraphBidirectionalInfo.Count()); - mParagraphBidirectionalInfo.PushBack( bidirectionalInfo ); + mParagraphBidirectionalInfo.PushBack(bidirectionalInfo); } return index; } - void DestroyInfo( BidiInfoIndex bidiInfoIndex ) + void DestroyInfo(BidiInfoIndex bidiInfoIndex) { - if( bidiInfoIndex >= mParagraphBidirectionalInfo.Count() ) + if(bidiInfoIndex >= mParagraphBidirectionalInfo.Count()) { return; } // Retrieve the paragraph's bidirectional info. - Vector::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex; - BidirectionalInfo* bidirectionalInfo = *it; + Vector::Iterator it = mParagraphBidirectionalInfo.Begin() + bidiInfoIndex; + BidirectionalInfo* bidirectionalInfo = *it; - if( NULL != bidirectionalInfo ) + if(NULL != bidirectionalInfo) { // Free resources and destroy the container. - free( bidirectionalInfo->embeddedLevels ); - free( bidirectionalInfo->characterTypes ); + free(bidirectionalInfo->embeddedLevels); + free(bidirectionalInfo->characterTypes); delete bidirectionalInfo; *it = NULL; } // Add the index to the free indices vector. - mFreeIndices.PushBack( bidiInfoIndex ); + mFreeIndices.PushBack(bidiInfoIndex); } - void Reorder( BidiInfoIndex bidiInfoIndex, - CharacterIndex firstCharacterIndex, - Length numberOfCharacters, - CharacterIndex* visualToLogicalMap ) + void Reorder(BidiInfoIndex bidiInfoIndex, + CharacterIndex firstCharacterIndex, + Length numberOfCharacters, + CharacterIndex* visualToLogicalMap) { const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT | FRIBIDI_FLAGS_ARABIC; // Retrieve the paragraph's bidirectional info. - const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); + const BidirectionalInfo* const bidirectionalInfo = *(mParagraphBidirectionalInfo.Begin() + bidiInfoIndex); // Initialize the visual to logical mapping table to the identity. Otherwise fribidi_reorder_line fails to retrieve a valid mapping table. - for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) + for(CharacterIndex index = 0u; index < numberOfCharacters; ++index) { - visualToLogicalMap[ index ] = index; + visualToLogicalMap[index] = index; } // Copy embedded levels as fribidi_reorder_line() may change them. - const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof( FriBidiLevel ); - FriBidiLevel* embeddedLevels = reinterpret_cast( malloc( embeddedLevelsSize ) ); - if( embeddedLevels ) + const uint32_t embeddedLevelsSize = numberOfCharacters * sizeof(FriBidiLevel); + FriBidiLevel* embeddedLevels = reinterpret_cast(malloc(embeddedLevelsSize)); + if(embeddedLevels) { - memcpy( embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize ); + memcpy(embeddedLevels, bidirectionalInfo->embeddedLevels + firstCharacterIndex, embeddedLevelsSize); // Reorder the line. - if (fribidi_reorder_line( flags, - bidirectionalInfo->characterTypes + firstCharacterIndex, - numberOfCharacters, - 0u, - bidirectionalInfo->paragraphDirection, - embeddedLevels, - NULL, - reinterpret_cast( visualToLogicalMap ) ) == 0) + if(fribidi_reorder_line(flags, + bidirectionalInfo->characterTypes + firstCharacterIndex, + numberOfCharacters, + 0u, + bidirectionalInfo->paragraphDirection, + embeddedLevels, + NULL, + reinterpret_cast(visualToLogicalMap)) == 0) { DALI_LOG_ERROR("fribidi_reorder_line is failed\n"); } // Free resources. - free( embeddedLevels ); + free(embeddedLevels); } } - bool GetMirroredText( Character* text, - CharacterDirection* directions, - Length numberOfCharacters ) const + bool GetMirroredText(Character* text, + CharacterDirection* directions, + Length numberOfCharacters) const { bool updated = false; - for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) + for(CharacterIndex index = 0u; index < numberOfCharacters; ++index) { // Get a reference to the character inside the text. - Character& character = *( text + index ); + Character& character = *(text + index); // Retrieve the mirrored character. FriBidiChar mirroredCharacter = character; - bool mirrored = false; - if( *( directions + index ) ) + bool mirrored = false; + if(*(directions + index)) { - mirrored = fribidi_get_mirror_char( character, &mirroredCharacter ); + mirrored = fribidi_get_mirror_char(character, &mirroredCharacter); } updated = updated || mirrored; @@ -279,39 +275,39 @@ struct BidirectionalSupport::Plugin return updated; } - bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const + bool GetParagraphDirection(BidiInfoIndex bidiInfoIndex) const { // Retrieve the paragraph's bidirectional info. - const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); + const BidirectionalInfo* const bidirectionalInfo = *(mParagraphBidirectionalInfo.Begin() + bidiInfoIndex); - return GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection ); + return GetBidiParagraphDirection(bidirectionalInfo->paragraphDirection); } - void GetCharactersDirection( BidiInfoIndex bidiInfoIndex, - CharacterDirection* directions, - Length numberOfCharacters ) + void GetCharactersDirection(BidiInfoIndex bidiInfoIndex, + CharacterDirection* directions, + Length numberOfCharacters) { - const BidirectionalInfo* const bidirectionalInfo = *( mParagraphBidirectionalInfo.Begin() + bidiInfoIndex ); + const BidirectionalInfo* const bidirectionalInfo = *(mParagraphBidirectionalInfo.Begin() + bidiInfoIndex); - const CharacterDirection paragraphDirection = GetBidiParagraphDirection( bidirectionalInfo->paragraphDirection ); - CharacterDirection previousDirection = paragraphDirection; + const CharacterDirection paragraphDirection = GetBidiParagraphDirection(bidirectionalInfo->paragraphDirection); + CharacterDirection previousDirection = paragraphDirection; - for( CharacterIndex index = 0u; index < numberOfCharacters; ++index ) + for(CharacterIndex index = 0u; index < numberOfCharacters; ++index) { - CharacterDirection& characterDirection = *( directions + index ); - CharacterDirection nextDirection = false; + CharacterDirection& characterDirection = *(directions + index); + CharacterDirection nextDirection = false; characterDirection = false; // Get the bidi direction. - const BidiDirection bidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + index ) ); + const BidiDirection bidiDirection = GetBidiCharacterDirection(*(bidirectionalInfo->characterTypes + index)); - if( RIGHT_TO_LEFT == bidiDirection ) + if(RIGHT_TO_LEFT == bidiDirection) { characterDirection = true; - nextDirection = true; + nextDirection = true; } - else if( NEUTRAL == bidiDirection ) + else if(NEUTRAL == bidiDirection) { // For neutral characters it check's the next and previous directions. // If they are equals set that direction. If they are not, sets the paragraph's direction. @@ -320,10 +316,10 @@ struct BidirectionalSupport::Plugin // Look for the next non-neutral character. Length nextIndex = index + 1u; - for( ; nextIndex < numberOfCharacters; ++nextIndex ) + for(; nextIndex < numberOfCharacters; ++nextIndex) { - BidiDirection nextBidiDirection = GetBidiCharacterDirection( *( bidirectionalInfo->characterTypes + nextIndex ) ); - if( nextBidiDirection != NEUTRAL ) + BidiDirection nextBidiDirection = GetBidiCharacterDirection(*(bidirectionalInfo->characterTypes + nextIndex)); + if(nextBidiDirection != NEUTRAL) { nextDirection = RIGHT_TO_LEFT == nextBidiDirection; break; @@ -337,16 +333,16 @@ struct BidirectionalSupport::Plugin // The indices from currentIndex + 1u to nextIndex - 1u are neutral characters. ++index; - for( ; index < nextIndex; ++index ) + for(; index < nextIndex; ++index) { - CharacterDirection& nextCharacterDirection = *( directions + index ); - nextCharacterDirection = characterDirection; + CharacterDirection& nextCharacterDirection = *(directions + index); + nextCharacterDirection = characterDirection; } // Set the direction of the next non-neutral character. - if( nextIndex < numberOfCharacters ) + if(nextIndex < numberOfCharacters) { - *( directions + nextIndex ) = nextDirection; + *(directions + nextIndex) = nextDirection; } } @@ -359,7 +355,7 @@ struct BidirectionalSupport::Plugin }; BidirectionalSupport::BidirectionalSupport() -: mPlugin( NULL ) +: mPlugin(NULL) { } @@ -372,93 +368,93 @@ TextAbstraction::BidirectionalSupport BidirectionalSupport::Get() { TextAbstraction::BidirectionalSupport bidirectionalSupportHandle; - SingletonService service( SingletonService::Get() ); - if( service ) + SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::BidirectionalSupport ) ); + BaseHandle handle = service.GetSingleton(typeid(TextAbstraction::BidirectionalSupport)); if(handle) { // If so, downcast the handle - BidirectionalSupport* impl = dynamic_cast< Internal::BidirectionalSupport* >( handle.GetObjectPtr() ); - bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( impl ); + BidirectionalSupport* impl = dynamic_cast(handle.GetObjectPtr()); + bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport(impl); } else // create and register the object { - bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport( new BidirectionalSupport ); - service.Register( typeid( bidirectionalSupportHandle ), bidirectionalSupportHandle ); + bidirectionalSupportHandle = TextAbstraction::BidirectionalSupport(new BidirectionalSupport); + service.Register(typeid(bidirectionalSupportHandle), bidirectionalSupportHandle); } } return bidirectionalSupportHandle; } -BidiInfoIndex BidirectionalSupport::CreateInfo( const Character* const paragraph, - Length numberOfCharacters, - bool matchSystemLanguageDirection, - Dali::LayoutDirection::Type layoutDirection ) +BidiInfoIndex BidirectionalSupport::CreateInfo(const Character* const paragraph, + Length numberOfCharacters, + bool matchSystemLanguageDirection, + Dali::LayoutDirection::Type layoutDirection) { CreatePlugin(); - return mPlugin->CreateInfo( paragraph, - numberOfCharacters, - matchSystemLanguageDirection, - layoutDirection ); + return mPlugin->CreateInfo(paragraph, + numberOfCharacters, + matchSystemLanguageDirection, + layoutDirection); } -void BidirectionalSupport::DestroyInfo( BidiInfoIndex bidiInfoIndex ) +void BidirectionalSupport::DestroyInfo(BidiInfoIndex bidiInfoIndex) { CreatePlugin(); - mPlugin->DestroyInfo( bidiInfoIndex ); + mPlugin->DestroyInfo(bidiInfoIndex); } -void BidirectionalSupport::Reorder( BidiInfoIndex bidiInfoIndex, - CharacterIndex firstCharacterIndex, - Length numberOfCharacters, - CharacterIndex* visualToLogicalMap ) +void BidirectionalSupport::Reorder(BidiInfoIndex bidiInfoIndex, + CharacterIndex firstCharacterIndex, + Length numberOfCharacters, + CharacterIndex* visualToLogicalMap) { CreatePlugin(); - mPlugin->Reorder( bidiInfoIndex, - firstCharacterIndex, - numberOfCharacters, - visualToLogicalMap ); + mPlugin->Reorder(bidiInfoIndex, + firstCharacterIndex, + numberOfCharacters, + visualToLogicalMap); } -bool BidirectionalSupport::GetMirroredText( Character* text, - CharacterDirection* directions, - Length numberOfCharacters ) +bool BidirectionalSupport::GetMirroredText(Character* text, + CharacterDirection* directions, + Length numberOfCharacters) { CreatePlugin(); - return mPlugin->GetMirroredText( text, directions, numberOfCharacters ); + return mPlugin->GetMirroredText(text, directions, numberOfCharacters); } -bool BidirectionalSupport::GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const +bool BidirectionalSupport::GetParagraphDirection(BidiInfoIndex bidiInfoIndex) const { - if( !mPlugin ) + if(!mPlugin) { return false; } - return mPlugin->GetParagraphDirection( bidiInfoIndex ); + return mPlugin->GetParagraphDirection(bidiInfoIndex); } -void BidirectionalSupport::GetCharactersDirection( BidiInfoIndex bidiInfoIndex, - CharacterDirection* directions, - Length numberOfCharacters ) +void BidirectionalSupport::GetCharactersDirection(BidiInfoIndex bidiInfoIndex, + CharacterDirection* directions, + Length numberOfCharacters) { CreatePlugin(); - mPlugin->GetCharactersDirection( bidiInfoIndex, - directions, - numberOfCharacters ); + mPlugin->GetCharactersDirection(bidiInfoIndex, + directions, + numberOfCharacters); } void BidirectionalSupport::CreatePlugin() { - if( !mPlugin ) + if(!mPlugin) { mPlugin = new Plugin(); } diff --git a/dali/internal/text/text-abstraction/bidirectional-support-impl.h b/dali/internal/text/text-abstraction/bidirectional-support-impl.h old mode 100755 new mode 100644 index bfd583a..03c7faa --- a/dali/internal/text/text-abstraction/bidirectional-support-impl.h +++ b/dali/internal/text/text-abstraction/bidirectional-support-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_BIDIRECTIONAL_SUPPORT_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,20 +27,16 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * Implementation of the BidirectionalSupport */ class BidirectionalSupport : public BaseObject { public: - /** * Constructor */ @@ -59,60 +55,57 @@ public: /** * @copydoc Dali::BidirectionalSupport::CreateInfo() */ - BidiInfoIndex CreateInfo( const Character* const paragraph, - Length numberOfCharacters, - bool matchSystemLanguageDirection, - LayoutDirection::Type layoutDirection ); + BidiInfoIndex CreateInfo(const Character* const paragraph, + Length numberOfCharacters, + bool matchSystemLanguageDirection, + LayoutDirection::Type layoutDirection); /** * @copydoc Dali::BidirectionalSupport::DestroyInfo() */ - void DestroyInfo( BidiInfoIndex bidiInfoIndex ); + void DestroyInfo(BidiInfoIndex bidiInfoIndex); /** * @copydoc Dali::BidirectionalSupport::Reorder() */ - void Reorder( BidiInfoIndex bidiInfoIndex, - CharacterIndex firstCharacterIndex, - Length numberOfCharacters, - CharacterIndex* visualToLogicalMap ); + void Reorder(BidiInfoIndex bidiInfoIndex, + CharacterIndex firstCharacterIndex, + Length numberOfCharacters, + CharacterIndex* visualToLogicalMap); /** * @copydoc Dali::BidirectionalSupport::GetMirroredText() */ - bool GetMirroredText( Character* text, - CharacterDirection* directions, - Length numberOfCharacters ); + bool GetMirroredText(Character* text, + CharacterDirection* directions, + Length numberOfCharacters); /** * @copydoc Dali::BidirectionalSupport::GetParagraphDirection() */ - bool GetParagraphDirection( BidiInfoIndex bidiInfoIndex ) const; + bool GetParagraphDirection(BidiInfoIndex bidiInfoIndex) const; /** * @copydoc Dali::BidirectionalSupport::GetCharactersDirection() */ - void GetCharactersDirection( BidiInfoIndex bidiInfoIndex, - CharacterDirection* directions, - Length numberOfCharacters ); + void GetCharactersDirection(BidiInfoIndex bidiInfoIndex, + CharacterDirection* directions, + Length numberOfCharacters); private: - /** * Helper for lazy initialization. */ void CreatePlugin(); private: - // Undefined copy constructor. - BidirectionalSupport( const BidirectionalSupport& ); + BidirectionalSupport(const BidirectionalSupport&); // Undefined assignment constructor. - BidirectionalSupport& operator=( const BidirectionalSupport& ); + BidirectionalSupport& operator=(const BidirectionalSupport&); private: - struct Plugin; Plugin* mPlugin; @@ -122,16 +115,16 @@ private: } // namespace TextAbstraction -inline static TextAbstraction::Internal::BidirectionalSupport& GetImplementation( TextAbstraction::BidirectionalSupport& bidirectionalSupport ) +inline static TextAbstraction::Internal::BidirectionalSupport& GetImplementation(TextAbstraction::BidirectionalSupport& bidirectionalSupport) { - DALI_ASSERT_ALWAYS( bidirectionalSupport && "bidirectional support handle is empty" ); + DALI_ASSERT_ALWAYS(bidirectionalSupport && "bidirectional support handle is empty"); BaseObject& handle = bidirectionalSupport.GetBaseObject(); return static_cast(handle); } -inline static const TextAbstraction::Internal::BidirectionalSupport& GetImplementation( const TextAbstraction::BidirectionalSupport& bidirectionalSupport ) +inline static const TextAbstraction::Internal::BidirectionalSupport& GetImplementation(const TextAbstraction::BidirectionalSupport& bidirectionalSupport) { - DALI_ASSERT_ALWAYS( bidirectionalSupport && "bidirectional support handle is empty" ); + DALI_ASSERT_ALWAYS(bidirectionalSupport && "bidirectional support handle is empty"); const BaseObject& handle = bidirectionalSupport.GetBaseObject(); return static_cast(handle); } diff --git a/dali/internal/text/text-abstraction/cairo-renderer.cpp b/dali/internal/text/text-abstraction/cairo-renderer.cpp old mode 100755 new mode 100644 index eba8cbe..0735798 --- a/dali/internal/text/text-abstraction/cairo-renderer.cpp +++ b/dali/internal/text/text-abstraction/cairo-renderer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include +#include #include #include @@ -42,10 +42,9 @@ using namespace std; namespace { - const float TO_FLOAT = 1.f / 255.f; const float TO_UCHAR = 255.f; -const float TWO_PI = 2.f * Dali::Math::PI; ///< 360 degrees in radians +const float TWO_PI = 2.f * Dali::Math::PI; ///< 360 degrees in radians /** * @brief Run of glyphs that have the same style. @@ -53,24 +52,25 @@ const float TWO_PI = 2.f * Dali::Math::PI; ///< 360 degrees in radians struct GlyphRun { GlyphRun() - : fontFace{ nullptr }, - fontSize{ 0.0 }, - glyphIndex{ 0u }, - numberOfGlyphs{ 0u }, - fontId{ 0u }, - colorIndex{ 0u }, - isItalicRequired{ false }, - isBoldRequired{ false } - {} - - FT_Face fontFace; ///< The font face used by the glyphs in the run. - double fontSize; ///< The font size used by the glyphs in the run. According the Cairo's documentation this is in user space units. It works if I set the size in pixels. - unsigned int glyphIndex; ///< Index to the first glyph of the run. - unsigned int numberOfGlyphs; ///< Number of glyphs in the run. - unsigned int fontId; ///< The id of the font. - unsigned int colorIndex; ///< The index to the color of the glyphs. - bool isItalicRequired:1; ///< Whether the italic style is required. - bool isBoldRequired:1; ///< Whether the bold style is required. + : fontFace{nullptr}, + fontSize{0.0}, + glyphIndex{0u}, + numberOfGlyphs{0u}, + fontId{0u}, + colorIndex{0u}, + isItalicRequired{false}, + isBoldRequired{false} + { + } + + FT_Face fontFace; ///< The font face used by the glyphs in the run. + double fontSize; ///< The font size used by the glyphs in the run. According the Cairo's documentation this is in user space units. It works if I set the size in pixels. + unsigned int glyphIndex; ///< Index to the first glyph of the run. + unsigned int numberOfGlyphs; ///< Number of glyphs in the run. + unsigned int fontId; ///< The id of the font. + unsigned int colorIndex; ///< The index to the color of the glyphs. + bool isItalicRequired : 1; ///< Whether the italic style is required. + bool isBoldRequired : 1; ///< Whether the bold style is required. }; /** @@ -92,19 +92,19 @@ struct GlyphBuffer DELETE }; - GlyphBuffer( Dali::TextAbstraction::FontClient::GlyphBufferData& data, DestructorType type ) - : data( data ), - type( type ) + GlyphBuffer(Dali::TextAbstraction::FontClient::GlyphBufferData& data, DestructorType type) + : data(data), + type(type) { } ~GlyphBuffer() { - switch( type ) + switch(type) { case FREE: { - free( data.buffer ); + free(data.buffer); break; } case DELETE: @@ -115,7 +115,7 @@ struct GlyphBuffer } Dali::TextAbstraction::FontClient::GlyphBufferData& data; - DestructorType type; + DestructorType type; }; /** @@ -125,16 +125,16 @@ struct GlyphBuffer * * @return The pixel buffer. */ -Dali::Devel::PixelBuffer CreateVoidPixelBuffer( const Dali::TextAbstraction::TextRenderer::Parameters& parameters ) +Dali::Devel::PixelBuffer CreateVoidPixelBuffer(const Dali::TextAbstraction::TextRenderer::Parameters& parameters) { - Dali::Pixel::Format pixelFormat = parameters.pixelFormat == Dali::TextAbstraction::TextRenderer::Parameters::A8 ? Dali::Pixel::A8 : Dali::Pixel::RGBA8888; - Dali::Devel::PixelBuffer pixelBuffer = Dali::Devel::PixelBuffer::New( parameters.width, - parameters.height, - pixelFormat ); + Dali::Pixel::Format pixelFormat = parameters.pixelFormat == Dali::TextAbstraction::TextRenderer::Parameters::A8 ? Dali::Pixel::A8 : Dali::Pixel::RGBA8888; + Dali::Devel::PixelBuffer pixelBuffer = Dali::Devel::PixelBuffer::New(parameters.width, + parameters.height, + pixelFormat); - const unsigned int bufferSize = parameters.width * parameters.height * Dali::Pixel::GetBytesPerPixel( pixelFormat ); - unsigned char* buffer = pixelBuffer.GetBuffer(); - memset( buffer, 0, bufferSize ); + const unsigned int bufferSize = parameters.width * parameters.height * Dali::Pixel::GetBytesPerPixel(pixelFormat); + unsigned char* buffer = pixelBuffer.GetBuffer(); + memset(buffer, 0, bufferSize); return pixelBuffer; } @@ -149,41 +149,41 @@ Dali::Devel::PixelBuffer CreateVoidPixelBuffer( const Dali::TextAbstraction::Tex * @param[in] circularCr The extra cairo context created to layout horizontal text. * @param[in] parameters The parameters of the circular path. */ -void WrapToCircularPath( cairo_t* cr, cairo_t* circularCr, const Dali::TextAbstraction::CircularTextParameters& parameters ) +void WrapToCircularPath(cairo_t* cr, cairo_t* circularCr, const Dali::TextAbstraction::CircularTextParameters& parameters) { bool first = true; // Copy the path to get a cairo_path_t pointer used to iterate through all its items. - std::unique_ptr path( cairo_copy_path( circularCr ), cairo_path_destroy ); + std::unique_ptr path(cairo_copy_path(circularCr), cairo_path_destroy); // Iterates through all the path items and transform each vertex to follow the circle. // Transformed vertices are added to a new path in the 'cr' context (the one used to render the circular text) - for( int i = 0; i < path->num_data; i += path->data[i].header.length ) + for(int i = 0; i < path->num_data; i += path->data[i].header.length) { cairo_path_data_t* data = &path->data[i]; - switch( data->header.type ) + switch(data->header.type) { case CAIRO_PATH_MOVE_TO: { - if( first ) + if(first) { - cairo_new_path( cr ); + cairo_new_path(cr); } - first = false; + first = false; double x = data[1].point.x; double y = data[1].point.y; - Dali::TextAbstraction::TransformToArc( parameters, x, y ); - cairo_move_to( cr, x, y ); + Dali::TextAbstraction::TransformToArc(parameters, x, y); + cairo_move_to(cr, x, y); break; } case CAIRO_PATH_LINE_TO: { double x = data[1].point.x; double y = data[1].point.y; - Dali::TextAbstraction::TransformToArc( parameters, x, y ); - cairo_line_to( cr, x, y ); + Dali::TextAbstraction::TransformToArc(parameters, x, y); + cairo_line_to(cr, x, y); break; } case CAIRO_PATH_CURVE_TO: @@ -194,20 +194,20 @@ void WrapToCircularPath( cairo_t* cr, cairo_t* circularCr, const Dali::TextAbstr double y2 = data[2].point.y; double x3 = data[3].point.x; double y3 = data[3].point.y; - Dali::TextAbstraction::TransformToArc( parameters, x1, y1 ); - Dali::TextAbstraction::TransformToArc( parameters, x2, y2 ); - Dali::TextAbstraction::TransformToArc( parameters, x3, y3 ); - cairo_curve_to( cr, x1, y1, x2, y2, x3, y3 ); + Dali::TextAbstraction::TransformToArc(parameters, x1, y1); + Dali::TextAbstraction::TransformToArc(parameters, x2, y2); + Dali::TextAbstraction::TransformToArc(parameters, x3, y3); + cairo_curve_to(cr, x1, y1, x2, y2, x3, y3); break; } case CAIRO_PATH_CLOSE_PATH: { - cairo_close_path( cr ); + cairo_close_path(cr); break; } default: { - DALI_LOG_WARNING( "Type of path not handled.\n" ); + DALI_LOG_WARNING("Type of path not handled.\n"); // Nothing else to do. break; } @@ -219,16 +219,12 @@ void WrapToCircularPath( cairo_t* cr, cairo_t* circularCr, const Dali::TextAbstr namespace Dali { - namespace TextAbstraction { - namespace Internal { - namespace { - /** * @brief Converts the size so that it can be used by Cairo * @param[in] fontClient A reference to the font client @@ -239,12 +235,12 @@ namespace * @param[in/out] glyphRuns A vector of glyph-runs */ bool ConvertSizeForCairo( - TextAbstraction::FontClient& fontClient, - FT_Library& ftLibrary, - const unsigned int numberOfGlyphs, - const GlyphInfo* const daliGlyphsBuffer, - const ColorIndex* const colorIndicesBuffer, - std::vector& glyphRuns) + TextAbstraction::FontClient& fontClient, + FT_Library& ftLibrary, + const unsigned int numberOfGlyphs, + const GlyphInfo* const daliGlyphsBuffer, + const ColorIndex* const colorIndicesBuffer, + std::vector& glyphRuns) { // The size set in Cairo and FreeType has different units. // Before the size is set in Cairo it needs to be converted according the formula @@ -252,73 +248,72 @@ bool ConvertSizeForCairo( // https://www.freetype.org/freetype2/docs/glyphs/glyphs-2.html unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - fontClient.GetDpi( horizontalDpi, verticalDpi ); - const double dVerticalDpi = static_cast( verticalDpi ); - - const double FROM_26_DOT_6_TO_PIXELS = dVerticalDpi / ( 64.0 * 72.0 ); + unsigned int verticalDpi = 0u; + fontClient.GetDpi(horizontalDpi, verticalDpi); + const double dVerticalDpi = static_cast(verticalDpi); + const double FROM_26_DOT_6_TO_PIXELS = dVerticalDpi / (64.0 * 72.0); GlyphRun currentGlyphRun; - currentGlyphRun.fontId = 0u; - currentGlyphRun.colorIndex = 0u; + currentGlyphRun.fontId = 0u; + currentGlyphRun.colorIndex = 0u; currentGlyphRun.isItalicRequired = false; - currentGlyphRun.isBoldRequired = false; - for( unsigned index = 0u; index < numberOfGlyphs; ++index ) + currentGlyphRun.isBoldRequired = false; + for(unsigned index = 0u; index < numberOfGlyphs; ++index) { - const GlyphInfo& daliGlyph = *( daliGlyphsBuffer + index ); - const FontId fontId = daliGlyph.fontId; - const ColorIndex colorIndex = ( nullptr == colorIndicesBuffer ) ? 0u : *( colorIndicesBuffer + index ); - const bool isItalicRequired = daliGlyph.isItalicRequired; - const bool isBoldRequired = daliGlyph.isBoldRequired; - - if( ( fontId != currentGlyphRun.fontId ) || - ( ( 0u == fontId ) && ( 0u != daliGlyph.index ) ) || - ( colorIndex != currentGlyphRun.colorIndex ) || - ( isItalicRequired != currentGlyphRun.isItalicRequired ) || - ( isBoldRequired != currentGlyphRun.isBoldRequired ) ) + const GlyphInfo& daliGlyph = *(daliGlyphsBuffer + index); + const FontId fontId = daliGlyph.fontId; + const ColorIndex colorIndex = (nullptr == colorIndicesBuffer) ? 0u : *(colorIndicesBuffer + index); + const bool isItalicRequired = daliGlyph.isItalicRequired; + const bool isBoldRequired = daliGlyph.isBoldRequired; + + if((fontId != currentGlyphRun.fontId) || + ((0u == fontId) && (0u != daliGlyph.index)) || + (colorIndex != currentGlyphRun.colorIndex) || + (isItalicRequired != currentGlyphRun.isItalicRequired) || + (isBoldRequired != currentGlyphRun.isBoldRequired)) { // There is a new run. First set the number of glyphs of the previous run and store it. currentGlyphRun.numberOfGlyphs = index - currentGlyphRun.glyphIndex; - if( 0u != currentGlyphRun.numberOfGlyphs ) + if(0u != currentGlyphRun.numberOfGlyphs) { - glyphRuns.push_back( currentGlyphRun ); + glyphRuns.push_back(currentGlyphRun); } - currentGlyphRun.fontFace = nullptr; - currentGlyphRun.fontSize = 0.0; - currentGlyphRun.glyphIndex = index; - currentGlyphRun.numberOfGlyphs = 0u; - currentGlyphRun.fontId = 0u; - currentGlyphRun.colorIndex = 0u; + currentGlyphRun.fontFace = nullptr; + currentGlyphRun.fontSize = 0.0; + currentGlyphRun.glyphIndex = index; + currentGlyphRun.numberOfGlyphs = 0u; + currentGlyphRun.fontId = 0u; + currentGlyphRun.colorIndex = 0u; currentGlyphRun.isItalicRequired = false; - currentGlyphRun.isBoldRequired = false; + currentGlyphRun.isBoldRequired = false; - if( 0u != fontId ) + if(0u != fontId) { // Get the font's path file name from the font Id. FontDescription fontDescription; - fontClient.GetDescription( fontId, fontDescription ); + fontClient.GetDescription(fontId, fontDescription); - switch( fontDescription.type ) + switch(fontDescription.type) { case FontDescription::FACE_FONT: { // Create a FreeType font's face. - auto error = FT_New_Face( ftLibrary, fontDescription.path.c_str(), 0u, ¤tGlyphRun.fontFace ); - if( error ) + auto error = FT_New_Face(ftLibrary, fontDescription.path.c_str(), 0u, ¤tGlyphRun.fontFace); + if(error) { - DALI_LOG_ERROR( "Error in FT while creating a new face\n" ); + DALI_LOG_ERROR("Error in FT while creating a new face\n"); // Error so just return false return false; } // Set the font's size. It needs to be set in the Freetype font and in the Cairo's context. - unsigned int fontSize = fontClient.GetPointSize( fontId ); + unsigned int fontSize = fontClient.GetPointSize(fontId); // Font's size to be set in the Cairo's context. - currentGlyphRun.fontSize = FROM_26_DOT_6_TO_PIXELS * static_cast( fontSize ); + currentGlyphRun.fontSize = FROM_26_DOT_6_TO_PIXELS * static_cast(fontSize); break; } case FontDescription::BITMAP_FONT: @@ -333,18 +328,18 @@ bool ConvertSizeForCairo( } } } - currentGlyphRun.fontId = fontId; - currentGlyphRun.colorIndex = colorIndex; + currentGlyphRun.fontId = fontId; + currentGlyphRun.colorIndex = colorIndex; currentGlyphRun.isItalicRequired = isItalicRequired; - currentGlyphRun.isBoldRequired = isBoldRequired; + currentGlyphRun.isBoldRequired = isBoldRequired; } } // Calculate the number of glyphs of the last run and store it. currentGlyphRun.numberOfGlyphs = numberOfGlyphs - currentGlyphRun.glyphIndex; - if( 0u != currentGlyphRun.numberOfGlyphs ) + if(0u != currentGlyphRun.numberOfGlyphs) { - glyphRuns.push_back( currentGlyphRun ); + glyphRuns.push_back(currentGlyphRun); } return true; // Successfully converted @@ -367,115 +362,115 @@ bool ConvertSizeForCairo( * @param[in] doBlendWithTextColor Whether to blend with the text color or not) */ void CopyImageToSurface( - const TextAbstraction::TextRenderer::Parameters& parameters, - const Pixel::Format pixelFormat, - TextAbstraction::FontClient::GlyphBufferData& data, - unsigned char * buffer, - const int rgbaCase, - const double glyphX, - const double glyphY, - const int strideWidth, - const Vector4& color, - const bool doBlendWithTextColor) + const TextAbstraction::TextRenderer::Parameters& parameters, + const Pixel::Format pixelFormat, + TextAbstraction::FontClient::GlyphBufferData& data, + unsigned char* buffer, + const int rgbaCase, + const double glyphX, + const double glyphY, + const int strideWidth, + const Vector4& color, + const bool doBlendWithTextColor) { // Select the cropped source image area to copy into the surface buffer unsigned int glyphUintX = 0u; unsigned int glyphUintY = 0u; - unsigned int srcWidth = data.width; - unsigned int srcHeight = data.height; - unsigned int xSrcIndex = 0u; - unsigned int ySrcIndex = 0u; - if( glyphX < 0.f ) + unsigned int srcWidth = data.width; + unsigned int srcHeight = data.height; + unsigned int xSrcIndex = 0u; + unsigned int ySrcIndex = 0u; + if(glyphX < 0.f) { - xSrcIndex = static_cast( abs( glyphX ) ); + xSrcIndex = static_cast(abs(glyphX)); srcWidth -= xSrcIndex; } else { - glyphUintX = static_cast( glyphX ); + glyphUintX = static_cast(glyphX); } - if( glyphUintX + srcWidth > static_cast( strideWidth ) ) + if(glyphUintX + srcWidth > static_cast(strideWidth)) { - srcWidth -= ( ( glyphUintX + srcWidth ) - strideWidth ); + srcWidth -= ((glyphUintX + srcWidth) - strideWidth); } - if( glyphY - static_cast( srcHeight ) < 0.f ) + if(glyphY - static_cast(srcHeight) < 0.f) { - ySrcIndex = static_cast( abs( glyphY - static_cast( srcHeight ) ) ); + ySrcIndex = static_cast(abs(glyphY - static_cast(srcHeight))); srcHeight -= ySrcIndex; } else { - glyphUintY = static_cast( glyphY - static_cast( srcHeight ) ); + glyphUintY = static_cast(glyphY - static_cast(srcHeight)); } - if( glyphUintY + srcHeight > parameters.height ) + if(glyphUintY + srcHeight > parameters.height) { - srcHeight -= ( ( glyphUintY + srcHeight ) - parameters.height ); + srcHeight -= ((glyphUintY + srcHeight) - parameters.height); } // Calculate the source and destination indices. - const unsigned int srcPixelSize = Pixel::GetBytesPerPixel( data.format ); - const unsigned int dstPixelSize = Pixel::GetBytesPerPixel( pixelFormat ); + const unsigned int srcPixelSize = Pixel::GetBytesPerPixel(data.format); + const unsigned int dstPixelSize = Pixel::GetBytesPerPixel(pixelFormat); - unsigned int srcIndex = srcPixelSize * ( ySrcIndex * srcWidth + xSrcIndex ); - unsigned int dstIndex = dstPixelSize * ( glyphUintY * strideWidth + glyphUintX ); + unsigned int srcIndex = srcPixelSize * (ySrcIndex * srcWidth + xSrcIndex); + unsigned int dstIndex = dstPixelSize * (glyphUintY * strideWidth + glyphUintX); - const unsigned int srcWidthOffset = srcPixelSize * ( data.width - srcWidth ); - const unsigned int dstWidthOffset = dstPixelSize * ( strideWidth - srcWidth ); + const unsigned int srcWidthOffset = srcPixelSize * (data.width - srcWidth); + const unsigned int dstWidthOffset = dstPixelSize * (strideWidth - srcWidth); // Copy the image to the surface - for( unsigned int j = 0; j < srcHeight; ++j ) + for(unsigned int j = 0; j < srcHeight; ++j) { - for( unsigned int i = 0; i < srcWidth; ++i ) + for(unsigned int i = 0; i < srcWidth; ++i) { - switch( rgbaCase ) + switch(rgbaCase) { case 0: // Both the image's buffer and cairo's buffer are A8 { - const unsigned char alpha = *( data.buffer + srcIndex ); - if( alpha != 0u ) + const unsigned char alpha = *(data.buffer + srcIndex); + if(alpha != 0u) { // @todo needs a proper blending! - *( buffer + dstIndex ) = alpha; + *(buffer + dstIndex) = alpha; } break; } case 1: // The image's buffer is A8 and the cairo's buffer is ARGB { - const unsigned char alpha = *( data.buffer + srcIndex ); - if( alpha != 0u ) + const unsigned char alpha = *(data.buffer + srcIndex); + if(alpha != 0u) { // @todo needs a proper blending! - const float srcAlpha = TO_FLOAT * static_cast( alpha ); + const float srcAlpha = TO_FLOAT * static_cast(alpha); // Write the RGBA modulated with the given default color. const float* const colorPtr = color.AsFloat(); - *( buffer + dstIndex + 0u ) = static_cast( TO_UCHAR * colorPtr[0u] * srcAlpha ); - *( buffer + dstIndex + 1u ) = static_cast( TO_UCHAR * colorPtr[1u] * srcAlpha ); - *( buffer + dstIndex + 2u ) = static_cast( TO_UCHAR * colorPtr[2u] * srcAlpha ); - *( buffer + dstIndex + 3u ) = static_cast( TO_UCHAR * colorPtr[3u] * srcAlpha ); + *(buffer + dstIndex + 0u) = static_cast(TO_UCHAR * colorPtr[0u] * srcAlpha); + *(buffer + dstIndex + 1u) = static_cast(TO_UCHAR * colorPtr[1u] * srcAlpha); + *(buffer + dstIndex + 2u) = static_cast(TO_UCHAR * colorPtr[2u] * srcAlpha); + *(buffer + dstIndex + 3u) = static_cast(TO_UCHAR * colorPtr[3u] * srcAlpha); } break; } case 2: // The image's buffer is RGBA and the cairo's buffer is ARGB { const unsigned char alpha = *(data.buffer + srcIndex + 3u); - if( alpha != 0u ) + if(alpha != 0u) { - if( doBlendWithTextColor ) + if(doBlendWithTextColor) { const float* const colorPtr = color.AsFloat(); const float srcAlpha = TO_FLOAT * static_cast(alpha) * colorPtr[3u]; - *(buffer + dstIndex + 0u) = static_cast( static_cast( *(data.buffer + srcIndex + 0u) ) * colorPtr[0u] ); - *(buffer + dstIndex + 1u) = static_cast( static_cast( *(data.buffer + srcIndex + 1u) ) * colorPtr[1u] ); - *(buffer + dstIndex + 2u) = static_cast( static_cast( *(data.buffer + srcIndex + 2u) ) * colorPtr[2u] ); + *(buffer + dstIndex + 0u) = static_cast(static_cast(*(data.buffer + srcIndex + 0u)) * colorPtr[0u]); + *(buffer + dstIndex + 1u) = static_cast(static_cast(*(data.buffer + srcIndex + 1u)) * colorPtr[1u]); + *(buffer + dstIndex + 2u) = static_cast(static_cast(*(data.buffer + srcIndex + 2u)) * colorPtr[2u]); // Write the alpha. - *(buffer + dstIndex + 3u) = static_cast( TO_UCHAR * srcAlpha ); + *(buffer + dstIndex + 3u) = static_cast(TO_UCHAR * srcAlpha); } else { @@ -494,20 +489,20 @@ void CopyImageToSurface( case 3: // The image's buffer is BGRA and the cairo's buffer is ARGB { const unsigned char alpha = *(data.buffer + srcIndex + 3u); - if( alpha != 0u ) + if(alpha != 0u) { - if( doBlendWithTextColor ) + if(doBlendWithTextColor) { const float* const colorPtr = color.AsFloat(); const float srcAlpha = TO_FLOAT * static_cast(alpha) * colorPtr[3u]; - *(buffer + dstIndex + 0u) = static_cast( static_cast( *(data.buffer + srcIndex + 2u) ) * colorPtr[0u] ); - *(buffer + dstIndex + 1u) = static_cast( static_cast( *(data.buffer + srcIndex + 1u) ) * colorPtr[1u] ); - *(buffer + dstIndex + 2u) = static_cast( static_cast( *(data.buffer + srcIndex + 0u) ) * colorPtr[2u] ); + *(buffer + dstIndex + 0u) = static_cast(static_cast(*(data.buffer + srcIndex + 2u)) * colorPtr[0u]); + *(buffer + dstIndex + 1u) = static_cast(static_cast(*(data.buffer + srcIndex + 1u)) * colorPtr[1u]); + *(buffer + dstIndex + 2u) = static_cast(static_cast(*(data.buffer + srcIndex + 0u)) * colorPtr[2u]); // Write the alpha. - *(buffer + dstIndex + 3u) = static_cast( TO_UCHAR * srcAlpha ); + *(buffer + dstIndex + 3u) = static_cast(TO_UCHAR * srcAlpha); } else { @@ -523,7 +518,7 @@ void CopyImageToSurface( } default: { - DALI_ASSERT_ALWAYS( !"Cairo Renderer: The accepted values for this switch case are: 0, 1, 2!" ); + DALI_ASSERT_ALWAYS(!"Cairo Renderer: The accepted values for this switch case are: 0, 1, 2!"); } } // switch srcIndex += srcPixelSize; @@ -545,81 +540,81 @@ void CopyImageToSurface( * @param[in/out] circularTextParameters The circular text parameters */ void RenderGlyphs( - const TextAbstraction::TextRenderer::Parameters& parameters, - const GlyphRun& run, - cairo_glyph_t*& cairoGlyphsBuffer, - cairo_t*& cr, - cairo_t*& circularCr, - const bool isCircularText, - CircularTextParameters& circularTextParameters) + const TextAbstraction::TextRenderer::Parameters& parameters, + const GlyphRun& run, + cairo_glyph_t*& cairoGlyphsBuffer, + cairo_t*& cr, + cairo_t*& circularCr, + const bool isCircularText, + CircularTextParameters& circularTextParameters) { // Sets the color. The color is actually BGRA const Vector4& color = parameters.colors[run.colorIndex]; - cairo_set_source_rgba( cr, - static_cast( color.b ), - static_cast( color.g ), - static_cast( color.r ), - static_cast( color.a ) ); + cairo_set_source_rgba(cr, + static_cast(color.b), + static_cast(color.g), + static_cast(color.r), + static_cast(color.a)); // Create the Cairo's font from the FreeType font. int options = 0; - options = CAIRO_HINT_STYLE_SLIGHT; - std::unique_ptr fontFacePtr( cairo_ft_font_face_create_for_ft_face( run.fontFace, options ), cairo_font_face_destroy ); - cairo_font_face_t* fontFace = fontFacePtr.get(); + options = CAIRO_HINT_STYLE_SLIGHT; + std::unique_ptr fontFacePtr(cairo_ft_font_face_create_for_ft_face(run.fontFace, options), cairo_font_face_destroy); + cairo_font_face_t* fontFace = fontFacePtr.get(); - static const cairo_user_data_key_t key = { 0 }; - cairo_status_t status = cairo_font_face_set_user_data( fontFace, &key, run.fontFace, reinterpret_cast( FT_Done_Face ) ); - if( status ) + static const cairo_user_data_key_t key = {0}; + cairo_status_t status = cairo_font_face_set_user_data(fontFace, &key, run.fontFace, reinterpret_cast(FT_Done_Face)); + if(status) { - cairo_font_face_destroy( fontFace ); + cairo_font_face_destroy(fontFace); } unsigned int ftSynthesizeFlag = 0u; - if( run.isBoldRequired && !( run.fontFace->style_flags & FT_STYLE_FLAG_BOLD ) ) + if(run.isBoldRequired && !(run.fontFace->style_flags & FT_STYLE_FLAG_BOLD)) { ftSynthesizeFlag |= CAIRO_FT_SYNTHESIZE_BOLD; } - cairo_ft_font_face_set_synthesize( fontFace, ftSynthesizeFlag ); + cairo_ft_font_face_set_synthesize(fontFace, ftSynthesizeFlag); - cairo_font_face_reference( fontFace ); + cairo_font_face_reference(fontFace); - const bool synthesizeItalic = ( run.isItalicRequired && !( run.fontFace->style_flags & FT_STYLE_FLAG_ITALIC ) ); + const bool synthesizeItalic = (run.isItalicRequired && !(run.fontFace->style_flags & FT_STYLE_FLAG_ITALIC)); - if( CAIRO_STATUS_SUCCESS != cairo_font_face_status( fontFace ) ) + if(CAIRO_STATUS_SUCCESS != cairo_font_face_status(fontFace)) { - DALI_LOG_ERROR( "Failed to load the Freetype Font\n" ); + DALI_LOG_ERROR("Failed to load the Freetype Font\n"); } // Sets the font. - cairo_set_font_face( isCircularText ? circularCr : cr, fontFace ); + cairo_set_font_face(isCircularText ? circularCr : cr, fontFace); // Sets the size - cairo_set_font_size( isCircularText ? circularCr : cr, run.fontSize ); + cairo_set_font_size(isCircularText ? circularCr : cr, run.fontSize); // Render the glyphs. - if( isCircularText ) + if(isCircularText) { circularTextParameters.synthesizeItalic = synthesizeItalic; const unsigned int glyphJump = circularTextParameters.synthesizeItalic ? 1u : run.numberOfGlyphs; - for( unsigned int index = 0u; index < run.numberOfGlyphs; index += glyphJump ) + for(unsigned int index = 0u; index < run.numberOfGlyphs; index += glyphJump) { // Clears the current path where the text is laid out on a horizontal straight line. - cairo_new_path( circularCr ); - cairo_move_to( circularCr, 0.0, 0.0 ); + cairo_new_path(circularCr); + cairo_move_to(circularCr, 0.0, 0.0); - cairo_glyph_path( circularCr, ( cairoGlyphsBuffer + run.glyphIndex + index ), glyphJump ); + cairo_glyph_path(circularCr, (cairoGlyphsBuffer + run.glyphIndex + index), glyphJump); - WrapToCircularPath( cr, circularCr, circularTextParameters ); - cairo_fill( cr ); + WrapToCircularPath(cr, circularCr, circularTextParameters); + cairo_fill(cr); } } else { - if( synthesizeItalic ) + if(synthesizeItalic) { // Apply a shear transform to synthesize the italics. // For a reason Cairo may trim some glyphs if the CAIRO_FT_SYNTHESIZE_OBLIQUE flag is used. @@ -627,44 +622,47 @@ void RenderGlyphs( // This is to calculate an offset used to compensate the 'translation' done by the shear transform // as it's done for the whole render buffer. double maxY = 0.0; - for( unsigned int index = run.glyphIndex, endIndex = run.glyphIndex + run.numberOfGlyphs; index < endIndex; ++index ) + for(unsigned int index = run.glyphIndex, endIndex = run.glyphIndex + run.numberOfGlyphs; index < endIndex; ++index) { - maxY = std::max( maxY, (*( cairoGlyphsBuffer + index )).y ); + maxY = std::max(maxY, (*(cairoGlyphsBuffer + index)).y); } cairo_matrix_t matrix; - cairo_matrix_init( &matrix, - 1.0, 0.0, - -TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, 1.0, - maxY * TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, 0.0 ); - - cairo_transform( cr, &matrix ); + cairo_matrix_init(&matrix, + 1.0, + 0.0, + -TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, + 1.0, + maxY * TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, + 0.0); + + cairo_transform(cr, &matrix); } - cairo_show_glyphs( cr, ( cairoGlyphsBuffer + run.glyphIndex ), run.numberOfGlyphs ); + cairo_show_glyphs(cr, (cairoGlyphsBuffer + run.glyphIndex), run.numberOfGlyphs); - if( synthesizeItalic ) + if(synthesizeItalic) { // Restore the transform matrix to the identity. cairo_matrix_t matrix; - cairo_matrix_init_identity( &matrix ); - cairo_set_matrix( cr, &matrix ); + cairo_matrix_init_identity(&matrix); + cairo_set_matrix(cr, &matrix); } - cairo_fill( cr ); + cairo_fill(cr); } } } // unnamed namespace -Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Parameters& parameters ) +Devel::PixelBuffer RenderTextCairo(const TextAbstraction::TextRenderer::Parameters& parameters) { const unsigned int numberOfGlyphs = parameters.glyphs.Count(); - if( 0u == numberOfGlyphs ) + if(0u == numberOfGlyphs) { // return a pixel buffer with all pixels set to transparent. - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } // Choose the pixel format to be used. @@ -674,86 +672,86 @@ Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Paramet // // Here in practice Cairo's ARGB32 is like DALi's RGBA8888. // - const bool isDstRgba = TextAbstraction::TextRenderer::Parameters::RGBA8888 == parameters.pixelFormat; - const Pixel::Format pixelFormat = isDstRgba ? Pixel::Format::RGBA8888 : Pixel::Format::A8; + const bool isDstRgba = TextAbstraction::TextRenderer::Parameters::RGBA8888 == parameters.pixelFormat; + const Pixel::Format pixelFormat = isDstRgba ? Pixel::Format::RGBA8888 : Pixel::Format::A8; const cairo_format_t cairoFormat = isDstRgba ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_A8; - const int bpp = Pixel::GetBytesPerPixel( pixelFormat ); - if( 0u == bpp ) + const int bpp = Pixel::GetBytesPerPixel(pixelFormat); + if(0u == bpp) { // return a pixel buffer with all pixels set to transparent. - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } // This function provides a stride value that will respect all alignment requirements of the // accelerated image-rendering code within cairo. - const int stride = cairo_format_stride_for_width( cairoFormat, - static_cast( parameters.width ) ); + const int stride = cairo_format_stride_for_width(cairoFormat, + static_cast(parameters.width)); const int strideWidth = stride / bpp; // Convert from DALi glyphs to Cairo glyphs. std::vector cairoGlyphs; - cairoGlyphs.resize( numberOfGlyphs ); + cairoGlyphs.resize(numberOfGlyphs); cairo_glyph_t* cairoGlyphsBuffer = &cairoGlyphs[0u]; - const GlyphInfo* const daliGlyphsBuffer = parameters.glyphs.Begin(); - const Vector2* const positionsBuffer = parameters.positions.Begin(); - const ColorIndex* const colorIndicesBuffer = ( 0u == parameters.colorIndices.Count() ) ? nullptr : parameters.colorIndices.Begin(); + const GlyphInfo* const daliGlyphsBuffer = parameters.glyphs.Begin(); + const Vector2* const positionsBuffer = parameters.positions.Begin(); + const ColorIndex* const colorIndicesBuffer = (0u == parameters.colorIndices.Count()) ? nullptr : parameters.colorIndices.Begin(); - for( unsigned index = 0u; index < numberOfGlyphs; ++index ) + for(unsigned index = 0u; index < numberOfGlyphs; ++index) { - const GlyphInfo& daliGlyph = *( daliGlyphsBuffer + index ); - const Vector2& position = *( positionsBuffer + index ); - cairo_glyph_t& cairoGlyph = *( cairoGlyphsBuffer + index ); + const GlyphInfo& daliGlyph = *(daliGlyphsBuffer + index); + const Vector2& position = *(positionsBuffer + index); + cairo_glyph_t& cairoGlyph = *(cairoGlyphsBuffer + index); cairoGlyph.index = daliGlyph.index; - cairoGlyph.x = round( position.x ); - cairoGlyph.y = round( position.y ); + cairoGlyph.x = round(position.x); + cairoGlyph.y = round(position.y); } // Retrieve the FreeType fonts needed by Cairo from the font-client. Dali::TextAbstraction::FontClient fontClient = Dali::TextAbstraction::FontClient::Get(); FT_Library ftLibrary; - auto error = FT_Init_FreeType( &ftLibrary ); - if( error ) + auto error = FT_Init_FreeType(&ftLibrary); + if(error) { - DALI_LOG_ERROR( "Error initializing FT library\n" ); + DALI_LOG_ERROR("Error initializing FT library\n"); // return a pixel buffer with all pixels set to transparent. - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } // Vector used to store the FreeType font faces, its size and the run of glyphs that use the font. std::vector glyphRuns; - glyphRuns.reserve( 8u ); + glyphRuns.reserve(8u); - if( ! ConvertSizeForCairo(fontClient, ftLibrary, numberOfGlyphs, daliGlyphsBuffer, colorIndicesBuffer, glyphRuns) ) + if(!ConvertSizeForCairo(fontClient, ftLibrary, numberOfGlyphs, daliGlyphsBuffer, colorIndicesBuffer, glyphRuns)) { // return a pixel buffer with all pixels set to transparent. - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } // Creates the pixel buffer and retrieves the buffer pointer used to create the Cairo's surface. - Devel::PixelBuffer pixelBuffer = Devel::PixelBuffer::New( strideWidth, parameters.height, pixelFormat ); + Devel::PixelBuffer pixelBuffer = Devel::PixelBuffer::New(strideWidth, parameters.height, pixelFormat); - unsigned char* buffer = pixelBuffer.GetBuffer(); + unsigned char* buffer = pixelBuffer.GetBuffer(); const unsigned int bufferSize = stride * parameters.height; - memset( buffer, 0, bufferSize ); + memset(buffer, 0, bufferSize); - std::unique_ptr surfacePtr( cairo_image_surface_create_for_data( buffer, - cairoFormat, - parameters.width, - parameters.height, - stride ), - cairo_surface_destroy ); - cairo_surface_t* surface = surfacePtr.get(); + std::unique_ptr surfacePtr(cairo_image_surface_create_for_data(buffer, + cairoFormat, + parameters.width, + parameters.height, + stride), + cairo_surface_destroy); + cairo_surface_t* surface = surfacePtr.get(); - if( ( nullptr == surface ) || ( CAIRO_STATUS_SUCCESS != cairo_surface_status( surface ) ) ) + if((nullptr == surface) || (CAIRO_STATUS_SUCCESS != cairo_surface_status(surface))) { - DALI_LOG_ERROR( "Failed to create a cairo's surface\n" ); + DALI_LOG_ERROR("Failed to create a cairo's surface\n"); - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } // Whether the text is circular. @@ -768,104 +766,104 @@ Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Paramet // // As the glyphs are laid out first in a straight line they may exceed the // boundaries of the surface in that case cairo ignores them. - std::unique_ptr circularSurfacePtr( nullptr, cairo_surface_destroy ); - cairo_surface_t* circularSurface = nullptr; - if( isCircularText ) + std::unique_ptr circularSurfacePtr(nullptr, cairo_surface_destroy); + cairo_surface_t* circularSurface = nullptr; + if(isCircularText) { - circularSurfacePtr.reset( cairo_surface_create_similar( surface, - CAIRO_CONTENT_ALPHA, - parameters.circularWidth, - parameters.circularHeight ) ); + circularSurfacePtr.reset(cairo_surface_create_similar(surface, + CAIRO_CONTENT_ALPHA, + parameters.circularWidth, + parameters.circularHeight)); circularSurface = circularSurfacePtr.get(); - if( ( nullptr == circularSurface ) || ( CAIRO_STATUS_SUCCESS != cairo_surface_status( circularSurface ) ) ) + if((nullptr == circularSurface) || (CAIRO_STATUS_SUCCESS != cairo_surface_status(circularSurface))) { - DALI_LOG_ERROR( "Failed to create a cairo's circular surface\n" ); + DALI_LOG_ERROR("Failed to create a cairo's circular surface\n"); - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } } - std::unique_ptr crPtr( cairo_create( surface ), cairo_destroy ); - cairo_t* cr = crPtr.get(); + std::unique_ptr crPtr(cairo_create(surface), cairo_destroy); + cairo_t* cr = crPtr.get(); - if( CAIRO_STATUS_SUCCESS != cairo_status( cr ) ) + if(CAIRO_STATUS_SUCCESS != cairo_status(cr)) { - DALI_LOG_ERROR( "Failed to create a cairo context\n" ); + DALI_LOG_ERROR("Failed to create a cairo context\n"); - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } - std::unique_ptr circularCrPtr( nullptr, cairo_destroy ); - cairo_t* circularCr = nullptr; + std::unique_ptr circularCrPtr(nullptr, cairo_destroy); + cairo_t* circularCr = nullptr; - if( isCircularText ) + if(isCircularText) { - circularCrPtr.reset( cairo_create( circularSurface ) ); + circularCrPtr.reset(cairo_create(circularSurface)); circularCr = circularCrPtr.get(); - if( CAIRO_STATUS_SUCCESS != cairo_status( circularCr ) ) + if(CAIRO_STATUS_SUCCESS != cairo_status(circularCr)) { - DALI_LOG_ERROR( "Failed to create a cairo context\n" ); + DALI_LOG_ERROR("Failed to create a cairo context\n"); - return CreateVoidPixelBuffer( parameters ); + return CreateVoidPixelBuffer(parameters); } } CircularTextParameters circularTextParameters; // Render the glyphs. - if( isCircularText ) + if(isCircularText) { // Set the parameters. - circularTextParameters.isClockwise = ( TextAbstraction::TextRenderer::Parameters::CLOCKWISE == parameters.circularLayout ); + circularTextParameters.isClockwise = (TextAbstraction::TextRenderer::Parameters::CLOCKWISE == parameters.circularLayout); - circularTextParameters.centerX = static_cast( parameters.centerX ); - circularTextParameters.centerY = static_cast( parameters.centerY ); - circularTextParameters.radius = static_cast( parameters.radius ); - circularTextParameters.invRadius = 1.0 / circularTextParameters.radius; + circularTextParameters.centerX = static_cast(parameters.centerX); + circularTextParameters.centerY = static_cast(parameters.centerY); + circularTextParameters.radius = static_cast(parameters.radius); + circularTextParameters.invRadius = 1.0 / circularTextParameters.radius; circularTextParameters.beginAngle = -parameters.beginAngle + Dali::Math::PI_2; } - cairo_move_to( cr, 0.0, 0.0 ); + cairo_move_to(cr, 0.0, 0.0); - for( const auto& run: glyphRuns ) + for(const auto& run : glyphRuns) { const bool isEmoji = parameters.isEmoji[run.glyphIndex]; - if( isEmoji || ( nullptr == run.fontFace ) ) + if(isEmoji || (nullptr == run.fontFace)) { // Retrieve the color for the glyph. const Vector4& color = parameters.colors[run.colorIndex]; const unsigned int lastGlyphIndex = run.glyphIndex + run.numberOfGlyphs; - for( unsigned int index = run.glyphIndex; index < lastGlyphIndex; ++index ) + for(unsigned int index = run.glyphIndex; index < lastGlyphIndex; ++index) { // Whether it's a bitmap font. - const bool doBlendWithTextColor = !isEmoji && ( ColorBlendingMode::MULTIPLY == parameters.blendingMode[index] ); + const bool doBlendWithTextColor = !isEmoji && (ColorBlendingMode::MULTIPLY == parameters.blendingMode[index]); // Check if there is an embedded image or a bitmap font image. const GlyphIndex glyphFontIndex = daliGlyphsBuffer[index].index; - if( 0u != glyphFontIndex ) + if(0u != glyphFontIndex) { // The embedded image could be A8, RGBA8888 or BGRA8888. // // If the embedded image is RGBA8888 or BGRA8888 then the cairo's buffer is ARGB32. It's needed to convert from RGBA or BGRA to ARGB. // If the embedded image is A8 it's needed to check if the cairo's buffer is A8 or ARGB32 and do the conversion if needed. - const cairo_glyph_t& glyph = *( cairoGlyphsBuffer + index ); + const cairo_glyph_t& glyph = *(cairoGlyphsBuffer + index); // Retrieve the image TextAbstraction::FontClient::GlyphBufferData data; - std::unique_ptr glyphBufferPtr( new GlyphBuffer( data, GlyphBuffer::DELETE ) ); - if( isEmoji ) + std::unique_ptr glyphBufferPtr(new GlyphBuffer(data, GlyphBuffer::DELETE)); + if(isEmoji) { - data.width = parameters.glyphs[run.glyphIndex].width; + data.width = parameters.glyphs[run.glyphIndex].width; data.height = parameters.glyphs[run.glyphIndex].height; } - fontClient.CreateBitmap( run.fontId, glyphFontIndex, false, false, data, 0u ); + fontClient.CreateBitmap(run.fontId, glyphFontIndex, false, false, data, 0u); - if( nullptr == data.buffer ) + if(nullptr == data.buffer) { // nothing else to do if there is no image. continue; @@ -875,68 +873,67 @@ Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Paramet double glyphX = glyph.x; double glyphY = glyph.y; - if( isCircularText ) + if(isCircularText) { // Center of the bitmap. - const double halfWidth = 0.5 * static_cast( data.width ); - const double halfHeight = 0.5 * static_cast( data.height ); + const double halfWidth = 0.5 * static_cast(data.width); + const double halfHeight = 0.5 * static_cast(data.height); double centerX = glyph.x + halfWidth; double centerY = glyph.y - halfHeight; - float radians = circularTextParameters.beginAngle + ( circularTextParameters.isClockwise ? -1.f : 1.f ) * ( Dali::Math::PI_2 + circularTextParameters.invRadius * centerX ); - radians = fmod( radians, TWO_PI ); - radians += ( radians < 0.f ) ? TWO_PI : 0.f; - - TransformToArc( circularTextParameters, centerX, centerY ); - - uint8_t* pixelsOut = nullptr; - unsigned int widthOut = data.width; - unsigned int heightOut = data.height; - const unsigned int pixelSize = Pixel::GetBytesPerPixel( data.format ); - - Dali::Internal::Platform::RotateByShear( data.buffer, - data.width, - data.height, - pixelSize, - radians, - pixelsOut, - widthOut, - heightOut ); - if( nullptr != pixelsOut ) + float radians = circularTextParameters.beginAngle + (circularTextParameters.isClockwise ? -1.f : 1.f) * (Dali::Math::PI_2 + circularTextParameters.invRadius * centerX); + radians = fmod(radians, TWO_PI); + radians += (radians < 0.f) ? TWO_PI : 0.f; + + TransformToArc(circularTextParameters, centerX, centerY); + + uint8_t* pixelsOut = nullptr; + unsigned int widthOut = data.width; + unsigned int heightOut = data.height; + const unsigned int pixelSize = Pixel::GetBytesPerPixel(data.format); + + Dali::Internal::Platform::RotateByShear(data.buffer, + data.width, + data.height, + pixelSize, + radians, + pixelsOut, + widthOut, + heightOut); + if(nullptr != pixelsOut) { delete[] data.buffer; - data.buffer = pixelsOut; + data.buffer = pixelsOut; glyphBufferPtr.get()->type = GlyphBuffer::FREE; - data.width = widthOut; - data.height = heightOut; + data.width = widthOut; + data.height = heightOut; } - glyphX = centerX - 0.5 * static_cast( data.width ); - glyphY = centerY + 0.5 * static_cast( data.height ); + glyphX = centerX - 0.5 * static_cast(data.width); + glyphY = centerY + 0.5 * static_cast(data.height); } - - if( ( Pixel::A8 != data.format ) && - ( Pixel::L8 != data.format ) && - ( Pixel::RGBA8888 != data.format ) && - ( Pixel::BGRA8888 != data.format ) ) + if((Pixel::A8 != data.format) && + (Pixel::L8 != data.format) && + (Pixel::RGBA8888 != data.format) && + (Pixel::BGRA8888 != data.format)) { - DALI_LOG_ERROR( " Cairo Renderer: The valid pixel format for embedded items are A8 or RGBA8888\n" ); + DALI_LOG_ERROR(" Cairo Renderer: The valid pixel format for embedded items are A8 or RGBA8888\n"); continue; } // Check if the item is out of the buffer. - if( ( glyphX + static_cast( data.width ) < 0.f ) || - ( glyphX > static_cast( strideWidth ) ) || - ( glyphY < 0.f ) || - ( glyphY - static_cast( data.height ) > static_cast( parameters.height ) ) ) + if((glyphX + static_cast(data.width) < 0.f) || + (glyphX > static_cast(strideWidth)) || + (glyphY < 0.f) || + (glyphY - static_cast(data.height) > static_cast(parameters.height))) { // The embedded item is completely out of the buffer. continue; } - const bool isSrcA = ( Pixel::A8 == data.format ) || ( Pixel::L8 == data.format ); + const bool isSrcA = (Pixel::A8 == data.format) || (Pixel::L8 == data.format); const bool isSrcRgba = Pixel::RGBA8888 == data.format; const bool isSrcBgra = Pixel::BGRA8888 == data.format; @@ -945,21 +942,21 @@ Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Paramet // 2 -> image is RGBA and cairo buffer is ARGB // 3 -> image is BGRA and cairo buffer is ARGB int rgbaCase = 0; - if( isSrcA && isDstRgba ) + if(isSrcA && isDstRgba) { rgbaCase = 1; } - else if( isSrcRgba && isDstRgba ) + else if(isSrcRgba && isDstRgba) { rgbaCase = 2; } - else if( isSrcBgra && isDstRgba ) + else if(isSrcBgra && isDstRgba) { rgbaCase = 3; } - else if( ( isSrcRgba || isSrcBgra ) && !isDstRgba ) + else if((isSrcRgba || isSrcBgra) && !isDstRgba) { - DALI_LOG_ERROR( "Cairo Renderer: The embedded image is RGBA or BGRA and the Cairo's buffer has been creates with A8 format!\n" ); + DALI_LOG_ERROR("Cairo Renderer: The embedded image is RGBA or BGRA and the Cairo's buffer has been creates with A8 format!\n"); continue; } diff --git a/dali/internal/text/text-abstraction/cairo-renderer.h b/dali/internal/text/text-abstraction/cairo-renderer.h old mode 100755 new mode 100644 index 4b6595f..caefff9 --- a/dali/internal/text/text-abstraction/cairo-renderer.h +++ b/dali/internal/text/text-abstraction/cairo-renderer.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_CAIRO_RENDERER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,8 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { /** @@ -34,7 +32,7 @@ namespace Internal * * @see Dali::TextAbstraction::TextRenderer. */ -Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Parameters& parameters ); +Devel::PixelBuffer RenderTextCairo(const TextAbstraction::TextRenderer::Parameters& parameters); } // namespace Internal @@ -43,4 +41,3 @@ Devel::PixelBuffer RenderTextCairo( const TextAbstraction::TextRenderer::Paramet } // namespace Dali #endif // DALI_INTERNAL_TEXT_ABSTRACTION_CAIRO_RENDERER_H - diff --git a/dali/internal/text/text-abstraction/font-client-helper.cpp b/dali/internal/text/text-abstraction/font-client-helper.cpp index c6dec8d..b5e4b91 100644 --- a/dali/internal/text/text-abstraction/font-client-helper.cpp +++ b/dali/internal/text/text-abstraction/font-client-helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,51 +27,48 @@ namespace #if defined(DEBUG_ENABLED) Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT_VALUE_TO_INDEX"); #endif -} +} // namespace namespace Dali { - namespace TextAbstraction { - namespace Internal { - -int ValueToIndex( int value, const int* const table, unsigned int maxIndex ) +int ValueToIndex(int value, const int* const table, unsigned int maxIndex) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->FontClient::Plugin::ValueToIndex value(%d)\n", value); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->FontClient::Plugin::ValueToIndex value(%d)\n", value); - if( NULL == table ) + if(NULL == table) { // Return an invalid index if there is no table. return -1; } - if( value <= table[0] ) + if(value <= table[0]) { return 0; } - if( value >= table[maxIndex] ) + if(value >= table[maxIndex]) { return maxIndex; } - for( unsigned int index = 0u; index < maxIndex; ++index ) + for(unsigned int index = 0u; index < maxIndex; ++index) { - const int v1 = table[index]; + const int v1 = table[index]; const unsigned int indexPlus = index + 1u; - const int v2 = table[indexPlus]; - if( ( v1 < value ) && ( value <= v2 ) ) + const int v2 = table[indexPlus]; + if((v1 < value) && (value <= v2)) { - const int result = ( ( v1 > 0 ) && ( ( value - v1 ) < ( v2 - value ) ) ) ? index : indexPlus; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex result(%d)\n", result ); + const int result = ((v1 > 0) && ((value - v1) < (v2 - value))) ? index : indexPlus; + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex result(%d)\n", result); return result; } } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex exit 0 <-- \n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FontClient::Plugin::ValueToIndex exit 0 <-- \n"); return 0; } diff --git a/dali/internal/text/text-abstraction/font-client-helper.h b/dali/internal/text/text-abstraction/font-client-helper.h index 91071f7..6916ae6 100644 --- a/dali/internal/text/text-abstraction/font-client-helper.h +++ b/dali/internal/text/text-abstraction/font-client-helper.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_HELPER_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * @brief Retrieves a table index for a given value. * @@ -36,12 +33,12 @@ namespace Internal * * @return The index to the closest available value */ -int ValueToIndex( int value, const int* const table, unsigned int maxIndex ); +int ValueToIndex(int value, const int* const table, unsigned int maxIndex); -} // Internal +} // namespace Internal -} // TextAbstraction +} // namespace TextAbstraction -} // Dali +} // namespace Dali #endif // DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_HELPER_H diff --git a/dali/internal/text/text-abstraction/font-client-impl.cpp b/dali/internal/text/text-abstraction/font-client-impl.cpp old mode 100755 new mode 100644 index eec3695..3f3bedb --- a/dali/internal/text/text-abstraction/font-client-impl.cpp +++ b/dali/internal/text/text-abstraction/font-client-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,19 +31,16 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - -Dali::TextAbstraction::FontClient FontClient::gPreInitializedFontClient( NULL ); +Dali::TextAbstraction::FontClient FontClient::gPreInitializedFontClient(NULL); FontClient::FontClient() -: mPlugin( nullptr ), - mDpiHorizontal( 0 ), - mDpiVertical( 0 ) +: mPlugin(nullptr), + mDpiHorizontal(0), + mDpiVertical(0) { } @@ -56,30 +53,30 @@ Dali::TextAbstraction::FontClient FontClient::Get() { Dali::TextAbstraction::FontClient fontClientHandle; - Dali::SingletonService service( SingletonService::Get() ); - if ( service ) + Dali::SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( Dali::TextAbstraction::FontClient ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::TextAbstraction::FontClient)); if(handle) { // If so, downcast the handle - FontClient* impl = dynamic_cast< Dali::TextAbstraction::Internal::FontClient* >( handle.GetObjectPtr() ); - fontClientHandle = Dali::TextAbstraction::FontClient( impl ); + FontClient* impl = dynamic_cast(handle.GetObjectPtr()); + fontClientHandle = Dali::TextAbstraction::FontClient(impl); } else // create and register the object { - if( gPreInitializedFontClient ) + if(gPreInitializedFontClient) { fontClientHandle = gPreInitializedFontClient; gPreInitializedFontClient.Reset(); // No longer needed } else { - fontClientHandle = Dali::TextAbstraction::FontClient( new FontClient ); + fontClientHandle = Dali::TextAbstraction::FontClient(new FontClient); } - service.Register( typeid( fontClientHandle ), fontClientHandle ); + service.Register(typeid(fontClientHandle), fontClientHandle); } } @@ -88,48 +85,47 @@ Dali::TextAbstraction::FontClient FontClient::Get() Dali::TextAbstraction::FontClient FontClient::PreInitialize() { - gPreInitializedFontClient = Dali::TextAbstraction::FontClient( new FontClient ); + gPreInitializedFontClient = Dali::TextAbstraction::FontClient(new FontClient); // Make DefaultFontDescription cached Dali::TextAbstraction::FontDescription defaultFontDescription; - gPreInitializedFontClient.GetDefaultPlatformFontDescription( defaultFontDescription ); + gPreInitializedFontClient.GetDefaultPlatformFontDescription(defaultFontDescription); return gPreInitializedFontClient; } void FontClient::ClearCache() { - if( mPlugin ) + if(mPlugin) { mPlugin->ClearCache(); } } - -void FontClient::SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi ) +void FontClient::SetDpi(unsigned int horizontalDpi, unsigned int verticalDpi) { mDpiHorizontal = horizontalDpi; - mDpiVertical = verticalDpi; + mDpiVertical = verticalDpi; // Allow DPI to be set without loading plugin - if( mPlugin ) + if(mPlugin) { - mPlugin->SetDpi( horizontalDpi, verticalDpi ); + mPlugin->SetDpi(horizontalDpi, verticalDpi); } } -void FontClient::GetDpi( unsigned int& horizontalDpi, unsigned int& verticalDpi ) +void FontClient::GetDpi(unsigned int& horizontalDpi, unsigned int& verticalDpi) { horizontalDpi = mDpiHorizontal; - verticalDpi = mDpiVertical; + verticalDpi = mDpiVertical; } int FontClient::GetDefaultFontSize() { - int fontSize( -1 ); + int fontSize(-1); #if !(defined(DALI_PROFILE_UBUNTU) || defined(ANDROID) || defined(WIN32) || defined(__APPLE__)) - vconf_get_int( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, &fontSize ); + vconf_get_int(VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, &fontSize); #endif return fontSize; @@ -142,227 +138,227 @@ void FontClient::ResetSystemDefaults() mPlugin->ResetSystemDefaults(); } -void FontClient::GetDefaultFonts( FontList& defaultFonts ) +void FontClient::GetDefaultFonts(FontList& defaultFonts) { CreatePlugin(); - mPlugin->GetDefaultFonts( defaultFonts ); + mPlugin->GetDefaultFonts(defaultFonts); } -void FontClient::GetDefaultPlatformFontDescription( FontDescription& fontDescription ) +void FontClient::GetDefaultPlatformFontDescription(FontDescription& fontDescription) { CreatePlugin(); - mPlugin->GetDefaultPlatformFontDescription( fontDescription ); + mPlugin->GetDefaultPlatformFontDescription(fontDescription); } -void FontClient::GetDescription( FontId id, FontDescription& fontDescription ) +void FontClient::GetDescription(FontId id, FontDescription& fontDescription) { CreatePlugin(); - mPlugin->GetDescription( id, fontDescription ); + mPlugin->GetDescription(id, fontDescription); } -PointSize26Dot6 FontClient::GetPointSize( FontId id ) +PointSize26Dot6 FontClient::GetPointSize(FontId id) { CreatePlugin(); - return mPlugin->GetPointSize( id ); + return mPlugin->GetPointSize(id); } -bool FontClient::IsCharacterSupportedByFont( FontId fontId, Character character ) +bool FontClient::IsCharacterSupportedByFont(FontId fontId, Character character) { CreatePlugin(); - return mPlugin->IsCharacterSupportedByFont( fontId, character ); + return mPlugin->IsCharacterSupportedByFont(fontId, character); } -void FontClient::GetSystemFonts( FontList& systemFonts ) +void FontClient::GetSystemFonts(FontList& systemFonts) { CreatePlugin(); - mPlugin->GetSystemFonts( systemFonts ); + mPlugin->GetSystemFonts(systemFonts); } -FontId FontClient::FindDefaultFont( Character charcode, - PointSize26Dot6 requestedPointSize, - bool preferColor ) +FontId FontClient::FindDefaultFont(Character charcode, + PointSize26Dot6 requestedPointSize, + bool preferColor) { CreatePlugin(); - return mPlugin->FindDefaultFont( charcode, - requestedPointSize, - preferColor ); + return mPlugin->FindDefaultFont(charcode, + requestedPointSize, + preferColor); } -FontId FontClient::FindFallbackFont( Character charcode, - const FontDescription& preferredFontDescription, - PointSize26Dot6 requestedPointSize, - bool preferColor ) +FontId FontClient::FindFallbackFont(Character charcode, + const FontDescription& preferredFontDescription, + PointSize26Dot6 requestedPointSize, + bool preferColor) { CreatePlugin(); - return mPlugin->FindFallbackFont( charcode, - preferredFontDescription, - requestedPointSize, - preferColor ); + return mPlugin->FindFallbackFont(charcode, + preferredFontDescription, + requestedPointSize, + preferColor); } -bool FontClient::IsScalable( const FontPath& path ) +bool FontClient::IsScalable(const FontPath& path) { CreatePlugin(); - return mPlugin->IsScalable( path ); + return mPlugin->IsScalable(path); } -bool FontClient::IsScalable( const FontDescription& fontDescription ) +bool FontClient::IsScalable(const FontDescription& fontDescription) { CreatePlugin(); - return mPlugin->IsScalable( fontDescription ); + return mPlugin->IsScalable(fontDescription); } -void FontClient::GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes ) +void FontClient::GetFixedSizes(const FontPath& path, Dali::Vector& sizes) { CreatePlugin(); - mPlugin->GetFixedSizes( path, sizes ); + mPlugin->GetFixedSizes(path, sizes); } -void FontClient::GetFixedSizes( const FontDescription& fontDescription, - Dali::Vector< PointSize26Dot6 >& sizes ) +void FontClient::GetFixedSizes(const FontDescription& fontDescription, + Dali::Vector& sizes) { CreatePlugin(); - mPlugin->GetFixedSizes( fontDescription, sizes ); + mPlugin->GetFixedSizes(fontDescription, sizes); } -bool FontClient::HasItalicStyle( FontId fontId ) const +bool FontClient::HasItalicStyle(FontId fontId) const { - if( !mPlugin ) + if(!mPlugin) { return false; } - return mPlugin->HasItalicStyle( fontId ); + return mPlugin->HasItalicStyle(fontId); } -FontId FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex ) +FontId FontClient::GetFontId(const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex) { CreatePlugin(); - return mPlugin->GetFontId( path, - requestedPointSize, - faceIndex, - true ); + return mPlugin->GetFontId(path, + requestedPointSize, + faceIndex, + true); } -FontId FontClient::GetFontId( const FontDescription& fontDescription, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex ) +FontId FontClient::GetFontId(const FontDescription& fontDescription, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex) { CreatePlugin(); - return mPlugin->GetFontId( fontDescription, - requestedPointSize, - faceIndex ); + return mPlugin->GetFontId(fontDescription, + requestedPointSize, + faceIndex); } -FontId FontClient::GetFontId( const BitmapFont& bitmapFont ) +FontId FontClient::GetFontId(const BitmapFont& bitmapFont) { CreatePlugin(); - return mPlugin->GetFontId( bitmapFont ); + return mPlugin->GetFontId(bitmapFont); } -void FontClient::GetFontMetrics( FontId fontId, FontMetrics& metrics ) +void FontClient::GetFontMetrics(FontId fontId, FontMetrics& metrics) { CreatePlugin(); - mPlugin->GetFontMetrics( fontId, metrics ); + mPlugin->GetFontMetrics(fontId, metrics); } -GlyphIndex FontClient::GetGlyphIndex( FontId fontId, Character charcode ) +GlyphIndex FontClient::GetGlyphIndex(FontId fontId, Character charcode) { CreatePlugin(); - return mPlugin->GetGlyphIndex( fontId, charcode ); + return mPlugin->GetGlyphIndex(fontId, charcode); } -bool FontClient::GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal ) +bool FontClient::GetGlyphMetrics(GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal) { CreatePlugin(); - return mPlugin->GetGlyphMetrics( array, size, type, horizontal ); + return mPlugin->GetGlyphMetrics(array, size, type, horizontal); } -void FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth ) +void FontClient::CreateBitmap(FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth) { CreatePlugin(); - mPlugin->CreateBitmap( fontId, glyphIndex, isItalicRequired, isBoldRequired, data, outlineWidth ); + mPlugin->CreateBitmap(fontId, glyphIndex, isItalicRequired, isBoldRequired, data, outlineWidth); } -PixelData FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth ) +PixelData FontClient::CreateBitmap(FontId fontId, GlyphIndex glyphIndex, int outlineWidth) { CreatePlugin(); - return mPlugin->CreateBitmap( fontId, glyphIndex, outlineWidth ); + return mPlugin->CreateBitmap(fontId, glyphIndex, outlineWidth); } -void FontClient::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight ) +void FontClient::CreateVectorBlob(FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight) { CreatePlugin(); - mPlugin->CreateVectorBlob( fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight ); + mPlugin->CreateVectorBlob(fontId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight); } -const GlyphInfo& FontClient::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize ) +const GlyphInfo& FontClient::GetEllipsisGlyph(PointSize26Dot6 requestedPointSize) { CreatePlugin(); - return mPlugin->GetEllipsisGlyph( requestedPointSize ); + return mPlugin->GetEllipsisGlyph(requestedPointSize); } -bool FontClient::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex ) +bool FontClient::IsColorGlyph(FontId fontId, GlyphIndex glyphIndex) { CreatePlugin(); - return mPlugin->IsColorGlyph( fontId, glyphIndex ); + return mPlugin->IsColorGlyph(fontId, glyphIndex); } GlyphIndex FontClient::CreateEmbeddedItem(const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat) { CreatePlugin(); - return mPlugin->CreateEmbeddedItem( description, pixelFormat ); + return mPlugin->CreateEmbeddedItem(description, pixelFormat); } -FT_FaceRec_* FontClient::GetFreetypeFace( FontId fontId ) +FT_FaceRec_* FontClient::GetFreetypeFace(FontId fontId) { CreatePlugin(); - return mPlugin->GetFreetypeFace( fontId ); + return mPlugin->GetFreetypeFace(fontId); } -FontDescription::Type FontClient::GetFontType( FontId fontId ) +FontDescription::Type FontClient::GetFontType(FontId fontId) { CreatePlugin(); - return mPlugin->GetFontType( fontId ); + return mPlugin->GetFontType(fontId); } -bool FontClient::AddCustomFontDirectory( const FontPath& path ) +bool FontClient::AddCustomFontDirectory(const FontPath& path) { CreatePlugin(); - return mPlugin->AddCustomFontDirectory( path ); + return mPlugin->AddCustomFontDirectory(path); } void FontClient::CreatePlugin() { - if( !mPlugin ) + if(!mPlugin) { - mPlugin = new Plugin( mDpiHorizontal, mDpiVertical ); + mPlugin = new Plugin(mDpiHorizontal, mDpiVertical); } } diff --git a/dali/internal/text/text-abstraction/font-client-impl.h b/dali/internal/text/text-abstraction/font-client-impl.h old mode 100755 new mode 100644 index def0799..de6b99f --- a/dali/internal/text/text-abstraction/font-client-impl.h +++ b/dali/internal/text/text-abstraction/font-client-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,25 +24,20 @@ // INTERNAL INCLUDES #include - struct FT_FaceRec_; namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * Implementation of the FontClient */ class FontClient : public BaseObject { public: - /** * Constructor */ @@ -73,12 +68,12 @@ public: /** * @copydoc Dali::TextAbstraction::FontClient::SetDpi() */ - void SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi ); + void SetDpi(unsigned int horizontalDpi, unsigned int verticalDpi); /** * @copydoc Dali::TextAbstraction::FontClient::GetDpi() */ - void GetDpi( unsigned int& horizontalDpi, unsigned int& verticalDpi ); + void GetDpi(unsigned int& horizontalDpi, unsigned int& verticalDpi); /** * @copydoc Dali::TextAbstraction::FontClient::GetDefaultFontSize() @@ -93,135 +88,135 @@ public: /** * @copydoc Dali::TextAbstraction::FontClient::GetDefaultFonts() */ - void GetDefaultFonts( FontList& defaultFonts ); + void GetDefaultFonts(FontList& defaultFonts); /** * @copydoc Dali::TextAbstraction::FontClient::GetDefaultPlatformFontDescription() */ - void GetDefaultPlatformFontDescription( FontDescription& fontDescription ); + void GetDefaultPlatformFontDescription(FontDescription& fontDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetSystemFonts() */ - void GetSystemFonts( FontList& systemFonts ); + void GetSystemFonts(FontList& systemFonts); /** * @copydoc Dali::TextAbstraction::FontClient::GetDescription() */ - void GetDescription( FontId id, FontDescription& fontDescription ); + void GetDescription(FontId id, FontDescription& fontDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetPointSize() */ - PointSize26Dot6 GetPointSize( FontId id ); + PointSize26Dot6 GetPointSize(FontId id); /** * @copydoc Dali::TextAbstraction::FontClient::IsCharacterSupportedByFont() */ - bool IsCharacterSupportedByFont( FontId fontId, Character character ); + bool IsCharacterSupportedByFont(FontId fontId, Character character); /** * @copydoc Dali::TextAbstraction::FontClient::FindDefaultFont() */ - FontId FindDefaultFont( Character charcode, - PointSize26Dot6 requestedPointSize, - bool preferColor ); + FontId FindDefaultFont(Character charcode, + PointSize26Dot6 requestedPointSize, + bool preferColor); /** * @copydoc Dali::TextAbstraction::FontClient::FindFallbackFont() */ - FontId FindFallbackFont( Character charcode, - const FontDescription& preferredFontDescription, - PointSize26Dot6 requestedPointSize, - bool preferColor ); + FontId FindFallbackFont(Character charcode, + const FontDescription& preferredFontDescription, + PointSize26Dot6 requestedPointSize, + bool preferColor); /** * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex ) */ - FontId GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex ); + FontId GetFontId(const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex); /** * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const FontDescription& fontDescription, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex ) */ - FontId GetFontId( const FontDescription& fontDescription, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex ); + FontId GetFontId(const FontDescription& fontDescription, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex); /** * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const BitmapFont& bitmapFont ) */ - FontId GetFontId( const BitmapFont& bitmapFont ); + FontId GetFontId(const BitmapFont& bitmapFont); /** * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontPath& path ) */ - bool IsScalable( const FontPath& path ); + bool IsScalable(const FontPath& path); /** * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontDescription& fontDescription ) */ - bool IsScalable( const FontDescription& fontDescription ); + bool IsScalable(const FontDescription& fontDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes ) */ - void GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes ); + void GetFixedSizes(const FontPath& path, Dali::Vector& sizes); /** * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes() */ - void GetFixedSizes( const FontDescription& fontDescription, - Dali::Vector< PointSize26Dot6 >& sizes ); + void GetFixedSizes(const FontDescription& fontDescription, + Dali::Vector& sizes); /** * @copydoc Dali::TextAbstraction::FontClient::HasItalicStyle() */ - bool HasItalicStyle( FontId fontId ) const; + bool HasItalicStyle(FontId fontId) const; /** * @copydoc Dali::TextAbstraction::FontClient::GetFontMetrics() */ - void GetFontMetrics( FontId fontId, FontMetrics& metrics ); + void GetFontMetrics(FontId fontId, FontMetrics& metrics); /** * @copydoc Dali::TextAbstraction::FontClient::GetGlyphIndex() */ - GlyphIndex GetGlyphIndex( FontId fontId, Character charcode ); + GlyphIndex GetGlyphIndex(FontId fontId, Character charcode); /** * @copydoc Dali::TextAbstraction::FontClient::GetGlyphMetrics() */ - bool GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal ); + bool GetGlyphMetrics(GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal); /** * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth ) */ - void CreateBitmap( FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth ); + void CreateBitmap(FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth); /** * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth ) */ - PixelData CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth ); + PixelData CreateBitmap(FontId fontId, GlyphIndex glyphIndex, int outlineWidth); /** * @copydoc Dali::TextAbstraction::FontClient::CreateVectorBlob() */ - void CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight ); + void CreateVectorBlob(FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight); /** * @copydoc Dali::TextAbstraction::FontClient::GetEllipsisGlyph() */ - const GlyphInfo& GetEllipsisGlyph( PointSize26Dot6 requestedPointSize ); + const GlyphInfo& GetEllipsisGlyph(PointSize26Dot6 requestedPointSize); /** * @copydoc Dali::TextAbstraction::FontClient::IsColorGlyph() */ - bool IsColorGlyph( FontId fontId, GlyphIndex glyphIndex ); + bool IsColorGlyph(FontId fontId, GlyphIndex glyphIndex); /** * @copydoc Dali::TextAbstraction::FontClient::CreateEmbeddedItem() */ - GlyphIndex CreateEmbeddedItem( const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat ); + GlyphIndex CreateEmbeddedItem(const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat); /** * @brief Retrieves the pointer to the FreeType Font Face for the given @p fontId. @@ -230,7 +225,7 @@ public: * * @return The pointer to the FreeType Font Face. */ - FT_FaceRec_* GetFreetypeFace( FontId fontId ); + FT_FaceRec_* GetFreetypeFace(FontId fontId); /** * @brief Retrieves the type of font. @@ -239,28 +234,26 @@ public: * * @return FACE_FONT if the font has been loaded by FreeType, BITMAP_FONT if it's a font that has been loaded from images or INVALID if it's a non valid font. */ - FontDescription::Type GetFontType( FontId fontId ); + FontDescription::Type GetFontType(FontId fontId); /** * @copydoc Dali::TextAbstraction::FontClient::AddCustomFontDirectory() */ - bool AddCustomFontDirectory( const FontPath& path ); + bool AddCustomFontDirectory(const FontPath& path); private: - /** * Helper for lazy initialization. */ void CreatePlugin(); // Undefined copy constructor. - FontClient( const FontClient& ); + FontClient(const FontClient&); // Undefined assignment constructor. - FontClient& operator=( const FontClient& ); + FontClient& operator=(const FontClient&); private: - struct Plugin; Plugin* mPlugin; @@ -276,14 +269,14 @@ private: inline static Internal::FontClient& GetImplementation(FontClient& fontClient) { - DALI_ASSERT_ALWAYS( fontClient && "fontClient handle is empty" ); + DALI_ASSERT_ALWAYS(fontClient && "fontClient handle is empty"); BaseObject& handle = fontClient.GetBaseObject(); return static_cast(handle); } inline static const Internal::FontClient& GetImplementation(const FontClient& fontClient) { - DALI_ASSERT_ALWAYS( fontClient && "fontClient handle is empty" ); + DALI_ASSERT_ALWAYS(fontClient && "fontClient handle is empty"); const BaseObject& handle = fontClient.GetBaseObject(); return static_cast(handle); } diff --git a/dali/internal/text/text-abstraction/font-client-plugin-impl.cpp b/dali/internal/text/text-abstraction/font-client-plugin-impl.cpp old mode 100755 new mode 100644 index 5adf76f..5bf652c --- a/dali/internal/text/text-abstraction/font-client-plugin-impl.cpp +++ b/dali/internal/text/text-abstraction/font-client-plugin-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,14 +21,14 @@ // INTERNAL INCLUDES #include -#include -#include +#include #include #include -#include -#include #include -#include +#include +#include +#include +#include // EXTERNAL INCLUDES #include @@ -37,7 +37,6 @@ namespace { - #if defined(DEBUG_ENABLED) Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT"); #endif @@ -45,13 +44,13 @@ Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New /** * Conversion from Fractional26.6 to float */ -const float FROM_266 = 1.0f / 64.0f; +const float FROM_266 = 1.0f / 64.0f; const float POINTS_PER_INCH = 72.f; -const std::string DEFAULT_FONT_FAMILY_NAME( "Tizen" ); -const int DEFAULT_FONT_WIDTH = 100; // normal -const int DEFAULT_FONT_WEIGHT = 80; // normal -const int DEFAULT_FONT_SLANT = 0; // normal +const std::string DEFAULT_FONT_FAMILY_NAME("Tizen"); +const int DEFAULT_FONT_WIDTH = 100; // normal +const int DEFAULT_FONT_WEIGHT = 80; // normal +const int DEFAULT_FONT_SLANT = 0; // normal const uint32_t ELLIPSIS_CHARACTER = 0x2026; @@ -67,8 +66,8 @@ const uint32_t ELLIPSIS_CHARACTER = 0x2026; // EXPANDED 125 // EXTRA_EXPANDED 150 // ULTRA_EXPANDED 200 -const int FONT_WIDTH_TYPE_TO_INT[] = { -1, 50, 63, 75, 87, 100, 113, 125, 150, 200 }; -const unsigned int NUM_FONT_WIDTH_TYPE = sizeof( FONT_WIDTH_TYPE_TO_INT ) / sizeof( int ); +const int FONT_WIDTH_TYPE_TO_INT[] = {-1, 50, 63, 75, 87, 100, 113, 125, 150, 200}; +const unsigned int NUM_FONT_WIDTH_TYPE = sizeof(FONT_WIDTH_TYPE_TO_INT) / sizeof(int); // NONE -1 --> DEFAULT_FONT_WEIGHT (NORMAL) will be used. // THIN 0 @@ -82,15 +81,15 @@ const unsigned int NUM_FONT_WIDTH_TYPE = sizeof( FONT_WIDTH_TYPE_TO_INT ) / size // BOLD 200 // ULTRA_BOLD, EXTRA_BOLD 205 // BLACK, HEAVY, EXTRA_BLACK 210 -const int FONT_WEIGHT_TYPE_TO_INT[] = { -1, 0, 40, 50, 55, 75, 80, 100, 180, 200, 205, 210 }; -const unsigned int NUM_FONT_WEIGHT_TYPE = sizeof( FONT_WEIGHT_TYPE_TO_INT ) / sizeof( int ); +const int FONT_WEIGHT_TYPE_TO_INT[] = {-1, 0, 40, 50, 55, 75, 80, 100, 180, 200, 205, 210}; +const unsigned int NUM_FONT_WEIGHT_TYPE = sizeof(FONT_WEIGHT_TYPE_TO_INT) / sizeof(int); // NONE -1 --> DEFAULT_FONT_SLANT (NORMAL) will be used. // NORMAL, ROMAN 0 // ITALIC 100 // OBLIQUE 110 -const int FONT_SLANT_TYPE_TO_INT[] = { -1, 0, 100, 110 }; -const unsigned int NUM_FONT_SLANT_TYPE = sizeof( FONT_SLANT_TYPE_TO_INT ) / sizeof( int ); +const int FONT_SLANT_TYPE_TO_INT[] = {-1, 0, 100, 110}; +const unsigned int NUM_FONT_SLANT_TYPE = sizeof(FONT_SLANT_TYPE_TO_INT) / sizeof(int); } // namespace @@ -99,13 +98,10 @@ using namespace std; namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * @brief Returns the FontWidth's enum index for the given width value. * @@ -113,9 +109,9 @@ namespace Internal * * @return The FontWidth's enum index. */ -FontWidth::Type IntToWidthType( int width ) +FontWidth::Type IntToWidthType(int width) { - return static_cast( ValueToIndex( width, FONT_WIDTH_TYPE_TO_INT, NUM_FONT_WIDTH_TYPE - 1u ) ); + return static_cast(ValueToIndex(width, FONT_WIDTH_TYPE_TO_INT, NUM_FONT_WIDTH_TYPE - 1u)); } /** @@ -125,9 +121,9 @@ FontWidth::Type IntToWidthType( int width ) * * @return The FontWeight's enum index. */ -FontWeight::Type IntToWeightType( int weight ) +FontWeight::Type IntToWeightType(int weight) { - return static_cast( ValueToIndex( weight, FONT_WEIGHT_TYPE_TO_INT, NUM_FONT_WEIGHT_TYPE - 1u ) ); + return static_cast(ValueToIndex(weight, FONT_WEIGHT_TYPE_TO_INT, NUM_FONT_WEIGHT_TYPE - 1u)); } /** @@ -137,9 +133,9 @@ FontWeight::Type IntToWeightType( int weight ) * * @return The FontSlant's enum index. */ -FontSlant::Type IntToSlantType( int slant ) +FontSlant::Type IntToSlantType(int slant) { - return static_cast( ValueToIndex( slant, FONT_SLANT_TYPE_TO_INT, NUM_FONT_SLANT_TYPE - 1u ) ); + return static_cast(ValueToIndex(slant, FONT_SLANT_TYPE_TO_INT, NUM_FONT_SLANT_TYPE - 1u)); } /** @@ -147,98 +143,98 @@ FontSlant::Type IntToSlantType( int slant ) * * @param[in] characterSets The vector of character sets. */ -void DestroyCharacterSets( CharacterSetList& characterSets ) +void DestroyCharacterSets(CharacterSetList& characterSets) { - for( auto& item : characterSets ) + for(auto& item : characterSets) { - if( item ) + if(item) { - FcCharSetDestroy( item ); + FcCharSetDestroy(item); } } } -FontClient::Plugin::FallbackCacheItem::FallbackCacheItem( FontDescription&& font, FontList* fallbackFonts, CharacterSetList* characterSets ) -: fontDescription{ std::move( font ) }, - fallbackFonts{ fallbackFonts }, - characterSets{ characterSets } +FontClient::Plugin::FallbackCacheItem::FallbackCacheItem(FontDescription&& font, FontList* fallbackFonts, CharacterSetList* characterSets) +: fontDescription{std::move(font)}, + fallbackFonts{fallbackFonts}, + characterSets{characterSets} { } -FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem( const FontDescription& fontDescription, - FontDescriptionId index ) -: fontDescription{ fontDescription }, - index{ index } +FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem(const FontDescription& fontDescription, + FontDescriptionId index) +: fontDescription{fontDescription}, + index{index} { } -FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem( FontDescription&& fontDescription, - FontDescriptionId index ) -: fontDescription{ std::move( fontDescription ) }, - index{ index } +FontClient::Plugin::FontDescriptionCacheItem::FontDescriptionCacheItem(FontDescription&& fontDescription, + FontDescriptionId index) +: fontDescription{std::move(fontDescription)}, + index{index} { } -FontClient::Plugin::FontDescriptionSizeCacheItem::FontDescriptionSizeCacheItem( FontDescriptionId validatedFontId, - PointSize26Dot6 requestedPointSize, - FontId fontId ) -: validatedFontId( validatedFontId ), - requestedPointSize( requestedPointSize ), - fontId( fontId ) +FontClient::Plugin::FontDescriptionSizeCacheItem::FontDescriptionSizeCacheItem(FontDescriptionId validatedFontId, + PointSize26Dot6 requestedPointSize, + FontId fontId) +: validatedFontId(validatedFontId), + requestedPointSize(requestedPointSize), + fontId(fontId) { } -FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem( FT_Face ftFace, - const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex face, - const FontMetrics& metrics ) -: mFreeTypeFace( ftFace ), - mPath( path ), - mRequestedPointSize( requestedPointSize ), - mFaceIndex( face ), - mMetrics( metrics ), - mCharacterSet( nullptr ), - mFixedSizeIndex( 0 ), - mFixedWidthPixels( 0.f ), - mFixedHeightPixels( 0.f ), - mVectorFontId( 0u ), - mFontId( 0u ), - mIsFixedSizeBitmap( false ), - mHasColorTables( false ) +FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem(FT_Face ftFace, + const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex face, + const FontMetrics& metrics) +: mFreeTypeFace(ftFace), + mPath(path), + mRequestedPointSize(requestedPointSize), + mFaceIndex(face), + mMetrics(metrics), + mCharacterSet(nullptr), + mFixedSizeIndex(0), + mFixedWidthPixels(0.f), + mFixedHeightPixels(0.f), + mVectorFontId(0u), + mFontId(0u), + mIsFixedSizeBitmap(false), + mHasColorTables(false) { } -FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem( FT_Face ftFace, - const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex face, - const FontMetrics& metrics, - int fixedSizeIndex, - float fixedWidth, - float fixedHeight, - bool hasColorTables ) -: mFreeTypeFace( ftFace ), - mPath( path ), - mRequestedPointSize( requestedPointSize ), - mFaceIndex( face ), - mMetrics( metrics ), - mCharacterSet( nullptr ), - mFixedSizeIndex( fixedSizeIndex ), - mFixedWidthPixels( fixedWidth ), - mFixedHeightPixels( fixedHeight ), - mVectorFontId( 0u ), - mFontId( 0u ), - mIsFixedSizeBitmap( true ), - mHasColorTables( hasColorTables ) +FontClient::Plugin::FontFaceCacheItem::FontFaceCacheItem(FT_Face ftFace, + const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex face, + const FontMetrics& metrics, + int fixedSizeIndex, + float fixedWidth, + float fixedHeight, + bool hasColorTables) +: mFreeTypeFace(ftFace), + mPath(path), + mRequestedPointSize(requestedPointSize), + mFaceIndex(face), + mMetrics(metrics), + mCharacterSet(nullptr), + mFixedSizeIndex(fixedSizeIndex), + mFixedWidthPixels(fixedWidth), + mFixedHeightPixels(fixedHeight), + mVectorFontId(0u), + mFontId(0u), + mIsFixedSizeBitmap(true), + mHasColorTables(hasColorTables) { } -FontClient::Plugin::Plugin( unsigned int horizontalDpi, - unsigned int verticalDpi ) -: mFreeTypeLibrary( nullptr ), - mDpiHorizontal( horizontalDpi ), - mDpiVertical( verticalDpi ), +FontClient::Plugin::Plugin(unsigned int horizontalDpi, + unsigned int verticalDpi) +: mFreeTypeLibrary(nullptr), + mDpiHorizontal(horizontalDpi), + mDpiVertical(verticalDpi), mDefaultFontDescription(), mSystemFonts(), mDefaultFonts(), @@ -248,35 +244,35 @@ FontClient::Plugin::Plugin( unsigned int horizontalDpi, mFontDescriptionCache(), mCharacterSetCache(), mFontDescriptionSizeCache(), - mVectorFontCache( nullptr ), + mVectorFontCache(nullptr), mEllipsisCache(), mEmbeddedItemCache(), - mDefaultFontDescriptionCached( false ) + mDefaultFontDescriptionCached(false) { - int error = FT_Init_FreeType( &mFreeTypeLibrary ); - if( FT_Err_Ok != error ) + int error = FT_Init_FreeType(&mFreeTypeLibrary); + if(FT_Err_Ok != error) { - DALI_LOG_INFO( gLogFilter, Debug::General, "FreeType Init error: %d\n", error ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FreeType Init error: %d\n", error); } #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING - mVectorFontCache = new VectorFontCache( mFreeTypeLibrary ); + mVectorFontCache = new VectorFontCache(mFreeTypeLibrary); #endif } FontClient::Plugin::~Plugin() { - ClearFallbackCache( mFallbackCache ); + ClearFallbackCache(mFallbackCache); // Free the resources allocated by the FcCharSet objects. - DestroyCharacterSets( mDefaultFontCharacterSets ); - DestroyCharacterSets( mCharacterSetCache ); + DestroyCharacterSets(mDefaultFontCharacterSets); + DestroyCharacterSets(mCharacterSetCache); ClearCharacterSetFromFontFaceCache(); #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING delete mVectorFontCache; #endif - FT_Done_FreeType( mFreeTypeLibrary ); + FT_Done_FreeType(mFreeTypeLibrary); } void FontClient::Plugin::ClearCache() @@ -286,10 +282,10 @@ void FontClient::Plugin::ClearCache() mSystemFonts.clear(); mDefaultFonts.clear(); - DestroyCharacterSets( mDefaultFontCharacterSets ); + DestroyCharacterSets(mDefaultFontCharacterSets); mDefaultFontCharacterSets.Clear(); - ClearFallbackCache( mFallbackCache ); + ClearFallbackCache(mFallbackCache); mFallbackCache.clear(); mFontIdCache.Clear(); @@ -300,7 +296,7 @@ void FontClient::Plugin::ClearCache() mValidatedFontCache.clear(); mFontDescriptionCache.clear(); - DestroyCharacterSets( mCharacterSetCache ); + DestroyCharacterSets(mCharacterSetCache); mCharacterSetCache.Clear(); mFontDescriptionSizeCache.clear(); @@ -313,11 +309,11 @@ void FontClient::Plugin::ClearCache() mDefaultFontDescriptionCached = false; } -void FontClient::Plugin::SetDpi( unsigned int horizontalDpi, - unsigned int verticalDpi ) +void FontClient::Plugin::SetDpi(unsigned int horizontalDpi, + unsigned int verticalDpi) { mDpiHorizontal = horizontalDpi; - mDpiVertical = verticalDpi; + mDpiVertical = verticalDpi; } void FontClient::Plugin::ResetSystemDefaults() @@ -325,125 +321,125 @@ void FontClient::Plugin::ResetSystemDefaults() mDefaultFontDescriptionCached = false; } -void FontClient::Plugin::SetFontList( const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList ) +void FontClient::Plugin::SetFontList(const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::SetFontList\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::SetFontList\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); fontList.clear(); - FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription ); // Creates a pattern that needs to be destroyed by calling FcPatternDestroy. + FcPattern* fontFamilyPattern = CreateFontFamilyPattern(fontDescription); // Creates a pattern that needs to be destroyed by calling FcPatternDestroy. FcResult result = FcResultMatch; // Match the pattern. - FcFontSet* fontSet = FcFontSort( nullptr /* use default configure */, - fontFamilyPattern, - false /* don't trim */, - nullptr, - &result ); // FcFontSort creates a font set that needs to be destroyed by calling FcFontSetDestroy. + FcFontSet* fontSet = FcFontSort(nullptr /* use default configure */, + fontFamilyPattern, + false /* don't trim */, + nullptr, + &result); // FcFontSort creates a font set that needs to be destroyed by calling FcFontSetDestroy. - if( nullptr != fontSet ) + if(nullptr != fontSet) { - DALI_LOG_INFO( gLogFilter, Debug::General, " number of fonts found : [%d]\n", fontSet->nfont ); + DALI_LOG_INFO(gLogFilter, Debug::General, " number of fonts found : [%d]\n", fontSet->nfont); // Reserve some space to avoid reallocations. - fontList.reserve( fontSet->nfont ); + fontList.reserve(fontSet->nfont); - for( int i = 0u; i < fontSet->nfont; ++i ) + for(int i = 0u; i < fontSet->nfont; ++i) { FcPattern* fontPattern = fontSet->fonts[i]; FontPath path; // Skip fonts with no path - if( GetFcString( fontPattern, FC_FILE, path ) ) + if(GetFcString(fontPattern, FC_FILE, path)) { // Retrieve the character set. Need to call FcCharSetDestroy to free the resources. FcCharSet* characterSet = nullptr; - FcPatternGetCharSet( fontPattern, FC_CHARSET, 0u, &characterSet ); + FcPatternGetCharSet(fontPattern, FC_CHARSET, 0u, &characterSet); // Increase the reference counter of the character set. - characterSetList.PushBack( FcCharSetCopy( characterSet ) ); + characterSetList.PushBack(FcCharSetCopy(characterSet)); - fontList.push_back( FontDescription() ); + fontList.push_back(FontDescription()); FontDescription& newFontDescription = fontList.back(); - newFontDescription.path = std::move( path ); + newFontDescription.path = std::move(path); - int width = 0; + int width = 0; int weight = 0; - int slant = 0; - GetFcString( fontPattern, FC_FAMILY, newFontDescription.family ); - GetFcInt( fontPattern, FC_WIDTH, width ); - GetFcInt( fontPattern, FC_WEIGHT, weight ); - GetFcInt( fontPattern, FC_SLANT, slant ); - newFontDescription.width = IntToWidthType( width ); - newFontDescription.weight = IntToWeightType( weight ); - newFontDescription.slant = IntToSlantType( slant ); - - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", newFontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", newFontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[newFontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[newFontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[newFontDescription.slant] ); + int slant = 0; + GetFcString(fontPattern, FC_FAMILY, newFontDescription.family); + GetFcInt(fontPattern, FC_WIDTH, width); + GetFcInt(fontPattern, FC_WEIGHT, weight); + GetFcInt(fontPattern, FC_SLANT, slant); + newFontDescription.width = IntToWidthType(width); + newFontDescription.weight = IntToWeightType(weight); + newFontDescription.slant = IntToSlantType(slant); + + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " description; family : [%s]\n", newFontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", newFontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[newFontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[newFontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[newFontDescription.slant]); } } // Destroys the font set created by FcFontSort. - FcFontSetDestroy( fontSet ); + FcFontSetDestroy(fontSet); } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " No fonts found.\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " No fonts found.\n"); } // Destroys the pattern created by FcPatternCreate in CreateFontFamilyPattern. - FcPatternDestroy( fontFamilyPattern ); + FcPatternDestroy(fontFamilyPattern); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::SetFontList\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::SetFontList\n"); } -void FontClient::Plugin::GetDefaultFonts( FontList& defaultFonts ) +void FontClient::Plugin::GetDefaultFonts(FontList& defaultFonts) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultFonts\n"); - if( mDefaultFonts.empty() ) + if(mDefaultFonts.empty()) { FontDescription fontDescription; - fontDescription.family = DEFAULT_FONT_FAMILY_NAME; // todo This could be set to the Platform font - fontDescription.width = IntToWidthType( DEFAULT_FONT_WIDTH ); - fontDescription.weight = IntToWeightType( DEFAULT_FONT_WEIGHT ); - fontDescription.slant = IntToSlantType( DEFAULT_FONT_SLANT ); - SetFontList( fontDescription, mDefaultFonts, mDefaultFontCharacterSets ); + fontDescription.family = DEFAULT_FONT_FAMILY_NAME; // todo This could be set to the Platform font + fontDescription.width = IntToWidthType(DEFAULT_FONT_WIDTH); + fontDescription.weight = IntToWeightType(DEFAULT_FONT_WEIGHT); + fontDescription.slant = IntToSlantType(DEFAULT_FONT_SLANT); + SetFontList(fontDescription, mDefaultFonts, mDefaultFontCharacterSets); } defaultFonts = mDefaultFonts; - DALI_LOG_INFO( gLogFilter, Debug::General, " number of default fonts : [%d]\n", mDefaultFonts.size() ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " number of default fonts : [%d]\n", mDefaultFonts.size()); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultFonts\n"); } -void FontClient::Plugin::GetDefaultPlatformFontDescription( FontDescription& fontDescription ) +void FontClient::Plugin::GetDefaultPlatformFontDescription(FontDescription& fontDescription) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultPlatformFontDescription\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetDefaultPlatformFontDescription\n"); - if( !mDefaultFontDescriptionCached ) + if(!mDefaultFontDescriptionCached) { // Clear any font config stored info in the caches. // Decrease the reference counter and eventually free the resources allocated by FcCharSet objects. - DestroyCharacterSets( mDefaultFontCharacterSets ); - DestroyCharacterSets( mCharacterSetCache ); + DestroyCharacterSets(mDefaultFontCharacterSets); + DestroyCharacterSets(mCharacterSetCache); mDefaultFontCharacterSets.Clear(); mCharacterSetCache.Clear(); - for( auto& item : mFallbackCache ) + for(auto& item : mFallbackCache) { // Decrease the reference counter and eventually free the resources allocated by FcCharSet objects. - DestroyCharacterSets( *item.characterSets ); + DestroyCharacterSets(*item.characterSets); delete item.characterSets; item.characterSets = nullptr; @@ -457,44 +453,44 @@ void FontClient::Plugin::GetDefaultPlatformFontDescription( FontDescription& fon FcPattern* matchPattern = FcPatternCreate(); // Creates a pattern that needs to be destroyed by calling FcPatternDestroy. - if( nullptr != matchPattern ) + if(nullptr != matchPattern) { - FcConfigSubstitute( nullptr, matchPattern, FcMatchPattern ); - FcDefaultSubstitute( matchPattern ); + FcConfigSubstitute(nullptr, matchPattern, FcMatchPattern); + FcDefaultSubstitute(matchPattern); FcCharSet* characterSet = nullptr; - MatchFontDescriptionToPattern( matchPattern, mDefaultFontDescription, &characterSet ); + MatchFontDescriptionToPattern(matchPattern, mDefaultFontDescription, &characterSet); // Decrease the reference counter of the character set as it's not stored. - FcCharSetDestroy( characterSet ); + FcCharSetDestroy(characterSet); // Destroys the pattern created. - FcPatternDestroy( matchPattern ); + FcPatternDestroy(matchPattern); } // Create again the character sets as they are not valid after FcInitReinitialize() - for( const auto& description : mDefaultFonts ) + for(const auto& description : mDefaultFonts) { - mDefaultFontCharacterSets.PushBack( FcCharSetCopy( CreateCharacterSetFromDescription( description ) ) ); + mDefaultFontCharacterSets.PushBack(FcCharSetCopy(CreateCharacterSetFromDescription(description))); } - for( const auto& description : mFontDescriptionCache ) + for(const auto& description : mFontDescriptionCache) { - mCharacterSetCache.PushBack( FcCharSetCopy( CreateCharacterSetFromDescription( description ) ) ); + mCharacterSetCache.PushBack(FcCharSetCopy(CreateCharacterSetFromDescription(description))); } - for( auto& item : mFallbackCache ) + for(auto& item : mFallbackCache) { - if( nullptr != item.fallbackFonts ) + if(nullptr != item.fallbackFonts) { - if( nullptr == item.characterSets ) + if(nullptr == item.characterSets) { item.characterSets = new CharacterSetList; } - for( const auto& description : *( item.fallbackFonts ) ) + for(const auto& description : *(item.fallbackFonts)) { - item.characterSets->PushBack( FcCharSetCopy( CreateCharacterSetFromDescription( description ) ) ); + item.characterSets->PushBack(FcCharSetCopy(CreateCharacterSetFromDescription(description))); } } } @@ -508,54 +504,54 @@ void FontClient::Plugin::GetDefaultPlatformFontDescription( FontDescription& fon fontDescription.weight = mDefaultFontDescription.weight; fontDescription.slant = mDefaultFontDescription.slant; - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultPlatformFontDescription\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetDefaultPlatformFontDescription\n"); } -void FontClient::Plugin::GetSystemFonts( FontList& systemFonts ) +void FontClient::Plugin::GetSystemFonts(FontList& systemFonts) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetSystemFonts\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetSystemFonts\n"); - if( mSystemFonts.empty() ) + if(mSystemFonts.empty()) { InitSystemFonts(); } systemFonts = mSystemFonts; - DALI_LOG_INFO( gLogFilter, Debug::General, " number of system fonts : [%d]\n", mSystemFonts.size() ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetSystemFonts\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " number of system fonts : [%d]\n", mSystemFonts.size()); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetSystemFonts\n"); } -void FontClient::Plugin::GetDescription( FontId id, - FontDescription& fontDescription ) const +void FontClient::Plugin::GetDescription(FontId id, + FontDescription& fontDescription) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetDescription\n"); - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetDescription\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", id); const FontId index = id - 1u; - if( ( id > 0u ) && ( index < mFontIdCache.Count() ) ) + if((id > 0u) && (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { - for( const auto& item : mFontDescriptionSizeCache ) + for(const auto& item : mFontDescriptionSizeCache) { - if( item.fontId == fontIdCacheItem.id ) + if(item.fontId == fontIdCacheItem.id) { - fontDescription = *( mFontDescriptionCache.begin() + item.validatedFontId - 1u ); - - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n"); + fontDescription = *(mFontDescriptionCache.begin() + item.validatedFontId - 1u); + + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n"); return; } } @@ -563,7 +559,7 @@ void FontClient::Plugin::GetDescription( FontId id, } case FontDescription::BITMAP_FONT: { - fontDescription.type = FontDescription::BITMAP_FONT; + fontDescription.type = FontDescription::BITMAP_FONT; fontDescription.family = mBitmapFontCache[fontIdCacheItem.id].font.name; break; } @@ -576,28 +572,28 @@ void FontClient::Plugin::GetDescription( FontId id, } } - DALI_LOG_INFO( gLogFilter, Debug::General, " No description found for the font ID %d\n", id ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " No description found for the font ID %d\n", id); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetDescription\n"); } -PointSize26Dot6 FontClient::Plugin::GetPointSize( FontId id ) +PointSize26Dot6 FontClient::Plugin::GetPointSize(FontId id) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetPointSize\n"); - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetPointSize\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", id); const FontId index = id - 1u; - if( ( id > 0u ) && - ( index < mFontIdCache.Count() ) ) + if((id > 0u) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { - DALI_LOG_INFO( gLogFilter, Debug::General, " point size : %d\n", ( *( mFontFaceCache.begin() + fontIdCacheItem.id ) ).mRequestedPointSize ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n"); - return ( *( mFontFaceCache.begin() + fontIdCacheItem.id ) ).mRequestedPointSize; + DALI_LOG_INFO(gLogFilter, Debug::General, " point size : %d\n", (*(mFontFaceCache.begin() + fontIdCacheItem.id)).mRequestedPointSize); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n"); + return (*(mFontFaceCache.begin() + fontIdCacheItem.id)).mRequestedPointSize; } case FontDescription::BITMAP_FONT: { @@ -611,24 +607,24 @@ PointSize26Dot6 FontClient::Plugin::GetPointSize( FontId id ) } else { - DALI_LOG_INFO( gLogFilter, Debug::General, " Invalid font ID %d\n", id ); + DALI_LOG_INFO(gLogFilter, Debug::General, " Invalid font ID %d\n", id); } - DALI_LOG_INFO( gLogFilter, Debug::General, " default point size : %d\n", TextAbstraction::FontClient::DEFAULT_POINT_SIZE ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " default point size : %d\n", TextAbstraction::FontClient::DEFAULT_POINT_SIZE); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetPointSize\n"); return TextAbstraction::FontClient::DEFAULT_POINT_SIZE; } -bool FontClient::Plugin::IsCharacterSupportedByFont( FontId fontId, Character character ) +bool FontClient::Plugin::IsCharacterSupportedByFont(FontId fontId, Character character) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::IsCharacterSupportedByFont\n"); - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", character ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::IsCharacterSupportedByFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, " character : %p\n", character); - if( ( fontId < 1u ) || ( fontId > mFontIdCache.Count() ) ) + if((fontId < 1u) || (fontId > mFontIdCache.Count())) { - DALI_LOG_INFO( gLogFilter, Debug::General, " Invalid font id. Number of items in the cache: %d\n",mFontIdCache.Count()); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " Invalid font id. Number of items in the cache: %d\n", mFontIdCache.Count()); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n"); return false; } @@ -638,40 +634,40 @@ bool FontClient::Plugin::IsCharacterSupportedByFont( FontId fontId, Character ch const FontIdCacheItem& fontIdCacheItem = mFontIdCache[fontId]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { - if( fontIdCacheItem.id < mFontFaceCache.size() ) + if(fontIdCacheItem.id < mFontFaceCache.size()) { FontFaceCacheItem& cacheItem = mFontFaceCache[fontIdCacheItem.id]; - if( nullptr == cacheItem.mCharacterSet ) + if(nullptr == cacheItem.mCharacterSet) { // Create again the character set. // It can be null if the ResetSystemDefaults() method has been called. FontDescription description; - description.path = cacheItem.mPath; - description.family = std::move( FontFamily( cacheItem.mFreeTypeFace->family_name ) ); + description.path = cacheItem.mPath; + description.family = std::move(FontFamily(cacheItem.mFreeTypeFace->family_name)); description.weight = FontWeight::NONE; - description.width = FontWidth::NONE; - description.slant = FontSlant::NONE; + description.width = FontWidth::NONE; + description.slant = FontSlant::NONE; // Note FreeType doesn't give too much info to build a proper font style. - if( cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC ) + if(cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC) { description.slant = FontSlant::ITALIC; } - if( cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD ) + if(cacheItem.mFreeTypeFace->style_flags & FT_STYLE_FLAG_BOLD) { description.weight = FontWeight::BOLD; } - cacheItem.mCharacterSet = FcCharSetCopy( CreateCharacterSetFromDescription( description ) ); + cacheItem.mCharacterSet = FcCharSetCopy(CreateCharacterSetFromDescription(description)); } - isSupported = FcCharSetHasChar( cacheItem.mCharacterSet, character ); + isSupported = FcCharSetHasChar(cacheItem.mCharacterSet, character); } break; } @@ -679,9 +675,9 @@ bool FontClient::Plugin::IsCharacterSupportedByFont( FontId fontId, Character ch { const BitmapFont& bitmapFont = mBitmapFontCache[fontIdCacheItem.id].font; - for( const auto& glyph : bitmapFont.glyphs ) + for(const auto& glyph : bitmapFont.glyphs) { - if( glyph.utf32 == character ) + if(glyph.utf32 == character) { isSupported = true; break; @@ -695,126 +691,125 @@ bool FontClient::Plugin::IsCharacterSupportedByFont( FontId fontId, Character ch } } - DALI_LOG_INFO( gLogFilter, Debug::General, " is supported : %s\n", (isSupported ? "true" : "false") ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " is supported : %s\n", (isSupported ? "true" : "false")); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::IsCharacterSupportedByFont\n"); return isSupported; } -FontId FontClient::Plugin::FindFontForCharacter( const FontList& fontList, - const CharacterSetList& characterSetList, - Character character, - PointSize26Dot6 requestedPointSize, - bool preferColor ) +FontId FontClient::Plugin::FindFontForCharacter(const FontList& fontList, + const CharacterSetList& characterSetList, + Character character, + PointSize26Dot6 requestedPointSize, + bool preferColor) { - DALI_ASSERT_DEBUG( ( fontList.size() == characterSetList.Count() ) && "FontClient::Plugin::FindFontForCharacter. Different number of fonts and character sets." ); + DALI_ASSERT_DEBUG((fontList.size() == characterSetList.Count()) && "FontClient::Plugin::FindFontForCharacter. Different number of fonts and character sets."); - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFontForCharacter\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", character ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); - DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindFontForCharacter\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " character : %p\n", character); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); + DALI_LOG_INFO(gLogFilter, Debug::General, " preferColor : %s\n", (preferColor ? "true" : "false")); - FontId fontId = 0u; - bool foundColor = false; + FontId fontId = 0u; + bool foundColor = false; - DALI_LOG_INFO( gLogFilter, Debug::General, " number of fonts : %d\n", fontList.size() ); + DALI_LOG_INFO(gLogFilter, Debug::General, " number of fonts : %d\n", fontList.size()); // Traverse the list of fonts. // Check for each font if supports the character. - for( unsigned int index = 0u, numberOfFonts = fontList.size(); index < numberOfFonts; ++index ) + for(unsigned int index = 0u, numberOfFonts = fontList.size(); index < numberOfFonts; ++index) { - const FontDescription& description = fontList[index]; + const FontDescription& description = fontList[index]; const FcCharSet* const characterSet = characterSetList[index]; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", description.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant] ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " description; family : [%s]\n", description.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant]); bool foundInRanges = false; - if( nullptr != characterSet ) + if(nullptr != characterSet) { - foundInRanges = FcCharSetHasChar( characterSet, character ); + foundInRanges = FcCharSetHasChar(characterSet, character); } - if( foundInRanges ) + if(foundInRanges) { - fontId = GetFontId( description, - requestedPointSize, - 0u ); + fontId = GetFontId(description, + requestedPointSize, + 0u); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " font id : %d\n", fontId ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " font id : %d\n", fontId); - if( preferColor ) + if(preferColor) { - if( ( fontId > 0 ) && - ( fontId - 1u < mFontIdCache.Count() ) ) + if((fontId > 0) && + (fontId - 1u < mFontIdCache.Count())) { const FontFaceCacheItem& item = mFontFaceCache[mFontIdCache[fontId - 1u].id]; foundColor = item.mHasColorTables; } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " foundColor : %s\n", ( foundColor ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " foundColor : %s\n", (foundColor ? "true" : "false")); } // Keep going unless we prefer a different (color) font. - if( !preferColor || foundColor ) + if(!preferColor || foundColor) { break; } } } - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFontForCharacter\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFontForCharacter\n"); return fontId; } -FontId FontClient::Plugin::FindDefaultFont( Character charcode, - PointSize26Dot6 requestedPointSize, - bool preferColor ) +FontId FontClient::Plugin::FindDefaultFont(Character charcode, + PointSize26Dot6 requestedPointSize, + bool preferColor) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindDefaultFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", charcode ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); - DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindDefaultFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " character : %p\n", charcode); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); + DALI_LOG_INFO(gLogFilter, Debug::General, " preferColor : %s\n", (preferColor ? "true" : "false")); FontId fontId(0); // Create the list of default fonts if it has not been created. - if( mDefaultFonts.empty() ) + if(mDefaultFonts.empty()) { FontDescription fontDescription; fontDescription.family = DEFAULT_FONT_FAMILY_NAME; - fontDescription.width = IntToWidthType( DEFAULT_FONT_WIDTH ); - fontDescription.weight = IntToWeightType( DEFAULT_FONT_WEIGHT ); - fontDescription.slant = IntToSlantType( DEFAULT_FONT_SLANT ); + fontDescription.width = IntToWidthType(DEFAULT_FONT_WIDTH); + fontDescription.weight = IntToWeightType(DEFAULT_FONT_WEIGHT); + fontDescription.slant = IntToSlantType(DEFAULT_FONT_SLANT); - SetFontList( fontDescription, mDefaultFonts, mDefaultFontCharacterSets ); + SetFontList(fontDescription, mDefaultFonts, mDefaultFontCharacterSets); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of default fonts : %d\n", mDefaultFonts.size() ); - + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of default fonts : %d\n", mDefaultFonts.size()); // Traverse the list of default fonts. // Check for each default font if supports the character. - fontId = FindFontForCharacter( mDefaultFonts, mDefaultFontCharacterSets, charcode, requestedPointSize, preferColor ); + fontId = FindFontForCharacter(mDefaultFonts, mDefaultFontCharacterSets, charcode, requestedPointSize, preferColor); - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindDefaultFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindDefaultFont\n"); return fontId; } -FontId FontClient::Plugin::FindFallbackFont( Character charcode, - const FontDescription& preferredFontDescription, - PointSize26Dot6 requestedPointSize, - bool preferColor ) +FontId FontClient::Plugin::FindFallbackFont(Character charcode, + const FontDescription& preferredFontDescription, + PointSize26Dot6 requestedPointSize, + bool preferColor) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " character : %p\n", charcode ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); - DALI_LOG_INFO( gLogFilter, Debug::General, " preferColor : %s\n", ( preferColor ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " character : %p\n", charcode); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); + DALI_LOG_INFO(gLogFilter, Debug::General, " preferColor : %s\n", (preferColor ? "true" : "false")); // The font id to be returned. FontId fontId = 0u; @@ -823,97 +818,97 @@ FontId FontClient::Plugin::FindFallbackFont( Character charcode, // Fill the font description with the preferred font description and complete with the defaults. fontDescription.family = preferredFontDescription.family.empty() ? DEFAULT_FONT_FAMILY_NAME : preferredFontDescription.family; - fontDescription.weight = ( ( FontWeight::NONE == preferredFontDescription.weight ) ? IntToWeightType( DEFAULT_FONT_WEIGHT ) : preferredFontDescription.weight ); - fontDescription.width = ( ( FontWidth::NONE == preferredFontDescription.width ) ? IntToWidthType( DEFAULT_FONT_WIDTH ) : preferredFontDescription.width ); - fontDescription.slant = ( ( FontSlant::NONE == preferredFontDescription.slant ) ? IntToSlantType( DEFAULT_FONT_SLANT ) : preferredFontDescription.slant ); + fontDescription.weight = ((FontWeight::NONE == preferredFontDescription.weight) ? IntToWeightType(DEFAULT_FONT_WEIGHT) : preferredFontDescription.weight); + fontDescription.width = ((FontWidth::NONE == preferredFontDescription.width) ? IntToWidthType(DEFAULT_FONT_WIDTH) : preferredFontDescription.width); + fontDescription.slant = ((FontSlant::NONE == preferredFontDescription.slant) ? IntToSlantType(DEFAULT_FONT_SLANT) : preferredFontDescription.slant); - DALI_LOG_INFO( gLogFilter, Debug::General, " preferredFontDescription --> fontDescription\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " [%s] --> [%s]\n", preferredFontDescription.family.c_str(), fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWeight::Name[preferredFontDescription.weight], FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWidth::Name[preferredFontDescription.width], FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontSlant::Name[preferredFontDescription.slant], FontSlant::Name[fontDescription.slant] ); + DALI_LOG_INFO(gLogFilter, Debug::General, " preferredFontDescription --> fontDescription\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " [%s] --> [%s]\n", preferredFontDescription.family.c_str(), fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWeight::Name[preferredFontDescription.weight], FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontWidth::Name[preferredFontDescription.width], FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " [%s] --> [%s]\n", FontSlant::Name[preferredFontDescription.slant], FontSlant::Name[fontDescription.slant]); // Check first if the font's description has been queried before. - FontList* fontList = nullptr; + FontList* fontList = nullptr; CharacterSetList* characterSetList = nullptr; - if( !FindFallbackFontList( fontDescription, fontList, characterSetList ) ) + if(!FindFallbackFontList(fontDescription, fontList, characterSetList)) { - fontList = new FontList; + fontList = new FontList; characterSetList = new CharacterSetList; - SetFontList( fontDescription, *fontList, *characterSetList ); + SetFontList(fontDescription, *fontList, *characterSetList); #ifdef __APPLE__ FontDescription appleColorEmoji; appleColorEmoji.family = "Apple Color Emoji"; - appleColorEmoji.width = fontDescription.width; + appleColorEmoji.width = fontDescription.width; appleColorEmoji.weight = fontDescription.weight; - appleColorEmoji.slant = fontDescription.slant; - FontList emojiFontList; + appleColorEmoji.slant = fontDescription.slant; + FontList emojiFontList; CharacterSetList emojiCharSetList; SetFontList(appleColorEmoji, emojiFontList, emojiCharSetList); std::move(fontList->begin(), fontList->end(), std::back_inserter(emojiFontList)); emojiCharSetList.Insert(emojiCharSetList.End(), characterSetList->Begin(), characterSetList->End()); - *fontList = std::move(emojiFontList); + *fontList = std::move(emojiFontList); *characterSetList = std::move(emojiCharSetList); #endif // Add the font-list to the cache. - mFallbackCache.push_back( std::move( FallbackCacheItem( std::move( fontDescription ), fontList, characterSetList ) ) ); + mFallbackCache.push_back(std::move(FallbackCacheItem(std::move(fontDescription), fontList, characterSetList))); } - if( fontList && characterSetList ) + if(fontList && characterSetList) { - fontId = FindFontForCharacter( *fontList, *characterSetList, charcode, requestedPointSize, preferColor ); + fontId = FindFontForCharacter(*fontList, *characterSetList, charcode, requestedPointSize, preferColor); } - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFont\n"); return fontId; } -FontId FontClient::Plugin::GetFontId( const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex, - bool cacheDescription ) +FontId FontClient::Plugin::GetFontId(const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex, + bool cacheDescription) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " path : [%s]\n", path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); FontId id = 0u; - if( nullptr != mFreeTypeLibrary ) + if(nullptr != mFreeTypeLibrary) { FontId foundId = 0u; - if( FindFont( path, requestedPointSize, faceIndex, foundId ) ) + if(FindFont(path, requestedPointSize, faceIndex, foundId)) { id = foundId; } else { - id = CreateFont( path, requestedPointSize, faceIndex, cacheDescription ); + id = CreateFont(path, requestedPointSize, faceIndex, cacheDescription); } } - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", id); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n"); return id; } -FontId FontClient::Plugin::GetFontId( const FontDescription& fontDescription, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex ) +FontId FontClient::Plugin::GetFontId(const FontDescription& fontDescription, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetFontId\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); // This method uses three vectors which caches: // * The bitmap font cache @@ -937,7 +932,7 @@ FontId FontClient::Plugin::GetFontId( const FontDescription& fontDescription, FontId fontId = 0u; // Check first if the font description matches with a previously loaded bitmap font. - if( FindBitmapFont( fontDescription.family, fontId ) ) + if(FindBitmapFont(fontDescription.family, fontId)) { return fontId; } @@ -945,51 +940,51 @@ FontId FontClient::Plugin::GetFontId( const FontDescription& fontDescription, // Check if the font's description have been validated before. FontDescriptionId validatedFontId = 0u; - if( !FindValidatedFont( fontDescription, - validatedFontId ) ) + if(!FindValidatedFont(fontDescription, + validatedFontId)) { // Use font config to validate the font's description. - ValidateFont( fontDescription, - validatedFontId ); + ValidateFont(fontDescription, + validatedFontId); } FontId fontFaceId = 0u; // Check if exists a pair 'validatedFontId, requestedPointSize' in the cache. - if( !FindFont( validatedFontId, requestedPointSize, fontFaceId ) ) + if(!FindFont(validatedFontId, requestedPointSize, fontFaceId)) { // Retrieve the font file name path. - const FontDescription& description = *( mFontDescriptionCache.begin() + validatedFontId - 1u ); + const FontDescription& description = *(mFontDescriptionCache.begin() + validatedFontId - 1u); // Retrieve the font id. Do not cache the description as it has been already cached. - fontId = GetFontId( description.path, - requestedPointSize, - faceIndex, - false ); + fontId = GetFontId(description.path, + requestedPointSize, + faceIndex, + false); - fontFaceId = mFontIdCache[fontId-1u].id; - mFontFaceCache[fontFaceId].mCharacterSet = FcCharSetCopy( mCharacterSetCache[validatedFontId - 1u] ); + fontFaceId = mFontIdCache[fontId - 1u].id; + mFontFaceCache[fontFaceId].mCharacterSet = FcCharSetCopy(mCharacterSetCache[validatedFontId - 1u]); // Cache the pair 'validatedFontId, requestedPointSize' to improve the following queries. - mFontDescriptionSizeCache.push_back( FontDescriptionSizeCacheItem( validatedFontId, - requestedPointSize, - fontFaceId ) ); + mFontDescriptionSizeCache.push_back(FontDescriptionSizeCacheItem(validatedFontId, + requestedPointSize, + fontFaceId)); } else { fontId = mFontFaceCache[fontFaceId].mFontId + 1u; } - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetFontId\n"); return fontId; } -FontId FontClient::Plugin::GetFontId( const BitmapFont& bitmapFont ) +FontId FontClient::Plugin::GetFontId(const BitmapFont& bitmapFont) { - for( const auto& item : mBitmapFontCache ) + for(const auto& item : mBitmapFontCache) { - if( bitmapFont.name == item.font.name ) + if(bitmapFont.name == item.font.name) { return item.id + 1u; } @@ -997,119 +992,119 @@ FontId FontClient::Plugin::GetFontId( const BitmapFont& bitmapFont ) BitmapFontCacheItem bitmapFontCacheItem; bitmapFontCacheItem.font = bitmapFont; - bitmapFontCacheItem.id = mFontIdCache.Count(); + bitmapFontCacheItem.id = mFontIdCache.Count(); // Resize the vector with the pixel buffers. - bitmapFontCacheItem.pixelBuffers.resize( bitmapFont.glyphs.size() ); + bitmapFontCacheItem.pixelBuffers.resize(bitmapFont.glyphs.size()); // Traverse all the glyphs and load the pixel buffer of those with ascender and descender equal to zero. unsigned int index = 0u; - for( auto& glyph : bitmapFontCacheItem.font.glyphs ) + for(auto& glyph : bitmapFontCacheItem.font.glyphs) { Devel::PixelBuffer& pixelBuffer = bitmapFontCacheItem.pixelBuffers[index]; - if( EqualsZero( glyph.ascender ) && EqualsZero( glyph.descender ) ) + if(EqualsZero(glyph.ascender) && EqualsZero(glyph.descender)) { // Load the glyph. - pixelBuffer = LoadImageFromFile( glyph.url ); + pixelBuffer = LoadImageFromFile(glyph.url); - if( pixelBuffer ) + if(pixelBuffer) { glyph.ascender = static_cast(pixelBuffer.GetHeight()); } } - bitmapFontCacheItem.font.ascender = std::max( glyph.ascender, bitmapFontCacheItem.font.ascender ); - bitmapFontCacheItem.font.descender = std::min( glyph.descender, bitmapFontCacheItem.font.descender ); + bitmapFontCacheItem.font.ascender = std::max(glyph.ascender, bitmapFontCacheItem.font.ascender); + bitmapFontCacheItem.font.descender = std::min(glyph.descender, bitmapFontCacheItem.font.descender); ++index; } FontIdCacheItem fontIdCacheItem; fontIdCacheItem.type = FontDescription::BITMAP_FONT; - fontIdCacheItem.id = mBitmapFontCache.size(); + fontIdCacheItem.id = mBitmapFontCache.size(); - mBitmapFontCache.push_back( std::move( bitmapFontCacheItem ) ); - mFontIdCache.PushBack( fontIdCacheItem ); + mBitmapFontCache.push_back(std::move(bitmapFontCacheItem)); + mFontIdCache.PushBack(fontIdCacheItem); return bitmapFontCacheItem.id + 1u; } -void FontClient::Plugin::ValidateFont( const FontDescription& fontDescription, - FontDescriptionId& validatedFontId ) +void FontClient::Plugin::ValidateFont(const FontDescription& fontDescription, + FontDescriptionId& validatedFontId) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::ValidateFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::ValidateFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); // Create a font pattern. - FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription ); + FcPattern* fontFamilyPattern = CreateFontFamilyPattern(fontDescription); FontDescription description; FcCharSet* characterSet = nullptr; - bool matched = MatchFontDescriptionToPattern( fontFamilyPattern, description, &characterSet ); - FcPatternDestroy( fontFamilyPattern ); + bool matched = MatchFontDescriptionToPattern(fontFamilyPattern, description, &characterSet); + FcPatternDestroy(fontFamilyPattern); - if( matched && ( nullptr != characterSet ) ) + if(matched && (nullptr != characterSet)) { // Add the path to the cache. description.type = FontDescription::FACE_FONT; - mFontDescriptionCache.push_back( description ); + mFontDescriptionCache.push_back(description); // Set the index to the vector of paths to font file names. validatedFontId = mFontDescriptionCache.size(); - DALI_LOG_INFO( gLogFilter, Debug::General, " matched description; family : [%s]\n", description.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant] ); - DALI_LOG_INFO( gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId ); + DALI_LOG_INFO(gLogFilter, Debug::General, " matched description; family : [%s]\n", description.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", description.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[description.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[description.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[description.slant]); + DALI_LOG_INFO(gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId); // The reference counter of the character set has already been increased in MatchFontDescriptionToPattern. - mCharacterSetCache.PushBack( characterSet ); + mCharacterSetCache.PushBack(characterSet); // Cache the index and the matched font's description. - FontDescriptionCacheItem item( description, - validatedFontId ); + FontDescriptionCacheItem item(description, + validatedFontId); - mValidatedFontCache.push_back( std::move( item ) ); + mValidatedFontCache.push_back(std::move(item)); - if( ( fontDescription.family != description.family ) || - ( fontDescription.width != description.width ) || - ( fontDescription.weight != description.weight ) || - ( fontDescription.slant != description.slant ) ) + if((fontDescription.family != description.family) || + (fontDescription.width != description.width) || + (fontDescription.weight != description.weight) || + (fontDescription.slant != description.slant)) { // Cache the given font's description if it's different than the matched. - FontDescriptionCacheItem item( fontDescription, - validatedFontId ); + FontDescriptionCacheItem item(fontDescription, + validatedFontId); - mValidatedFontCache.push_back( std::move( item ) ); + mValidatedFontCache.push_back(std::move(item)); } } else { - DALI_LOG_INFO( gLogFilter, Debug::General, " font validation failed for font [%s]\n", fontDescription.family.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font validation failed for font [%s]\n", fontDescription.family.c_str()); } - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::ValidateFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::ValidateFont\n"); } -void FontClient::Plugin::GetFontMetrics( FontId fontId, - FontMetrics& metrics ) +void FontClient::Plugin::GetFontMetrics(FontId fontId, + FontMetrics& metrics) { const FontId index = fontId - 1u; - if( ( fontId > 0 ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { @@ -1118,18 +1113,18 @@ void FontClient::Plugin::GetFontMetrics( FontId fontId, metrics = font.mMetrics; // Adjust the metrics if the fixed-size font should be down-scaled - if( font.mIsFixedSizeBitmap ) + if(font.mIsFixedSizeBitmap) { - const float desiredFixedSize = static_cast( font.mRequestedPointSize ) * FROM_266 / POINTS_PER_INCH * mDpiVertical; + const float desiredFixedSize = static_cast(font.mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * mDpiVertical; - if( desiredFixedSize > 0.f ) + if(desiredFixedSize > 0.f) { const float scaleFactor = desiredFixedSize / font.mFixedHeightPixels; - metrics.ascender = metrics.ascender * scaleFactor; - metrics.descender = metrics.descender * scaleFactor; - metrics.height = metrics.height * scaleFactor; - metrics.underlinePosition = metrics.underlinePosition * scaleFactor; + metrics.ascender = metrics.ascender * scaleFactor; + metrics.descender = metrics.descender * scaleFactor; + metrics.height = metrics.height * scaleFactor; + metrics.underlinePosition = metrics.underlinePosition * scaleFactor; metrics.underlineThickness = metrics.underlineThickness * scaleFactor; } } @@ -1139,10 +1134,10 @@ void FontClient::Plugin::GetFontMetrics( FontId fontId, { const BitmapFontCacheItem& bitmapFontCacheItem = mBitmapFontCache[fontIdCacheItem.id]; - metrics.ascender = bitmapFontCacheItem.font.ascender; - metrics.descender = bitmapFontCacheItem.font.descender; - metrics.height = metrics.ascender - metrics.descender; - metrics.underlinePosition = bitmapFontCacheItem.font.underlinePosition; + metrics.ascender = bitmapFontCacheItem.font.ascender; + metrics.descender = bitmapFontCacheItem.font.descender; + metrics.height = metrics.ascender - metrics.descender; + metrics.underlinePosition = bitmapFontCacheItem.font.underlinePosition; metrics.underlineThickness = bitmapFontCacheItem.font.underlineThickness; break; } @@ -1154,63 +1149,63 @@ void FontClient::Plugin::GetFontMetrics( FontId fontId, } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFontMetrics. Invalid font id : %d\n", fontId ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::GetFontMetrics. Invalid font id : %d\n", fontId); } } -GlyphIndex FontClient::Plugin::GetGlyphIndex( FontId fontId, - Character charcode ) +GlyphIndex FontClient::Plugin::GetGlyphIndex(FontId fontId, + Character charcode) { - GlyphIndex glyphIndex = 0u; - const FontId index = fontId - 1u; + GlyphIndex glyphIndex = 0u; + const FontId index = fontId - 1u; - if( ( fontId > 0u ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0u) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - if( FontDescription::FACE_FONT == fontIdCacheItem.type ) + if(FontDescription::FACE_FONT == fontIdCacheItem.type) { FT_Face ftFace = mFontFaceCache[fontIdCacheItem.id].mFreeTypeFace; - glyphIndex = FT_Get_Char_Index( ftFace, charcode ); + glyphIndex = FT_Get_Char_Index(ftFace, charcode); } } return glyphIndex; } -bool FontClient::Plugin::GetGlyphMetrics( GlyphInfo* array, - uint32_t size, - GlyphType type, - bool horizontal ) +bool FontClient::Plugin::GetGlyphMetrics(GlyphInfo* array, + uint32_t size, + GlyphType type, + bool horizontal) { - if( VECTOR_GLYPH == type ) + if(VECTOR_GLYPH == type) { - return GetVectorMetrics( array, size, horizontal ); + return GetVectorMetrics(array, size, horizontal); } - return GetBitmapMetrics( array, size, horizontal ); + return GetBitmapMetrics(array, size, horizontal); } -bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, - uint32_t size, - bool horizontal ) +bool FontClient::Plugin::GetBitmapMetrics(GlyphInfo* array, + uint32_t size, + bool horizontal) { - bool success( true ); + bool success(true); - for( unsigned int i=0; i 0u ) && - ( index < mFontIdCache.Count() ) ) + if((glyph.fontId > 0u) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { @@ -1220,28 +1215,28 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if we should be loading a Fixed Size bitmap? - if( font.mIsFixedSizeBitmap ) + if(font.mIsFixedSizeBitmap) { - FT_Select_Size( ftFace, font.mFixedSizeIndex ); ///< @todo: needs to be investigated why it's needed to select the size again. - int error = FT_Load_Glyph( ftFace, glyph.index, FT_LOAD_COLOR ); - if ( FT_Err_Ok == error ) + FT_Select_Size(ftFace, font.mFixedSizeIndex); ///< @todo: needs to be investigated why it's needed to select the size again. + int error = FT_Load_Glyph(ftFace, glyph.index, FT_LOAD_COLOR); + if(FT_Err_Ok == error) { - glyph.width = font.mFixedWidthPixels; - glyph.height = font.mFixedHeightPixels; - glyph.advance = font.mFixedWidthPixels; + glyph.width = font.mFixedWidthPixels; + glyph.height = font.mFixedHeightPixels; + glyph.advance = font.mFixedWidthPixels; glyph.xBearing = 0.0f; glyph.yBearing = font.mFixedHeightPixels; // Adjust the metrics if the fixed-size font should be down-scaled - const float desiredFixedSize = static_cast( font.mRequestedPointSize ) * FROM_266 / POINTS_PER_INCH * mDpiVertical; + const float desiredFixedSize = static_cast(font.mRequestedPointSize) * FROM_266 / POINTS_PER_INCH * mDpiVertical; - if( desiredFixedSize > 0.f ) + if(desiredFixedSize > 0.f) { const float scaleFactor = desiredFixedSize / font.mFixedHeightPixels; - glyph.width = glyph.width * scaleFactor ; - glyph.height = glyph.height * scaleFactor; - glyph.advance = glyph.advance * scaleFactor; + glyph.width = glyph.width * scaleFactor; + glyph.height = glyph.height * scaleFactor; + glyph.advance = glyph.advance * scaleFactor; glyph.xBearing = glyph.xBearing * scaleFactor; glyph.yBearing = glyph.yBearing * scaleFactor; @@ -1250,7 +1245,7 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::GetBitmapMetrics. FreeType Bitmap Load_Glyph error %d\n", error); success = false; } } @@ -1260,41 +1255,41 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap. // i.e. with the SNum-3R font. // @todo: add an option to use the FT_LOAD_DEFAULT if required? - int error = FT_Load_Glyph( ftFace, glyph.index, FT_LOAD_NO_AUTOHINT ); + int error = FT_Load_Glyph(ftFace, glyph.index, FT_LOAD_NO_AUTOHINT); // Keep the width of the glyph before doing the software emboldening. // It will be used to calculate a scale factor to be applied to the // advance as Harfbuzz doesn't apply any SW emboldening to calculate // the advance of the glyph. - const float width = static_cast< float >( ftFace->glyph->metrics.width ) * FROM_266; + const float width = static_cast(ftFace->glyph->metrics.width) * FROM_266; - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - const bool isEmboldeningRequired = glyph.isBoldRequired && !( ftFace->style_flags & FT_STYLE_FLAG_BOLD ); - if( isEmboldeningRequired ) + const bool isEmboldeningRequired = glyph.isBoldRequired && !(ftFace->style_flags & FT_STYLE_FLAG_BOLD); + if(isEmboldeningRequired) { // Does the software bold. - FT_GlyphSlot_Embolden( ftFace->glyph ); + FT_GlyphSlot_Embolden(ftFace->glyph); } - glyph.width = static_cast< float >( ftFace->glyph->metrics.width ) * FROM_266; - glyph.height = static_cast< float >( ftFace->glyph->metrics.height ) * FROM_266; - if( horizontal ) + glyph.width = static_cast(ftFace->glyph->metrics.width) * FROM_266; + glyph.height = static_cast(ftFace->glyph->metrics.height) * FROM_266; + if(horizontal) { - glyph.xBearing += static_cast< float >( ftFace->glyph->metrics.horiBearingX ) * FROM_266; - glyph.yBearing += static_cast< float >( ftFace->glyph->metrics.horiBearingY ) * FROM_266; + glyph.xBearing += static_cast(ftFace->glyph->metrics.horiBearingX) * FROM_266; + glyph.yBearing += static_cast(ftFace->glyph->metrics.horiBearingY) * FROM_266; } else { - glyph.xBearing += static_cast< float >( ftFace->glyph->metrics.vertBearingX ) * FROM_266; - glyph.yBearing += static_cast< float >( ftFace->glyph->metrics.vertBearingY ) * FROM_266; + glyph.xBearing += static_cast(ftFace->glyph->metrics.vertBearingX) * FROM_266; + glyph.yBearing += static_cast(ftFace->glyph->metrics.vertBearingY) * FROM_266; } - if( isEmboldeningRequired && !Dali::EqualsZero( width ) ) + if(isEmboldeningRequired && !Dali::EqualsZero(width)) { // If the glyph is emboldened by software, the advance is multiplied by a // scale factor to make it slightly bigger. - glyph.advance *= ( glyph.width / width ); + glyph.advance *= (glyph.width / width); } // Use the bounding box of the bitmap to correct the metrics. @@ -1303,17 +1298,17 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, // font's point size. FT_Glyph ftGlyph; - error = FT_Get_Glyph( ftFace->glyph, &ftGlyph ); + error = FT_Get_Glyph(ftFace->glyph, &ftGlyph); FT_BBox bbox; - FT_Glyph_Get_CBox( ftGlyph, FT_GLYPH_BBOX_GRIDFIT, &bbox ); + FT_Glyph_Get_CBox(ftGlyph, FT_GLYPH_BBOX_GRIDFIT, &bbox); const float descender = glyph.height - glyph.yBearing; - glyph.height = ( bbox.yMax - bbox.yMin) * FROM_266; - glyph.yBearing = glyph.height - round( descender ); + glyph.height = (bbox.yMax - bbox.yMin) * FROM_266; + glyph.yBearing = glyph.height - round(descender); // Created FT_Glyph object must be released with FT_Done_Glyph - FT_Done_Glyph( ftGlyph ); + FT_Done_Glyph(ftGlyph); } else { @@ -1327,21 +1322,21 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, BitmapFontCacheItem& bitmapFontCacheItem = mBitmapFontCache[fontIdCacheItem.id]; unsigned int index = 0u; - for( auto& item : bitmapFontCacheItem.font.glyphs ) + for(auto& item : bitmapFontCacheItem.font.glyphs) { - if( item.utf32 == glyph.index ) + if(item.utf32 == glyph.index) { Devel::PixelBuffer& pixelBuffer = bitmapFontCacheItem.pixelBuffers[index]; - if( !pixelBuffer ) + if(!pixelBuffer) { - pixelBuffer = LoadImageFromFile( item.url ); + pixelBuffer = LoadImageFromFile(item.url); } - glyph.width = static_cast< float >( pixelBuffer.GetWidth() ); - glyph.height = static_cast< float >( pixelBuffer.GetHeight() ); - glyph.xBearing = 0.f; - glyph.yBearing = glyph.height + item.descender; - glyph.advance = glyph.width; + glyph.width = static_cast(pixelBuffer.GetWidth()); + glyph.height = static_cast(pixelBuffer.GetHeight()); + glyph.xBearing = 0.f; + glyph.yBearing = glyph.height + item.descender; + glyph.advance = glyph.width; glyph.scaleFactor = 1.f; break; } @@ -1360,15 +1355,15 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, else { // Check if it's an embedded image. - if( ( 0u == glyph.fontId ) && ( 0u != glyph.index ) && ( glyph.index <= mEmbeddedItemCache.Count() ) ) + if((0u == glyph.fontId) && (0u != glyph.index) && (glyph.index <= mEmbeddedItemCache.Count())) { const EmbeddedItem& item = mEmbeddedItemCache[glyph.index - 1u]; - glyph.width = static_cast( item.width ); - glyph.height = static_cast( item.height ); - glyph.xBearing = 0.f; - glyph.yBearing = glyph.height; - glyph.advance = glyph.width; + glyph.width = static_cast(item.width); + glyph.height = static_cast(item.height); + glyph.xBearing = 0.f; + glyph.yBearing = glyph.height; + glyph.advance = glyph.width; glyph.scaleFactor = 1.f; } else @@ -1381,36 +1376,36 @@ bool FontClient::Plugin::GetBitmapMetrics( GlyphInfo* array, return success; } -bool FontClient::Plugin::GetVectorMetrics( GlyphInfo* array, - uint32_t size, - bool horizontal ) +bool FontClient::Plugin::GetVectorMetrics(GlyphInfo* array, + uint32_t size, + bool horizontal) { #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING - bool success( true ); + bool success(true); - for( unsigned int i = 0u; i < size; ++i ) + for(unsigned int i = 0u; i < size; ++i) { FontId fontId = array[i].fontId; - if( ( fontId > 0u ) && - ( fontId - 1u ) < mFontIdCache.Count() ) + if((fontId > 0u) && + (fontId - 1u) < mFontIdCache.Count()) { FontFaceCacheItem& font = mFontFaceCache[mFontIdCache[fontId - 1u].id]; - if( ! font.mVectorFontId ) + if(!font.mVectorFontId) { - font.mVectorFontId = mVectorFontCache->GetFontId( font.mPath ); + font.mVectorFontId = mVectorFontCache->GetFontId(font.mPath); } - mVectorFontCache->GetGlyphMetrics( font.mVectorFontId, array[i] ); + mVectorFontCache->GetGlyphMetrics(font.mVectorFontId, array[i]); // Vector metrics are in EMs, convert to pixels - const float scale = ( static_cast( font.mRequestedPointSize ) * FROM_266 ) * static_cast( mDpiVertical ) / POINTS_PER_INCH; - array[i].width *= scale; - array[i].height *= scale; + const float scale = (static_cast(font.mRequestedPointSize) * FROM_266) * static_cast(mDpiVertical) / POINTS_PER_INCH; + array[i].width *= scale; + array[i].height *= scale; array[i].xBearing *= scale; array[i].yBearing *= scale; - array[i].advance *= scale; + array[i].advance *= scale; } else { @@ -1424,19 +1419,19 @@ bool FontClient::Plugin::GetVectorMetrics( GlyphInfo* array, #endif } -void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth ) +void FontClient::Plugin::CreateBitmap(FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth) { const FontId index = fontId - 1u; - if( ( fontId > 0u ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0u) && + (index < mFontIdCache.Count())) { data.isColorBitmap = false; - data.isColorEmoji = false; + data.isColorEmoji = false; const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { @@ -1444,15 +1439,15 @@ void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, boo bool isShearRequired = false; const FontFaceCacheItem& fontFaceCacheItem = mFontFaceCache[fontIdCacheItem.id]; - FT_Face ftFace = fontFaceCacheItem.mFreeTypeFace; + FT_Face ftFace = fontFaceCacheItem.mFreeTypeFace; FT_Error error; #ifdef FREETYPE_BITMAP_SUPPORT // Check to see if this is fixed size bitmap - if( fontFaceCacheItem.mIsFixedSizeBitmap ) + if(fontFaceCacheItem.mIsFixedSizeBitmap) { - error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_COLOR ); + error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_COLOR); } else #endif @@ -1460,115 +1455,115 @@ void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, boo // FT_LOAD_DEFAULT causes some issues in the alignment of the glyph inside the bitmap. // i.e. with the SNum-3R font. // @todo: add an option to use the FT_LOAD_DEFAULT if required? - error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_NO_AUTOHINT ); + error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_NO_AUTOHINT); } - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - if( isBoldRequired && !( ftFace->style_flags & FT_STYLE_FLAG_BOLD ) ) + if(isBoldRequired && !(ftFace->style_flags & FT_STYLE_FLAG_BOLD)) { // Does the software bold. - FT_GlyphSlot_Embolden( ftFace->glyph ); + FT_GlyphSlot_Embolden(ftFace->glyph); } - if( isItalicRequired && !( ftFace->style_flags & FT_STYLE_FLAG_ITALIC ) ) + if(isItalicRequired && !(ftFace->style_flags & FT_STYLE_FLAG_ITALIC)) { // Will do the software italic. isShearRequired = true; } FT_Glyph glyph; - error = FT_Get_Glyph( ftFace->glyph, &glyph ); + error = FT_Get_Glyph(ftFace->glyph, &glyph); // Convert to bitmap if necessary - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - if( glyph->format != FT_GLYPH_FORMAT_BITMAP ) + if(glyph->format != FT_GLYPH_FORMAT_BITMAP) { - int offsetX = 0, offsetY = 0; - bool isOutlineGlyph = ( glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0 ); + int offsetX = 0, offsetY = 0; + bool isOutlineGlyph = (glyph->format == FT_GLYPH_FORMAT_OUTLINE && outlineWidth > 0); // Create a bitmap for the outline - if( isOutlineGlyph ) + if(isOutlineGlyph) { // Retrieve the horizontal and vertical distance from the current pen position to the // left and top border of the glyph bitmap for a normal glyph before applying the outline. - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { FT_Glyph normalGlyph; - error = FT_Get_Glyph( ftFace->glyph, &normalGlyph ); + error = FT_Get_Glyph(ftFace->glyph, &normalGlyph); - error = FT_Glyph_To_Bitmap( &normalGlyph, FT_RENDER_MODE_NORMAL, 0, 1 ); - if( FT_Err_Ok == error ) + error = FT_Glyph_To_Bitmap(&normalGlyph, FT_RENDER_MODE_NORMAL, 0, 1); + if(FT_Err_Ok == error) { - FT_BitmapGlyph bitmapGlyph = reinterpret_cast< FT_BitmapGlyph >( normalGlyph ); + FT_BitmapGlyph bitmapGlyph = reinterpret_cast(normalGlyph); offsetX = bitmapGlyph->left; offsetY = bitmapGlyph->top; } // Created FT_Glyph object must be released with FT_Done_Glyph - FT_Done_Glyph( normalGlyph ); + FT_Done_Glyph(normalGlyph); } // Now apply the outline // Set up a stroker FT_Stroker stroker; - error = FT_Stroker_New( mFreeTypeLibrary, &stroker ); + error = FT_Stroker_New(mFreeTypeLibrary, &stroker); - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - FT_Stroker_Set( stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0 ); - error = FT_Glyph_StrokeBorder( &glyph, stroker, 0, 1 ); + FT_Stroker_Set(stroker, outlineWidth * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0); + error = FT_Glyph_StrokeBorder(&glyph, stroker, 0, 1); - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - FT_Stroker_Done( stroker ); + FT_Stroker_Done(stroker); } else { - DALI_LOG_ERROR( "FT_Glyph_StrokeBorder Failed with error: %d\n", error ); + DALI_LOG_ERROR("FT_Glyph_StrokeBorder Failed with error: %d\n", error); } } else { - DALI_LOG_ERROR( "FT_Stroker_New Failed with error: %d\n", error ); + DALI_LOG_ERROR("FT_Stroker_New Failed with error: %d\n", error); } } - error = FT_Glyph_To_Bitmap( &glyph, FT_RENDER_MODE_NORMAL, 0, 1 ); - if( FT_Err_Ok == error ) + error = FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); + if(FT_Err_Ok == error) { - FT_BitmapGlyph bitmapGlyph = reinterpret_cast< FT_BitmapGlyph >( glyph ); + FT_BitmapGlyph bitmapGlyph = reinterpret_cast(glyph); - if( isOutlineGlyph ) + if(isOutlineGlyph) { // Calculate the additional horizontal and vertical offsets needed for the position of the outline glyph data.outlineOffsetX = offsetX - bitmapGlyph->left - outlineWidth; data.outlineOffsetY = bitmapGlyph->top - offsetY - outlineWidth; } - ConvertBitmap( data, bitmapGlyph->bitmap, isShearRequired ); + ConvertBitmap(data, bitmapGlyph->bitmap, isShearRequired); } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Get_Glyph Failed with error: %d\n", error); } } else { - ConvertBitmap( data, ftFace->glyph->bitmap, isShearRequired ); + ConvertBitmap(data, ftFace->glyph->bitmap, isShearRequired); } data.isColorEmoji = fontFaceCacheItem.mIsFixedSizeBitmap; // Created FT_Glyph object must be released with FT_Done_Glyph - FT_Done_Glyph( glyph ); + FT_Done_Glyph(glyph); } } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::CreateBitmap. FT_Load_Glyph Failed with error: %d\n", error); } break; } @@ -1577,22 +1572,22 @@ void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, boo BitmapFontCacheItem& bitmapFontCacheItem = mBitmapFontCache[fontIdCacheItem.id]; unsigned int index = 0u; - for( auto& item : bitmapFontCacheItem.font.glyphs ) + for(auto& item : bitmapFontCacheItem.font.glyphs) { - if( item.utf32 == glyphIndex ) + if(item.utf32 == glyphIndex) { Devel::PixelBuffer& pixelBuffer = bitmapFontCacheItem.pixelBuffers[index]; - if( !pixelBuffer ) + if(!pixelBuffer) { - pixelBuffer = LoadImageFromFile( item.url ); + pixelBuffer = LoadImageFromFile(item.url); } - data.width = pixelBuffer.GetWidth(); + data.width = pixelBuffer.GetWidth(); data.height = pixelBuffer.GetHeight(); data.isColorBitmap = bitmapFontCacheItem.font.isColorFont; - ConvertBitmap( data, data.width, data.height, pixelBuffer.GetBuffer() ); + ConvertBitmap(data, data.width, data.height, pixelBuffer.GetBuffer()); // Sets the pixel format. data.format = pixelBuffer.GetPixelFormat(); @@ -1610,19 +1605,19 @@ void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, boo } else { - if( ( 0u != glyphIndex ) && ( glyphIndex <= mEmbeddedItemCache.Count() ) ) + if((0u != glyphIndex) && (glyphIndex <= mEmbeddedItemCache.Count())) { // It's an embedded item. const EmbeddedItem& item = mEmbeddedItemCache[glyphIndex - 1u]; - data.width = item.width; + data.width = item.width; data.height = item.height; - if( 0u != item.pixelBufferId ) + if(0u != item.pixelBufferId) { - Devel::PixelBuffer pixelBuffer = mPixelBufferCache[item.pixelBufferId-1u].pixelBuffer; - if( pixelBuffer ) + Devel::PixelBuffer pixelBuffer = mPixelBufferCache[item.pixelBufferId - 1u].pixelBuffer; + if(pixelBuffer) { - ConvertBitmap( data, pixelBuffer.GetWidth(), pixelBuffer.GetHeight(), pixelBuffer.GetBuffer() ); + ConvertBitmap(data, pixelBuffer.GetWidth(), pixelBuffer.GetHeight(), pixelBuffer.GetBuffer()); // Sets the pixel format. data.format = pixelBuffer.GetPixelFormat(); @@ -1632,9 +1627,9 @@ void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, boo { // Creates the output buffer const unsigned int bufferSize = data.width * data.height * 4u; - data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[]. + data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[]. - memset( data.buffer, 0u, bufferSize ); + memset(data.buffer, 0u, bufferSize); // Just creates a void buffer. Doesn't matter what pixel format is set as is the application code the responsible of filling it. } @@ -1642,109 +1637,109 @@ void FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, boo } } -PixelData FontClient::Plugin::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth ) +PixelData FontClient::Plugin::CreateBitmap(FontId fontId, GlyphIndex glyphIndex, int outlineWidth) { TextAbstraction::FontClient::GlyphBufferData data; - CreateBitmap( fontId, glyphIndex, false, false, data, outlineWidth ); + CreateBitmap(fontId, glyphIndex, false, false, data, outlineWidth); - return PixelData::New( data.buffer, - data.width * data.height * Pixel::GetBytesPerPixel( data.format ), - data.width, - data.height, - data.format, - PixelData::DELETE_ARRAY ); + return PixelData::New(data.buffer, + data.width * data.height * Pixel::GetBytesPerPixel(data.format), + data.width, + data.height, + data.format, + PixelData::DELETE_ARRAY); } -void FontClient::Plugin::CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight ) +void FontClient::Plugin::CreateVectorBlob(FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight) { - blob = nullptr; + blob = nullptr; blobLength = 0; #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING - if( ( fontId > 0u ) && - ( fontId - 1u < mFontIdCache.Count() ) ) + if((fontId > 0u) && + (fontId - 1u < mFontIdCache.Count())) { - const FontId fontFaceId = mFontIdCache[fontId - 1u].id; - FontFaceCacheItem& font = mFontFaceCache[fontFaceId]; + const FontId fontFaceId = mFontIdCache[fontId - 1u].id; + FontFaceCacheItem& font = mFontFaceCache[fontFaceId]; - if( ! font.mVectorFontId ) + if(!font.mVectorFontId) { - font.mVectorFontId = mVectorFontCache->GetFontId( font.mPath ); + font.mVectorFontId = mVectorFontCache->GetFontId(font.mPath); } - mVectorFontCache->GetVectorBlob( font.mVectorFontId, fontFaceId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight ); + mVectorFontCache->GetVectorBlob(font.mVectorFontId, fontFaceId, glyphIndex, blob, blobLength, nominalWidth, nominalHeight); } #endif } -const GlyphInfo& FontClient::Plugin::GetEllipsisGlyph( PointSize26Dot6 requestedPointSize ) +const GlyphInfo& FontClient::Plugin::GetEllipsisGlyph(PointSize26Dot6 requestedPointSize) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::GetEllipsisGlyph\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize %d.\n", requestedPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::GetEllipsisGlyph\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize %d.\n", requestedPointSize); // First look into the cache if there is an ellipsis glyph for the requested point size. - for( const auto& item : mEllipsisCache ) + for(const auto& item : mEllipsisCache) { - if( item.requestedPointSize == requestedPointSize ) + if(item.requestedPointSize == requestedPointSize) { // Use the glyph in the cache. - DALI_LOG_INFO( gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index ); - DALI_LOG_INFO( gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index); + DALI_LOG_INFO(gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n"); return item.glyph; } } // No glyph has been found. Create one. - mEllipsisCache.PushBack( EllipsisItem() ); - EllipsisItem& item = *( mEllipsisCache.End() - 1u ); + mEllipsisCache.PushBack(EllipsisItem()); + EllipsisItem& item = *(mEllipsisCache.End() - 1u); item.requestedPointSize = requestedPointSize; // Find a font for the ellipsis glyph. - item.glyph.fontId = FindDefaultFont( ELLIPSIS_CHARACTER, - requestedPointSize, - false ); + item.glyph.fontId = FindDefaultFont(ELLIPSIS_CHARACTER, + requestedPointSize, + false); // Set the character index to access the glyph inside the font. - item.glyph.index = FT_Get_Char_Index( mFontFaceCache[mFontIdCache[item.glyph.fontId-1u].id].mFreeTypeFace, - ELLIPSIS_CHARACTER ); + item.glyph.index = FT_Get_Char_Index(mFontFaceCache[mFontIdCache[item.glyph.fontId - 1u].id].mFreeTypeFace, + ELLIPSIS_CHARACTER); - GetBitmapMetrics( &item.glyph, 1u, true ); + GetBitmapMetrics(&item.glyph, 1u, true); - DALI_LOG_INFO( gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index ); - DALI_LOG_INFO( gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " glyph id %d found in the cache.\n", item.glyph.index); + DALI_LOG_INFO(gLogFilter, Debug::General, " font %d.\n", item.glyph.fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::GetEllipsisGlyph\n"); return item.glyph; } -bool FontClient::Plugin::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex ) +bool FontClient::Plugin::IsColorGlyph(FontId fontId, GlyphIndex glyphIndex) { FT_Error error = -1; const FontId index = fontId - 1u; - if( ( fontId > 0u ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0u) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - switch( fontIdCacheItem.type ) + switch(fontIdCacheItem.type) { case FontDescription::FACE_FONT: { #ifdef FREETYPE_BITMAP_SUPPORT - const FontFaceCacheItem& item = mFontFaceCache[fontIdCacheItem.id]; - FT_Face ftFace = item.mFreeTypeFace; + const FontFaceCacheItem& item = mFontFaceCache[fontIdCacheItem.id]; + FT_Face ftFace = item.mFreeTypeFace; // Check to see if this is fixed size bitmap - if( item.mHasColorTables ) + if(item.mHasColorTables) { - error = FT_Load_Glyph( ftFace, glyphIndex, FT_LOAD_COLOR ); + error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_COLOR); } #endif break; @@ -1764,17 +1759,17 @@ bool FontClient::Plugin::IsColorGlyph( FontId fontId, GlyphIndex glyphIndex ) return FT_Err_Ok == error; } -FT_FaceRec_* FontClient::Plugin::GetFreetypeFace( FontId fontId ) +FT_FaceRec_* FontClient::Plugin::GetFreetypeFace(FontId fontId) { FT_Face fontFace = nullptr; const FontId index = fontId - 1u; - if( ( fontId > 0u ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0u) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - if( FontDescription::FACE_FONT == fontIdCacheItem.type ) + if(FontDescription::FACE_FONT == fontIdCacheItem.type) { fontFace = mFontFaceCache[fontIdCacheItem.id].mFreeTypeFace; } @@ -1782,42 +1777,42 @@ FT_FaceRec_* FontClient::Plugin::GetFreetypeFace( FontId fontId ) return fontFace; } -FontDescription::Type FontClient::Plugin::GetFontType( FontId fontId ) +FontDescription::Type FontClient::Plugin::GetFontType(FontId fontId) { const FontId index = fontId - 1u; - if( ( fontId > 0u ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0u) && + (index < mFontIdCache.Count())) { return mFontIdCache[index].type; } return FontDescription::INVALID; } -bool FontClient::Plugin::AddCustomFontDirectory( const FontPath& path ) +bool FontClient::Plugin::AddCustomFontDirectory(const FontPath& path) { // nullptr as first parameter means the current configuration is used. - return FcConfigAppFontAddDir( nullptr, reinterpret_cast( path.c_str() ) ); + return FcConfigAppFontAddDir(nullptr, reinterpret_cast(path.c_str())); } -GlyphIndex FontClient::Plugin::CreateEmbeddedItem( const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat ) +GlyphIndex FontClient::Plugin::CreateEmbeddedItem(const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat) { EmbeddedItem embeddedItem; embeddedItem.pixelBufferId = 0u; - embeddedItem.width = description.width; - embeddedItem.height = description.height; + embeddedItem.width = description.width; + embeddedItem.height = description.height; pixelFormat = Pixel::A8; - if( !description.url.empty() ) + if(!description.url.empty()) { // Check if the url is in the cache. PixelBufferId index = 0u; - for( const auto& cacheItem : mPixelBufferCache ) + for(const auto& cacheItem : mPixelBufferCache) { ++index; - if( cacheItem.url == description.url ) + if(cacheItem.url == description.url) { // The url is in the pixel buffer cache. // Set the index +1 to the vector. @@ -1827,20 +1822,20 @@ GlyphIndex FontClient::Plugin::CreateEmbeddedItem( const TextAbstraction::FontCl } Devel::PixelBuffer pixelBuffer; - if( 0u == embeddedItem.pixelBufferId ) + if(0u == embeddedItem.pixelBufferId) { // The pixel buffer is not in the cache. Create one and cache it. // Load the image from the url. - pixelBuffer = LoadImageFromFile( description.url ); + pixelBuffer = LoadImageFromFile(description.url); // Create the cache item. PixelBufferCacheItem pixelBufferCacheItem; pixelBufferCacheItem.pixelBuffer = pixelBuffer; - pixelBufferCacheItem.url = description.url; + pixelBufferCacheItem.url = description.url; // Store the cache item in the cache. - mPixelBufferCache.push_back( std::move( pixelBufferCacheItem ) ); + mPixelBufferCache.push_back(std::move(pixelBufferCacheItem)); // Set the pixel buffer id to the embedded item. embeddedItem.pixelBufferId = mPixelBufferCache.size(); @@ -1848,20 +1843,20 @@ GlyphIndex FontClient::Plugin::CreateEmbeddedItem( const TextAbstraction::FontCl else { // Retrieve the pixel buffer from the cache to set the pixel format. - pixelBuffer = mPixelBufferCache[embeddedItem.pixelBufferId-1u].pixelBuffer; + pixelBuffer = mPixelBufferCache[embeddedItem.pixelBufferId - 1u].pixelBuffer; } - if( pixelBuffer ) + if(pixelBuffer) { // Set the size of the embedded item if it has not been set. - if( 0u == embeddedItem.width ) + if(0u == embeddedItem.width) { - embeddedItem.width = static_cast( pixelBuffer.GetWidth() ); + embeddedItem.width = static_cast(pixelBuffer.GetWidth()); } - if( 0u == embeddedItem.height ) + if(0u == embeddedItem.height) { - embeddedItem.height = static_cast( pixelBuffer.GetHeight() ); + embeddedItem.height = static_cast(pixelBuffer.GetHeight()); } // Set the pixel format. @@ -1871,169 +1866,169 @@ GlyphIndex FontClient::Plugin::CreateEmbeddedItem( const TextAbstraction::FontCl // Find if the same embeddedItem has already been created. unsigned int index = 0u; - for( const auto& item : mEmbeddedItemCache ) + for(const auto& item : mEmbeddedItemCache) { ++index; - if( ( item.pixelBufferId == embeddedItem.pixelBufferId ) && - ( item.width == embeddedItem.width ) && - ( item.height == embeddedItem.height ) ) + if((item.pixelBufferId == embeddedItem.pixelBufferId) && + (item.width == embeddedItem.width) && + (item.height == embeddedItem.height)) { return index; } } // Cache the embedded item. - mEmbeddedItemCache.PushBack( embeddedItem ); + mEmbeddedItemCache.PushBack(embeddedItem); return mEmbeddedItemCache.Count(); } void FontClient::Plugin::InitSystemFonts() { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::InitSystemFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::InitSystemFonts\n"); FcFontSet* fontSet = GetFcFontSet(); // Creates a FcFontSet that needs to be destroyed by calling FcFontSetDestroy. - if( fontSet ) + if(fontSet) { - DALI_LOG_INFO( gLogFilter, Debug::General, " number of system fonts : %d\n", fontSet->nfont ); + DALI_LOG_INFO(gLogFilter, Debug::General, " number of system fonts : %d\n", fontSet->nfont); // Reserve some space to avoid reallocations. - mSystemFonts.reserve( fontSet->nfont ); + mSystemFonts.reserve(fontSet->nfont); - for( int i = 0u; i < fontSet->nfont; ++i ) + for(int i = 0u; i < fontSet->nfont; ++i) { FcPattern* fontPattern = fontSet->fonts[i]; FontPath path; // Skip fonts with no path - if( GetFcString( fontPattern, FC_FILE, path ) ) + if(GetFcString(fontPattern, FC_FILE, path)) { - mSystemFonts.push_back( FontDescription() ); + mSystemFonts.push_back(FontDescription()); FontDescription& fontDescription = mSystemFonts.back(); - fontDescription.path = std::move( path ); + fontDescription.path = std::move(path); - int width = 0; + int width = 0; int weight = 0; - int slant = 0; - GetFcString( fontPattern, FC_FAMILY, fontDescription.family ); - GetFcInt( fontPattern, FC_WIDTH, width ); - GetFcInt( fontPattern, FC_WEIGHT, weight ); - GetFcInt( fontPattern, FC_SLANT, slant ); - fontDescription.width = IntToWidthType( width ); - fontDescription.weight = IntToWeightType( weight ); - fontDescription.slant = IntToSlantType( slant ); - - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); + int slant = 0; + GetFcString(fontPattern, FC_FAMILY, fontDescription.family); + GetFcInt(fontPattern, FC_WIDTH, width); + GetFcInt(fontPattern, FC_WEIGHT, weight); + GetFcInt(fontPattern, FC_SLANT, slant); + fontDescription.width = IntToWidthType(width); + fontDescription.weight = IntToWeightType(weight); + fontDescription.slant = IntToSlantType(slant); + + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); } } // Destroys the font set created. - FcFontSetDestroy( fontSet ); + FcFontSetDestroy(fontSet); } - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::InitSystemFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::InitSystemFonts\n"); } -bool FontClient::Plugin::MatchFontDescriptionToPattern( FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, FcCharSet** characterSet ) +bool FontClient::Plugin::MatchFontDescriptionToPattern(FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, FcCharSet** characterSet) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::MatchFontDescriptionToPattern\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::MatchFontDescriptionToPattern\n"); - FcResult result = FcResultMatch; - FcPattern* match = FcFontMatch( nullptr /* use default configure */, pattern, &result ); // Creates a new font pattern that needs to be destroyed by calling FcPatternDestroy. + FcResult result = FcResultMatch; + FcPattern* match = FcFontMatch(nullptr /* use default configure */, pattern, &result); // Creates a new font pattern that needs to be destroyed by calling FcPatternDestroy. const bool matched = nullptr != match; - DALI_LOG_INFO( gLogFilter, Debug::General, " pattern matched : %s\n", ( matched ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::General, " pattern matched : %s\n", (matched ? "true" : "false")); - if( matched ) + if(matched) { - int width = 0; + int width = 0; int weight = 0; - int slant = 0; - GetFcString( match, FC_FILE, fontDescription.path ); - GetFcString( match, FC_FAMILY, fontDescription.family ); - GetFcInt( match, FC_WIDTH, width ); - GetFcInt( match, FC_WEIGHT, weight ); - GetFcInt( match, FC_SLANT, slant ); - fontDescription.width = IntToWidthType( width ); - fontDescription.weight = IntToWeightType( weight ); - fontDescription.slant = IntToSlantType( slant ); + int slant = 0; + GetFcString(match, FC_FILE, fontDescription.path); + GetFcString(match, FC_FAMILY, fontDescription.family); + GetFcInt(match, FC_WIDTH, width); + GetFcInt(match, FC_WEIGHT, weight); + GetFcInt(match, FC_SLANT, slant); + fontDescription.width = IntToWidthType(width); + fontDescription.weight = IntToWeightType(weight); + fontDescription.slant = IntToSlantType(slant); // Retrieve the character set and increase the reference counter. - FcPatternGetCharSet( match, FC_CHARSET, 0u, characterSet ); - *characterSet = FcCharSetCopy( *characterSet ); + FcPatternGetCharSet(match, FC_CHARSET, 0u, characterSet); + *characterSet = FcCharSetCopy(*characterSet); // destroyed the matched pattern - FcPatternDestroy( match ); + FcPatternDestroy(match); - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); } - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::MatchFontDescriptionToPattern\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::MatchFontDescriptionToPattern\n"); return matched; } -FcPattern* FontClient::Plugin::CreateFontFamilyPattern( const FontDescription& fontDescription ) const +FcPattern* FontClient::Plugin::CreateFontFamilyPattern(const FontDescription& fontDescription) const { // create the cached font family lookup pattern // a pattern holds a set of names, each name refers to a property of the font FcPattern* fontFamilyPattern = FcPatternCreate(); // FcPatternCreate creates a new pattern that needs to be destroyed by calling FcPatternDestroy. - if( !fontFamilyPattern ) + if(!fontFamilyPattern) { return nullptr; } // add a property to the pattern for the font family - FcPatternAddString( fontFamilyPattern, FC_FAMILY, reinterpret_cast( fontDescription.family.c_str() ) ); + FcPatternAddString(fontFamilyPattern, FC_FAMILY, reinterpret_cast(fontDescription.family.c_str())); // add a property to the pattern for local setting. - const char* locale = setlocale( LC_MESSAGES, nullptr ); - if( locale != nullptr) + const char* locale = setlocale(LC_MESSAGES, nullptr); + if(locale != nullptr) { - FcPatternAddString( fontFamilyPattern, FC_LANG, reinterpret_cast( locale ) ); + FcPatternAddString(fontFamilyPattern, FC_LANG, reinterpret_cast(locale)); } int width = FONT_WIDTH_TYPE_TO_INT[fontDescription.width]; - if( width < 0 ) + if(width < 0) { // Use default. width = DEFAULT_FONT_WIDTH; } int weight = FONT_WEIGHT_TYPE_TO_INT[fontDescription.weight]; - if( weight < 0 ) + if(weight < 0) { // Use default. weight = DEFAULT_FONT_WEIGHT; } int slant = FONT_SLANT_TYPE_TO_INT[fontDescription.slant]; - if( slant < 0 ) + if(slant < 0) { // Use default. slant = DEFAULT_FONT_SLANT; } - FcPatternAddInteger( fontFamilyPattern, FC_WIDTH, width ); - FcPatternAddInteger( fontFamilyPattern, FC_WEIGHT, weight ); - FcPatternAddInteger( fontFamilyPattern, FC_SLANT, slant ); + FcPatternAddInteger(fontFamilyPattern, FC_WIDTH, width); + FcPatternAddInteger(fontFamilyPattern, FC_WEIGHT, weight); + FcPatternAddInteger(fontFamilyPattern, FC_SLANT, slant); // modify the config, with the mFontFamilyPatterm - FcConfigSubstitute( nullptr /* use default configure */, fontFamilyPattern, FcMatchPattern ); + FcConfigSubstitute(nullptr /* use default configure */, fontFamilyPattern, FcMatchPattern); // provide default values for unspecified properties in the font pattern // e.g. patterns without a specified style or weight are set to Medium - FcDefaultSubstitute( fontFamilyPattern ); + FcDefaultSubstitute(fontFamilyPattern); return fontFamilyPattern; } @@ -2046,46 +2041,46 @@ _FcFontSet* FontClient::Plugin::GetFcFontSet() const // a pattern holds a set of names, each name refers to a property of the font FcPattern* pattern = FcPatternCreate(); - if( nullptr != pattern ) + if(nullptr != pattern) { // create an object set used to define which properties are to be returned in the patterns from FcFontList. FcObjectSet* objectSet = FcObjectSetCreate(); - if( nullptr != objectSet ) + if(nullptr != objectSet) { // build an object set from a list of property names - FcObjectSetAdd( objectSet, FC_FILE ); - FcObjectSetAdd( objectSet, FC_FAMILY ); - FcObjectSetAdd( objectSet, FC_WIDTH ); - FcObjectSetAdd( objectSet, FC_WEIGHT ); - FcObjectSetAdd( objectSet, FC_SLANT ); + FcObjectSetAdd(objectSet, FC_FILE); + FcObjectSetAdd(objectSet, FC_FAMILY); + FcObjectSetAdd(objectSet, FC_WIDTH); + FcObjectSetAdd(objectSet, FC_WEIGHT); + FcObjectSetAdd(objectSet, FC_SLANT); // get a list of fonts // creates patterns from those fonts containing only the objects in objectSet and returns the set of unique such patterns - fontset = FcFontList( nullptr /* the default configuration is checked to be up to date, and used */, pattern, objectSet ); // Creates a FcFontSet that needs to be destroyed by calling FcFontSetDestroy. + fontset = FcFontList(nullptr /* the default configuration is checked to be up to date, and used */, pattern, objectSet); // Creates a FcFontSet that needs to be destroyed by calling FcFontSetDestroy. // clear up the object set - FcObjectSetDestroy( objectSet ); + FcObjectSetDestroy(objectSet); } // clear up the pattern - FcPatternDestroy( pattern ); + FcPatternDestroy(pattern); } return fontset; } -bool FontClient::Plugin::GetFcString( const FcPattern* const pattern, - const char* const n, - std::string& string ) +bool FontClient::Plugin::GetFcString(const FcPattern* const pattern, + const char* const n, + std::string& string) { - FcChar8* file = nullptr; - const FcResult retVal = FcPatternGetString( pattern, n, 0u, &file ); + FcChar8* file = nullptr; + const FcResult retVal = FcPatternGetString(pattern, n, 0u, &file); - if( FcResultMatch == retVal ) + if(FcResultMatch == retVal) { // Have to use reinterpret_cast because FcChar8 is unsigned char*, not a const char*. - string.assign( reinterpret_cast( file ) ); + string.assign(reinterpret_cast(file)); return true; } @@ -2093,11 +2088,11 @@ bool FontClient::Plugin::GetFcString( const FcPattern* const pattern, return false; } -bool FontClient::Plugin::GetFcInt( const _FcPattern* const pattern, const char* const n, int& intVal ) +bool FontClient::Plugin::GetFcInt(const _FcPattern* const pattern, const char* const n, int& intVal) { - const FcResult retVal = FcPatternGetInteger( pattern, n, 0u, &intVal ); + const FcResult retVal = FcPatternGetInteger(pattern, n, 0u, &intVal); - if( FcResultMatch == retVal ) + if(FcResultMatch == retVal) { return true; } @@ -2105,82 +2100,82 @@ bool FontClient::Plugin::GetFcInt( const _FcPattern* const pattern, const char* return false; } -FontId FontClient::Plugin::CreateFont( const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex, - bool cacheDescription ) +FontId FontClient::Plugin::CreateFont(const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex, + bool cacheDescription) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::CreateFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::CreateFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " path : [%s]\n", path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); FontId id = 0u; // Create & cache new font face FT_Face ftFace; - int error = FT_New_Face( mFreeTypeLibrary, - path.c_str(), - 0, - &ftFace ); + int error = FT_New_Face(mFreeTypeLibrary, + path.c_str(), + 0, + &ftFace); - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { // Check if a font is scalable. - const bool isScalable = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_SCALABLE ) ); - const bool hasFixedSizedBitmaps = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_FIXED_SIZES ) ) && ( 0 != ftFace->num_fixed_sizes ); - const bool hasColorTables = ( 0 != ( ftFace->face_flags & FT_FACE_FLAG_COLOR ) ); - FontId fontFaceId = 0u; + const bool isScalable = (0 != (ftFace->face_flags & FT_FACE_FLAG_SCALABLE)); + const bool hasFixedSizedBitmaps = (0 != (ftFace->face_flags & FT_FACE_FLAG_FIXED_SIZES)) && (0 != ftFace->num_fixed_sizes); + const bool hasColorTables = (0 != (ftFace->face_flags & FT_FACE_FLAG_COLOR)); + FontId fontFaceId = 0u; - DALI_LOG_INFO( gLogFilter, Debug::General, " isScalable : [%s]\n", ( isScalable ? "true" : "false" ) ); - DALI_LOG_INFO( gLogFilter, Debug::General, " hasFixedSizedBitmaps : [%s]\n", ( hasFixedSizedBitmaps ? "true" : "false" ) ); - DALI_LOG_INFO( gLogFilter, Debug::General, " hasColorTables : [%s]\n", ( hasColorTables ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::General, " isScalable : [%s]\n", (isScalable ? "true" : "false")); + DALI_LOG_INFO(gLogFilter, Debug::General, " hasFixedSizedBitmaps : [%s]\n", (hasFixedSizedBitmaps ? "true" : "false")); + DALI_LOG_INFO(gLogFilter, Debug::General, " hasColorTables : [%s]\n", (hasColorTables ? "true" : "false")); // Check to see if the font contains fixed sizes? - if( !isScalable && hasFixedSizedBitmaps ) + if(!isScalable && hasFixedSizedBitmaps) { PointSize26Dot6 actualPointSize = 0u; - int fixedSizeIndex = 0; - for( ; fixedSizeIndex < ftFace->num_fixed_sizes; ++fixedSizeIndex ) + int fixedSizeIndex = 0; + for(; fixedSizeIndex < ftFace->num_fixed_sizes; ++fixedSizeIndex) { const PointSize26Dot6 fixedSize = ftFace->available_sizes[fixedSizeIndex].size; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " size index : %d, size : %d\n", fixedSizeIndex, fixedSize ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " size index : %d, size : %d\n", fixedSizeIndex, fixedSize); - if( fixedSize >= requestedPointSize ) + if(fixedSize >= requestedPointSize) { actualPointSize = fixedSize; break; } } - if( 0u == actualPointSize ) + if(0u == actualPointSize) { // The requested point size is bigger than the bigest fixed size. - fixedSizeIndex = ftFace->num_fixed_sizes - 1; + fixedSizeIndex = ftFace->num_fixed_sizes - 1; actualPointSize = ftFace->available_sizes[fixedSizeIndex].size; } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " size index : %d, actual size : %d\n", fixedSizeIndex, actualPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " size index : %d, actual size : %d\n", fixedSizeIndex, actualPointSize); // Tell Freetype to use this size - error = FT_Select_Size( ftFace, fixedSizeIndex ); - if ( FT_Err_Ok != error ) + error = FT_Select_Size(ftFace, fixedSizeIndex); + if(FT_Err_Ok != error) { - DALI_LOG_INFO( gLogFilter, Debug::General, "FreeType Select_Size error: %d\n", error ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FreeType Select_Size error: %d\n", error); } else { - const float fixedWidth = static_cast( ftFace->available_sizes[ fixedSizeIndex ].width ); - const float fixedHeight = static_cast( ftFace->available_sizes[ fixedSizeIndex ].height ); + const float fixedWidth = static_cast(ftFace->available_sizes[fixedSizeIndex].width); + const float fixedHeight = static_cast(ftFace->available_sizes[fixedSizeIndex].height); // Indicate that the font is a fixed sized bitmap - FontMetrics metrics( fixedHeight, // The ascender in pixels. - 0.0f, - fixedHeight, // The height in pixels. - 0.0f, - 0.0f ); + FontMetrics metrics(fixedHeight, // The ascender in pixels. + 0.0f, + fixedHeight, // The height in pixels. + 0.0f, + 0.0f); // Create the FreeType font face item to cache. - FontFaceCacheItem fontFaceCacheItem( ftFace, path, requestedPointSize, faceIndex, metrics, fixedSizeIndex, fixedWidth, fixedHeight, hasColorTables ); + FontFaceCacheItem fontFaceCacheItem(ftFace, path, requestedPointSize, faceIndex, metrics, fixedSizeIndex, fixedWidth, fixedHeight, hasColorTables); // Set the index to the font's id cache. fontFaceCacheItem.mFontId = mFontIdCache.Count(); @@ -2191,11 +2186,11 @@ FontId FontClient::Plugin::CreateFont( const FontPath& path, // Set the index to the FreeType font face cache. fontIdCacheItem.id = mFontFaceCache.size(); - fontFaceId = fontIdCacheItem.id + 1u; + fontFaceId = fontIdCacheItem.id + 1u; // Cache the items. - mFontFaceCache.push_back( fontFaceCacheItem ); - mFontIdCache.PushBack( fontIdCacheItem ); + mFontFaceCache.push_back(fontFaceCacheItem); + mFontIdCache.PushBack(fontIdCacheItem); // Set the font id to be returned. id = mFontIdCache.Count(); @@ -2203,25 +2198,24 @@ FontId FontClient::Plugin::CreateFont( const FontPath& path, } else { - error = FT_Set_Char_Size( ftFace, - 0, - requestedPointSize, - mDpiHorizontal, - mDpiVertical ); + error = FT_Set_Char_Size(ftFace, + 0, + requestedPointSize, + mDpiHorizontal, + mDpiVertical); - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - FT_Size_Metrics& ftMetrics = ftFace->size->metrics; - FontMetrics metrics( static_cast< float >( ftMetrics.ascender ) * FROM_266, - static_cast< float >( ftMetrics.descender ) * FROM_266, - static_cast< float >( ftMetrics.height ) * FROM_266, - static_cast< float >( ftFace->underline_position ) * FROM_266, - static_cast< float >( ftFace->underline_thickness ) * FROM_266 ); + FontMetrics metrics(static_cast(ftMetrics.ascender) * FROM_266, + static_cast(ftMetrics.descender) * FROM_266, + static_cast(ftMetrics.height) * FROM_266, + static_cast(ftFace->underline_position) * FROM_266, + static_cast(ftFace->underline_thickness) * FROM_266); // Create the FreeType font face item to cache. - FontFaceCacheItem fontFaceCacheItem( ftFace, path, requestedPointSize, faceIndex, metrics ); + FontFaceCacheItem fontFaceCacheItem(ftFace, path, requestedPointSize, faceIndex, metrics); // Set the index to the font's id cache. fontFaceCacheItem.mFontId = mFontIdCache.Count(); @@ -2232,87 +2226,87 @@ FontId FontClient::Plugin::CreateFont( const FontPath& path, // Set the index to the FreeType font face cache. fontIdCacheItem.id = mFontFaceCache.size(); - fontFaceId = fontIdCacheItem.id + 1u; + fontFaceId = fontIdCacheItem.id + 1u; // Cache the items. - mFontFaceCache.push_back( fontFaceCacheItem ); - mFontIdCache.PushBack( fontIdCacheItem ); + mFontFaceCache.push_back(fontFaceCacheItem); + mFontIdCache.PushBack(fontIdCacheItem); // Set the font id to be returned. id = mFontIdCache.Count(); } else { - DALI_LOG_INFO( gLogFilter, Debug::General, " FreeType Set_Char_Size error: %d for pointSize %d\n", error, requestedPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::General, " FreeType Set_Char_Size error: %d for pointSize %d\n", error, requestedPointSize); } } - if( 0u != fontFaceId ) + if(0u != fontFaceId) { - if( cacheDescription ) + if(cacheDescription) { - CacheFontPath( ftFace, fontFaceId, requestedPointSize, path ); + CacheFontPath(ftFace, fontFaceId, requestedPointSize, path); } } } else { - DALI_LOG_INFO( gLogFilter, Debug::General, " FreeType New_Face error: %d for [%s]\n", error, path.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::General, " FreeType New_Face error: %d for [%s]\n", error, path.c_str()); } - DALI_LOG_INFO( gLogFilter, Debug::General, " font id : %d\n", id ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::CreateFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font id : %d\n", id); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::CreateFont\n"); return id; } -void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, unsigned int srcWidth, unsigned int srcHeight, const unsigned char* const srcBuffer ) +void FontClient::Plugin::ConvertBitmap(TextAbstraction::FontClient::GlyphBufferData& data, unsigned int srcWidth, unsigned int srcHeight, const unsigned char* const srcBuffer) { // Set the input dimensions. - const ImageDimensions inputDimensions( srcWidth, srcHeight ); + const ImageDimensions inputDimensions(srcWidth, srcHeight); // Set the output dimensions. // If the output dimension is not given, the input dimension is set // and won't be downscaling. - data.width = ( data.width == 0 ) ? srcWidth : data.width; - data.height = ( data.height == 0 ) ? srcHeight : data.height; - const ImageDimensions desiredDimensions( data.width, data.height ); + data.width = (data.width == 0) ? srcWidth : data.width; + data.height = (data.height == 0) ? srcHeight : data.height; + const ImageDimensions desiredDimensions(data.width, data.height); // Creates the output buffer const unsigned int bufferSize = data.width * data.height * 4u; - data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[]. + data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[]. - if( inputDimensions == desiredDimensions ) + if(inputDimensions == desiredDimensions) { // There isn't downscaling. - memcpy( data.buffer, srcBuffer, bufferSize ); + memcpy(data.buffer, srcBuffer, bufferSize); } else { - Dali::Internal::Platform::LanczosSample4BPP( srcBuffer, - inputDimensions, - data.buffer, - desiredDimensions ); + Dali::Internal::Platform::LanczosSample4BPP(srcBuffer, + inputDimensions, + data.buffer, + desiredDimensions); } } -void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap, bool isShearRequired ) +void FontClient::Plugin::ConvertBitmap(TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap, bool isShearRequired) { - if( srcBitmap.width*srcBitmap.rows > 0 ) + if(srcBitmap.width * srcBitmap.rows > 0) { - switch( srcBitmap.pixel_mode ) + switch(srcBitmap.pixel_mode) { case FT_PIXEL_MODE_GRAY: { - if( srcBitmap.pitch == static_cast( srcBitmap.width ) ) + if(srcBitmap.pitch == static_cast(srcBitmap.width)) { - uint8_t* pixelsIn = srcBitmap.buffer; - unsigned int width = srcBitmap.width; - unsigned height = srcBitmap.rows; + uint8_t* pixelsIn = srcBitmap.buffer; + unsigned int width = srcBitmap.width; + unsigned height = srcBitmap.rows; - std::unique_ptr pixelsOutPtr( nullptr, free ); + std::unique_ptr pixelsOutPtr(nullptr, free); - if( isShearRequired ) + if(isShearRequired) { /** * Glyphs' bitmaps with no slant retrieved from FreeType: @@ -2347,31 +2341,31 @@ void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBuffer * * This difference in some bitmaps' width causes an overlap of some glyphs. This is the reason why a shear operation is done here instead of relying on the experimental FT_GlyphSlot_Oblique() implementation. */ - unsigned int widthOut = 0u; + unsigned int widthOut = 0u; unsigned int heightOut = 0u; - uint8_t* pixelsOut = nullptr; - - Dali::Internal::Platform::HorizontalShear( pixelsIn, - width, - height, - 1u, - -TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, - pixelsOut, - widthOut, - heightOut ); - - width = widthOut; - height = heightOut; + uint8_t* pixelsOut = nullptr; + + Dali::Internal::Platform::HorizontalShear(pixelsIn, + width, + height, + 1u, + -TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE, + pixelsOut, + widthOut, + heightOut); + + width = widthOut; + height = heightOut; pixelsIn = pixelsOut; - pixelsOutPtr.reset( pixelsOut ); + pixelsOutPtr.reset(pixelsOut); } const unsigned int bufferSize = width * height; - data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[]. - data.width = width; - data.height = height; - data.format = Pixel::L8; // Sets the pixel format. - memcpy( data.buffer, pixelsIn, bufferSize ); + data.buffer = new unsigned char[bufferSize]; // @note The caller is responsible for deallocating the bitmap data using delete[]. + data.width = width; + data.height = height; + data.format = Pixel::L8; // Sets the pixel format. + memcpy(data.buffer, pixelsIn, bufferSize); } break; } @@ -2379,9 +2373,9 @@ void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBuffer #ifdef FREETYPE_BITMAP_SUPPORT case FT_PIXEL_MODE_BGRA: { - if( srcBitmap.pitch == static_cast( srcBitmap.width << 2u ) ) + if(srcBitmap.pitch == static_cast(srcBitmap.width << 2u)) { - ConvertBitmap( data, srcBitmap.width, srcBitmap.rows, srcBitmap.buffer ); + ConvertBitmap(data, srcBitmap.width, srcBitmap.rows, srcBitmap.buffer); // Sets the pixel format. data.format = Pixel::BGRA8888; @@ -2391,150 +2385,150 @@ void FontClient::Plugin::ConvertBitmap( TextAbstraction::FontClient::GlyphBuffer #endif default: { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::ConvertBitmap. FontClient Unable to create Bitmap of this PixelType\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::ConvertBitmap. FontClient Unable to create Bitmap of this PixelType\n"); break; } } } } -bool FontClient::Plugin::FindFont( const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex, - FontId& fontId ) const +bool FontClient::Plugin::FindFont(const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex, + FontId& fontId) const { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " path : [%s]\n", path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of fonts in the cache : %d\n", mFontFaceCache.size() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " path : [%s]\n", path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of fonts in the cache : %d\n", mFontFaceCache.size()); fontId = 0u; - for( const auto& cacheItem : mFontFaceCache ) + for(const auto& cacheItem : mFontFaceCache) { - if( cacheItem.mRequestedPointSize == requestedPointSize && - cacheItem.mFaceIndex == faceIndex && - cacheItem.mPath == path ) + if(cacheItem.mRequestedPointSize == requestedPointSize && + cacheItem.mFaceIndex == faceIndex && + cacheItem.mPath == path) { fontId = cacheItem.mFontId + 1u; - DALI_LOG_INFO( gLogFilter, Debug::General, " font found, id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font found, id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n"); return true; } } - DALI_LOG_INFO( gLogFilter, Debug::General, " font not found\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font not found\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n"); return false; } -bool FontClient::Plugin::FindValidatedFont( const FontDescription& fontDescription, - FontDescriptionId& validatedFontId ) +bool FontClient::Plugin::FindValidatedFont(const FontDescription& fontDescription, + FontDescriptionId& validatedFontId) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindValidatedFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of validated fonts in the cache : %d\n", mValidatedFontCache.size() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindValidatedFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of validated fonts in the cache : %d\n", mValidatedFontCache.size()); validatedFontId = 0u; - for( const auto& item : mValidatedFontCache ) + for(const auto& item : mValidatedFontCache) { - if( !fontDescription.family.empty() && - ( fontDescription.family == item.fontDescription.family ) && - ( fontDescription.width == item.fontDescription.width ) && - ( fontDescription.weight == item.fontDescription.weight ) && - ( fontDescription.slant == item.fontDescription.slant ) ) + if(!fontDescription.family.empty() && + (fontDescription.family == item.fontDescription.family) && + (fontDescription.width == item.fontDescription.width) && + (fontDescription.weight == item.fontDescription.weight) && + (fontDescription.slant == item.fontDescription.slant)) { validatedFontId = item.index; - DALI_LOG_INFO( gLogFilter, Debug::General, " validated font found, id : %d\n", validatedFontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " validated font found, id : %d\n", validatedFontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n"); return true; } } - DALI_LOG_INFO( gLogFilter, Debug::General, " validated font not found\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " validated font not found\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindValidatedFont\n"); return false; } -bool FontClient::Plugin::FindFallbackFontList( const FontDescription& fontDescription, - FontList*& fontList, - CharacterSetList*& characterSetList ) +bool FontClient::Plugin::FindFallbackFontList(const FontDescription& fontDescription, + FontList*& fontList, + CharacterSetList*& characterSetList) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFontList\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant] ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of fallback font lists in the cache : %d\n", mFallbackCache.size() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindFallbackFontList\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " description; family : [%s]\n", fontDescription.family.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " path : [%s]\n", fontDescription.path.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " width : [%s]\n", FontWidth::Name[fontDescription.width]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " weight : [%s]\n", FontWeight::Name[fontDescription.weight]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " slant : [%s]\n\n", FontSlant::Name[fontDescription.slant]); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of fallback font lists in the cache : %d\n", mFallbackCache.size()); fontList = nullptr; - for( const auto& item : mFallbackCache ) + for(const auto& item : mFallbackCache) { - if( !fontDescription.family.empty() && - ( fontDescription.family == item.fontDescription.family ) && - ( fontDescription.width == item.fontDescription.width ) && - ( fontDescription.weight == item.fontDescription.weight ) && - ( fontDescription.slant == item.fontDescription.slant ) ) + if(!fontDescription.family.empty() && + (fontDescription.family == item.fontDescription.family) && + (fontDescription.width == item.fontDescription.width) && + (fontDescription.weight == item.fontDescription.weight) && + (fontDescription.slant == item.fontDescription.slant)) { - fontList = item.fallbackFonts; + fontList = item.fallbackFonts; characterSetList = item.characterSets; - DALI_LOG_INFO( gLogFilter, Debug::General, " fallback font list found.\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " fallback font list found.\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n"); return true; } } - DALI_LOG_INFO( gLogFilter, Debug::General, " fallback font list not found.\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " fallback font list not found.\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFallbackFontList\n"); return false; } -bool FontClient::Plugin::FindFont( FontDescriptionId validatedFontId, - PointSize26Dot6 requestedPointSize, - FontId& fontId ) +bool FontClient::Plugin::FindFont(FontDescriptionId validatedFontId, + PointSize26Dot6 requestedPointSize, + FontId& fontId) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->FontClient::Plugin::FindFont\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, " validatedFontId : %d\n", validatedFontId); + DALI_LOG_INFO(gLogFilter, Debug::General, " requestedPointSize : %d\n", requestedPointSize); fontId = 0u; - for( const auto& item : mFontDescriptionSizeCache ) + for(const auto& item : mFontDescriptionSizeCache) { - if( ( validatedFontId == item.validatedFontId ) && - ( requestedPointSize == item.requestedPointSize ) ) + if((validatedFontId == item.validatedFontId) && + (requestedPointSize == item.requestedPointSize)) { fontId = item.fontId; - DALI_LOG_INFO( gLogFilter, Debug::General, " font found, id : %d\n", fontId ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font found, id : %d\n", fontId); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n"); return true; } } - DALI_LOG_INFO( gLogFilter, Debug::General, " font not found.\n" ); - DALI_LOG_INFO( gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, " font not found.\n"); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--FontClient::Plugin::FindFont\n"); return false; } -bool FontClient::Plugin::FindBitmapFont( const FontFamily& bitmapFont, FontId& fontId ) const +bool FontClient::Plugin::FindBitmapFont(const FontFamily& bitmapFont, FontId& fontId) const { fontId = 0u; - for( const auto& item : mBitmapFontCache ) + for(const auto& item : mBitmapFontCache) { - if( bitmapFont == item.font.name ) + if(bitmapFont == item.font.name) { fontId = item.id + 1u; return true; @@ -2544,18 +2538,18 @@ bool FontClient::Plugin::FindBitmapFont( const FontFamily& bitmapFont, FontId& f return false; } -bool FontClient::Plugin::IsScalable( const FontPath& path ) +bool FontClient::Plugin::IsScalable(const FontPath& path) { bool isScalable = false; FT_Face ftFace; - int error = FT_New_Face( mFreeTypeLibrary, - path.c_str(), - 0, - &ftFace ); - if( FT_Err_Ok != error ) + int error = FT_New_Face(mFreeTypeLibrary, + path.c_str(), + 0, + &ftFace); + if(FT_Err_Ok != error) { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: %s\n", path.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: %s\n", path.c_str()); } else { @@ -2565,208 +2559,208 @@ bool FontClient::Plugin::IsScalable( const FontPath& path ) return isScalable; } -bool FontClient::Plugin::IsScalable( const FontDescription& fontDescription ) +bool FontClient::Plugin::IsScalable(const FontDescription& fontDescription) { // Create a font pattern. - FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription ); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. + FcPattern* fontFamilyPattern = CreateFontFamilyPattern(fontDescription); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. FcResult result = FcResultMatch; // match the pattern - FcPattern* match = FcFontMatch( nullptr /* use default configure */, fontFamilyPattern, &result ); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. - bool isScalable = false; + FcPattern* match = FcFontMatch(nullptr /* use default configure */, fontFamilyPattern, &result); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. + bool isScalable = false; - if( match ) + if(match) { // Get the path to the font file name. FontPath path; - GetFcString( match, FC_FILE, path ); - isScalable = IsScalable( path ); + GetFcString(match, FC_FILE, path); + isScalable = IsScalable(path); } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::IsScalable. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str()); } // Destroys the created patterns. - FcPatternDestroy( match ); - FcPatternDestroy( fontFamilyPattern ); + FcPatternDestroy(match); + FcPatternDestroy(fontFamilyPattern); return isScalable; } -void FontClient::Plugin::GetFixedSizes( const FontPath& path, Vector< PointSize26Dot6 >& sizes ) +void FontClient::Plugin::GetFixedSizes(const FontPath& path, Vector& sizes) { // Empty the caller container sizes.Clear(); FT_Face ftFace; - int error = FT_New_Face( mFreeTypeLibrary, - path.c_str(), - 0, - &ftFace ); - if( FT_Err_Ok != error ) + int error = FT_New_Face(mFreeTypeLibrary, + path.c_str(), + 0, + &ftFace); + if(FT_Err_Ok != error) { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font path : [%s]\n", path.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font path : [%s]\n", path.c_str()); } // Fetch the number of fixed sizes available - if ( ftFace->num_fixed_sizes && ftFace->available_sizes ) + if(ftFace->num_fixed_sizes && ftFace->available_sizes) { - for ( int i = 0; i < ftFace->num_fixed_sizes; ++i ) + for(int i = 0; i < ftFace->num_fixed_sizes; ++i) { - sizes.PushBack( ftFace->available_sizes[ i ].size ); + sizes.PushBack(ftFace->available_sizes[i].size); } } } -void FontClient::Plugin::GetFixedSizes( const FontDescription& fontDescription, - Vector< PointSize26Dot6 >& sizes ) +void FontClient::Plugin::GetFixedSizes(const FontDescription& fontDescription, + Vector& sizes) { // Create a font pattern. - FcPattern* fontFamilyPattern = CreateFontFamilyPattern( fontDescription ); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. + FcPattern* fontFamilyPattern = CreateFontFamilyPattern(fontDescription); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. FcResult result = FcResultMatch; // match the pattern - FcPattern* match = FcFontMatch( nullptr /* use default configure */, fontFamilyPattern, &result ); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. + FcPattern* match = FcFontMatch(nullptr /* use default configure */, fontFamilyPattern, &result); // Creates a font pattern that needs to be destroyed by calling FcPatternDestroy. - if( match ) + if(match) { // Get the path to the font file name. FontPath path; - GetFcString( match, FC_FILE, path ); - GetFixedSizes( path, sizes ); + GetFcString(match, FC_FILE, path); + GetFixedSizes(path, sizes); } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::GetFixedSizes. FreeType Cannot check font: [%s]\n", fontDescription.family.c_str()); } // Destroys the created patterns. - FcPatternDestroy( match ); - FcPatternDestroy( fontFamilyPattern ); + FcPatternDestroy(match); + FcPatternDestroy(fontFamilyPattern); } -bool FontClient::Plugin::HasItalicStyle( FontId fontId ) const +bool FontClient::Plugin::HasItalicStyle(FontId fontId) const { bool hasItalicStyle = false; const FontId index = fontId - 1u; - if( ( fontId > 0 ) && - ( index < mFontIdCache.Count() ) ) + if((fontId > 0) && + (index < mFontIdCache.Count())) { const FontIdCacheItem& fontIdCacheItem = mFontIdCache[index]; - if( FontDescription::FACE_FONT == fontIdCacheItem.type ) + if(FontDescription::FACE_FONT == fontIdCacheItem.type) { const FontFaceCacheItem& font = mFontFaceCache[fontIdCacheItem.id]; - hasItalicStyle = 0u != ( font.mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC ); + hasItalicStyle = 0u != (font.mFreeTypeFace->style_flags & FT_STYLE_FLAG_ITALIC); } } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "FontClient::Plugin::GetFontMetrics. Invalid font id : %d\n", fontId ); + DALI_LOG_INFO(gLogFilter, Debug::General, "FontClient::Plugin::GetFontMetrics. Invalid font id : %d\n", fontId); } return hasItalicStyle; } -void FontClient::Plugin::CacheFontPath( FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path ) +void FontClient::Plugin::CacheFontPath(FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path) { FontDescription description; - description.path = path; - description.family = std::move( FontFamily( ftFace->family_name ) ); + description.path = path; + description.family = std::move(FontFamily(ftFace->family_name)); description.weight = FontWeight::NONE; - description.width = FontWidth::NONE; - description.slant = FontSlant::NONE; + description.width = FontWidth::NONE; + description.slant = FontSlant::NONE; // Note FreeType doesn't give too much info to build a proper font style. - if( ftFace->style_flags & FT_STYLE_FLAG_ITALIC ) + if(ftFace->style_flags & FT_STYLE_FLAG_ITALIC) { description.slant = FontSlant::ITALIC; } - if( ftFace->style_flags & FT_STYLE_FLAG_BOLD ) + if(ftFace->style_flags & FT_STYLE_FLAG_BOLD) { description.weight = FontWeight::BOLD; } FontDescriptionId validatedFontId = 0u; - if( !FindValidatedFont( description, - validatedFontId ) ) + if(!FindValidatedFont(description, + validatedFontId)) { - FcPattern* pattern = CreateFontFamilyPattern( description ); // Creates a new pattern that needs to be destroyed by calling FcPatternDestroy. + FcPattern* pattern = CreateFontFamilyPattern(description); // Creates a new pattern that needs to be destroyed by calling FcPatternDestroy. - FcResult result = FcResultMatch; - FcPattern* match = FcFontMatch( nullptr, pattern, &result ); // FcFontMatch creates a new pattern that needs to be destroyed by calling FcPatternDestroy. + FcResult result = FcResultMatch; + FcPattern* match = FcFontMatch(nullptr, pattern, &result); // FcFontMatch creates a new pattern that needs to be destroyed by calling FcPatternDestroy. FcCharSet* characterSet = nullptr; - FcPatternGetCharSet( match, FC_CHARSET, 0u, &characterSet ); + FcPatternGetCharSet(match, FC_CHARSET, 0u, &characterSet); - const FontId fontFaceId = id - 1u; - mFontFaceCache[fontFaceId].mCharacterSet = FcCharSetCopy( characterSet ); // Increases the reference counter. + const FontId fontFaceId = id - 1u; + mFontFaceCache[fontFaceId].mCharacterSet = FcCharSetCopy(characterSet); // Increases the reference counter. // Destroys the created patterns. - FcPatternDestroy( match ); - FcPatternDestroy( pattern ); + FcPatternDestroy(match); + FcPatternDestroy(pattern); // Add the path to the cache. description.type = FontDescription::FACE_FONT; - mFontDescriptionCache.push_back( description ); + mFontDescriptionCache.push_back(description); // Set the index to the vector of paths to font file names. validatedFontId = mFontDescriptionCache.size(); // Increase the reference counter and add the character set to the cache. - mCharacterSetCache.PushBack( FcCharSetCopy( characterSet ) ); + mCharacterSetCache.PushBack(FcCharSetCopy(characterSet)); // Cache the index and the font's description. - mValidatedFontCache.push_back( std::move( FontDescriptionCacheItem( std::move( description ), - validatedFontId) ) ); + mValidatedFontCache.push_back(std::move(FontDescriptionCacheItem(std::move(description), + validatedFontId))); // Cache the pair 'validatedFontId, requestedPointSize' to improve the following queries. - mFontDescriptionSizeCache.push_back( FontDescriptionSizeCacheItem( validatedFontId, - requestedPointSize, - fontFaceId ) ); + mFontDescriptionSizeCache.push_back(FontDescriptionSizeCacheItem(validatedFontId, + requestedPointSize, + fontFaceId)); } } -FcCharSet* FontClient::Plugin::CreateCharacterSetFromDescription( const FontDescription& description ) +FcCharSet* FontClient::Plugin::CreateCharacterSetFromDescription(const FontDescription& description) { FcCharSet* characterSet = nullptr; - FcPattern* pattern = CreateFontFamilyPattern( description ); // Creates a new pattern that needs to be destroyed by calling FcPatternDestroy. + FcPattern* pattern = CreateFontFamilyPattern(description); // Creates a new pattern that needs to be destroyed by calling FcPatternDestroy. - if( nullptr != pattern ) + if(nullptr != pattern) { - FcResult result = FcResultMatch; - FcPattern* match = FcFontMatch( nullptr, pattern, &result ); // FcFontMatch creates a new pattern that needs to be destroyed by calling FcPatternDestroy. + FcResult result = FcResultMatch; + FcPattern* match = FcFontMatch(nullptr, pattern, &result); // FcFontMatch creates a new pattern that needs to be destroyed by calling FcPatternDestroy. - FcPatternGetCharSet( match, FC_CHARSET, 0u, &characterSet ); + FcPatternGetCharSet(match, FC_CHARSET, 0u, &characterSet); // Destroys the created patterns. - FcPatternDestroy( match ); - FcPatternDestroy( pattern ); + FcPatternDestroy(match); + FcPatternDestroy(pattern); } return characterSet; } -void FontClient::Plugin::ClearFallbackCache( std::vector& fallbackCache ) +void FontClient::Plugin::ClearFallbackCache(std::vector& fallbackCache) { - for( auto& item : fallbackCache ) + for(auto& item : fallbackCache) { - if( nullptr != item.fallbackFonts ) + if(nullptr != item.fallbackFonts) { delete item.fallbackFonts; } - if( nullptr != item.characterSets ) + if(nullptr != item.characterSets) { // Free the resources allocated by the FcCharSet objects in the 'characterSets' vector. - DestroyCharacterSets( *item.characterSets ); + DestroyCharacterSets(*item.characterSets); delete item.characterSets; } } @@ -2774,9 +2768,9 @@ void FontClient::Plugin::ClearFallbackCache( std::vector& fal void FontClient::Plugin::ClearCharacterSetFromFontFaceCache() { - for( auto& item : mFontFaceCache ) + for(auto& item : mFontFaceCache) { - FcCharSetDestroy( item.mCharacterSet ); + FcCharSetDestroy(item.mCharacterSet); item.mCharacterSet = nullptr; } } diff --git a/dali/internal/text/text-abstraction/font-client-plugin-impl.h b/dali/internal/text/text-abstraction/font-client-plugin-impl.h old mode 100755 new mode 100644 index 8c8d6f1..1449e49 --- a/dali/internal/text/text-abstraction/font-client-plugin-impl.h +++ b/dali/internal/text/text-abstraction/font-client-plugin-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_FONT_CLIENT_PLUGIN_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ */ // INTERNAL INCLUDES +#include #include #include #include #include -#include #ifdef ENABLE_VECTOR_BASED_TEXT_RENDERING #include @@ -46,13 +46,10 @@ struct _FcPattern; namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * @brief Type used for indices addressing the vector with front descriptions of validated fonts. */ @@ -84,11 +81,11 @@ struct FontClient::Plugin */ struct FallbackCacheItem { - FallbackCacheItem( FontDescription&& fontDescription, FontList* fallbackFonts, CharacterSetList* characterSets ); + FallbackCacheItem(FontDescription&& fontDescription, FontList* fallbackFonts, CharacterSetList* characterSets); - FontDescription fontDescription; ///< The font description. - FontList* fallbackFonts; ///< The list of fallback fonts for the given font-description. - CharacterSetList* characterSets; ///< The list of character sets for the given font-description. + FontDescription fontDescription; ///< The font description. + FontList* fallbackFonts; ///< The list of fallback fonts for the given font-description. + CharacterSetList* characterSets; ///< The list of character sets for the given font-description. }; /** @@ -96,13 +93,13 @@ struct FontClient::Plugin */ struct FontDescriptionCacheItem { - FontDescriptionCacheItem( const FontDescription& fontDescription, - FontDescriptionId index ); - FontDescriptionCacheItem( FontDescription&& fontDescription, - FontDescriptionId index ); + FontDescriptionCacheItem(const FontDescription& fontDescription, + FontDescriptionId index); + FontDescriptionCacheItem(FontDescription&& fontDescription, + FontDescriptionId index); - FontDescription fontDescription; ///< The font description. - FontDescriptionId index; ///< Index to the vector of font descriptions. + FontDescription fontDescription; ///< The font description. + FontDescriptionId index; ///< Index to the vector of font descriptions. }; /** @@ -110,9 +107,9 @@ struct FontClient::Plugin */ struct FontDescriptionSizeCacheItem { - FontDescriptionSizeCacheItem( FontDescriptionId validatedFontId, - PointSize26Dot6 requestedPointSize, - FontId fontId ); + FontDescriptionSizeCacheItem(FontDescriptionId validatedFontId, + PointSize26Dot6 requestedPointSize, + FontId fontId); FontDescriptionId validatedFontId; ///< Index to the vector with font descriptions. PointSize26Dot6 requestedPointSize; ///< The font point size. @@ -124,41 +121,41 @@ struct FontClient::Plugin */ struct FontFaceCacheItem { - FontFaceCacheItem( FT_Face ftFace, - const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex face, - const FontMetrics& metrics ); - - FontFaceCacheItem( FT_Face ftFace, - const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex face, - const FontMetrics& metrics, - int fixedSizeIndex, - float fixedWidth, - float fixedHeight, - bool hasColorTables ); - - FT_Face mFreeTypeFace; ///< The FreeType face. - FontPath mPath; ///< The path to the font file name. - PointSize26Dot6 mRequestedPointSize; ///< The font point size. - FaceIndex mFaceIndex; ///< The face index. - FontMetrics mMetrics; ///< The font metrics. - _FcCharSet* mCharacterSet; ///< Pointer with the range of characters. - int mFixedSizeIndex; ///< Index to the fixed size table for the requested size. - float mFixedWidthPixels; ///< The height in pixels (fixed size bitmaps only) - float mFixedHeightPixels; ///< The height in pixels (fixed size bitmaps only) - unsigned int mVectorFontId; ///< The ID of the equivalent vector-based font - FontId mFontId; ///< Index to the vector with the cache of font's ids. - bool mIsFixedSizeBitmap : 1; ///< Whether the font has fixed size bitmaps. - bool mHasColorTables : 1; ///< Whether the font has color tables. + FontFaceCacheItem(FT_Face ftFace, + const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex face, + const FontMetrics& metrics); + + FontFaceCacheItem(FT_Face ftFace, + const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex face, + const FontMetrics& metrics, + int fixedSizeIndex, + float fixedWidth, + float fixedHeight, + bool hasColorTables); + + FT_Face mFreeTypeFace; ///< The FreeType face. + FontPath mPath; ///< The path to the font file name. + PointSize26Dot6 mRequestedPointSize; ///< The font point size. + FaceIndex mFaceIndex; ///< The face index. + FontMetrics mMetrics; ///< The font metrics. + _FcCharSet* mCharacterSet; ///< Pointer with the range of characters. + int mFixedSizeIndex; ///< Index to the fixed size table for the requested size. + float mFixedWidthPixels; ///< The height in pixels (fixed size bitmaps only) + float mFixedHeightPixels; ///< The height in pixels (fixed size bitmaps only) + unsigned int mVectorFontId; ///< The ID of the equivalent vector-based font + FontId mFontId; ///< Index to the vector with the cache of font's ids. + bool mIsFixedSizeBitmap : 1; ///< Whether the font has fixed size bitmaps. + bool mHasColorTables : 1; ///< Whether the font has color tables. }; struct EllipsisItem { PointSize26Dot6 requestedPointSize; - GlyphInfo glyph; + GlyphInfo glyph; }; /** @@ -167,7 +164,7 @@ struct FontClient::Plugin struct PixelBufferCacheItem { Devel::PixelBuffer pixelBuffer; ///< The pixel buffer loaded from the url. - std::string url; ///< The url. + std::string url; ///< The url. }; /** @@ -176,8 +173,8 @@ struct FontClient::Plugin struct EmbeddedItem { PixelBufferId pixelBufferId; ///< Index to the vector of pixel buffers - unsigned int width; ///< The desired width. - unsigned int height; ///< The desired height. + unsigned int width; ///< The desired width. + unsigned int height; ///< The desired height. }; /** @@ -185,9 +182,9 @@ struct FontClient::Plugin */ struct BitmapFontCacheItem { - BitmapFont font; ///< The bitmap font. + BitmapFont font; ///< The bitmap font. std::vector pixelBuffers; ///< The pixel buffers of the glyphs. - FontId id; ///< Index to the vector with the cache of font's ids. + FontId id; ///< Index to the vector with the cache of font's ids. }; /** @@ -199,7 +196,7 @@ struct FontClient::Plugin * @param[in] horizontalDpi The horizontal dpi. * @param[in] verticalDpi The vertical dpi. */ - Plugin( unsigned int horizontalDpi, unsigned int verticalDpi ); + Plugin(unsigned int horizontalDpi, unsigned int verticalDpi); /** * Default destructor. @@ -216,7 +213,7 @@ struct FontClient::Plugin /** * @copydoc Dali::TextAbstraction::FontClient::SetDpi() */ - void SetDpi( unsigned int horizontalDpi, unsigned int verticalDpi ); + void SetDpi(unsigned int horizontalDpi, unsigned int verticalDpi); /** * @copydoc Dali::TextAbstraction::FontClient::ResetSystemDefaults() @@ -226,37 +223,37 @@ struct FontClient::Plugin /** * @copydoc Dali::TextAbstraction::FontClient::SetDefaultFont() */ - void SetDefaultFont( const FontDescription& preferredFontDescription ); + void SetDefaultFont(const FontDescription& preferredFontDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetDefaultPlatformFontDescription() */ - void GetDefaultPlatformFontDescription( FontDescription& fontDescription ); + void GetDefaultPlatformFontDescription(FontDescription& fontDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetDefaultFonts() */ - void GetDefaultFonts( FontList& defaultFonts ); + void GetDefaultFonts(FontList& defaultFonts); /** * @copydoc Dali::TextAbstraction::FontClient::GetSystemFonts() */ - void GetSystemFonts( FontList& systemFonts ); + void GetSystemFonts(FontList& systemFonts); /** * @copydoc Dali::TextAbstraction::FontClient::GetDescription() */ - void GetDescription( FontId id, FontDescription& fontDescription ) const; + void GetDescription(FontId id, FontDescription& fontDescription) const; /** * @copydoc Dali::TextAbstraction::FontClient::GetPointSize() */ - PointSize26Dot6 GetPointSize( FontId id ); + PointSize26Dot6 GetPointSize(FontId id); /** * @copydoc Dali::TextAbstraction::FontClient::IsCharacterSupportedByFont() */ - bool IsCharacterSupportedByFont( FontId fontId, Character character ); + bool IsCharacterSupportedByFont(FontId fontId, Character character); /** * @brief Finds within the @p fontList a font which support the @p carcode. @@ -269,147 +266,146 @@ struct FontClient::Plugin * * @return A valid font identifier, or zero if no font is found. */ - FontId FindFontForCharacter( const FontList& fontList, - const CharacterSetList& characterSetList, - Character charcode, - PointSize26Dot6 requestedPointSize, - bool preferColor ); + FontId FindFontForCharacter(const FontList& fontList, + const CharacterSetList& characterSetList, + Character charcode, + PointSize26Dot6 requestedPointSize, + bool preferColor); /** * @copydoc Dali::TextAbstraction::FontClient::FindDefaultFont() */ - FontId FindDefaultFont( Character charcode, - PointSize26Dot6 requestedPointSize, - bool preferColor ); + FontId FindDefaultFont(Character charcode, + PointSize26Dot6 requestedPointSize, + bool preferColor); /** * @copydoc Dali::TextAbstraction::FontClient::FindFallbackFont() */ - FontId FindFallbackFont( Character charcode, - const FontDescription& preferredFontDescription, - PointSize26Dot6 requestedPointSize, - bool preferColor ); + FontId FindFallbackFont(Character charcode, + const FontDescription& preferredFontDescription, + PointSize26Dot6 requestedPointSize, + bool preferColor); /** * @see Dali::TextAbstraction::FontClient::GetFontId( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex ) * * @param[in] cacheDescription Whether to cache the font description. */ - FontId GetFontId( const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex, - bool cacheDescription ); + FontId GetFontId(const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex, + bool cacheDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const FontDescription& preferredFontDescription, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex ) */ - FontId GetFontId( const FontDescription& fontDescription, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex ); + FontId GetFontId(const FontDescription& fontDescription, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex); /** * @copydoc Dali::TextAbstraction::FontClient::GetFontId( const BitmapFont& bitmapFont ) */ - FontId GetFontId( const BitmapFont& bitmapFont ); + FontId GetFontId(const BitmapFont& bitmapFont); /** * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontPath& path ) */ - bool IsScalable( const FontPath& path ); + bool IsScalable(const FontPath& path); /** * @copydoc Dali::TextAbstraction::FontClient::IsScalable( const FontDescription& fontDescription ) */ - bool IsScalable( const FontDescription& fontDescription ); + bool IsScalable(const FontDescription& fontDescription); /** * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes() */ - void GetFixedSizes( const FontPath& path, Dali::Vector< PointSize26Dot6>& sizes ); + void GetFixedSizes(const FontPath& path, Dali::Vector& sizes); /** * @copydoc Dali::TextAbstraction::FontClient::GetFixedSizes() */ - void GetFixedSizes( const FontDescription& fontDescription, - Dali::Vector< PointSize26Dot6 >& sizes ); + void GetFixedSizes(const FontDescription& fontDescription, + Dali::Vector& sizes); /** * @copydoc Dali::TextAbstraction::FontClient::HasItalicStyle() */ - bool HasItalicStyle( FontId fontId ) const; + bool HasItalicStyle(FontId fontId) const; /** * @copydoc Dali::TextAbstraction::FontClient::GetFontMetrics() */ - void GetFontMetrics( FontId fontId, FontMetrics& metrics ); + void GetFontMetrics(FontId fontId, FontMetrics& metrics); /** * @copydoc Dali::TextAbstraction::FontClient::GetGlyphIndex() */ - GlyphIndex GetGlyphIndex( FontId fontId, Character charcode ); + GlyphIndex GetGlyphIndex(FontId fontId, Character charcode); /** * @copydoc Dali::TextAbstraction::FontClient::GetGlyphMetrics() */ - bool GetGlyphMetrics( GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal ); + bool GetGlyphMetrics(GlyphInfo* array, uint32_t size, GlyphType type, bool horizontal); /** * Helper for GetGlyphMetrics when using bitmaps */ - bool GetBitmapMetrics( GlyphInfo* array, uint32_t size, bool horizontal ); + bool GetBitmapMetrics(GlyphInfo* array, uint32_t size, bool horizontal); /** * Helper for GetGlyphMetrics when using vectors */ - bool GetVectorMetrics( GlyphInfo* array, uint32_t size, bool horizontal ); + bool GetVectorMetrics(GlyphInfo* array, uint32_t size, bool horizontal); /** * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth ) */ - void CreateBitmap( FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth ); + void CreateBitmap(FontId fontId, GlyphIndex glyphIndex, bool isItalicRequired, bool isBoldRequired, Dali::TextAbstraction::FontClient::GlyphBufferData& data, int outlineWidth); /** * @copydoc Dali::TextAbstraction::FontClient::CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth ) */ - PixelData CreateBitmap( FontId fontId, GlyphIndex glyphIndex, int outlineWidth ); + PixelData CreateBitmap(FontId fontId, GlyphIndex glyphIndex, int outlineWidth); /** * @copydoc Dali::TextAbstraction::FontClient::CreateVectorBlob() */ - void CreateVectorBlob( FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight ); + void CreateVectorBlob(FontId fontId, GlyphIndex glyphIndex, VectorBlob*& blob, unsigned int& blobLength, unsigned int& nominalWidth, unsigned int& nominalHeight); /** * @copydoc Dali::TextAbstraction::FontClient::GetEllipsisGlyph() */ - const GlyphInfo& GetEllipsisGlyph( PointSize26Dot6 requestedPointSize ); + const GlyphInfo& GetEllipsisGlyph(PointSize26Dot6 requestedPointSize); /** * @copydoc Dali::TextAbstraction::FontClient::IsColorGlyph() */ - bool IsColorGlyph( FontId fontId, GlyphIndex glyphIndex ); + bool IsColorGlyph(FontId fontId, GlyphIndex glyphIndex); /** * @copydoc Dali::TextAbstraction::FontClient::CreateEmbeddedItem() */ - GlyphIndex CreateEmbeddedItem( const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat ); + GlyphIndex CreateEmbeddedItem(const TextAbstraction::FontClient::EmbeddedItemDescription& description, Pixel::Format& pixelFormat); /** * @copydoc Dali::TextAbstraction::Internal::FontClient::GetFreetypeFace() */ - FT_FaceRec_* GetFreetypeFace( FontId fontId ); + FT_FaceRec_* GetFreetypeFace(FontId fontId); /** * @copydoc Dali::TextAbstraction::Internal::FontClient::GetFontType() */ - FontDescription::Type GetFontType( FontId fontId ); + FontDescription::Type GetFontType(FontId fontId); /** * @copydoc Dali::TextAbstraction::FontClient::AddCustomFontDirectory() */ - bool AddCustomFontDirectory( const FontPath& path ); + bool AddCustomFontDirectory(const FontPath& path); private: - /** * @brief Caches the fonts present in the platform. * @@ -427,7 +423,7 @@ private: * @param[out] characterSet The character set for that pattern. * @return true if match found. */ - bool MatchFontDescriptionToPattern( _FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, _FcCharSet** characterSet ); + bool MatchFontDescriptionToPattern(_FcPattern* pattern, Dali::TextAbstraction::FontDescription& fontDescription, _FcCharSet** characterSet); /** * @brief Creates a font family pattern used to match fonts. @@ -438,7 +434,7 @@ private: * * @return The pattern. */ - _FcPattern* CreateFontFamilyPattern( const FontDescription& fontDescription ) const; + _FcPattern* CreateFontFamilyPattern(const FontDescription& fontDescription) const; /** * @brief Retrieves the fonts present in the platform. @@ -458,7 +454,7 @@ private: * * @return @e true if the operation is successful. */ - bool GetFcString( const _FcPattern* const pattern, const char* const n, std::string& string ); + bool GetFcString(const _FcPattern* const pattern, const char* const n, std::string& string); /** * @brief Retrieves a font config object's value from a pattern. @@ -469,7 +465,7 @@ private: * * @return @e true if the operation is successful. */ - bool GetFcInt( const _FcPattern* const pattern, const char* const n, int& intVal ); + bool GetFcInt(const _FcPattern* const pattern, const char* const n, int& intVal); /** * @brief Creates a font. @@ -481,10 +477,10 @@ private: * * @return The font identifier. */ - FontId CreateFont( const FontPath& path, - PointSize26Dot6 requestedPointSize, - FaceIndex faceIndex, - bool cacheDescription ); + FontId CreateFont(const FontPath& path, + PointSize26Dot6 requestedPointSize, + FaceIndex faceIndex, + bool cacheDescription); /** * @brief Copy the color bitmap given in @p srcBuffer to @p data. @@ -494,7 +490,7 @@ private: * @param[in] srcHeight The height of the bitmap. * @param[in] srcBuffer The buffer of the bitmap. */ - void ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, unsigned int srcWidth, unsigned int srcHeight, const unsigned char* const srcBuffer ); + void ConvertBitmap(TextAbstraction::FontClient::GlyphBufferData& data, unsigned int srcWidth, unsigned int srcHeight, const unsigned char* const srcBuffer); /** * @brief Copy the FreeType bitmap to the given buffer. @@ -503,7 +499,7 @@ private: * @param[in] srcBitmap The FreeType bitmap. * @param[in] isShearRequired Whether the bitmap needs a shear transform (for software italics). */ - void ConvertBitmap( TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap, bool isShearRequired ); + void ConvertBitmap(TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap srcBitmap, bool isShearRequired); /** * @brief Finds in the cache if there is a triplet with the path to the font file name, the font point size and the face index. @@ -516,7 +512,7 @@ private: * * @return @e true if there triplet is found. */ - bool FindFont( const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex, FontId& fontId ) const; + bool FindFont(const FontPath& path, PointSize26Dot6 requestedPointSize, FaceIndex faceIndex, FontId& fontId) const; /** * @brief Finds in the cache a cluster 'font family, font width, font weight, font slant' @@ -527,8 +523,8 @@ private: * * @return @e true if the pair is found. */ - bool FindValidatedFont( const FontDescription& fontDescription, - FontDescriptionId& validatedFontId ); + bool FindValidatedFont(const FontDescription& fontDescription, + FontDescriptionId& validatedFontId); /** * @brief Finds a fallback font list from the cache for a given font-description @@ -537,9 +533,9 @@ private: * @param[out] A valid pointer to a font list, or @e nullptr if not found. * @param[out] characterSetList A valid pointer to a character set list, or @e nullptr if not found. */ - bool FindFallbackFontList( const FontDescription& fontDescription, - FontList*& fontList, - CharacterSetList*& characterSetList ); + bool FindFallbackFontList(const FontDescription& fontDescription, + FontList*& fontList, + CharacterSetList*& characterSetList); /** * @brief Finds in the cache a pair 'validated font identifier and font point size'. @@ -551,9 +547,9 @@ private: * * @return @e true if the pair is found. */ - bool FindFont( FontDescriptionId validatedFontId, - PointSize26Dot6 requestedPointSize, - FontId& fontId ); + bool FindFont(FontDescriptionId validatedFontId, + PointSize26Dot6 requestedPointSize, + FontId& fontId); /** * @brief Finds in the cache a bitmap font with the @p bitmapFont family name. @@ -563,7 +559,7 @@ private: * * @return Whether the font has been found. */ - bool FindBitmapFont( const FontFamily& bitmapFont, FontId& fontId ) const; + bool FindBitmapFont(const FontFamily& bitmapFont, FontId& fontId) const; /** * @brief Validate a font description. @@ -571,8 +567,8 @@ private: * @param[in] fontDescription The font to validate. * @param[out] validatedFontId Result of validation */ - void ValidateFont( const FontDescription& fontDescription, - FontDescriptionId& validatedFontId ); + void ValidateFont(const FontDescription& fontDescription, + FontDescriptionId& validatedFontId); /** * @brief Helper for GetDefaultFonts etc. @@ -583,7 +579,7 @@ private: * @param[out] fontList A list of the fonts which are a close match for fontDescription. * @param[out] characterSetList A list of character sets which are a close match for fontDescription. */ - void SetFontList( const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList ); + void SetFontList(const FontDescription& fontDescription, FontList& fontList, CharacterSetList& characterSetList); /** * Caches a font path. @@ -593,7 +589,7 @@ private: * @param[in] requestedPointSize The font point size. * @param[in] path Path to the font file name. */ - void CacheFontPath( FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path ); + void CacheFontPath(FT_Face ftFace, FontId id, PointSize26Dot6 requestedPointSize, const FontPath& path); /** * @brief Creates a character set from a given font's @p description. @@ -604,14 +600,14 @@ private: * * @return A character set. */ - _FcCharSet* CreateCharacterSetFromDescription( const FontDescription& description ); + _FcCharSet* CreateCharacterSetFromDescription(const FontDescription& description); /** * @brief Free the resources allocated in the fallback cache. * * @param[in] fallbackCache The fallback cache. */ - void ClearFallbackCache( std::vector& fallbackCache ); + void ClearFallbackCache(std::vector& fallbackCache); /** * @brief Free the resources allocated by the FcCharSet objects. @@ -619,14 +615,12 @@ private: void ClearCharacterSetFromFontFaceCache(); private: - // Declared private and left undefined to avoid copies. - Plugin( const Plugin& ); + Plugin(const Plugin&); // Declared private and left undefined to avoid copies. - Plugin& operator=( const Plugin& ); + Plugin& operator=(const Plugin&); private: - FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance. unsigned int mDpiHorizontal; ///< Horizontal dpi. @@ -634,8 +628,8 @@ private: FontDescription mDefaultFontDescription; ///< The cached default font from the system - FontList mSystemFonts; ///< Cached system fonts. - FontList mDefaultFonts; ///< Cached default fonts. + FontList mSystemFonts; ///< Cached system fonts. + FontList mDefaultFonts; ///< Cached default fonts. CharacterSetList mDefaultFontCharacterSets; std::vector mFallbackCache; ///< Cached fallback font lists. @@ -649,10 +643,10 @@ private: VectorFontCache* mVectorFontCache; ///< Separate cache for vector data blobs etc. - Vector mEllipsisCache; ///< Caches ellipsis glyphs for a particular point size. - std::vector mPixelBufferCache; ///< Caches the pixel buffer of a url. - Vector mEmbeddedItemCache; ///< Cache embedded items. - std::vector mBitmapFontCache; ///< Stores bitmap fonts. + Vector mEllipsisCache; ///< Caches ellipsis glyphs for a particular point size. + std::vector mPixelBufferCache; ///< Caches the pixel buffer of a url. + Vector mEmbeddedItemCache; ///< Cache embedded items. + std::vector mBitmapFontCache; ///< Stores bitmap fonts. bool mDefaultFontDescriptionCached : 1; ///< Whether the default font is cached or not }; diff --git a/dali/internal/text/text-abstraction/segmentation-impl.cpp b/dali/internal/text/text-abstraction/segmentation-impl.cpp index fd97c20..a677176 100644 --- a/dali/internal/text/text-abstraction/segmentation-impl.cpp +++ b/dali/internal/text/text-abstraction/segmentation-impl.cpp @@ -25,33 +25,31 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - struct Segmentation::Plugin { - void GetLineBreakPositions( const Character* const text, - Length numberOfCharacters, - LineBreakInfo* breakInfo ) + void GetLineBreakPositions(const Character* const text, + Length numberOfCharacters, + LineBreakInfo* breakInfo) { - set_linebreaks_utf32( text, numberOfCharacters, NULL, breakInfo ); + set_linebreaks_utf32(text, numberOfCharacters, NULL, breakInfo); } - void GetWordBreakPositions( const Character* const text, - Length numberOfCharacters, - WordBreakInfo* breakInfo ) + void GetWordBreakPositions(const Character* const text, + Length numberOfCharacters, + WordBreakInfo* breakInfo) { - set_wordbreaks_utf32( text, numberOfCharacters, NULL, breakInfo ); + set_wordbreaks_utf32(text, numberOfCharacters, NULL, breakInfo); } }; Segmentation::Segmentation() -: mPlugin( NULL ) -{} +: mPlugin(NULL) +{ +} Segmentation::~Segmentation() { @@ -62,48 +60,48 @@ TextAbstraction::Segmentation Segmentation::Get() { TextAbstraction::Segmentation segmentationHandle; - SingletonService service( SingletonService::Get() ); - if( service ) + SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Segmentation ) ); - if( handle ) + Dali::BaseHandle handle = service.GetSingleton(typeid(TextAbstraction::Segmentation)); + if(handle) { // If so, downcast the handle - Segmentation* impl = dynamic_cast< Internal::Segmentation* >( handle.GetObjectPtr() ); - segmentationHandle = TextAbstraction::Segmentation( impl ); + Segmentation* impl = dynamic_cast(handle.GetObjectPtr()); + segmentationHandle = TextAbstraction::Segmentation(impl); } else // create and register the object { - segmentationHandle = TextAbstraction::Segmentation( new Segmentation ); - service.Register( typeid( segmentationHandle ), segmentationHandle ); + segmentationHandle = TextAbstraction::Segmentation(new Segmentation); + service.Register(typeid(segmentationHandle), segmentationHandle); } } return segmentationHandle; } -void Segmentation::GetLineBreakPositions( const Character* const text, - Length numberOfCharacters, - LineBreakInfo* breakInfo ) +void Segmentation::GetLineBreakPositions(const Character* const text, + Length numberOfCharacters, + LineBreakInfo* breakInfo) { CreatePlugin(); - mPlugin->GetLineBreakPositions( text, numberOfCharacters, breakInfo ); + mPlugin->GetLineBreakPositions(text, numberOfCharacters, breakInfo); } -void Segmentation::GetWordBreakPositions( const Character* const text, - Length numberOfCharacters, - WordBreakInfo* breakInfo ) +void Segmentation::GetWordBreakPositions(const Character* const text, + Length numberOfCharacters, + WordBreakInfo* breakInfo) { CreatePlugin(); - mPlugin->GetWordBreakPositions( text, numberOfCharacters, breakInfo ); + mPlugin->GetWordBreakPositions(text, numberOfCharacters, breakInfo); } void Segmentation::CreatePlugin() { - if( !mPlugin ) + if(!mPlugin) { mPlugin = new Plugin(); } diff --git a/dali/internal/text/text-abstraction/segmentation-impl.h b/dali/internal/text/text-abstraction/segmentation-impl.h index f8404c7..170b7b7 100644 --- a/dali/internal/text/text-abstraction/segmentation-impl.h +++ b/dali/internal/text/text-abstraction/segmentation-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_SEGMENTATION_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,13 +26,10 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * Implementation of the Segmentation */ @@ -40,7 +37,6 @@ namespace Internal class Segmentation : public BaseObject { public: - /** * Constructor */ @@ -59,35 +55,31 @@ public: /** * @copydoc Dali::Segmentation::GetLineBreakPositions() */ - void GetLineBreakPositions( const Character* const text, - Length numberOfCharacters, - LineBreakInfo* breakInfo ); - + void GetLineBreakPositions(const Character* const text, + Length numberOfCharacters, + LineBreakInfo* breakInfo); /** * @copydoc Dali::Segmentation::GetWordBreakPositions() */ - void GetWordBreakPositions( const Character* const text, - Length numberOfCharacters, - WordBreakInfo* breakInfo ); + void GetWordBreakPositions(const Character* const text, + Length numberOfCharacters, + WordBreakInfo* breakInfo); private: - /** * Helper for lazy initialization. */ void CreatePlugin(); private: - // Undefined copy constructor. - Segmentation( const Segmentation& ); + Segmentation(const Segmentation&); // Undefined assignment constructor. - Segmentation& operator=( Segmentation& ); + Segmentation& operator=(Segmentation&); private: - struct Plugin; Plugin* mPlugin; @@ -97,18 +89,18 @@ private: } // namespace TextAbstraction -inline static TextAbstraction::Internal::Segmentation& GetImplementation( TextAbstraction::Segmentation& segmentation ) +inline static TextAbstraction::Internal::Segmentation& GetImplementation(TextAbstraction::Segmentation& segmentation) { - DALI_ASSERT_ALWAYS( segmentation && "segmentation handle is empty" ); + DALI_ASSERT_ALWAYS(segmentation && "segmentation handle is empty"); BaseObject& handle = segmentation.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } -inline static const TextAbstraction::Internal::Segmentation& GetImplementation( const TextAbstraction::Segmentation& segmentation ) +inline static const TextAbstraction::Internal::Segmentation& GetImplementation(const TextAbstraction::Segmentation& segmentation) { - DALI_ASSERT_ALWAYS( segmentation && "segmentation handle is empty" ); + DALI_ASSERT_ALWAYS(segmentation && "segmentation handle is empty"); const BaseObject& handle = segmentation.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } } // namespace Dali diff --git a/dali/internal/text/text-abstraction/shaping-impl.cpp b/dali/internal/text/text-abstraction/shaping-impl.cpp old mode 100755 new mode 100644 index da78f59..31a2efa --- a/dali/internal/text/text-abstraction/shaping-impl.cpp +++ b/dali/internal/text/text-abstraction/shaping-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,99 +25,94 @@ #include "font-client-impl.h" // EXTERNAL INCLUDES -#include -#include #include +#include +#include namespace { - #if defined(DEBUG_ENABLED) Dali::Integration::Log::Filter* gLogFilter = Dali::Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_FONT_CLIENT"); #endif -} +} // namespace namespace Dali { - namespace TextAbstraction { - namespace Internal { - -const char* const DEFAULT_LANGUAGE = "en"; +const char* const DEFAULT_LANGUAGE = "en"; const unsigned int DEFAULT_LANGUAGE_LENGTH = 2u; -const float FROM_266 = 1.0f / 64.0f; +const float FROM_266 = 1.0f / 64.0f; const hb_script_t SCRIPT_TO_HARFBUZZ[] = -{ - HB_SCRIPT_COMMON, - - HB_SCRIPT_COMMON, // ASCII_DIGITS - HB_SCRIPT_COMMON, // ASCII_PS - - HB_SCRIPT_COMMON, // C1_CONTROLS - HB_SCRIPT_COMMON, // C1_PS - HB_SCRIPT_COMMON, // C1_MATH - HB_SCRIPT_COMMON, // SML_P - HB_SCRIPT_COMMON, // PHONETIC_U - HB_SCRIPT_COMMON, // PHONETIC_SS - HB_SCRIPT_COMMON, // NUMERIC_SS - HB_SCRIPT_COMMON, // LETTER_LIKE - HB_SCRIPT_COMMON, // NUMBER_FORMS - HB_SCRIPT_COMMON, // FRACTIONS_NF - HB_SCRIPT_COMMON, // NON_LATIN_LED - HB_SCRIPT_COMMON, // HWFW_S - - HB_SCRIPT_CYRILLIC, - HB_SCRIPT_GREEK, - HB_SCRIPT_LATIN, - - HB_SCRIPT_ARABIC, - HB_SCRIPT_HEBREW, - - HB_SCRIPT_ARMENIAN, - HB_SCRIPT_GEORGIAN, - - HB_SCRIPT_HAN, - HB_SCRIPT_HANGUL, - HB_SCRIPT_HIRAGANA, - HB_SCRIPT_KATAKANA, - HB_SCRIPT_BOPOMOFO, - - HB_SCRIPT_BENGALI, - HB_SCRIPT_MYANMAR, - HB_SCRIPT_DEVANAGARI, - HB_SCRIPT_GUJARATI, - HB_SCRIPT_GURMUKHI, - HB_SCRIPT_KANNADA, - HB_SCRIPT_MALAYALAM, - HB_SCRIPT_ORIYA, - HB_SCRIPT_SINHALA, - HB_SCRIPT_TAMIL, - HB_SCRIPT_TELUGU, - - HB_SCRIPT_LAO, - HB_SCRIPT_THAI, - HB_SCRIPT_KHMER, - HB_SCRIPT_JAVANESE, - HB_SCRIPT_SUNDANESE, - - HB_SCRIPT_ETHIOPIC, - HB_SCRIPT_OL_CHIKI, - HB_SCRIPT_TAGALOG, - HB_SCRIPT_MEETEI_MAYEK, - - HB_SCRIPT_UNKNOWN, // EMOJI - HB_SCRIPT_UNKNOWN, // SYMBOLS1 - HB_SCRIPT_UNKNOWN, // SYMBOLS2 - HB_SCRIPT_UNKNOWN, // SYMBOLS3 - HB_SCRIPT_UNKNOWN, // SYMBOLS4 - HB_SCRIPT_UNKNOWN, // SYMBOLS5 - HB_SCRIPT_UNKNOWN -}; + { + HB_SCRIPT_COMMON, + + HB_SCRIPT_COMMON, // ASCII_DIGITS + HB_SCRIPT_COMMON, // ASCII_PS + + HB_SCRIPT_COMMON, // C1_CONTROLS + HB_SCRIPT_COMMON, // C1_PS + HB_SCRIPT_COMMON, // C1_MATH + HB_SCRIPT_COMMON, // SML_P + HB_SCRIPT_COMMON, // PHONETIC_U + HB_SCRIPT_COMMON, // PHONETIC_SS + HB_SCRIPT_COMMON, // NUMERIC_SS + HB_SCRIPT_COMMON, // LETTER_LIKE + HB_SCRIPT_COMMON, // NUMBER_FORMS + HB_SCRIPT_COMMON, // FRACTIONS_NF + HB_SCRIPT_COMMON, // NON_LATIN_LED + HB_SCRIPT_COMMON, // HWFW_S + + HB_SCRIPT_CYRILLIC, + HB_SCRIPT_GREEK, + HB_SCRIPT_LATIN, + + HB_SCRIPT_ARABIC, + HB_SCRIPT_HEBREW, + + HB_SCRIPT_ARMENIAN, + HB_SCRIPT_GEORGIAN, + + HB_SCRIPT_HAN, + HB_SCRIPT_HANGUL, + HB_SCRIPT_HIRAGANA, + HB_SCRIPT_KATAKANA, + HB_SCRIPT_BOPOMOFO, + + HB_SCRIPT_BENGALI, + HB_SCRIPT_MYANMAR, + HB_SCRIPT_DEVANAGARI, + HB_SCRIPT_GUJARATI, + HB_SCRIPT_GURMUKHI, + HB_SCRIPT_KANNADA, + HB_SCRIPT_MALAYALAM, + HB_SCRIPT_ORIYA, + HB_SCRIPT_SINHALA, + HB_SCRIPT_TAMIL, + HB_SCRIPT_TELUGU, + + HB_SCRIPT_LAO, + HB_SCRIPT_THAI, + HB_SCRIPT_KHMER, + HB_SCRIPT_JAVANESE, + HB_SCRIPT_SUNDANESE, + + HB_SCRIPT_ETHIOPIC, + HB_SCRIPT_OL_CHIKI, + HB_SCRIPT_TAGALOG, + HB_SCRIPT_MEETEI_MAYEK, + + HB_SCRIPT_UNKNOWN, // EMOJI + HB_SCRIPT_UNKNOWN, // SYMBOLS1 + HB_SCRIPT_UNKNOWN, // SYMBOLS2 + HB_SCRIPT_UNKNOWN, // SYMBOLS3 + HB_SCRIPT_UNKNOWN, // SYMBOLS4 + HB_SCRIPT_UNKNOWN, // SYMBOLS5 + HB_SCRIPT_UNKNOWN}; struct Shaping::Plugin { @@ -125,7 +120,7 @@ struct Shaping::Plugin : mIndices(), mAdvance(), mCharacterMap(), - mFontId( 0u ) + mFontId(0u) { } @@ -133,10 +128,10 @@ struct Shaping::Plugin { } - Length Shape( const Character* const text, - Length numberOfCharacters, - FontId fontId, - Script script ) + Length Shape(const Character* const text, + Length numberOfCharacters, + FontId fontId, + Script script) { // Clear previoursly shaped texts. mIndices.Clear(); @@ -145,92 +140,91 @@ struct Shaping::Plugin mOffset.Clear(); mFontId = fontId; - TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - TextAbstraction::Internal::FontClient& fontClientImpl = TextAbstraction::GetImplementation( fontClient ); + TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); + TextAbstraction::Internal::FontClient& fontClientImpl = TextAbstraction::GetImplementation(fontClient); - const FontDescription::Type type = fontClientImpl.GetFontType( fontId ); + const FontDescription::Type type = fontClientImpl.GetFontType(fontId); - switch( type ) + switch(type) { case FontDescription::FACE_FONT: { // Reserve some space to avoid reallocations. - const Length numberOfGlyphs = static_cast( 1.3f * static_cast( numberOfCharacters ) ); - mIndices.Reserve( numberOfGlyphs ); - mAdvance.Reserve( numberOfGlyphs ); - mCharacterMap.Reserve( numberOfGlyphs ); - mOffset.Reserve( 2u * numberOfGlyphs ); + const Length numberOfGlyphs = static_cast(1.3f * static_cast(numberOfCharacters)); + mIndices.Reserve(numberOfGlyphs); + mAdvance.Reserve(numberOfGlyphs); + mCharacterMap.Reserve(numberOfGlyphs); + mOffset.Reserve(2u * numberOfGlyphs); // Retrieve a FreeType font's face. - FT_Face face = fontClientImpl.GetFreetypeFace( fontId ); - if( nullptr == face ) + FT_Face face = fontClientImpl.GetFreetypeFace(fontId); + if(nullptr == face) { // Nothing to do if the face is null. return 0u; } unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - fontClient.GetDpi( horizontalDpi, verticalDpi ); + unsigned int verticalDpi = 0u; + fontClient.GetDpi(horizontalDpi, verticalDpi); - FT_Set_Char_Size( face, - 0u, - fontClient.GetPointSize( fontId ), - horizontalDpi, - verticalDpi ); + FT_Set_Char_Size(face, + 0u, + fontClient.GetPointSize(fontId), + horizontalDpi, + verticalDpi); /* Get our harfbuzz font struct */ hb_font_t* harfBuzzFont; - harfBuzzFont = hb_ft_font_create( face, NULL ); + harfBuzzFont = hb_ft_font_create(face, NULL); /* Create a buffer for harfbuzz to use */ hb_buffer_t* harfBuzzBuffer = hb_buffer_create(); - const bool rtlDirection = IsRightToLeftScript( script ); - hb_buffer_set_direction( harfBuzzBuffer, - rtlDirection ? HB_DIRECTION_RTL : HB_DIRECTION_LTR ); /* or LTR */ - - hb_buffer_set_script( harfBuzzBuffer, - SCRIPT_TO_HARFBUZZ[ script ] ); /* see hb-unicode.h */ + const bool rtlDirection = IsRightToLeftScript(script); + hb_buffer_set_direction(harfBuzzBuffer, + rtlDirection ? HB_DIRECTION_RTL : HB_DIRECTION_LTR); /* or LTR */ + hb_buffer_set_script(harfBuzzBuffer, + SCRIPT_TO_HARFBUZZ[script]); /* see hb-unicode.h */ - char* currentLocale = setlocale(LC_MESSAGES,NULL); + char* currentLocale = setlocale(LC_MESSAGES, NULL); - std::istringstream stringStream( currentLocale ); - std::string localeString; + std::istringstream stringStream(currentLocale); + std::string localeString; std::getline(stringStream, localeString, '_'); - hb_buffer_set_language( harfBuzzBuffer, hb_language_from_string( localeString.c_str(), localeString.size() ) ); + hb_buffer_set_language(harfBuzzBuffer, hb_language_from_string(localeString.c_str(), localeString.size())); /* Layout the text */ - hb_buffer_add_utf32( harfBuzzBuffer, text, numberOfCharacters, 0u, numberOfCharacters ); + hb_buffer_add_utf32(harfBuzzBuffer, text, numberOfCharacters, 0u, numberOfCharacters); - hb_shape( harfBuzzFont, harfBuzzBuffer, NULL, 0u ); + hb_shape(harfBuzzFont, harfBuzzBuffer, NULL, 0u); /* Get glyph data */ - unsigned int glyphCount; - hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos( harfBuzzBuffer, &glyphCount ); - hb_glyph_position_t *glyphPositions = hb_buffer_get_glyph_positions( harfBuzzBuffer, &glyphCount ); - const GlyphIndex lastGlyphIndex = glyphCount - 1u; + unsigned int glyphCount; + hb_glyph_info_t* glyphInfo = hb_buffer_get_glyph_infos(harfBuzzBuffer, &glyphCount); + hb_glyph_position_t* glyphPositions = hb_buffer_get_glyph_positions(harfBuzzBuffer, &glyphCount); + const GlyphIndex lastGlyphIndex = glyphCount - 1u; - for( GlyphIndex i = 0u; i < glyphCount; ) + for(GlyphIndex i = 0u; i < glyphCount;) { - if( rtlDirection ) + if(rtlDirection) { // If the direction is right to left, Harfbuzz retrieves the glyphs in the visual order. // The glyphs are needed in the logical order to layout the text in lines. // Do not change the order of the glyphs if they belong to the same cluster. GlyphIndex rtlIndex = lastGlyphIndex - i; - unsigned int cluster = glyphInfo[rtlIndex].cluster; - unsigned int previousCluster = cluster; - Length numberOfGlyphsInCluster = 0u; + unsigned int cluster = glyphInfo[rtlIndex].cluster; + unsigned int previousCluster = cluster; + Length numberOfGlyphsInCluster = 0u; - while( ( cluster == previousCluster ) ) + while((cluster == previousCluster)) { ++numberOfGlyphsInCluster; previousCluster = cluster; - if( rtlIndex > 0u ) + if(rtlIndex > 0u) { --rtlIndex; @@ -242,54 +236,54 @@ struct Shaping::Plugin } } - rtlIndex = lastGlyphIndex - ( i + ( numberOfGlyphsInCluster - 1u ) ); + rtlIndex = lastGlyphIndex - (i + (numberOfGlyphsInCluster - 1u)); - for( GlyphIndex j = 0u; j < numberOfGlyphsInCluster; ++j ) + for(GlyphIndex j = 0u; j < numberOfGlyphsInCluster; ++j) { const GlyphIndex index = rtlIndex + j; - mIndices.PushBack( glyphInfo[index].codepoint ); - mAdvance.PushBack( glyphPositions[index].x_advance * FROM_266 ); - mCharacterMap.PushBack( glyphInfo[index].cluster ); - mOffset.PushBack( glyphPositions[index].x_offset * FROM_266 ); - mOffset.PushBack( glyphPositions[index].y_offset * FROM_266 ); + mIndices.PushBack(glyphInfo[index].codepoint); + mAdvance.PushBack(glyphPositions[index].x_advance * FROM_266); + mCharacterMap.PushBack(glyphInfo[index].cluster); + mOffset.PushBack(glyphPositions[index].x_offset * FROM_266); + mOffset.PushBack(glyphPositions[index].y_offset * FROM_266); } i += numberOfGlyphsInCluster; } else { - mIndices.PushBack( glyphInfo[i].codepoint ); - mAdvance.PushBack( glyphPositions[i].x_advance * FROM_266 ); - mCharacterMap.PushBack( glyphInfo[i].cluster ); - mOffset.PushBack( glyphPositions[i].x_offset * FROM_266 ); - mOffset.PushBack( glyphPositions[i].y_offset * FROM_266 ); + mIndices.PushBack(glyphInfo[i].codepoint); + mAdvance.PushBack(glyphPositions[i].x_advance * FROM_266); + mCharacterMap.PushBack(glyphInfo[i].cluster); + mOffset.PushBack(glyphPositions[i].x_offset * FROM_266); + mOffset.PushBack(glyphPositions[i].y_offset * FROM_266); ++i; } } /* Cleanup */ - hb_buffer_destroy( harfBuzzBuffer ); - hb_font_destroy( harfBuzzFont ); + hb_buffer_destroy(harfBuzzBuffer); + hb_font_destroy(harfBuzzFont); break; } case FontDescription::BITMAP_FONT: { // Reserve some space to avoid reallocations. // The advance and offset tables can be initialized with zeros as it's not needed to get metrics from the bitmaps here. - mIndices.Resize( numberOfCharacters ); - mAdvance.Resize( numberOfCharacters, 0u ); - mCharacterMap.Reserve( numberOfCharacters ); - mOffset.Resize( 2u * numberOfCharacters, 0.f ); + mIndices.Resize(numberOfCharacters); + mAdvance.Resize(numberOfCharacters, 0u); + mCharacterMap.Reserve(numberOfCharacters); + mOffset.Resize(2u * numberOfCharacters, 0.f); // The utf32 character can be used as the glyph's index. - std::copy( text, text + numberOfCharacters, mIndices.Begin() ); + std::copy(text, text + numberOfCharacters, mIndices.Begin()); // The glyph to character map is 1 to 1. - for( unsigned int index = 0u; index < numberOfCharacters; ++index ) + for(unsigned int index = 0u; index < numberOfCharacters; ++index) { - mCharacterMap.PushBack( index ); + mCharacterMap.PushBack(index); } break; } @@ -302,28 +296,28 @@ struct Shaping::Plugin return mIndices.Count(); } - void GetGlyphs( GlyphInfo* glyphInfo, - CharacterIndex* glyphToCharacterMap ) + void GetGlyphs(GlyphInfo* glyphInfo, + CharacterIndex* glyphToCharacterMap) { - Vector::ConstIterator indicesIt = mIndices.Begin(); - Vector::ConstIterator advanceIt = mAdvance.Begin(); - Vector::ConstIterator offsetIt = mOffset.Begin(); + Vector::ConstIterator indicesIt = mIndices.Begin(); + Vector::ConstIterator advanceIt = mAdvance.Begin(); + Vector::ConstIterator offsetIt = mOffset.Begin(); Vector::ConstIterator characterMapIt = mCharacterMap.Begin(); - for( GlyphIndex index = 0u, size = mIndices.Count(); index < size; ++index ) + for(GlyphIndex index = 0u, size = mIndices.Count(); index < size; ++index) { - GlyphInfo& glyph = *( glyphInfo + index ); - CharacterIndex& glyphToCharacter = *( glyphToCharacterMap + index ); + GlyphInfo& glyph = *(glyphInfo + index); + CharacterIndex& glyphToCharacter = *(glyphToCharacterMap + index); - glyph.fontId = mFontId; - glyph.index = *( indicesIt + index ); - glyph.advance = *( advanceIt + index ); + glyph.fontId = mFontId; + glyph.index = *(indicesIt + index); + glyph.advance = *(advanceIt + index); const GlyphIndex offsetIndex = 2u * index; - glyph.xBearing = *( offsetIt + offsetIndex ); - glyph.yBearing = *( offsetIt + offsetIndex + 1u ); + glyph.xBearing = *(offsetIt + offsetIndex); + glyph.yBearing = *(offsetIt + offsetIndex + 1u); - glyphToCharacter = *( characterMapIt + index ); + glyphToCharacter = *(characterMapIt + index); } } @@ -335,7 +329,7 @@ struct Shaping::Plugin }; Shaping::Shaping() -: mPlugin( NULL ) +: mPlugin(NULL) { } @@ -348,52 +342,52 @@ TextAbstraction::Shaping Shaping::Get() { TextAbstraction::Shaping shapingHandle; - SingletonService service( SingletonService::Get() ); - if( service ) + SingletonService service(SingletonService::Get()); + if(service) { // Check whether the singleton is already created - Dali::BaseHandle handle = service.GetSingleton( typeid( TextAbstraction::Shaping ) ); - if( handle ) + Dali::BaseHandle handle = service.GetSingleton(typeid(TextAbstraction::Shaping)); + if(handle) { // If so, downcast the handle - Shaping* impl = dynamic_cast< Internal::Shaping* >( handle.GetObjectPtr() ); - shapingHandle = TextAbstraction::Shaping( impl ); + Shaping* impl = dynamic_cast(handle.GetObjectPtr()); + shapingHandle = TextAbstraction::Shaping(impl); } else // create and register the object { - shapingHandle = TextAbstraction::Shaping( new Shaping ); - service.Register( typeid( shapingHandle ), shapingHandle ); + shapingHandle = TextAbstraction::Shaping(new Shaping); + service.Register(typeid(shapingHandle), shapingHandle); } } return shapingHandle; } -Length Shaping::Shape( const Character* const text, - Length numberOfCharacters, - FontId fontId, - Script script ) +Length Shaping::Shape(const Character* const text, + Length numberOfCharacters, + FontId fontId, + Script script) { CreatePlugin(); - return mPlugin->Shape( text, - numberOfCharacters, - fontId, - script ); + return mPlugin->Shape(text, + numberOfCharacters, + fontId, + script); } -void Shaping::GetGlyphs( GlyphInfo* glyphInfo, - CharacterIndex* glyphToCharacterMap ) +void Shaping::GetGlyphs(GlyphInfo* glyphInfo, + CharacterIndex* glyphToCharacterMap) { CreatePlugin(); - mPlugin->GetGlyphs( glyphInfo, - glyphToCharacterMap ); + mPlugin->GetGlyphs(glyphInfo, + glyphToCharacterMap); } void Shaping::CreatePlugin() { - if( !mPlugin ) + if(!mPlugin) { mPlugin = new Plugin(); } diff --git a/dali/internal/text/text-abstraction/shaping-impl.h b/dali/internal/text/text-abstraction/shaping-impl.h index 2eb809e..4ba0448 100644 --- a/dali/internal/text/text-abstraction/shaping-impl.h +++ b/dali/internal/text/text-abstraction/shaping-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_SHAPING_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,25 +22,21 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * Implementation of the Shaping */ class Shaping : public BaseObject { public: - /** * Constructor */ @@ -59,31 +55,29 @@ public: /** * @copydoc Dali::Shaping::Shape() */ - Length Shape( const Character* const text, - Length numberOfCharacters, - FontId fontId, - Script script ); + Length Shape(const Character* const text, + Length numberOfCharacters, + FontId fontId, + Script script); /** * @copydoc Dali::Shaping::GetGlyphs() */ - void GetGlyphs( GlyphInfo* glyphInfo, - CharacterIndex* glyphToCharacterMap ); + void GetGlyphs(GlyphInfo* glyphInfo, + CharacterIndex* glyphToCharacterMap); private: - /** * Helper for lazy initialization. */ void CreatePlugin(); private: - // Undefined copy constructor. - Shaping( const Shaping& ); + Shaping(const Shaping&); // Undefined assignment constructor. - Shaping& operator=( const Shaping& ); + Shaping& operator=(const Shaping&); struct Plugin; Plugin* mPlugin; @@ -94,18 +88,18 @@ private: } // namespace TextAbstraction -inline static TextAbstraction::Internal::Shaping& GetImplementation( TextAbstraction::Shaping& shaping ) +inline static TextAbstraction::Internal::Shaping& GetImplementation(TextAbstraction::Shaping& shaping) { - DALI_ASSERT_ALWAYS( shaping && "shaping handle is empty" ); + DALI_ASSERT_ALWAYS(shaping && "shaping handle is empty"); BaseObject& handle = shaping.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } -inline static const TextAbstraction::Internal::Shaping& GetImplementation( const TextAbstraction::Shaping& shaping ) +inline static const TextAbstraction::Internal::Shaping& GetImplementation(const TextAbstraction::Shaping& shaping) { - DALI_ASSERT_ALWAYS( shaping && "shaping handle is empty" ); + DALI_ASSERT_ALWAYS(shaping && "shaping handle is empty"); const BaseObject& handle = shaping.GetBaseObject(); - return static_cast( handle ); + return static_cast(handle); } } // namespace Dali diff --git a/dali/internal/text/text-abstraction/text-renderer-impl.cpp b/dali/internal/text/text-abstraction/text-renderer-impl.cpp old mode 100755 new mode 100644 index a360361..1b29267 --- a/dali/internal/text/text-abstraction/text-renderer-impl.cpp +++ b/dali/internal/text/text-abstraction/text-renderer-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,13 +26,10 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - TextRenderer::TextRenderer() { } @@ -46,15 +43,15 @@ TextAbstraction::TextRenderer TextRenderer::Get() TextAbstraction::TextRenderer shapingHandle; SingletonService service(SingletonService::Get()); - if (service) + if(service) { // Check whether the singleton is already created Dali::BaseHandle handle = service.GetSingleton(typeid(TextAbstraction::TextRenderer)); - if (handle) + if(handle) { // If so, downcast the handle - TextRenderer* impl = dynamic_cast< Internal::TextRenderer* >(handle.GetObjectPtr()); - shapingHandle = TextAbstraction::TextRenderer(impl); + TextRenderer* impl = dynamic_cast(handle.GetObjectPtr()); + shapingHandle = TextAbstraction::TextRenderer(impl); } else // create and register the object { diff --git a/dali/internal/text/text-abstraction/text-renderer-impl.h b/dali/internal/text/text-abstraction/text-renderer-impl.h old mode 100755 new mode 100644 index 5133ff4..1b55b0e --- a/dali/internal/text/text-abstraction/text-renderer-impl.h +++ b/dali/internal/text/text-abstraction/text-renderer-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TEXT_ABSTRACTION_TEXT_RENDERER_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,20 +26,16 @@ namespace Dali { - namespace TextAbstraction { - namespace Internal { - /** * Implementation of the TextRenderer */ class TextRenderer : public BaseObject { public: - /** * Constructor */ @@ -61,7 +57,6 @@ public: Devel::PixelBuffer Render(const TextAbstraction::TextRenderer::Parameters& parameters); private: - // Undefined copy constructor. TextRenderer(const TextRenderer&); diff --git a/dali/internal/text/ubuntu/vector-font-cache.cpp b/dali/internal/text/ubuntu/vector-font-cache.cpp index a6f8175..62523e2 100644 --- a/dali/internal/text/ubuntu/vector-font-cache.cpp +++ b/dali/internal/text/ubuntu/vector-font-cache.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,26 +19,25 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include using namespace std; namespace { - const unsigned int INITIAL_GLYPH_CAPACITY = 50; -const double MIN_FONT_SIZE = 10; +const double MIN_FONT_SIZE = 10; static glyphy_bool_t -accumulate_endpoint( glyphy_arc_endpoint_t* endpoint, - vector* endpoints ) +accumulate_endpoint(glyphy_arc_endpoint_t* endpoint, + vector* endpoints) { - endpoints->push_back( *endpoint ); + endpoints->push_back(*endpoint); return true; } @@ -46,13 +45,10 @@ accumulate_endpoint( glyphy_arc_endpoint_t* endpoint, namespace Dali { - namespace TextAbstraction { - namespace Internal { - typedef vector BlobArray; struct VectorGlyph @@ -60,79 +56,79 @@ struct VectorGlyph /** * @brief Create a vector-based glyph. */ - static VectorGlyph* New( FT_Face face, - FontId fontId, - GlyphIndex index, - glyphy_arc_accumulator_t* accumulator ) + static VectorGlyph* New(FT_Face face, + FontId fontId, + GlyphIndex index, + glyphy_arc_accumulator_t* accumulator) { VectorGlyph* newGlyph = new VectorGlyph(); - newGlyph->blobData.resize( 1024 * 16 ); + newGlyph->blobData.resize(1024 * 16); - if( FT_Err_Ok != FT_Load_Glyph( face, - index, - FT_LOAD_NO_BITMAP | + if(FT_Err_Ok != FT_Load_Glyph(face, + index, + FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT | FT_LOAD_NO_SCALE | FT_LOAD_LINEAR_DESIGN | FT_LOAD_IGNORE_TRANSFORM)) { - DALI_LOG_ERROR( "FT_Load_Glyph failed\n" ); + DALI_LOG_ERROR("FT_Load_Glyph failed\n"); delete newGlyph; return NULL; } - const double upem = static_cast( face->units_per_EM ); - const double tolerance = upem * 1.0f/2048.0f; + const double upem = static_cast(face->units_per_EM); + const double tolerance = upem * 1.0f / 2048.0f; - glyphy_arc_accumulator_reset( accumulator); - glyphy_arc_accumulator_set_tolerance( accumulator, tolerance ); + glyphy_arc_accumulator_reset(accumulator); + glyphy_arc_accumulator_set_tolerance(accumulator, tolerance); vector endpoints; - glyphy_arc_accumulator_set_callback( accumulator, - reinterpret_cast( accumulate_endpoint ), - &endpoints ); + glyphy_arc_accumulator_set_callback(accumulator, + reinterpret_cast(accumulate_endpoint), + &endpoints); - if( FT_Err_Ok != glyphy_freetype_outline_decompose( &face->glyph->outline, accumulator ) ) + if(FT_Err_Ok != glyphy_freetype_outline_decompose(&face->glyph->outline, accumulator)) { - DALI_LOG_ERROR( "glyphy_freetype_outline_decompose failed\n" ); + DALI_LOG_ERROR("glyphy_freetype_outline_decompose failed\n"); delete newGlyph; return NULL; } - DALI_ASSERT_DEBUG( glyphy_arc_accumulator_get_error(accumulator) <= tolerance && "glyphy_arc_accumulator_get_error > tolerance" ); + DALI_ASSERT_DEBUG(glyphy_arc_accumulator_get_error(accumulator) <= tolerance && "glyphy_arc_accumulator_get_error > tolerance"); - if( endpoints.size() ) + if(endpoints.size()) { - glyphy_outline_winding_from_even_odd( &endpoints[0], endpoints.size (), false ); + glyphy_outline_winding_from_even_odd(&endpoints[0], endpoints.size(), false); } - unsigned int blobLength( 0 ); - double averageFetchAchieved( 0.0 ); - if (!glyphy_arc_list_encode_blob( endpoints.size() ? &endpoints[0] : NULL, - endpoints.size(), - &newGlyph->blobData[0], - newGlyph->blobData.capacity(), - upem / ( MIN_FONT_SIZE * M_SQRT2 ), - 4, - &averageFetchAchieved, - &blobLength, - &newGlyph->nominalWidth, - &newGlyph->nominalHeight, - &newGlyph->extents ) ) + unsigned int blobLength(0); + double averageFetchAchieved(0.0); + if(!glyphy_arc_list_encode_blob(endpoints.size() ? &endpoints[0] : NULL, + endpoints.size(), + &newGlyph->blobData[0], + newGlyph->blobData.capacity(), + upem / (MIN_FONT_SIZE * M_SQRT2), + 4, + &averageFetchAchieved, + &blobLength, + &newGlyph->nominalWidth, + &newGlyph->nominalHeight, + &newGlyph->extents)) { - DALI_LOG_ERROR( "glyphy_arc_list_encode_blob failed\n" ); + DALI_LOG_ERROR("glyphy_arc_list_encode_blob failed\n"); delete newGlyph; return NULL; } - newGlyph->blobData.resize( blobLength ); + newGlyph->blobData.resize(blobLength); - glyphy_extents_scale( &newGlyph->extents, 1.0/upem, 1.0/upem ); + glyphy_extents_scale(&newGlyph->extents, 1.0 / upem, 1.0 / upem); newGlyph->glyphInfo.fontId = fontId; newGlyph->glyphInfo.index = index; - if( glyphy_extents_is_empty( &newGlyph->extents ) ) + if(glyphy_extents_is_empty(&newGlyph->extents)) { newGlyph->glyphInfo.width = 0.0f; newGlyph->glyphInfo.height = 0.0f; @@ -149,20 +145,20 @@ struct VectorGlyph newGlyph->glyphInfo.yBearing = newGlyph->glyphInfo.height + (newGlyph->extents.min_y); } - newGlyph->glyphInfo.advance = face->glyph->metrics.horiAdvance / upem; + newGlyph->glyphInfo.advance = face->glyph->metrics.horiAdvance / upem; newGlyph->glyphInfo.scaleFactor = 0.0f; return newGlyph; } VectorGlyph() - : advance( 0.0 ), - nominalWidth( 0 ), - nominalHeight( 0 ), + : advance(0.0), + nominalWidth(0), + nominalHeight(0), glyphInfo(), blobData() { - glyphy_extents_clear( &extents ); + glyphy_extents_clear(&extents); } glyphy_extents_t extents; @@ -177,11 +173,11 @@ typedef vector GlyphCache; struct VectorFont { - VectorFont( FT_Face face ) - : mFace( face ), + VectorFont(FT_Face face) + : mFace(face), mGlyphCache() { - mGlyphCache.reserve( INITIAL_GLYPH_CAPACITY ); + mGlyphCache.reserve(INITIAL_GLYPH_CAPACITY); } FT_Face mFace; @@ -190,29 +186,27 @@ struct VectorFont struct VectorFontCache::Impl { - Impl( FT_Library freeTypeLibrary ) - : mFreeTypeLibrary( freeTypeLibrary ), + Impl(FT_Library freeTypeLibrary) + : mFreeTypeLibrary(freeTypeLibrary), mIdLookup(), mVectorFonts(), - mAccumulator( NULL ) + mAccumulator(NULL) { mAccumulator = glyphy_arc_accumulator_create(); } ~Impl() { - glyphy_arc_accumulator_destroy( mAccumulator ); + glyphy_arc_accumulator_destroy(mAccumulator); } private: - // Declared private and left undefined to avoid copies. - Impl( const Impl& ); + Impl(const Impl&); // Declared private and left undefined to avoid copies. - Impl& operator=( const Impl& ); + Impl& operator=(const Impl&); public: - FT_Library mFreeTypeLibrary; ///< A handle to a FreeType library instance. vector mIdLookup; @@ -222,10 +216,10 @@ public: glyphy_arc_accumulator_t* mAccumulator; }; -VectorFontCache::VectorFontCache( FT_Library freeTypeLibrary ) -: mImpl( NULL ) +VectorFontCache::VectorFontCache(FT_Library freeTypeLibrary) +: mImpl(NULL) { - mImpl = new Impl( freeTypeLibrary ); + mImpl = new Impl(freeTypeLibrary); } VectorFontCache::~VectorFontCache() @@ -233,38 +227,38 @@ VectorFontCache::~VectorFontCache() delete mImpl; } -FontId VectorFontCache::GetFontId( const std::string& url ) +FontId VectorFontCache::GetFontId(const std::string& url) { - FontId id( 0 ); + FontId id(0); - if( mImpl ) + if(mImpl) { - if( ! FindFont( url, id ) ) + if(!FindFont(url, id)) { - id = CreateFont( url ); + id = CreateFont(url); } } return id; } -void VectorFontCache::GetGlyphMetrics( FontId vectorFontId, GlyphInfo& glyphInfo ) +void VectorFontCache::GetGlyphMetrics(FontId vectorFontId, GlyphInfo& glyphInfo) { - if( mImpl ) + if(mImpl) { - if( vectorFontId > 0 && - vectorFontId-1 < mImpl->mVectorFonts.size() ) + if(vectorFontId > 0 && + vectorFontId - 1 < mImpl->mVectorFonts.size()) { - VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ]; + VectorFont* font = mImpl->mVectorFonts[vectorFontId - 1]; GlyphCache& cache = font->mGlyphCache; - bool foundGlyph( false ); - unsigned int foundIndex( 0 ); - for( unsigned int i=0; iglyphInfo.index == glyphInfo.index ) + if(glyph->glyphInfo.index == glyphInfo.index) { foundIndex = i; foundGlyph = true; @@ -272,7 +266,7 @@ void VectorFontCache::GetGlyphMetrics( FontId vectorFontId, GlyphInfo& glyphInfo } } - if( foundGlyph ) + if(foundGlyph) { VectorGlyph* glyph = cache[foundIndex]; // Note - this clobbers the original fontId, but helps avoid duplicating identical blobs @@ -281,45 +275,45 @@ void VectorFontCache::GetGlyphMetrics( FontId vectorFontId, GlyphInfo& glyphInfo } else { - VectorGlyph* newGlyph = VectorGlyph::New( font->mFace, - glyphInfo.fontId, - glyphInfo.index, - mImpl->mAccumulator ); + VectorGlyph* newGlyph = VectorGlyph::New(font->mFace, + glyphInfo.fontId, + glyphInfo.index, + mImpl->mAccumulator); - if( newGlyph ) + if(newGlyph) { glyphInfo = newGlyph->glyphInfo; - cache.push_back( newGlyph ); + cache.push_back(newGlyph); } } } } } -void VectorFontCache::GetVectorBlob( FontId vectorFontId, - FontId fontId, - GlyphIndex glyphIndex, - VectorBlob*& blob, - unsigned int& blobLength, - unsigned int& nominalWidth, - unsigned int& nominalHeight ) +void VectorFontCache::GetVectorBlob(FontId vectorFontId, + FontId fontId, + GlyphIndex glyphIndex, + VectorBlob*& blob, + unsigned int& blobLength, + unsigned int& nominalWidth, + unsigned int& nominalHeight) { - if( mImpl ) + if(mImpl) { - if( vectorFontId > 0 && - vectorFontId-1 < mImpl->mVectorFonts.size() ) + if(vectorFontId > 0 && + vectorFontId - 1 < mImpl->mVectorFonts.size()) { - VectorFont* font = mImpl->mVectorFonts[ vectorFontId-1 ]; + VectorFont* font = mImpl->mVectorFonts[vectorFontId - 1]; GlyphCache& cache = font->mGlyphCache; - bool foundGlyph( false ); - unsigned int foundIndex( 0 ); - for( unsigned int i=0; iglyphInfo.index == glyphIndex ) + if(glyph->glyphInfo.index == glyphIndex) { foundIndex = i; foundGlyph = true; @@ -327,7 +321,7 @@ void VectorFontCache::GetVectorBlob( FontId vectorFontId, } } - if( foundGlyph ) + if(foundGlyph) { VectorGlyph* glyph = cache[foundIndex]; @@ -338,31 +332,31 @@ void VectorFontCache::GetVectorBlob( FontId vectorFontId, } else { - VectorGlyph* newGlyph = VectorGlyph::New( font->mFace, fontId, glyphIndex, mImpl->mAccumulator ); + VectorGlyph* newGlyph = VectorGlyph::New(font->mFace, fontId, glyphIndex, mImpl->mAccumulator); - if( newGlyph ) + if(newGlyph) { blob = &newGlyph->blobData[0]; blobLength = newGlyph->blobData.size(); nominalWidth = newGlyph->nominalWidth; nominalHeight = newGlyph->nominalHeight; - cache.push_back( newGlyph ); + cache.push_back(newGlyph); } } } } } -bool VectorFontCache::FindFont( const string& url, FontId& vectorFontId ) const +bool VectorFontCache::FindFont(const string& url, FontId& vectorFontId) const { vectorFontId = 0u; const vector& idLookup = mImpl->mIdLookup; - for( unsigned int i=0; imFreeTypeLibrary, - url.c_str(), - 0, - &face ); + int error = FT_New_Face(mImpl->mFreeTypeLibrary, + url.c_str(), + 0, + &face); - if( FT_Err_Ok == error ) + if(FT_Err_Ok == error) { - mImpl->mIdLookup.push_back( url ); + mImpl->mIdLookup.push_back(url); id = mImpl->mIdLookup.size(); - VectorFont* newFont = new VectorFont( face ); - mImpl->mVectorFonts.push_back( newFont ); + VectorFont* newFont = new VectorFont(face); + mImpl->mVectorFonts.push_back(newFont); - DALI_ASSERT_DEBUG( mImpl->mIdLookup.size() == mImpl->mVectorFonts.size() ); + DALI_ASSERT_DEBUG(mImpl->mIdLookup.size() == mImpl->mVectorFonts.size()); } return id; diff --git a/dali/internal/thread/common/thread-settings-impl.cpp b/dali/internal/thread/common/thread-settings-impl.cpp index 849cb4d..aa0616e 100644 --- a/dali/internal/thread/common/thread-settings-impl.cpp +++ b/dali/internal/thread/common/thread-settings-impl.cpp @@ -23,22 +23,18 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace ThreadSettings { - void SetThreadName(const std::string& threadName) { int err = prctl(PR_SET_NAME, threadName.c_str()); - if ( err ) + if(err) { - DALI_LOG_ERROR( "prctl(PR_SET_NAME, %s) failed\n", threadName.c_str() ); + DALI_LOG_ERROR("prctl(PR_SET_NAME, %s) failed\n", threadName.c_str()); } } diff --git a/dali/internal/thread/common/thread-settings-impl.h b/dali/internal/thread/common/thread-settings-impl.h index 43f1c09..b091736 100644 --- a/dali/internal/thread/common/thread-settings-impl.h +++ b/dali/internal/thread/common/thread-settings-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_THREAD_SETTINGS_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,24 +19,20 @@ */ // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Implementation of the Thread Settings */ namespace ThreadSettings { - /** * @brief Set the thread name. * diff --git a/dali/internal/trace/android/trace-factory-android.cpp b/dali/internal/trace/android/trace-factory-android.cpp index 3e78e8a..831c45a 100644 --- a/dali/internal/trace/android/trace-factory-android.cpp +++ b/dali/internal/trace/android/trace-factory-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,25 +15,21 @@ * */ -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TraceManagerFactory { - // TraceManager Factory to be implemented by the platform -TraceManagerUPtr CreateTraceFactory( PerformanceInterface* performanceInterface ) +TraceManagerUPtr CreateTraceFactory(PerformanceInterface* performanceInterface) { - return TraceManagerUPtr( new Dali::Internal::Adaptor::TraceManagerAndroid( performanceInterface ) ); + return TraceManagerUPtr(new Dali::Internal::Adaptor::TraceManagerAndroid(performanceInterface)); } } // namespace TraceManagerFactory @@ -42,4 +38,4 @@ TraceManagerUPtr CreateTraceFactory( PerformanceInterface* performanceInterface } // namespace Internal -} // namespace Dali // namespace Dali +} // namespace Dali diff --git a/dali/internal/trace/android/trace-manager-impl-android.cpp b/dali/internal/trace/android/trace-manager-impl-android.cpp index d0d235c..ddad644 100644 --- a/dali/internal/trace/android/trace-manager-impl-android.cpp +++ b/dali/internal/trace/android/trace-manager-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,25 +16,21 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES namespace Dali { - - namespace Internal { - namespace Adaptor { - TraceManagerAndroid* TraceManagerAndroid::traceManagerAndroid = nullptr; -TraceManagerAndroid::TraceManagerAndroid( PerformanceInterface* performanceInterface ) -: TraceManager( performanceInterface ) +TraceManagerAndroid::TraceManagerAndroid(PerformanceInterface* performanceInterface) +: TraceManager(performanceInterface) { TraceManagerAndroid::traceManagerAndroid = this; } @@ -44,17 +40,17 @@ Dali::Integration::Trace::LogContextFunction TraceManagerAndroid::GetLogContextF return LogContext; } -void TraceManagerAndroid::LogContext( bool start, const char* tag ) +void TraceManagerAndroid::LogContext(bool start, const char* tag) { - if( start ) + if(start) { - unsigned short contextId = traceManagerAndroid->mPerformanceInterface->AddContext( tag ); - traceManagerAndroid->mPerformanceInterface->AddMarker( PerformanceInterface::START, contextId ); + unsigned short contextId = traceManagerAndroid->mPerformanceInterface->AddContext(tag); + traceManagerAndroid->mPerformanceInterface->AddMarker(PerformanceInterface::START, contextId); } else { - unsigned short contextId = traceManagerAndroid->mPerformanceInterface->AddContext( tag ); - traceManagerAndroid->mPerformanceInterface->AddMarker( PerformanceInterface::END, contextId ); + unsigned short contextId = traceManagerAndroid->mPerformanceInterface->AddContext(tag); + traceManagerAndroid->mPerformanceInterface->AddMarker(PerformanceInterface::END, contextId); } } diff --git a/dali/internal/trace/android/trace-manager-impl-android.h b/dali/internal/trace/android/trace-manager-impl-android.h index 1107d4e..66703da 100644 --- a/dali/internal/trace/android/trace-manager-impl-android.h +++ b/dali/internal/trace/android/trace-manager-impl-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRACE_MANAGER_IMPL_ANDROID_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class PerformanceInterface; @@ -45,7 +43,7 @@ public: /** * Explicit Constructor */ - explicit TraceManagerAndroid( PerformanceInterface* performanceInterface ); + explicit TraceManagerAndroid(PerformanceInterface* performanceInterface); protected: /** @@ -59,11 +57,10 @@ protected: Dali::Integration::Trace::LogContextFunction GetLogContextFunction() final; private: - /** * LogContext method (Android specific) used for tracing */ - static void LogContext( bool start, const char* tag ); + static void LogContext(bool start, const char* tag); }; } // namespace Adaptor diff --git a/dali/internal/trace/common/trace-factory.cpp b/dali/internal/trace/common/trace-factory.cpp index c7d15f7..b9ed5d3 100644 --- a/dali/internal/trace/common/trace-factory.cpp +++ b/dali/internal/trace/common/trace-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,21 +19,18 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TraceManagerFactory { - // Factory function creating new TraceFactory // Symbol exists but may be overriden during linking __attribute__((weak)) -TraceManagerUPtr CreateTraceFactory( PerformanceInterface* performanceInterface ) +TraceManagerUPtr +CreateTraceFactory(PerformanceInterface* performanceInterface) { // return empty handle if TraceManager not implemented return nullptr; diff --git a/dali/internal/trace/common/trace-factory.h b/dali/internal/trace/common/trace-factory.h index 5f1cfb9..1a2b16b 100644 --- a/dali/internal/trace/common/trace-factory.h +++ b/dali/internal/trace/common/trace-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRACE_FACTORY_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,21 +26,17 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TraceManagerFactory { - using TraceManagerUPtr = std::unique_ptr; // Factory function creating new TraceFactory // Symbol exists but may be overriden during linking -TraceManagerUPtr CreateTraceFactory( PerformanceInterface* performanceInterface ); +TraceManagerUPtr CreateTraceFactory(PerformanceInterface* performanceInterface); } // namespace TraceManagerFactory diff --git a/dali/internal/trace/common/trace-manager-impl.cpp b/dali/internal/trace/common/trace-manager-impl.cpp index 8a34c2f..b80c1eb 100644 --- a/dali/internal/trace/common/trace-manager-impl.cpp +++ b/dali/internal/trace/common/trace-manager-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,26 +22,23 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - -TraceManager::TraceManager( PerformanceInterface* performanceInterface ) -: mPerformanceInterface( performanceInterface ) +TraceManager::TraceManager(PerformanceInterface* performanceInterface) +: mPerformanceInterface(performanceInterface) { } bool TraceManager::Initialise() { auto logFunction = GetLogContextFunction(); - if( !logFunction ) + if(!logFunction) { - return false; + return false; } - Dali::Integration::Trace::InstallLogContextFunction( logFunction ); + Dali::Integration::Trace::InstallLogContextFunction(logFunction); return true; } diff --git a/dali/internal/trace/common/trace-manager-impl.h b/dali/internal/trace/common/trace-manager-impl.h index 7bbb6cc..94a8e4c 100644 --- a/dali/internal/trace/common/trace-manager-impl.h +++ b/dali/internal/trace/common/trace-manager-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRACE_MANAGER_IMPL_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,10 @@ // INTERNAL INCLUDES - namespace Dali { - namespace Internal { - namespace Adaptor { class PerformanceInterface; @@ -37,11 +34,10 @@ class PerformanceInterface; class TraceManager { public: - /** * Explicit Constructor */ - explicit TraceManager( PerformanceInterface* performanceInterface ); + explicit TraceManager(PerformanceInterface* performanceInterface); /** * Constructor @@ -64,22 +60,23 @@ public: PerformanceInterface* mPerformanceInterface; protected: - /** * Obtain the platform dependent LogContextFunction method used for tracing */ - virtual Dali::Integration::Trace::LogContextFunction GetLogContextFunction() { return nullptr; }; + virtual Dali::Integration::Trace::LogContextFunction GetLogContextFunction() + { + return nullptr; + }; private: - /** * Set / Install the platform dependent trace function * @param logContextFunction - Platform dependent trace function */ - void SetTraceLogContextFunction( const Dali::Integration::Trace::LogContextFunction& logContextFunction ); + void SetTraceLogContextFunction(const Dali::Integration::Trace::LogContextFunction& logContextFunction); - TraceManager( const TraceManager& ) = delete; - TraceManager& operator=( TraceManager& ) = delete; + TraceManager(const TraceManager&) = delete; + TraceManager& operator=(TraceManager&) = delete; }; } // namespace Adaptor diff --git a/dali/internal/trace/generic/trace-factory-generic.cpp b/dali/internal/trace/generic/trace-factory-generic.cpp index 9c30534..5609c38 100644 --- a/dali/internal/trace/generic/trace-factory-generic.cpp +++ b/dali/internal/trace/generic/trace-factory-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +20,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TraceManagerFactory { - // TraceManager Factory to be implemented by the platform -TraceManagerUPtr CreateTraceFactory( PerformanceInterface* performanceInterface ) +TraceManagerUPtr CreateTraceFactory(PerformanceInterface* performanceInterface) { - return TraceManagerUPtr( new Dali::Internal::Adaptor::TraceManagerGeneric( performanceInterface ) ); + return TraceManagerUPtr(new Dali::Internal::Adaptor::TraceManagerGeneric(performanceInterface)); } } // namespace TraceManagerFactory diff --git a/dali/internal/trace/generic/trace-manager-impl-generic.cpp b/dali/internal/trace/generic/trace-manager-impl-generic.cpp index e741a64..92ada6e 100644 --- a/dali/internal/trace/generic/trace-manager-impl-generic.cpp +++ b/dali/internal/trace/generic/trace-manager-impl-generic.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,21 @@ */ // EXTERNAL INCLUDES -#include #include "trace-manager-impl-generic.h" +#include // INTERNAL INCLUDES namespace Dali { - namespace Internal { - namespace Adaptor { - TraceManagerGeneric* TraceManagerGeneric::traceManagerGeneric = nullptr; -TraceManagerGeneric::TraceManagerGeneric( PerformanceInterface* performanceInterface ) -: TraceManager( performanceInterface ) +TraceManagerGeneric::TraceManagerGeneric(PerformanceInterface* performanceInterface) +: TraceManager(performanceInterface) { TraceManagerGeneric::traceManagerGeneric = this; } @@ -43,17 +40,17 @@ Dali::Integration::Trace::LogContextFunction TraceManagerGeneric::GetLogContextF return LogContext; } -void TraceManagerGeneric::LogContext( bool start, const char* tag ) +void TraceManagerGeneric::LogContext(bool start, const char* tag) { - if( start ) + if(start) { - unsigned short contextId = traceManagerGeneric->mPerformanceInterface->AddContext( tag ); - traceManagerGeneric->mPerformanceInterface->AddMarker( PerformanceInterface::START, contextId ); + unsigned short contextId = traceManagerGeneric->mPerformanceInterface->AddContext(tag); + traceManagerGeneric->mPerformanceInterface->AddMarker(PerformanceInterface::START, contextId); } else { - unsigned short contextId = traceManagerGeneric->mPerformanceInterface->AddContext( tag ); - traceManagerGeneric->mPerformanceInterface->AddMarker( PerformanceInterface::END, contextId ); + unsigned short contextId = traceManagerGeneric->mPerformanceInterface->AddContext(tag); + traceManagerGeneric->mPerformanceInterface->AddMarker(PerformanceInterface::END, contextId); } } diff --git a/dali/internal/trace/generic/trace-manager-impl-generic.h b/dali/internal/trace/generic/trace-manager-impl-generic.h index d7ff58f..99cb917 100644 --- a/dali/internal/trace/generic/trace-manager-impl-generic.h +++ b/dali/internal/trace/generic/trace-manager-impl-generic.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRACE_MANAGER_IMPL_GENERIC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class PerformanceInterface; @@ -45,7 +43,7 @@ public: /** * Explicit Constructor */ - explicit TraceManagerGeneric( PerformanceInterface* performanceInterface ); + explicit TraceManagerGeneric(PerformanceInterface* performanceInterface); protected: /** @@ -59,11 +57,10 @@ protected: Dali::Integration::Trace::LogContextFunction GetLogContextFunction() final; private: - /** * LogContext method (Generic specific) used for tracing */ - static void LogContext( bool start, const char* tag ); + static void LogContext(bool start, const char* tag); }; } // namespace Adaptor diff --git a/dali/internal/trace/tizen/trace-factory-tizen.cpp b/dali/internal/trace/tizen/trace-factory-tizen.cpp index 51715ba..4a05648 100644 --- a/dali/internal/trace/tizen/trace-factory-tizen.cpp +++ b/dali/internal/trace/tizen/trace-factory-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +20,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace TraceManagerFactory { - // TraceManager Factory to be implemented by the platform -TraceManagerUPtr CreateTraceFactory( PerformanceInterface* performanceInterface ) +TraceManagerUPtr CreateTraceFactory(PerformanceInterface* performanceInterface) { - return TraceManagerUPtr( new Dali::Internal::Adaptor::TraceManagerTizen( performanceInterface ) ); + return TraceManagerUPtr(new Dali::Internal::Adaptor::TraceManagerTizen(performanceInterface)); } } // namespace TraceManagerFactory diff --git a/dali/internal/trace/tizen/trace-manager-impl-tizen.cpp b/dali/internal/trace/tizen/trace-manager-impl-tizen.cpp index 9095bcf..41e8205 100644 --- a/dali/internal/trace/tizen/trace-manager-impl-tizen.cpp +++ b/dali/internal/trace/tizen/trace-manager-impl-tizen.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,22 +16,19 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES namespace Dali { - namespace Internal { - namespace Adaptor { - -TraceManagerTizen::TraceManagerTizen( PerformanceInterface* performanceInterface ) -: TraceManager( performanceInterface ) +TraceManagerTizen::TraceManagerTizen(PerformanceInterface* performanceInterface) +: TraceManager(performanceInterface) { } @@ -40,15 +37,15 @@ Dali::Integration::Trace::LogContextFunction TraceManagerTizen::GetLogContextFun return LogContext; } -void TraceManagerTizen::LogContext( bool start, const char* tag ) +void TraceManagerTizen::LogContext(bool start, const char* tag) { - if( start ) + if(start) { - traceBegin( TTRACE_TAG_GRAPHICS, tag ); + traceBegin(TTRACE_TAG_GRAPHICS, tag); } else { - traceEnd( TTRACE_TAG_GRAPHICS ); + traceEnd(TTRACE_TAG_GRAPHICS); } } diff --git a/dali/internal/trace/tizen/trace-manager-impl-tizen.h b/dali/internal/trace/tizen/trace-manager-impl-tizen.h index c596bcc..c01248c 100644 --- a/dali/internal/trace/tizen/trace-manager-impl-tizen.h +++ b/dali/internal/trace/tizen/trace-manager-impl-tizen.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_TRACE_MANAGER_IMPL_TIZEN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class PerformanceInterface; @@ -39,10 +37,9 @@ public: /** * Explicit Constructor */ - explicit TraceManagerTizen( PerformanceInterface* performanceInterface ); + explicit TraceManagerTizen(PerformanceInterface* performanceInterface); protected: - /** * Destructor */ @@ -54,11 +51,10 @@ protected: Dali::Integration::Trace::LogContextFunction GetLogContextFunction() final; private: - /** * LogContext method (Tizen specific) used for tracing */ - static void LogContext( bool start, const char* tag ); + static void LogContext(bool start, const char* tag); }; } // namespace Adaptor diff --git a/dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp b/dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp index 9b1c9da..b80b64b 100644 --- a/dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp +++ b/dali/internal/vector-animation/common/vector-animation-renderer-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,23 +25,19 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { - // Type Registration Dali::BaseHandle Create() { return Dali::BaseHandle(); } -Dali::TypeRegistration type( typeid( Dali::VectorAnimationRenderer ), typeid( Dali::BaseHandle ), Create ); +Dali::TypeRegistration type(typeid(Dali::VectorAnimationRenderer), typeid(Dali::BaseHandle), Create); } // unnamed namespace @@ -52,7 +48,7 @@ VectorAnimationRendererPtr VectorAnimationRenderer::New() } VectorAnimationRenderer::VectorAnimationRenderer() -: mPlugin( std::string() ) +: mPlugin(std::string()) { } @@ -60,9 +56,9 @@ VectorAnimationRenderer::~VectorAnimationRenderer() { } -void VectorAnimationRenderer::Initialize( const std::string& url ) +void VectorAnimationRenderer::Initialize(const std::string& url) { - mPlugin.Initialize( url ); + mPlugin.Initialize(url); } void VectorAnimationRenderer::Finalize() @@ -70,19 +66,19 @@ void VectorAnimationRenderer::Finalize() mPlugin.Finalize(); } -void VectorAnimationRenderer::SetRenderer( Dali::Renderer renderer ) +void VectorAnimationRenderer::SetRenderer(Dali::Renderer renderer) { - mPlugin.SetRenderer( renderer ); + mPlugin.SetRenderer(renderer); } -void VectorAnimationRenderer::SetSize( uint32_t width, uint32_t height ) +void VectorAnimationRenderer::SetSize(uint32_t width, uint32_t height) { - mPlugin.SetSize( width, height ); + mPlugin.SetSize(width, height); } -bool VectorAnimationRenderer::Render( uint32_t frameNumber ) +bool VectorAnimationRenderer::Render(uint32_t frameNumber) { - return mPlugin.Render( frameNumber ); + return mPlugin.Render(frameNumber); } uint32_t VectorAnimationRenderer::GetTotalFrameNumber() const @@ -95,19 +91,19 @@ float VectorAnimationRenderer::GetFrameRate() const return mPlugin.GetFrameRate(); } -void VectorAnimationRenderer::GetDefaultSize( uint32_t& width, uint32_t& height ) const +void VectorAnimationRenderer::GetDefaultSize(uint32_t& width, uint32_t& height) const { - mPlugin.GetDefaultSize( width, height ); + mPlugin.GetDefaultSize(width, height); } -void VectorAnimationRenderer::GetLayerInfo( Property::Map& map ) const +void VectorAnimationRenderer::GetLayerInfo(Property::Map& map) const { - mPlugin.GetLayerInfo( map ); + mPlugin.GetLayerInfo(map); } -bool VectorAnimationRenderer::GetMarkerInfo( const std::string& marker, uint32_t& startFrame, uint32_t& endFrame ) const +bool VectorAnimationRenderer::GetMarkerInfo(const std::string& marker, uint32_t& startFrame, uint32_t& endFrame) const { - return mPlugin.GetMarkerInfo( marker, startFrame, endFrame ); + return mPlugin.GetMarkerInfo(marker, startFrame, endFrame); } void VectorAnimationRenderer::IgnoreRenderedFrame() @@ -122,6 +118,6 @@ Dali::VectorAnimationRenderer::UploadCompletedSignalType& VectorAnimationRendere } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/vector-animation/common/vector-animation-renderer-impl.h b/dali/internal/vector-animation/common/vector-animation-renderer-impl.h old mode 100755 new mode 100644 index 0d2a428..df676bb --- a/dali/internal/vector-animation/common/vector-animation-renderer-impl.h +++ b/dali/internal/vector-animation/common/vector-animation-renderer-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_VECTOR_ANIMATION_RENDERER_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,15 +27,12 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class VectorAnimationRenderer; -using VectorAnimationRendererPtr = IntrusivePtr< VectorAnimationRenderer >; +using VectorAnimationRendererPtr = IntrusivePtr; /** * Dali internal VectorAnimationRenderer. @@ -43,7 +40,6 @@ using VectorAnimationRendererPtr = IntrusivePtr< VectorAnimationRenderer >; class VectorAnimationRenderer : public BaseObject, public ConnectionTracker { public: - /** * @brief Creates a VectorAnimationRenderer object. * @@ -54,7 +50,7 @@ public: /** * @brief Initializes member data. */ - void Initialize( const std::string& url ); + void Initialize(const std::string& url); /** * @copydoc Dali::VectorAnimationRenderer::Finalize() @@ -64,17 +60,17 @@ public: /** * @copydoc Dali::VectorAnimationRenderer::SetRenderer() */ - void SetRenderer( Dali::Renderer renderer ); + void SetRenderer(Dali::Renderer renderer); /** * @copydoc Dali::VectorAnimationRenderer::SetSize() */ - void SetSize( uint32_t width, uint32_t height ); + void SetSize(uint32_t width, uint32_t height); /** * @copydoc Dali::VectorAnimationRenderer::Render() */ - bool Render( uint32_t frameNumber ); + bool Render(uint32_t frameNumber); /** * @copydoc Dali::VectorAnimationRenderer::GetTotalFrameNumber() @@ -89,17 +85,17 @@ public: /** * @copydoc Dali::VectorAnimationRenderer::GetDefaultSize() */ - void GetDefaultSize( uint32_t& width, uint32_t& height ) const; + void GetDefaultSize(uint32_t& width, uint32_t& height) const; /** * @copydoc Dali::VectorAnimationRenderer::GetLayerInfo() */ - void GetLayerInfo( Property::Map& map ) const; + void GetLayerInfo(Property::Map& map) const; /** * @copydoc Dali::VectorAnimationRenderer::GetMarkerInfo() */ - bool GetMarkerInfo( const std::string& marker, uint32_t& startFrame, uint32_t& endFrame ) const; + bool GetMarkerInfo(const std::string& marker, uint32_t& startFrame, uint32_t& endFrame) const; /** * @copydoc Dali::VectorAnimationRenderer::IgnoreRenderedFrame() @@ -112,7 +108,6 @@ public: Dali::VectorAnimationRenderer::UploadCompletedSignalType& UploadCompletedSignal(); private: - /** * @brief Constructor */ @@ -124,12 +119,10 @@ private: ~VectorAnimationRenderer(); private: - - VectorAnimationRenderer( const VectorAnimationRenderer& ) = delete; - VectorAnimationRenderer& operator=( VectorAnimationRenderer& ) = delete; + VectorAnimationRenderer(const VectorAnimationRenderer&) = delete; + VectorAnimationRenderer& operator=(VectorAnimationRenderer&) = delete; private: - VectorAnimationRendererPluginProxy mPlugin; }; @@ -137,22 +130,22 @@ private: } // namespace Internal -inline static Internal::Adaptor::VectorAnimationRenderer& GetImplementation( Dali::VectorAnimationRenderer& renderer ) +inline static Internal::Adaptor::VectorAnimationRenderer& GetImplementation(Dali::VectorAnimationRenderer& renderer) { - DALI_ASSERT_ALWAYS( renderer && "VectorAnimationRenderer handle is empty." ); + DALI_ASSERT_ALWAYS(renderer && "VectorAnimationRenderer handle is empty."); BaseObject& handle = renderer.GetBaseObject(); - return static_cast< Internal::Adaptor::VectorAnimationRenderer& >( handle ); + return static_cast(handle); } -inline static const Internal::Adaptor::VectorAnimationRenderer& GetImplementation( const Dali::VectorAnimationRenderer& renderer ) +inline static const Internal::Adaptor::VectorAnimationRenderer& GetImplementation(const Dali::VectorAnimationRenderer& renderer) { - DALI_ASSERT_ALWAYS( renderer && "VectorAnimationRenderer handle is empty." ); + DALI_ASSERT_ALWAYS(renderer && "VectorAnimationRenderer handle is empty."); const BaseObject& handle = renderer.GetBaseObject(); - return static_cast< const Internal::Adaptor::VectorAnimationRenderer& >( handle ); + return static_cast(handle); } } // namespace Dali diff --git a/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.cpp b/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.cpp index b2e2eac..97c3d5b 100644 --- a/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.cpp +++ b/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,34 +19,30 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - // The default plugin name -const char* DEFAULT_OBJECT_NAME( "libdali2-vector-animation-renderer-plugin.so" ); +const char* DEFAULT_OBJECT_NAME("libdali2-vector-animation-renderer-plugin.so"); -} +} // namespace -VectorAnimationRendererPluginProxy::VectorAnimationRendererPluginProxy( const std::string& sharedObjectName ) +VectorAnimationRendererPluginProxy::VectorAnimationRendererPluginProxy(const std::string& sharedObjectName) : mSharedObjectName(), - mLibHandle( NULL ), - mPlugin( NULL ), - mCreateVectorAnimationRendererPtr( NULL ), + mLibHandle(NULL), + mPlugin(NULL), + mCreateVectorAnimationRendererPtr(NULL), mDefaultSignal() { - if( !sharedObjectName.empty() ) + if(!sharedObjectName.empty()) { mSharedObjectName = sharedObjectName; } @@ -60,92 +56,92 @@ VectorAnimationRendererPluginProxy::VectorAnimationRendererPluginProxy( const st VectorAnimationRendererPluginProxy::~VectorAnimationRendererPluginProxy() { - if( mPlugin ) + if(mPlugin) { delete mPlugin; mPlugin = NULL; - if( mLibHandle && dlclose( mLibHandle ) ) + if(mLibHandle && dlclose(mLibHandle)) { - DALI_LOG_ERROR( "Error closing vector animation renderer plugin library: %s\n", dlerror() ); + DALI_LOG_ERROR("Error closing vector animation renderer plugin library: %s\n", dlerror()); } } } void VectorAnimationRendererPluginProxy::Initialize() { - mLibHandle = dlopen( mSharedObjectName.c_str(), RTLD_LAZY ); + mLibHandle = dlopen(mSharedObjectName.c_str(), RTLD_LAZY); char* error = dlerror(); - if( mLibHandle == NULL || error != NULL ) + if(mLibHandle == NULL || error != NULL) { - DALI_LOG_ERROR( "VectorAnimationRendererPluginProxy::Initialize: dlopen error [%s]\n", error ); + DALI_LOG_ERROR("VectorAnimationRendererPluginProxy::Initialize: dlopen error [%s]\n", error); return; } // load plugin - mCreateVectorAnimationRendererPtr = reinterpret_cast< CreateVectorAnimationRendererFunction >( dlsym( mLibHandle, "CreateVectorAnimationRendererPlugin" ) ); + mCreateVectorAnimationRendererPtr = reinterpret_cast(dlsym(mLibHandle, "CreateVectorAnimationRendererPlugin")); error = dlerror(); - if( mCreateVectorAnimationRendererPtr == NULL || error != NULL ) + if(mCreateVectorAnimationRendererPtr == NULL || error != NULL) { - DALI_LOG_ERROR( "VectorAnimationRendererPluginProxy::Initialize: Cannot load symbol: %s\n", error ); + DALI_LOG_ERROR("VectorAnimationRendererPluginProxy::Initialize: Cannot load symbol: %s\n", error); return; } mPlugin = mCreateVectorAnimationRendererPtr(); - if( !mPlugin ) + if(!mPlugin) { DALI_LOG_ERROR("VectorAnimationRendererPluginProxy::Initialize: Plugin creation failed\n"); return; } } -bool VectorAnimationRendererPluginProxy::Initialize( const std::string& url ) +bool VectorAnimationRendererPluginProxy::Initialize(const std::string& url) { - if( mPlugin ) + if(mPlugin) { - return mPlugin->Initialize( url ); + return mPlugin->Initialize(url); } return false; } void VectorAnimationRendererPluginProxy::Finalize() { - if( mPlugin ) + if(mPlugin) { mPlugin->Finalize(); } } -void VectorAnimationRendererPluginProxy::SetRenderer( Dali::Renderer renderer ) +void VectorAnimationRendererPluginProxy::SetRenderer(Dali::Renderer renderer) { - if( mPlugin ) + if(mPlugin) { - mPlugin->SetRenderer( renderer ); + mPlugin->SetRenderer(renderer); } } -void VectorAnimationRendererPluginProxy::SetSize( uint32_t width, uint32_t height ) +void VectorAnimationRendererPluginProxy::SetSize(uint32_t width, uint32_t height) { - if( mPlugin ) + if(mPlugin) { - mPlugin->SetSize( width, height ); + mPlugin->SetSize(width, height); } } -bool VectorAnimationRendererPluginProxy::Render( uint32_t frameNumber ) +bool VectorAnimationRendererPluginProxy::Render(uint32_t frameNumber) { - if( mPlugin ) + if(mPlugin) { - return mPlugin->Render( frameNumber ); + return mPlugin->Render(frameNumber); } return false; } uint32_t VectorAnimationRendererPluginProxy::GetTotalFrameNumber() const { - if( mPlugin ) + if(mPlugin) { return mPlugin->GetTotalFrameNumber(); } @@ -154,41 +150,41 @@ uint32_t VectorAnimationRendererPluginProxy::GetTotalFrameNumber() const float VectorAnimationRendererPluginProxy::GetFrameRate() const { - if( mPlugin ) + if(mPlugin) { return mPlugin->GetFrameRate(); } return 0.0f; } -void VectorAnimationRendererPluginProxy::GetDefaultSize( uint32_t& width, uint32_t& height ) const +void VectorAnimationRendererPluginProxy::GetDefaultSize(uint32_t& width, uint32_t& height) const { - if( mPlugin ) + if(mPlugin) { - mPlugin->GetDefaultSize( width, height ); + mPlugin->GetDefaultSize(width, height); } } -void VectorAnimationRendererPluginProxy::GetLayerInfo( Property::Map& map ) const +void VectorAnimationRendererPluginProxy::GetLayerInfo(Property::Map& map) const { - if( mPlugin ) + if(mPlugin) { - mPlugin->GetLayerInfo( map ); + mPlugin->GetLayerInfo(map); } } -bool VectorAnimationRendererPluginProxy::GetMarkerInfo( const std::string& marker, uint32_t& startFrame, uint32_t& endFrame ) const +bool VectorAnimationRendererPluginProxy::GetMarkerInfo(const std::string& marker, uint32_t& startFrame, uint32_t& endFrame) const { - if( mPlugin ) + if(mPlugin) { - return mPlugin->GetMarkerInfo( marker, startFrame, endFrame ); + return mPlugin->GetMarkerInfo(marker, startFrame, endFrame); } return false; } void VectorAnimationRendererPluginProxy::IgnoreRenderedFrame() { - if( mPlugin ) + if(mPlugin) { mPlugin->IgnoreRenderedFrame(); } @@ -196,7 +192,7 @@ void VectorAnimationRendererPluginProxy::IgnoreRenderedFrame() VectorAnimationRendererPlugin::UploadCompletedSignalType& VectorAnimationRendererPluginProxy::UploadCompletedSignal() { - if( mPlugin ) + if(mPlugin) { return mPlugin->UploadCompletedSignal(); } diff --git a/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.h b/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.h index d63faa3..e07c40b 100644 --- a/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.h +++ b/dali/internal/vector-animation/common/vector-animation-renderer-plugin-proxy.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_VECTOR_ANIMATION_RENDERER_PLUGIN_PROXY_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,24 +23,20 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Proxy class to dynamically load, use and unload vector animation renderer plugin. */ class VectorAnimationRendererPluginProxy { public: - /** * @brief Constructor */ - VectorAnimationRendererPluginProxy( const std::string& sharedObjectName ); + VectorAnimationRendererPluginProxy(const std::string& sharedObjectName); /** * @brief Destructor @@ -50,7 +46,7 @@ public: /** * @copydoc Dali::VectorAnimationRendererPlugin::Initialize() */ - bool Initialize( const std::string& url ); + bool Initialize(const std::string& url); /** * @copydoc Dali::VectorAnimationRendererPlugin::Finalize() @@ -60,17 +56,17 @@ public: /** * @copydoc Dali::VectorAnimationRendererPlugin::SetRenderer() */ - void SetRenderer( Dali::Renderer renderer ); + void SetRenderer(Dali::Renderer renderer); /** * @copydoc Dali::VectorAnimationRendererPlugin::SetSize() */ - void SetSize( uint32_t width, uint32_t height ); + void SetSize(uint32_t width, uint32_t height); /** * @copydoc Dali::VectorAnimationRendererPlugin::Render() */ - bool Render( uint32_t frameNumber ); + bool Render(uint32_t frameNumber); /** * @copydoc Dali::VectorAnimationRendererPlugin::GetTotalFrameNumber() @@ -85,17 +81,17 @@ public: /** * @copydoc Dali::VectorAnimationRendererPlugin::GetDefaultSize() */ - void GetDefaultSize( uint32_t& width, uint32_t& height ) const; + void GetDefaultSize(uint32_t& width, uint32_t& height) const; /** * @copydoc Dali::VectorAnimationRendererPlugin::GetLayerInfo() */ - void GetLayerInfo( Property::Map& map ) const; + void GetLayerInfo(Property::Map& map) const; /** * @copydoc Dali::VectorAnimationRendererPlugin::GetMarkerInfo() */ - bool GetMarkerInfo( const std::string& marker, uint32_t& startFrame, uint32_t& endFrame ) const; + bool GetMarkerInfo(const std::string& marker, uint32_t& startFrame, uint32_t& endFrame) const; /** * @copydoc Dali::VectorAnimationRendererPlugin::IgnoreRenderedFrame() @@ -108,29 +104,26 @@ public: VectorAnimationRendererPlugin::UploadCompletedSignalType& UploadCompletedSignal(); // Not copyable or movable - VectorAnimationRendererPluginProxy( const VectorAnimationRendererPluginProxy& ) = delete; ///< Deleted copy constructor - VectorAnimationRendererPluginProxy( VectorAnimationRendererPluginProxy&& ) = delete; ///< Deleted move constructor - VectorAnimationRendererPluginProxy& operator=( const VectorAnimationRendererPluginProxy& ) = delete; ///< Deleted copy assignment operator - VectorAnimationRendererPluginProxy& operator=( VectorAnimationRendererPluginProxy&& ) = delete; ///< Deleted move assignment operator + VectorAnimationRendererPluginProxy(const VectorAnimationRendererPluginProxy&) = delete; ///< Deleted copy constructor + VectorAnimationRendererPluginProxy(VectorAnimationRendererPluginProxy&&) = delete; ///< Deleted move constructor + VectorAnimationRendererPluginProxy& operator=(const VectorAnimationRendererPluginProxy&) = delete; ///< Deleted copy assignment operator + VectorAnimationRendererPluginProxy& operator=(VectorAnimationRendererPluginProxy&&) = delete; ///< Deleted move assignment operator private: - /** * Dynamically loads the plugin. */ void Initialize(); private: - using CreateVectorAnimationRendererFunction = Dali::VectorAnimationRendererPlugin* (*)(); - std::string mSharedObjectName; ///< Shared object name - void* mLibHandle; ///< Handle for the loaded library - Dali::VectorAnimationRendererPlugin* mPlugin; ///< Plugin handle + std::string mSharedObjectName; ///< Shared object name + void* mLibHandle; ///< Handle for the loaded library + Dali::VectorAnimationRendererPlugin* mPlugin; ///< Plugin handle - CreateVectorAnimationRendererFunction mCreateVectorAnimationRendererPtr; ///< Function pointer called in adaptor to create a plugin instance + CreateVectorAnimationRendererFunction mCreateVectorAnimationRendererPtr; ///< Function pointer called in adaptor to create a plugin instance VectorAnimationRendererPlugin::UploadCompletedSignalType mDefaultSignal; - }; } // namespace Adaptor diff --git a/dali/internal/vector-image/common/vector-image-renderer-impl.cpp b/dali/internal/vector-image/common/vector-image-renderer-impl.cpp index 9f6daaa..5b1669d 100644 --- a/dali/internal/vector-image/common/vector-image-renderer-impl.cpp +++ b/dali/internal/vector-image/common/vector-image-renderer-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,13 +28,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { const char* const UNITS("px"); @@ -45,7 +42,7 @@ Dali::BaseHandle Create() return Dali::BaseHandle(); } -Dali::TypeRegistration type( typeid( Dali::VectorImageRenderer ), typeid( Dali::BaseHandle ), Create ); +Dali::TypeRegistration type(typeid(Dali::VectorImageRenderer), typeid(Dali::BaseHandle), Create); } // unnamed namespace @@ -123,7 +120,7 @@ bool VectorImageRenderer::Rasterize(Dali::Devel::PixelBuffer& buffer, float scal } } -void VectorImageRenderer::GetDefaultSize( uint32_t& width, uint32_t& height ) const +void VectorImageRenderer::GetDefaultSize(uint32_t& width, uint32_t& height) const { if(mPlugin.IsValid()) { diff --git a/dali/internal/vector-image/common/vector-image-renderer-impl.h b/dali/internal/vector-image/common/vector-image-renderer-impl.h old mode 100755 new mode 100644 index 1d85b69..2bfc1e0 --- a/dali/internal/vector-image/common/vector-image-renderer-impl.h +++ b/dali/internal/vector-image/common/vector-image-renderer-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_VECTOR_IMAGE_RENDERER_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,24 +23,21 @@ #include // INTERNAL INCLUDES +#include #include #include -#include struct NSVGrasterizer; struct NSVGimage; namespace Dali { - namespace Internal { - namespace Adaptor { - class VectorImageRenderer; -using VectorImageRendererPtr = IntrusivePtr< VectorImageRenderer >; +using VectorImageRendererPtr = IntrusivePtr; /** * Dali internal VectorImageRenderer. @@ -48,7 +45,6 @@ using VectorImageRendererPtr = IntrusivePtr< VectorImageRenderer >; class VectorImageRenderer : public BaseObject { public: - /** * @brief Creates a VectorImageRenderer object. * @@ -69,15 +65,14 @@ public: /** * @copydoc Dali::VectorImageRenderer::GetDefaultSize() */ - void GetDefaultSize( uint32_t& width, uint32_t& height ) const; + void GetDefaultSize(uint32_t& width, uint32_t& height) const; - VectorImageRenderer( const VectorImageRenderer& ) = delete; - VectorImageRenderer& operator=( VectorImageRenderer& ) = delete; - VectorImageRenderer( VectorImageRenderer&& ) = delete; - VectorImageRenderer& operator=( VectorImageRenderer&& ) = delete; + VectorImageRenderer(const VectorImageRenderer&) = delete; + VectorImageRenderer& operator=(VectorImageRenderer&) = delete; + VectorImageRenderer(VectorImageRenderer&&) = delete; + VectorImageRenderer& operator=(VectorImageRenderer&&) = delete; private: - /** * @brief Constructor */ @@ -94,7 +89,6 @@ private: void Initialize(); private: - VectorImageRendererPluginProxy mPlugin; NSVGimage* mParsedImage; NSVGrasterizer* mRasterizer; @@ -104,22 +98,22 @@ private: } // namespace Internal -inline static Internal::Adaptor::VectorImageRenderer& GetImplementation( Dali::VectorImageRenderer& renderer ) +inline static Internal::Adaptor::VectorImageRenderer& GetImplementation(Dali::VectorImageRenderer& renderer) { - DALI_ASSERT_ALWAYS( renderer && "VectorImageRenderer handle is empty." ); + DALI_ASSERT_ALWAYS(renderer && "VectorImageRenderer handle is empty."); BaseObject& handle = renderer.GetBaseObject(); - return static_cast< Internal::Adaptor::VectorImageRenderer& >( handle ); + return static_cast(handle); } -inline static const Internal::Adaptor::VectorImageRenderer& GetImplementation( const Dali::VectorImageRenderer& renderer ) +inline static const Internal::Adaptor::VectorImageRenderer& GetImplementation(const Dali::VectorImageRenderer& renderer) { - DALI_ASSERT_ALWAYS( renderer && "VectorImageRenderer handle is empty." ); + DALI_ASSERT_ALWAYS(renderer && "VectorImageRenderer handle is empty."); const BaseObject& handle = renderer.GetBaseObject(); - return static_cast< const Internal::Adaptor::VectorImageRenderer& >( handle ); + return static_cast(handle); } } // namespace Dali diff --git a/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.cpp b/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.cpp index d136f14..324dfb7 100644 --- a/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.cpp +++ b/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,25 +19,21 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - // The default plugin name -const char* DEFAULT_OBJECT_NAME( "libdali2-vector-image-renderer-plugin.so" ); +const char* DEFAULT_OBJECT_NAME("libdali2-vector-image-renderer-plugin.so"); -} +} // namespace VectorImageRendererPluginProxy::VectorImageRendererPluginProxy(std::string sharedObjectName) : mSharedObjectName(std::move(sharedObjectName)), @@ -79,17 +75,17 @@ void VectorImageRendererPluginProxy::InitializePlugin() } // load plugin - mCreateVectorImageRendererPtr = reinterpret_cast< CreateVectorImageRendererFunction >( dlsym( mLibHandle, "CreateVectorImageRendererPlugin" ) ); + mCreateVectorImageRendererPtr = reinterpret_cast(dlsym(mLibHandle, "CreateVectorImageRendererPlugin")); error = dlerror(); - if( mCreateVectorImageRendererPtr == nullptr || error != nullptr ) + if(mCreateVectorImageRendererPtr == nullptr || error != nullptr) { - DALI_LOG_ERROR( "VectorImageRendererPluginProxy::Initialize: Cannot load symbol: %s\n", error ); + DALI_LOG_ERROR("VectorImageRendererPluginProxy::Initialize: Cannot load symbol: %s\n", error); return; } mPlugin = mCreateVectorImageRendererPtr(); - if( !mPlugin ) + if(!mPlugin) { DALI_LOG_ERROR("VectorImageRendererPluginProxy::Initialize: Plugin creation failed\n"); return; @@ -112,18 +108,18 @@ bool VectorImageRendererPluginProxy::Load(const Vector& data) bool VectorImageRendererPluginProxy::Rasterize(Dali::Devel::PixelBuffer& buffer) { - if( mPlugin ) + if(mPlugin) { return mPlugin->Rasterize(buffer); } return false; } -void VectorImageRendererPluginProxy::GetDefaultSize( uint32_t& width, uint32_t& height ) const +void VectorImageRendererPluginProxy::GetDefaultSize(uint32_t& width, uint32_t& height) const { - if( mPlugin ) + if(mPlugin) { - mPlugin->GetDefaultSize( width, height ); + mPlugin->GetDefaultSize(width, height); } } diff --git a/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.h b/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.h index 25d4c42..13527a3 100644 --- a/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.h +++ b/dali/internal/vector-image/common/vector-image-renderer-plugin-proxy.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_VECTOR_IMAGE_RENDERER_PLUGIN_PROXY_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,29 +19,25 @@ */ // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * Proxy class to dynamically load, use and unload vector image renderer plugin. */ class VectorImageRendererPluginProxy { public: - /** * @brief Constructor */ - VectorImageRendererPluginProxy( std::string sharedObjectName ); + VectorImageRendererPluginProxy(std::string sharedObjectName); /** * @brief Destructor @@ -70,28 +66,25 @@ public: void GetDefaultSize(uint32_t& width, uint32_t& height) const; // Not copyable or movable - VectorImageRendererPluginProxy( const VectorImageRendererPluginProxy& ) = delete; ///< Deleted copy constructor - VectorImageRendererPluginProxy( VectorImageRendererPluginProxy&& ) = delete; ///< Deleted move constructor - VectorImageRendererPluginProxy& operator=( const VectorImageRendererPluginProxy& ) = delete; ///< Deleted copy assignment operator - VectorImageRendererPluginProxy& operator=( VectorImageRendererPluginProxy&& ) = delete; ///< Deleted move assignment operator + VectorImageRendererPluginProxy(const VectorImageRendererPluginProxy&) = delete; ///< Deleted copy constructor + VectorImageRendererPluginProxy(VectorImageRendererPluginProxy&&) = delete; ///< Deleted move constructor + VectorImageRendererPluginProxy& operator=(const VectorImageRendererPluginProxy&) = delete; ///< Deleted copy assignment operator + VectorImageRendererPluginProxy& operator=(VectorImageRendererPluginProxy&&) = delete; ///< Deleted move assignment operator private: - /** * Dynamically loads the plugin. */ void InitializePlugin(); private: - using CreateVectorImageRendererFunction = Dali::VectorImageRendererPlugin* (*)(); - std::string mSharedObjectName; ///< Shared object name - void* mLibHandle; ///< Handle for the loaded library - Dali::VectorImageRendererPlugin* mPlugin; ///< Plugin handle - - CreateVectorImageRendererFunction mCreateVectorImageRendererPtr; ///< Function pointer called in adaptor to create a plugin instance + std::string mSharedObjectName; ///< Shared object name + void* mLibHandle; ///< Handle for the loaded library + Dali::VectorImageRendererPlugin* mPlugin; ///< Plugin handle + CreateVectorImageRendererFunction mCreateVectorImageRendererPtr; ///< Function pointer called in adaptor to create a plugin instance }; } // namespace Adaptor diff --git a/dali/internal/video/common/video-player-impl.cpp b/dali/internal/video/common/video-player-impl.cpp old mode 100755 new mode 100644 index 7fd5bd8..ef46f90 --- a/dali/internal/video/common/video-player-impl.cpp +++ b/dali/internal/video/common/video-player-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,34 +19,30 @@ #include // EXTERNAL INCLUDES -#include #include -#include #include +#include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { - -const char* VIDEO_PLUGIN_SO( "libdali2-video-player-plugin.so" ); +const char* VIDEO_PLUGIN_SO("libdali2-video-player-plugin.so"); Dali::BaseHandle Create() { return Dali::VideoPlayer::New(); } -Dali::TypeRegistration type( typeid( Dali::VideoPlayer ), typeid( Dali::BaseHandle ), Create ); +Dali::TypeRegistration type(typeid(Dali::VideoPlayer), typeid(Dali::BaseHandle), Create); } // unnamed namespace @@ -57,77 +53,77 @@ VideoPlayerPtr VideoPlayer::New() } VideoPlayer::VideoPlayer() -: mPlugin( NULL ), - mHandle( NULL ), - mCreateVideoPlayerPtr( NULL ), - mDestroyVideoPlayerPtr( NULL ) +: mPlugin(NULL), + mHandle(NULL), + mCreateVideoPlayerPtr(NULL), + mDestroyVideoPlayerPtr(NULL) { } VideoPlayer::~VideoPlayer() { - if( mHandle != NULL ) + if(mHandle != NULL) { - if( mDestroyVideoPlayerPtr != NULL ) + if(mDestroyVideoPlayerPtr != NULL) { - mDestroyVideoPlayerPtr( mPlugin ); + mDestroyVideoPlayerPtr(mPlugin); } - dlclose( mHandle ); + dlclose(mHandle); } } -void VideoPlayer::Initialize( Dali::Actor actor, VideoSyncMode syncMode ) +void VideoPlayer::Initialize(Dali::Actor actor, VideoSyncMode syncMode) { char* error = NULL; - mHandle = dlopen( VIDEO_PLUGIN_SO, RTLD_LAZY ); + mHandle = dlopen(VIDEO_PLUGIN_SO, RTLD_LAZY); error = dlerror(); - if( mHandle == NULL || error != NULL ) + if(mHandle == NULL || error != NULL) { - DALI_LOG_ERROR( "VideoPlayer::Initialize(), dlopen error: %s\n", error ); + DALI_LOG_ERROR("VideoPlayer::Initialize(), dlopen error: %s\n", error); return; } - mCreateVideoPlayerPtr = reinterpret_cast< CreateVideoPlayerFunction >( dlsym( mHandle, "CreateVideoPlayerPlugin" ) ); + mCreateVideoPlayerPtr = reinterpret_cast(dlsym(mHandle, "CreateVideoPlayerPlugin")); error = dlerror(); - if( mCreateVideoPlayerPtr == NULL || error != NULL ) + if(mCreateVideoPlayerPtr == NULL || error != NULL) { - DALI_LOG_ERROR( "Can't load symbol CreateVideoPlayerPlugin(), error: %s\n", error ); + DALI_LOG_ERROR("Can't load symbol CreateVideoPlayerPlugin(), error: %s\n", error); return; } - mPlugin = mCreateVideoPlayerPtr( actor, syncMode ); + mPlugin = mCreateVideoPlayerPtr(actor, syncMode); - if( mPlugin == NULL ) + if(mPlugin == NULL) { - DALI_LOG_ERROR( "Can't create the VideoPlayerPlugin object\n" ); + DALI_LOG_ERROR("Can't create the VideoPlayerPlugin object\n"); return; } - mDestroyVideoPlayerPtr = reinterpret_cast< DestroyVideoPlayerFunction >( dlsym( mHandle, "DestroyVideoPlayerPlugin" ) ); + mDestroyVideoPlayerPtr = reinterpret_cast(dlsym(mHandle, "DestroyVideoPlayerPlugin")); error = dlerror(); - if( mDestroyVideoPlayerPtr == NULL || error != NULL ) + if(mDestroyVideoPlayerPtr == NULL || error != NULL) { - DALI_LOG_ERROR( "Can't load symbol DestroyVideoPlayerPlugin(), error: %s\n", error ); + DALI_LOG_ERROR("Can't load symbol DestroyVideoPlayerPlugin(), error: %s\n", error); return; } } -void VideoPlayer::SetUrl( const std::string& url ) +void VideoPlayer::SetUrl(const std::string& url) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetUrl( url ); + mPlugin->SetUrl(url); } } std::string VideoPlayer::GetUrl() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->GetUrl(); } @@ -137,15 +133,15 @@ std::string VideoPlayer::GetUrl() void VideoPlayer::SetLooping(bool looping) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetLooping( looping ); + mPlugin->SetLooping(looping); } } bool VideoPlayer::IsLooping() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->IsLooping(); } @@ -155,7 +151,7 @@ bool VideoPlayer::IsLooping() void VideoPlayer::Play() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { mPlugin->Play(); } @@ -163,7 +159,7 @@ void VideoPlayer::Play() void VideoPlayer::Pause() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { mPlugin->Pause(); } @@ -171,23 +167,23 @@ void VideoPlayer::Pause() void VideoPlayer::Stop() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { mPlugin->Stop(); } } -void VideoPlayer::SetMute( bool mute ) +void VideoPlayer::SetMute(bool mute) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetMute( mute ); + mPlugin->SetMute(mute); } } bool VideoPlayer::IsMuted() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->IsMuted(); } @@ -195,66 +191,66 @@ bool VideoPlayer::IsMuted() return false; } -void VideoPlayer::SetVolume( float left, float right ) +void VideoPlayer::SetVolume(float left, float right) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetVolume( left, right ); + mPlugin->SetVolume(left, right); } } -void VideoPlayer::GetVolume( float& left, float& right ) +void VideoPlayer::GetVolume(float& left, float& right) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->GetVolume( left, right ); + mPlugin->GetVolume(left, right); } } -void VideoPlayer::SetRenderingTarget( Dali::Any target ) +void VideoPlayer::SetRenderingTarget(Dali::Any target) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetRenderingTarget( target ); + mPlugin->SetRenderingTarget(target); } } -void VideoPlayer::SetPlayPosition( int millisecond ) +void VideoPlayer::SetPlayPosition(int millisecond) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetPlayPosition( millisecond ); + mPlugin->SetPlayPosition(millisecond); } } int VideoPlayer::GetPlayPosition() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->GetPlayPosition(); } return 0; } -void VideoPlayer::SetDisplayArea( DisplayArea area ) +void VideoPlayer::SetDisplayArea(DisplayArea area) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetDisplayArea( area ); + mPlugin->SetDisplayArea(area); } } -void VideoPlayer::SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation ) +void VideoPlayer::SetDisplayRotation(Dali::VideoPlayerPlugin::DisplayRotation rotation) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetDisplayRotation( rotation ); + mPlugin->SetDisplayRotation(rotation); } } Dali::VideoPlayerPlugin::DisplayRotation VideoPlayer::GetDisplayRotation() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->GetDisplayRotation(); } @@ -264,7 +260,7 @@ Dali::VideoPlayerPlugin::DisplayRotation VideoPlayer::GetDisplayRotation() Dali::VideoPlayerPlugin::VideoPlayerSignalType& VideoPlayer::FinishedSignal() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->FinishedSignal(); } @@ -272,25 +268,25 @@ Dali::VideoPlayerPlugin::VideoPlayerSignalType& VideoPlayer::FinishedSignal() return mFinishedSignal; } -void VideoPlayer::Forward( int millisecond ) +void VideoPlayer::Forward(int millisecond) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->Forward( millisecond ); + mPlugin->Forward(millisecond); } } -void VideoPlayer::Backward( int millisecond ) +void VideoPlayer::Backward(int millisecond) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->Backward( millisecond ); + mPlugin->Backward(millisecond); } } bool VideoPlayer::IsVideoTextureSupported() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->IsVideoTextureSupported(); } @@ -298,17 +294,17 @@ bool VideoPlayer::IsVideoTextureSupported() return false; } -void VideoPlayer::SetCodecType( Dali::VideoPlayerPlugin::CodecType type ) +void VideoPlayer::SetCodecType(Dali::VideoPlayerPlugin::CodecType type) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetCodecType( type ); + mPlugin->SetCodecType(type); } } Dali::VideoPlayerPlugin::CodecType VideoPlayer::GetCodecType() const { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->GetCodecType(); } @@ -316,17 +312,17 @@ Dali::VideoPlayerPlugin::CodecType VideoPlayer::GetCodecType() const return Dali::VideoPlayerPlugin::CodecType::DEFAULT; } -void VideoPlayer::SetDisplayMode( Dali::VideoPlayerPlugin::DisplayMode::Type mode ) +void VideoPlayer::SetDisplayMode(Dali::VideoPlayerPlugin::DisplayMode::Type mode) { - if( mPlugin != NULL ) + if(mPlugin != NULL) { - mPlugin->SetDisplayMode( mode ); + mPlugin->SetDisplayMode(mode); } } Dali::VideoPlayerPlugin::DisplayMode::Type VideoPlayer::GetDisplayMode() const { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->GetDisplayMode(); } @@ -336,7 +332,7 @@ Dali::VideoPlayerPlugin::DisplayMode::Type VideoPlayer::GetDisplayMode() const Any VideoPlayer::GetMediaPlayer() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { return mPlugin->GetMediaPlayer(); } @@ -345,7 +341,7 @@ Any VideoPlayer::GetMediaPlayer() void VideoPlayer::StartSynchronization() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { mPlugin->StartSynchronization(); } @@ -353,13 +349,12 @@ void VideoPlayer::StartSynchronization() void VideoPlayer::FinishSynchronization() { - if( mPlugin != NULL ) + if(mPlugin != NULL) { mPlugin->FinishSynchronization(); } } -} // namespace Adaptor; -} // namespace Internal; -} // namespace Dali; - +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/video/common/video-player-impl.h b/dali/internal/video/common/video-player-impl.h old mode 100755 new mode 100644 index cac7744..21f9c0e --- a/dali/internal/video/common/video-player-impl.h +++ b/dali/internal/video/common/video-player-impl.h @@ -2,7 +2,7 @@ #define DALI_VIDEO_PLAYER_IMPL_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -32,22 +32,19 @@ class Any; namespace Internal { - namespace Adaptor { - class VideoPlayer; -typedef IntrusivePtr< VideoPlayer > VideoPlayerPtr; +typedef IntrusivePtr VideoPlayerPtr; /** * @brief VideoPlayer class is used for video playback. * @SINCE_1_1.24 */ -class VideoPlayer: public Dali::BaseObject +class VideoPlayer : public Dali::BaseObject { public: - /** * @brief Creates a new VideoPlayer handle * @SINCE_1_1.24 @@ -58,7 +55,7 @@ public: /** * @copydoc Dali::VideoPlayer::SetUrl() */ - void SetUrl( const std::string& url ); + void SetUrl(const std::string& url); /** * @copydoc Dali::VideoPlayer::GetUrl() @@ -93,7 +90,7 @@ public: /** * @copydoc Dali::VideoPlayer::SetMute() */ - void SetMute( bool mute ); + void SetMute(bool mute); /** * @copydoc Dali::VideoPlayer::IsMuted() @@ -103,22 +100,22 @@ public: /** * @copydoc Dali::VideoPlayer::SetVolume() */ - void SetVolume( float left, float right ); + void SetVolume(float left, float right); /** * @copydoc Dali::VideoPlayer::GetVolume() */ - void GetVolume( float& left, float& right ); + void GetVolume(float& left, float& right); /** * @copydoc Dali::VideoPlayer::SetRenderingTarget() */ - void SetRenderingTarget( Dali::Any target ); + void SetRenderingTarget(Dali::Any target); /** * @copydoc Dali::VideoPlayer::SetPlayPosition() */ - void SetPlayPosition( int millisecond ); + void SetPlayPosition(int millisecond); /** * @copydoc Dali::VideoPlayer::GetPlayPosition() @@ -128,12 +125,12 @@ public: /** * @copydoc Dali::VideoPlayer::SetDisplayArea() */ - void SetDisplayArea( DisplayArea area ); + void SetDisplayArea(DisplayArea area); /** * @copydoc Dali::VideoPlayer::SetSetDisplayRotation() */ - void SetDisplayRotation( Dali::VideoPlayerPlugin::DisplayRotation rotation ); + void SetDisplayRotation(Dali::VideoPlayerPlugin::DisplayRotation rotation); /** * @copydoc Dali::VideoPlayer::GetDisplayRotation() @@ -148,17 +145,17 @@ public: /** * @brief Initializes member data. */ - void Initialize( Dali::Actor actor, VideoSyncMode syncMode ); + void Initialize(Dali::Actor actor, VideoSyncMode syncMode); /** * @brief Dali::VideoPlayer::Forward() */ - void Forward( int millisecond ); + void Forward(int millisecond); /** * @brief Dali::VideoPlayer::Backward() */ - void Backward( int millisecond ); + void Backward(int millisecond); /** * @brief Dali::VideoPlayer::IsVideoTextureSupported() @@ -168,7 +165,7 @@ public: /** * @brief Dali::VideoPlayer::SetCodecType() */ - void SetCodecType( Dali::VideoPlayerPlugin::CodecType type ); + void SetCodecType(Dali::VideoPlayerPlugin::CodecType type); /** * @brief Dali::VideoPlayer::GetCodecType() @@ -178,7 +175,7 @@ public: /** * @copydoc Dali::VideoPlayer::SetDisplayMode() */ - void SetDisplayMode( Dali::VideoPlayerPlugin::DisplayMode::Type mode ); + void SetDisplayMode(Dali::VideoPlayerPlugin::DisplayMode::Type mode); /** * @brief Dali::VideoPlayer::GetDisplayMode() @@ -201,7 +198,6 @@ public: void FinishSynchronization(); private: - /** * @brief Constructor. * @SINCE_1_1.24 @@ -215,20 +211,19 @@ private: virtual ~VideoPlayer(); // Undefined copy constructor - VideoPlayer( const VideoPlayer& player ); + VideoPlayer(const VideoPlayer& player); // Undefined assignment operator - VideoPlayer& operator=( const VideoPlayer& player ); + VideoPlayer& operator=(const VideoPlayer& player); private: - Dali::VideoPlayerPlugin* mPlugin; ///< Videoplayer plugin handle - void* mHandle; ///< Handle for the loaded library + void* mHandle; ///< Handle for the loaded library - typedef Dali::VideoPlayerPlugin* (*CreateVideoPlayerFunction)( Dali::Actor actor, Dali::VideoSyncMode syncMode ); - typedef void (*DestroyVideoPlayerFunction)( Dali::VideoPlayerPlugin* plugin ); + typedef Dali::VideoPlayerPlugin* (*CreateVideoPlayerFunction)(Dali::Actor actor, Dali::VideoSyncMode syncMode); + typedef void (*DestroyVideoPlayerFunction)(Dali::VideoPlayerPlugin* plugin); - CreateVideoPlayerFunction mCreateVideoPlayerPtr; + CreateVideoPlayerFunction mCreateVideoPlayerPtr; DestroyVideoPlayerFunction mDestroyVideoPlayerPtr; Dali::VideoPlayerPlugin::VideoPlayerSignalType mFinishedSignal; @@ -237,25 +232,24 @@ private: } // namespace Adaptor } // namespace Internal -inline static Internal::Adaptor::VideoPlayer& GetImplementation( Dali::VideoPlayer& player ) +inline static Internal::Adaptor::VideoPlayer& GetImplementation(Dali::VideoPlayer& player) { - DALI_ASSERT_ALWAYS( player && "VideoPlayer handle is empty." ); + DALI_ASSERT_ALWAYS(player && "VideoPlayer handle is empty."); BaseObject& handle = player.GetBaseObject(); - return static_cast< Internal::Adaptor::VideoPlayer& >( handle ); + return static_cast(handle); } -inline static const Internal::Adaptor::VideoPlayer& GetImplementation( const Dali::VideoPlayer& player ) +inline static const Internal::Adaptor::VideoPlayer& GetImplementation(const Dali::VideoPlayer& player) { - DALI_ASSERT_ALWAYS( player && "VideoPlayer handle is empty." ); + DALI_ASSERT_ALWAYS(player && "VideoPlayer handle is empty."); const BaseObject& handle = player.GetBaseObject(); - return static_cast< const Internal::Adaptor::VideoPlayer& >( handle ); + return static_cast(handle); } -} // namespace Dali; +} // namespace Dali #endif // DALI_VIDEO_PLAYER_IMPL_H - diff --git a/dali/internal/web-engine/common/web-engine-impl.cpp b/dali/internal/web-engine/common/web-engine-impl.cpp old mode 100755 new mode 100644 index 0a6ecf0..1bb7af9 --- a/dali/internal/web-engine/common/web-engine-impl.cpp +++ b/dali/internal/web-engine/common/web-engine-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include #include // INTERNAL INCLUDES @@ -36,29 +36,25 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace // unnamed namespace { - -constexpr char const * const kPluginFullNamePrefix = "libdali2-web-engine-"; -constexpr char const * const kPluginFullNamePostfix = "-plugin.so"; -constexpr char const * const kPluginFullNameDefault = "libdali2-web-engine-plugin.so"; +constexpr char const* const kPluginFullNamePrefix = "libdali2-web-engine-"; +constexpr char const* const kPluginFullNamePostfix = "-plugin.so"; +constexpr char const* const kPluginFullNameDefault = "libdali2-web-engine-plugin.so"; // Note: Dali WebView policy does not allow to use multiple web engines in an application. // So once pluginName is set to non-empty string, it will not change. std::string pluginName; -std::string MakePluginName( const char* environmentName ) +std::string MakePluginName(const char* environmentName) { std::stringstream fullName; fullName << kPluginFullNamePrefix << environmentName << kPluginFullNamePostfix; - return std::move( fullName.str() ); + return std::move(fullName.str()); } Dali::BaseHandle Create() @@ -66,7 +62,7 @@ Dali::BaseHandle Create() return Dali::WebEngine::New(); } -Dali::TypeRegistration type( typeid( Dali::WebEngine ), typeid( Dali::BaseHandle ), Create ); +Dali::TypeRegistration type(typeid(Dali::WebEngine), typeid(Dali::BaseHandle), Create); } // unnamed namespace @@ -74,7 +70,7 @@ WebEnginePtr WebEngine::New() { WebEngine* instance = new WebEngine(); - if( !instance->Initialize() ) + if(!instance->Initialize()) { delete instance; return nullptr; @@ -84,49 +80,49 @@ WebEnginePtr WebEngine::New() } WebEngine::WebEngine() -: mPlugin( NULL ), - mHandle( NULL ), - mCreateWebEnginePtr( NULL ), - mDestroyWebEnginePtr( NULL ) +: mPlugin(NULL), + mHandle(NULL), + mCreateWebEnginePtr(NULL), + mDestroyWebEnginePtr(NULL) { } WebEngine::~WebEngine() { - if( mHandle != NULL ) + if(mHandle != NULL) { - if( mDestroyWebEnginePtr != NULL ) + if(mDestroyWebEnginePtr != NULL) { mPlugin->Destroy(); - mDestroyWebEnginePtr( mPlugin ); + mDestroyWebEnginePtr(mPlugin); } - dlclose( mHandle ); + dlclose(mHandle); } } bool WebEngine::InitializePluginHandle() { - if( pluginName.length() == 0 ) + if(pluginName.length() == 0) { // pluginName is not initialized yet. - const char* name = EnvironmentVariable::GetEnvironmentVariable( DALI_ENV_WEB_ENGINE_NAME ); - if( name ) + const char* name = EnvironmentVariable::GetEnvironmentVariable(DALI_ENV_WEB_ENGINE_NAME); + if(name) { - pluginName = MakePluginName( name ); - mHandle = dlopen( pluginName.c_str(), RTLD_LAZY ); - if( mHandle ) + pluginName = MakePluginName(name); + mHandle = dlopen(pluginName.c_str(), RTLD_LAZY); + if(mHandle) { return true; } } - pluginName = std::string( kPluginFullNameDefault ); + pluginName = std::string(kPluginFullNameDefault); } - mHandle = dlopen( pluginName.c_str(), RTLD_LAZY ); - if( !mHandle ) + mHandle = dlopen(pluginName.c_str(), RTLD_LAZY); + if(!mHandle) { - DALI_LOG_ERROR( "Can't load %s : %s\n", pluginName.c_str(), dlerror() ); + DALI_LOG_ERROR("Can't load %s : %s\n", pluginName.c_str(), dlerror()); return false; } @@ -137,45 +133,45 @@ bool WebEngine::Initialize() { char* error = NULL; - if( !InitializePluginHandle() ) + if(!InitializePluginHandle()) { return false; } - mCreateWebEnginePtr = reinterpret_cast< CreateWebEngineFunction >( dlsym( mHandle, "CreateWebEnginePlugin" ) ); - if( mCreateWebEnginePtr == NULL ) + mCreateWebEnginePtr = reinterpret_cast(dlsym(mHandle, "CreateWebEnginePlugin")); + if(mCreateWebEnginePtr == NULL) { - DALI_LOG_ERROR( "Can't load symbol CreateWebEnginePlugin(), error: %s\n", error ); + DALI_LOG_ERROR("Can't load symbol CreateWebEnginePlugin(), error: %s\n", error); return false; } - mDestroyWebEnginePtr = reinterpret_cast< DestroyWebEngineFunction >( dlsym( mHandle, "DestroyWebEnginePlugin" ) ); + mDestroyWebEnginePtr = reinterpret_cast(dlsym(mHandle, "DestroyWebEnginePlugin")); - if( mDestroyWebEnginePtr == NULL ) + if(mDestroyWebEnginePtr == NULL) { - DALI_LOG_ERROR( "Can't load symbol DestroyWebEnginePlugin(), error: %s\n", error ); + DALI_LOG_ERROR("Can't load symbol DestroyWebEnginePlugin(), error: %s\n", error); return false; } mPlugin = mCreateWebEnginePtr(); - if( mPlugin == NULL ) + if(mPlugin == NULL) { - DALI_LOG_ERROR( "Can't create the WebEnginePlugin object\n" ); + DALI_LOG_ERROR("Can't create the WebEnginePlugin object\n"); return false; } return true; } -void WebEngine::Create( int width, int height, const std::string& locale, const std::string& timezoneId ) +void WebEngine::Create(int width, int height, const std::string& locale, const std::string& timezoneId) { - mPlugin->Create( width, height, locale, timezoneId ); + mPlugin->Create(width, height, locale, timezoneId); } -void WebEngine::Create( int width, int height, int argc, char** argv ) +void WebEngine::Create(int width, int height, int argc, char** argv) { - mPlugin->Create( width, height, argc, argv ); + mPlugin->Create(width, height, argc, argv); } void WebEngine::Destroy() @@ -208,9 +204,9 @@ Dali::WebEngineBackForwardList& WebEngine::GetBackForwardList() const return mPlugin->GetBackForwardList(); } -void WebEngine::LoadUrl( const std::string& url ) +void WebEngine::LoadUrl(const std::string& url) { - mPlugin->LoadUrl( url ); + mPlugin->LoadUrl(url); } std::string WebEngine::GetTitle() const @@ -233,14 +229,14 @@ const std::string& WebEngine::GetUserAgent() const return mPlugin->GetUserAgent(); } -void WebEngine::SetUserAgent( const std::string& userAgent ) +void WebEngine::SetUserAgent(const std::string& userAgent) { - mPlugin->SetUserAgent( userAgent ); + mPlugin->SetUserAgent(userAgent); } -void WebEngine::LoadHtmlString( const std::string& htmlString ) +void WebEngine::LoadHtmlString(const std::string& htmlString) { - mPlugin->LoadHtmlString( htmlString ); + mPlugin->LoadHtmlString(htmlString); } void WebEngine::Reload() @@ -263,14 +259,14 @@ void WebEngine::Resume() mPlugin->Resume(); } -void WebEngine::ScrollBy( int deltaX, int deltaY ) +void WebEngine::ScrollBy(int deltaX, int deltaY) { - mPlugin->ScrollBy( deltaX, deltaY ); + mPlugin->ScrollBy(deltaX, deltaY); } -void WebEngine::SetScrollPosition( int x, int y ) +void WebEngine::SetScrollPosition(int x, int y) { - mPlugin->SetScrollPosition( x, y ); + mPlugin->SetScrollPosition(x, y); } Dali::Vector2 WebEngine::GetScrollPosition() const @@ -308,14 +304,14 @@ void WebEngine::GoBack() mPlugin->GoBack(); } -void WebEngine::EvaluateJavaScript( const std::string& script, std::function< void( const std::string& ) > resultHandler ) +void WebEngine::EvaluateJavaScript(const std::string& script, std::function resultHandler) { - mPlugin->EvaluateJavaScript( script, resultHandler ); + mPlugin->EvaluateJavaScript(script, resultHandler); } -void WebEngine::AddJavaScriptMessageHandler( const std::string& exposedObjectName, std::function< void(const std::string&) > handler ) +void WebEngine::AddJavaScriptMessageHandler(const std::string& exposedObjectName, std::function handler) { - mPlugin->AddJavaScriptMessageHandler( exposedObjectName, handler ); + mPlugin->AddJavaScriptMessageHandler(exposedObjectName, handler); } void WebEngine::ClearAllTilesResources() @@ -328,24 +324,34 @@ void WebEngine::ClearHistory() mPlugin->ClearHistory(); } -void WebEngine::SetSize( int width, int height ) +void WebEngine::SetSize(int width, int height) +{ + mPlugin->SetSize(width, height); +} + +bool WebEngine::SendTouchEvent(const Dali::TouchEvent& touch) { - mPlugin->SetSize( width, height ); + return mPlugin->SendTouchEvent(touch); } -bool WebEngine::SendTouchEvent( const Dali::TouchEvent& touch ) +bool WebEngine::SendKeyEvent(const Dali::KeyEvent& event) { - return mPlugin->SendTouchEvent( touch ); + return mPlugin->SendKeyEvent(event); } -bool WebEngine::SendKeyEvent( const Dali::KeyEvent& event ) +void WebEngine::SetFocus(bool focused) { - return mPlugin->SendKeyEvent( event ); + mPlugin->SetFocus(focused); } -void WebEngine::SetFocus( bool focused ) +void WebEngine::UpdateDisplayArea(Dali::Rect displayArea) { - mPlugin->SetFocus( focused ); + mPlugin->UpdateDisplayArea(displayArea); +} + +void WebEngine::EnableVideoHole(bool enabled) +{ + mPlugin->EnableVideoHole(enabled); } Dali::WebEnginePlugin::WebEnginePageLoadSignalType& WebEngine::PageLoadStartedSignal() @@ -368,8 +374,6 @@ Dali::WebEnginePlugin::WebEngineScrollEdgeReachedSignalType& WebEngine::ScrollEd return mPlugin->ScrollEdgeReachedSignal(); } -} // namespace Adaptor; -} // namespace Internal; -} // namespace Dali; - - +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/web-engine/common/web-engine-impl.h b/dali/internal/web-engine/common/web-engine-impl.h old mode 100755 new mode 100644 index dea65ba..069339f --- a/dali/internal/web-engine/common/web-engine-impl.h +++ b/dali/internal/web-engine/common/web-engine-impl.h @@ -2,7 +2,7 @@ #define DALI_WEB_ENGINE_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,12 +22,11 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - // forward declaration class WebEngineBackForwardList; class WebEngineContext; @@ -36,13 +35,11 @@ class WebEngineSettings; namespace Internal { - namespace Adaptor { - class WebEngine; -typedef IntrusivePtr< WebEngine > WebEnginePtr; +typedef IntrusivePtr WebEnginePtr; /** * @brief WebEngine class is used for Web. @@ -50,7 +47,6 @@ typedef IntrusivePtr< WebEngine > WebEnginePtr; class WebEngine : public Dali::BaseObject { public: - /** * @brief Creates a new WebEngine handle * @@ -61,12 +57,12 @@ public: /** * @copydoc Dali::WebEngine::Create() */ - void Create( int width, int height, const std::string& locale, const std::string& timezoneId ); + void Create(int width, int height, const std::string& locale, const std::string& timezoneId); /** * @copydoc Dali::WebEngine::Create() */ - void Create( int width, int height, int argc, char** argv ); + void Create(int width, int height, int argc, char** argv); /** * @copydoc Dali::WebEngine::Destroy() @@ -101,7 +97,7 @@ public: /** * @copydoc Dali::WebEngine::LoadUrl() */ - void LoadUrl( const std::string& url ); + void LoadUrl(const std::string& url); /** * @copydoc Dali::WebEngine::GetTitle() @@ -126,12 +122,12 @@ public: /** * @copydoc Dali::WebEngine::SetUserAgent() */ - void SetUserAgent( const std::string& userAgent ); + void SetUserAgent(const std::string& userAgent); /** * @copydoc Dali::WebEngine::LoadHtmlString() */ - void LoadHtmlString( const std::string& htmlString ); + void LoadHtmlString(const std::string& htmlString); /** * @copydoc Dali::WebEngine::Reload() @@ -156,12 +152,12 @@ public: /** * @copydoc Dali::WebEngine::ScrollBy() */ - void ScrollBy( int deltaX, int deltaY ); + void ScrollBy(int deltaX, int deltaY); /** * @copydoc Dali::WebEngine::SetScrollPosition() */ - void SetScrollPosition( int x, int y ); + void SetScrollPosition(int x, int y); /** * @copydoc Dali::WebEngine::GetScrollPosition() @@ -201,12 +197,12 @@ public: /** * @copydoc Dali::WebEngine::EvaluateJavaScript() */ - void EvaluateJavaScript( const std::string& script, std::function< void(const std::string&) > resultHandler ); + void EvaluateJavaScript(const std::string& script, std::function resultHandler); /** * @copydoc Dali::WebEngine::AddJavaScriptMessageHandler() */ - void AddJavaScriptMessageHandler( const std::string& exposedObjectName, std::function< void(const std::string&) > handler ); + void AddJavaScriptMessageHandler(const std::string& exposedObjectName, std::function handler); /** * @copydoc Dali::WebEngine::ClearAllTilesResources() @@ -221,22 +217,32 @@ public: /** * @copydoc Dali::WebEngine::SetSize() */ - void SetSize( int width, int height ); + void SetSize(int width, int height); /** * @copydoc Dali::WebEngine::SendTouchEvent() */ - bool SendTouchEvent( const Dali::TouchEvent& touch ); + bool SendTouchEvent(const Dali::TouchEvent& touch); /** * @copydoc Dali::WebEngine::SendKeyEvent() */ - bool SendKeyEvent( const Dali::KeyEvent& event ); + bool SendKeyEvent(const Dali::KeyEvent& event); /** * @copydoc Dali::WebEngine::SetFocus() */ - void SetFocus( bool focused ); + void SetFocus(bool focused); + + /** + * @copydoc Dali::WebEngine::UpdateDisplayArea() + */ + void UpdateDisplayArea(Dali::Rect displayArea); + + /** + * @copydoc Dali::WebEngine::EnableVideoHole() + */ + void EnableVideoHole(bool enabled); /** * @copydoc Dali::WebEngine::PageLoadStartedSignal() @@ -259,7 +265,6 @@ public: Dali::WebEnginePlugin::WebEngineScrollEdgeReachedSignalType& ScrollEdgeReachedSignal(); private: - /** * @brief Constructor. */ @@ -271,10 +276,10 @@ private: virtual ~WebEngine(); // Undefined copy constructor - WebEngine( const WebEngine& WebEngine ); + WebEngine(const WebEngine& WebEngine); // Undefined assignment operator - WebEngine& operator=( const WebEngine& WebEngine ); + WebEngine& operator=(const WebEngine& WebEngine); /** * @brief Initializes member data. @@ -291,38 +296,36 @@ private: bool InitializePluginHandle(); private: - typedef Dali::WebEnginePlugin* (*CreateWebEngineFunction)(); - typedef void (*DestroyWebEngineFunction)( Dali::WebEnginePlugin* plugin ); + typedef void (*DestroyWebEngineFunction)(Dali::WebEnginePlugin* plugin); - Dali::WebEnginePlugin* mPlugin; ///< WebEnginePlugin instance - void* mHandle; ///< Handle for the loaded library - CreateWebEngineFunction mCreateWebEnginePtr; ///< Function to create plugin instance - DestroyWebEngineFunction mDestroyWebEnginePtr; ///< Function to destroy plugin instance + Dali::WebEnginePlugin* mPlugin; ///< WebEnginePlugin instance + void* mHandle; ///< Handle for the loaded library + CreateWebEngineFunction mCreateWebEnginePtr; ///< Function to create plugin instance + DestroyWebEngineFunction mDestroyWebEnginePtr; ///< Function to destroy plugin instance }; } // namespace Adaptor } // namespace Internal -inline static Internal::Adaptor::WebEngine& GetImplementation( Dali::WebEngine& webEngine ) +inline static Internal::Adaptor::WebEngine& GetImplementation(Dali::WebEngine& webEngine) { - DALI_ASSERT_ALWAYS( webEngine && "WebEngine handle is empty." ); + DALI_ASSERT_ALWAYS(webEngine && "WebEngine handle is empty."); BaseObject& handle = webEngine.GetBaseObject(); - return static_cast< Internal::Adaptor::WebEngine& >( handle ); + return static_cast(handle); } -inline static const Internal::Adaptor::WebEngine& GetImplementation( const Dali::WebEngine& webEngine ) +inline static const Internal::Adaptor::WebEngine& GetImplementation(const Dali::WebEngine& webEngine) { - DALI_ASSERT_ALWAYS( webEngine && "WebEngine handle is empty." ); + DALI_ASSERT_ALWAYS(webEngine && "WebEngine handle is empty."); const BaseObject& handle = webEngine.GetBaseObject(); - return static_cast< const Internal::Adaptor::WebEngine& >( handle ); + return static_cast(handle); } -} // namespace Dali; +} // namespace Dali #endif - diff --git a/dali/internal/window-system/android/display-connection-factory-android.cpp b/dali/internal/window-system/android/display-connection-factory-android.cpp index 18aa472..ebaffad 100644 --- a/dali/internal/window-system/android/display-connection-factory-android.cpp +++ b/dali/internal/window-system/android/display-connection-factory-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - std::unique_ptr DisplayConnectionFactoryAndroid::CreateDisplayConnection() { return Utils::MakeUnique(); @@ -39,8 +36,8 @@ std::unique_ptr GetDisplayConnectionFactory() return Utils::MakeUnique(); } -} +} // namespace Adaptor -} +} // namespace Internal -} +} // namespace Dali diff --git a/dali/internal/window-system/android/display-connection-factory-android.h b/dali/internal/window-system/android/display-connection-factory-android.h index 50a97af..fbef5c5 100644 --- a/dali/internal/window-system/android/display-connection-factory-android.h +++ b/dali/internal/window-system/android/display-connection-factory-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ANDROID_DISPLAY_CONNECTION_FACTORY_ANDROID_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class DisplayConnectionFactoryAndroid : public DisplayConnectionFactory { public: @@ -42,5 +39,4 @@ public: } // namespace Dali - #endif // DALI_INTERNAL_WINDOWSYSTEM_ANDROID_DISPLAY_CONNECTION_FACTORY_ANDROID_H diff --git a/dali/internal/window-system/android/display-connection-impl-android.cpp b/dali/internal/window-system/android/display-connection-impl-android.cpp index bcf14ff..8b28938 100644 --- a/dali/internal/window-system/android/display-connection-impl-android.cpp +++ b/dali/internal/window-system/android/display-connection-impl-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,18 @@ */ // CLASS HEADER -#include #include +#include // EXTERNAL_HEADERS #include namespace Dali { - namespace Internal { - namespace Adaptor { - DisplayConnection* DisplayConnectionAndroid::New() { DisplayConnection* pDisplayConnection(new DisplayConnectionAndroid()); @@ -39,9 +36,9 @@ DisplayConnection* DisplayConnectionAndroid::New() } DisplayConnectionAndroid::DisplayConnectionAndroid() -: mDisplay( NULL ), - mSurfaceType( RenderSurfaceInterface::WINDOW_RENDER_SURFACE ), - mGraphics( nullptr ) +: mDisplay(NULL), + mSurfaceType(RenderSurfaceInterface::WINDOW_RENDER_SURFACE), + mGraphics(nullptr) { } @@ -49,7 +46,7 @@ DisplayConnectionAndroid::~DisplayConnectionAndroid() = default; Any DisplayConnectionAndroid::GetDisplay() { - return Any( mDisplay ); + return Any(mDisplay); } void DisplayConnectionAndroid::ConsumeEvents() @@ -58,25 +55,25 @@ void DisplayConnectionAndroid::ConsumeEvents() bool DisplayConnectionAndroid::InitializeGraphics() { - auto eglGraphics = static_cast( mGraphics ); - EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - if( !eglImpl.InitializeGles( mDisplay ) ) + if(!eglImpl.InitializeGles(mDisplay)) { - DALI_LOG_ERROR( "Failed to initialize GLES.\n" ); + DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; } return true; } -void DisplayConnectionAndroid::SetSurfaceType( Dali::RenderSurfaceInterface::Type type ) +void DisplayConnectionAndroid::SetSurfaceType(Dali::RenderSurfaceInterface::Type type) { mSurfaceType = type; - mDisplay = EGL_DEFAULT_DISPLAY; + mDisplay = EGL_DEFAULT_DISPLAY; } -void DisplayConnectionAndroid::SetGraphicsInterface( GraphicsInterface& graphics ) +void DisplayConnectionAndroid::SetGraphicsInterface(GraphicsInterface& graphics) { mGraphics = &graphics; } diff --git a/dali/internal/window-system/android/display-connection-impl-android.h b/dali/internal/window-system/android/display-connection-impl-android.h index 0f1691c..ff178a4 100644 --- a/dali/internal/window-system/android/display-connection-impl-android.h +++ b/dali/internal/window-system/android/display-connection-impl-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_DISPLAY_CONNECTION_IMPL_ANDROID_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,22 +23,18 @@ namespace Dali { - class DisplayConnection; namespace Internal { - namespace Adaptor { - /** * DisplayConnection implementation */ class DisplayConnectionAndroid : public Dali::Internal::Adaptor::DisplayConnection { public: - /** * @brief Default constructor */ @@ -52,7 +48,6 @@ public: static DisplayConnection* New(); public: - /** * @copydoc Dali::DisplayConnection::GetDisplay */ @@ -72,23 +67,21 @@ public: * @brief Sets the surface type * @param[in] type The surface type */ - void SetSurfaceType( Dali::RenderSurfaceInterface::Type type ); + void SetSurfaceType(Dali::RenderSurfaceInterface::Type type); /** * @brief Sets the graphics interface * @param[in] graphics The graphics interface */ - void SetGraphicsInterface( GraphicsInterface& graphics ); + void SetGraphicsInterface(GraphicsInterface& graphics); public: - /** * Destructor */ virtual ~DisplayConnectionAndroid(); protected: - // Undefined DisplayConnectionAndroid(const DisplayConnectionAndroid&); @@ -96,14 +89,14 @@ protected: DisplayConnectionAndroid& operator=(const DisplayConnectionAndroid& rhs); private: - EGLNativeDisplayType mDisplay; ///< EGL display for rendering - Dali::RenderSurfaceInterface::Type mSurfaceType; ///< The surface type - GraphicsInterface* mGraphics; ///< The graphics interface + EGLNativeDisplayType mDisplay; ///< EGL display for rendering + Dali::RenderSurfaceInterface::Type mSurfaceType; ///< The surface type + GraphicsInterface* mGraphics; ///< The graphics interface }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/android/render-surface-factory-android.cpp b/dali/internal/window-system/android/render-surface-factory-android.cpp index 6dc3f79..c8084e3 100644 --- a/dali/internal/window-system/android/render-surface-factory-android.cpp +++ b/dali/internal/window-system/android/render-surface-factory-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ #include // INTERNAL HEADERS -#include -#include -#include #include +#include +#include +#include // EXTERNAL INCLUDES #include @@ -33,27 +33,26 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowRenderSurface > RenderSurfaceFactoryAndroid::CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryAndroid::CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowRenderSurface >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< PixmapRenderSurface > RenderSurfaceFactoryAndroid::CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryAndroid::CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return std::unique_ptr< PixmapRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } -std::unique_ptr< NativeRenderSurface > RenderSurfaceFactoryAndroid::CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryAndroid::CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent) { - return std::unique_ptr< NativeRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } // this should be created from somewhere -std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory() +std::unique_ptr GetRenderSurfaceFactory() { // returns Window factory - return Utils::MakeUnique< RenderSurfaceFactoryAndroid >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/android/render-surface-factory-android.h b/dali/internal/window-system/android/render-surface-factory-android.h index 4ade01e..b83d21c 100644 --- a/dali/internal/window-system/android/render-surface-factory-android.h +++ b/dali/internal/window-system/android/render-surface-factory-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ANDROID_RENDER_SURFACE_FACTORY_ANDROID_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,15 +26,14 @@ namespace Internal { namespace Adaptor { - class RenderSurfaceFactoryAndroid : public RenderSurfaceFactory { public: - std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/android/window-base-android.cpp b/dali/internal/window-system/android/window-base-android.cpp index 5e6b7ae..8ce440b 100644 --- a/dali/internal/window-system/android/window-base-android.cpp +++ b/dali/internal/window-system/android/window-base-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,49 +23,46 @@ #include // EXTERNAL_HEADERS -#include -#include -#include #include +#include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - #if defined(DEBUG_ENABLED) -Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_WINDOW_BASE" ); +Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW_BASE"); #endif -WindowBaseAndroid::WindowBaseAndroid( Dali::PositionSize positionSize, Any surface, bool isTransparent ) -: mWindow( nullptr ), - mOwnSurface( false ), - mIsTransparent( false ), // Should only be set to true once we actually create a transparent window regardless of what isTransparent is. - mRotationAppSet( false ) +WindowBaseAndroid::WindowBaseAndroid(Dali::PositionSize positionSize, Any surface, bool isTransparent) +: mWindow(nullptr), + mOwnSurface(false), + mIsTransparent(false), // Should only be set to true once we actually create a transparent window regardless of what isTransparent is. + mRotationAppSet(false) { - Initialize( positionSize, surface, isTransparent ); + Initialize(positionSize, surface, isTransparent); } WindowBaseAndroid::~WindowBaseAndroid() = default; -void WindowBaseAndroid::Initialize( PositionSize positionSize, Any surface, bool isTransparent ) +void WindowBaseAndroid::Initialize(PositionSize positionSize, Any surface, bool isTransparent) { - if( !surface.Empty() ) + if(!surface.Empty()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Initialising using supplied Android native window\n" ); - mWindow = static_cast< ANativeWindow* >( AnyCast< void* >( surface ) ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Initialising using supplied Android native window\n"); + mWindow = static_cast(AnyCast(surface)); } else { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Initialising using default Android native window\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Initialising using default Android native window\n"); mWindow = Dali::Integration::AndroidFramework::Get().GetApplicationWindow(); } - DALI_ASSERT_ALWAYS( mWindow && "Failed to get Android window" ); + DALI_ASSERT_ALWAYS(mWindow && "Failed to get Android window"); mIsTransparent = true; } @@ -74,53 +71,53 @@ void WindowBaseAndroid::OnDeleteRequest() mDeleteRequestSignal.Emit(); } -void WindowBaseAndroid::OnFocusIn( void* data, int type, void* event ) +void WindowBaseAndroid::OnFocusIn(void* data, int type, void* event) { } -void WindowBaseAndroid::OnFocusOut( void* data, int type, void* event ) +void WindowBaseAndroid::OnFocusOut(void* data, int type, void* event) { } -void WindowBaseAndroid::OnWindowDamaged( void* data, int type, void* event ) +void WindowBaseAndroid::OnWindowDamaged(void* data, int type, void* event) { } -void WindowBaseAndroid::OnMouseButtonDown( void* data, int type, void* event ) +void WindowBaseAndroid::OnMouseButtonDown(void* data, int type, void* event) { } -void WindowBaseAndroid::OnMouseButtonUp( void* data, int type, void* event ) +void WindowBaseAndroid::OnMouseButtonUp(void* data, int type, void* event) { } -void WindowBaseAndroid::OnMouseButtonMove( void* data, int type, void* event ) +void WindowBaseAndroid::OnMouseButtonMove(void* data, int type, void* event) { } -void WindowBaseAndroid::OnMouseWheel( void* data, int type, void* event ) +void WindowBaseAndroid::OnMouseWheel(void* data, int type, void* event) { } -void WindowBaseAndroid::OnKeyDown( void* data, int type, void* event ) +void WindowBaseAndroid::OnKeyDown(void* data, int type, void* event) { } -void WindowBaseAndroid::OnKeyUp( void* data, int type, void* event ) +void WindowBaseAndroid::OnKeyUp(void* data, int type, void* event) { } -void WindowBaseAndroid::OnSelectionClear( void* data, int type, void* event ) +void WindowBaseAndroid::OnSelectionClear(void* data, int type, void* event) { } -void WindowBaseAndroid::OnSelectionNotify( void* data, int type, void* event ) +void WindowBaseAndroid::OnSelectionNotify(void* data, int type, void* event) { } Any WindowBaseAndroid::GetNativeWindow() { - return static_cast< void* >( mWindow ); + return static_cast(mWindow); } int WindowBaseAndroid::GetNativeWindowId() @@ -128,32 +125,32 @@ int WindowBaseAndroid::GetNativeWindowId() return 0; } -EGLNativeWindowType WindowBaseAndroid::CreateEglWindow( int width, int height ) +EGLNativeWindowType WindowBaseAndroid::CreateEglWindow(int width, int height) { // from eglplatform.h header // typedef struct ANativeWindow* EGLNativeWindowType; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Returns the window created for us.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Returns the window created for us.\n"); return mWindow; } void WindowBaseAndroid::DestroyEglWindow() { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Does nothing, the window is not owned by us.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Does nothing, the window is not owned by us.\n"); } -void WindowBaseAndroid::SetEglWindowRotation( int angle ) +void WindowBaseAndroid::SetEglWindowRotation(int angle) { } -void WindowBaseAndroid::SetEglWindowBufferTransform( int angle ) +void WindowBaseAndroid::SetEglWindowBufferTransform(int angle) { } -void WindowBaseAndroid::SetEglWindowTransform( int angle ) +void WindowBaseAndroid::SetEglWindowTransform(int angle) { } -void WindowBaseAndroid::ResizeEglWindow( PositionSize positionSize ) +void WindowBaseAndroid::ResizeEglWindow(PositionSize positionSize) { } @@ -162,19 +159,19 @@ bool WindowBaseAndroid::IsEglWindowRotationSupported() return false; } -void WindowBaseAndroid::Move( PositionSize positionSize ) +void WindowBaseAndroid::Move(PositionSize positionSize) { } -void WindowBaseAndroid::Resize( PositionSize positionSize ) +void WindowBaseAndroid::Resize(PositionSize positionSize) { } -void WindowBaseAndroid::MoveResize( PositionSize positionSize ) +void WindowBaseAndroid::MoveResize(PositionSize positionSize) { } -void WindowBaseAndroid::SetClass( const std::string& name, const std::string& className ) +void WindowBaseAndroid::SetClass(const std::string& name, const std::string& className) { } @@ -190,15 +187,15 @@ void WindowBaseAndroid::Activate() { } -void WindowBaseAndroid::SetAvailableAnlges( const std::vector< int >& angles ) +void WindowBaseAndroid::SetAvailableAnlges(const std::vector& angles) { } -void WindowBaseAndroid::SetPreferredAngle( int angle ) +void WindowBaseAndroid::SetPreferredAngle(int angle) { } -void WindowBaseAndroid::SetAcceptFocus( bool accept ) +void WindowBaseAndroid::SetAcceptFocus(bool accept) { } @@ -215,45 +212,45 @@ unsigned int WindowBaseAndroid::GetSupportedAuxiliaryHintCount() const return 0; } -std::string WindowBaseAndroid::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string WindowBaseAndroid::GetSupportedAuxiliaryHint(unsigned int index) const { return std::string(); } -unsigned int WindowBaseAndroid::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int WindowBaseAndroid::AddAuxiliaryHint(const std::string& hint, const std::string& value) { return 0; } -bool WindowBaseAndroid::RemoveAuxiliaryHint( unsigned int id ) +bool WindowBaseAndroid::RemoveAuxiliaryHint(unsigned int id) { return false; } -bool WindowBaseAndroid::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool WindowBaseAndroid::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { return false; } -std::string WindowBaseAndroid::GetAuxiliaryHintValue( unsigned int id ) const +std::string WindowBaseAndroid::GetAuxiliaryHintValue(unsigned int id) const { return std::string(); } -unsigned int WindowBaseAndroid::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int WindowBaseAndroid::GetAuxiliaryHintId(const std::string& hint) const { return 0; } -void WindowBaseAndroid::SetInputRegion( const Rect< int >& inputRegion ) +void WindowBaseAndroid::SetInputRegion(const Rect& inputRegion) { } -void WindowBaseAndroid::SetType( Dali::WindowType type ) +void WindowBaseAndroid::SetType(Dali::WindowType type) { } -bool WindowBaseAndroid::SetNotificationLevel( Dali::WindowNotificationLevel level ) +bool WindowBaseAndroid::SetNotificationLevel(Dali::WindowNotificationLevel level) { return false; } @@ -263,7 +260,7 @@ Dali::WindowNotificationLevel WindowBaseAndroid::GetNotificationLevel() const return Dali::WindowNotificationLevel::NONE; } -void WindowBaseAndroid::SetOpaqueState( bool opaque ) +void WindowBaseAndroid::SetOpaqueState(bool opaque) { } @@ -277,7 +274,7 @@ WindowScreenOffMode WindowBaseAndroid::GetScreenOffMode() const return WindowScreenOffMode::TIMEOUT; } -bool WindowBaseAndroid::SetBrightness( int brightness ) +bool WindowBaseAndroid::SetBrightness(int brightness) { return false; } @@ -287,34 +284,34 @@ int WindowBaseAndroid::GetBrightness() const return 0; } -bool WindowBaseAndroid::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) +bool WindowBaseAndroid::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) { return false; } -bool WindowBaseAndroid::UngrabKey( Dali::KEY key ) +bool WindowBaseAndroid::UngrabKey(Dali::KEY key) { return false; } -bool WindowBaseAndroid::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) +bool WindowBaseAndroid::GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) { return false; } -bool WindowBaseAndroid::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) +bool WindowBaseAndroid::UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) { return false; } -void WindowBaseAndroid::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void WindowBaseAndroid::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { AConfiguration* config = Dali::Integration::AndroidFramework::Get().GetApplicationConfiguration(); - int32_t density = AConfiguration_getDensity( config ); - if( density == ACONFIGURATION_DENSITY_ANY ) + int32_t density = AConfiguration_getDensity(config); + if(density == ACONFIGURATION_DENSITY_ANY) { - DALI_LOG_ERROR( "Failed to get Android DPI, use 0 instead." ); + DALI_LOG_ERROR("Failed to get Android DPI, use 0 instead."); density = 0; } @@ -327,19 +324,19 @@ int WindowBaseAndroid::GetScreenRotationAngle() return 0; } -void WindowBaseAndroid::SetWindowRotationAngle( int degree ) +void WindowBaseAndroid::SetWindowRotationAngle(int degree) { } -void WindowBaseAndroid::WindowRotationCompleted( int degree, int width, int height ) +void WindowBaseAndroid::WindowRotationCompleted(int degree, int width, int height) { } -void WindowBaseAndroid::SetTransparency( bool transparent ) +void WindowBaseAndroid::SetTransparency(bool transparent) { } -void WindowBaseAndroid::SetParent( WindowBase* parentWinBase ) +void WindowBaseAndroid::SetParent(WindowBase* parentWinBase) { } @@ -363,4 +360,3 @@ int WindowBaseAndroid::GetOrientation() const } // namespace Internal } // namespace Dali - diff --git a/dali/internal/window-system/android/window-base-android.h b/dali/internal/window-system/android/window-base-android.h index ee5c300..1dd4cd6 100644 --- a/dali/internal/window-system/android/window-base-android.h +++ b/dali/internal/window-system/android/window-base-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ANDROID_WINDOW_BASE_ANDROID_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,18 +30,16 @@ namespace Internal { namespace Adaptor { - /** * WindowBaseAndroid class provides an WindowBase Android implementation. */ class WindowBaseAndroid : public WindowBase { public: - /** * @brief Constructor */ - WindowBaseAndroid( PositionSize positionSize, Any surface, bool isTransparent ); + WindowBaseAndroid(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Destructor @@ -49,11 +47,10 @@ public: virtual ~WindowBaseAndroid(); public: - /** * @brief Called when the window property is changed. */ - bool OnWindowPropertyChanged( void* data, int type, void* event ); + bool OnWindowPropertyChanged(void* data, int type, void* event); /** * @brief Called when the window receives a delete request @@ -63,60 +60,59 @@ public: /** * @brief Called when the window gains focus. */ - void OnFocusIn( void* data, int type, void* event ); + void OnFocusIn(void* data, int type, void* event); /** * @brief Called when the window loses focus. */ - void OnFocusOut( void* data, int type, void* event ); + void OnFocusOut(void* data, int type, void* event); /** * @brief Called when the window is damaged. */ - void OnWindowDamaged( void* data, int type, void* event ); + void OnWindowDamaged(void* data, int type, void* event); /** * @brief Called when a touch down is received. */ - void OnMouseButtonDown( void* data, int type, void* event ); + void OnMouseButtonDown(void* data, int type, void* event); /** * @brief Called when a touch up is received. */ - void OnMouseButtonUp( void* data, int type, void* event ); + void OnMouseButtonUp(void* data, int type, void* event); /** * @brief Called when a touch motion is received. */ - void OnMouseButtonMove( void* data, int type, void* event ); + void OnMouseButtonMove(void* data, int type, void* event); /** * @brief Called when a mouse wheel is received. */ - void OnMouseWheel( void* data, int type, void* event ); + void OnMouseWheel(void* data, int type, void* event); /** * @brief Called when a key down is received. */ - void OnKeyDown( void* data, int type, void* event ); + void OnKeyDown(void* data, int type, void* event); /** * @brief Called when a key up is received. */ - void OnKeyUp( void* data, int type, void* event ); + void OnKeyUp(void* data, int type, void* event); /** * @brief Called when the source window notifies us the content in clipboard is selected. */ - void OnSelectionClear( void* data, int type, void* event ); + void OnSelectionClear(void* data, int type, void* event); /** * @brief Called when the source window sends us about the selected content. */ - void OnSelectionNotify( void* data, int type, void* event ); + void OnSelectionNotify(void* data, int type, void* event); public: - /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNativeWindow() */ @@ -130,7 +126,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateEglWindow() */ - EGLNativeWindowType CreateEglWindow( int width, int height ) override; + EGLNativeWindowType CreateEglWindow(int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::DestroyEglWindow() @@ -140,22 +136,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowRotation() */ - void SetEglWindowRotation( int angle ) override; + void SetEglWindowRotation(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowBufferTransform() */ - void SetEglWindowBufferTransform( int angle ) override; + void SetEglWindowBufferTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowTransform() */ - void SetEglWindowTransform( int angle ) override; + void SetEglWindowTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::ResizeEglWindow() */ - void ResizeEglWindow( PositionSize positionSize ) override; + void ResizeEglWindow(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::IsEglWindowRotationSupported() @@ -165,22 +161,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::Move() */ - void Move( PositionSize positionSize ) override; + void Move(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Resize() */ - void Resize( PositionSize positionSize ) override; + void Resize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::MoveResize() */ - void MoveResize( PositionSize positionSize ) override; + void MoveResize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetClass() */ - void SetClass( const std::string& name, const std::string& className ) override; + void SetClass(const std::string& name, const std::string& className) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Raise() @@ -200,17 +196,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAvailableAnlges() */ - void SetAvailableAnlges( const std::vector< int >& angles ) override; + void SetAvailableAnlges(const std::vector& angles) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetPreferredAngle() */ - void SetPreferredAngle( int angle ) override; + void SetPreferredAngle(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ) override; + void SetAcceptFocus(bool accept) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Show() @@ -230,47 +226,47 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const override; + std::string GetSupportedAuxiliaryHint(unsigned int index) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) override; + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ) override; + bool RemoveAuxiliaryHint(unsigned int id) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) override; + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const override; + std::string GetAuxiliaryHintValue(unsigned int id) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const override; + unsigned int GetAuxiliaryHintId(const std::string& hint) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ) override; + void SetInputRegion(const Rect& inputRegion) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetType() */ - void SetType( Dali::WindowType type ) override; + void SetType(Dali::WindowType type) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetNotificationLevel() */ - bool SetNotificationLevel( Dali::WindowNotificationLevel level ) override; + bool SetNotificationLevel(Dali::WindowNotificationLevel level) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNotificationLevel() @@ -280,7 +276,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetOpaqueState() */ - void SetOpaqueState( bool opaque ) override; + void SetOpaqueState(bool opaque) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetScreenOffMode() @@ -295,7 +291,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetBrightness() */ - bool SetBrightness( int brightness ) override; + bool SetBrightness(int brightness) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetBrightness() @@ -305,27 +301,27 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) override; + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKey() */ - bool UngrabKey( Dali::KEY key ) override; + bool UngrabKey(Dali::KEY key) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKeyList() */ - bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) override; + bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKeyList() */ - bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) override; + bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetScreenRotationAngle() @@ -335,22 +331,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetWindowRotationAngle() */ - void SetWindowRotationAngle( int degree ) override; + void SetWindowRotationAngle(int degree) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::WindowRotationCompleted() */ - void WindowRotationCompleted( int degree, int width, int height ) override; + void WindowRotationCompleted(int degree, int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetTransparency() */ - void SetTransparency( bool transparent ) override; + void SetTransparency(bool transparent) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetParent() */ - void SetParent( WindowBase* parentWinBase ) override; + void SetParent(WindowBase* parentWinBase) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateFrameRenderedSyncFence() @@ -368,21 +364,19 @@ public: int GetOrientation() const override; private: - /** * Second stage initialization */ - void Initialize( PositionSize positionSize, Any surface, bool isTransparent ); + void Initialize(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Get the surface id if the surface parameter is not empty * @param surface Any containing a surface id, or can be empty * @return surface id, or zero if surface is empty */ - unsigned int GetSurfaceId( Any surface ) const; + unsigned int GetSurfaceId(Any surface) const; protected: - // Undefined WindowBaseAndroid(const WindowBaseAndroid&) = delete; @@ -390,16 +384,15 @@ protected: WindowBaseAndroid& operator=(const WindowBaseAndroid& rhs) = delete; private: - - ANativeWindow* mWindow; ///< Native window handle - bool mOwnSurface:1; ///< Whether we own the surface (responsible for deleting it) - bool mIsTransparent; ///< Whether the window is transparent (32 bit or 24 bit) - bool mRotationAppSet:1; + ANativeWindow* mWindow; ///< Native window handle + bool mOwnSurface : 1; ///< Whether we own the surface (responsible for deleting it) + bool mIsTransparent; ///< Whether the window is transparent (32 bit or 24 bit) + bool mRotationAppSet : 1; }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/android/window-factory-android.cpp b/dali/internal/window-system/android/window-factory-android.cpp index 01ec05b..735c1b7 100644 --- a/dali/internal/window-system/android/window-factory-android.cpp +++ b/dali/internal/window-system/android/window-factory-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,17 +28,16 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowBase > WindowFactoryAndroid::CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr WindowFactoryAndroid::CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowBaseAndroid >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } // this should be created from Window impl -std::unique_ptr< WindowFactory > GetWindowFactory() +std::unique_ptr GetWindowFactory() { // returns Window factory - return Utils::MakeUnique< WindowFactoryAndroid >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/android/window-factory-android.h b/dali/internal/window-system/android/window-factory-android.h index f267c35..de917bb 100644 --- a/dali/internal/window-system/android/window-factory-android.h +++ b/dali/internal/window-system/android/window-factory-android.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ANDROID_WINDOW_FACTORY_ANDROID_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,10 @@ namespace Internal { namespace Adaptor { - class WindowFactoryAndroid : public WindowFactory { public: - std::unique_ptr< WindowBase > CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) override; + std::unique_ptr CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/android/window-system-android.cpp b/dali/internal/window-system/android/window-system-android.cpp index e6ba067..749e140 100644 --- a/dali/internal/window-system/android/window-system-android.cpp +++ b/dali/internal/window-system/android/window-system-android.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,21 +20,17 @@ #include // EXTERNAL_HEADERS -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowSystem { - void Initialize() { } @@ -43,20 +39,20 @@ void Shutdown() { } -void GetScreenSize( int& width, int& height ) +void GetScreenSize(int& width, int& height) { ANativeWindow* window = Dali::Integration::AndroidFramework::Get().GetApplicationWindow(); - width = ANativeWindow_getWidth( window ); - height = ANativeWindow_getHeight( window ); - DALI_LOG_WARNING( "Native window width %d, height %d", width, height ); + width = ANativeWindow_getWidth(window); + height = ANativeWindow_getHeight(window); + DALI_LOG_WARNING("Native window width %d, height %d", width, height); } -bool SetKeyboardRepeatInfo( float rate, float delay ) +bool SetKeyboardRepeatInfo(float rate, float delay) { return false; } -bool GetKeyboardRepeatInfo( float& rate, float& delay ) +bool GetKeyboardRepeatInfo(float& rate, float& delay) { return false; } @@ -68,4 +64,3 @@ bool GetKeyboardRepeatInfo( float& rate, float& delay ) } // namespace Internal } // namespace Dali - diff --git a/dali/internal/window-system/common/damage-observer.h b/dali/internal/window-system/common/damage-observer.h index b6442a7..5040967 100644 --- a/dali/internal/window-system/common/damage-observer.h +++ b/dali/internal/window-system/common/damage-observer.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_DAMAGE_OBSERVER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - typedef Rect DamageArea; /** @@ -39,15 +36,13 @@ typedef Rect DamageArea; class DamageObserver { public: - /** * Deriving classes should override this to be notified when we receive a damage event. * @param[in] area The area that has been damaged. */ - virtual void OnDamaged( const DamageArea& area ) = 0; + virtual void OnDamaged(const DamageArea& area) = 0; protected: - /** * Protected Constructor. */ diff --git a/dali/internal/window-system/common/display-connection-factory.h b/dali/internal/window-system/common/display-connection-factory.h index 14f5bd0..e1da385 100644 --- a/dali/internal/window-system/common/display-connection-factory.h +++ b/dali/internal/window-system/common/display-connection-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_FACTORY_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,17 +26,14 @@ namespace Internal { namespace Adaptor { - class DisplayConnection; class DisplayConnectionFactory { public: - - DisplayConnectionFactory() = default; + DisplayConnectionFactory() = default; virtual ~DisplayConnectionFactory() = default; virtual std::unique_ptr CreateDisplayConnection() = 0; - }; extern std::unique_ptr GetDisplayConnectionFactory(); diff --git a/dali/internal/window-system/common/display-connection-impl.h b/dali/internal/window-system/common/display-connection-impl.h index 8ced957..1dbbe3c 100644 --- a/dali/internal/window-system/common/display-connection-impl.h +++ b/dali/internal/window-system/common/display-connection-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,28 +19,24 @@ */ // INTERNAL INCLUDES +#include #include #include -#include - namespace Dali { - class DisplayConnection; namespace Internal { namespace Adaptor { - /** * DisplayConnection implementation */ class DisplayConnection : public Dali::BaseObject { public: - /** * @brief Default constructor */ @@ -54,7 +50,6 @@ public: static DisplayConnection* New(); public: - /** * @copydoc Dali::DisplayConnection::GetDisplay */ @@ -74,34 +69,31 @@ public: * Sets the render surface type * @param[in] type The render surface type */ - virtual void SetSurfaceType( Dali::RenderSurfaceInterface::Type type ) = 0; + virtual void SetSurfaceType(Dali::RenderSurfaceInterface::Type type) = 0; /** * Sets the graphics interface * @param[in] graphics The graphics interface */ - virtual void SetGraphicsInterface( GraphicsInterface& graphics ) = 0; + virtual void SetGraphicsInterface(GraphicsInterface& graphics) = 0; public: - /** * Destructor */ ~DisplayConnection() override = default; protected: - // Undefined DisplayConnection(const DisplayConnection&) = delete; // Undefined DisplayConnection& operator=(const DisplayConnection& rhs) = delete; - }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/common/display-connection.cpp b/dali/internal/window-system/common/display-connection.cpp index a91d507..2c3a1a4 100644 --- a/dali/internal/window-system/common/display-connection.cpp +++ b/dali/internal/window-system/common/display-connection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,37 +16,35 @@ */ // CLASS HEADER -#include #include +#include // INTERNAL INCLUDES -#include #include - +#include namespace Dali { - -DisplayConnection* DisplayConnection::New( Dali::Internal::Adaptor::GraphicsInterface& graphics ) +DisplayConnection* DisplayConnection::New(Dali::Internal::Adaptor::GraphicsInterface& graphics) { - auto factory = Dali::Internal::Adaptor::GetDisplayConnectionFactory(); + auto factory = Dali::Internal::Adaptor::GetDisplayConnectionFactory(); auto displayConnection = factory->CreateDisplayConnection(); - Internal::Adaptor::DisplayConnection* internal( displayConnection.release() ); - internal->SetGraphicsInterface( graphics ); + Internal::Adaptor::DisplayConnection* internal(displayConnection.release()); + internal->SetGraphicsInterface(graphics); return new DisplayConnection(internal); } -DisplayConnection* DisplayConnection::New( Dali::Internal::Adaptor::GraphicsInterface& graphics, Dali::RenderSurfaceInterface::Type type ) +DisplayConnection* DisplayConnection::New(Dali::Internal::Adaptor::GraphicsInterface& graphics, Dali::RenderSurfaceInterface::Type type) { - auto factory = Dali::Internal::Adaptor::GetDisplayConnectionFactory(); + auto factory = Dali::Internal::Adaptor::GetDisplayConnectionFactory(); auto displayConnection = factory->CreateDisplayConnection(); - Internal::Adaptor::DisplayConnection* internal( displayConnection.release() ); + Internal::Adaptor::DisplayConnection* internal(displayConnection.release()); - internal->SetGraphicsInterface( graphics ); - internal->SetSurfaceType( type ); + internal->SetGraphicsInterface(graphics); + internal->SetSurfaceType(type); return new DisplayConnection(internal); } @@ -57,7 +55,7 @@ DisplayConnection::~DisplayConnection() = default; DisplayConnection::DisplayConnection(Internal::Adaptor::DisplayConnection* impl) { - mImpl.reset( impl ); + mImpl.reset(impl); } Any DisplayConnection::GetDisplay() @@ -75,4 +73,4 @@ bool DisplayConnection::Initialize() return mImpl->InitializeGraphics(); } -} +} // namespace Dali diff --git a/dali/internal/window-system/common/display-connection.h b/dali/internal/window-system/common/display-connection.h index 3982d09..1fb9008 100644 --- a/dali/internal/window-system/common/display-connection.h +++ b/dali/internal/window-system/common/display-connection.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ #include #include - namespace Dali { namespace Internal @@ -34,19 +33,18 @@ namespace Adaptor { class DisplayConnection; } -} +} // namespace Internal class DisplayConnection { public: - /** * @brief Create an initialized DisplayConnection. * * @param[in] graphics The abstracted graphics interface * @return A handle to a newly allocated DisplayConnection resource. */ - static DisplayConnection* New( Dali::Internal::Adaptor::GraphicsInterface& graphics ); + static DisplayConnection* New(Dali::Internal::Adaptor::GraphicsInterface& graphics); /** * @brief Create an initialized DisplayConnection. @@ -56,7 +54,7 @@ public: * @param[in] type Render surface type * @return A handle to a newly allocated DisplayConnection resource. */ - static DisplayConnection* New( Dali::Internal::Adaptor::GraphicsInterface& graphics, Dali::RenderSurfaceInterface::Type type ); + static DisplayConnection* New(Dali::Internal::Adaptor::GraphicsInterface& graphics, Dali::RenderSurfaceInterface::Type type); /** * @brief Create a DisplayConnection handle; this can be initialised with DisplayConnection::New(). @@ -90,7 +88,6 @@ public: bool Initialize(); public: - /** * @brief This constructor is used by DisplayConnection New() methods. * @@ -99,10 +96,9 @@ public: explicit DALI_INTERNAL DisplayConnection(Internal::Adaptor::DisplayConnection* impl); private: - std::unique_ptr mImpl; }; -} +} // namespace Dali #endif // DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_CONNECTION_H diff --git a/dali/internal/window-system/common/display-utils.h b/dali/internal/window-system/common/display-utils.h index 05d0176..5a9456f 100644 --- a/dali/internal/window-system/common/display-utils.h +++ b/dali/internal/window-system/common/display-utils.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_DISPLAY_UTILs_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ namespace Adaptor { namespace Utils { - template std::unique_ptr MakeUnique(Args&&... args) { diff --git a/dali/internal/window-system/common/event-handler.cpp b/dali/internal/window-system/common/event-handler.cpp old mode 100755 new mode 100644 index bf614d7..691f5e6 --- a/dali/internal/window-system/common/event-handler.cpp +++ b/dali/internal/window-system/common/event-handler.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,17 +19,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include #include -#include -#include #include +#include #include #include -#include #include +#include +#include // INTERNAL INCLUDES #include @@ -38,13 +38,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - #if defined(DEBUG_ENABLED) namespace { @@ -52,25 +49,25 @@ Integration::Log::Filter* gSelectionEventLogFilter = Integration::Log::Filter::N } // unnamed namespace #endif -EventHandler::EventHandler( WindowBase* windowBase, DamageObserver& damageObserver ) -: mStyleMonitor( StyleMonitor::Get() ), - mDamageObserver( damageObserver ), - mClipboardEventNotifier( ClipboardEventNotifier::Get() ), - mClipboard( Clipboard::Get() ), - mPaused( false ) +EventHandler::EventHandler(WindowBase* windowBase, DamageObserver& damageObserver) +: mStyleMonitor(StyleMonitor::Get()), + mDamageObserver(damageObserver), + mClipboardEventNotifier(ClipboardEventNotifier::Get()), + mClipboard(Clipboard::Get()), + mPaused(false) { // Connect signals - if( windowBase ) + if(windowBase) { - windowBase->WindowDamagedSignal().Connect( this, &EventHandler::OnWindowDamaged ); - windowBase->FocusChangedSignal().Connect( this, &EventHandler::OnFocusChanged ); - windowBase->RotationSignal().Connect( this, &EventHandler::OnRotation ); - windowBase->TouchEventSignal().Connect( this, &EventHandler::OnTouchEvent ); - windowBase->WheelEventSignal().Connect( this, &EventHandler::OnWheelEvent ); - windowBase->KeyEventSignal().Connect( this, &EventHandler::OnKeyEvent ); - windowBase->SelectionDataSendSignal().Connect( this, &EventHandler::OnSelectionDataSend ); - windowBase->SelectionDataReceivedSignal().Connect( this, &EventHandler::OnSelectionDataReceived ); - windowBase->StyleChangedSignal().Connect( this, &EventHandler::OnStyleChanged ); + windowBase->WindowDamagedSignal().Connect(this, &EventHandler::OnWindowDamaged); + windowBase->FocusChangedSignal().Connect(this, &EventHandler::OnFocusChanged); + windowBase->RotationSignal().Connect(this, &EventHandler::OnRotation); + windowBase->TouchEventSignal().Connect(this, &EventHandler::OnTouchEvent); + windowBase->WheelEventSignal().Connect(this, &EventHandler::OnWheelEvent); + windowBase->KeyEventSignal().Connect(this, &EventHandler::OnKeyEvent); + windowBase->SelectionDataSendSignal().Connect(this, &EventHandler::OnSelectionDataSend); + windowBase->SelectionDataReceivedSignal().Connect(this, &EventHandler::OnSelectionDataReceived); + windowBase->StyleChangedSignal().Connect(this, &EventHandler::OnStyleChanged); } else { @@ -82,15 +79,15 @@ EventHandler::~EventHandler() { } -void EventHandler::SendEvent( StyleChange::Type styleChange ) +void EventHandler::SendEvent(StyleChange::Type styleChange) { - DALI_ASSERT_DEBUG( mStyleMonitor && "StyleMonitor Not Available" ); - GetImplementation( mStyleMonitor ).StyleChanged(styleChange); + DALI_ASSERT_DEBUG(mStyleMonitor && "StyleMonitor Not Available"); + GetImplementation(mStyleMonitor).StyleChanged(styleChange); } -void EventHandler::SendEvent( const DamageArea& area ) +void EventHandler::SendEvent(const DamageArea& area) { - mDamageObserver.OnDamaged( area ); + mDamageObserver.OnDamaged(area); } void EventHandler::Pause() @@ -103,37 +100,37 @@ void EventHandler::Resume() mPaused = false; } -void EventHandler::OnTouchEvent( Integration::Point& point, uint32_t timeStamp ) +void EventHandler::OnTouchEvent(Integration::Point& point, uint32_t timeStamp) { - for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter ) + for(ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter) { - (*iter)->OnTouchPoint( point, timeStamp ); + (*iter)->OnTouchPoint(point, timeStamp); } } -void EventHandler::OnWheelEvent( Integration::WheelEvent& wheelEvent ) +void EventHandler::OnWheelEvent(Integration::WheelEvent& wheelEvent) { - for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter ) + for(ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter) { - (*iter)->OnWheelEvent( wheelEvent ); + (*iter)->OnWheelEvent(wheelEvent); } } -void EventHandler::OnKeyEvent( Integration::KeyEvent& keyEvent ) +void EventHandler::OnKeyEvent(Integration::KeyEvent& keyEvent) { - for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter ) + for(ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter) { - (*iter)->OnKeyEvent( keyEvent ); + (*iter)->OnKeyEvent(keyEvent); } } -void EventHandler::OnFocusChanged( bool focusIn ) +void EventHandler::OnFocusChanged(bool focusIn) { // If the window gains focus and we hid the keyboard then show it again. - if( focusIn ) + if(focusIn) { Dali::Clipboard clipboard = Clipboard::Get(); - if ( clipboard ) + if(clipboard) { clipboard.HideClipboard(); } @@ -142,82 +139,82 @@ void EventHandler::OnFocusChanged( bool focusIn ) { // Hiding clipboard event will be ignored once because window focus out event is always received on showing clipboard Dali::Clipboard clipboard = Clipboard::Get(); - if ( clipboard ) + if(clipboard) { - Clipboard& clipBoardImpl( GetImplementation( clipboard ) ); + Clipboard& clipBoardImpl(GetImplementation(clipboard)); clipBoardImpl.HideClipboard(true); } } } -void EventHandler::OnRotation( const RotationEvent& event ) +void EventHandler::OnRotation(const RotationEvent& event) { - for ( ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter ) + for(ObserverContainer::iterator iter = mObservers.begin(), endIter = mObservers.end(); iter != endIter; ++iter) { - (*iter)->OnRotation( event ); + (*iter)->OnRotation(event); } } -void EventHandler::OnWindowDamaged( const DamageArea& area ) +void EventHandler::OnWindowDamaged(const DamageArea& area) { - SendEvent( area ); + SendEvent(area); } -void EventHandler::OnSelectionDataSend( void* event ) +void EventHandler::OnSelectionDataSend(void* event) { Dali::Clipboard clipboard = Clipboard::Get(); - if( clipboard ) + if(clipboard) { - Clipboard& clipBoardImpl( GetImplementation( clipboard ) ); - clipBoardImpl.ExcuteBuffered( true, event ); + Clipboard& clipBoardImpl(GetImplementation(clipboard)); + clipBoardImpl.ExcuteBuffered(true, event); } } -void EventHandler::OnSelectionDataReceived( void* event ) +void EventHandler::OnSelectionDataReceived(void* event) { // We have got the selected content, inform the clipboard event listener (if we have one). - Dali::Clipboard clipboard = Clipboard::Get(); - char* selectionData = NULL; - if( clipboard ) + Dali::Clipboard clipboard = Clipboard::Get(); + char* selectionData = NULL; + if(clipboard) { - Clipboard& clipBoardImpl( GetImplementation( clipboard ) ); - selectionData = clipBoardImpl.ExcuteBuffered( false, event ); + Clipboard& clipBoardImpl(GetImplementation(clipboard)); + selectionData = clipBoardImpl.ExcuteBuffered(false, event); } - if( selectionData && mClipboardEventNotifier ) + if(selectionData && mClipboardEventNotifier) { - ClipboardEventNotifier& clipboardEventNotifier( ClipboardEventNotifier::GetImplementation( mClipboardEventNotifier ) ); - std::string content( selectionData, strlen( selectionData ) ); + ClipboardEventNotifier& clipboardEventNotifier(ClipboardEventNotifier::GetImplementation(mClipboardEventNotifier)); + std::string content(selectionData, strlen(selectionData)); - clipboardEventNotifier.SetContent( content ); + clipboardEventNotifier.SetContent(content); clipboardEventNotifier.EmitContentSelectedSignal(); - DALI_LOG_INFO( gSelectionEventLogFilter, Debug::General, "EcoreEventSelectionNotify: Content(%d): %s\n" , strlen(selectionData), selectionData ); + DALI_LOG_INFO(gSelectionEventLogFilter, Debug::General, "EcoreEventSelectionNotify: Content(%d): %s\n", strlen(selectionData), selectionData); } } -void EventHandler::OnStyleChanged( StyleChange::Type styleChange ) +void EventHandler::OnStyleChanged(StyleChange::Type styleChange) { - SendEvent( styleChange ); + SendEvent(styleChange); } -void EventHandler::AddObserver( Observer& observer ) +void EventHandler::AddObserver(Observer& observer) { - ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) ); + ObserverContainer::iterator match(find(mObservers.begin(), mObservers.end(), &observer)); - if ( match == mObservers.end() ) + if(match == mObservers.end()) { - mObservers.push_back( &observer ); + mObservers.push_back(&observer); } } -void EventHandler::RemoveObserver( Observer& observer ) +void EventHandler::RemoveObserver(Observer& observer) { - ObserverContainer::iterator match ( find(mObservers.begin(), mObservers.end(), &observer) ); + ObserverContainer::iterator match(find(mObservers.begin(), mObservers.end(), &observer)); - if ( match != mObservers.end() ) + if(match != mObservers.end()) { - mObservers.erase( match ); + mObservers.erase(match); } } diff --git a/dali/internal/window-system/common/event-handler.h b/dali/internal/window-system/common/event-handler.h index 808f2ef..3158efd 100644 --- a/dali/internal/window-system/common/event-handler.h +++ b/dali/internal/window-system/common/event-handler.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_EVENT_HANDLER_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ */ // EXTERNAL INCLUDES -#include // uint32_t #include +#include // uint32_t #include #include @@ -32,22 +32,18 @@ namespace Dali { - namespace Integration { - struct Point; struct KeyEvent; struct WheelEvent; -} +} // namespace Integration namespace Internal { - namespace Adaptor { - class StyleMonitor; class WindowRenderSurface; @@ -60,60 +56,60 @@ class WindowRenderSurface; class EventHandler : public ConnectionTracker, public Dali::RefObject { public: - /** * The observer can be overridden in order to listen to the events. */ class Observer { public: - /** * Deriving classes should override this to be notified when we receive a touch point event. * @param[in] point The touch point * @param[in] timeStamp The time stamp */ - virtual void OnTouchPoint( Dali::Integration::Point& point, int timeStamp ) = 0; + virtual void OnTouchPoint(Dali::Integration::Point& point, int timeStamp) = 0; /** * Deriving classes should override this to be notified when we receive a wheel event. * @param[in] wheelEvent The wheel event */ - virtual void OnWheelEvent( Dali::Integration::WheelEvent& wheelEvent ) = 0; + virtual void OnWheelEvent(Dali::Integration::WheelEvent& wheelEvent) = 0; /** * Deriving classes should override this to be notified when we receive a key event. * @param[in] keyEvent The key event holding the key information. */ - virtual void OnKeyEvent( Dali::Integration::KeyEvent& keyEvent ) = 0; + virtual void OnKeyEvent(Dali::Integration::KeyEvent& keyEvent) = 0; /** * Deriving classes should override this to be notified when the window is rotated. * @param[in] rotation The rotation event. */ - virtual void OnRotation( const RotationEvent& rotation ) = 0; + virtual void OnRotation(const RotationEvent& rotation) = 0; protected: - /** * Protected Constructor. */ - Observer() {} + Observer() + { + } /** * Protected virtual destructor. */ - virtual ~Observer() {} + virtual ~Observer() + { + } }; public: - /** * Constructor. * @param[in] windowBase The window base to be handled * @param[in] damageObserver The damage observer (to pass damage events to). */ - EventHandler( WindowBase* windowBase, DamageObserver& damageObserver ); + EventHandler(WindowBase* windowBase, DamageObserver& damageObserver); /** * Destructor. @@ -134,93 +130,90 @@ public: * Adds an observer so that we can observe the events. * @param[in] observer The observer. */ - void AddObserver( Observer& observer ); + void AddObserver(Observer& observer); /** * Removes the observer from the EventHandler. * @param[in] observer The observer to remove. * @note Observers should remove themselves when they are destroyed. */ - void RemoveObserver( Observer& observer ); + void RemoveObserver(Observer& observer); private: - /** * Send a style change event to the style monitor. * @param[in] styleChange The style that has changed. */ - void SendEvent( StyleChange::Type styleChange ); + void SendEvent(StyleChange::Type styleChange); /** * Send a window damage event to the observer. * @param[in] area Damaged area. */ - void SendEvent( const DamageArea& area ); + void SendEvent(const DamageArea& area); /** * Called when a touch event is received. */ - void OnTouchEvent( Integration::Point& point, uint32_t timeStamp ); + void OnTouchEvent(Integration::Point& point, uint32_t timeStamp); /** * Called when a mouse wheel is received. */ - void OnWheelEvent( Integration::WheelEvent& wheelEvent ); + void OnWheelEvent(Integration::WheelEvent& wheelEvent); /** * Called when a key event is received. */ - void OnKeyEvent( Integration::KeyEvent& keyEvent ); + void OnKeyEvent(Integration::KeyEvent& keyEvent); /** * Called when the window focus is changed. */ - void OnFocusChanged( bool focusIn ); + void OnFocusChanged(bool focusIn); /** * Called when the window is rotated. * @param[in] event The rotation event */ - void OnRotation( const RotationEvent& event ); + void OnRotation(const RotationEvent& event); /** * Called when the window is damaged. */ - void OnWindowDamaged( const DamageArea& area ); + void OnWindowDamaged(const DamageArea& area); /** * Called when the source window notifies us the content in clipboard is selected. */ - void OnSelectionDataSend( void* event ); + void OnSelectionDataSend(void* event); /** * Called when the source window sends us about the selected content. */ - void OnSelectionDataReceived( void* event ); + void OnSelectionDataReceived(void* event); /** * Called when the style is changed. */ - void OnStyleChanged( StyleChange::Type styleChange ); + void OnStyleChanged(StyleChange::Type styleChange); private: - // Undefined - EventHandler( const EventHandler& eventHandler ); + EventHandler(const EventHandler& eventHandler); // Undefined - EventHandler& operator=( const EventHandler& eventHandler ); + EventHandler& operator=(const EventHandler& eventHandler); private: - - Dali::StyleMonitor mStyleMonitor; ///< Handle to the style monitor, set on construction, to send font size and font change events to. - DamageObserver& mDamageObserver; ///< Reference to the DamageObserver, set on construction, to sent damage events to. + Dali::StyleMonitor mStyleMonitor; ///< Handle to the style monitor, set on construction, to send font size and font change events to. + DamageObserver& mDamageObserver; ///< Reference to the DamageObserver, set on construction, to sent damage events to. Dali::ClipboardEventNotifier mClipboardEventNotifier; ///< Pointer to the clipboard event notifier - Dali::Clipboard mClipboard;///< Pointer to the clipboard + Dali::Clipboard mClipboard; ///< Pointer to the clipboard using ObserverContainer = std::vector; - ObserverContainer mObservers; ///< A list of event observer pointers + ObserverContainer mObservers; ///< A list of event observer pointers bool mPaused; ///< The paused state of the adaptor. }; diff --git a/dali/internal/window-system/common/native-render-surface-factory.cpp b/dali/internal/window-system/common/native-render-surface-factory.cpp index 9263c40..28ed119 100644 --- a/dali/internal/window-system/common/native-render-surface-factory.cpp +++ b/dali/internal/window-system/common/native-render-surface-factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,11 +22,10 @@ namespace Dali { - -DALI_ADAPTOR_API NativeRenderSurface* CreateNativeSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent ) +DALI_ADAPTOR_API NativeRenderSurface* CreateNativeSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent) { auto renderSurfaceFactory = Dali::Internal::Adaptor::GetRenderSurfaceFactory(); - auto nativeRenderSurface = renderSurfaceFactory->CreateNativeRenderSurface( surfaceSize, surface, isTransparent ); + auto nativeRenderSurface = renderSurfaceFactory->CreateNativeRenderSurface(surfaceSize, surface, isTransparent); return nativeRenderSurface.release(); } diff --git a/dali/internal/window-system/common/orientation-impl.cpp b/dali/internal/window-system/common/orientation-impl.cpp index 70af3c4..977ea93 100644 --- a/dali/internal/window-system/common/orientation-impl.cpp +++ b/dali/internal/window-system/common/orientation-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -31,7 +31,6 @@ namespace Internal { namespace Adaptor { - Orientation* Orientation::New(Window* window) { Orientation* orientation = new Orientation(window); @@ -68,17 +67,17 @@ Orientation::OrientationSignalType& Orientation::ChangedSignal() return mChangedSignal; } -void Orientation::OnOrientationChange( const RotationEvent& rotation ) +void Orientation::OnOrientationChange(const RotationEvent& rotation) { mOrientation = rotation.angle; mWindowWidth = rotation.width; mWindowHeight = rotation.height; // Emit signal - if( !mChangedSignal.Empty() ) + if(!mChangedSignal.Empty()) { - Dali::Orientation handle( this ); - mChangedSignal.Emit( handle ); + Dali::Orientation handle(this); + mChangedSignal.Emit(handle); } } diff --git a/dali/internal/window-system/common/orientation-impl.h b/dali/internal/window-system/common/orientation-impl.h index 28d4f98..e0598b9 100644 --- a/dali/internal/window-system/common/orientation-impl.h +++ b/dali/internal/window-system/common/orientation-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ORIENTATION_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,9 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES #include @@ -29,10 +29,8 @@ namespace Dali { - namespace Internal { - namespace Adaptor { class Window; @@ -43,7 +41,6 @@ typedef IntrusivePtr OrientationPtr; class Orientation : public BaseObject { public: - typedef Dali::Orientation::OrientationSignalType OrientationSignalType; static Orientation* New(Window* window); @@ -60,7 +57,6 @@ protected: ~Orientation() override; public: - /** * Returns the actual orientation in degrees * @return The device's orientation @@ -77,33 +73,30 @@ public: * Called by the Window when orientation is changed * @param[in] rotation The rotation event */ - void OnOrientationChange( const RotationEvent& rotation ); + void OnOrientationChange(const RotationEvent& rotation); public: // Signals - /** * @copydoc Dali::Orientation::ChangedSignal() */ OrientationSignalType& ChangedSignal(); private: - // Undefined Orientation(const Orientation&); Orientation& operator=(Orientation&); private: - - Window* mWindow; + Window* mWindow; OrientationSignalType mChangedSignal; - int mOrientation; - int mWindowWidth; - int mWindowHeight; + int mOrientation; + int mWindowWidth; + int mWindowHeight; }; -inline Orientation& GetImplementation (Dali::Orientation& orientation) +inline Orientation& GetImplementation(Dali::Orientation& orientation) { DALI_ASSERT_ALWAYS(orientation && "Orientation handle is empty"); diff --git a/dali/internal/window-system/common/pixmap-render-surface.h b/dali/internal/window-system/common/pixmap-render-surface.h index 53f03b5..0574ae4 100644 --- a/dali/internal/window-system/common/pixmap-render-surface.h +++ b/dali/internal/window-system/common/pixmap-render-surface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_PIXMAP_RENDER_SURFACE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,21 +24,18 @@ namespace Dali { - class TriggerEventInterface; namespace Internal { namespace Adaptor { - /** * Pixmap interface of render surface. */ class PixmapRenderSurface : public Dali::RenderSurfaceInterface { public: - /** * @brief Default constructor */ @@ -50,7 +47,6 @@ public: virtual ~PixmapRenderSurface() = default; public: // API - /** * @brief Get the render surface the adaptor is using to render to. * @return reference to current render surface @@ -61,7 +57,7 @@ public: // API * @brief Sets the render notification trigger to call when render thread is completed a frame * @param renderNotification to use */ - virtual void SetRenderNotification( TriggerEventInterface* renderNotification ) = 0; + virtual void SetRenderNotification(TriggerEventInterface* renderNotification) = 0; /** * @copydoc Dali::RenderSurfaceInterface::GetDepthBufferRequired() @@ -80,11 +76,10 @@ public: // API } private: - /** * Second stage construction */ - virtual void Initialize( Any surface ) = 0; + virtual void Initialize(Any surface) = 0; /** * @brief Create a renderable @@ -95,21 +90,19 @@ private: * @brief Use an existing render surface * @param surfaceId the id of the surface */ - virtual void UseExistingRenderable( unsigned int surfaceId ) = 0; + virtual void UseExistingRenderable(unsigned int surfaceId) = 0; protected: - // Undefined PixmapRenderSurface(const PixmapRenderSurface&) = delete; // Undefined PixmapRenderSurface& operator=(const PixmapRenderSurface& rhs) = delete; - }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/common/render-surface-factory.h b/dali/internal/window-system/common/render-surface-factory.h index a5d8d72..bade0da 100644 --- a/dali/internal/window-system/common/render-surface-factory.h +++ b/dali/internal/window-system/common/render-surface-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_RENDER_SURFACE_FACTORY_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,32 +27,29 @@ namespace Dali { - class NativeRenderSurface; namespace Internal { namespace Adaptor { - class WindowRenderSurface; class PixmapRenderSurface; class RenderSurfaceFactory { public: - - RenderSurfaceFactory() = default; + RenderSurfaceFactory() = default; virtual ~RenderSurfaceFactory() = default; - virtual std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) = 0; + virtual std::unique_ptr CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) = 0; - virtual std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) = 0; + virtual std::unique_ptr CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) = 0; - virtual std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent = false ) = 0; + virtual std::unique_ptr CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) = 0; }; -extern std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory(); +extern std::unique_ptr GetRenderSurfaceFactory(); } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/window-system/common/rotation-event.h b/dali/internal/window-system/common/rotation-event.h index 4972eff..3ad8de5 100644 --- a/dali/internal/window-system/common/rotation-event.h +++ b/dali/internal/window-system/common/rotation-event.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ROTATION_EVENT_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - struct RotationEvent { int angle; ///< one of 0, 90, 180, 270 diff --git a/dali/internal/window-system/common/window-base.cpp b/dali/internal/window-system/common/window-base.cpp index eb39d96..867b72a 100644 --- a/dali/internal/window-system/common/window-base.cpp +++ b/dali/internal/window-system/common/window-base.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - WindowBase::WindowBase() : mIconifyChangedSignal(), mFocusChangedSignal(), diff --git a/dali/internal/window-system/common/window-base.h b/dali/internal/window-system/common/window-base.h index f4081ea..62a70ed 100644 --- a/dali/internal/window-system/common/window-base.h +++ b/dali/internal/window-system/common/window-base.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_WINDOW_BASE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,19 +22,19 @@ #include #include #include +#include #include #include -#include // INTERNAL INCLUDES -#include -#include -#include -#include #include +#include #include #include -#include +#include +#include +#include +#include namespace Dali { @@ -42,14 +42,12 @@ namespace Internal { namespace Adaptor { - /** * WindowBase interface */ class WindowBase { public: - /** * @brief Struct used to retrieve accessibility information */ @@ -65,27 +63,27 @@ public: }; // Window - typedef Signal< void ( bool ) > IconifySignalType; - typedef Signal< void ( bool ) > FocusSignalType; - typedef Signal< void ( ) > OutputSignalType; - typedef Signal< void ( ) > DeleteSignalType; - typedef Signal< void ( const DamageArea& ) > DamageSignalType; - typedef Signal< void ( const RotationEvent& ) > RotationSignalType; - typedef Signal< void ( WindowEffectState, WindowEffectType ) > TransitionEffectEventSignalType; - typedef Signal< void ( ) > KeyboardRepeatSettingsChangedSignalType; - typedef Signal< void ( ) > WindowRedrawRequestSignalType; + typedef Signal IconifySignalType; + typedef Signal FocusSignalType; + typedef Signal OutputSignalType; + typedef Signal DeleteSignalType; + typedef Signal DamageSignalType; + typedef Signal RotationSignalType; + typedef Signal TransitionEffectEventSignalType; + typedef Signal KeyboardRepeatSettingsChangedSignalType; + typedef Signal WindowRedrawRequestSignalType; // Input events - typedef Signal< void ( Integration::Point&, uint32_t ) > TouchEventSignalType; - typedef Signal< void ( Integration::WheelEvent& ) > WheelEventSignalType; - typedef Signal< void( Integration::KeyEvent& ) > KeyEventSignalType; + typedef Signal TouchEventSignalType; + typedef Signal WheelEventSignalType; + typedef Signal KeyEventSignalType; // Clipboard - typedef Signal< void ( void* ) > SelectionSignalType; + typedef Signal SelectionSignalType; // Accessibility - typedef Signal< void ( StyleChange::Type ) > StyleSignalType; - typedef Signal< void ( const AccessibilityInfo& ) > AccessibilitySignalType; + typedef Signal StyleSignalType; + typedef Signal AccessibilitySignalType; /** * @brief Default constructor @@ -98,7 +96,6 @@ public: virtual ~WindowBase(); public: - /** * @brief Get the native window handle * @return The native window handle @@ -114,7 +111,7 @@ public: /** * @brief Create the egl window */ - virtual EGLNativeWindowType CreateEglWindow( int width, int height ) = 0; + virtual EGLNativeWindowType CreateEglWindow(int width, int height) = 0; /** * @brief Destroy the egl window @@ -124,22 +121,22 @@ public: /** * @brief Set the egl window rotation */ - virtual void SetEglWindowRotation( int angle ) = 0; + virtual void SetEglWindowRotation(int angle) = 0; /** * @brief Set the egl window buffer transform */ - virtual void SetEglWindowBufferTransform( int angle ) = 0; + virtual void SetEglWindowBufferTransform(int angle) = 0; /** * @brief Set the egl window transform */ - virtual void SetEglWindowTransform( int angle ) = 0; + virtual void SetEglWindowTransform(int angle) = 0; /** * @brief Resize the egl window */ - virtual void ResizeEglWindow( Dali::PositionSize positionSize ) = 0; + virtual void ResizeEglWindow(Dali::PositionSize positionSize) = 0; /** * @brief Returns whether the egl window support rotation or not @@ -149,22 +146,22 @@ public: /** * @brief Move the window */ - virtual void Move( Dali::PositionSize positionSize ) = 0; + virtual void Move(Dali::PositionSize positionSize) = 0; /** * @brief Resize the window */ - virtual void Resize( Dali::PositionSize positionSize ) = 0; + virtual void Resize(Dali::PositionSize positionSize) = 0; /** * @brief Move and resize the window */ - virtual void MoveResize( Dali::PositionSize positionSize ) = 0; + virtual void MoveResize(Dali::PositionSize positionSize) = 0; /** * @copydoc Dali::Window::SetClass() */ - virtual void SetClass( const std::string& name, const std::string& className ) = 0; + virtual void SetClass(const std::string& name, const std::string& className) = 0; /** * @copydoc Dali::Window::Raise() @@ -184,17 +181,17 @@ public: /** * @copydoc Dali::Window::SetAvailableOrientations() */ - virtual void SetAvailableAnlges( const std::vector< int >& angles ) = 0; + virtual void SetAvailableAnlges(const std::vector& angles) = 0; /** * @copydoc Dali::Window::SetPreferredOrientation() */ - virtual void SetPreferredAngle( int angle ) = 0; + virtual void SetPreferredAngle(int angle) = 0; /** * @copydoc Dali::Window::SetAcceptFocus() */ - virtual void SetAcceptFocus( bool accept ) = 0; + virtual void SetAcceptFocus(bool accept) = 0; /** * @copydoc Dali::Window::Show() @@ -214,47 +211,47 @@ public: /** * @copydoc Dali::Window::GetSupportedAuxiliaryHint() */ - virtual std::string GetSupportedAuxiliaryHint( unsigned int index ) const = 0; + virtual std::string GetSupportedAuxiliaryHint(unsigned int index) const = 0; /** * @copydoc Dali::Window::AddAuxiliaryHint() */ - virtual unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) = 0; + virtual unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) = 0; /** * @copydoc Dali::Window::RemoveAuxiliaryHint() */ - virtual bool RemoveAuxiliaryHint( unsigned int id ) = 0; + virtual bool RemoveAuxiliaryHint(unsigned int id) = 0; /** * @copydoc Dali::Window::SetAuxiliaryHintValue() */ - virtual bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) = 0; + virtual bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) = 0; /** * @copydoc Dali::Window::GetAuxiliaryHintValue() */ - virtual std::string GetAuxiliaryHintValue( unsigned int id ) const = 0; + virtual std::string GetAuxiliaryHintValue(unsigned int id) const = 0; /** * @copydoc Dali::Window::GetAuxiliaryHintId() */ - virtual unsigned int GetAuxiliaryHintId( const std::string& hint ) const = 0; + virtual unsigned int GetAuxiliaryHintId(const std::string& hint) const = 0; /** * @copydoc Dali::Window::SetInputRegion() */ - virtual void SetInputRegion( const Rect< int >& inputRegion ) = 0; + virtual void SetInputRegion(const Rect& inputRegion) = 0; /** * @copydoc Dali::Window::SetType() */ - virtual void SetType( Dali::WindowType type ) = 0; + virtual void SetType(Dali::WindowType type) = 0; /** * @copydoc Dali::Window::SetNotificationLevel() */ - virtual bool SetNotificationLevel( Dali::WindowNotificationLevel level ) = 0; + virtual bool SetNotificationLevel(Dali::WindowNotificationLevel level) = 0; /** * @copydoc Dali::Window::GetNotificationLevel() @@ -264,7 +261,7 @@ public: /** * @copydoc Dali::Window::SetOpaqueState() */ - virtual void SetOpaqueState( bool opaque ) = 0; + virtual void SetOpaqueState(bool opaque) = 0; /** * @copydoc Dali::Window::SetScreenOffMode() @@ -279,7 +276,7 @@ public: /** * @copydoc Dali::Window::SetBrightness() */ - virtual bool SetBrightness( int brightness ) = 0; + virtual bool SetBrightness(int brightness) = 0; /** * @copydoc Dali::Window::GetBrightness() @@ -289,29 +286,29 @@ public: /** * @copydoc Dali::KeyGrab::GrabKey() */ - virtual bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) = 0; + virtual bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) = 0; /** * @copydoc Dali::KeyGrab::UngrabKey() */ - virtual bool UngrabKey( Dali::KEY key ) = 0; + virtual bool UngrabKey(Dali::KEY key) = 0; /** * @copydoc Dali::KeyGrab::GrabKeyList() */ - virtual bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) = 0; + virtual bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) = 0; /** * @copydoc Dali::KeyGrab::UngrabKeyList() */ - virtual bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) = 0; + virtual bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) = 0; /** * @brief Get DPI * @param[out] dpiHorizontal set to the horizontal dpi * @param[out] dpiVertical set to the vertical dpi */ - virtual void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) = 0; + virtual void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) = 0; /** * @brief Return the orientation of the surface. @@ -327,22 +324,22 @@ public: /** * @brief Set the rotation angle of the window */ - virtual void SetWindowRotationAngle( int degree ) = 0; + virtual void SetWindowRotationAngle(int degree) = 0; /** * @brief Inform the window rotation is completed */ - virtual void WindowRotationCompleted( int degree, int width, int height ) = 0; + virtual void WindowRotationCompleted(int degree, int width, int height) = 0; /** * @copydoc Dali::Window::SetTransparency() */ - virtual void SetTransparency( bool transparent ) = 0; + virtual void SetTransparency(bool transparent) = 0; /** * @copydoc Dali::Window::SetParent() */ - virtual void SetParent( WindowBase* parentWinBase ) = 0; + virtual void SetParent(WindowBase* parentWinBase) = 0; /** * @brief Create a sync fence that can tell the frame is rendered by the graphics driver. @@ -361,7 +358,7 @@ public: /** * @brief This signal is emitted when the window becomes iconified or deiconified. */ - IconifySignalType& IconifyChangedSignal(); + IconifySignalType& IconifyChangedSignal(); /** * @brief This signal is emitted when the window focus is changed. @@ -439,7 +436,6 @@ public: WindowRedrawRequestSignalType& WindowRedrawRequestSignal(); protected: - // Undefined WindowBase(const WindowBase&) = delete; @@ -447,7 +443,6 @@ protected: WindowBase& operator=(const WindowBase& rhs) = delete; protected: - IconifySignalType mIconifyChangedSignal; FocusSignalType mFocusChangedSignal; OutputSignalType mOutputTransformedSignal; @@ -468,7 +463,7 @@ protected: } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/common/window-event-interface.h b/dali/internal/window-system/common/window-event-interface.h index c9d9c8b..872832a 100644 --- a/dali/internal/window-system/common/window-event-interface.h +++ b/dali/internal/window-system/common/window-event-interface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_BASE_WINDOW_EVENT_INTERFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,53 +19,48 @@ */ // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - /** * @brief Abstract interface for handling DALi events received from the native window system * */ class WindowEventInterface { - public: - /** * @brief Touch Event callback * @param[in] point touch point * @param[in] timeStamp time stamp */ - virtual void TouchEvent( Dali::Integration::Point& point, unsigned long timeStamp ) = 0; + virtual void TouchEvent(Dali::Integration::Point& point, unsigned long timeStamp) = 0; /** * @brief Key Event callback * @param[in] keyEvent key event */ - virtual void KeyEvent( Dali::Integration::KeyEvent& keyEvent ) = 0; + virtual void KeyEvent(Dali::Integration::KeyEvent& keyEvent) = 0; /** * @brief Wheel Event callback * @param[in] wheelEvent wheel event */ - virtual void WheelEvent( Dali::WheelEvent& wheelEvent ) = 0; + virtual void WheelEvent(Dali::WheelEvent& wheelEvent) = 0; /** * @brief Window damage callback * @param[in] damageArea Window damage area */ - virtual void DamageEvent( Dali::Rect& damageArea ) = 0; + virtual void DamageEvent(Dali::Rect& damageArea) = 0; /** * @brief Window Focused @@ -78,7 +73,6 @@ public: virtual void WindowFocusOut() = 0; protected: - /** * @brief Constructor */ @@ -94,11 +88,10 @@ protected: } // Undefined copy constructor. - WindowEventInterface( const WindowEventInterface& ); + WindowEventInterface(const WindowEventInterface&); // Undefined assignment operator. - WindowEventInterface& operator=( const WindowEventInterface& ); - + WindowEventInterface& operator=(const WindowEventInterface&); }; } // namespace Adaptor diff --git a/dali/internal/window-system/common/window-factory.h b/dali/internal/window-system/common/window-factory.h index 741e744..023dd39 100644 --- a/dali/internal/window-system/common/window-factory.h +++ b/dali/internal/window-system/common/window-factory.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_WINDOW_FACTORY_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,21 +30,19 @@ namespace Internal { namespace Adaptor { - class Adaptor; class WindowBase; class WindowFactory { public: - - WindowFactory() = default; + WindowFactory() = default; virtual ~WindowFactory() = default; - virtual std::unique_ptr< WindowBase > CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) = 0; + virtual std::unique_ptr CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) = 0; }; -extern std::unique_ptr< WindowFactory > GetWindowFactory(); +extern std::unique_ptr GetWindowFactory(); } // namespace Adaptor } // namespace Internal diff --git a/dali/internal/window-system/common/window-impl.cpp b/dali/internal/window-system/common/window-impl.cpp old mode 100755 new mode 100644 index 2c63958..f3a74fe --- a/dali/internal/window-system/common/window-impl.cpp +++ b/dali/internal/window-system/common/window-impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,30 +19,30 @@ #include // EXTERNAL HEADERS -#include +#include #include +#include #include -#include #include -#include +#include +#include #include +#include #include -#include -#include -#include +#include // INTERNAL HEADERS +#include #include #include #include #include #include -#include #include -#include +#include #include +#include #include -#include namespace Dali { @@ -50,12 +50,10 @@ namespace Internal { namespace Adaptor { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gWindowLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_WINDOW" ); +Debug::Filter* gWindowLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW"); #endif } // unnamed namespace @@ -68,7 +66,7 @@ Window* Window::New(const PositionSize& positionSize, const std::string& name, c Window* Window::New(Any surface, const PositionSize& positionSize, const std::string& name, const std::string& className, bool isTransparent) { - Window* window = new Window(); + Window* window = new Window(); window->mIsTransparent = isTransparent; window->Initialize(surface, positionSize, name, className); return window; @@ -77,19 +75,19 @@ Window* Window::New(Any surface, const PositionSize& positionSize, const std::st Window::Window() : mWindowSurface(nullptr), mWindowBase(), - mIsTransparent( false ), - mIsFocusAcceptable( true ), - mIconified( false ), - mOpaqueState( false ), - mResizeEnabled( false ), - mType( WindowType::NORMAL ), - mParentWindow( NULL ), - mPreferredAngle( static_cast< int >( WindowOrientation::NO_ORIENTATION_PREFERENCE ) ), - mRotationAngle( 0 ), - mWindowWidth( 0 ), - mWindowHeight( 0 ), - mOrientationMode( Internal::Adaptor::Window::OrientationMode::PORTRAIT ), - mNativeWindowId( -1 ), + mIsTransparent(false), + mIsFocusAcceptable(true), + mIconified(false), + mOpaqueState(false), + mResizeEnabled(false), + mType(WindowType::NORMAL), + mParentWindow(NULL), + mPreferredAngle(static_cast(WindowOrientation::NO_ORIENTATION_PREFERENCE)), + mRotationAngle(0), + mWindowWidth(0), + mWindowHeight(0), + mOrientationMode(Internal::Adaptor::Window::OrientationMode::PORTRAIT), + mNativeWindowId(-1), mDeleteRequestSignal(), mFocusChangeSignal(), mResizeSignal(), @@ -101,19 +99,19 @@ Window::Window() Window::~Window() { - if ( mAdaptor ) + if(mAdaptor) { - auto bridge = Accessibility::Bridge::GetCurrentBridge(); + auto bridge = Accessibility::Bridge::GetCurrentBridge(); auto accessible2 = mScene.GetRootLayer(); - auto accessible = Accessibility::Accessible::Get( accessible2 ); - bridge->RemoveTopLevelWindow( accessible ); + auto accessible = Accessibility::Accessible::Get(accessible2); + bridge->RemoveTopLevelWindow(accessible); - mAdaptor->RemoveWindow( this ); + mAdaptor->RemoveWindow(this); } - if ( mEventHandler ) + if(mEventHandler) { - mEventHandler->RemoveObserver( *this ); + mEventHandler->RemoveObserver(*this); } } @@ -121,38 +119,38 @@ void Window::Initialize(Any surface, const PositionSize& positionSize, const std { // Create a window render surface auto renderSurfaceFactory = Dali::Internal::Adaptor::GetRenderSurfaceFactory(); - mSurface = renderSurfaceFactory->CreateWindowRenderSurface( positionSize, surface, mIsTransparent ); - mWindowSurface = static_cast( mSurface.get() ); + mSurface = renderSurfaceFactory->CreateWindowRenderSurface(positionSize, surface, mIsTransparent); + mWindowSurface = static_cast(mSurface.get()); // Get a window base mWindowBase = mWindowSurface->GetWindowBase(); // Connect signals - mWindowBase->IconifyChangedSignal().Connect( this, &Window::OnIconifyChanged ); - mWindowBase->FocusChangedSignal().Connect( this, &Window::OnFocusChanged ); - mWindowBase->DeleteRequestSignal().Connect( this, &Window::OnDeleteRequest ); - mWindowBase->TransitionEffectEventSignal().Connect( this, &Window::OnTransitionEffectEvent ); - mWindowBase->KeyboardRepeatSettingsChangedSignal().Connect( this, &Window::OnKeyboardRepeatSettingsChanged ); - mWindowBase->WindowRedrawRequestSignal().Connect( this, &Window::OnWindowRedrawRequest ); + mWindowBase->IconifyChangedSignal().Connect(this, &Window::OnIconifyChanged); + mWindowBase->FocusChangedSignal().Connect(this, &Window::OnFocusChanged); + mWindowBase->DeleteRequestSignal().Connect(this, &Window::OnDeleteRequest); + mWindowBase->TransitionEffectEventSignal().Connect(this, &Window::OnTransitionEffectEvent); + mWindowBase->KeyboardRepeatSettingsChangedSignal().Connect(this, &Window::OnKeyboardRepeatSettingsChanged); + mWindowBase->WindowRedrawRequestSignal().Connect(this, &Window::OnWindowRedrawRequest); - mWindowSurface->OutputTransformedSignal().Connect( this, &Window::OnOutputTransformed ); + mWindowSurface->OutputTransformedSignal().Connect(this, &Window::OnOutputTransformed); - if( !positionSize.IsEmpty() ) + if(!positionSize.IsEmpty()) { - AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" ); + AddAuxiliaryHint("wm.policy.win.user.geometry", "1"); mResizeEnabled = true; } - SetClass( name, className ); + SetClass(name, className); mWindowSurface->Map(); - mOrientation = Orientation::New( this ); + mOrientation = Orientation::New(this); // Get OrientationMode int screenWidth, screenHeight; - WindowSystem::GetScreenSize( screenWidth, screenHeight ); - if( screenWidth > screenHeight ) + WindowSystem::GetScreenSize(screenWidth, screenHeight); + if(screenWidth > screenHeight) { mOrientationMode = Internal::Adaptor::Window::OrientationMode::LANDSCAPE; } @@ -166,28 +164,28 @@ void Window::Initialize(Any surface, const PositionSize& positionSize, const std void Window::OnAdaptorSet(Dali::Adaptor& adaptor) { - mEventHandler = EventHandlerPtr(new EventHandler( mWindowSurface->GetWindowBase(), *mAdaptor ) ); - mEventHandler->AddObserver( *this ); + mEventHandler = EventHandlerPtr(new EventHandler(mWindowSurface->GetWindowBase(), *mAdaptor)); + mEventHandler->AddObserver(*this); - auto bridge = Accessibility::Bridge::GetCurrentBridge(); - auto v = mScene.GetRootLayer(); - auto accessible = Accessibility::Accessible::Get( v, true ); - bridge->AddTopLevelWindow( accessible ); + auto bridge = Accessibility::Bridge::GetCurrentBridge(); + auto v = mScene.GetRootLayer(); + auto accessible = Accessibility::Accessible::Get(v, true); + bridge->AddTopLevelWindow(accessible); //FIXME: line below is temporary solution for missing "activate" signal and should be removed Show(); } -void Window::OnSurfaceSet( Dali::RenderSurfaceInterface* surface ) +void Window::OnSurfaceSet(Dali::RenderSurfaceInterface* surface) { - mWindowSurface = static_cast( surface ); + mWindowSurface = static_cast(surface); } -void Window::SetClass( std::string name, std::string className ) +void Window::SetClass(std::string name, std::string className) { - mName = name; + mName = name; mClassName = className; - mWindowBase->SetClass( name, className ); + mWindowBase->SetClass(name, className); } std::string Window::GetClassName() const @@ -201,7 +199,7 @@ void Window::Raise() mSurface->SetFullSwapNextFrame(); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Raise() \n", this, mNativeWindowId ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Raise() \n", this, mNativeWindowId); } void Window::Lower() @@ -210,7 +208,7 @@ void Window::Lower() mSurface->SetFullSwapNextFrame(); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Lower() \n", this, mNativeWindowId ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Lower() \n", this, mNativeWindowId); } void Window::Activate() @@ -219,7 +217,7 @@ void Window::Activate() mSurface->SetFullSwapNextFrame(); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Activate() \n", this, mNativeWindowId ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Activate() \n", this, mNativeWindowId); } uint32_t Window::GetLayerCount() const @@ -227,9 +225,9 @@ uint32_t Window::GetLayerCount() const return mScene.GetLayerCount(); } -Dali::Layer Window::GetLayer( uint32_t depth ) const +Dali::Layer Window::GetLayer(uint32_t depth) const { - return mScene.GetLayer( depth ); + return mScene.GetLayer(depth); } Dali::RenderTaskList Window::GetRenderTaskList() const @@ -237,90 +235,91 @@ Dali::RenderTaskList Window::GetRenderTaskList() const return mScene.GetRenderTaskList(); } -void Window::AddAvailableOrientation( WindowOrientation orientation ) +void Window::AddAvailableOrientation(WindowOrientation orientation) { - if( IsOrientationAvailable( orientation ) == false ) + if(IsOrientationAvailable(orientation) == false) { return; } - bool found = false; - int convertedAngle = ConvertToAngle( orientation ); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), AddAvailableOrientation: %d\n", this, mNativeWindowId, convertedAngle ); - for( std::size_t i = 0; i < mAvailableAngles.size(); i++ ) + bool found = false; + int convertedAngle = ConvertToAngle(orientation); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), AddAvailableOrientation: %d\n", this, mNativeWindowId, convertedAngle); + for(std::size_t i = 0; i < mAvailableAngles.size(); i++) { - if( mAvailableAngles[i] == convertedAngle ) + if(mAvailableAngles[i] == convertedAngle) { found = true; break; } } - if( !found ) + if(!found) { - mAvailableAngles.push_back( convertedAngle ); - SetAvailableAnlges( mAvailableAngles ); + mAvailableAngles.push_back(convertedAngle); + SetAvailableAnlges(mAvailableAngles); } } -void Window::RemoveAvailableOrientation( WindowOrientation orientation ) +void Window::RemoveAvailableOrientation(WindowOrientation orientation) { - if( IsOrientationAvailable( orientation ) == false ) + if(IsOrientationAvailable(orientation) == false) { return; } - int convertedAngle = ConvertToAngle( orientation ); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), RemoveAvailableOrientation: %d\n", this, mNativeWindowId, convertedAngle ); - for( std::vector< int >::iterator iter = mAvailableAngles.begin(); - iter != mAvailableAngles.end(); ++iter ) + int convertedAngle = ConvertToAngle(orientation); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), RemoveAvailableOrientation: %d\n", this, mNativeWindowId, convertedAngle); + for(std::vector::iterator iter = mAvailableAngles.begin(); + iter != mAvailableAngles.end(); + ++iter) { - if( *iter == convertedAngle ) + if(*iter == convertedAngle) { - mAvailableAngles.erase( iter ); + mAvailableAngles.erase(iter); break; } } - SetAvailableAnlges( mAvailableAngles ); + SetAvailableAnlges(mAvailableAngles); } -void Window::SetPreferredOrientation( WindowOrientation orientation ) +void Window::SetPreferredOrientation(WindowOrientation orientation) { - if( orientation < WindowOrientation::NO_ORIENTATION_PREFERENCE || orientation > WindowOrientation::LANDSCAPE_INVERSE ) + if(orientation < WindowOrientation::NO_ORIENTATION_PREFERENCE || orientation > WindowOrientation::LANDSCAPE_INVERSE) { - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::CheckOrientation: Invalid input orientation [%d]\n", orientation ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::CheckOrientation: Invalid input orientation [%d]\n", orientation); return; } - mPreferredAngle = ConvertToAngle( orientation ); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), SetPreferredOrientation: %d\n", this, mNativeWindowId, mPreferredAngle ); - mWindowBase->SetPreferredAngle( mPreferredAngle ); + mPreferredAngle = ConvertToAngle(orientation); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), SetPreferredOrientation: %d\n", this, mNativeWindowId, mPreferredAngle); + mWindowBase->SetPreferredAngle(mPreferredAngle); } WindowOrientation Window::GetPreferredOrientation() { - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), GetPreferredOrientation: %d\n", this, mNativeWindowId, mPreferredAngle ); - WindowOrientation preferredOrientation = ConvertToOrientation( mPreferredAngle ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), GetPreferredOrientation: %d\n", this, mNativeWindowId, mPreferredAngle); + WindowOrientation preferredOrientation = ConvertToOrientation(mPreferredAngle); return preferredOrientation; } -void Window::SetAvailableAnlges( const std::vector< int >& angles ) +void Window::SetAvailableAnlges(const std::vector& angles) { - if( angles.size() > 4 ) + if(angles.size() > 4) { - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetAvailableAnlges: Invalid vector size! [%d]\n", angles.size() ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::SetAvailableAnlges: Invalid vector size! [%d]\n", angles.size()); return; } - mWindowBase->SetAvailableAnlges( angles ); + mWindowBase->SetAvailableAnlges(angles); } -int Window::ConvertToAngle( WindowOrientation orientation ) +int Window::ConvertToAngle(WindowOrientation orientation) { - int convertAngle = static_cast< int >( orientation ); - if( mOrientationMode == Internal::Adaptor::Window::OrientationMode::LANDSCAPE ) + int convertAngle = static_cast(orientation); + if(mOrientationMode == Internal::Adaptor::Window::OrientationMode::LANDSCAPE) { - switch( orientation ) + switch(orientation) { case WindowOrientation::LANDSCAPE: { @@ -352,12 +351,12 @@ int Window::ConvertToAngle( WindowOrientation orientation ) return convertAngle; } -WindowOrientation Window::ConvertToOrientation( int angle ) const +WindowOrientation Window::ConvertToOrientation(int angle) const { - WindowOrientation orientation = static_cast< WindowOrientation >( angle ); - if( mOrientationMode == Internal::Adaptor::Window::OrientationMode::LANDSCAPE ) + WindowOrientation orientation = static_cast(angle); + if(mOrientationMode == Internal::Adaptor::Window::OrientationMode::LANDSCAPE) { - switch( angle ) + switch(angle) { case 0: { @@ -389,11 +388,11 @@ WindowOrientation Window::ConvertToOrientation( int angle ) const return orientation; } -bool Window::IsOrientationAvailable( WindowOrientation orientation ) const +bool Window::IsOrientationAvailable(WindowOrientation orientation) const { - if( orientation <= WindowOrientation::NO_ORIENTATION_PREFERENCE || orientation > WindowOrientation::LANDSCAPE_INVERSE ) + if(orientation <= WindowOrientation::NO_ORIENTATION_PREFERENCE || orientation > WindowOrientation::LANDSCAPE_INVERSE) { - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::IsOrientationAvailable: Invalid input orientation [%d]\n", orientation ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::IsOrientationAvailable: Invalid input orientation [%d]\n", orientation); return false; } return true; @@ -404,11 +403,11 @@ Dali::Any Window::GetNativeHandle() const return mWindowSurface->GetNativeWindow(); } -void Window::SetAcceptFocus( bool accept ) +void Window::SetAcceptFocus(bool accept) { mIsFocusAcceptable = accept; - mWindowBase->SetAcceptFocus( accept ); + mWindowBase->SetAcceptFocus(accept); } bool Window::IsFocusAcceptable() const @@ -422,18 +421,18 @@ void Window::Show() mWindowBase->Show(); - if( !mIconified ) + if(!mIconified) { - WindowVisibilityObserver* observer( mAdaptor ); + WindowVisibilityObserver* observer(mAdaptor); observer->OnWindowShown(); - Dali::Window handle( this ); - mVisibilityChangedSignal.Emit( handle, true ); + Dali::Window handle(this); + mVisibilityChangedSignal.Emit(handle, true); } mSurface->SetFullSwapNextFrame(); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Show(): iconified = %d, visible = %d\n", this, mNativeWindowId, mIconified, mVisible ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Show(): iconified = %d, visible = %d\n", this, mNativeWindowId, mIconified, mVisible); } void Window::Hide() @@ -442,21 +441,21 @@ void Window::Hide() mWindowBase->Hide(); - if( !mIconified ) + if(!mIconified) { - WindowVisibilityObserver* observer( mAdaptor ); + WindowVisibilityObserver* observer(mAdaptor); observer->OnWindowHidden(); - Dali::Window handle( this ); - mVisibilityChangedSignal.Emit( handle, false ); + Dali::Window handle(this); + mVisibilityChangedSignal.Emit(handle, false); } - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Hide(): iconified = %d, visible = %d\n", this, mNativeWindowId, mIconified, mVisible ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Hide(): iconified = %d, visible = %d\n", this, mNativeWindowId, mIconified, mVisible); } bool Window::IsVisible() const { - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), IsVisible(): iconified = %d, visible = %d\n", this, mNativeWindowId, mIconified, mVisible ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), IsVisible(): iconified = %d, visible = %d\n", this, mNativeWindowId, mIconified, mVisible); return mVisible && !mIconified; } @@ -465,48 +464,48 @@ unsigned int Window::GetSupportedAuxiliaryHintCount() const return mWindowBase->GetSupportedAuxiliaryHintCount(); } -std::string Window::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string Window::GetSupportedAuxiliaryHint(unsigned int index) const { - return mWindowBase->GetSupportedAuxiliaryHint( index ); + return mWindowBase->GetSupportedAuxiliaryHint(index); } -unsigned int Window::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int Window::AddAuxiliaryHint(const std::string& hint, const std::string& value) { - return mWindowBase->AddAuxiliaryHint( hint, value ); + return mWindowBase->AddAuxiliaryHint(hint, value); } -bool Window::RemoveAuxiliaryHint( unsigned int id ) +bool Window::RemoveAuxiliaryHint(unsigned int id) { - return mWindowBase->RemoveAuxiliaryHint( id ); + return mWindowBase->RemoveAuxiliaryHint(id); } -bool Window::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool Window::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { - return mWindowBase->SetAuxiliaryHintValue( id, value ); + return mWindowBase->SetAuxiliaryHintValue(id, value); } -std::string Window::GetAuxiliaryHintValue( unsigned int id ) const +std::string Window::GetAuxiliaryHintValue(unsigned int id) const { - return mWindowBase->GetAuxiliaryHintValue( id ); + return mWindowBase->GetAuxiliaryHintValue(id); } -unsigned int Window::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int Window::GetAuxiliaryHintId(const std::string& hint) const { - return mWindowBase->GetAuxiliaryHintId( hint ); + return mWindowBase->GetAuxiliaryHintId(hint); } -void Window::SetInputRegion( const Rect< int >& inputRegion ) +void Window::SetInputRegion(const Rect& inputRegion) { - mWindowBase->SetInputRegion( inputRegion ); + mWindowBase->SetInputRegion(inputRegion); - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetInputRegion: x = %d, y = %d, w = %d, h = %d\n", inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::SetInputRegion: x = %d, y = %d, w = %d, h = %d\n", inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height); } -void Window::SetType( WindowType type ) +void Window::SetType(WindowType type) { - if( type != mType ) + if(type != mType) { - mWindowBase->SetType( type ); + mWindowBase->SetType(type); mType = type; } @@ -517,35 +516,35 @@ WindowType Window::GetType() const return mType; } -bool Window::SetNotificationLevel( WindowNotificationLevel level ) +bool Window::SetNotificationLevel(WindowNotificationLevel level) { - if( mType != WindowType::NOTIFICATION ) + if(mType != WindowType::NOTIFICATION) { - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Not supported window type [%d]\n", mType ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::SetNotificationLevel: Not supported window type [%d]\n", mType); return false; } - return mWindowBase->SetNotificationLevel( level ); + return mWindowBase->SetNotificationLevel(level); } WindowNotificationLevel Window::GetNotificationLevel() const { - if( mType != WindowType::NOTIFICATION ) + if(mType != WindowType::NOTIFICATION) { - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: Not supported window type [%d]\n", mType ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::GetNotificationLevel: Not supported window type [%d]\n", mType); return WindowNotificationLevel::NONE; } return mWindowBase->GetNotificationLevel(); } -void Window::SetOpaqueState( bool opaque ) +void Window::SetOpaqueState(bool opaque) { mOpaqueState = opaque; - mWindowBase->SetOpaqueState( opaque ); + mWindowBase->SetOpaqueState(opaque); - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetOpaqueState: opaque = %d\n", opaque ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::SetOpaqueState: opaque = %d\n", opaque); } bool Window::IsOpaqueState() const @@ -555,7 +554,7 @@ bool Window::IsOpaqueState() const bool Window::SetScreenOffMode(WindowScreenOffMode screenOffMode) { - return mWindowBase->SetScreenOffMode( screenOffMode ); + return mWindowBase->SetScreenOffMode(screenOffMode); } WindowScreenOffMode Window::GetScreenOffMode() const @@ -563,15 +562,15 @@ WindowScreenOffMode Window::GetScreenOffMode() const return mWindowBase->GetScreenOffMode(); } -bool Window::SetBrightness( int brightness ) +bool Window::SetBrightness(int brightness) { - if( brightness < 0 || brightness > 100 ) + if(brightness < 0 || brightness > 100) { - DALI_LOG_INFO( gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Invalid brightness value [%d]\n", brightness ); + DALI_LOG_INFO(gWindowLogFilter, Debug::Verbose, "Window::SetBrightness: Invalid brightness value [%d]\n", brightness); return false; } - return mWindowBase->SetBrightness( brightness ); + return mWindowBase->SetBrightness(brightness); } int Window::GetBrightness() const @@ -579,35 +578,35 @@ int Window::GetBrightness() const return mWindowBase->GetBrightness(); } -void Window::SetSize( Dali::Window::WindowSize size ) +void Window::SetSize(Dali::Window::WindowSize size) { - if( !mResizeEnabled ) + if(!mResizeEnabled) { - AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" ); + AddAuxiliaryHint("wm.policy.win.user.geometry", "1"); mResizeEnabled = true; } PositionSize oldRect = mSurface->GetPositionSize(); - mWindowSurface->MoveResize( PositionSize( oldRect.x, oldRect.y, size.GetWidth(), size.GetHeight() ) ); + mWindowSurface->MoveResize(PositionSize(oldRect.x, oldRect.y, size.GetWidth(), size.GetHeight())); PositionSize newRect = mSurface->GetPositionSize(); // When surface size is updated, inform adaptor of resizing and emit ResizeSignal - if( ( oldRect.width != newRect.width ) || ( oldRect.height != newRect.height ) ) + if((oldRect.width != newRect.width) || (oldRect.height != newRect.height)) { - Uint16Pair newSize( newRect.width, newRect.height ); + Uint16Pair newSize(newRect.width, newRect.height); SurfaceResized(); - mAdaptor->SurfaceResizePrepare( mSurface.get(), newSize ); + mAdaptor->SurfaceResizePrepare(mSurface.get(), newSize); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), SetSize(): resize signal [%d x %d]\n", this, mNativeWindowId, newRect.width, newRect.height ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), SetSize(): resize signal [%d x %d]\n", this, mNativeWindowId, newRect.width, newRect.height); - Dali::Window handle( this ); - mResizeSignal.Emit( handle, newSize ); + Dali::Window handle(this); + mResizeSignal.Emit(handle, newSize); - mAdaptor->SurfaceResizeComplete( mSurface.get(), newSize ); + mAdaptor->SurfaceResizeComplete(mSurface.get(), newSize); } mSurface->SetFullSwapNextFrame(); @@ -617,20 +616,20 @@ Dali::Window::WindowSize Window::GetSize() const { PositionSize positionSize = mSurface->GetPositionSize(); - return Dali::Window::WindowSize( positionSize.width, positionSize.height ); + return Dali::Window::WindowSize(positionSize.width, positionSize.height); } -void Window::SetPosition( Dali::Window::WindowPosition position ) +void Window::SetPosition(Dali::Window::WindowPosition position) { - if( !mResizeEnabled ) + if(!mResizeEnabled) { - AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" ); + AddAuxiliaryHint("wm.policy.win.user.geometry", "1"); mResizeEnabled = true; } PositionSize oldRect = mSurface->GetPositionSize(); - mWindowSurface->MoveResize( PositionSize( position.GetX(), position.GetY(), oldRect.width, oldRect.height ) ); + mWindowSurface->MoveResize(PositionSize(position.GetX(), position.GetY(), oldRect.width, oldRect.height)); mSurface->SetFullSwapNextFrame(); } @@ -639,36 +638,36 @@ Dali::Window::WindowPosition Window::GetPosition() const { PositionSize positionSize = mSurface->GetPositionSize(); - return Dali::Window::WindowPosition( positionSize.x, positionSize.y ); + return Dali::Window::WindowPosition(positionSize.x, positionSize.y); } -void Window::SetPositionSize( PositionSize positionSize ) +void Window::SetPositionSize(PositionSize positionSize) { - if( !mResizeEnabled ) + if(!mResizeEnabled) { - AddAuxiliaryHint( "wm.policy.win.user.geometry", "1" ); + AddAuxiliaryHint("wm.policy.win.user.geometry", "1"); mResizeEnabled = true; } PositionSize oldRect = mSurface->GetPositionSize(); - mWindowSurface->MoveResize( positionSize ); + mWindowSurface->MoveResize(positionSize); PositionSize newRect = mSurface->GetPositionSize(); // When surface size is updated, inform adaptor of resizing and emit ResizeSignal - if( ( oldRect.width != newRect.width ) || ( oldRect.height != newRect.height ) ) + if((oldRect.width != newRect.width) || (oldRect.height != newRect.height)) { - Uint16Pair newSize( newRect.width, newRect.height ); + Uint16Pair newSize(newRect.width, newRect.height); SurfaceResized(); - mAdaptor->SurfaceResizePrepare( mSurface.get(), newSize ); + mAdaptor->SurfaceResizePrepare(mSurface.get(), newSize); - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), SetPositionSize():resize signal [%d x %d]\n", this, mNativeWindowId, newRect.width, newRect.height ); - Dali::Window handle( this ); - mResizeSignal.Emit( handle, newSize ); - mAdaptor->SurfaceResizeComplete( mSurface.get(), newSize ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), SetPositionSize():resize signal [%d x %d]\n", this, mNativeWindowId, newRect.width, newRect.height); + Dali::Window handle(this); + mResizeSignal.Emit(handle, newSize); + mAdaptor->SurfaceResizeComplete(mSurface.get(), newSize); } mSurface->SetFullSwapNextFrame(); @@ -679,77 +678,77 @@ Dali::Layer Window::GetRootLayer() const return mScene.GetRootLayer(); } -void Window::SetTransparency( bool transparent ) +void Window::SetTransparency(bool transparent) { - mWindowSurface->SetTransparency( transparent ); + mWindowSurface->SetTransparency(transparent); } -bool Window::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) +bool Window::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) { - return mWindowBase->GrabKey( key, grabMode ); + return mWindowBase->GrabKey(key, grabMode); } -bool Window::UngrabKey( Dali::KEY key ) +bool Window::UngrabKey(Dali::KEY key) { - return mWindowBase->UngrabKey( key ); + return mWindowBase->UngrabKey(key); } -bool Window::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) +bool Window::GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) { - return mWindowBase->GrabKeyList( key, grabMode, result ); + return mWindowBase->GrabKeyList(key, grabMode, result); } -bool Window::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) +bool Window::UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) { - return mWindowBase->UngrabKeyList( key, result ); + return mWindowBase->UngrabKeyList(key, result); } -void Window::OnIconifyChanged( bool iconified ) +void Window::OnIconifyChanged(bool iconified) { - if( iconified ) + if(iconified) { mIconified = true; - if( mVisible ) + if(mVisible) { - WindowVisibilityObserver* observer( mAdaptor ); + WindowVisibilityObserver* observer(mAdaptor); observer->OnWindowHidden(); - Dali::Window handle( this ); - mVisibilityChangedSignal.Emit( handle, false ); + Dali::Window handle(this); + mVisibilityChangedSignal.Emit(handle, false); } - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Iconified: visible = %d\n", this, mNativeWindowId, mVisible ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Iconified: visible = %d\n", this, mNativeWindowId, mVisible); } else { mIconified = false; - if( mVisible ) + if(mVisible) { - WindowVisibilityObserver* observer( mAdaptor ); + WindowVisibilityObserver* observer(mAdaptor); observer->OnWindowShown(); - Dali::Window handle( this ); - mVisibilityChangedSignal.Emit( handle, true ); + Dali::Window handle(this); + mVisibilityChangedSignal.Emit(handle, true); } - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), Deiconified: visible = %d\n", this, mNativeWindowId, mVisible ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), Deiconified: visible = %d\n", this, mNativeWindowId, mVisible); } mSurface->SetFullSwapNextFrame(); } -void Window::OnFocusChanged( bool focusIn ) +void Window::OnFocusChanged(bool focusIn) { - Dali::Window handle( this ); - mFocusChangeSignal.Emit( handle, focusIn ); + Dali::Window handle(this); + mFocusChangeSignal.Emit(handle, focusIn); mSurface->SetFullSwapNextFrame(); - if (auto b = Dali::Accessibility::Bridge::GetCurrentBridge()) + if(auto b = Dali::Accessibility::Bridge::GetCurrentBridge()) { - if (focusIn) + if(focusIn) { b->ApplicationShown(); } @@ -776,15 +775,15 @@ void Window::OnDeleteRequest() mDeleteRequestSignal.Emit(); } -void Window::OnTransitionEffectEvent( WindowEffectState state, WindowEffectType type ) +void Window::OnTransitionEffectEvent(WindowEffectState state, WindowEffectType type) { - Dali::Window handle( this ); - mTransitionEffectEventSignal.Emit( handle, state, type ); + Dali::Window handle(this); + mTransitionEffectEventSignal.Emit(handle, state, type); } void Window::OnKeyboardRepeatSettingsChanged() { - Dali::Window handle( this ); + Dali::Window handle(this); mKeyboardRepeatSettingsChangedSignal.Emit(); } @@ -793,19 +792,19 @@ void Window::OnWindowRedrawRequest() mAdaptor->RenderOnce(); } -void Window::OnTouchPoint( Dali::Integration::Point& point, int timeStamp ) +void Window::OnTouchPoint(Dali::Integration::Point& point, int timeStamp) { - FeedTouchPoint( point, timeStamp ); + FeedTouchPoint(point, timeStamp); } -void Window::OnWheelEvent( Dali::Integration::WheelEvent& wheelEvent ) +void Window::OnWheelEvent(Dali::Integration::WheelEvent& wheelEvent) { - FeedWheelEvent( wheelEvent ); + FeedWheelEvent(wheelEvent); } -void Window::OnKeyEvent( Dali::Integration::KeyEvent& keyEvent ) +void Window::OnKeyEvent(Dali::Integration::KeyEvent& keyEvent) { - FeedKeyEvent( keyEvent ); + FeedKeyEvent(keyEvent); } void Window::OnRotation(const RotationEvent& rotation) @@ -834,7 +833,7 @@ void Window::OnRotation(const RotationEvent& rotation) void Window::OnPause() { - if( mEventHandler ) + if(mEventHandler) { mEventHandler->Pause(); } @@ -842,7 +841,7 @@ void Window::OnPause() void Window::OnResume() { - if( mEventHandler ) + if(mEventHandler) { mEventHandler->Resume(); } @@ -850,29 +849,29 @@ void Window::OnResume() mSurface->SetFullSwapNextFrame(); } -void Window::RecalculateTouchPosition( Integration::Point& point ) +void Window::RecalculateTouchPosition(Integration::Point& point) { Vector2 position = point.GetScreenPosition(); Vector2 convertedPosition; - switch( mRotationAngle ) + switch(mRotationAngle) { case 90: { - convertedPosition.x = static_cast( mWindowWidth ) - position.y; + convertedPosition.x = static_cast(mWindowWidth) - position.y; convertedPosition.y = position.x; break; } case 180: { - convertedPosition.x = static_cast( mWindowWidth ) - position.x; - convertedPosition.y = static_cast( mWindowHeight ) - position.y; + convertedPosition.x = static_cast(mWindowWidth) - position.x; + convertedPosition.y = static_cast(mWindowHeight) - position.y; break; } case 270: { convertedPosition.x = position.y; - convertedPosition.y = static_cast( mWindowHeight ) - position.x; + convertedPosition.y = static_cast(mWindowHeight) - position.x; break; } default: @@ -882,44 +881,44 @@ void Window::RecalculateTouchPosition( Integration::Point& point ) } } - point.SetScreenPosition( convertedPosition ); + point.SetScreenPosition(convertedPosition); } -Dali::Window Window::Get( Dali::Actor actor ) +Dali::Window Window::Get(Dali::Actor actor) { Internal::Adaptor::Window* windowImpl = nullptr; - if ( Internal::Adaptor::Adaptor::IsAvailable() ) + if(Internal::Adaptor::Adaptor::IsAvailable()) { - Dali::Internal::Adaptor::Adaptor& adaptor = Internal::Adaptor::Adaptor::GetImplementation( Internal::Adaptor::Adaptor::Get() ); - windowImpl = dynamic_cast( adaptor.GetWindow( actor ) ); - if( windowImpl ) + Dali::Internal::Adaptor::Adaptor& adaptor = Internal::Adaptor::Adaptor::GetImplementation(Internal::Adaptor::Adaptor::Get()); + windowImpl = dynamic_cast(adaptor.GetWindow(actor)); + if(windowImpl) { - return Dali::Window( windowImpl ); + return Dali::Window(windowImpl); } } return Dali::Window(); } -void Window::SetParent( Dali::Window& parent ) +void Window::SetParent(Dali::Window& parent) { - if ( DALI_UNLIKELY( parent ) ) + if(DALI_UNLIKELY(parent)) { - mParentWindow = parent; - Dali::Window self = Dali::Window( this ); + mParentWindow = parent; + Dali::Window self = Dali::Window(this); // check circular parent window setting - if ( Dali::DevelWindow::GetParent( parent ) == self ) + if(Dali::DevelWindow::GetParent(parent) == self) { - Dali::DevelWindow::Unparent( parent ); + Dali::DevelWindow::Unparent(parent); } - mWindowBase->SetParent( GetImplementation( mParentWindow ).mWindowBase ); + mWindowBase->SetParent(GetImplementation(mParentWindow).mWindowBase); } } void Window::Unparent() { - mWindowBase->SetParent( nullptr ); + mWindowBase->SetParent(nullptr); mParentWindow.Reset(); } @@ -930,40 +929,40 @@ Dali::Window Window::GetParent() WindowOrientation Window::GetCurrentOrientation() const { - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), GetCurrentOrientation(): %d\n", this, mNativeWindowId, mRotationAngle ); - return ConvertToOrientation( mRotationAngle ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), GetCurrentOrientation(): %d\n", this, mNativeWindowId, mRotationAngle); + return ConvertToOrientation(mRotationAngle); } -void Window::SetAvailableOrientations( const Dali::Vector& orientations ) +void Window::SetAvailableOrientations(const Dali::Vector& orientations) { Dali::Vector::SizeType count = orientations.Count(); - for( Dali::Vector::SizeType index = 0; index < count; ++index ) + for(Dali::Vector::SizeType index = 0; index < count; ++index) { - if( IsOrientationAvailable( orientations[index] ) == false ) + if(IsOrientationAvailable(orientations[index]) == false) { DALI_LOG_ERROR("Window::SetAvailableOrientations, invalid orientation: %d\n", orientations[index]); continue; } - bool found = false; - int convertedAngle = ConvertToAngle( orientations[index] ); + bool found = false; + int convertedAngle = ConvertToAngle(orientations[index]); - for( std::size_t i = 0; i < mAvailableAngles.size(); i++ ) + for(std::size_t i = 0; i < mAvailableAngles.size(); i++) { - if( mAvailableAngles[i] == convertedAngle ) + if(mAvailableAngles[i] == convertedAngle) { found = true; break; } } - if( !found ) + if(!found) { - DALI_LOG_RELEASE_INFO( "Window (%p), WinId (%d), SetAvailableOrientations: %d\n", this, mNativeWindowId, convertedAngle ); - mAvailableAngles.push_back( convertedAngle ); + DALI_LOG_RELEASE_INFO("Window (%p), WinId (%d), SetAvailableOrientations: %d\n", this, mNativeWindowId, convertedAngle); + mAvailableAngles.push_back(convertedAngle); } } - SetAvailableAnlges( mAvailableAngles ); + SetAvailableAnlges(mAvailableAngles); } int32_t Window::GetNativeId() const @@ -971,8 +970,8 @@ int32_t Window::GetNativeId() const return mWindowBase->GetNativeWindowId(); } -} // Adaptor +} // namespace Adaptor -} // Internal +} // namespace Internal -} // Dali +} // namespace Dali diff --git a/dali/internal/window-system/common/window-impl.h b/dali/internal/window-system/common/window-impl.h index e9f8063..b364827 100644 --- a/dali/internal/window-system/common/window-impl.h +++ b/dali/internal/window-system/common/window-impl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_WINDOW_IMPL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,20 +19,20 @@ */ // EXTERNAL INCLUDES -#include -#include #include -#include -#include #include +#include +#include +#include +#include // INTERNAL INCLUDES -#include -#include #include #include #include #include +#include +#include namespace Dali { @@ -49,9 +49,9 @@ class WindowRenderSurface; class WindowBase; class Window; -using WindowPtr = IntrusivePtr< Window >; -using OrientationPtr = IntrusivePtr< Orientation >; -using EventHandlerPtr = IntrusivePtr< EventHandler >; +using WindowPtr = IntrusivePtr; +using OrientationPtr = IntrusivePtr; +using EventHandlerPtr = IntrusivePtr; /** * Window provides a surface to render onto with orientation & indicator properties. @@ -59,12 +59,12 @@ using EventHandlerPtr = IntrusivePtr< EventHandler >; class Window : public Dali::Internal::Adaptor::SceneHolder, public EventHandler::Observer, public ConnectionTracker { public: - typedef Dali::Window::FocusChangeSignalType FocusChangeSignalType; - typedef Dali::Window::ResizeSignalType ResizeSignalType; - typedef Dali::DevelWindow::VisibilityChangedSignalType VisibilityChangedSignalType; - typedef Dali::DevelWindow::TransitionEffectEventSignalType TransitionEffectEventSignalType; + typedef Dali::Window::FocusChangeSignalType FocusChangeSignalType; + typedef Dali::Window::ResizeSignalType ResizeSignalType; + typedef Dali::DevelWindow::VisibilityChangedSignalType VisibilityChangedSignalType; + typedef Dali::DevelWindow::TransitionEffectEventSignalType TransitionEffectEventSignalType; typedef Dali::DevelWindow::KeyboardRepeatSettingsChangedSignalType KeyboardRepeatSettingsChangedSignalType; - typedef Signal< void () > SignalType; + typedef Signal SignalType; /** * @brief Create a new Window. This should only be called once by the Application class @@ -90,7 +90,7 @@ public: /** * @copydoc Dali::Window::SetClass() */ - void SetClass( std::string name, std::string className ); + void SetClass(std::string name, std::string className); /** * @brief Gets the window class name. @@ -121,7 +121,7 @@ public: /** * @copydoc Dali::Window::GetLayer() */ - Dali::Layer GetLayer( uint32_t depth ) const; + Dali::Layer GetLayer(uint32_t depth) const; /** * @copydoc Dali::DevelWindow::GetRenderTaskList() @@ -151,7 +151,7 @@ public: /** * @copydoc Dali::Window::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ); + void SetAcceptFocus(bool accept); /** * @copydoc Dali::Window::IsFocusAcceptable() @@ -176,42 +176,42 @@ public: /** * @copydoc Dali::Window::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const; + std::string GetSupportedAuxiliaryHint(unsigned int index) const; /** * @copydoc Dali::Window::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ); + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value); /** * @copydoc Dali::Window::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ); + bool RemoveAuxiliaryHint(unsigned int id); /** * @copydoc Dali::Window::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ); + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value); /** * @copydoc Dali::Window::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const; + std::string GetAuxiliaryHintValue(unsigned int id) const; /** * @copydoc Dali::Window::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const; + unsigned int GetAuxiliaryHintId(const std::string& hint) const; /** * @copydoc Dali::Window::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ); + void SetInputRegion(const Rect& inputRegion); /** * @copydoc Dali::Window::SetType() */ - void SetType( WindowType type ); + void SetType(WindowType type); /** * @copydoc Dali::Window::GetType() const @@ -221,7 +221,7 @@ public: /** * @copydoc Dali::Window::SetNotificationLevel() */ - bool SetNotificationLevel( WindowNotificationLevel level ); + bool SetNotificationLevel(WindowNotificationLevel level); /** * @copydoc Dali::Window::GetNotificationLevel() @@ -231,7 +231,7 @@ public: /** * @copydoc Dali::Window::SetOpaqueState() */ - void SetOpaqueState( bool opaque ); + void SetOpaqueState(bool opaque); /** * @copydoc Dali::Window::IsOpaqueState() @@ -251,7 +251,7 @@ public: /** * @copydoc Dali::Window::SetBrightness() */ - bool SetBrightness( int brightness ); + bool SetBrightness(int brightness); /** * @copydoc Dali::Window::GetBrightness() @@ -261,7 +261,7 @@ public: /** * @copydoc Dali::Window::SetSize() */ - void SetSize( Dali::Window::WindowSize size ); + void SetSize(Dali::Window::WindowSize size); /** * @copydoc Dali::Window::GetSize() @@ -271,7 +271,7 @@ public: /** * @copydoc Dali::Window::SetPosition() */ - void SetPosition( Dali::Window::WindowPosition position ); + void SetPosition(Dali::Window::WindowPosition position); /** * @copydoc Dali::Window::GetPosition() @@ -281,7 +281,7 @@ public: /** * @copydoc Dali::DevelWindow::SetPositionSize() */ - void SetPositionSize( PositionSize positionSize ); + void SetPositionSize(PositionSize positionSize); /** * @copydoc Dali::Window::GetRootLayer() @@ -291,37 +291,37 @@ public: /** * @copydoc Dali::Window::SetTransparency() */ - void SetTransparency( bool transparent ); + void SetTransparency(bool transparent); /** * @copydoc Dali::KeyGrab::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ); + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode); /** * @copydoc Dali::KeyGrab::UngrabKey() */ - bool UngrabKey( Dali::KEY key ); + bool UngrabKey(Dali::KEY key); /** * @copydoc Dali::KeyGrab::GrabKeyList() */ - bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ); + bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result); /** * @copydoc Dali::KeyGrab::UngrabKeyList() */ - bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ); + bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result); /** * @copydoc Dali::DevelWindow::Get() */ - static Dali::Window Get( Dali::Actor actor ); + static Dali::Window Get(Dali::Actor actor); /** * @copydoc Dali::DevelWindow::SetParent() */ - void SetParent( Dali::Window& parent ); + void SetParent(Dali::Window& parent); /** * @copydoc Dali::DevelWindow::Unparent() @@ -341,10 +341,9 @@ public: /** * @copydoc Dali::DevelWindow::SetAvailableOrientations() */ - void SetAvailableOrientations( const Dali::Vector& orientations ); + void SetAvailableOrientations(const Dali::Vector& orientations); public: // Dali::Internal::Adaptor::SceneHolder - /** * @copydoc Dali::Internal::Adaptor::SceneHolder::GetNativeHandle */ @@ -361,7 +360,6 @@ public: // Dali::Internal::Adaptor::SceneHolder int32_t GetNativeId() const; private: - /** * @brief Enumeration for orietation mode. * The Orientation Mode is related to screen size. @@ -393,12 +391,12 @@ private: /** * Called when the window becomes iconified or deiconified. */ - void OnIconifyChanged( bool iconified ); + void OnIconifyChanged(bool iconified); /** * Called when the window focus is changed. */ - void OnFocusChanged( bool focusIn ); + void OnFocusChanged(bool focusIn); /** * Called when the output is transformed. @@ -413,7 +411,7 @@ private: /** * Called when the window receives a Transition effect-start/end event. */ - void OnTransitionEffectEvent( WindowEffectState state, WindowEffectType type ); + void OnTransitionEffectEvent(WindowEffectState state, WindowEffectType type); /** * @brief Called when window receives a keyboard repeat event. @@ -428,34 +426,33 @@ private: /** * @brief Set available orientation to window base. */ - void SetAvailableAnlges( const std::vector< int >& angles ); + void SetAvailableAnlges(const std::vector& angles); /** * @brief Convert from window orientation to angle using OrientationMode. */ - int ConvertToAngle( WindowOrientation orientation ); + int ConvertToAngle(WindowOrientation orientation); /** * @brief Convert from angle to window orientation using OrientationMode. */ - WindowOrientation ConvertToOrientation( int angle ) const; + WindowOrientation ConvertToOrientation(int angle) const; /** * @brief Check available window orientation for Available orientation. */ - bool IsOrientationAvailable( WindowOrientation orientation ) const; + bool IsOrientationAvailable(WindowOrientation orientation) const; private: // Dali::Internal::Adaptor::SceneHolder - /** * @copydoc Dali::Internal::Adaptor::SceneHolder::OnAdaptorSet */ - void OnAdaptorSet( Dali::Adaptor& adaptor ) override; + void OnAdaptorSet(Dali::Adaptor& adaptor) override; /** * @copydoc Dali::Internal::Adaptor::SceneHolder::OnSurfaceSet */ - void OnSurfaceSet( Dali::RenderSurfaceInterface* surface ) override; + void OnSurfaceSet(Dali::RenderSurfaceInterface* surface) override; /** * @copydoc Dali::Internal::Adaptor::SceneHolder::OnPause @@ -470,94 +467,112 @@ private: // Dali::Internal::Adaptor::SceneHolder /** * @copydoc Dali::Internal::Adaptor::SceneHolder::RecalculateTouchPosition */ - void RecalculateTouchPosition( Integration::Point& point ) override; + void RecalculateTouchPosition(Integration::Point& point) override; private: // Dali::Internal::Adaptor::EventHandler::Observer - /** * @copydoc Dali::Internal::Adaptor::EventHandler::Observer::OnTouchPoint */ - void OnTouchPoint( Dali::Integration::Point& point, int timeStamp ) override; + void OnTouchPoint(Dali::Integration::Point& point, int timeStamp) override; /** * @copydoc Dali::Internal::Adaptor::EventHandler::Observer::OnWheelEvent */ - void OnWheelEvent( Dali::Integration::WheelEvent& wheelEvent ) override; + void OnWheelEvent(Dali::Integration::WheelEvent& wheelEvent) override; /** * @copydoc Dali::Internal::Adaptor::EventHandler::Observer::OnKeyEvent */ - void OnKeyEvent( Dali::Integration::KeyEvent& keyEvent ) override; + void OnKeyEvent(Dali::Integration::KeyEvent& keyEvent) override; /** * @copydoc Dali::Internal::Adaptor::EventHandler::Observer::OnRotation */ - void OnRotation( const RotationEvent& rotation ) override; + void OnRotation(const RotationEvent& rotation) override; public: // Signals - /** * @copydoc Dali::Window::FocusChangeSignal() */ - FocusChangeSignalType& FocusChangeSignal() { return mFocusChangeSignal; } + FocusChangeSignalType& FocusChangeSignal() + { + return mFocusChangeSignal; + } /** * @copydoc Dali::Window::ResizedSignal() */ - ResizeSignalType& ResizeSignal() { return mResizeSignal; } + ResizeSignalType& ResizeSignal() + { + return mResizeSignal; + } /** * This signal is emitted when the window is requesting to be deleted */ - SignalType& DeleteRequestSignal() { return mDeleteRequestSignal; } + SignalType& DeleteRequestSignal() + { + return mDeleteRequestSignal; + } /** * @copydoc Dali::DevelWindow::VisibilityChangedSignal() */ - VisibilityChangedSignalType& VisibilityChangedSignal() { return mVisibilityChangedSignal; } + VisibilityChangedSignalType& VisibilityChangedSignal() + { + return mVisibilityChangedSignal; + } /** * @copydoc Dali::Window::SignalEventProcessingFinished() */ - Dali::DevelWindow::EventProcessingFinishedSignalType& EventProcessingFinishedSignal() { return mScene.EventProcessingFinishedSignal(); } + Dali::DevelWindow::EventProcessingFinishedSignalType& EventProcessingFinishedSignal() + { + return mScene.EventProcessingFinishedSignal(); + } /** * @copydoc Dali::DevelWindow::TransitionEffectEventSignal() */ - TransitionEffectEventSignalType& TransitionEffectEventSignal() { return mTransitionEffectEventSignal; } + TransitionEffectEventSignalType& TransitionEffectEventSignal() + { + return mTransitionEffectEventSignal; + } /** * @copydoc Dali::DevelWindow::KeyboardRepeatSettingsChangedSignal() */ - KeyboardRepeatSettingsChangedSignalType& KeyboardRepeatSettingsChangedSignal() { return mKeyboardRepeatSettingsChangedSignal; } + KeyboardRepeatSettingsChangedSignalType& KeyboardRepeatSettingsChangedSignal() + { + return mKeyboardRepeatSettingsChangedSignal; + } private: + WindowRenderSurface* mWindowSurface; ///< The window rendering surface + WindowBase* mWindowBase; + std::string mName; + std::string mClassName; + bool mIsTransparent : 1; + bool mIsFocusAcceptable : 1; + bool mIconified : 1; + bool mOpaqueState : 1; + bool mResizeEnabled : 1; + WindowType mType; + Dali::Window mParentWindow; - WindowRenderSurface* mWindowSurface; ///< The window rendering surface - WindowBase* mWindowBase; - std::string mName; - std::string mClassName; - bool mIsTransparent:1; - bool mIsFocusAcceptable:1; - bool mIconified:1; - bool mOpaqueState:1; - bool mResizeEnabled:1; - WindowType mType; - Dali::Window mParentWindow; - - OrientationPtr mOrientation; - std::vector< int > mAvailableAngles; - int mPreferredAngle; + OrientationPtr mOrientation; + std::vector mAvailableAngles; + int mPreferredAngle; - int mRotationAngle; ///< The angle of the rotation - int mWindowWidth; ///< The width of the window - int mWindowHeight; ///< The height of the window + int mRotationAngle; ///< The angle of the rotation + int mWindowWidth; ///< The width of the window + int mWindowHeight; ///< The height of the window - EventHandlerPtr mEventHandler; ///< The window events handler + EventHandlerPtr mEventHandler; ///< The window events handler - OrientationMode mOrientationMode; + OrientationMode mOrientationMode; - int mNativeWindowId; ///< The Native Window Id + int mNativeWindowId; ///< The Native Window Id // Signals SignalType mDeleteRequestSignal; @@ -569,20 +584,20 @@ private: }; } // namespace Adaptor -} // namepsace Internal +} // namespace Internal // Helpers for public-api forwarding methods inline Internal::Adaptor::Window& GetImplementation(Dali::Window& window) { - DALI_ASSERT_ALWAYS( window && "Window handle is empty" ); + DALI_ASSERT_ALWAYS(window && "Window handle is empty"); BaseObject& object = window.GetBaseObject(); return static_cast(object); } inline const Internal::Adaptor::Window& GetImplementation(const Dali::Window& window) { - DALI_ASSERT_ALWAYS( window && "Window handle is empty" ); + DALI_ASSERT_ALWAYS(window && "Window handle is empty"); const BaseObject& object = window.GetBaseObject(); return static_cast(object); } diff --git a/dali/internal/window-system/common/window-render-surface.cpp b/dali/internal/window-system/common/window-render-surface.cpp index d92c5dc..b5fffa8 100644 --- a/dali/internal/window-system/common/window-render-surface.cpp +++ b/dali/internal/window-system/common/window-render-surface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -29,10 +29,10 @@ #include #include #include +#include #include #include #include -#include namespace Dali { @@ -40,25 +40,23 @@ namespace Internal { namespace Adaptor { - namespace { - -const int MINIMUM_DIMENSION_CHANGE( 1 ); ///< Minimum change for window to be considered to have moved -const float FULL_UPDATE_RATIO( 0.8f ); ///< Force full update when the dirty area is larget than this ratio +const int MINIMUM_DIMENSION_CHANGE(1); ///< Minimum change for window to be considered to have moved +const float FULL_UPDATE_RATIO(0.8f); ///< Force full update when the dirty area is larget than this ratio #if defined(DEBUG_ENABLED) Debug::Filter* gWindowRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_WINDOW_RENDER_SURFACE"); #endif -void MergeRects( Rect< int >& mergingRect, const std::vector< Rect< int > >& rects ) +void MergeRects(Rect& mergingRect, const std::vector>& rects) { uint32_t i = 0; - if( mergingRect.IsEmpty() ) + if(mergingRect.IsEmpty()) { - for( ; i < rects.size(); i++ ) + for(; i < rects.size(); i++) { - if( !rects[i].IsEmpty() ) + if(!rects[i].IsEmpty()) { mergingRect = rects[i]; break; @@ -66,16 +64,16 @@ void MergeRects( Rect< int >& mergingRect, const std::vector< Rect< int > >& rec } } - for( ; i < rects.size(); i++ ) + for(; i < rects.size(); i++) { - mergingRect.Merge( rects[i] ); + mergingRect.Merge(rects[i]); } } -void InsertRects( WindowRenderSurface::DamagedRectsContainer& damagedRectsList, const std::vector< Rect< int > >& damagedRects ) +void InsertRects(WindowRenderSurface::DamagedRectsContainer& damagedRectsList, const std::vector>& damagedRects) { - damagedRectsList.push_front( damagedRects ); - if( damagedRectsList.size() > 4 ) // past triple buffers + current + damagedRectsList.push_front(damagedRects); + if(damagedRectsList.size() > 4) // past triple buffers + current { damagedRectsList.pop_back(); } @@ -110,44 +108,44 @@ WindowRenderSurface::WindowRenderSurface(Dali::PositionSize positionSize, Any su mResizeFinished(true), mDefaultScreenRotationAvailable(false) { - DALI_LOG_INFO( gWindowRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n" ); - Initialize( surface ); + DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n"); + Initialize(surface); } WindowRenderSurface::~WindowRenderSurface() { - if( mRotationTrigger ) + if(mRotationTrigger) { delete mRotationTrigger; } } -void WindowRenderSurface::Initialize( Any surface ) +void WindowRenderSurface::Initialize(Any surface) { // If width or height are zero, go full screen. - if ( (mPositionSize.width == 0) || (mPositionSize.height == 0) ) + if((mPositionSize.width == 0) || (mPositionSize.height == 0)) { // Default window size == screen size mPositionSize.x = 0; mPositionSize.y = 0; - WindowSystem::GetScreenSize( mPositionSize.width, mPositionSize.height ); + WindowSystem::GetScreenSize(mPositionSize.width, mPositionSize.height); } // Create a window base auto windowFactory = Dali::Internal::Adaptor::GetWindowFactory(); - mWindowBase = windowFactory->CreateWindowBase( mPositionSize, surface, ( mColorDepth == COLOR_DEPTH_32 ? true : false ) ); + mWindowBase = windowFactory->CreateWindowBase(mPositionSize, surface, (mColorDepth == COLOR_DEPTH_32 ? true : false)); // Connect signals - mWindowBase->OutputTransformedSignal().Connect( this, &WindowRenderSurface::OutputTransformed ); + mWindowBase->OutputTransformedSignal().Connect(this, &WindowRenderSurface::OutputTransformed); // Check screen rotation mScreenRotationAngle = mWindowBase->GetScreenRotationAngle(); - if( mScreenRotationAngle != 0 ) + if(mScreenRotationAngle != 0) { - mScreenRotationFinished = false; - mResizeFinished = false; + mScreenRotationFinished = false; + mResizeFinished = false; mDefaultScreenRotationAvailable = true; - DALI_LOG_RELEASE_INFO("WindowRenderSurface::Initialize, screen rotation is enabled, screen rotation angle:[%d]\n", mScreenRotationAngle ); + DALI_LOG_RELEASE_INFO("WindowRenderSurface::Initialize, screen rotation is enabled, screen rotation angle:[%d]\n", mScreenRotationAngle); } } @@ -166,14 +164,14 @@ void WindowRenderSurface::Map() mWindowBase->Show(); } -void WindowRenderSurface::SetRenderNotification( TriggerEventInterface* renderNotification ) +void WindowRenderSurface::SetRenderNotification(TriggerEventInterface* renderNotification) { mRenderNotification = renderNotification; } -void WindowRenderSurface::SetTransparency( bool transparent ) +void WindowRenderSurface::SetTransparency(bool transparent) { - mWindowBase->SetTransparency( transparent ); + mWindowBase->SetTransparency(transparent); } void WindowRenderSurface::RequestRotation(int angle, int width, int height) @@ -209,24 +207,24 @@ PositionSize WindowRenderSurface::GetPositionSize() const return mPositionSize; } -void WindowRenderSurface::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void WindowRenderSurface::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { - if( mDpiHorizontal == 0 || mDpiVertical == 0 ) + if(mDpiHorizontal == 0 || mDpiVertical == 0) { - const char* environmentDpiHorizontal = std::getenv( DALI_ENV_DPI_HORIZONTAL ); - mDpiHorizontal = environmentDpiHorizontal ? std::atoi( environmentDpiHorizontal ) : 0; + const char* environmentDpiHorizontal = std::getenv(DALI_ENV_DPI_HORIZONTAL); + mDpiHorizontal = environmentDpiHorizontal ? std::atoi(environmentDpiHorizontal) : 0; - const char* environmentDpiVertical = std::getenv( DALI_ENV_DPI_VERTICAL ); - mDpiVertical = environmentDpiVertical ? std::atoi( environmentDpiVertical ) : 0; + const char* environmentDpiVertical = std::getenv(DALI_ENV_DPI_VERTICAL); + mDpiVertical = environmentDpiVertical ? std::atoi(environmentDpiVertical) : 0; - if( mDpiHorizontal == 0 || mDpiVertical == 0 ) + if(mDpiHorizontal == 0 || mDpiVertical == 0) { - mWindowBase->GetDpi( mDpiHorizontal, mDpiVertical ); + mWindowBase->GetDpi(mDpiHorizontal, mDpiVertical); } } dpiHorizontal = mDpiHorizontal; - dpiVertical = mDpiVertical; + dpiVertical = mDpiVertical; } int WindowRenderSurface::GetOrientation() const @@ -238,17 +236,17 @@ void WindowRenderSurface::InitializeGraphics() { mGraphics = &mAdaptor->GetGraphicsInterface(); - DALI_ASSERT_ALWAYS( mGraphics && "Graphics interface is not created" ); + DALI_ASSERT_ALWAYS(mGraphics && "Graphics interface is not created"); - auto eglGraphics = static_cast(mGraphics); - mEGL = &eglGraphics->GetEglInterface(); + auto eglGraphics = static_cast(mGraphics); + mEGL = &eglGraphics->GetEglInterface(); - if ( mEGLContext == NULL ) + if(mEGLContext == NULL) { // Create the OpenGL context for this window Internal::Adaptor::EglImplementation& eglImpl = static_cast(*mEGL); eglImpl.ChooseConfig(true, mColorDepth); - eglImpl.CreateWindowContext( mEGLContext ); + eglImpl.CreateWindowContext(mEGLContext); // Create the OpenGL surface CreateSurface(); @@ -289,20 +287,20 @@ void WindowRenderSurface::CreateSurface() void WindowRenderSurface::DestroySurface() { - DALI_LOG_TRACE_METHOD( gWindowRenderSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gWindowRenderSurfaceLogFilter); - auto eglGraphics = static_cast(mGraphics); - if( eglGraphics ) + auto eglGraphics = static_cast(mGraphics); + if(eglGraphics) { - DALI_LOG_RELEASE_INFO("WindowRenderSurface::DestroySurface: WinId (%d)\n", mWindowBase->GetNativeWindowId() ); + DALI_LOG_RELEASE_INFO("WindowRenderSurface::DestroySurface: WinId (%d)\n", mWindowBase->GetNativeWindowId()); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - eglImpl.DestroySurface( mEGLSurface ); + eglImpl.DestroySurface(mEGLSurface); mEGLSurface = nullptr; // Destroy context also - eglImpl.DestroyContext( mEGLContext ); + eglImpl.DestroyContext(mEGLContext); mEGLContext = nullptr; mWindowBase->DestroyEglWindow(); @@ -311,79 +309,79 @@ void WindowRenderSurface::DestroySurface() bool WindowRenderSurface::ReplaceGraphicsSurface() { - DALI_LOG_TRACE_METHOD( gWindowRenderSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gWindowRenderSurfaceLogFilter); // Destroy the old one mWindowBase->DestroyEglWindow(); int width, height; - if( mScreenRotationAngle == 0 || mScreenRotationAngle == 180 ) + if(mScreenRotationAngle == 0 || mScreenRotationAngle == 180) { - width = mPositionSize.width; + width = mPositionSize.width; height = mPositionSize.height; } else { - width = mPositionSize.height; + width = mPositionSize.height; height = mPositionSize.width; } // Create the EGL window - EGLNativeWindowType window = mWindowBase->CreateEglWindow( width, height ); + EGLNativeWindowType window = mWindowBase->CreateEglWindow(width, height); // Set screen rotation mScreenRotationFinished = false; - auto eglGraphics = static_cast(mGraphics); + auto eglGraphics = static_cast(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - return eglImpl.ReplaceSurfaceWindow( window, mEGLSurface, mEGLContext ); + return eglImpl.ReplaceSurfaceWindow(window, mEGLSurface, mEGLContext); } -void WindowRenderSurface::MoveResize( Dali::PositionSize positionSize ) +void WindowRenderSurface::MoveResize(Dali::PositionSize positionSize) { - bool needToMove = false; + bool needToMove = false; bool needToResize = false; // Check moving - if( (fabs(positionSize.x - mPositionSize.x) > MINIMUM_DIMENSION_CHANGE) || - (fabs(positionSize.y - mPositionSize.y) > MINIMUM_DIMENSION_CHANGE) ) + if((fabs(positionSize.x - mPositionSize.x) > MINIMUM_DIMENSION_CHANGE) || + (fabs(positionSize.y - mPositionSize.y) > MINIMUM_DIMENSION_CHANGE)) { needToMove = true; } // Check resizing - if( (fabs(positionSize.width - mPositionSize.width) > MINIMUM_DIMENSION_CHANGE) || - (fabs(positionSize.height - mPositionSize.height) > MINIMUM_DIMENSION_CHANGE) ) + if((fabs(positionSize.width - mPositionSize.width) > MINIMUM_DIMENSION_CHANGE) || + (fabs(positionSize.height - mPositionSize.height) > MINIMUM_DIMENSION_CHANGE)) { needToResize = true; } - if( needToResize ) + if(needToResize) { - if( needToMove ) + if(needToMove) { - mWindowBase->MoveResize( positionSize ); + mWindowBase->MoveResize(positionSize); } else { - mWindowBase->Resize( positionSize ); + mWindowBase->Resize(positionSize); } mResizeFinished = false; - mPositionSize = positionSize; + mPositionSize = positionSize; } else { - if( needToMove ) + if(needToMove) { - mWindowBase->Move( positionSize ); + mWindowBase->Move(positionSize); mPositionSize = positionSize; } } - DALI_LOG_INFO( gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::MoveResize: %d, %d, %d, %d\n", mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height ); + DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::MoveResize: %d, %d, %d, %d\n", mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height); } void WindowRenderSurface::StartRender() @@ -407,7 +405,7 @@ bool WindowRenderSurface::PreRender(bool resizingSurface, const std::vector(new FrameCallbackInfo(callbacks, frameRenderedSync))); @@ -430,7 +428,7 @@ bool WindowRenderSurface::PreRender(bool resizingSurface, const std::vector(new FrameCallbackInfo(callbacks, framePresentedSync))); @@ -571,9 +569,9 @@ void WindowRenderSurface::StopRender() { } -void WindowRenderSurface::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization ) +void WindowRenderSurface::SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) { - DALI_LOG_INFO( gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::SetThreadSynchronization: called\n" ); + DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::SetThreadSynchronization: called\n"); mThreadSynchronization = &threadSynchronization; } @@ -590,9 +588,9 @@ Dali::RenderSurfaceInterface::Type WindowRenderSurface::GetSurfaceType() void WindowRenderSurface::MakeContextCurrent() { - if ( mEGL != nullptr ) + if(mEGL != nullptr) { - mEGL->MakeContextCurrent( mEGLSurface, mEGLContext ); + mEGL->MakeContextCurrent(mEGLSurface, mEGLContext); } } @@ -642,185 +640,184 @@ void WindowRenderSurface::ProcessRotationRequest() void WindowRenderSurface::ProcessFrameCallback() { - Dali::Mutex::ScopedLock lock( mMutex ); + Dali::Mutex::ScopedLock lock(mMutex); - for( auto&& iter : mFrameCallbackInfoContainer ) + for(auto&& iter : mFrameCallbackInfoContainer) { - if( !iter->fileDescriptorMonitor ) + if(!iter->fileDescriptorMonitor) { - iter->fileDescriptorMonitor = std::unique_ptr< FileDescriptorMonitor >( new FileDescriptorMonitor( iter->fileDescriptor, - MakeCallback( this, &WindowRenderSurface::OnFileDescriptorEventDispatched ), FileDescriptorMonitor::FD_READABLE ) ); + iter->fileDescriptorMonitor = std::unique_ptr(new FileDescriptorMonitor(iter->fileDescriptor, + MakeCallback(this, &WindowRenderSurface::OnFileDescriptorEventDispatched), + FileDescriptorMonitor::FD_READABLE)); - DALI_LOG_RELEASE_INFO( "WindowRenderSurface::ProcessFrameCallback: Add handler [%d]\n", iter->fileDescriptor ); + DALI_LOG_RELEASE_INFO("WindowRenderSurface::ProcessFrameCallback: Add handler [%d]\n", iter->fileDescriptor); } } } -void WindowRenderSurface::OnFileDescriptorEventDispatched( FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor ) +void WindowRenderSurface::OnFileDescriptorEventDispatched(FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor) { - if( !( eventBitMask & FileDescriptorMonitor::FD_READABLE ) ) + if(!(eventBitMask & FileDescriptorMonitor::FD_READABLE)) { - DALI_LOG_ERROR( "WindowRenderSurface::OnFileDescriptorEventDispatched: file descriptor error [%d]\n", eventBitMask ); - close( fileDescriptor ); + DALI_LOG_ERROR("WindowRenderSurface::OnFileDescriptorEventDispatched: file descriptor error [%d]\n", eventBitMask); + close(fileDescriptor); return; } - DALI_LOG_RELEASE_INFO( "WindowRenderSurface::OnFileDescriptorEventDispatched: Frame rendered [%d]\n", fileDescriptor ); + DALI_LOG_RELEASE_INFO("WindowRenderSurface::OnFileDescriptorEventDispatched: Frame rendered [%d]\n", fileDescriptor); - std::unique_ptr< FrameCallbackInfo > callbackInfo; + std::unique_ptr callbackInfo; { - Dali::Mutex::ScopedLock lock( mMutex ); - auto frameCallbackInfo = std::find_if( mFrameCallbackInfoContainer.begin(), mFrameCallbackInfoContainer.end(), - [fileDescriptor]( std::unique_ptr< FrameCallbackInfo >& callbackInfo ) - { - return callbackInfo->fileDescriptor == fileDescriptor; - } ); - if( frameCallbackInfo != mFrameCallbackInfoContainer.end() ) + Dali::Mutex::ScopedLock lock(mMutex); + auto frameCallbackInfo = std::find_if(mFrameCallbackInfoContainer.begin(), mFrameCallbackInfoContainer.end(), [fileDescriptor](std::unique_ptr& callbackInfo) { + return callbackInfo->fileDescriptor == fileDescriptor; + }); + if(frameCallbackInfo != mFrameCallbackInfoContainer.end()) { - callbackInfo = std::move( *frameCallbackInfo ); + callbackInfo = std::move(*frameCallbackInfo); - mFrameCallbackInfoContainer.erase( frameCallbackInfo ); + mFrameCallbackInfoContainer.erase(frameCallbackInfo); } } // Call the connected callback - if( callbackInfo ) + if(callbackInfo) { - for( auto&& iter : ( callbackInfo )->callbacks ) + for(auto&& iter : (callbackInfo)->callbacks) { - CallbackBase::Execute( *( iter.first ), iter.second ); + CallbackBase::Execute(*(iter.first), iter.second); } } } -void WindowRenderSurface::SetBufferDamagedRects( const std::vector< Rect< int > >& damagedRects, Rect< int >& clippingRect ) +void WindowRenderSurface::SetBufferDamagedRects(const std::vector>& damagedRects, Rect& clippingRect) { - auto eglGraphics = static_cast< EglGraphics* >( mGraphics ); - if ( eglGraphics ) + auto eglGraphics = static_cast(mGraphics); + if(eglGraphics) { Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - if( !eglImpl.IsPartialUpdateRequired() ) + if(!eglImpl.IsPartialUpdateRequired()) { return; } - Rect< int > surfaceRect( 0, 0, mPositionSize.width, mPositionSize.height ); + Rect surfaceRect(0, 0, mPositionSize.width, mPositionSize.height); - if( mFullSwapNextFrame ) + if(mFullSwapNextFrame) { - InsertRects( mBufferDamagedRects, std::vector< Rect< int > >( 1, surfaceRect ) ); - clippingRect = Rect< int >(); + InsertRects(mBufferDamagedRects, std::vector>(1, surfaceRect)); + clippingRect = Rect(); return; } - EGLint bufferAge = eglImpl.GetBufferAge( mEGLSurface ); + EGLint bufferAge = eglImpl.GetBufferAge(mEGLSurface); // Buffer age 0 means the back buffer in invalid and requires full swap - if( !damagedRects.size() || bufferAge == 0 ) + if(!damagedRects.size() || bufferAge == 0) { - InsertRects( mBufferDamagedRects, std::vector< Rect< int > >( 1, surfaceRect ) ); - clippingRect = Rect< int >(); + InsertRects(mBufferDamagedRects, std::vector>(1, surfaceRect)); + clippingRect = Rect(); return; } // We push current frame damaged rects here, zero index for current frame - InsertRects( mBufferDamagedRects, damagedRects ); + InsertRects(mBufferDamagedRects, damagedRects); // Merge damaged rects into clipping rect auto bufferDamagedRects = mBufferDamagedRects.begin(); - while( bufferAge-- >= 0 && bufferDamagedRects != mBufferDamagedRects.end() ) + while(bufferAge-- >= 0 && bufferDamagedRects != mBufferDamagedRects.end()) { - const std::vector< Rect< int > >& rects = *bufferDamagedRects++; - MergeRects( clippingRect, rects ); + const std::vector>& rects = *bufferDamagedRects++; + MergeRects(clippingRect, rects); } - if( !clippingRect.Intersect( surfaceRect ) || clippingRect.Area() > surfaceRect.Area() * FULL_UPDATE_RATIO ) + if(!clippingRect.Intersect(surfaceRect) || clippingRect.Area() > surfaceRect.Area() * FULL_UPDATE_RATIO) { // clipping area too big or doesn't intersect surface rect - clippingRect = Rect< int >(); + clippingRect = Rect(); return; } - std::vector< Rect< int > > damagedRegion; - damagedRegion.push_back( clippingRect ); + std::vector> damagedRegion; + damagedRegion.push_back(clippingRect); - eglImpl.SetDamageRegion( mEGLSurface, damagedRegion ); + eglImpl.SetDamageRegion(mEGLSurface, damagedRegion); } } -void WindowRenderSurface::SwapBuffers( const std::vector>& damagedRects ) +void WindowRenderSurface::SwapBuffers(const std::vector>& damagedRects) { - auto eglGraphics = static_cast< EglGraphics* >( mGraphics ); - if( eglGraphics ) + auto eglGraphics = static_cast(mGraphics); + if(eglGraphics) { - Rect< int > surfaceRect( 0, 0, mPositionSize.width, mPositionSize.height ); + Rect surfaceRect(0, 0, mPositionSize.width, mPositionSize.height); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - if( !eglImpl.IsPartialUpdateRequired() || mFullSwapNextFrame || !damagedRects.size() || (damagedRects[0].Area() > surfaceRect.Area() * FULL_UPDATE_RATIO) ) + if(!eglImpl.IsPartialUpdateRequired() || mFullSwapNextFrame || !damagedRects.size() || (damagedRects[0].Area() > surfaceRect.Area() * FULL_UPDATE_RATIO)) { mFullSwapNextFrame = false; - eglImpl.SwapBuffers( mEGLSurface ); + eglImpl.SwapBuffers(mEGLSurface); return; } mFullSwapNextFrame = false; - std::vector< Rect< int > > mergedRects = damagedRects; + std::vector> mergedRects = damagedRects; // Merge intersecting rects, form an array of non intersecting rects to help driver a bit // Could be optional and can be removed, needs to be checked with and without on platform const int n = mergedRects.size(); - for( int i = 0; i < n - 1; i++ ) + for(int i = 0; i < n - 1; i++) { - if( mergedRects[i].IsEmpty() ) + if(mergedRects[i].IsEmpty()) { continue; } - for( int j = i + 1; j < n; j++ ) + for(int j = i + 1; j < n; j++) { - if( mergedRects[j].IsEmpty() ) + if(mergedRects[j].IsEmpty()) { continue; } - if( mergedRects[i].Intersects( mergedRects[j] ) ) + if(mergedRects[i].Intersects(mergedRects[j])) { - mergedRects[i].Merge( mergedRects[j] ); - mergedRects[j].width = 0; + mergedRects[i].Merge(mergedRects[j]); + mergedRects[j].width = 0; mergedRects[j].height = 0; } } } int j = 0; - for( int i = 0; i < n; i++ ) + for(int i = 0; i < n; i++) { - if( !mergedRects[i].IsEmpty() ) + if(!mergedRects[i].IsEmpty()) { mergedRects[j++] = mergedRects[i]; } } - if( j != 0 ) + if(j != 0) { - mergedRects.resize( j ); + mergedRects.resize(j); } - if( !mergedRects.size() || ( mergedRects[0].Area() > surfaceRect.Area() * FULL_UPDATE_RATIO ) ) + if(!mergedRects.size() || (mergedRects[0].Area() > surfaceRect.Area() * FULL_UPDATE_RATIO)) { - eglImpl.SwapBuffers( mEGLSurface ); + eglImpl.SwapBuffers(mEGLSurface); } else { - eglImpl.SwapBuffers( mEGLSurface, mergedRects ); + eglImpl.SwapBuffers(mEGLSurface, mergedRects); } } } } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/common/window-render-surface.h b/dali/internal/window-system/common/window-render-surface.h index e748b18..d2584f1 100644 --- a/dali/internal/window-system/common/window-render-surface.h +++ b/dali/internal/window-system/common/window-render-surface.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_WINDOW_RENDER_SURFACE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ */ // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include #include // INTERNAL INCLUDES @@ -33,14 +33,12 @@ namespace Dali { - class TriggerEventInterface; namespace Internal { namespace Adaptor { - class WindowBase; class AdaptorInternalServices; @@ -50,9 +48,8 @@ class AdaptorInternalServices; class WindowRenderSurface : public Dali::RenderSurfaceInterface, public ConnectionTracker { public: - - using OutputSignalType = Signal< void ( ) >; - using DamagedRectsContainer = std::list< std::vector< Rect< int > > >; + using OutputSignalType = Signal; + using DamagedRectsContainer = std::list>>; /** * Uses an window surface to render to. @@ -60,7 +57,7 @@ public: * @param [in] surface can be a window or pixmap. * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit */ - WindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ); + WindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false); /** * @brief Destructor @@ -68,7 +65,6 @@ public: virtual ~WindowRenderSurface(); public: // API - /** * @brief Get the native window handle * @return The native window handle @@ -90,13 +86,13 @@ public: // API * @brief Sets the render notification trigger to call when render thread is completed a frame * @param renderNotification to use */ - void SetRenderNotification( TriggerEventInterface* renderNotification ); + void SetRenderNotification(TriggerEventInterface* renderNotification); /** * @brief Sets whether the surface is transparent or not. * @param[in] transparent Whether the surface is transparent */ - void SetTransparency( bool transparent ); + void SetTransparency(bool transparent); /** * Request surface rotation @@ -104,7 +100,7 @@ public: // API * @param[in] width A new width of the surface * @param[in] height A new height of the surface */ - void RequestRotation( int angle, int width, int height ); + void RequestRotation(int angle, int width, int height); /** * @brief Gets the window base object @@ -118,7 +114,6 @@ public: // API OutputSignalType& OutputTransformedSignal(); public: // from Dali::RenderSurfaceInterface - /** * @copydoc Dali::RenderSurfaceInterface::GetPositionSize() */ @@ -126,7 +121,7 @@ public: // from Dali::RenderSurfaceInterface /** */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::RenderSurfaceInterface::GetOrientation() @@ -156,7 +151,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::MoveResize() */ - void MoveResize( Dali::PositionSize positionSize) override; + void MoveResize(Dali::PositionSize positionSize) override; /** * @copydoc Dali::RenderSurfaceInterface::StartRender() @@ -166,12 +161,12 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::PreRender() */ - bool PreRender( bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect ) override; + bool PreRender(bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect) override; /** * @copydoc Dali::RenderSurfaceInterface::PostRender() */ - void PostRender( bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects ) override; + void PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects) override; /** * @copydoc Dali::RenderSurfaceInterface::StopRender() @@ -181,7 +176,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::SetThreadSynchronization */ - void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization ) override; + void SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) override; /** * @copydoc Dali::RenderSurfaceInterface::ReleaseLock() @@ -209,11 +204,10 @@ public: // from Dali::RenderSurfaceInterface Integration::StencilBufferAvailable GetStencilBufferRequired() override; private: - /** * @brief Second stage construction */ - void Initialize( Any surface ); + void Initialize(Any surface); /** * Notify output is transformed. @@ -235,23 +229,22 @@ private: * @param[in] eventBitMask bit mask of events that occured on the file descriptor * @param[in] fileDescriptor The file descriptor */ - void OnFileDescriptorEventDispatched( FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor ); + void OnFileDescriptorEventDispatched(FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor); /** * @brief Set the buffer damage rects. * @param[in] damagedRects List of damaged rects * @param[in] clippingRect The rect to clip rendered scene */ - void SetBufferDamagedRects( const std::vector< Rect< int > >& damagedRects, Rect< int >& clippingRect ); + void SetBufferDamagedRects(const std::vector>& damagedRects, Rect& clippingRect); /** * @brief Swap buffers. * @param[in] damagedRects List of damaged rects */ - void SwapBuffers( const std::vector>& damagedRects ); + void SwapBuffers(const std::vector>& damagedRects); protected: - // Undefined WindowRenderSurface(const WindowRenderSurface&) = delete; @@ -259,18 +252,17 @@ protected: WindowRenderSurface& operator=(const WindowRenderSurface& rhs) = delete; private: - struct FrameCallbackInfo { - FrameCallbackInfo( Dali::Integration::Scene::FrameCallbackContainer& callbackList, int fd ) + FrameCallbackInfo(Dali::Integration::Scene::FrameCallbackContainer& callbackList, int fd) : callbacks(), fileDescriptorMonitor(), - fileDescriptor( fd ) + fileDescriptor(fd) { // Transfer owership of the CallbackBase - for( auto&& iter : callbackList ) + for(auto&& iter : callbackList) { - callbacks.push_back( std::make_pair( std::move( iter.first ), iter.second ) ); + callbacks.push_back(std::make_pair(std::move(iter.first), iter.second)); } } @@ -278,49 +270,48 @@ private: { // Delete FileDescriptorMonitor before close fd. fileDescriptorMonitor.release(); - close( fileDescriptor ); + close(fileDescriptor); } Dali::Integration::Scene::FrameCallbackContainer callbacks; - std::unique_ptr< FileDescriptorMonitor > fileDescriptorMonitor; - int fileDescriptor; + std::unique_ptr fileDescriptorMonitor; + int fileDescriptor; }; - using FrameCallbackInfoContainer = std::vector< std::unique_ptr< FrameCallbackInfo > >; + using FrameCallbackInfoContainer = std::vector>; private: // Data - - EglInterface* mEGL; - Dali::DisplayConnection* mDisplayConnection; - PositionSize mPositionSize; ///< Position - std::unique_ptr< WindowBase > mWindowBase; - ThreadSynchronizationInterface* mThreadSynchronization; - TriggerEventInterface* mRenderNotification; ///< Render notification trigger - TriggerEventInterface* mRotationTrigger; - std::unique_ptr< TriggerEventInterface > mFrameRenderedTrigger; - GraphicsInterface* mGraphics; ///< Graphics interface - EGLSurface mEGLSurface; - EGLContext mEGLContext; - ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit) - OutputSignalType mOutputTransformedSignal; - FrameCallbackInfoContainer mFrameCallbackInfoContainer; - DamagedRectsContainer mBufferDamagedRects; - Dali::Mutex mMutex; - int mWindowRotationAngle; - int mScreenRotationAngle; - uint32_t mDpiHorizontal; - uint32_t mDpiVertical; - bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it) - bool mWindowRotationFinished; - bool mScreenRotationFinished; - bool mResizeFinished; - bool mDefaultScreenRotationAvailable; + EglInterface* mEGL; + Dali::DisplayConnection* mDisplayConnection; + PositionSize mPositionSize; ///< Position + std::unique_ptr mWindowBase; + ThreadSynchronizationInterface* mThreadSynchronization; + TriggerEventInterface* mRenderNotification; ///< Render notification trigger + TriggerEventInterface* mRotationTrigger; + std::unique_ptr mFrameRenderedTrigger; + GraphicsInterface* mGraphics; ///< Graphics interface + EGLSurface mEGLSurface; + EGLContext mEGLContext; + ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit) + OutputSignalType mOutputTransformedSignal; + FrameCallbackInfoContainer mFrameCallbackInfoContainer; + DamagedRectsContainer mBufferDamagedRects; + Dali::Mutex mMutex; + int mWindowRotationAngle; + int mScreenRotationAngle; + uint32_t mDpiHorizontal; + uint32_t mDpiVertical; + bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it) + bool mWindowRotationFinished; + bool mScreenRotationFinished; + bool mResizeFinished; + bool mDefaultScreenRotationAvailable; }; // class WindowRenderSurface } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/common/window-system.h b/dali/internal/window-system/common/window-system.h index 978e334..c39af3f 100644 --- a/dali/internal/window-system/common/window-system.h +++ b/dali/internal/window-system/common/window-system.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_COMMON_WINDOW_SYSTEM_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,8 @@ namespace Internal { namespace Adaptor { - namespace WindowSystem { - /** * @brief Initialize a window system */ @@ -41,22 +39,22 @@ void Shutdown(); /** * @brief Get the screen size */ -void GetScreenSize( int& width, int& height ); +void GetScreenSize(int& width, int& height); /** * @copydoc Dali::Keyboard::SetRepeatInfo() */ -bool SetKeyboardRepeatInfo( float rate, float delay ); +bool SetKeyboardRepeatInfo(float rate, float delay); /** * @copydoc Dali::Keyboard::GetRepeatInfo() */ -bool GetKeyboardRepeatInfo( float& rate, float& delay ); +bool GetKeyboardRepeatInfo(float& rate, float& delay); } // namespace WindowSystem } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali #endif // DALI_INTERNAL_WINDOWSYSTEM_COMMON_WINDOW_SYSTEM_H diff --git a/dali/internal/window-system/common/window-visibility-observer.h b/dali/internal/window-system/common/window-visibility-observer.h index 179c0de..2ac06d3 100644 --- a/dali/internal/window-system/common/window-visibility-observer.h +++ b/dali/internal/window-system/common/window-visibility-observer.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOW_VISIBILITY_OBSERVER_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,20 +20,16 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - /** * An interface used to observe when the application's window is shown/hidden. */ class WindowVisibilityObserver { public: - /** * Called when the window becomes fully or partially visible. */ @@ -45,7 +41,6 @@ public: virtual void OnWindowHidden() = 0; protected: - /** * Protected Constructor. */ diff --git a/dali/internal/window-system/macos/display-connection-factory-mac.cpp b/dali/internal/window-system/macos/display-connection-factory-mac.cpp index 14e95d9..cbb4f2e 100644 --- a/dali/internal/window-system/macos/display-connection-factory-mac.cpp +++ b/dali/internal/window-system/macos/display-connection-factory-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ namespace Dali::Internal::Adaptor { - std::unique_ptr DisplayConnectionFactoryCocoa::CreateDisplayConnection() { @@ -34,4 +33,4 @@ GetDisplayConnectionFactory() return Utils::MakeUnique(); } -} +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/display-connection-factory-mac.h b/dali/internal/window-system/macos/display-connection-factory-mac.h index 2892af2..607ddde 100644 --- a/dali/internal/window-system/macos/display-connection-factory-mac.h +++ b/dali/internal/window-system/macos/display-connection-factory-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ namespace Dali::Internal::Adaptor { - class DisplayConnectionFactoryCocoa : public DisplayConnectionFactory { public: diff --git a/dali/internal/window-system/macos/display-connection-impl-mac.cpp b/dali/internal/window-system/macos/display-connection-impl-mac.cpp index f8488e4..f514b70 100644 --- a/dali/internal/window-system/macos/display-connection-impl-mac.cpp +++ b/dali/internal/window-system/macos/display-connection-impl-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ * */ - // CLASS HEADER +// CLASS HEADER #include #include @@ -27,7 +27,6 @@ namespace Dali::Internal::Adaptor { - DisplayConnection* DisplayConnectionCocoa::New() { return new DisplayConnectionCocoa(); @@ -53,11 +52,11 @@ void DisplayConnectionCocoa::ConsumeEvents() bool DisplayConnectionCocoa::InitializeEgl(EglInterface& egl) { - EglImplementation& eglImpl = static_cast( egl ); + EglImplementation& eglImpl = static_cast(egl); if(!eglImpl.InitializeGles(EGL_DEFAULT_DISPLAY)) { - DALI_LOG_ERROR( "Failed to initialize GLES.\n" ); + DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; } @@ -66,23 +65,23 @@ bool DisplayConnectionCocoa::InitializeEgl(EglInterface& egl) bool DisplayConnectionCocoa::InitializeGraphics() { - auto eglGraphics = static_cast( mGraphics ); - EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); if(!eglImpl.InitializeGles(EGL_DEFAULT_DISPLAY)) { - DALI_LOG_ERROR( "Failed to initialize GLES.\n" ); + DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; } return true; } -void DisplayConnectionCocoa::SetSurfaceType( Dali::RenderSurfaceInterface::Type type ) +void DisplayConnectionCocoa::SetSurfaceType(Dali::RenderSurfaceInterface::Type type) { } -void DisplayConnectionCocoa::SetGraphicsInterface( GraphicsInterface& graphics ) +void DisplayConnectionCocoa::SetGraphicsInterface(GraphicsInterface& graphics) { mGraphics = &graphics; } diff --git a/dali/internal/window-system/macos/display-connection-impl-mac.h b/dali/internal/window-system/macos/display-connection-impl-mac.h index 9cb24bf..16bba7d 100644 --- a/dali/internal/window-system/macos/display-connection-impl-mac.h +++ b/dali/internal/window-system/macos/display-connection-impl-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,20 +18,18 @@ */ // INTERNAL INCLUDES +#include #include #include -#include namespace Dali::Internal::Adaptor { - /** * DisplayConnection implementation */ class DisplayConnectionCocoa : public Dali::Internal::Adaptor::DisplayConnection { public: - /** * @brief Default constructor */ @@ -45,7 +43,6 @@ public: static DisplayConnection* New(); public: - /** * @copydoc Dali::DisplayConnection::GetDisplay */ @@ -69,22 +66,20 @@ public: /** * @copydoc Dali::Internal::Adaptor::DisplayConnection::SetSurfaceType */ - void SetSurfaceType( Dali::RenderSurfaceInterface::Type type ); + void SetSurfaceType(Dali::RenderSurfaceInterface::Type type); /** * @copydoc Dali::Internal::Adaptor::DisplayConnection::SetGraphicsInterface */ - void SetGraphicsInterface( GraphicsInterface& graphics ); + void SetGraphicsInterface(GraphicsInterface& graphics); public: - /** * Destructor */ virtual ~DisplayConnectionCocoa(); private: - // Undefined DisplayConnectionCocoa(const DisplayConnectionCocoa&) = delete; @@ -92,8 +87,7 @@ private: DisplayConnectionCocoa& operator=(const DisplayConnectionCocoa& rhs) = delete; private: - - GraphicsInterface *mGraphics; ///< The graphics interface + GraphicsInterface* mGraphics; ///< The graphics interface }; } // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/render-surface-factory-mac.cpp b/dali/internal/window-system/macos/render-surface-factory-mac.cpp index 1c76cf4..4b399ba 100644 --- a/dali/internal/window-system/macos/render-surface-factory-mac.cpp +++ b/dali/internal/window-system/macos/render-surface-factory-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,43 +29,39 @@ namespace Dali::Internal::Adaptor { - -std::unique_ptr< WindowRenderSurface > +std::unique_ptr RenderSurfaceFactoryCocoa::CreateWindowRenderSurface( Dali::PositionSize positionSize, - Any surface, - bool isTransparent -) + Any surface, + bool isTransparent) { - return Utils::MakeUnique< WindowRenderSurfaceCocoa >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< PixmapRenderSurface > +std::unique_ptr RenderSurfaceFactoryCocoa::CreatePixmapRenderSurface( Dali::PositionSize positionSize, - Any surface, - bool isTransparent -) + Any surface, + bool isTransparent) { DALI_LOG_ERROR("Pixmap isn't been supported in Windows"); return nullptr; } -std::unique_ptr< NativeRenderSurface > +std::unique_ptr RenderSurfaceFactoryCocoa::CreateNativeRenderSurface( SurfaceSize surfaceSize, - Any surface, - bool isTransparent -) + Any surface, + bool isTransparent) { - return std::unique_ptr< NativeRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } // this should be created from somewhere -std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory() +std::unique_ptr GetRenderSurfaceFactory() { // returns Window factory - return Utils::MakeUnique< RenderSurfaceFactoryCocoa >(); + return Utils::MakeUnique(); } -} // namespace Dali::Adaptor::Internal +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/render-surface-factory-mac.h b/dali/internal/window-system/macos/render-surface-factory-mac.h index 52388ca..e6326a2 100644 --- a/dali/internal/window-system/macos/render-surface-factory-mac.h +++ b/dali/internal/window-system/macos/render-surface-factory-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,27 +21,23 @@ namespace Dali::Internal::Adaptor { - class RenderSurfaceFactoryCocoa : public RenderSurfaceFactory { public: - std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( + std::unique_ptr CreateWindowRenderSurface( Dali::PositionSize positionSize, - Any surface, - bool isTransparent = false - ) override; + Any surface, + bool isTransparent = false) override; - std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( + std::unique_ptr CreatePixmapRenderSurface( Dali::PositionSize positionSize, - Any surface, - bool isTransparent = false - ) override; + Any surface, + bool isTransparent = false) override; - std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface( + std::unique_ptr CreateNativeRenderSurface( SurfaceSize surfaceSize, - Any surface, - bool isTransparent = false - ) override; + Any surface, + bool isTransparent = false) override; }; } // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/window-base-mac.h b/dali/internal/window-system/macos/window-base-mac.h index 547583d..dc0ee59 100644 --- a/dali/internal/window-system/macos/window-base-mac.h +++ b/dali/internal/window-system/macos/window-base-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,20 +23,18 @@ namespace Dali::Internal::Adaptor { - /** * WindowBaseCocoa class provides an WindowBase Win32 implementation. */ class WindowBaseCocoa : public WindowBase { public: - struct Impl; /** * @brief Constructor */ - WindowBaseCocoa( PositionSize positionSize, Any surface, bool isTransparent ); + WindowBaseCocoa(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Destructor @@ -44,7 +42,6 @@ public: ~WindowBaseCocoa(); public: - /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNativeWindow() */ @@ -58,7 +55,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateEglWindow() */ - EGLNativeWindowType CreateEglWindow( int width, int height ) override; + EGLNativeWindowType CreateEglWindow(int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::DestroyEglWindow() @@ -68,22 +65,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowRotation() */ - void SetEglWindowRotation( int angle ) override; + void SetEglWindowRotation(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowBufferTransform() */ - void SetEglWindowBufferTransform( int angle ) override; + void SetEglWindowBufferTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowTransform() */ - void SetEglWindowTransform( int angle ) override; + void SetEglWindowTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::ResizeEglWindow() */ - void ResizeEglWindow( PositionSize positionSize ) override; + void ResizeEglWindow(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::IsEglWindowRotationSupported() @@ -93,22 +90,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::Move() */ - void Move( PositionSize positionSize ) override; + void Move(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Resize() */ - void Resize( PositionSize positionSize ) override; + void Resize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::MoveResize() */ - void MoveResize( PositionSize positionSize ) override; + void MoveResize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetClass() */ - void SetClass( const std::string& name, const std::string& className ) override; + void SetClass(const std::string& name, const std::string& className) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Raise() @@ -128,17 +125,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAvailableAnlges() */ - void SetAvailableAnlges( const std::vector< int >& angles ) override; + void SetAvailableAnlges(const std::vector& angles) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetPreferredAngle() */ - void SetPreferredAngle( int angle ) override; + void SetPreferredAngle(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ) override; + void SetAcceptFocus(bool accept) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Show() @@ -158,47 +155,47 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const override; + std::string GetSupportedAuxiliaryHint(unsigned int index) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) override; + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ) override; + bool RemoveAuxiliaryHint(unsigned int id) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) override; + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const override; + std::string GetAuxiliaryHintValue(unsigned int id) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const override; + unsigned int GetAuxiliaryHintId(const std::string& hint) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ) override; + void SetInputRegion(const Rect& inputRegion) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetType() */ - void SetType( Dali::WindowType type ) override; + void SetType(Dali::WindowType type) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetNotificationLevel() */ - bool SetNotificationLevel( WindowNotificationLevel level ) override; + bool SetNotificationLevel(WindowNotificationLevel level) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNotificationLevel() @@ -208,7 +205,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetOpaqueState() */ - void SetOpaqueState( bool opaque ) override; + void SetOpaqueState(bool opaque) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetScreenOffMode() @@ -223,7 +220,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetBrightness() */ - bool SetBrightness( int brightness ) override; + bool SetBrightness(int brightness) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetBrightness() @@ -233,34 +230,32 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) override; + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKey() */ - bool UngrabKey( Dali::KEY key ) override; + bool UngrabKey(Dali::KEY key) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKeyList() */ bool GrabKeyList( - const Dali::Vector< Dali::KEY >& key, - const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, - Dali::Vector< bool >& result - ) override; + const Dali::Vector& key, + const Dali::Vector& grabMode, + Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKeyList() */ bool UngrabKeyList( - const Dali::Vector< Dali::KEY >& key, - Dali::Vector< bool >& result - ) override; + const Dali::Vector& key, + Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetOrientation() @@ -275,22 +270,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetWindowRotationAngle() */ - void SetWindowRotationAngle( int degree ) override; + void SetWindowRotationAngle(int degree) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::WindowRotationCompleted() */ - void WindowRotationCompleted( int degree, int width, int height ) override; + void WindowRotationCompleted(int degree, int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetTransparency() */ - void SetTransparency( bool transparent ) override; + void SetTransparency(bool transparent) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetParent() */ - void SetParent( WindowBase* parentWinBase ) override; + void SetParent(WindowBase* parentWinBase) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateFrameRenderedSyncFence() @@ -303,9 +298,8 @@ public: int CreateFramePresentedSyncFence() override; private: - // Undefined - WindowBaseCocoa(const WindowBaseCocoa &) = delete; + WindowBaseCocoa(const WindowBaseCocoa&) = delete; // Undefined WindowBaseCocoa& operator=(const WindowBaseCocoa& rhs) = delete; diff --git a/dali/internal/window-system/macos/window-factory-mac.cpp b/dali/internal/window-system/macos/window-factory-mac.cpp index bb1ad51..179dd4b 100644 --- a/dali/internal/window-system/macos/window-factory-mac.cpp +++ b/dali/internal/window-system/macos/window-factory-mac.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,26 +19,24 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali::Internal::Adaptor { - std::unique_ptr WindowFactoryCocoa::CreateWindowBase( Dali::PositionSize positionSize, - Any surface, - bool isTransparent -) + Any surface, + bool isTransparent) { - return Utils::MakeUnique< WindowBaseCocoa >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } // this should be created from Window impl -std::unique_ptr< WindowFactory > GetWindowFactory() +std::unique_ptr GetWindowFactory() { // returns Window factory - return Utils::MakeUnique< WindowFactoryCocoa >(); + return Utils::MakeUnique(); } } // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/window-factory-mac.h b/dali/internal/window-system/macos/window-factory-mac.h index 19c33ce..2a122f7 100644 --- a/dali/internal/window-system/macos/window-factory-mac.h +++ b/dali/internal/window-system/macos/window-factory-mac.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,13 @@ namespace Dali::Internal::Adaptor { - class WindowFactoryCocoa : public WindowFactory { public: std::unique_ptr CreateWindowBase( Dali::PositionSize positionSize, - Any surface, - bool isTransparent - ) override; + Any surface, + bool isTransparent) override; }; } // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/window-render-surface-cocoa.cpp b/dali/internal/window-system/macos/window-render-surface-cocoa.cpp index 90d0d0d..37af0c4 100644 --- a/dali/internal/window-system/macos/window-render-surface-cocoa.cpp +++ b/dali/internal/window-system/macos/window-render-surface-cocoa.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ namespace Dali::Internal::Adaptor { WindowRenderSurfaceCocoa::WindowRenderSurfaceCocoa(Dali::PositionSize positionSize, Any surface, bool isTransparent) - : WindowRenderSurface(positionSize, surface, isTransparent) - , mReady(false) +: WindowRenderSurface(positionSize, surface, isTransparent), + mReady(false) { } @@ -29,7 +29,7 @@ void WindowRenderSurfaceCocoa::StartRender() { std::unique_lock lock(mCondMutex); WindowRenderSurface::StartRender(); - while (!mReady) + while(!mReady) { mRenderWait.wait(lock); } @@ -42,4 +42,4 @@ void WindowRenderSurfaceCocoa::CreateSurface() mReady = true; mRenderWait.notify_all(); } -} // Dali::Internal::Adaptor +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/macos/window-render-surface-cocoa.h b/dali/internal/window-system/macos/window-render-surface-cocoa.h index 7e573a4..7a99571 100644 --- a/dali/internal/window-system/macos/window-render-surface-cocoa.h +++ b/dali/internal/window-system/macos/window-render-surface-cocoa.h @@ -1,7 +1,7 @@ #pragma once /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ */ // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -33,7 +33,6 @@ namespace Dali::Internal::Adaptor class WindowRenderSurfaceCocoa : public WindowRenderSurface { public: - /** * @copydoc Dali::WindowRenderSurface() */ @@ -50,8 +49,8 @@ public: void CreateSurface() override; private: - std::mutex mCondMutex; + std::mutex mCondMutex; std::condition_variable mRenderWait; - bool mReady; + bool mReady; }; -} // Dali::Internal::Adaptor +} // namespace Dali::Internal::Adaptor diff --git a/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.cpp index 488835c..a73c564 100644 --- a/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ namespace Internal { namespace Adaptor { - std::unique_ptr DisplayConnectionFactoryEcoreWl::CreateDisplayConnection() { return Utils::MakeUnique(); @@ -37,6 +36,6 @@ std::unique_ptr GetDisplayConnectionFactory() return Utils::MakeUnique(); } -} -} -} +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.h b/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.h index e156313..1c23ffc 100644 --- a/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.h +++ b/dali/internal/window-system/tizen-wayland/display-connection-factory-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_FACTORY_ECORE_WL_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,11 +32,10 @@ public: std::unique_ptr CreateDisplayConnection() override; }; -} // Adaptor +} // namespace Adaptor -} // Internal - -} // Dali +} // namespace Internal +} // namespace Dali #endif // DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_FACTORY_ECORE_WL_H diff --git a/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.cpp old mode 100755 new mode 100644 index 3d9911b..3c2e234 --- a/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,12 @@ */ // CLASS HEADER -#include #include +#include // EXTERNAL_HEADERS -#include #include +#include #ifdef ECORE_WAYLAND2 #include @@ -31,13 +31,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - DisplayConnection* DisplayConnectionEcoreWl::New() { DisplayConnection* pDisplayConnection(new DisplayConnectionEcoreWl()); @@ -46,15 +43,15 @@ DisplayConnection* DisplayConnectionEcoreWl::New() } DisplayConnectionEcoreWl::DisplayConnectionEcoreWl() -: mDisplay( NULL ), - mSurfaceType( RenderSurfaceInterface::WINDOW_RENDER_SURFACE ), - mGraphics( nullptr ) +: mDisplay(NULL), + mSurfaceType(RenderSurfaceInterface::WINDOW_RENDER_SURFACE), + mGraphics(nullptr) { } DisplayConnectionEcoreWl::~DisplayConnectionEcoreWl() { - if( mSurfaceType == RenderSurfaceInterface::NATIVE_RENDER_SURFACE ) + if(mSurfaceType == RenderSurfaceInterface::NATIVE_RENDER_SURFACE) { ReleaseNativeDisplay(); } @@ -62,7 +59,7 @@ DisplayConnectionEcoreWl::~DisplayConnectionEcoreWl() Any DisplayConnectionEcoreWl::GetDisplay() { - return Any( mDisplay ); + return Any(mDisplay); } void DisplayConnectionEcoreWl::ConsumeEvents() @@ -71,10 +68,10 @@ void DisplayConnectionEcoreWl::ConsumeEvents() bool DisplayConnectionEcoreWl::InitializeGraphics() { - auto eglGraphics = static_cast(mGraphics); - EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - if( !eglImpl.InitializeGles( mDisplay ) ) + if(!eglImpl.InitializeGles(mDisplay)) { DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; @@ -83,40 +80,40 @@ bool DisplayConnectionEcoreWl::InitializeGraphics() return true; } -void DisplayConnectionEcoreWl::SetSurfaceType( Dali::RenderSurfaceInterface::Type type ) +void DisplayConnectionEcoreWl::SetSurfaceType(Dali::RenderSurfaceInterface::Type type) { mSurfaceType = type; - if( mSurfaceType == Dali::RenderSurfaceInterface::NATIVE_RENDER_SURFACE ) + if(mSurfaceType == Dali::RenderSurfaceInterface::NATIVE_RENDER_SURFACE) { mDisplay = GetNativeDisplay(); } else { #ifdef ECORE_WAYLAND2 - Ecore_Wl2_Display* display = ecore_wl2_connected_display_get( NULL ); - mDisplay = reinterpret_cast< EGLNativeDisplayType >( ecore_wl2_display_get( display ) ); + Ecore_Wl2_Display* display = ecore_wl2_connected_display_get(NULL); + mDisplay = reinterpret_cast(ecore_wl2_display_get(display)); #else - mDisplay = reinterpret_cast< EGLNativeDisplayType >( ecore_wl_display_get() ); + mDisplay = reinterpret_cast(ecore_wl_display_get()); #endif } } -void DisplayConnectionEcoreWl::SetGraphicsInterface( GraphicsInterface& graphics ) +void DisplayConnectionEcoreWl::SetGraphicsInterface(GraphicsInterface& graphics) { mGraphics = &graphics; } EGLNativeDisplayType DisplayConnectionEcoreWl::GetNativeDisplay() { - return reinterpret_cast< EGLNativeDisplayType >( tbm_dummy_display_create() ); + return reinterpret_cast(tbm_dummy_display_create()); } void DisplayConnectionEcoreWl::ReleaseNativeDisplay() { - if( mDisplay ) + if(mDisplay) { - tbm_dummy_display_destroy( reinterpret_cast< tbm_dummy_display* >( mDisplay ) ); + tbm_dummy_display_destroy(reinterpret_cast(mDisplay)); } } diff --git a/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.h b/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.h index d3471f2..191a9ee 100644 --- a/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.h +++ b/dali/internal/window-system/tizen-wayland/display-connection-impl-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREWL_DISPLAY_CONNECTION_IMPL_ECORE_WL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,22 +23,18 @@ namespace Dali { - class DisplayConnection; namespace Internal { - namespace Adaptor { - /** * DisplayConnection implementation */ class DisplayConnectionEcoreWl : public Dali::Internal::Adaptor::DisplayConnection { public: - /** * @brief Default constructor */ @@ -52,7 +48,6 @@ public: static DisplayConnection* New(); public: - /** * @copydoc Dali::DisplayConnection::GetDisplay */ @@ -72,23 +67,21 @@ public: * @brief Sets the surface type * @param[in] type The surface type */ - void SetSurfaceType( Dali::RenderSurfaceInterface::Type type ); + void SetSurfaceType(Dali::RenderSurfaceInterface::Type type); /** * @brief Sets the graphics interface * @param[in] graphics The graphics interface */ - void SetGraphicsInterface( GraphicsInterface& graphics ); + void SetGraphicsInterface(GraphicsInterface& graphics); public: - /** * Destructor */ virtual ~DisplayConnectionEcoreWl(); protected: - /** * @brief Gets display connection for native surface */ @@ -106,14 +99,14 @@ protected: DisplayConnectionEcoreWl& operator=(const DisplayConnectionEcoreWl& rhs); private: - EGLNativeDisplayType mDisplay; ///< Wayland-display for rendering - Dali::RenderSurfaceInterface::Type mSurfaceType; ///< The surface type - GraphicsInterface* mGraphics; ///< The graphics interface + EGLNativeDisplayType mDisplay; ///< Wayland-display for rendering + Dali::RenderSurfaceInterface::Type mSurfaceType; ///< The surface type + GraphicsInterface* mGraphics; ///< The graphics interface }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.cpp index bd23041..97c6183 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ #include // INTERNAL HEADERS +#include +#include #include #include -#include -#include // EXTERNAL INCLUDES #include @@ -33,27 +33,26 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowRenderSurface > RenderSurfaceFactoryEcoreWl::CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreWl::CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowRenderSurface >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< PixmapRenderSurface > RenderSurfaceFactoryEcoreWl::CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreWl::CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return std::unique_ptr< PixmapRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } -std::unique_ptr< NativeRenderSurface > RenderSurfaceFactoryEcoreWl::CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreWl::CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< NativeRenderSurfaceEcoreWl >( surfaceSize, surface, isTransparent ); + return Utils::MakeUnique(surfaceSize, surface, isTransparent); } // this should be created from somewhere -std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory() +std::unique_ptr GetRenderSurfaceFactory() { // returns Window factory - return Utils::MakeUnique< RenderSurfaceFactoryEcoreWl >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.h b/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.h index a20bc74..8384f6f 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.h +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/render-surface-factory-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_RENDER_SURFACE_FACTORY_ECORE_WL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,15 +26,14 @@ namespace Internal { namespace Adaptor { - class RenderSurfaceFactoryEcoreWl : public RenderSurfaceFactory { public: - std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.cpp index 74a67c0..3a07b04 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,52 +23,48 @@ #include // INTERNAL HEADERS +#include #include -#include #include -#include +#include // EXTERNAL_HEADERS -#include -#include #include -#include +#include +#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_WINDOW_BASE" ); +Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW_BASE"); #endif -const uint32_t MAX_TIZEN_CLIENT_VERSION = 7; -const unsigned int PRIMARY_TOUCH_BUTTON_ID = 1; +const uint32_t MAX_TIZEN_CLIENT_VERSION = 7; +const unsigned int PRIMARY_TOUCH_BUTTON_ID = 1; -const char* DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced. +const char* DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced. // DBUS accessibility -const char* BUS = "org.enlightenment.wm-screen-reader"; +const char* BUS = "org.enlightenment.wm-screen-reader"; const char* INTERFACE = "org.tizen.GestureNavigation"; -const char* PATH = "/org/tizen/GestureNavigation"; +const char* PATH = "/org/tizen/GestureNavigation"; /** * Get the device name from the provided ecore key event */ -void GetDeviceName( Ecore_Event_Key* keyEvent, std::string& result ) +void GetDeviceName(Ecore_Event_Key* keyEvent, std::string& result) { - const char* ecoreDeviceName = ecore_device_name_get( keyEvent->dev ); + const char* ecoreDeviceName = ecore_device_name_get(keyEvent->dev); - if( ecoreDeviceName ) + if(ecoreDeviceName) { result = ecoreDeviceName; } @@ -77,9 +73,9 @@ void GetDeviceName( Ecore_Event_Key* keyEvent, std::string& result ) /** * Get the device class from the provided ecore event */ -void GetDeviceClass( Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& deviceClass ) +void GetDeviceClass(Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& deviceClass) { - switch( ecoreDeviceClass ) + switch(ecoreDeviceClass) { case ECORE_DEVICE_CLASS_SEAT: { @@ -124,9 +120,9 @@ void GetDeviceClass( Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& d } } -void GetDeviceSubclass( Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subclass::Type& deviceSubclass ) +void GetDeviceSubclass(Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subclass::Type& deviceSubclass) { - switch( ecoreDeviceSubclass ) + switch(ecoreDeviceSubclass) { case ECORE_DEVICE_SUBCLASS_FINGER: { @@ -201,60 +197,60 @@ void GetDeviceSubclass( Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subcl ///////////////////////////////////////////////////////////////////////////////////////////////// /// Called when the window iconify state is changed. -static Eina_Bool EcoreEventWindowIconifyStateChanged( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowIconifyStateChanged(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnIconifyStateChanged( data, type, event ); + return windowBase->OnIconifyStateChanged(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the window gains focus -static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowFocusIn(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnFocusIn( data, type, event ); + return windowBase->OnFocusIn(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the window loses focus -static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowFocusOut(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnFocusOut( data, type, event ); + return windowBase->OnFocusOut(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the output is transformed -static Eina_Bool EcoreEventOutputTransform( void* data, int type, void* event ) +static Eina_Bool EcoreEventOutputTransform(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnOutputTransform( data, type, event ); + return windowBase->OnOutputTransform(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the output transform should be ignored -static Eina_Bool EcoreEventIgnoreOutputTransform( void* data, int type, void* event ) +static Eina_Bool EcoreEventIgnoreOutputTransform(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnIgnoreOutputTransform( data, type, event ); + return windowBase->OnIgnoreOutputTransform(data, type, event); } return ECORE_CALLBACK_PASS_ON; @@ -263,13 +259,13 @@ static Eina_Bool EcoreEventIgnoreOutputTransform( void* data, int type, void* ev /** * Called when rotate event is recevied. */ -static Eina_Bool EcoreEventRotate( void* data, int type, void* event ) +static Eina_Bool EcoreEventRotate(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - DALI_LOG_RELEASE_INFO( "WindowBaseEcoreWl::EcoreEventRotate\n" ); - windowBase->OnRotation( data, type, event ); + DALI_LOG_RELEASE_INFO("WindowBaseEcoreWl::EcoreEventRotate\n"); + windowBase->OnRotation(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -281,12 +277,12 @@ static Eina_Bool EcoreEventRotate( void* data, int type, void* event ) /** * Called when a touch down is received. */ -static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonDown(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonDown( data, type, event ); + windowBase->OnMouseButtonDown(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -294,12 +290,12 @@ static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event ) /** * Called when a touch up is received. */ -static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonUp(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonUp( data, type, event ); + windowBase->OnMouseButtonUp(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -307,12 +303,12 @@ static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event ) /** * Called when a touch motion is received. */ -static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonMove(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonMove( data, type, event ); + windowBase->OnMouseButtonMove(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -320,12 +316,12 @@ static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event ) /** * Called when a touch is canceled. */ -static Eina_Bool EcoreEventMouseButtonCancel( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonCancel(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonCancel( data, type, event ); + windowBase->OnMouseButtonCancel(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -333,12 +329,12 @@ static Eina_Bool EcoreEventMouseButtonCancel( void* data, int type, void* event /** * Called when a mouse wheel is received. */ -static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseWheel(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseWheel( data, type, event ); + windowBase->OnMouseWheel(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -346,12 +342,12 @@ static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event ) /** * Called when a detent rotation event is recevied. */ -static Eina_Bool EcoreEventDetentRotation( void* data, int type, void* event ) +static Eina_Bool EcoreEventDetentRotation(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnDetentRotation( data, type, event ); + windowBase->OnDetentRotation(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -363,12 +359,12 @@ static Eina_Bool EcoreEventDetentRotation( void* data, int type, void* event ) /** * Called when a key down is received. */ -static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event ) +static Eina_Bool EcoreEventKeyDown(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnKeyDown( data, type, event ); + windowBase->OnKeyDown(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -376,12 +372,12 @@ static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event ) /** * Called when a key up is received. */ -static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event ) +static Eina_Bool EcoreEventKeyUp(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnKeyUp( data, type, event ); + windowBase->OnKeyUp(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -393,12 +389,12 @@ static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event ) /** * Called when the source window notifies us the content in clipboard is selected. */ -static Eina_Bool EcoreEventDataSend( void* data, int type, void* event ) +static Eina_Bool EcoreEventDataSend(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnDataSend( data, type, event ); + windowBase->OnDataSend(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -407,12 +403,12 @@ static Eina_Bool EcoreEventDataSend( void* data, int type, void* event ) * Called when the source window sends us about the selected content. * For example, when item is selected in the clipboard. */ -static Eina_Bool EcoreEventDataReceive( void* data, int type, void* event ) +static Eina_Bool EcoreEventDataReceive(void* data, int type, void* event) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnDataReceive( data, type, event ); + windowBase->OnDataReceive(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -424,10 +420,10 @@ static Eina_Bool EcoreEventDataReceive( void* data, int type, void* event ) /** * Called when a font name is changed. */ -static void VconfNotifyFontNameChanged( keynode_t* node, void* data ) +static void VconfNotifyFontNameChanged(keynode_t* node, void* data) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { windowBase->OnFontNameChanged(); } @@ -436,10 +432,10 @@ static void VconfNotifyFontNameChanged( keynode_t* node, void* data ) /** * Called when a font size is changed. */ -static void VconfNotifyFontSizeChanged( keynode_t* node, void* data ) +static void VconfNotifyFontSizeChanged(keynode_t* node, void* data) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { windowBase->OnFontSizeChanged(); } @@ -451,117 +447,114 @@ static void VconfNotifyFontSizeChanged( keynode_t* node, void* data ) #ifdef DALI_ELDBUS_AVAILABLE // Callback for Ecore ElDBus accessibility events. -static void EcoreElDBusAccessibilityNotification( void* context, const Eldbus_Message* message ) +static void EcoreElDBusAccessibilityNotification(void* context, const Eldbus_Message* message) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( context ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(context); + if(windowBase) { - windowBase->OnEcoreElDBusAccessibilityNotification( context, message ); + windowBase->OnEcoreElDBusAccessibilityNotification(context, message); } } #endif // DALI_ELDBUS_AVAILABLE -static void RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version ) +static void RegistryGlobalCallback(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->RegistryGlobalCallback( data, registry, name, interface, version ); + windowBase->RegistryGlobalCallback(data, registry, name, interface, version); } } -static void RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id ) +static void RegistryGlobalCallbackRemove(void* data, struct wl_registry* registry, uint32_t id) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->RegistryGlobalCallbackRemove( data, registry, id ); + windowBase->RegistryGlobalCallbackRemove(data, registry, id); } } -static void TizenPolicyConformant( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t isConformant ) +static void TizenPolicyConformant(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t isConformant) { } -static void TizenPolicyConformantArea( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h ) +static void TizenPolicyConformantArea(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h) { } -static void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state ) +static void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->TizenPolicyNotificationChangeDone( data, tizenPolicy, surface, level, state ); + windowBase->TizenPolicyNotificationChangeDone(data, tizenPolicy, surface, level, state); } } -static void TizenPolicyTransientForDone( void* data, struct tizen_policy* tizenPolicy, uint32_t childId ) +static void TizenPolicyTransientForDone(void* data, struct tizen_policy* tizenPolicy, uint32_t childId) { } -static void TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state ) +static void TizenPolicyScreenModeChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->TizenPolicyScreenModeChangeDone( data, tizenPolicy, surface, mode, state ); + windowBase->TizenPolicyScreenModeChangeDone(data, tizenPolicy, surface, mode, state); } } -static void TizenPolicyIconifyStateChanged( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t iconified, uint32_t force ) +static void TizenPolicyIconifyStateChanged(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t iconified, uint32_t force) { } -static void TizenPolicySupportedAuxiliaryHints( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, struct wl_array* hints, uint32_t numNints ) +static void TizenPolicySupportedAuxiliaryHints(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, struct wl_array* hints, uint32_t numNints) { } -static void TizenPolicyAllowedAuxiliaryHint( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int id ) +static void TizenPolicyAllowedAuxiliaryHint(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int id) { } -static void TizenPolicyAuxiliaryMessage( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, const char* key, const char* val, struct wl_array* options ) +static void TizenPolicyAuxiliaryMessage(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, const char* key, const char* val, struct wl_array* options) { } -static void TizenPolicyConformantRegion( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t serial ) +static void TizenPolicyConformantRegion(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t serial) { } -static void DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state ) +static void DisplayPolicyBrightnessChangeDone(void* data, struct tizen_display_policy* displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state) { - WindowBaseEcoreWl* windowBase = static_cast< WindowBaseEcoreWl* >( data ); - if( windowBase ) + WindowBaseEcoreWl* windowBase = static_cast(data); + if(windowBase) { - windowBase->DisplayPolicyBrightnessChangeDone( data, displayPolicy, surface, brightness, state ); + windowBase->DisplayPolicyBrightnessChangeDone(data, displayPolicy, surface, brightness, state); } } const struct wl_registry_listener registryListener = -{ - RegistryGlobalCallback, - RegistryGlobalCallbackRemove -}; + { + RegistryGlobalCallback, + RegistryGlobalCallbackRemove}; const struct tizen_policy_listener tizenPolicyListener = -{ - TizenPolicyConformant, - TizenPolicyConformantArea, - TizenPolicyNotificationChangeDone, - TizenPolicyTransientForDone, - TizenPolicyScreenModeChangeDone, - TizenPolicyIconifyStateChanged, - TizenPolicySupportedAuxiliaryHints, - TizenPolicyAllowedAuxiliaryHint, - TizenPolicyAuxiliaryMessage, - TizenPolicyConformantRegion -}; + { + TizenPolicyConformant, + TizenPolicyConformantArea, + TizenPolicyNotificationChangeDone, + TizenPolicyTransientForDone, + TizenPolicyScreenModeChangeDone, + TizenPolicyIconifyStateChanged, + TizenPolicySupportedAuxiliaryHints, + TizenPolicyAllowedAuxiliaryHint, + TizenPolicyAuxiliaryMessage, + TizenPolicyConformantRegion}; const struct tizen_display_policy_listener tizenDisplayPolicyListener = -{ - DisplayPolicyBrightnessChangeDone -}; + { + DisplayPolicyBrightnessChangeDone}; } // unnamed namespace @@ -600,52 +593,52 @@ WindowBaseEcoreWl::WindowBaseEcoreWl(Dali::PositionSize positionSize, Any surfac WindowBaseEcoreWl::~WindowBaseEcoreWl() { #ifdef DALI_ELDBUS_AVAILABLE - // Close down ElDBus connections. - if( mSystemConnection ) - { - eldbus_connection_unref( mSystemConnection ); - } + // Close down ElDBus connections. + if(mSystemConnection) + { + eldbus_connection_unref(mSystemConnection); + } #endif // DALI_ELDBUS_AVAILABLE - vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged ); - vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged ); + vconf_ignore_key_changed(VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged); + vconf_ignore_key_changed(DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged); - for( Dali::Vector< Ecore_Event_Handler* >::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter ) + for(Dali::Vector::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter) { - ecore_event_handler_del( *iter ); + ecore_event_handler_del(*iter); } mEcoreEventHandler.Clear(); - if( mEventQueue ) + if(mEventQueue) { - wl_event_queue_destroy( mEventQueue ); + wl_event_queue_destroy(mEventQueue); } mSupportedAuxiliaryHints.clear(); mAuxiliaryHints.clear(); - if( mEglWindow != NULL ) + if(mEglWindow != NULL) { - wl_egl_window_destroy( mEglWindow ); + wl_egl_window_destroy(mEglWindow); mEglWindow = NULL; } - if( mOwnSurface ) + if(mOwnSurface) { - ecore_wl_window_free( mEcoreWindow ); + ecore_wl_window_free(mEcoreWindow); WindowSystem::Shutdown(); } } -void WindowBaseEcoreWl::Initialize( PositionSize positionSize, Any surface, bool isTransparent ) +void WindowBaseEcoreWl::Initialize(PositionSize positionSize, Any surface, bool isTransparent) { - if( surface.Empty() == false ) + if(surface.Empty() == false) { // check we have a valid type - DALI_ASSERT_ALWAYS( ( surface.GetType() == typeid (Ecore_Wl_Window *) ) && "Surface type is invalid" ); + DALI_ASSERT_ALWAYS((surface.GetType() == typeid(Ecore_Wl_Window*)) && "Surface type is invalid"); - mEcoreWindow = AnyCast< Ecore_Wl_Window* >( surface ); + mEcoreWindow = AnyCast(surface); } else { @@ -653,98 +646,98 @@ void WindowBaseEcoreWl::Initialize( PositionSize positionSize, Any surface, bool WindowSystem::Initialize(); mOwnSurface = true; - CreateWindow( positionSize ); + CreateWindow(positionSize); } - mWlSurface = ecore_wl_window_surface_create( mEcoreWindow ); + mWlSurface = ecore_wl_window_surface_create(mEcoreWindow); - SetTransparency( isTransparent ); + SetTransparency(isTransparent); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_WINDOW_ICONIFY_STATE_CHANGE, EcoreEventWindowIconifyStateChanged, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_OUTPUT_TRANSFORM, EcoreEventOutputTransform, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_IGNORE_OUTPUT_TRANSFORM, EcoreEventIgnoreOutputTransform, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_WINDOW_ICONIFY_STATE_CHANGE, EcoreEventWindowIconifyStateChanged, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_OUTPUT_TRANSFORM, EcoreEventOutputTransform, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_IGNORE_OUTPUT_TRANSFORM, EcoreEventIgnoreOutputTransform, this)); // Register Rotate event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_WINDOW_ROTATE, EcoreEventRotate, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_WINDOW_ROTATE, EcoreEventRotate, this)); // Register Touch events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_CANCEL, EcoreEventMouseButtonCancel, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_CANCEL, EcoreEventMouseButtonCancel, this)); // Register Mouse wheel events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this)); // Register Detent event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_DETENT_ROTATE, EcoreEventDetentRotation, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_DETENT_ROTATE, EcoreEventDetentRotation, this)); // Register Key events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this)); // Register Selection event - clipboard selection - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_DATA_SOURCE_SEND, EcoreEventDataSend, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL_EVENT_SELECTION_DATA_READY, EcoreEventDataReceive, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_DATA_SOURCE_SEND, EcoreEventDataSend, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL_EVENT_SELECTION_DATA_READY, EcoreEventDataReceive, this)); // Register Vconf notify - font name and size - vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged, this ); - vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, this ); + vconf_notify_key_changed(DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged, this); + vconf_notify_key_changed(VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, this); InitializeEcoreElDBus(); mDisplay = ecore_wl_display_get(); - if( mDisplay ) + if(mDisplay) { - wl_display* displayWrapper = static_cast< wl_display* >( wl_proxy_create_wrapper( mDisplay ) ); - if( displayWrapper ) + wl_display* displayWrapper = static_cast(wl_proxy_create_wrapper(mDisplay)); + if(displayWrapper) { - mEventQueue = wl_display_create_queue( mDisplay ); - if( mEventQueue ) + mEventQueue = wl_display_create_queue(mDisplay); + if(mEventQueue) { - wl_proxy_set_queue( reinterpret_cast< wl_proxy* >( displayWrapper ), mEventQueue ); + wl_proxy_set_queue(reinterpret_cast(displayWrapper), mEventQueue); - wl_registry* registry = wl_display_get_registry( displayWrapper ); - wl_registry_add_listener( registry, ®istryListener, this ); + wl_registry* registry = wl_display_get_registry(displayWrapper); + wl_registry_add_listener(registry, ®istryListener, this); } - wl_proxy_wrapper_destroy( displayWrapper ); + wl_proxy_wrapper_destroy(displayWrapper); } } // get auxiliary hint - Eina_List* hints = ecore_wl_window_aux_hints_supported_get( mEcoreWindow ); - if( hints ) + Eina_List* hints = ecore_wl_window_aux_hints_supported_get(mEcoreWindow); + if(hints) { - Eina_List* l = NULL; - char* hint = NULL; + Eina_List* l = NULL; + char* hint = NULL; - for( l = hints, ( hint = static_cast< char* >( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( hint = static_cast< char* >( eina_list_data_get(l) ) ) ) + for(l = hints, (hint = static_cast(eina_list_data_get(l))); l; l = eina_list_next(l), (hint = static_cast(eina_list_data_get(l)))) { - mSupportedAuxiliaryHints.push_back( hint ); + mSupportedAuxiliaryHints.push_back(hint); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::Initialize: %s\n", hint ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::Initialize: %s\n", hint); } } } -Eina_Bool WindowBaseEcoreWl::OnIconifyStateChanged( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl::OnIconifyStateChanged(void* data, int type, void* event) { - Ecore_Wl_Event_Window_Iconify_State_Change* iconifyChangedEvent( static_cast< Ecore_Wl_Event_Window_Iconify_State_Change* >( event ) ); - Eina_Bool handled( ECORE_CALLBACK_PASS_ON ); + Ecore_Wl_Event_Window_Iconify_State_Change* iconifyChangedEvent(static_cast(event)); + Eina_Bool handled(ECORE_CALLBACK_PASS_ON); - if( iconifyChangedEvent->win == static_cast< unsigned int>( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(iconifyChangedEvent->win == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - if( iconifyChangedEvent->iconified == EINA_TRUE ) + if(iconifyChangedEvent->iconified == EINA_TRUE) { - mIconifyChangedSignal.Emit( true ); + mIconifyChangedSignal.Emit(true); } else { - mIconifyChangedSignal.Emit( false ); + mIconifyChangedSignal.Emit(false); } handled = ECORE_CALLBACK_DONE; } @@ -752,41 +745,41 @@ Eina_Bool WindowBaseEcoreWl::OnIconifyStateChanged( void* data, int type, void* return handled; } -Eina_Bool WindowBaseEcoreWl::OnFocusIn( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl::OnFocusIn(void* data, int type, void* event) { - Ecore_Wl_Event_Focus_In* focusInEvent( static_cast< Ecore_Wl_Event_Focus_In* >( event ) ); + Ecore_Wl_Event_Focus_In* focusInEvent(static_cast(event)); - if( focusInEvent->win == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(focusInEvent->win == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n"); - mFocusChangedSignal.Emit( true ); + mFocusChangedSignal.Emit(true); } return ECORE_CALLBACK_PASS_ON; } -Eina_Bool WindowBaseEcoreWl::OnFocusOut( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl::OnFocusOut(void* data, int type, void* event) { - Ecore_Wl_Event_Focus_Out* focusOutEvent( static_cast< Ecore_Wl_Event_Focus_Out* >( event ) ); + Ecore_Wl_Event_Focus_Out* focusOutEvent(static_cast(event)); - if( focusOutEvent->win == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(focusOutEvent->win == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n"); - mFocusChangedSignal.Emit( false ); + mFocusChangedSignal.Emit(false); } return ECORE_CALLBACK_PASS_ON; } -Eina_Bool WindowBaseEcoreWl::OnOutputTransform( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl::OnOutputTransform(void* data, int type, void* event) { - Ecore_Wl_Event_Output_Transform* transformEvent( static_cast< Ecore_Wl_Event_Output_Transform* >( event ) ); + Ecore_Wl_Event_Output_Transform* transformEvent(static_cast(event)); - if( transformEvent->output == ecore_wl_window_output_find( mEcoreWindow ) ) + if(transformEvent->output == ecore_wl_window_output_find(mEcoreWindow)) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventOutputTransform\n", mEcoreWindow ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventOutputTransform\n", mEcoreWindow); mOutputTransformedSignal.Emit(); } @@ -794,13 +787,13 @@ Eina_Bool WindowBaseEcoreWl::OnOutputTransform( void* data, int type, void* even return ECORE_CALLBACK_PASS_ON; } -Eina_Bool WindowBaseEcoreWl::OnIgnoreOutputTransform( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl::OnIgnoreOutputTransform(void* data, int type, void* event) { - Ecore_Wl_Event_Ignore_Output_Transform* ignoreTransformEvent( static_cast< Ecore_Wl_Event_Ignore_Output_Transform* >( event ) ); + Ecore_Wl_Event_Ignore_Output_Transform* ignoreTransformEvent(static_cast(event)); - if( ignoreTransformEvent->win == mEcoreWindow ) + if(ignoreTransformEvent->win == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventIgnoreOutputTransform\n", mEcoreWindow ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventIgnoreOutputTransform\n", mEcoreWindow); mOutputTransformedSignal.Emit(); } @@ -808,381 +801,381 @@ Eina_Bool WindowBaseEcoreWl::OnIgnoreOutputTransform( void* data, int type, void return ECORE_CALLBACK_PASS_ON; } -void WindowBaseEcoreWl::OnRotation( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnRotation(void* data, int type, void* event) { - Ecore_Wl_Event_Window_Rotate* ev( static_cast< Ecore_Wl_Event_Window_Rotate* >( event ) ); + Ecore_Wl_Event_Window_Rotate* ev(static_cast(event)); - if( ev->win == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(ev->win == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - DALI_LOG_RELEASE_INFO( "WindowBaseEcoreWl::OnRotation, angle: %d, width: %d, height: %d\n", ev->angle, ev->w, ev->h ); + DALI_LOG_RELEASE_INFO("WindowBaseEcoreWl::OnRotation, angle: %d, width: %d, height: %d\n", ev->angle, ev->w, ev->h); RotationEvent rotationEvent; - rotationEvent.angle = ev->angle; + rotationEvent.angle = ev->angle; rotationEvent.winResize = 0; - if( ev->angle == 0 || ev->angle == 180 ) + if(ev->angle == 0 || ev->angle == 180) { - rotationEvent.width = ev->w; + rotationEvent.width = ev->w; rotationEvent.height = ev->h; } else { - rotationEvent.width = ev->h; + rotationEvent.width = ev->h; rotationEvent.height = ev->w; } - mRotationSignal.Emit( rotationEvent ); + mRotationSignal.Emit(rotationEvent); } } -void WindowBaseEcoreWl::OnMouseButtonDown( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnMouseButtonDown(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - PointState::Type state ( PointState::DOWN ); + PointState::Type state(PointState::DOWN); // Check if the buttons field is set and ensure it's the primary touch button. // If this event was triggered by buttons other than the primary button (used for touch), then // just send an interrupted event to Core. - if( touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID ) ) + if(touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID)) { state = PointState::INTERRUPTED; } - Device::Class::Type deviceClass; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass ); + GetDeviceClass(ecore_device_class_get(touchEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(touchEvent->dev), deviceSubclass); Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( state ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - point.SetDeviceClass( deviceClass ); - point.SetDeviceSubclass( deviceSubclass ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(state); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + point.SetDeviceClass(deviceClass); + point.SetDeviceSubclass(deviceSubclass); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreWl::OnMouseButtonUp( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnMouseButtonUp(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - Device::Class::Type deviceClass; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass ); + GetDeviceClass(ecore_device_class_get(touchEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(touchEvent->dev), deviceSubclass); Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::UP ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - point.SetDeviceClass( deviceClass ); - point.SetDeviceSubclass( deviceSubclass ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::UP); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + point.SetDeviceClass(deviceClass); + point.SetDeviceSubclass(deviceSubclass); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreWl::OnMouseButtonMove( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnMouseButtonMove(void* data, int type, void* event) { - Ecore_Event_Mouse_Move* touchEvent = static_cast< Ecore_Event_Mouse_Move* >( event ); + Ecore_Event_Mouse_Move* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - Device::Class::Type deviceClass; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass ); + GetDeviceClass(ecore_device_class_get(touchEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(touchEvent->dev), deviceSubclass); Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::MOTION ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - point.SetDeviceClass( deviceClass ); - point.SetDeviceSubclass( deviceSubclass ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::MOTION); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + point.SetDeviceClass(deviceClass); + point.SetDeviceSubclass(deviceSubclass); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreWl::OnMouseButtonCancel( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnMouseButtonCancel(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::INTERRUPTED ); - point.SetScreenPosition( Vector2( 0.0f, 0.0f ) ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::INTERRUPTED); + point.SetScreenPosition(Vector2(0.0f, 0.0f)); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnMouseButtonCancel\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnMouseButtonCancel\n"); } } -void WindowBaseEcoreWl::OnMouseWheel( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnMouseWheel(void* data, int type, void* event) { - Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast< Ecore_Event_Mouse_Wheel* >( event ); + Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast(event); - if( mouseWheelEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(mouseWheelEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z); - Integration::WheelEvent wheelEvent( Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2( mouseWheelEvent->x, mouseWheelEvent->y ), mouseWheelEvent->z, mouseWheelEvent->timestamp ); + Integration::WheelEvent wheelEvent(Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(mouseWheelEvent->x, mouseWheelEvent->y), mouseWheelEvent->z, mouseWheelEvent->timestamp); - mWheelEventSignal.Emit( wheelEvent ); + mWheelEventSignal.Emit(wheelEvent); } } -void WindowBaseEcoreWl::OnDetentRotation( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnDetentRotation(void* data, int type, void* event) { - Ecore_Event_Detent_Rotate* detentEvent = static_cast< Ecore_Event_Detent_Rotate* >( event ); + Ecore_Event_Detent_Rotate* detentEvent = static_cast(event); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::OnDetentRotation\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::OnDetentRotation\n"); - int direction = ( detentEvent->direction == ECORE_DETENT_DIRECTION_CLOCKWISE ) ? 1 : -1; + int direction = (detentEvent->direction == ECORE_DETENT_DIRECTION_CLOCKWISE) ? 1 : -1; int timeStamp = detentEvent->timestamp; - Integration::WheelEvent wheelEvent( Integration::WheelEvent::CUSTOM_WHEEL, 0, 0, Vector2( 0.0f, 0.0f ), direction, timeStamp ); + Integration::WheelEvent wheelEvent(Integration::WheelEvent::CUSTOM_WHEEL, 0, 0, Vector2(0.0f, 0.0f), direction, timeStamp); - mWheelEventSignal.Emit( wheelEvent ); + mWheelEventSignal.Emit(wheelEvent); } -void WindowBaseEcoreWl::OnKeyDown( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnKeyDown(void* data, int type, void* event) { - Ecore_Event_Key* keyEvent = static_cast< Ecore_Event_Key* >( event ); + Ecore_Event_Key* keyEvent = static_cast(event); - if( keyEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(keyEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnKeyDown\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnKeyDown\n"); - std::string keyName( keyEvent->keyname ); - std::string logicalKey( "" ); - std::string keyString( "" ); - std::string compose( "" ); + std::string keyName(keyEvent->keyname); + std::string logicalKey(""); + std::string keyString(""); + std::string compose(""); // Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string. - if( keyEvent->compose ) + if(keyEvent->compose) { compose = keyEvent->compose; } // Ensure key symbol is not NULL as keys like SHIFT have a null string. - if( keyEvent->key ) + if(keyEvent->key) { logicalKey = keyEvent->key; } - int keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname ); - keyCode = ( keyCode == -1 ) ? 0 : keyCode; - int modifier( keyEvent->modifiers ); + int keyCode = KeyLookup::GetDaliKeyCode(keyEvent->keyname); + keyCode = (keyCode == -1) ? 0 : keyCode; + int modifier(keyEvent->modifiers); unsigned long time = keyEvent->timestamp; - if( !strncmp( keyEvent->keyname, "Keycode-", 8 ) ) + if(!strncmp(keyEvent->keyname, "Keycode-", 8)) { - keyCode = atoi( keyEvent->keyname + 8 ); + keyCode = atoi(keyEvent->keyname + 8); } // Ensure key event string is not NULL as keys like SHIFT have a null string. - if( keyEvent->string ) + if(keyEvent->string) { keyString = keyEvent->string; } - std::string deviceName; - Device::Class::Type deviceClass; + std::string deviceName; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceName( keyEvent, deviceName ); - GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass ); + GetDeviceName(keyEvent, deviceName); + GetDeviceClass(ecore_device_class_get(keyEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(keyEvent->dev), deviceSubclass); - Integration::KeyEvent keyEvent( keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, deviceName, deviceClass, deviceSubclass ); + Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, deviceName, deviceClass, deviceSubclass); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseEcoreWl::OnKeyUp( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnKeyUp(void* data, int type, void* event) { - Ecore_Event_Key* keyEvent = static_cast< Ecore_Event_Key* >( event ); + Ecore_Event_Key* keyEvent = static_cast(event); - if( keyEvent->window == static_cast< unsigned int >( ecore_wl_window_id_get( mEcoreWindow ) ) ) + if(keyEvent->window == static_cast(ecore_wl_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnKeyUp\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnKeyUp\n"); #if defined(ECORE_VERSION_MAJOR) && (ECORE_VERSION_MAJOR >= 1) && defined(ECORE_VERSION_MINOR) && (ECORE_VERSION_MINOR >= 23) // Cancel processing flag is sent because this key event will combine with the previous key. So, the event should not actually perform anything. - if( keyEvent->event_flags & ECORE_EVENT_FLAG_CANCEL ) + if(keyEvent->event_flags & ECORE_EVENT_FLAG_CANCEL) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnKeyUp: This event flag indicates the event is canceled. \n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::OnKeyUp: This event flag indicates the event is canceled. \n"); return; } #endif // Since ecore 1.23 version - std::string keyName( keyEvent->keyname ); - std::string logicalKey( "" ); - std::string keyString( "" ); - std::string compose( "" ); + std::string keyName(keyEvent->keyname); + std::string logicalKey(""); + std::string keyString(""); + std::string compose(""); // Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string. - if( keyEvent->compose ) + if(keyEvent->compose) { compose = keyEvent->compose; } // Ensure key symbol is not NULL as keys like SHIFT have a null string. - if( keyEvent->key ) + if(keyEvent->key) { logicalKey = keyEvent->key; } - int keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname ); - keyCode = ( keyCode == -1 ) ? 0 : keyCode; - int modifier( keyEvent->modifiers ); + int keyCode = KeyLookup::GetDaliKeyCode(keyEvent->keyname); + keyCode = (keyCode == -1) ? 0 : keyCode; + int modifier(keyEvent->modifiers); unsigned long time = keyEvent->timestamp; - if( !strncmp( keyEvent->keyname, "Keycode-", 8 ) ) + if(!strncmp(keyEvent->keyname, "Keycode-", 8)) { - keyCode = atoi( keyEvent->keyname + 8 ); + keyCode = atoi(keyEvent->keyname + 8); } // Ensure key event string is not NULL as keys like SHIFT have a null string. - if( keyEvent->string ) + if(keyEvent->string) { keyString = keyEvent->string; } - std::string deviceName; - Device::Class::Type deviceClass; + std::string deviceName; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceName( keyEvent, deviceName ); - GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass ); + GetDeviceName(keyEvent, deviceName); + GetDeviceClass(ecore_device_class_get(keyEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(keyEvent->dev), deviceSubclass); - Integration::KeyEvent keyEvent( keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, deviceName, deviceClass, deviceSubclass ); + Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, deviceName, deviceClass, deviceSubclass); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseEcoreWl::OnDataSend( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnDataSend(void* data, int type, void* event) { - mSelectionDataSendSignal.Emit( event ); + mSelectionDataSendSignal.Emit(event); } -void WindowBaseEcoreWl::OnDataReceive( void* data, int type, void* event ) +void WindowBaseEcoreWl::OnDataReceive(void* data, int type, void* event) { - mSelectionDataReceivedSignal.Emit( event ); + mSelectionDataReceivedSignal.Emit(event); } void WindowBaseEcoreWl::OnFontNameChanged() { - mStyleChangedSignal.Emit( StyleChange::DEFAULT_FONT_CHANGE ); + mStyleChangedSignal.Emit(StyleChange::DEFAULT_FONT_CHANGE); } void WindowBaseEcoreWl::OnFontSizeChanged() { - mStyleChangedSignal.Emit( StyleChange::DEFAULT_FONT_SIZE_CHANGE ); + mStyleChangedSignal.Emit(StyleChange::DEFAULT_FONT_SIZE_CHANGE); } -void WindowBaseEcoreWl::OnEcoreElDBusAccessibilityNotification( void* context, const Eldbus_Message* message ) +void WindowBaseEcoreWl::OnEcoreElDBusAccessibilityNotification(void* context, const Eldbus_Message* message) { #ifdef DALI_ELDBUS_AVAILABLE AccessibilityInfo info; // The string defines the arg-list's respective types. - if( !eldbus_message_arguments_get( message, "iiiiiiu", &info.gestureValue, &info.startX, &info.startY, &info.endX, &info.endY, &info.state, &info.eventTime ) ) + if(!eldbus_message_arguments_get(message, "iiiiiiu", &info.gestureValue, &info.startX, &info.startY, &info.endX, &info.endY, &info.state, &info.eventTime)) { - DALI_LOG_ERROR( "OnEcoreElDBusAccessibilityNotification: Error getting arguments\n" ); + DALI_LOG_ERROR("OnEcoreElDBusAccessibilityNotification: Error getting arguments\n"); } - mAccessibilitySignal.Emit( info ); + mAccessibilitySignal.Emit(info); #endif } -void WindowBaseEcoreWl::RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version ) +void WindowBaseEcoreWl::RegistryGlobalCallback(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { - if( strcmp( interface, tizen_policy_interface.name ) == 0 ) + if(strcmp(interface, tizen_policy_interface.name) == 0) { - uint32_t clientVersion = std::min( version, MAX_TIZEN_CLIENT_VERSION ); + uint32_t clientVersion = std::min(version, MAX_TIZEN_CLIENT_VERSION); - mTizenPolicy = static_cast< tizen_policy* >( wl_registry_bind( registry, name, &tizen_policy_interface, clientVersion ) ); - if( !mTizenPolicy ) + mTizenPolicy = static_cast(wl_registry_bind(registry, name, &tizen_policy_interface, clientVersion)); + if(!mTizenPolicy) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: wl_registry_bind(tizen_policy_interface) is failed.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: wl_registry_bind(tizen_policy_interface) is failed.\n"); return; } - tizen_policy_add_listener( mTizenPolicy, &tizenPolicyListener, data ); + tizen_policy_add_listener(mTizenPolicy, &tizenPolicyListener, data); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: tizen_policy_add_listener is called.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: tizen_policy_add_listener is called.\n"); } - else if( strcmp( interface, tizen_display_policy_interface.name ) == 0 ) + else if(strcmp(interface, tizen_display_policy_interface.name) == 0) { - mTizenDisplayPolicy = static_cast< tizen_display_policy* >( wl_registry_bind( registry, name, &tizen_display_policy_interface, version ) ); - if( !mTizenDisplayPolicy ) + mTizenDisplayPolicy = static_cast(wl_registry_bind(registry, name, &tizen_display_policy_interface, version)); + if(!mTizenDisplayPolicy) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: wl_registry_bind(tizen_display_policy_interface) is failed.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: wl_registry_bind(tizen_display_policy_interface) is failed.\n"); return; } - tizen_display_policy_add_listener( mTizenDisplayPolicy, &tizenDisplayPolicyListener, data ); + tizen_display_policy_add_listener(mTizenDisplayPolicy, &tizenDisplayPolicyListener, data); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: tizen_display_policy_add_listener is called.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::RegistryGlobalCallback: tizen_display_policy_add_listener is called.\n"); } } -void WindowBaseEcoreWl::RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id ) +void WindowBaseEcoreWl::RegistryGlobalCallbackRemove(void* data, struct wl_registry* registry, uint32_t id) { - mTizenPolicy = NULL; + mTizenPolicy = NULL; mTizenDisplayPolicy = NULL; } -void WindowBaseEcoreWl::TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state ) +void WindowBaseEcoreWl::TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state) { - mNotificationLevel = level; - mNotificationChangeState = state; + mNotificationLevel = level; + mNotificationChangeState = state; mNotificationLevelChangeDone = true; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::TizenPolicyNotificationChangeDone: level = %d, state = %d\n", level, state ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::TizenPolicyNotificationChangeDone: level = %d, state = %d\n", level, state); } -void WindowBaseEcoreWl::TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state ) +void WindowBaseEcoreWl::TizenPolicyScreenModeChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state) { - mScreenOffMode = mode; + mScreenOffMode = mode; mScreenOffModeChangeState = state; - mScreenOffModeChangeDone = true; + mScreenOffModeChangeDone = true; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::TizenPolicyScreenModeChangeDone: mode = %d, state = %d\n", mode, state ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::TizenPolicyScreenModeChangeDone: mode = %d, state = %d\n", mode, state); } -void WindowBaseEcoreWl::DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state ) +void WindowBaseEcoreWl::DisplayPolicyBrightnessChangeDone(void* data, struct tizen_display_policy* displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state) { - mBrightness = brightness; + mBrightness = brightness; mBrightnessChangeState = state; - mBrightnessChangeDone = true; + mBrightnessChangeDone = true; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::DisplayPolicyBrightnessChangeDone: brightness = %d, state = %d\n", brightness, state ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl::DisplayPolicyBrightnessChangeDone: brightness = %d, state = %d\n", brightness, state); } Any WindowBaseEcoreWl::GetNativeWindow() @@ -1192,30 +1185,30 @@ Any WindowBaseEcoreWl::GetNativeWindow() int WindowBaseEcoreWl::GetNativeWindowId() { - return ecore_wl_window_id_get( mEcoreWindow ); + return ecore_wl_window_id_get(mEcoreWindow); } -EGLNativeWindowType WindowBaseEcoreWl::CreateEglWindow( int width, int height ) +EGLNativeWindowType WindowBaseEcoreWl::CreateEglWindow(int width, int height) { - mEglWindow = wl_egl_window_create( mWlSurface, width, height ); + mEglWindow = wl_egl_window_create(mWlSurface, width, height); - return static_cast< EGLNativeWindowType >( mEglWindow ); + return static_cast(mEglWindow); } void WindowBaseEcoreWl::DestroyEglWindow() { - if( mEglWindow != NULL ) + if(mEglWindow != NULL) { - wl_egl_window_destroy( mEglWindow ); + wl_egl_window_destroy(mEglWindow); mEglWindow = NULL; } } -void WindowBaseEcoreWl::SetEglWindowRotation( int angle ) +void WindowBaseEcoreWl::SetEglWindowRotation(int angle) { wl_egl_window_rotation rotation; - switch( angle ) + switch(angle) { case 0: { @@ -1244,14 +1237,14 @@ void WindowBaseEcoreWl::SetEglWindowRotation( int angle ) } } - wl_egl_window_set_rotation( mEglWindow, rotation ); + wl_egl_window_set_rotation(mEglWindow, rotation); } -void WindowBaseEcoreWl::SetEglWindowBufferTransform( int angle ) +void WindowBaseEcoreWl::SetEglWindowBufferTransform(int angle) { wl_output_transform bufferTransform; - switch( angle ) + switch(angle) { case 0: { @@ -1280,14 +1273,14 @@ void WindowBaseEcoreWl::SetEglWindowBufferTransform( int angle ) } } - wl_egl_window_set_buffer_transform( mEglWindow, bufferTransform ); + wl_egl_window_set_buffer_transform(mEglWindow, bufferTransform); } -void WindowBaseEcoreWl::SetEglWindowTransform( int angle ) +void WindowBaseEcoreWl::SetEglWindowTransform(int angle) { wl_output_transform windowTransform; - switch( angle ) + switch(angle) { case 0: { @@ -1316,19 +1309,19 @@ void WindowBaseEcoreWl::SetEglWindowTransform( int angle ) } } - wl_egl_window_set_window_transform( mEglWindow, windowTransform ); + wl_egl_window_set_window_transform(mEglWindow, windowTransform); } -void WindowBaseEcoreWl::ResizeEglWindow( PositionSize positionSize ) +void WindowBaseEcoreWl::ResizeEglWindow(PositionSize positionSize) { - wl_egl_window_resize( mEglWindow, positionSize.width, positionSize.height, positionSize.x, positionSize.y ); + wl_egl_window_resize(mEglWindow, positionSize.width, positionSize.height, positionSize.x, positionSize.y); } bool WindowBaseEcoreWl::IsEglWindowRotationSupported() { // Check capability - wl_egl_window_capability capability = static_cast< wl_egl_window_capability >( wl_egl_window_get_capabilities( mEglWindow ) ); - if( capability == WL_EGL_WINDOW_CAPABILITY_ROTATION_SUPPORTED ) + wl_egl_window_capability capability = static_cast(wl_egl_window_get_capabilities(mEglWindow)); + if(capability == WL_EGL_WINDOW_CAPABILITY_ROTATION_SUPPORTED) { mSupportedPreProtation = true; return true; @@ -1337,74 +1330,74 @@ bool WindowBaseEcoreWl::IsEglWindowRotationSupported() return false; } -void WindowBaseEcoreWl::Move( PositionSize positionSize ) +void WindowBaseEcoreWl::Move(PositionSize positionSize) { - ecore_wl_window_position_set( mEcoreWindow, positionSize.x, positionSize.y ); + ecore_wl_window_position_set(mEcoreWindow, positionSize.x, positionSize.y); } -void WindowBaseEcoreWl::Resize( PositionSize positionSize ) +void WindowBaseEcoreWl::Resize(PositionSize positionSize) { - ecore_wl_window_update_size( mEcoreWindow, positionSize.width, positionSize.height ); + ecore_wl_window_update_size(mEcoreWindow, positionSize.width, positionSize.height); } -void WindowBaseEcoreWl::MoveResize( PositionSize positionSize ) +void WindowBaseEcoreWl::MoveResize(PositionSize positionSize) { - ecore_wl_window_position_set( mEcoreWindow, positionSize.x, positionSize.y ); - ecore_wl_window_update_size( mEcoreWindow, positionSize.width, positionSize.height ); + ecore_wl_window_position_set(mEcoreWindow, positionSize.x, positionSize.y); + ecore_wl_window_update_size(mEcoreWindow, positionSize.width, positionSize.height); } -void WindowBaseEcoreWl::SetClass( const std::string& name, const std::string& className ) +void WindowBaseEcoreWl::SetClass(const std::string& name, const std::string& className) { - ecore_wl_window_title_set( mEcoreWindow, name.c_str() ); - ecore_wl_window_class_name_set( mEcoreWindow, className.c_str() ); + ecore_wl_window_title_set(mEcoreWindow, name.c_str()); + ecore_wl_window_class_name_set(mEcoreWindow, className.c_str()); } void WindowBaseEcoreWl::Raise() { // Use ecore_wl_window_activate to prevent the window shown without rendering - ecore_wl_window_activate( mEcoreWindow ); + ecore_wl_window_activate(mEcoreWindow); } void WindowBaseEcoreWl::Lower() { - ecore_wl_window_lower( mEcoreWindow ); + ecore_wl_window_lower(mEcoreWindow); } void WindowBaseEcoreWl::Activate() { - ecore_wl_window_activate( mEcoreWindow ); + ecore_wl_window_activate(mEcoreWindow); } -void WindowBaseEcoreWl::SetAvailableAnlges( const std::vector< int >& angles ) +void WindowBaseEcoreWl::SetAvailableAnlges(const std::vector& angles) { - int rotations[4] = { 0 }; - DALI_LOG_RELEASE_INFO( "WindowBaseEcoreWl::SetAvailableAnlges, angle's count: %d\n", angles.size() ); - for( std::size_t i = 0; i < angles.size(); ++i ) + int rotations[4] = {0}; + DALI_LOG_RELEASE_INFO("WindowBaseEcoreWl::SetAvailableAnlges, angle's count: %d\n", angles.size()); + for(std::size_t i = 0; i < angles.size(); ++i) { - rotations[i] = static_cast< int >( angles[i] ); - DALI_LOG_RELEASE_INFO( "%d ", rotations[i] ); + rotations[i] = static_cast(angles[i]); + DALI_LOG_RELEASE_INFO("%d ", rotations[i]); } - ecore_wl_window_rotation_available_rotations_set( mEcoreWindow, rotations, angles.size() ); + ecore_wl_window_rotation_available_rotations_set(mEcoreWindow, rotations, angles.size()); } -void WindowBaseEcoreWl::SetPreferredAngle( int angle ) +void WindowBaseEcoreWl::SetPreferredAngle(int angle) { - ecore_wl_window_rotation_preferred_rotation_set( mEcoreWindow, angle ); + ecore_wl_window_rotation_preferred_rotation_set(mEcoreWindow, angle); } -void WindowBaseEcoreWl::SetAcceptFocus( bool accept ) +void WindowBaseEcoreWl::SetAcceptFocus(bool accept) { - ecore_wl_window_focus_skip_set( mEcoreWindow, !accept ); + ecore_wl_window_focus_skip_set(mEcoreWindow, !accept); } void WindowBaseEcoreWl::Show() { - ecore_wl_window_show( mEcoreWindow ); + ecore_wl_window_show(mEcoreWindow); } void WindowBaseEcoreWl::Hide() { - ecore_wl_window_hide( mEcoreWindow ); + ecore_wl_window_hide(mEcoreWindow); } unsigned int WindowBaseEcoreWl::GetSupportedAuxiliaryHintCount() const @@ -1412,135 +1405,135 @@ unsigned int WindowBaseEcoreWl::GetSupportedAuxiliaryHintCount() const return mSupportedAuxiliaryHints.size(); } -std::string WindowBaseEcoreWl::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string WindowBaseEcoreWl::GetSupportedAuxiliaryHint(unsigned int index) const { - if( index >= GetSupportedAuxiliaryHintCount() ) + if(index >= GetSupportedAuxiliaryHintCount()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetSupportedAuxiliaryHint: Invalid index! [%d]\n", index ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetSupportedAuxiliaryHint: Invalid index! [%d]\n", index); } return mSupportedAuxiliaryHints[index]; } -unsigned int WindowBaseEcoreWl::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int WindowBaseEcoreWl::AddAuxiliaryHint(const std::string& hint, const std::string& value) { bool supported = false; // Check if the hint is suppported - for( std::vector< std::string >::iterator iter = mSupportedAuxiliaryHints.begin(); iter != mSupportedAuxiliaryHints.end(); ++iter ) + for(std::vector::iterator iter = mSupportedAuxiliaryHints.begin(); iter != mSupportedAuxiliaryHints.end(); ++iter) { - if( *iter == hint ) + if(*iter == hint) { supported = true; break; } } - if( !supported ) + if(!supported) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::AddAuxiliaryHint: Not supported auxiliary hint [%s]\n", hint.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::AddAuxiliaryHint: Not supported auxiliary hint [%s]\n", hint.c_str()); return 0; } // Check if the hint is already added - for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ ) + for(unsigned int i = 0; i < mAuxiliaryHints.size(); i++) { - if( mAuxiliaryHints[i].first == hint ) + if(mAuxiliaryHints[i].first == hint) { // Just change the value mAuxiliaryHints[i].second = value; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::AddAuxiliaryHint: Change! hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), i + 1 ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::AddAuxiliaryHint: Change! hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), i + 1); - return i + 1; // id is index + 1 + return i + 1; // id is index + 1 } } // Add the hint - mAuxiliaryHints.push_back( std::pair< std::string, std::string >( hint, value ) ); + mAuxiliaryHints.push_back(std::pair(hint, value)); unsigned int id = mAuxiliaryHints.size(); - ecore_wl_window_aux_hint_add( mEcoreWindow, static_cast< int >( id ), hint.c_str(), value.c_str() ); + ecore_wl_window_aux_hint_add(mEcoreWindow, static_cast(id), hint.c_str(), value.c_str()); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::AddAuxiliaryHint: hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::AddAuxiliaryHint: hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), id); return id; } -bool WindowBaseEcoreWl::RemoveAuxiliaryHint( unsigned int id ) +bool WindowBaseEcoreWl::RemoveAuxiliaryHint(unsigned int id) { - if( id == 0 || id > mAuxiliaryHints.size() ) + if(id == 0 || id > mAuxiliaryHints.size()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::RemoveAuxiliaryHint: Invalid id [%d]\n", id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::RemoveAuxiliaryHint: Invalid id [%d]\n", id); return false; } mAuxiliaryHints[id - 1].second = std::string(); - ecore_wl_window_aux_hint_del( mEcoreWindow, static_cast< int >( id ) ); + ecore_wl_window_aux_hint_del(mEcoreWindow, static_cast(id)); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::RemoveAuxiliaryHint: id = %d, hint = %s\n", id, mAuxiliaryHints[id - 1].first.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::RemoveAuxiliaryHint: id = %d, hint = %s\n", id, mAuxiliaryHints[id - 1].first.c_str()); return true; } -bool WindowBaseEcoreWl::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool WindowBaseEcoreWl::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { - if( id == 0 || id > mAuxiliaryHints.size() ) + if(id == 0 || id > mAuxiliaryHints.size()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::SetAuxiliaryHintValue: Invalid id [%d]\n", id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::SetAuxiliaryHintValue: Invalid id [%d]\n", id); return false; } mAuxiliaryHints[id - 1].second = value; - ecore_wl_window_aux_hint_change( mEcoreWindow, static_cast< int >( id ), value.c_str() ); + ecore_wl_window_aux_hint_change(mEcoreWindow, static_cast(id), value.c_str()); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str()); return true; } -std::string WindowBaseEcoreWl::GetAuxiliaryHintValue( unsigned int id ) const +std::string WindowBaseEcoreWl::GetAuxiliaryHintValue(unsigned int id) const { - if( id == 0 || id > mAuxiliaryHints.size() ) + if(id == 0 || id > mAuxiliaryHints.size()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::GetAuxiliaryHintValue: Invalid id [%d]\n", id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl::GetAuxiliaryHintValue: Invalid id [%d]\n", id); return std::string(); } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str()); return mAuxiliaryHints[id - 1].second; } -unsigned int WindowBaseEcoreWl::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int WindowBaseEcoreWl::GetAuxiliaryHintId(const std::string& hint) const { - for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ ) + for(unsigned int i = 0; i < mAuxiliaryHints.size(); i++) { - if( mAuxiliaryHints[i].first == hint ) + if(mAuxiliaryHints[i].first == hint) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetAuxiliaryHintId: hint = %s, id = %d\n", hint.c_str(), i + 1 ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetAuxiliaryHintId: hint = %s, id = %d\n", hint.c_str(), i + 1); return i + 1; } } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetAuxiliaryHintId: Invalid hint! [%s]\n", hint.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetAuxiliaryHintId: Invalid hint! [%s]\n", hint.c_str()); return 0; } -void WindowBaseEcoreWl::SetInputRegion( const Rect< int >& inputRegion ) +void WindowBaseEcoreWl::SetInputRegion(const Rect& inputRegion) { - ecore_wl_window_input_region_set( mEcoreWindow, inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height ); + ecore_wl_window_input_region_set(mEcoreWindow, inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height); } -void WindowBaseEcoreWl::SetType( Dali::WindowType type ) +void WindowBaseEcoreWl::SetType(Dali::WindowType type) { Ecore_Wl_Window_Type windowType; - switch( type ) + switch(type) { case Dali::WindowType::NORMAL: { @@ -1569,19 +1562,19 @@ void WindowBaseEcoreWl::SetType( Dali::WindowType type ) } } - ecore_wl_window_type_set( mEcoreWindow, windowType ); + ecore_wl_window_type_set(mEcoreWindow, windowType); } -bool WindowBaseEcoreWl::SetNotificationLevel( Dali::WindowNotificationLevel level ) +bool WindowBaseEcoreWl::SetNotificationLevel(Dali::WindowNotificationLevel level) { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int notificationLevel; - switch( level ) + switch(level) { case Dali::WindowNotificationLevel::NONE: { @@ -1610,67 +1603,67 @@ bool WindowBaseEcoreWl::SetNotificationLevel( Dali::WindowNotificationLevel leve } default: { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: invalid level [%d]\n", level ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: invalid level [%d]\n", level); notificationLevel = TIZEN_POLICY_LEVEL_DEFAULT; break; } } mNotificationLevelChangeDone = false; - mNotificationChangeState = TIZEN_POLICY_ERROR_STATE_NONE; + mNotificationChangeState = TIZEN_POLICY_ERROR_STATE_NONE; - tizen_policy_set_notification_level( mTizenPolicy, ecore_wl_window_surface_get( mEcoreWindow ), notificationLevel ); + tizen_policy_set_notification_level(mTizenPolicy, ecore_wl_window_surface_get(mEcoreWindow), notificationLevel); int count = 0; - while( !mNotificationLevelChangeDone && count < 3 ) + while(!mNotificationLevelChangeDone && count < 3) { ecore_wl_flush(); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mNotificationLevelChangeDone ) + if(!mNotificationLevelChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: Level change is failed [%d, %d]\n", level, mNotificationChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: Level change is failed [%d, %d]\n", level, mNotificationChangeState); return false; } - else if( mNotificationChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED ) + else if(mNotificationChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: Permission denied! [%d]\n", level ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: Permission denied! [%d]\n", level); return false; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: Level is changed [%d]\n", mNotificationLevel ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetNotificationLevel: Level is changed [%d]\n", mNotificationLevel); return true; } Dali::WindowNotificationLevel WindowBaseEcoreWl::GetNotificationLevel() const { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int count = 0; - while( !mNotificationLevelChangeDone && count < 3 ) + while(!mNotificationLevelChangeDone && count < 3) { ecore_wl_flush(); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mNotificationLevelChangeDone ) + if(!mNotificationLevelChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetNotificationLevel: Error! [%d]\n", mNotificationChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetNotificationLevel: Error! [%d]\n", mNotificationChangeState); return Dali::Window::NotificationLevel::NONE; } Dali::WindowNotificationLevel level; - switch( mNotificationLevel ) + switch(mNotificationLevel) { case TIZEN_POLICY_LEVEL_NONE: { @@ -1699,40 +1692,40 @@ Dali::WindowNotificationLevel WindowBaseEcoreWl::GetNotificationLevel() const } default: { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetNotificationLevel: invalid level [%d]\n", mNotificationLevel ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetNotificationLevel: invalid level [%d]\n", mNotificationLevel); level = Dali::WindowNotificationLevel::NONE; break; } } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetNotificationLevel: level [%d]\n", mNotificationLevel ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetNotificationLevel: level [%d]\n", mNotificationLevel); return level; } -void WindowBaseEcoreWl::SetOpaqueState( bool opaque ) +void WindowBaseEcoreWl::SetOpaqueState(bool opaque) { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } - tizen_policy_set_opaque_state( mTizenPolicy, ecore_wl_window_surface_get( mEcoreWindow ), ( opaque ? 1 : 0 ) ); + tizen_policy_set_opaque_state(mTizenPolicy, ecore_wl_window_surface_get(mEcoreWindow), (opaque ? 1 : 0)); } bool WindowBaseEcoreWl::SetScreenOffMode(WindowScreenOffMode screenOffMode) { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } - mScreenOffModeChangeDone = false; + mScreenOffModeChangeDone = false; mScreenOffModeChangeState = TIZEN_POLICY_ERROR_STATE_NONE; unsigned int mode = 0; - switch( screenOffMode ) + switch(screenOffMode) { case WindowScreenOffMode::TIMEOUT: { @@ -1746,58 +1739,58 @@ bool WindowBaseEcoreWl::SetScreenOffMode(WindowScreenOffMode screenOffMode) } } - tizen_policy_set_window_screen_mode( mTizenPolicy, ecore_wl_window_surface_get( mEcoreWindow ), mode ); + tizen_policy_set_window_screen_mode(mTizenPolicy, ecore_wl_window_surface_get(mEcoreWindow), mode); int count = 0; - while( !mScreenOffModeChangeDone && count < 3 ) + while(!mScreenOffModeChangeDone && count < 3) { ecore_wl_flush(); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mScreenOffModeChangeDone ) + if(!mScreenOffModeChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetScreenOffMode: Screen mode change is failed [%d, %d]\n", screenOffMode, mScreenOffModeChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetScreenOffMode: Screen mode change is failed [%d, %d]\n", screenOffMode, mScreenOffModeChangeState); return false; } - else if( mScreenOffModeChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED ) + else if(mScreenOffModeChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetScreenOffMode: Permission denied! [%d]\n", screenOffMode ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetScreenOffMode: Permission denied! [%d]\n", screenOffMode); return false; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetScreenOffMode: Screen mode is changed [%d]\n", mScreenOffMode ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetScreenOffMode: Screen mode is changed [%d]\n", mScreenOffMode); return true; } WindowScreenOffMode WindowBaseEcoreWl::GetScreenOffMode() const { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int count = 0; - while( !mScreenOffModeChangeDone && count < 3 ) + while(!mScreenOffModeChangeDone && count < 3) { ecore_wl_flush(); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mScreenOffModeChangeDone ) + if(!mScreenOffModeChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetScreenOffMode: Error! [%d]\n", mScreenOffModeChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetScreenOffMode: Error! [%d]\n", mScreenOffModeChangeState); return WindowScreenOffMode::TIMEOUT; } WindowScreenOffMode screenMode = WindowScreenOffMode::TIMEOUT; - switch( mScreenOffMode ) + switch(mScreenOffMode) { case 0: { @@ -1811,80 +1804,80 @@ WindowScreenOffMode WindowBaseEcoreWl::GetScreenOffMode() const } } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetScreenOffMode: screen mode [%d]\n", mScreenOffMode ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetScreenOffMode: screen mode [%d]\n", mScreenOffMode); return screenMode; } -bool WindowBaseEcoreWl::SetBrightness( int brightness ) +bool WindowBaseEcoreWl::SetBrightness(int brightness) { - while( !mTizenDisplayPolicy ) + while(!mTizenDisplayPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } - mBrightnessChangeDone = false; + mBrightnessChangeDone = false; mBrightnessChangeState = TIZEN_POLICY_ERROR_STATE_NONE; - tizen_display_policy_set_window_brightness( mTizenDisplayPolicy, ecore_wl_window_surface_get( mEcoreWindow ), brightness ); + tizen_display_policy_set_window_brightness(mTizenDisplayPolicy, ecore_wl_window_surface_get(mEcoreWindow), brightness); int count = 0; - while( !mBrightnessChangeDone && count < 3 ) + while(!mBrightnessChangeDone && count < 3) { ecore_wl_flush(); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mBrightnessChangeDone ) + if(!mBrightnessChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetBrightness: Brightness change is failed [%d, %d]\n", brightness, mBrightnessChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetBrightness: Brightness change is failed [%d, %d]\n", brightness, mBrightnessChangeState); return false; } - else if( mBrightnessChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED ) + else if(mBrightnessChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetBrightness: Permission denied! [%d]\n", brightness ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetBrightness: Permission denied! [%d]\n", brightness); return false; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetBrightness: Brightness is changed [%d]\n", mBrightness ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::SetBrightness: Brightness is changed [%d]\n", mBrightness); return true; } int WindowBaseEcoreWl::GetBrightness() const { - while( !mTizenDisplayPolicy ) + while(!mTizenDisplayPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int count = 0; - while( !mBrightnessChangeDone && count < 3 ) + while(!mBrightnessChangeDone && count < 3) { ecore_wl_flush(); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mBrightnessChangeDone ) + if(!mBrightnessChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetBrightness: Error! [%d]\n", mBrightnessChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetBrightness: Error! [%d]\n", mBrightnessChangeState); return 0; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetBrightness: Brightness [%d]\n", mBrightness ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl::GetBrightness: Brightness [%d]\n", mBrightness); return mBrightness; } -bool WindowBaseEcoreWl::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) +bool WindowBaseEcoreWl::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) { Ecore_Wl_Window_Keygrab_Mode mode; - switch( grabMode ) + switch(grabMode) { case KeyGrab::TOPMOST: { @@ -1912,34 +1905,34 @@ bool WindowBaseEcoreWl::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) } } - return ecore_wl_window_keygrab_set( mEcoreWindow, KeyLookup::GetKeyName( key ), 0, 0, 0, mode ); + return ecore_wl_window_keygrab_set(mEcoreWindow, KeyLookup::GetKeyName(key), 0, 0, 0, mode); } -bool WindowBaseEcoreWl::UngrabKey( Dali::KEY key ) +bool WindowBaseEcoreWl::UngrabKey(Dali::KEY key) { - return ecore_wl_window_keygrab_unset( mEcoreWindow, KeyLookup::GetKeyName( key ), 0, 0 ); + return ecore_wl_window_keygrab_unset(mEcoreWindow, KeyLookup::GetKeyName(key), 0, 0); } -bool WindowBaseEcoreWl::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) +bool WindowBaseEcoreWl::GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) { - int keyCount = key.Count(); + int keyCount = key.Count(); int keyGrabModeCount = grabMode.Count(); - if( keyCount != keyGrabModeCount || keyCount == 0 ) + if(keyCount != keyGrabModeCount || keyCount == 0) { return false; } eina_init(); - Eina_List* keyList = NULL; - Ecore_Wl_Window_Keygrab_Info* info = new Ecore_Wl_Window_Keygrab_Info[keyCount]; + Eina_List* keyList = NULL; + Ecore_Wl_Window_Keygrab_Info* info = new Ecore_Wl_Window_Keygrab_Info[keyCount]; - for( int index = 0; index < keyCount; ++index ) + for(int index = 0; index < keyCount; ++index) { - info[index].key = const_cast< char* >( KeyLookup::GetKeyName( key[index] ) ); + info[index].key = const_cast(KeyLookup::GetKeyName(key[index])); - switch( grabMode[index] ) + switch(grabMode[index]) { case KeyGrab::TOPMOST: { @@ -1968,31 +1961,31 @@ bool WindowBaseEcoreWl::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const } } - keyList = eina_list_append( keyList, &info ); + keyList = eina_list_append(keyList, &info); } - Eina_List* grabList = ecore_wl_window_keygrab_list_set( mEcoreWindow, keyList ); + Eina_List* grabList = ecore_wl_window_keygrab_list_set(mEcoreWindow, keyList); - result.Resize( keyCount, true ); + result.Resize(keyCount, true); - Eina_List* l = NULL; - Eina_List* m = NULL; - void* listData = NULL; - void* data = NULL; - if( grabList != NULL ) + Eina_List* l = NULL; + Eina_List* m = NULL; + void* listData = NULL; + void* data = NULL; + if(grabList != NULL) { - EINA_LIST_FOREACH( grabList, m, data ) + EINA_LIST_FOREACH(grabList, m, data) { int index = 0; - EINA_LIST_FOREACH( keyList, l, listData ) + EINA_LIST_FOREACH(keyList, l, listData) { - if( static_cast< Ecore_Wl_Window_Keygrab_Info* >( listData )->key == NULL ) + if(static_cast(listData)->key == NULL) { - DALI_LOG_ERROR( "input key list has null data!" ); + DALI_LOG_ERROR("input key list has null data!"); break; } - if( strcmp( static_cast< char* >( data ), static_cast< Ecore_Wl_Window_Keygrab_Info* >( listData )->key ) == 0 ) + if(strcmp(static_cast(data), static_cast(listData)->key) == 0) { result[index] = false; } @@ -2001,51 +1994,51 @@ bool WindowBaseEcoreWl::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const } } - delete [] info; + delete[] info; - eina_list_free( keyList ); - eina_list_free( grabList ); + eina_list_free(keyList); + eina_list_free(grabList); eina_shutdown(); return true; } -bool WindowBaseEcoreWl::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) +bool WindowBaseEcoreWl::UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) { int keyCount = key.Count(); - if( keyCount == 0 ) + if(keyCount == 0) { return false; } eina_init(); - Eina_List* keyList = NULL; - Ecore_Wl_Window_Keygrab_Info* info = new Ecore_Wl_Window_Keygrab_Info[keyCount]; + Eina_List* keyList = NULL; + Ecore_Wl_Window_Keygrab_Info* info = new Ecore_Wl_Window_Keygrab_Info[keyCount]; - for( int index = 0; index < keyCount; ++index ) + for(int index = 0; index < keyCount; ++index) { - info[index].key = const_cast< char* >( KeyLookup::GetKeyName( key[index] ) ); - keyList = eina_list_append( keyList, &info ); + info[index].key = const_cast(KeyLookup::GetKeyName(key[index])); + keyList = eina_list_append(keyList, &info); } - Eina_List* ungrabList = ecore_wl_window_keygrab_list_unset( mEcoreWindow, keyList ); + Eina_List* ungrabList = ecore_wl_window_keygrab_list_unset(mEcoreWindow, keyList); - result.Resize( keyCount, true ); + result.Resize(keyCount, true); - Eina_List* l = NULL; - Eina_List* m = NULL; - void *listData = NULL; - void *data = NULL; + Eina_List* l = NULL; + Eina_List* m = NULL; + void* listData = NULL; + void* data = NULL; - if( ungrabList != NULL ) + if(ungrabList != NULL) { - EINA_LIST_FOREACH( ungrabList, m, data ) + EINA_LIST_FOREACH(ungrabList, m, data) { int index = 0; - EINA_LIST_FOREACH( keyList, l, listData ) + EINA_LIST_FOREACH(keyList, l, listData) { - if( strcmp( static_cast< char* >( data ), static_cast< Ecore_Wl_Window_Keygrab_Info* >( listData )->key ) == 0 ) + if(strcmp(static_cast(data), static_cast(listData)->key) == 0) { result[index] = false; } @@ -2054,16 +2047,16 @@ bool WindowBaseEcoreWl::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dal } } - delete [] info; + delete[] info; - eina_list_free( keyList ); - eina_list_free( ungrabList ); + eina_list_free(keyList); + eina_list_free(ungrabList); eina_shutdown(); return true; } -void WindowBaseEcoreWl::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void WindowBaseEcoreWl::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; @@ -2072,8 +2065,8 @@ void WindowBaseEcoreWl::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVe xres = ecore_wl_dpi_get(); yres = ecore_wl_dpi_get(); - dpiHorizontal = int( xres + 0.5f ); // rounding - dpiVertical = int( yres + 0.5f ); + dpiHorizontal = int(xres + 0.5f); // rounding + dpiVertical = int(yres + 0.5f); } int WindowBaseEcoreWl::GetOrientation() const @@ -2090,86 +2083,86 @@ int WindowBaseEcoreWl::GetScreenRotationAngle() { int transform = 0; - if( ecore_wl_window_ignore_output_transform_get( mEcoreWindow ) ) + if(ecore_wl_window_ignore_output_transform_get(mEcoreWindow)) { transform = 0; } else { - transform = ecore_wl_output_transform_get( ecore_wl_window_output_find( mEcoreWindow ) ); + transform = ecore_wl_output_transform_get(ecore_wl_window_output_find(mEcoreWindow)); } mScreenRotationAngle = transform * 90; return mScreenRotationAngle; } -void WindowBaseEcoreWl::SetWindowRotationAngle( int degree ) +void WindowBaseEcoreWl::SetWindowRotationAngle(int degree) { mWindowRotationAngle = degree; - ecore_wl_window_rotation_set( mEcoreWindow, degree ); + ecore_wl_window_rotation_set(mEcoreWindow, degree); } -void WindowBaseEcoreWl::WindowRotationCompleted( int degree, int width, int height ) +void WindowBaseEcoreWl::WindowRotationCompleted(int degree, int width, int height) { - ecore_wl_window_rotation_change_done_send( mEcoreWindow ); + ecore_wl_window_rotation_change_done_send(mEcoreWindow); } -void WindowBaseEcoreWl::SetTransparency( bool transparent ) +void WindowBaseEcoreWl::SetTransparency(bool transparent) { - ecore_wl_window_alpha_set( mEcoreWindow, transparent ); + ecore_wl_window_alpha_set(mEcoreWindow, transparent); } void WindowBaseEcoreWl::InitializeEcoreElDBus() { #ifdef DALI_ELDBUS_AVAILABLE Eldbus_Object* object; - Eldbus_Proxy* manager; + Eldbus_Proxy* manager; - if( !( mSystemConnection = eldbus_connection_get( ELDBUS_CONNECTION_TYPE_SYSTEM ) ) ) + if(!(mSystemConnection = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SYSTEM))) { - DALI_LOG_ERROR( "Unable to get system bus\n" ); + DALI_LOG_ERROR("Unable to get system bus\n"); } - object = eldbus_object_get( mSystemConnection, BUS, PATH ); - if( !object ) + object = eldbus_object_get(mSystemConnection, BUS, PATH); + if(!object) { - DALI_LOG_ERROR( "Getting object failed\n" ); + DALI_LOG_ERROR("Getting object failed\n"); return; } - manager = eldbus_proxy_get( object, INTERFACE ); - if( !manager ) + manager = eldbus_proxy_get(object, INTERFACE); + if(!manager) { - DALI_LOG_ERROR( "Getting proxy failed\n" ); + DALI_LOG_ERROR("Getting proxy failed\n"); return; } - if( !eldbus_proxy_signal_handler_add( manager, "GestureDetected", EcoreElDBusAccessibilityNotification, this ) ) + if(!eldbus_proxy_signal_handler_add(manager, "GestureDetected", EcoreElDBusAccessibilityNotification, this)) { - DALI_LOG_ERROR( "No signal handler returned\n" ); + DALI_LOG_ERROR("No signal handler returned\n"); } #endif } -void WindowBaseEcoreWl::CreateWindow( PositionSize positionSize ) +void WindowBaseEcoreWl::CreateWindow(PositionSize positionSize) { - mEcoreWindow = ecore_wl_window_new( 0, positionSize.x, positionSize.y, positionSize.width, positionSize.height, ECORE_WL_WINDOW_BUFFER_TYPE_EGL_WINDOW ); + mEcoreWindow = ecore_wl_window_new(0, positionSize.x, positionSize.y, positionSize.width, positionSize.height, ECORE_WL_WINDOW_BUFFER_TYPE_EGL_WINDOW); - if ( mEcoreWindow == 0 ) + if(mEcoreWindow == 0) { - DALI_ASSERT_ALWAYS( 0 && "Failed to create Wayland window" ); + DALI_ASSERT_ALWAYS(0 && "Failed to create Wayland window"); } } -void WindowBaseEcoreWl::SetParent( WindowBase* parentWinBase ) +void WindowBaseEcoreWl::SetParent(WindowBase* parentWinBase) { Ecore_Wl_Window* ecoreParent = NULL; - if( parentWinBase ) + if(parentWinBase) { - WindowBaseEcoreWl* winBaseEcore = static_cast( parentWinBase ); - ecoreParent = winBaseEcore->mEcoreWindow; + WindowBaseEcoreWl* winBaseEcore = static_cast(parentWinBase); + ecoreParent = winBaseEcore->mEcoreWindow; } - ecore_wl_window_parent_set( mEcoreWindow, ecoreParent ); + ecore_wl_window_parent_set(mEcoreWindow, ecoreParent); } int WindowBaseEcoreWl::CreateFrameRenderedSyncFence() diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.h b/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.h index 24f676e..8726cd4 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.h +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/window-base-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_WINDOW_BASE_ECORE_WL_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,6 @@ namespace Internal { namespace Adaptor { - class WindowRenderSurface; class WindowRenderSurfaceEcoreWl; @@ -47,11 +46,10 @@ class WindowRenderSurfaceEcoreWl; class WindowBaseEcoreWl : public WindowBase { public: - /** * @brief Constructor */ - WindowBaseEcoreWl( PositionSize positionSize, Any surface, bool isTransparent ); + WindowBaseEcoreWl(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Destructor @@ -59,86 +57,85 @@ public: virtual ~WindowBaseEcoreWl(); public: - /** * @brief Called when the window iconify state is changed. */ - Eina_Bool OnIconifyStateChanged( void* data, int type, void* event ); + Eina_Bool OnIconifyStateChanged(void* data, int type, void* event); /** * @brief Called when the window gains focus. */ - Eina_Bool OnFocusIn( void* data, int type, void* event ); + Eina_Bool OnFocusIn(void* data, int type, void* event); /** * @brief Called when the window loses focus. */ - Eina_Bool OnFocusOut( void* data, int type, void* event ); + Eina_Bool OnFocusOut(void* data, int type, void* event); /** * @brief Called when the output is transformed. */ - Eina_Bool OnOutputTransform( void* data, int type, void* event ); + Eina_Bool OnOutputTransform(void* data, int type, void* event); /** * @brief Called when the output transform should be ignored. */ - Eina_Bool OnIgnoreOutputTransform( void* data, int type, void* event ); + Eina_Bool OnIgnoreOutputTransform(void* data, int type, void* event); /** * @brief Called when a rotation event is recevied. */ - void OnRotation( void* data, int type, void* event ); + void OnRotation(void* data, int type, void* event); /** * @brief Called when a touch down is received. */ - void OnMouseButtonDown( void* data, int type, void* event ); + void OnMouseButtonDown(void* data, int type, void* event); /** * @brief Called when a touch up is received. */ - void OnMouseButtonUp( void* data, int type, void* event ); + void OnMouseButtonUp(void* data, int type, void* event); /** * @brief Called when a touch motion is received. */ - void OnMouseButtonMove( void* data, int type, void* event ); + void OnMouseButtonMove(void* data, int type, void* event); /** * @brief Called when a touch is canceled. */ - void OnMouseButtonCancel( void* data, int type, void* event ); + void OnMouseButtonCancel(void* data, int type, void* event); /** * @brief Called when a mouse wheel is received. */ - void OnMouseWheel( void* data, int type, void* event ); + void OnMouseWheel(void* data, int type, void* event); /** * @brief Called when a detent rotation event is recevied. */ - void OnDetentRotation( void* data, int type, void* event ); + void OnDetentRotation(void* data, int type, void* event); /** * @brief Called when a key down is received. */ - void OnKeyDown( void* data, int type, void* event ); + void OnKeyDown(void* data, int type, void* event); /** * @brief Called when a key up is received. */ - void OnKeyUp( void* data, int type, void* event ); + void OnKeyUp(void* data, int type, void* event); /** * @brief Called when the source window notifies us the content in clipboard is selected. */ - void OnDataSend( void* data, int type, void* event ); + void OnDataSend(void* data, int type, void* event); /** * @brief Called when the source window sends us about the selected content. */ - void OnDataReceive( void* data, int type, void* event ); + void OnDataReceive(void* data, int type, void* event); /** * @brief Called when a font name is changed. @@ -154,36 +151,35 @@ public: /** * @brief Called when Ecore ElDBus accessibility event is received. */ - void OnEcoreElDBusAccessibilityNotification( void* context, const Eldbus_Message* message ); + void OnEcoreElDBusAccessibilityNotification(void* context, const Eldbus_Message* message); #endif /** * @brief RegistryGlobalCallback */ - void RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version ); + void RegistryGlobalCallback(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version); /** * @brief RegistryGlobalCallbackRemove */ - void RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id ); + void RegistryGlobalCallbackRemove(void* data, struct wl_registry* registry, uint32_t id); /** * @brief TizenPolicyNotificationChangeDone */ - void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state ); + void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state); /** * @brief TizenPolicyScreenModeChangeDone */ - void TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state ); + void TizenPolicyScreenModeChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state); /** * @brief DisplayPolicyBrightnessChangeDone */ - void DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state ); + void DisplayPolicyBrightnessChangeDone(void* data, struct tizen_display_policy* displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state); public: - /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNativeWindow() */ @@ -197,7 +193,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateEglWindow() */ - EGLNativeWindowType CreateEglWindow( int width, int height ) override; + EGLNativeWindowType CreateEglWindow(int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::DestroyEglWindow() @@ -207,22 +203,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowRotation() */ - void SetEglWindowRotation( int angle ) override; + void SetEglWindowRotation(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowBufferTransform() */ - void SetEglWindowBufferTransform( int angle ) override; + void SetEglWindowBufferTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowTransform() */ - void SetEglWindowTransform( int angle ) override; + void SetEglWindowTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::ResizeEglWindow() */ - void ResizeEglWindow( PositionSize positionSize ) override; + void ResizeEglWindow(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::IsEglWindowRotationSupported() @@ -232,22 +228,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::Move() */ - void Move( PositionSize positionSize ) override; + void Move(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Resize() */ - void Resize( PositionSize positionSize ) override; + void Resize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::MoveResize() */ - void MoveResize( PositionSize positionSize ) override; + void MoveResize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetClass() */ - void SetClass( const std::string& name, const std::string& className ) override; + void SetClass(const std::string& name, const std::string& className) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Raise() @@ -267,17 +263,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAvailableAnlges() */ - void SetAvailableAnlges( const std::vector< int >& angles ) override; + void SetAvailableAnlges(const std::vector& angles) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetPreferredAngle() */ - void SetPreferredAngle( int angle ) override; + void SetPreferredAngle(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ) override; + void SetAcceptFocus(bool accept) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Show() @@ -297,47 +293,47 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const override; + std::string GetSupportedAuxiliaryHint(unsigned int index) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) override; + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ) override; + bool RemoveAuxiliaryHint(unsigned int id) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) override; + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const override; + std::string GetAuxiliaryHintValue(unsigned int id) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const override; + unsigned int GetAuxiliaryHintId(const std::string& hint) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ) override; + void SetInputRegion(const Rect& inputRegion) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetType() */ - void SetType( Dali::WindowType type ) override; + void SetType(Dali::WindowType type) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetNotificationLevel() */ - bool SetNotificationLevel( Dali::WindowNotificationLevel level ) override; + bool SetNotificationLevel(Dali::WindowNotificationLevel level) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNotificationLevel() @@ -347,7 +343,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetOpaqueState() */ - void SetOpaqueState( bool opaque ) override; + void SetOpaqueState(bool opaque) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetScreenOffMode() @@ -362,7 +358,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetBrightness() */ - bool SetBrightness( int brightness ) override; + bool SetBrightness(int brightness) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetBrightness() @@ -372,27 +368,27 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) override; + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKey() */ - bool UngrabKey( Dali::KEY key ) override; + bool UngrabKey(Dali::KEY key) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKeyList() */ - bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) override; + bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKeyList() */ - bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) override; + bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetOrientation() @@ -407,22 +403,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetWindowRotationAngle() */ - void SetWindowRotationAngle( int degree ) override; + void SetWindowRotationAngle(int degree) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::WindowRotationCompleted() */ - void WindowRotationCompleted( int degree, int width, int height ) override; + void WindowRotationCompleted(int degree, int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetTransparency() */ - void SetTransparency( bool transparent ) override; + void SetTransparency(bool transparent) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetParent() */ - void SetParent( WindowBase* parentWinBase ) override; + void SetParent(WindowBase* parentWinBase) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateFrameRenderedSyncFence() @@ -435,11 +431,10 @@ public: int CreateFramePresentedSyncFence() override; private: - /** * Second stage initialization */ - void Initialize( PositionSize positionSize, Any surface, bool isTransparent ); + void Initialize(PositionSize positionSize, Any surface, bool isTransparent); /** * Initialize Ecore ElDBus @@ -449,10 +444,9 @@ private: /** * @brief Create window */ - void CreateWindow( PositionSize positionSize ); + void CreateWindow(PositionSize positionSize); protected: - // Undefined WindowBaseEcoreWl(const WindowBaseEcoreWl&) = delete; @@ -460,48 +454,46 @@ protected: WindowBaseEcoreWl& operator=(const WindowBaseEcoreWl& rhs) = delete; private: + typedef std::vector > AuxiliaryHints; - typedef std::vector< std::pair< std::string, std::string > > AuxiliaryHints; + Dali::Vector mEcoreEventHandler; - Dali::Vector< Ecore_Event_Handler* > mEcoreEventHandler; + Ecore_Wl_Window* mEcoreWindow; + wl_surface* mWlSurface; + wl_egl_window* mEglWindow; + wl_display* mDisplay; + wl_event_queue* mEventQueue; + tizen_policy* mTizenPolicy; + tizen_display_policy* mTizenDisplayPolicy; - Ecore_Wl_Window* mEcoreWindow; - wl_surface* mWlSurface; - wl_egl_window* mEglWindow; - wl_display* mDisplay; - wl_event_queue* mEventQueue; - tizen_policy* mTizenPolicy; - tizen_display_policy* mTizenDisplayPolicy; + std::vector mSupportedAuxiliaryHints; + AuxiliaryHints mAuxiliaryHints; - std::vector< std::string > mSupportedAuxiliaryHints; - AuxiliaryHints mAuxiliaryHints; + int mNotificationLevel; + uint32_t mNotificationChangeState; + bool mNotificationLevelChangeDone; - int mNotificationLevel; - uint32_t mNotificationChangeState; - bool mNotificationLevelChangeDone; + int mScreenOffMode; + uint32_t mScreenOffModeChangeState; + bool mScreenOffModeChangeDone; - int mScreenOffMode; - uint32_t mScreenOffModeChangeState; - bool mScreenOffModeChangeDone; + int mBrightness; + uint32_t mBrightnessChangeState; + bool mBrightnessChangeDone; - int mBrightness; - uint32_t mBrightnessChangeState; - bool mBrightnessChangeDone; + bool mOwnSurface; - bool mOwnSurface; - - int mWindowRotationAngle; - int mScreenRotationAngle; - int mSupportedPreProtation; + int mWindowRotationAngle; + int mScreenRotationAngle; + int mSupportedPreProtation; #ifdef DALI_ELDBUS_AVAILABLE - Eldbus_Connection* mSystemConnection; + Eldbus_Connection* mSystemConnection; #endif // DALI_ELDBUS_AVAILABLE - }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.cpp index 429de0d..fd488d7 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali { @@ -28,17 +28,16 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowBase > WindowFactoryEcoreWl::CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr WindowFactoryEcoreWl::CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowBaseEcoreWl >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } // this should be created from Window impl -std::unique_ptr< WindowFactory > GetWindowFactory() +std::unique_ptr GetWindowFactory() { // returns Window factory - return Utils::MakeUnique< WindowFactoryEcoreWl >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.h b/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.h index 9f58b99..24a36fc 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.h +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/window-factory-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_WINDOW_FACTORY_ECORE_WL_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,10 @@ namespace Internal { namespace Adaptor { - class WindowFactoryEcoreWl : public WindowFactory { public: - std::unique_ptr< WindowBase > CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) override; + std::unique_ptr CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl/window-system-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl/window-system-ecore-wl.cpp index a38aa6e..626ee7e 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl/window-system-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl/window-system-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,19 +23,15 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowSystem { - void Initialize() { - ecore_wl_init( NULL ); + ecore_wl_init(NULL); } void Shutdown() @@ -43,22 +39,22 @@ void Shutdown() ecore_wl_shutdown(); } -void GetScreenSize( int& width, int& height ) +void GetScreenSize(int& width, int& height) { - ecore_wl_screen_size_get( &width, &height ); + ecore_wl_screen_size_get(&width, &height); } -bool SetKeyboardRepeatInfo( float rate, float delay ) +bool SetKeyboardRepeatInfo(float rate, float delay) { - return ecore_wl_keyboard_repeat_info_set( static_cast( rate ), static_cast( delay ) ); + return ecore_wl_keyboard_repeat_info_set(static_cast(rate), static_cast(delay)); } -bool GetKeyboardRepeatInfo( float& rate, float& delay ) +bool GetKeyboardRepeatInfo(float& rate, float& delay) { double rateVal, delayVal; - bool ret = ecore_wl_keyboard_repeat_info_get( &rateVal, &delayVal ); - rate = static_cast( rateVal ); - delay = static_cast( delayVal ); + bool ret = ecore_wl_keyboard_repeat_info_get(&rateVal, &delayVal); + rate = static_cast(rateVal); + delay = static_cast(delayVal); return ret; } diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.cpp index 1b1f816..ad04f5e 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ #include // INTERNAL HEADERS +#include +#include #include #include -#include -#include // EXTERNAL INCLUDES #include @@ -33,27 +33,26 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowRenderSurface > RenderSurfaceFactoryEcoreWl2::CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreWl2::CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowRenderSurface >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< PixmapRenderSurface > RenderSurfaceFactoryEcoreWl2::CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreWl2::CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return std::unique_ptr< PixmapRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } -std::unique_ptr< NativeRenderSurface > RenderSurfaceFactoryEcoreWl2::CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreWl2::CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< NativeRenderSurfaceEcoreWl >( surfaceSize, surface, isTransparent ); + return Utils::MakeUnique(surfaceSize, surface, isTransparent); } // this should be created from somewhere -std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory() +std::unique_ptr GetRenderSurfaceFactory() { // returns Window factory - return Utils::MakeUnique< RenderSurfaceFactoryEcoreWl2 >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.h b/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.h index eca7f5d..01428d9 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.h +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/render-surface-factory-ecore-wl2.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_RENDER_SURFACE_FACTORY_ECORE_WL2_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,15 +26,14 @@ namespace Internal { namespace Adaptor { - class RenderSurfaceFactoryEcoreWl2 : public RenderSurfaceFactory { public: - std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.cpp old mode 100755 new mode 100644 index 856a8de..7d923b6 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,62 +23,58 @@ #include // INTERNAL HEADERS +#include #include -#include #include -#include +#include // EXTERNAL_HEADERS -#include -#include -#include -#include #include -#include +#include +#include +#include +#include #include +#include #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_WINDOW_BASE" ); +Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW_BASE"); #endif -const uint32_t MAX_TIZEN_CLIENT_VERSION = 7; -const unsigned int PRIMARY_TOUCH_BUTTON_ID = 1; +const uint32_t MAX_TIZEN_CLIENT_VERSION = 7; +const unsigned int PRIMARY_TOUCH_BUTTON_ID = 1; -const char* DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced. +const char* DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME = "db/setting/accessibility/font_name"; // It will be update at vconf-key.h and replaced. // DBUS accessibility -const char* BUS = "org.enlightenment.wm-screen-reader"; +const char* BUS = "org.enlightenment.wm-screen-reader"; const char* INTERFACE = "org.tizen.GestureNavigation"; -const char* PATH = "/org/tizen/GestureNavigation"; +const char* PATH = "/org/tizen/GestureNavigation"; struct KeyCodeMap { - xkb_keysym_t keySym; + xkb_keysym_t keySym; xkb_keycode_t keyCode; - bool isKeyCode; + bool isKeyCode; }; /** * Get the device name from the provided ecore key event */ -void GetDeviceName( Ecore_Event_Key* keyEvent, std::string& result ) +void GetDeviceName(Ecore_Event_Key* keyEvent, std::string& result) { - const char* ecoreDeviceName = ecore_device_name_get( keyEvent->dev ); + const char* ecoreDeviceName = ecore_device_name_get(keyEvent->dev); - if( ecoreDeviceName ) + if(ecoreDeviceName) { result = ecoreDeviceName; } @@ -87,9 +83,9 @@ void GetDeviceName( Ecore_Event_Key* keyEvent, std::string& result ) /** * Get the device class from the provided ecore event */ -void GetDeviceClass( Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& deviceClass ) +void GetDeviceClass(Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& deviceClass) { - switch( ecoreDeviceClass ) + switch(ecoreDeviceClass) { case ECORE_DEVICE_CLASS_SEAT: { @@ -134,9 +130,9 @@ void GetDeviceClass( Ecore_Device_Class ecoreDeviceClass, Device::Class::Type& d } } -void GetDeviceSubclass( Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subclass::Type& deviceSubclass ) +void GetDeviceSubclass(Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subclass::Type& deviceSubclass) { - switch( ecoreDeviceSubclass ) + switch(ecoreDeviceSubclass) { case ECORE_DEVICE_SUBCLASS_FINGER: { @@ -206,26 +202,25 @@ void GetDeviceSubclass( Ecore_Device_Subclass ecoreDeviceSubclass, Device::Subcl } } - -void FindKeyCode( struct xkb_keymap* keyMap, xkb_keycode_t key, void* data ) +void FindKeyCode(struct xkb_keymap* keyMap, xkb_keycode_t key, void* data) { - KeyCodeMap* foundKeyCode = static_cast< KeyCodeMap* >( data ); - if( foundKeyCode->isKeyCode ) + KeyCodeMap* foundKeyCode = static_cast(data); + if(foundKeyCode->isKeyCode) { return; } - xkb_keysym_t keySym = foundKeyCode->keySym; - int nsyms = 0; + xkb_keysym_t keySym = foundKeyCode->keySym; + int nsyms = 0; const xkb_keysym_t* symsOut = NULL; - nsyms = xkb_keymap_key_get_syms_by_level( keyMap, key, 0, 0, &symsOut ); + nsyms = xkb_keymap_key_get_syms_by_level(keyMap, key, 0, 0, &symsOut); - if( nsyms && symsOut ) + if(nsyms && symsOut) { - if( *symsOut == keySym ) + if(*symsOut == keySym) { - foundKeyCode->keyCode = key; + foundKeyCode->keyCode = key; foundKeyCode->isKeyCode = true; } } @@ -236,60 +231,60 @@ void FindKeyCode( struct xkb_keymap* keyMap, xkb_keycode_t key, void* data ) ///////////////////////////////////////////////////////////////////////////////////////////////// /// Called when the window iconify state is changed. -static Eina_Bool EcoreEventWindowIconifyStateChanged( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowIconifyStateChanged(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnIconifyStateChanged( data, type, event ); + return windowBase->OnIconifyStateChanged(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the window gains focus -static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowFocusIn(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnFocusIn( data, type, event ); + return windowBase->OnFocusIn(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the window loses focus -static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowFocusOut(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnFocusOut( data, type, event ); + return windowBase->OnFocusOut(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the output is transformed -static Eina_Bool EcoreEventOutputTransform( void* data, int type, void* event ) +static Eina_Bool EcoreEventOutputTransform(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnOutputTransform( data, type, event ); + return windowBase->OnOutputTransform(data, type, event); } return ECORE_CALLBACK_PASS_ON; } /// Called when the output transform should be ignored -static Eina_Bool EcoreEventIgnoreOutputTransform( void* data, int type, void* event ) +static Eina_Bool EcoreEventIgnoreOutputTransform(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnIgnoreOutputTransform( data, type, event ); + return windowBase->OnIgnoreOutputTransform(data, type, event); } return ECORE_CALLBACK_PASS_ON; @@ -298,13 +293,13 @@ static Eina_Bool EcoreEventIgnoreOutputTransform( void* data, int type, void* ev /** * Called when rotate event is recevied. */ -static Eina_Bool EcoreEventRotate( void* data, int type, void* event ) +static Eina_Bool EcoreEventRotate(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - DALI_LOG_RELEASE_INFO( "WindowBaseEcoreWl2::EcoreEventRotate\n" ); - windowBase->OnRotation( data, type, event ); + DALI_LOG_RELEASE_INFO("WindowBaseEcoreWl2::EcoreEventRotate\n"); + windowBase->OnRotation(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -312,12 +307,12 @@ static Eina_Bool EcoreEventRotate( void* data, int type, void* event ) /** * Called when configure event is recevied. */ -static Eina_Bool EcoreEventConfigure( void* data, int type, void* event ) +static Eina_Bool EcoreEventConfigure(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnConfiguration( data, type, event ); + windowBase->OnConfiguration(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -329,12 +324,12 @@ static Eina_Bool EcoreEventConfigure( void* data, int type, void* event ) /** * Called when a touch down is received. */ -static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonDown(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonDown( data, type, event ); + windowBase->OnMouseButtonDown(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -342,12 +337,12 @@ static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event ) /** * Called when a touch up is received. */ -static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonUp(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonUp( data, type, event ); + windowBase->OnMouseButtonUp(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -355,12 +350,12 @@ static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event ) /** * Called when a touch motion is received. */ -static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonMove(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonMove( data, type, event ); + windowBase->OnMouseButtonMove(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -368,12 +363,12 @@ static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event ) /** * Called when a touch is canceled. */ -static Eina_Bool EcoreEventMouseButtonCancel( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonCancel(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonCancel( data, type, event ); + windowBase->OnMouseButtonCancel(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -381,12 +376,12 @@ static Eina_Bool EcoreEventMouseButtonCancel( void* data, int type, void* event /** * Called when a mouse wheel is received. */ -static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseWheel(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseWheel( data, type, event ); + windowBase->OnMouseWheel(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -394,12 +389,12 @@ static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event ) /** * Called when a detent rotation event is recevied. */ -static Eina_Bool EcoreEventDetentRotation( void* data, int type, void* event ) +static Eina_Bool EcoreEventDetentRotation(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnDetentRotation( data, type, event ); + windowBase->OnDetentRotation(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -411,12 +406,12 @@ static Eina_Bool EcoreEventDetentRotation( void* data, int type, void* event ) /** * Called when a key down is received. */ -static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event ) +static Eina_Bool EcoreEventKeyDown(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnKeyDown( data, type, event ); + windowBase->OnKeyDown(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -424,12 +419,12 @@ static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event ) /** * Called when a key up is received. */ -static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event ) +static Eina_Bool EcoreEventKeyUp(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnKeyUp( data, type, event ); + windowBase->OnKeyUp(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -441,12 +436,12 @@ static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event ) /** * Called when the source window notifies us the content in clipboard is selected. */ -static Eina_Bool EcoreEventDataSend( void* data, int type, void* event ) +static Eina_Bool EcoreEventDataSend(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnDataSend( data, type, event ); + windowBase->OnDataSend(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -455,12 +450,12 @@ static Eina_Bool EcoreEventDataSend( void* data, int type, void* event ) * Called when the source window sends us about the selected content. * For example, when item is selected in the clipboard. */ -static Eina_Bool EcoreEventDataReceive( void* data, int type, void* event ) +static Eina_Bool EcoreEventDataReceive(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnDataReceive( data, type, event ); + windowBase->OnDataReceive(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -472,16 +467,16 @@ static Eina_Bool EcoreEventDataReceive( void* data, int type, void* event ) /** * Called when transition animation of the window's shown/hidden is started by window manager. */ -static Eina_Bool EcoreEventEffectStart(void *data, int type, void *event) +static Eina_Bool EcoreEventEffectStart(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - Ecore_Wl2_Event_Effect_Start *effectStart = static_cast( event ); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventEffectStart, effect type[ %d ]\n", effectStart->type ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + Ecore_Wl2_Event_Effect_Start* effectStart = static_cast(event); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventEffectStart, effect type[ %d ]\n", effectStart->type); + if(windowBase) { - if( effectStart->type < 3 ) // only under restack + if(effectStart->type < 3) // only under restack { - windowBase->OnTransitionEffectEvent( WindowEffectState::START, static_cast( effectStart->type ) ); + windowBase->OnTransitionEffectEvent(WindowEffectState::START, static_cast(effectStart->type)); } } return ECORE_CALLBACK_PASS_ON; @@ -490,16 +485,16 @@ static Eina_Bool EcoreEventEffectStart(void *data, int type, void *event) /** * Called when transition animation of the window's shown/hidden is ended by window manager. */ -static Eina_Bool EcoreEventEffectEnd(void *data, int type, void *event) +static Eina_Bool EcoreEventEffectEnd(void* data, int type, void* event) { - Ecore_Wl2_Event_Effect_Start *effectEnd = static_cast( event ); - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventEffectEnd, effect type[ %d ]\n", effectEnd->type ); - if( windowBase ) + Ecore_Wl2_Event_Effect_Start* effectEnd = static_cast(event); + WindowBaseEcoreWl2* windowBase = static_cast(data); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventEffectEnd, effect type[ %d ]\n", effectEnd->type); + if(windowBase) { - if( effectEnd->type < 3 ) // only under restack + if(effectEnd->type < 3) // only under restack { - windowBase->OnTransitionEffectEvent( WindowEffectState::END, static_cast( effectEnd->type ) ); + windowBase->OnTransitionEffectEvent(WindowEffectState::END, static_cast(effectEnd->type)); } } return ECORE_CALLBACK_PASS_ON; @@ -509,15 +504,15 @@ static Eina_Bool EcoreEventEffectEnd(void *data, int type, void *event) // Keyboard Repeat Settings Changed Callbacks ///////////////////////////////////////////////////////////////////////////////////////////////// -static Eina_Bool EcoreEventSeatKeyboardRepeatChanged(void *data, int type, void *event) +static Eina_Bool EcoreEventSeatKeyboardRepeatChanged(void* data, int type, void* event) { - Ecore_Wl2_Event_Seat_Keyboard_Repeat_Changed *keyboardRepeat = static_cast( event ); - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventSeatKeyboardRepeatChanged, id[ %d ]\n", keyboardRepeat->id ); - if( windowBase ) - { - windowBase->OnKeyboardRepeatSettingsChanged(); - } + Ecore_Wl2_Event_Seat_Keyboard_Repeat_Changed* keyboardRepeat = static_cast(event); + WindowBaseEcoreWl2* windowBase = static_cast(data); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventSeatKeyboardRepeatChanged, id[ %d ]\n", keyboardRepeat->id); + if(windowBase) + { + windowBase->OnKeyboardRepeatSettingsChanged(); + } return ECORE_CALLBACK_RENEW; } @@ -526,12 +521,12 @@ static Eina_Bool EcoreEventSeatKeyboardRepeatChanged(void *data, int type, void // Keymap Changed Callbacks ///////////////////////////////////////////////////////////////////////////////////////////////// -static Eina_Bool EcoreEventSeatKeymapChanged(void *data, int type, void *event) +static Eina_Bool EcoreEventSeatKeymapChanged(void* data, int type, void* event) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->KeymapChanged( data, type, event ); + windowBase->KeymapChanged(data, type, event); } return ECORE_CALLBACK_RENEW; @@ -544,10 +539,10 @@ static Eina_Bool EcoreEventSeatKeymapChanged(void *data, int type, void *event) /** * Called when a font name is changed. */ -static void VconfNotifyFontNameChanged( keynode_t* node, void* data ) +static void VconfNotifyFontNameChanged(keynode_t* node, void* data) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { windowBase->OnFontNameChanged(); } @@ -556,10 +551,10 @@ static void VconfNotifyFontNameChanged( keynode_t* node, void* data ) /** * Called when a font size is changed. */ -static void VconfNotifyFontSizeChanged( keynode_t* node, void* data ) +static void VconfNotifyFontSizeChanged(keynode_t* node, void* data) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { windowBase->OnFontSizeChanged(); } @@ -569,12 +564,12 @@ static void VconfNotifyFontSizeChanged( keynode_t* node, void* data ) // Window Redraw Request Event Callbacks ///////////////////////////////////////////////////////////////////////////////////////////////// -static Eina_Bool EcoreEventWindowRedrawRequest(void *data, int type, void *event) +static Eina_Bool EcoreEventWindowRedrawRequest(void* data, int type, void* event) { - Ecore_Wl2_Event_Window_Redraw_Request *windowRedrawRequest = static_cast(event); - WindowBaseEcoreWl2 *windowBase = static_cast(data); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventWindowRedrawRequest, window[ %d ]\n", windowRedrawRequest->win ); - if ( windowBase ) + Ecore_Wl2_Event_Window_Redraw_Request* windowRedrawRequest = static_cast(event); + WindowBaseEcoreWl2* windowBase = static_cast(data); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::EcoreEventWindowRedrawRequest, window[ %d ]\n", windowRedrawRequest->win); + if(windowBase) { windowBase->OnEcoreEventWindowRedrawRequest(); } @@ -588,117 +583,114 @@ static Eina_Bool EcoreEventWindowRedrawRequest(void *data, int type, void *event #ifdef DALI_ELDBUS_AVAILABLE // Callback for Ecore ElDBus accessibility events. -static void EcoreElDBusAccessibilityNotification( void* context, const Eldbus_Message* message ) +static void EcoreElDBusAccessibilityNotification(void* context, const Eldbus_Message* message) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( context ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(context); + if(windowBase) { - windowBase->OnEcoreElDBusAccessibilityNotification( context, message ); + windowBase->OnEcoreElDBusAccessibilityNotification(context, message); } } #endif // DALI_ELDBUS_AVAILABLE -static void RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version ) +static void RegistryGlobalCallback(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->RegistryGlobalCallback( data, registry, name, interface, version ); + windowBase->RegistryGlobalCallback(data, registry, name, interface, version); } } -static void RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id ) +static void RegistryGlobalCallbackRemove(void* data, struct wl_registry* registry, uint32_t id) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->RegistryGlobalCallbackRemove( data, registry, id ); + windowBase->RegistryGlobalCallbackRemove(data, registry, id); } } -static void TizenPolicyConformant( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t isConformant ) +static void TizenPolicyConformant(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t isConformant) { } -static void TizenPolicyConformantArea( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h ) +static void TizenPolicyConformantArea(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h) { } -static void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state ) +static void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->TizenPolicyNotificationChangeDone( data, tizenPolicy, surface, level, state ); + windowBase->TizenPolicyNotificationChangeDone(data, tizenPolicy, surface, level, state); } } -static void TizenPolicyTransientForDone( void* data, struct tizen_policy* tizenPolicy, uint32_t childId ) +static void TizenPolicyTransientForDone(void* data, struct tizen_policy* tizenPolicy, uint32_t childId) { } -static void TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state ) +static void TizenPolicyScreenModeChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->TizenPolicyScreenModeChangeDone( data, tizenPolicy, surface, mode, state ); + windowBase->TizenPolicyScreenModeChangeDone(data, tizenPolicy, surface, mode, state); } } -static void TizenPolicyIconifyStateChanged( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t iconified, uint32_t force ) +static void TizenPolicyIconifyStateChanged(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t iconified, uint32_t force) { } -static void TizenPolicySupportedAuxiliaryHints( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, struct wl_array* hints, uint32_t numNints ) +static void TizenPolicySupportedAuxiliaryHints(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, struct wl_array* hints, uint32_t numNints) { } -static void TizenPolicyAllowedAuxiliaryHint( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int id ) +static void TizenPolicyAllowedAuxiliaryHint(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int id) { } -static void TizenPolicyAuxiliaryMessage( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, const char* key, const char* val, struct wl_array* options ) +static void TizenPolicyAuxiliaryMessage(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, const char* key, const char* val, struct wl_array* options) { } -static void TizenPolicyConformantRegion( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t serial ) +static void TizenPolicyConformantRegion(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t conformantPart, uint32_t state, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t serial) { } -static void DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state ) +static void DisplayPolicyBrightnessChangeDone(void* data, struct tizen_display_policy* displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state) { - WindowBaseEcoreWl2* windowBase = static_cast< WindowBaseEcoreWl2* >( data ); - if( windowBase ) + WindowBaseEcoreWl2* windowBase = static_cast(data); + if(windowBase) { - windowBase->DisplayPolicyBrightnessChangeDone( data, displayPolicy, surface, brightness, state ); + windowBase->DisplayPolicyBrightnessChangeDone(data, displayPolicy, surface, brightness, state); } } const struct wl_registry_listener registryListener = -{ - RegistryGlobalCallback, - RegistryGlobalCallbackRemove -}; + { + RegistryGlobalCallback, + RegistryGlobalCallbackRemove}; const struct tizen_policy_listener tizenPolicyListener = -{ - TizenPolicyConformant, - TizenPolicyConformantArea, - TizenPolicyNotificationChangeDone, - TizenPolicyTransientForDone, - TizenPolicyScreenModeChangeDone, - TizenPolicyIconifyStateChanged, - TizenPolicySupportedAuxiliaryHints, - TizenPolicyAllowedAuxiliaryHint, - TizenPolicyAuxiliaryMessage, - TizenPolicyConformantRegion -}; + { + TizenPolicyConformant, + TizenPolicyConformantArea, + TizenPolicyNotificationChangeDone, + TizenPolicyTransientForDone, + TizenPolicyScreenModeChangeDone, + TizenPolicyIconifyStateChanged, + TizenPolicySupportedAuxiliaryHints, + TizenPolicyAllowedAuxiliaryHint, + TizenPolicyAuxiliaryMessage, + TizenPolicyConformantRegion}; const struct tizen_display_policy_listener tizenDisplayPolicyListener = -{ - DisplayPolicyBrightnessChangeDone -}; + { + DisplayPolicyBrightnessChangeDone}; } // unnamed namespace @@ -742,52 +734,52 @@ WindowBaseEcoreWl2::WindowBaseEcoreWl2(Dali::PositionSize positionSize, Any surf WindowBaseEcoreWl2::~WindowBaseEcoreWl2() { #ifdef DALI_ELDBUS_AVAILABLE - // Close down ElDBus connections. - if( mSystemConnection ) - { - eldbus_connection_unref( mSystemConnection ); - } + // Close down ElDBus connections. + if(mSystemConnection) + { + eldbus_connection_unref(mSystemConnection); + } #endif // DALI_ELDBUS_AVAILABLE - vconf_ignore_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged ); - vconf_ignore_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged ); + vconf_ignore_key_changed(VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged); + vconf_ignore_key_changed(DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged); - for( Dali::Vector< Ecore_Event_Handler* >::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter ) + for(Dali::Vector::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter) { - ecore_event_handler_del( *iter ); + ecore_event_handler_del(*iter); } mEcoreEventHandler.Clear(); - if( mEventQueue ) + if(mEventQueue) { - wl_event_queue_destroy( mEventQueue ); + wl_event_queue_destroy(mEventQueue); } mSupportedAuxiliaryHints.clear(); mAuxiliaryHints.clear(); - if( mEglWindow != NULL ) + if(mEglWindow != NULL) { - wl_egl_window_destroy( mEglWindow ); + wl_egl_window_destroy(mEglWindow); mEglWindow = NULL; } - if( mOwnSurface ) + if(mOwnSurface) { - ecore_wl2_window_free( mEcoreWindow ); + ecore_wl2_window_free(mEcoreWindow); WindowSystem::Shutdown(); } } -void WindowBaseEcoreWl2::Initialize( PositionSize positionSize, Any surface, bool isTransparent ) +void WindowBaseEcoreWl2::Initialize(PositionSize positionSize, Any surface, bool isTransparent) { - if( surface.Empty() == false ) + if(surface.Empty() == false) { // check we have a valid type - DALI_ASSERT_ALWAYS( ( surface.GetType() == typeid (Ecore_Wl2_Window *) ) && "Surface type is invalid" ); + DALI_ASSERT_ALWAYS((surface.GetType() == typeid(Ecore_Wl2_Window*)) && "Surface type is invalid"); - mEcoreWindow = AnyCast< Ecore_Wl2_Window* >( surface ); + mEcoreWindow = AnyCast(surface); } else { @@ -795,121 +787,121 @@ void WindowBaseEcoreWl2::Initialize( PositionSize positionSize, Any surface, boo WindowSystem::Initialize(); mOwnSurface = true; - CreateWindow( positionSize ); + CreateWindow(positionSize); } - mWlSurface = ecore_wl2_window_surface_get( mEcoreWindow ); + mWlSurface = ecore_wl2_window_surface_get(mEcoreWindow); - SetTransparency( isTransparent ); + SetTransparency(isTransparent); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_WINDOW_ICONIFY_STATE_CHANGE, EcoreEventWindowIconifyStateChanged, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_OUTPUT_TRANSFORM, EcoreEventOutputTransform, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_IGNORE_OUTPUT_TRANSFORM, EcoreEventIgnoreOutputTransform, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_WINDOW_ICONIFY_STATE_CHANGE, EcoreEventWindowIconifyStateChanged, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_FOCUS_IN, EcoreEventWindowFocusIn, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_FOCUS_OUT, EcoreEventWindowFocusOut, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_OUTPUT_TRANSFORM, EcoreEventOutputTransform, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_IGNORE_OUTPUT_TRANSFORM, EcoreEventIgnoreOutputTransform, this)); // Register Rotate event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_WINDOW_ROTATE, EcoreEventRotate, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_WINDOW_ROTATE, EcoreEventRotate, this)); // Register Configure event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_WINDOW_CONFIGURE, EcoreEventConfigure, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_WINDOW_CONFIGURE, EcoreEventConfigure, this)); // Register Touch events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_CANCEL, EcoreEventMouseButtonCancel, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_CANCEL, EcoreEventMouseButtonCancel, this)); // Register Mouse wheel events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this)); // Register Detent event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_DETENT_ROTATE, EcoreEventDetentRotation, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_DETENT_ROTATE, EcoreEventDetentRotation, this)); // Register Key events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this)); // Register Selection event - clipboard selection - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_DATA_SOURCE_SEND, EcoreEventDataSend, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_SELECTION_DATA_READY, EcoreEventDataReceive, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_DATA_SOURCE_SEND, EcoreEventDataSend, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_SELECTION_DATA_READY, EcoreEventDataReceive, this)); // Register Effect Start/End event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_EFFECT_START, EcoreEventEffectStart, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_EFFECT_END, EcoreEventEffectEnd, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_EFFECT_START, EcoreEventEffectStart, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_EFFECT_END, EcoreEventEffectEnd, this)); // Register Keyboard repeat event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_SEAT_KEYBOARD_REPEAT_CHANGED, EcoreEventSeatKeyboardRepeatChanged, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_SEAT_KEYBOARD_REPEAT_CHANGED, EcoreEventSeatKeyboardRepeatChanged, this)); // Register Window redraw request event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_WINDOW_REDRAW_REQUEST, EcoreEventWindowRedrawRequest, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_WINDOW_REDRAW_REQUEST, EcoreEventWindowRedrawRequest, this)); // Register Vconf notify - font name and size - vconf_notify_key_changed( DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged, this ); - vconf_notify_key_changed( VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, this ); + vconf_notify_key_changed(DALI_VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_NAME, VconfNotifyFontNameChanged, this); + vconf_notify_key_changed(VCONFKEY_SETAPPL_ACCESSIBILITY_FONT_SIZE, VconfNotifyFontSizeChanged, this); InitializeEcoreElDBus(); - Ecore_Wl2_Display* display = ecore_wl2_connected_display_get( NULL ); - mDisplay = ecore_wl2_display_get( display ); + Ecore_Wl2_Display* display = ecore_wl2_connected_display_get(NULL); + mDisplay = ecore_wl2_display_get(display); - if( mDisplay ) + if(mDisplay) { - wl_display* displayWrapper = static_cast< wl_display* >( wl_proxy_create_wrapper( mDisplay ) ); - if( displayWrapper ) + wl_display* displayWrapper = static_cast(wl_proxy_create_wrapper(mDisplay)); + if(displayWrapper) { - mEventQueue = wl_display_create_queue( mDisplay ); - if( mEventQueue ) + mEventQueue = wl_display_create_queue(mDisplay); + if(mEventQueue) { - wl_proxy_set_queue( reinterpret_cast< wl_proxy* >( displayWrapper ), mEventQueue ); + wl_proxy_set_queue(reinterpret_cast(displayWrapper), mEventQueue); - wl_registry* registry = wl_display_get_registry( displayWrapper ); - wl_registry_add_listener( registry, ®istryListener, this ); + wl_registry* registry = wl_display_get_registry(displayWrapper); + wl_registry_add_listener(registry, ®istryListener, this); } - wl_proxy_wrapper_destroy( displayWrapper ); + wl_proxy_wrapper_destroy(displayWrapper); } } - Ecore_Wl2_Input* ecoreWlInput = ecore_wl2_input_default_input_get( display ); + Ecore_Wl2_Input* ecoreWlInput = ecore_wl2_input_default_input_get(display); - if( ecoreWlInput ) + if(ecoreWlInput) { - mKeyMap = ecore_wl2_input_keymap_get( ecoreWlInput ); + mKeyMap = ecore_wl2_input_keymap_get(ecoreWlInput); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_WL2_EVENT_SEAT_KEYMAP_CHANGED, EcoreEventSeatKeymapChanged, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_WL2_EVENT_SEAT_KEYMAP_CHANGED, EcoreEventSeatKeymapChanged, this)); } // get auxiliary hint - Eina_List* hints = ecore_wl2_window_aux_hints_supported_get( mEcoreWindow ); - if( hints ) + Eina_List* hints = ecore_wl2_window_aux_hints_supported_get(mEcoreWindow); + if(hints) { - Eina_List* l = NULL; - char* hint = NULL; + Eina_List* l = NULL; + char* hint = NULL; - for( l = hints, ( hint = static_cast< char* >( eina_list_data_get(l) ) ); l; l = eina_list_next(l), ( hint = static_cast< char* >( eina_list_data_get(l) ) ) ) + for(l = hints, (hint = static_cast(eina_list_data_get(l))); l; l = eina_list_next(l), (hint = static_cast(eina_list_data_get(l)))) { - mSupportedAuxiliaryHints.push_back( hint ); + mSupportedAuxiliaryHints.push_back(hint); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::Initialize: %s\n", hint ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::Initialize: %s\n", hint); } } } -Eina_Bool WindowBaseEcoreWl2::OnIconifyStateChanged( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl2::OnIconifyStateChanged(void* data, int type, void* event) { - Ecore_Wl2_Event_Window_Iconify_State_Change* iconifyChangedEvent( static_cast< Ecore_Wl2_Event_Window_Iconify_State_Change* >( event ) ); - Eina_Bool handled( ECORE_CALLBACK_PASS_ON ); + Ecore_Wl2_Event_Window_Iconify_State_Change* iconifyChangedEvent(static_cast(event)); + Eina_Bool handled(ECORE_CALLBACK_PASS_ON); - if( iconifyChangedEvent->win == static_cast< unsigned int>( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(iconifyChangedEvent->win == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - if( iconifyChangedEvent->iconified == EINA_TRUE ) + if(iconifyChangedEvent->iconified == EINA_TRUE) { - mIconifyChangedSignal.Emit( true ); + mIconifyChangedSignal.Emit(true); } else { - mIconifyChangedSignal.Emit( false ); + mIconifyChangedSignal.Emit(false); } handled = ECORE_CALLBACK_DONE; } @@ -917,41 +909,41 @@ Eina_Bool WindowBaseEcoreWl2::OnIconifyStateChanged( void* data, int type, void* return handled; } -Eina_Bool WindowBaseEcoreWl2::OnFocusIn( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl2::OnFocusIn(void* data, int type, void* event) { - Ecore_Wl2_Event_Focus_In* focusInEvent( static_cast< Ecore_Wl2_Event_Focus_In* >( event ) ); + Ecore_Wl2_Event_Focus_In* focusInEvent(static_cast(event)); - if( focusInEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(focusInEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n"); - mFocusChangedSignal.Emit( true ); + mFocusChangedSignal.Emit(true); } return ECORE_CALLBACK_PASS_ON; } -Eina_Bool WindowBaseEcoreWl2::OnFocusOut( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl2::OnFocusOut(void* data, int type, void* event) { - Ecore_Wl2_Event_Focus_Out* focusOutEvent( static_cast< Ecore_Wl2_Event_Focus_Out* >( event ) ); + Ecore_Wl2_Event_Focus_Out* focusOutEvent(static_cast(event)); - if( focusOutEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(focusOutEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n"); - mFocusChangedSignal.Emit( false ); + mFocusChangedSignal.Emit(false); } return ECORE_CALLBACK_PASS_ON; } -Eina_Bool WindowBaseEcoreWl2::OnOutputTransform( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl2::OnOutputTransform(void* data, int type, void* event) { - Ecore_Wl2_Event_Output_Transform* transformEvent( static_cast< Ecore_Wl2_Event_Output_Transform* >( event ) ); + Ecore_Wl2_Event_Output_Transform* transformEvent(static_cast(event)); - if( transformEvent->output == ecore_wl2_window_output_find( mEcoreWindow ) ) + if(transformEvent->output == ecore_wl2_window_output_find(mEcoreWindow)) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventOutputTransform\n", mEcoreWindow ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventOutputTransform\n", mEcoreWindow); mScreenRotationAngle = GetScreenRotationAngle(); @@ -961,13 +953,13 @@ Eina_Bool WindowBaseEcoreWl2::OnOutputTransform( void* data, int type, void* eve return ECORE_CALLBACK_PASS_ON; } -Eina_Bool WindowBaseEcoreWl2::OnIgnoreOutputTransform( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreWl2::OnIgnoreOutputTransform(void* data, int type, void* event) { - Ecore_Wl2_Event_Ignore_Output_Transform* ignoreTransformEvent( static_cast< Ecore_Wl2_Event_Ignore_Output_Transform* >( event ) ); + Ecore_Wl2_Event_Ignore_Output_Transform* ignoreTransformEvent(static_cast(event)); - if( ignoreTransformEvent->win == mEcoreWindow ) + if(ignoreTransformEvent->win == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventIgnoreOutputTransform\n", mEcoreWindow ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window (%p) EcoreEventIgnoreOutputTransform\n", mEcoreWindow); mScreenRotationAngle = GetScreenRotationAngle(); @@ -1008,11 +1000,11 @@ void WindowBaseEcoreWl2::OnRotation(void* data, int type, void* event) } } -void WindowBaseEcoreWl2::OnConfiguration( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnConfiguration(void* data, int type, void* event) { - Ecore_Wl2_Event_Window_Configure* ev( static_cast< Ecore_Wl2_Event_Window_Configure* >( event ) ); + Ecore_Wl2_Event_Window_Configure* ev(static_cast(event)); - if( ev->win == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(ev->win == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { // Note: To comply with the wayland protocol, Dali should make an ack_configure // by calling ecore_wl2_window_commit @@ -1020,315 +1012,315 @@ void WindowBaseEcoreWl2::OnConfiguration( void* data, int type, void* event ) } } -void WindowBaseEcoreWl2::OnMouseButtonDown( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnMouseButtonDown(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - Device::Class::Type deviceClass; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass ); + GetDeviceClass(ecore_device_class_get(touchEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(touchEvent->dev), deviceSubclass); - PointState::Type state ( PointState::DOWN ); + PointState::Type state(PointState::DOWN); - if( deviceClass != Device::Class::Type::MOUSE ) + if(deviceClass != Device::Class::Type::MOUSE) { // Check if the buttons field is set and ensure it's the primary touch button. // If this event was triggered by buttons other than the primary button (used for touch), then // just send an interrupted event to Core. - if( touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID ) ) + if(touchEvent->buttons && (touchEvent->buttons != PRIMARY_TOUCH_BUTTON_ID)) { state = PointState::INTERRUPTED; } } Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( state ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - point.SetDeviceClass( deviceClass ); - point.SetDeviceSubclass( deviceSubclass ); - point.SetMouseButton( static_cast< MouseButton::Type >( touchEvent->buttons) ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(state); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + point.SetDeviceClass(deviceClass); + point.SetDeviceSubclass(deviceSubclass); + point.SetMouseButton(static_cast(touchEvent->buttons)); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreWl2::OnMouseButtonUp( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnMouseButtonUp(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - Device::Class::Type deviceClass; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass ); + GetDeviceClass(ecore_device_class_get(touchEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(touchEvent->dev), deviceSubclass); Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::UP ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - point.SetDeviceClass( deviceClass ); - point.SetDeviceSubclass( deviceSubclass ); - point.SetMouseButton( static_cast< MouseButton::Type >( touchEvent->buttons) ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::UP); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + point.SetDeviceClass(deviceClass); + point.SetDeviceSubclass(deviceSubclass); + point.SetMouseButton(static_cast(touchEvent->buttons)); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreWl2::OnMouseButtonMove( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnMouseButtonMove(void* data, int type, void* event) { - Ecore_Event_Mouse_Move* touchEvent = static_cast< Ecore_Event_Mouse_Move* >( event ); + Ecore_Event_Mouse_Move* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - Device::Class::Type deviceClass; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceClass( ecore_device_class_get( touchEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( touchEvent->dev ), deviceSubclass ); + GetDeviceClass(ecore_device_class_get(touchEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(touchEvent->dev), deviceSubclass); Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::MOTION ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - point.SetDeviceClass( deviceClass ); - point.SetDeviceSubclass( deviceSubclass ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::MOTION); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + point.SetDeviceClass(deviceClass); + point.SetDeviceSubclass(deviceSubclass); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreWl2::OnMouseButtonCancel( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnMouseButtonCancel(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(touchEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::INTERRUPTED ); - point.SetScreenPosition( Vector2( 0.0f, 0.0f ) ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::INTERRUPTED); + point.SetScreenPosition(Vector2(0.0f, 0.0f)); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnMouseButtonCancel\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnMouseButtonCancel\n"); } } -void WindowBaseEcoreWl2::OnMouseWheel( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnMouseWheel(void* data, int type, void* event) { - Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast< Ecore_Event_Mouse_Wheel* >( event ); + Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast(event); - if( mouseWheelEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(mouseWheelEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z); - Integration::WheelEvent wheelEvent( Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2( mouseWheelEvent->x, mouseWheelEvent->y ), mouseWheelEvent->z, mouseWheelEvent->timestamp ); + Integration::WheelEvent wheelEvent(Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(mouseWheelEvent->x, mouseWheelEvent->y), mouseWheelEvent->z, mouseWheelEvent->timestamp); - mWheelEventSignal.Emit( wheelEvent ); + mWheelEventSignal.Emit(wheelEvent); } } -void WindowBaseEcoreWl2::OnDetentRotation( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnDetentRotation(void* data, int type, void* event) { - Ecore_Event_Detent_Rotate* detentEvent = static_cast< Ecore_Event_Detent_Rotate* >( event ); + Ecore_Event_Detent_Rotate* detentEvent = static_cast(event); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::OnDetentRotation\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::OnDetentRotation\n"); - int direction = ( detentEvent->direction == ECORE_DETENT_DIRECTION_CLOCKWISE ) ? 1 : -1; + int direction = (detentEvent->direction == ECORE_DETENT_DIRECTION_CLOCKWISE) ? 1 : -1; int timeStamp = detentEvent->timestamp; - Integration::WheelEvent wheelEvent( Integration::WheelEvent::CUSTOM_WHEEL, direction, 0, Vector2( 0.0f, 0.0f ), 0, timeStamp ); + Integration::WheelEvent wheelEvent(Integration::WheelEvent::CUSTOM_WHEEL, direction, 0, Vector2(0.0f, 0.0f), 0, timeStamp); - mWheelEventSignal.Emit( wheelEvent ); + mWheelEventSignal.Emit(wheelEvent); } -void WindowBaseEcoreWl2::OnKeyDown( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnKeyDown(void* data, int type, void* event) { - Ecore_Event_Key* keyEvent = static_cast< Ecore_Event_Key* >( event ); + Ecore_Event_Key* keyEvent = static_cast(event); - if( keyEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(keyEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnKeyDown\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnKeyDown\n"); - std::string keyName( keyEvent->keyname ); - std::string logicalKey( "" ); - std::string keyString( "" ); - std::string compose( "" ); + std::string keyName(keyEvent->keyname); + std::string logicalKey(""); + std::string keyString(""); + std::string compose(""); // Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string. - if( keyEvent->compose ) + if(keyEvent->compose) { compose = keyEvent->compose; } // Ensure key symbol is not NULL as keys like SHIFT have a null string. - if( keyEvent->key ) + if(keyEvent->key) { logicalKey = keyEvent->key; } int keyCode = 0; - GetKeyCode( keyName, keyCode ); // Get key code dynamically. + GetKeyCode(keyName, keyCode); // Get key code dynamically. - if( keyCode == 0 ) + if(keyCode == 0) { // Get a specific key code from dali key look up table. - keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname ); + keyCode = KeyLookup::GetDaliKeyCode(keyEvent->keyname); } - keyCode = ( keyCode == -1 ) ? 0 : keyCode; - int modifier( keyEvent->modifiers ); + keyCode = (keyCode == -1) ? 0 : keyCode; + int modifier(keyEvent->modifiers); unsigned long time = keyEvent->timestamp; - if( !strncmp( keyEvent->keyname, "Keycode-", 8 ) ) + if(!strncmp(keyEvent->keyname, "Keycode-", 8)) { - keyCode = atoi( keyEvent->keyname + 8 ); + keyCode = atoi(keyEvent->keyname + 8); } // Ensure key event string is not NULL as keys like SHIFT have a null string. - if( keyEvent->string ) + if(keyEvent->string) { keyString = keyEvent->string; } - std::string deviceName; - Device::Class::Type deviceClass; + std::string deviceName; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceName( keyEvent, deviceName ); - GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass ); + GetDeviceName(keyEvent, deviceName); + GetDeviceClass(ecore_device_class_get(keyEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(keyEvent->dev), deviceSubclass); - Integration::KeyEvent keyEvent( keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, deviceName, deviceClass, deviceSubclass ); + Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, deviceName, deviceClass, deviceSubclass); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseEcoreWl2::OnKeyUp( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnKeyUp(void* data, int type, void* event) { - Ecore_Event_Key* keyEvent = static_cast< Ecore_Event_Key* >( event ); + Ecore_Event_Key* keyEvent = static_cast(event); - if( keyEvent->window == static_cast< unsigned int >( ecore_wl2_window_id_get( mEcoreWindow ) ) ) + if(keyEvent->window == static_cast(ecore_wl2_window_id_get(mEcoreWindow))) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnKeyUp\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnKeyUp\n"); #if defined(ECORE_VERSION_MAJOR) && (ECORE_VERSION_MAJOR >= 1) && defined(ECORE_VERSION_MINOR) && (ECORE_VERSION_MINOR >= 23) // Cancel processing flag is sent because this key event will combine with the previous key. So, the event should not actually perform anything. - if( keyEvent->event_flags & ECORE_EVENT_FLAG_CANCEL ) + if(keyEvent->event_flags & ECORE_EVENT_FLAG_CANCEL) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnKeyUp: This event flag indicates the event is canceled. \n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::OnKeyUp: This event flag indicates the event is canceled. \n"); return; } #endif // Since ecore 1.23 version - std::string keyName( keyEvent->keyname ); - std::string logicalKey( "" ); - std::string keyString( "" ); - std::string compose( "" ); + std::string keyName(keyEvent->keyname); + std::string logicalKey(""); + std::string keyString(""); + std::string compose(""); // Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string. - if( keyEvent->compose ) + if(keyEvent->compose) { compose = keyEvent->compose; } // Ensure key symbol is not NULL as keys like SHIFT have a null string. - if( keyEvent->key ) + if(keyEvent->key) { logicalKey = keyEvent->key; } int keyCode = 0; - GetKeyCode( keyName, keyCode ); // Get key code dynamically. + GetKeyCode(keyName, keyCode); // Get key code dynamically. - if( keyCode == 0 ) + if(keyCode == 0) { // Get a specific key code from dali key look up table. - keyCode = KeyLookup::GetDaliKeyCode( keyEvent->keyname ); + keyCode = KeyLookup::GetDaliKeyCode(keyEvent->keyname); } - keyCode = ( keyCode == -1 ) ? 0 : keyCode; - int modifier( keyEvent->modifiers ); + keyCode = (keyCode == -1) ? 0 : keyCode; + int modifier(keyEvent->modifiers); unsigned long time = keyEvent->timestamp; - if( !strncmp( keyEvent->keyname, "Keycode-", 8 ) ) + if(!strncmp(keyEvent->keyname, "Keycode-", 8)) { - keyCode = atoi( keyEvent->keyname + 8 ); + keyCode = atoi(keyEvent->keyname + 8); } // Ensure key event string is not NULL as keys like SHIFT have a null string. - if( keyEvent->string ) + if(keyEvent->string) { keyString = keyEvent->string; } - std::string deviceName; - Device::Class::Type deviceClass; + std::string deviceName; + Device::Class::Type deviceClass; Device::Subclass::Type deviceSubclass; - GetDeviceName( keyEvent, deviceName ); - GetDeviceClass( ecore_device_class_get( keyEvent->dev ), deviceClass ); - GetDeviceSubclass( ecore_device_subclass_get( keyEvent->dev ), deviceSubclass ); + GetDeviceName(keyEvent, deviceName); + GetDeviceClass(ecore_device_class_get(keyEvent->dev), deviceClass); + GetDeviceSubclass(ecore_device_subclass_get(keyEvent->dev), deviceSubclass); - Integration::KeyEvent keyEvent( keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, deviceName, deviceClass, deviceSubclass ); + Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, deviceName, deviceClass, deviceSubclass); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseEcoreWl2::OnDataSend( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnDataSend(void* data, int type, void* event) { - mSelectionDataSendSignal.Emit( event ); + mSelectionDataSendSignal.Emit(event); } -void WindowBaseEcoreWl2::OnDataReceive( void* data, int type, void* event ) +void WindowBaseEcoreWl2::OnDataReceive(void* data, int type, void* event) { - mSelectionDataReceivedSignal.Emit( event ); + mSelectionDataReceivedSignal.Emit(event); } void WindowBaseEcoreWl2::OnFontNameChanged() { - mStyleChangedSignal.Emit( StyleChange::DEFAULT_FONT_CHANGE ); + mStyleChangedSignal.Emit(StyleChange::DEFAULT_FONT_CHANGE); } void WindowBaseEcoreWl2::OnFontSizeChanged() { - mStyleChangedSignal.Emit( StyleChange::DEFAULT_FONT_SIZE_CHANGE ); + mStyleChangedSignal.Emit(StyleChange::DEFAULT_FONT_SIZE_CHANGE); } -void WindowBaseEcoreWl2::OnEcoreElDBusAccessibilityNotification( void* context, const Eldbus_Message* message ) +void WindowBaseEcoreWl2::OnEcoreElDBusAccessibilityNotification(void* context, const Eldbus_Message* message) { #ifdef DALI_ELDBUS_AVAILABLE AccessibilityInfo info; // The string defines the arg-list's respective types. - if( !eldbus_message_arguments_get( message, "iiiiiiu", &info.gestureValue, &info.startX, &info.startY, &info.endX, &info.endY, &info.state, &info.eventTime ) ) + if(!eldbus_message_arguments_get(message, "iiiiiiu", &info.gestureValue, &info.startX, &info.startY, &info.endX, &info.endY, &info.state, &info.eventTime)) { - DALI_LOG_ERROR( "OnEcoreElDBusAccessibilityNotification: Error getting arguments\n" ); + DALI_LOG_ERROR("OnEcoreElDBusAccessibilityNotification: Error getting arguments\n"); } - mAccessibilitySignal.Emit( info ); + mAccessibilitySignal.Emit(info); #endif } -void WindowBaseEcoreWl2::OnTransitionEffectEvent( WindowEffectState state, WindowEffectType type ) +void WindowBaseEcoreWl2::OnTransitionEffectEvent(WindowEffectState state, WindowEffectType type) { - mTransitionEffectEventSignal.Emit( state, type ); + mTransitionEffectEventSignal.Emit(state, type); } void WindowBaseEcoreWl2::OnKeyboardRepeatSettingsChanged() @@ -1341,98 +1333,98 @@ void WindowBaseEcoreWl2::OnEcoreEventWindowRedrawRequest() mWindowRedrawRequestSignal.Emit(); } -void WindowBaseEcoreWl2::KeymapChanged(void *data, int type, void *event) +void WindowBaseEcoreWl2::KeymapChanged(void* data, int type, void* event) { - Ecore_Wl2_Event_Seat_Keymap_Changed *changed = static_cast( event ); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::KeymapChanged, keymap id[ %d ]\n", changed->id ); - Ecore_Wl2_Input* ecoreWlInput = ecore_wl2_input_default_input_get( changed->display ); - if( ecoreWlInput ) + Ecore_Wl2_Event_Seat_Keymap_Changed* changed = static_cast(event); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::KeymapChanged, keymap id[ %d ]\n", changed->id); + Ecore_Wl2_Input* ecoreWlInput = ecore_wl2_input_default_input_get(changed->display); + if(ecoreWlInput) { - mKeyMap = ecore_wl2_input_keymap_get( ecoreWlInput ); + mKeyMap = ecore_wl2_input_keymap_get(ecoreWlInput); } } -void WindowBaseEcoreWl2::RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version ) +void WindowBaseEcoreWl2::RegistryGlobalCallback(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version) { - if( strcmp( interface, tizen_policy_interface.name ) == 0 ) + if(strcmp(interface, tizen_policy_interface.name) == 0) { - uint32_t clientVersion = std::min( version, MAX_TIZEN_CLIENT_VERSION ); + uint32_t clientVersion = std::min(version, MAX_TIZEN_CLIENT_VERSION); - mTizenPolicy = static_cast< tizen_policy* >( wl_registry_bind( registry, name, &tizen_policy_interface, clientVersion ) ); - if( !mTizenPolicy ) + mTizenPolicy = static_cast(wl_registry_bind(registry, name, &tizen_policy_interface, clientVersion)); + if(!mTizenPolicy) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: wl_registry_bind(tizen_policy_interface) is failed.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: wl_registry_bind(tizen_policy_interface) is failed.\n"); return; } - tizen_policy_add_listener( mTizenPolicy, &tizenPolicyListener, data ); + tizen_policy_add_listener(mTizenPolicy, &tizenPolicyListener, data); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: tizen_policy_add_listener is called.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: tizen_policy_add_listener is called.\n"); } - else if( strcmp( interface, tizen_display_policy_interface.name ) == 0 ) + else if(strcmp(interface, tizen_display_policy_interface.name) == 0) { - mTizenDisplayPolicy = static_cast< tizen_display_policy* >( wl_registry_bind( registry, name, &tizen_display_policy_interface, version ) ); - if( !mTizenDisplayPolicy ) + mTizenDisplayPolicy = static_cast(wl_registry_bind(registry, name, &tizen_display_policy_interface, version)); + if(!mTizenDisplayPolicy) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: wl_registry_bind(tizen_display_policy_interface) is failed.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: wl_registry_bind(tizen_display_policy_interface) is failed.\n"); return; } - tizen_display_policy_add_listener( mTizenDisplayPolicy, &tizenDisplayPolicyListener, data ); + tizen_display_policy_add_listener(mTizenDisplayPolicy, &tizenDisplayPolicyListener, data); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: tizen_display_policy_add_listener is called.\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::RegistryGlobalCallback: tizen_display_policy_add_listener is called.\n"); } } -void WindowBaseEcoreWl2::RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id ) +void WindowBaseEcoreWl2::RegistryGlobalCallbackRemove(void* data, struct wl_registry* registry, uint32_t id) { - mTizenPolicy = NULL; + mTizenPolicy = NULL; mTizenDisplayPolicy = NULL; } -void WindowBaseEcoreWl2::TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state ) +void WindowBaseEcoreWl2::TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state) { - mNotificationLevel = level; - mNotificationChangeState = state; + mNotificationLevel = level; + mNotificationChangeState = state; mNotificationLevelChangeDone = true; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::TizenPolicyNotificationChangeDone: level = %d, state = %d\n", level, state ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::TizenPolicyNotificationChangeDone: level = %d, state = %d\n", level, state); } -void WindowBaseEcoreWl2::TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state ) +void WindowBaseEcoreWl2::TizenPolicyScreenModeChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state) { - mScreenOffMode = mode; + mScreenOffMode = mode; mScreenOffModeChangeState = state; - mScreenOffModeChangeDone = true; + mScreenOffModeChangeDone = true; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::TizenPolicyScreenModeChangeDone: mode = %d, state = %d\n", mode, state ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::TizenPolicyScreenModeChangeDone: mode = %d, state = %d\n", mode, state); } -void WindowBaseEcoreWl2::DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state ) +void WindowBaseEcoreWl2::DisplayPolicyBrightnessChangeDone(void* data, struct tizen_display_policy* displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state) { - mBrightness = brightness; + mBrightness = brightness; mBrightnessChangeState = state; - mBrightnessChangeDone = true; + mBrightnessChangeDone = true; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::DisplayPolicyBrightnessChangeDone: brightness = %d, state = %d\n", brightness, state ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreWl2::DisplayPolicyBrightnessChangeDone: brightness = %d, state = %d\n", brightness, state); } -void WindowBaseEcoreWl2::GetKeyCode( std::string keyName, int32_t& keyCode ) +void WindowBaseEcoreWl2::GetKeyCode(std::string keyName, int32_t& keyCode) { xkb_keysym_t sym = XKB_KEY_NoSymbol; - KeyCodeMap foundKeyCode; + KeyCodeMap foundKeyCode; - sym = xkb_keysym_from_name( keyName.c_str(), XKB_KEYSYM_NO_FLAGS ); - if( sym == XKB_KEY_NoSymbol ) + sym = xkb_keysym_from_name(keyName.c_str(), XKB_KEYSYM_NO_FLAGS); + if(sym == XKB_KEY_NoSymbol) { - DALI_LOG_ERROR( "Failed to get keysym in WindowBaseEcoreWl2\n" ); + DALI_LOG_ERROR("Failed to get keysym in WindowBaseEcoreWl2\n"); return; } - foundKeyCode.keySym = sym; + foundKeyCode.keySym = sym; foundKeyCode.isKeyCode = false; - xkb_keymap_key_for_each( mKeyMap, FindKeyCode, &foundKeyCode ); - keyCode = static_cast< int32_t >( foundKeyCode.keyCode ); + xkb_keymap_key_for_each(mKeyMap, FindKeyCode, &foundKeyCode); + keyCode = static_cast(foundKeyCode.keyCode); } Any WindowBaseEcoreWl2::GetNativeWindow() @@ -1442,7 +1434,7 @@ Any WindowBaseEcoreWl2::GetNativeWindow() int WindowBaseEcoreWl2::GetNativeWindowId() { - return ecore_wl2_window_id_get( mEcoreWindow ); + return ecore_wl2_window_id_get(mEcoreWindow); } EGLNativeWindowType WindowBaseEcoreWl2::CreateEglWindow(int width, int height) @@ -1462,22 +1454,22 @@ EGLNativeWindowType WindowBaseEcoreWl2::CreateEglWindow(int width, int height) void WindowBaseEcoreWl2::DestroyEglWindow() { - if( mEglWindow != NULL ) + if(mEglWindow != NULL) { - wl_egl_window_destroy( mEglWindow ); + wl_egl_window_destroy(mEglWindow); mEglWindow = NULL; } } -void WindowBaseEcoreWl2::SetEglWindowRotation( int angle ) +void WindowBaseEcoreWl2::SetEglWindowRotation(int angle) { wl_egl_window_tizen_rotation rotation; - switch( angle ) + switch(angle) { case 0: { - rotation = WL_EGL_WINDOW_TIZEN_ROTATION_0 ; + rotation = WL_EGL_WINDOW_TIZEN_ROTATION_0; break; } case 90: @@ -1497,19 +1489,19 @@ void WindowBaseEcoreWl2::SetEglWindowRotation( int angle ) } default: { - rotation = WL_EGL_WINDOW_TIZEN_ROTATION_0 ; + rotation = WL_EGL_WINDOW_TIZEN_ROTATION_0; break; } } - wl_egl_window_tizen_set_rotation( mEglWindow, rotation ); + wl_egl_window_tizen_set_rotation(mEglWindow, rotation); } -void WindowBaseEcoreWl2::SetEglWindowBufferTransform( int angle ) +void WindowBaseEcoreWl2::SetEglWindowBufferTransform(int angle) { wl_output_transform bufferTransform; - switch( angle ) + switch(angle) { case 0: { @@ -1538,14 +1530,14 @@ void WindowBaseEcoreWl2::SetEglWindowBufferTransform( int angle ) } } - wl_egl_window_tizen_set_buffer_transform( mEglWindow, bufferTransform ); + wl_egl_window_tizen_set_buffer_transform(mEglWindow, bufferTransform); } -void WindowBaseEcoreWl2::SetEglWindowTransform( int angle ) +void WindowBaseEcoreWl2::SetEglWindowTransform(int angle) { wl_output_transform windowTransform; - switch( angle ) + switch(angle) { case 0: { @@ -1574,17 +1566,17 @@ void WindowBaseEcoreWl2::SetEglWindowTransform( int angle ) } } - wl_egl_window_tizen_set_window_transform( mEglWindow, windowTransform ); + wl_egl_window_tizen_set_window_transform(mEglWindow, windowTransform); } -void WindowBaseEcoreWl2::ResizeEglWindow( PositionSize positionSize ) +void WindowBaseEcoreWl2::ResizeEglWindow(PositionSize positionSize) { - wl_egl_window_resize( mEglWindow, positionSize.width, positionSize.height, positionSize.x, positionSize.y ); + wl_egl_window_resize(mEglWindow, positionSize.width, positionSize.height, positionSize.x, positionSize.y); // Note: Both "Resize" and "MoveResize" cases can reach here, but only "MoveResize" needs to submit serial number - if( mMoveResizeSerial != mLastSubmittedMoveResizeSerial ) + if(mMoveResizeSerial != mLastSubmittedMoveResizeSerial) { - wl_egl_window_tizen_set_window_serial( mEglWindow, mMoveResizeSerial ); + wl_egl_window_tizen_set_window_serial(mEglWindow, mMoveResizeSerial); mLastSubmittedMoveResizeSerial = mMoveResizeSerial; } } @@ -1602,44 +1594,44 @@ bool WindowBaseEcoreWl2::IsEglWindowRotationSupported() return false; } -void WindowBaseEcoreWl2::Move( PositionSize positionSize ) +void WindowBaseEcoreWl2::Move(PositionSize positionSize) { mWindowPositionSize = positionSize; - ecore_wl2_window_position_set( mEcoreWindow, positionSize.x, positionSize.y ); + ecore_wl2_window_position_set(mEcoreWindow, positionSize.x, positionSize.y); } -void WindowBaseEcoreWl2::Resize( PositionSize positionSize ) +void WindowBaseEcoreWl2::Resize(PositionSize positionSize) { mWindowPositionSize = positionSize; - ecore_wl2_window_geometry_set( mEcoreWindow, positionSize.x, positionSize.y, positionSize.width, positionSize.height ); + ecore_wl2_window_geometry_set(mEcoreWindow, positionSize.x, positionSize.y, positionSize.width, positionSize.height); } -void WindowBaseEcoreWl2::MoveResize( PositionSize positionSize ) +void WindowBaseEcoreWl2::MoveResize(PositionSize positionSize) { mWindowPositionSize = positionSize; - ecore_wl2_window_sync_geometry_set( mEcoreWindow, ++mMoveResizeSerial, positionSize.x, positionSize.y, positionSize.width, positionSize.height ); + ecore_wl2_window_sync_geometry_set(mEcoreWindow, ++mMoveResizeSerial, positionSize.x, positionSize.y, positionSize.width, positionSize.height); } -void WindowBaseEcoreWl2::SetClass( const std::string& name, const std::string& className ) +void WindowBaseEcoreWl2::SetClass(const std::string& name, const std::string& className) { - ecore_wl2_window_title_set( mEcoreWindow, name.c_str() ); - ecore_wl2_window_class_set( mEcoreWindow, className.c_str() ); + ecore_wl2_window_title_set(mEcoreWindow, name.c_str()); + ecore_wl2_window_class_set(mEcoreWindow, className.c_str()); } void WindowBaseEcoreWl2::Raise() { // Use ecore_wl2_window_activate to prevent the window shown without rendering - ecore_wl2_window_activate( mEcoreWindow ); + ecore_wl2_window_activate(mEcoreWindow); } void WindowBaseEcoreWl2::Lower() { - ecore_wl2_window_lower( mEcoreWindow ); + ecore_wl2_window_lower(mEcoreWindow); } void WindowBaseEcoreWl2::Activate() { - ecore_wl2_window_activate( mEcoreWindow ); + ecore_wl2_window_activate(mEcoreWindow); } void WindowBaseEcoreWl2::SetAvailableAnlges(const std::vector& angles) @@ -1654,32 +1646,32 @@ void WindowBaseEcoreWl2::SetAvailableAnlges(const std::vector& angles) ecore_wl2_window_available_rotations_set(mEcoreWindow, rotations, angles.size()); } -void WindowBaseEcoreWl2::SetPreferredAngle( int angle ) +void WindowBaseEcoreWl2::SetPreferredAngle(int angle) { - DALI_LOG_RELEASE_INFO( "WindowBaseEcoreWl2::SetPreferredAngle, angle: %d\n", angle ); - ecore_wl2_window_preferred_rotation_set( mEcoreWindow, angle ); + DALI_LOG_RELEASE_INFO("WindowBaseEcoreWl2::SetPreferredAngle, angle: %d\n", angle); + ecore_wl2_window_preferred_rotation_set(mEcoreWindow, angle); } -void WindowBaseEcoreWl2::SetAcceptFocus( bool accept ) +void WindowBaseEcoreWl2::SetAcceptFocus(bool accept) { - ecore_wl2_window_focus_skip_set( mEcoreWindow, !accept ); + ecore_wl2_window_focus_skip_set(mEcoreWindow, !accept); } void WindowBaseEcoreWl2::Show() { - if( !mVisible ) + if(!mVisible) { - ecore_wl2_window_geometry_set( mEcoreWindow, mWindowPositionSize.x, mWindowPositionSize.y, mWindowPositionSize.width, mWindowPositionSize.height ); + ecore_wl2_window_geometry_set(mEcoreWindow, mWindowPositionSize.x, mWindowPositionSize.y, mWindowPositionSize.width, mWindowPositionSize.height); } mVisible = true; - ecore_wl2_window_show( mEcoreWindow ); + ecore_wl2_window_show(mEcoreWindow); } void WindowBaseEcoreWl2::Hide() { mVisible = false; - ecore_wl2_window_hide( mEcoreWindow ); + ecore_wl2_window_hide(mEcoreWindow); } unsigned int WindowBaseEcoreWl2::GetSupportedAuxiliaryHintCount() const @@ -1687,135 +1679,135 @@ unsigned int WindowBaseEcoreWl2::GetSupportedAuxiliaryHintCount() const return mSupportedAuxiliaryHints.size(); } -std::string WindowBaseEcoreWl2::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string WindowBaseEcoreWl2::GetSupportedAuxiliaryHint(unsigned int index) const { - if( index >= GetSupportedAuxiliaryHintCount() ) + if(index >= GetSupportedAuxiliaryHintCount()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetSupportedAuxiliaryHint: Invalid index! [%d]\n", index ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetSupportedAuxiliaryHint: Invalid index! [%d]\n", index); } return mSupportedAuxiliaryHints[index]; } -unsigned int WindowBaseEcoreWl2::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int WindowBaseEcoreWl2::AddAuxiliaryHint(const std::string& hint, const std::string& value) { bool supported = false; // Check if the hint is suppported - for( std::vector< std::string >::iterator iter = mSupportedAuxiliaryHints.begin(); iter != mSupportedAuxiliaryHints.end(); ++iter ) + for(std::vector::iterator iter = mSupportedAuxiliaryHints.begin(); iter != mSupportedAuxiliaryHints.end(); ++iter) { - if( *iter == hint ) + if(*iter == hint) { supported = true; break; } } - if( !supported ) + if(!supported) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::AddAuxiliaryHint: Not supported auxiliary hint [%s]\n", hint.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::AddAuxiliaryHint: Not supported auxiliary hint [%s]\n", hint.c_str()); return 0; } // Check if the hint is already added - for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ ) + for(unsigned int i = 0; i < mAuxiliaryHints.size(); i++) { - if( mAuxiliaryHints[i].first == hint ) + if(mAuxiliaryHints[i].first == hint) { // Just change the value mAuxiliaryHints[i].second = value; - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::AddAuxiliaryHint: Change! hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), i + 1 ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::AddAuxiliaryHint: Change! hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), i + 1); - return i + 1; // id is index + 1 + return i + 1; // id is index + 1 } } // Add the hint - mAuxiliaryHints.push_back( std::pair< std::string, std::string >( hint, value ) ); + mAuxiliaryHints.push_back(std::pair(hint, value)); unsigned int id = mAuxiliaryHints.size(); - ecore_wl2_window_aux_hint_add( mEcoreWindow, static_cast< int >( id ), hint.c_str(), value.c_str() ); + ecore_wl2_window_aux_hint_add(mEcoreWindow, static_cast(id), hint.c_str(), value.c_str()); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::AddAuxiliaryHint: hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::AddAuxiliaryHint: hint = %s, value = %s, id = %d\n", hint.c_str(), value.c_str(), id); return id; } -bool WindowBaseEcoreWl2::RemoveAuxiliaryHint( unsigned int id ) +bool WindowBaseEcoreWl2::RemoveAuxiliaryHint(unsigned int id) { - if( id == 0 || id > mAuxiliaryHints.size() ) + if(id == 0 || id > mAuxiliaryHints.size()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::RemoveAuxiliaryHint: Invalid id [%d]\n", id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::RemoveAuxiliaryHint: Invalid id [%d]\n", id); return false; } mAuxiliaryHints[id - 1].second = std::string(); - ecore_wl2_window_aux_hint_del( mEcoreWindow, static_cast< int >( id ) ); + ecore_wl2_window_aux_hint_del(mEcoreWindow, static_cast(id)); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::RemoveAuxiliaryHint: id = %d, hint = %s\n", id, mAuxiliaryHints[id - 1].first.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::RemoveAuxiliaryHint: id = %d, hint = %s\n", id, mAuxiliaryHints[id - 1].first.c_str()); return true; } -bool WindowBaseEcoreWl2::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool WindowBaseEcoreWl2::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { - if( id == 0 || id > mAuxiliaryHints.size() ) + if(id == 0 || id > mAuxiliaryHints.size()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::SetAuxiliaryHintValue: Invalid id [%d]\n", id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::SetAuxiliaryHintValue: Invalid id [%d]\n", id); return false; } mAuxiliaryHints[id - 1].second = value; - ecore_wl2_window_aux_hint_change( mEcoreWindow, static_cast< int >( id ), value.c_str() ); + ecore_wl2_window_aux_hint_change(mEcoreWindow, static_cast(id), value.c_str()); - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str()); return true; } -std::string WindowBaseEcoreWl2::GetAuxiliaryHintValue( unsigned int id ) const +std::string WindowBaseEcoreWl2::GetAuxiliaryHintValue(unsigned int id) const { - if( id == 0 || id > mAuxiliaryHints.size() ) + if(id == 0 || id > mAuxiliaryHints.size()) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::GetAuxiliaryHintValue: Invalid id [%d]\n", id ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, "WindowBaseEcoreWl2::GetAuxiliaryHintValue: Invalid id [%d]\n", id); return std::string(); } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetAuxiliaryHintValue: id = %d, hint = %s, value = %s\n", id, mAuxiliaryHints[id - 1].first.c_str(), mAuxiliaryHints[id - 1].second.c_str()); return mAuxiliaryHints[id - 1].second; } -unsigned int WindowBaseEcoreWl2::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int WindowBaseEcoreWl2::GetAuxiliaryHintId(const std::string& hint) const { - for( unsigned int i = 0; i < mAuxiliaryHints.size(); i++ ) + for(unsigned int i = 0; i < mAuxiliaryHints.size(); i++) { - if( mAuxiliaryHints[i].first == hint ) + if(mAuxiliaryHints[i].first == hint) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetAuxiliaryHintId: hint = %s, id = %d\n", hint.c_str(), i + 1 ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetAuxiliaryHintId: hint = %s, id = %d\n", hint.c_str(), i + 1); return i + 1; } } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetAuxiliaryHintId: Invalid hint! [%s]\n", hint.c_str() ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetAuxiliaryHintId: Invalid hint! [%s]\n", hint.c_str()); return 0; } -void WindowBaseEcoreWl2::SetInputRegion( const Rect< int >& inputRegion ) +void WindowBaseEcoreWl2::SetInputRegion(const Rect& inputRegion) { - ecore_wl2_window_input_region_set( mEcoreWindow, inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height ); + ecore_wl2_window_input_region_set(mEcoreWindow, inputRegion.x, inputRegion.y, inputRegion.width, inputRegion.height); } -void WindowBaseEcoreWl2::SetType( Dali::WindowType type ) +void WindowBaseEcoreWl2::SetType(Dali::WindowType type) { Ecore_Wl2_Window_Type windowType; - switch( type ) + switch(type) { case Dali::WindowType::NORMAL: { @@ -1844,19 +1836,19 @@ void WindowBaseEcoreWl2::SetType( Dali::WindowType type ) } } - ecore_wl2_window_type_set( mEcoreWindow, windowType ); + ecore_wl2_window_type_set(mEcoreWindow, windowType); } -bool WindowBaseEcoreWl2::SetNotificationLevel( Dali::WindowNotificationLevel level ) +bool WindowBaseEcoreWl2::SetNotificationLevel(Dali::WindowNotificationLevel level) { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int notificationLevel; - switch( level ) + switch(level) { case Dali::WindowNotificationLevel::NONE: { @@ -1885,67 +1877,67 @@ bool WindowBaseEcoreWl2::SetNotificationLevel( Dali::WindowNotificationLevel lev } default: { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: invalid level [%d]\n", level ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: invalid level [%d]\n", level); notificationLevel = TIZEN_POLICY_LEVEL_DEFAULT; break; } } mNotificationLevelChangeDone = false; - mNotificationChangeState = TIZEN_POLICY_ERROR_STATE_NONE; + mNotificationChangeState = TIZEN_POLICY_ERROR_STATE_NONE; - tizen_policy_set_notification_level( mTizenPolicy, ecore_wl2_window_surface_get( mEcoreWindow ), notificationLevel ); + tizen_policy_set_notification_level(mTizenPolicy, ecore_wl2_window_surface_get(mEcoreWindow), notificationLevel); int count = 0; - while( !mNotificationLevelChangeDone && count < 3 ) + while(!mNotificationLevelChangeDone && count < 3) { - ecore_wl2_display_flush( ecore_wl2_connected_display_get( NULL ) ); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + ecore_wl2_display_flush(ecore_wl2_connected_display_get(NULL)); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mNotificationLevelChangeDone ) + if(!mNotificationLevelChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: Level change is failed [%d, %d]\n", level, mNotificationChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: Level change is failed [%d, %d]\n", level, mNotificationChangeState); return false; } - else if( mNotificationChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED ) + else if(mNotificationChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: Permission denied! [%d]\n", level ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: Permission denied! [%d]\n", level); return false; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: Level is changed [%d]\n", mNotificationLevel ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetNotificationLevel: Level is changed [%d]\n", mNotificationLevel); return true; } Dali::WindowNotificationLevel WindowBaseEcoreWl2::GetNotificationLevel() const { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int count = 0; - while( !mNotificationLevelChangeDone && count < 3 ) + while(!mNotificationLevelChangeDone && count < 3) { - ecore_wl2_display_flush( ecore_wl2_connected_display_get( NULL ) ); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + ecore_wl2_display_flush(ecore_wl2_connected_display_get(NULL)); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mNotificationLevelChangeDone ) + if(!mNotificationLevelChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetNotificationLevel: Error! [%d]\n", mNotificationChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetNotificationLevel: Error! [%d]\n", mNotificationChangeState); return Dali::WindowNotificationLevel::NONE; } Dali::WindowNotificationLevel level; - switch( mNotificationLevel ) + switch(mNotificationLevel) { case TIZEN_POLICY_LEVEL_NONE: { @@ -1974,40 +1966,40 @@ Dali::WindowNotificationLevel WindowBaseEcoreWl2::GetNotificationLevel() const } default: { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetNotificationLevel: invalid level [%d]\n", mNotificationLevel ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetNotificationLevel: invalid level [%d]\n", mNotificationLevel); level = Dali::WindowNotificationLevel::NONE; break; } } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetNotificationLevel: level [%d]\n", mNotificationLevel ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetNotificationLevel: level [%d]\n", mNotificationLevel); return level; } -void WindowBaseEcoreWl2::SetOpaqueState( bool opaque ) +void WindowBaseEcoreWl2::SetOpaqueState(bool opaque) { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } - tizen_policy_set_opaque_state( mTizenPolicy, ecore_wl2_window_surface_get( mEcoreWindow ), ( opaque ? 1 : 0 ) ); + tizen_policy_set_opaque_state(mTizenPolicy, ecore_wl2_window_surface_get(mEcoreWindow), (opaque ? 1 : 0)); } bool WindowBaseEcoreWl2::SetScreenOffMode(WindowScreenOffMode screenOffMode) { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } - mScreenOffModeChangeDone = false; + mScreenOffModeChangeDone = false; mScreenOffModeChangeState = TIZEN_POLICY_ERROR_STATE_NONE; unsigned int mode = 0; - switch( screenOffMode ) + switch(screenOffMode) { case WindowScreenOffMode::TIMEOUT: { @@ -2021,58 +2013,58 @@ bool WindowBaseEcoreWl2::SetScreenOffMode(WindowScreenOffMode screenOffMode) } } - tizen_policy_set_window_screen_mode( mTizenPolicy, ecore_wl2_window_surface_get( mEcoreWindow ), mode ); + tizen_policy_set_window_screen_mode(mTizenPolicy, ecore_wl2_window_surface_get(mEcoreWindow), mode); int count = 0; - while( !mScreenOffModeChangeDone && count < 3 ) + while(!mScreenOffModeChangeDone && count < 3) { - ecore_wl2_display_flush( ecore_wl2_connected_display_get( NULL ) ); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + ecore_wl2_display_flush(ecore_wl2_connected_display_get(NULL)); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mScreenOffModeChangeDone ) + if(!mScreenOffModeChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetScreenOffMode: Screen mode change is failed [%d, %d]\n", screenOffMode, mScreenOffModeChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetScreenOffMode: Screen mode change is failed [%d, %d]\n", screenOffMode, mScreenOffModeChangeState); return false; } - else if( mScreenOffModeChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED ) + else if(mScreenOffModeChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetScreenOffMode: Permission denied! [%d]\n", screenOffMode ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetScreenOffMode: Permission denied! [%d]\n", screenOffMode); return false; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetScreenOffMode: Screen mode is changed [%d]\n", mScreenOffMode ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetScreenOffMode: Screen mode is changed [%d]\n", mScreenOffMode); return true; } WindowScreenOffMode WindowBaseEcoreWl2::GetScreenOffMode() const { - while( !mTizenPolicy ) + while(!mTizenPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int count = 0; - while( !mScreenOffModeChangeDone && count < 3 ) + while(!mScreenOffModeChangeDone && count < 3) { - ecore_wl2_display_flush( ecore_wl2_connected_display_get( NULL ) ); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + ecore_wl2_display_flush(ecore_wl2_connected_display_get(NULL)); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mScreenOffModeChangeDone ) + if(!mScreenOffModeChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetScreenOffMode: Error! [%d]\n", mScreenOffModeChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetScreenOffMode: Error! [%d]\n", mScreenOffModeChangeState); return WindowScreenOffMode::TIMEOUT; } WindowScreenOffMode screenMode = WindowScreenOffMode::TIMEOUT; - switch( mScreenOffMode ) + switch(mScreenOffMode) { case 0: { @@ -2086,80 +2078,80 @@ WindowScreenOffMode WindowBaseEcoreWl2::GetScreenOffMode() const } } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetScreenOffMode: screen mode [%d]\n", mScreenOffMode ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetScreenOffMode: screen mode [%d]\n", mScreenOffMode); return screenMode; } -bool WindowBaseEcoreWl2::SetBrightness( int brightness ) +bool WindowBaseEcoreWl2::SetBrightness(int brightness) { - while( !mTizenDisplayPolicy ) + while(!mTizenDisplayPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } - mBrightnessChangeDone = false; + mBrightnessChangeDone = false; mBrightnessChangeState = TIZEN_POLICY_ERROR_STATE_NONE; - tizen_display_policy_set_window_brightness( mTizenDisplayPolicy, ecore_wl2_window_surface_get( mEcoreWindow ), brightness ); + tizen_display_policy_set_window_brightness(mTizenDisplayPolicy, ecore_wl2_window_surface_get(mEcoreWindow), brightness); int count = 0; - while( !mBrightnessChangeDone && count < 3 ) + while(!mBrightnessChangeDone && count < 3) { - ecore_wl2_display_flush( ecore_wl2_connected_display_get( NULL ) ); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + ecore_wl2_display_flush(ecore_wl2_connected_display_get(NULL)); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mBrightnessChangeDone ) + if(!mBrightnessChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetBrightness: Brightness change is failed [%d, %d]\n", brightness, mBrightnessChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetBrightness: Brightness change is failed [%d, %d]\n", brightness, mBrightnessChangeState); return false; } - else if( mBrightnessChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED ) + else if(mBrightnessChangeState == TIZEN_POLICY_ERROR_STATE_PERMISSION_DENIED) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetBrightness: Permission denied! [%d]\n", brightness ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetBrightness: Permission denied! [%d]\n", brightness); return false; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetBrightness: Brightness is changed [%d]\n", mBrightness ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::SetBrightness: Brightness is changed [%d]\n", mBrightness); return true; } int WindowBaseEcoreWl2::GetBrightness() const { - while( !mTizenDisplayPolicy ) + while(!mTizenDisplayPolicy) { - wl_display_dispatch_queue( mDisplay, mEventQueue ); + wl_display_dispatch_queue(mDisplay, mEventQueue); } int count = 0; - while( !mBrightnessChangeDone && count < 3 ) + while(!mBrightnessChangeDone && count < 3) { - ecore_wl2_display_flush( ecore_wl2_connected_display_get( NULL ) ); - wl_display_dispatch_queue( mDisplay, mEventQueue ); + ecore_wl2_display_flush(ecore_wl2_connected_display_get(NULL)); + wl_display_dispatch_queue(mDisplay, mEventQueue); count++; } - if( !mBrightnessChangeDone ) + if(!mBrightnessChangeDone) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetBrightness: Error! [%d]\n", mBrightnessChangeState ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetBrightness: Error! [%d]\n", mBrightnessChangeState); return 0; } - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetBrightness: Brightness [%d]\n", mBrightness ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Verbose, "WindowBaseEcoreWl2::GetBrightness: Brightness [%d]\n", mBrightness); return mBrightness; } -bool WindowBaseEcoreWl2::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) +bool WindowBaseEcoreWl2::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) { Ecore_Wl2_Window_Keygrab_Mode mode; - switch( grabMode ) + switch(grabMode) { case KeyGrab::TOPMOST: { @@ -2187,34 +2179,34 @@ bool WindowBaseEcoreWl2::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) } } - return ecore_wl2_window_keygrab_set( mEcoreWindow, KeyLookup::GetKeyName( key ), 0, 0, 0, mode ); + return ecore_wl2_window_keygrab_set(mEcoreWindow, KeyLookup::GetKeyName(key), 0, 0, 0, mode); } -bool WindowBaseEcoreWl2::UngrabKey( Dali::KEY key ) +bool WindowBaseEcoreWl2::UngrabKey(Dali::KEY key) { - return ecore_wl2_window_keygrab_unset( mEcoreWindow, KeyLookup::GetKeyName( key ), 0, 0 ); + return ecore_wl2_window_keygrab_unset(mEcoreWindow, KeyLookup::GetKeyName(key), 0, 0); } -bool WindowBaseEcoreWl2::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) +bool WindowBaseEcoreWl2::GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) { - int keyCount = key.Count(); + int keyCount = key.Count(); int keyGrabModeCount = grabMode.Count(); - if( keyCount != keyGrabModeCount || keyCount == 0 ) + if(keyCount != keyGrabModeCount || keyCount == 0) { return false; } eina_init(); - Eina_List* keyList = NULL; - Ecore_Wl2_Window_Keygrab_Info* info = new Ecore_Wl2_Window_Keygrab_Info[keyCount]; + Eina_List* keyList = NULL; + Ecore_Wl2_Window_Keygrab_Info* info = new Ecore_Wl2_Window_Keygrab_Info[keyCount]; - for( int index = 0; index < keyCount; ++index ) + for(int index = 0; index < keyCount; ++index) { - info[index].key = const_cast< char* >( KeyLookup::GetKeyName( key[index] ) ); + info[index].key = const_cast(KeyLookup::GetKeyName(key[index])); - switch( grabMode[index] ) + switch(grabMode[index]) { case KeyGrab::TOPMOST: { @@ -2243,31 +2235,31 @@ bool WindowBaseEcoreWl2::GrabKeyList( const Dali::Vector< Dali::KEY >& key, cons } } - keyList = eina_list_append( keyList, &info ); + keyList = eina_list_append(keyList, &info); } - Eina_List* grabList = ecore_wl2_window_keygrab_list_set( mEcoreWindow, keyList ); + Eina_List* grabList = ecore_wl2_window_keygrab_list_set(mEcoreWindow, keyList); - result.Resize( keyCount, true ); + result.Resize(keyCount, true); - Eina_List* l = NULL; - Eina_List* m = NULL; - void* listData = NULL; - void* data = NULL; - if( grabList != NULL ) + Eina_List* l = NULL; + Eina_List* m = NULL; + void* listData = NULL; + void* data = NULL; + if(grabList != NULL) { - EINA_LIST_FOREACH( grabList, m, data ) + EINA_LIST_FOREACH(grabList, m, data) { int index = 0; - EINA_LIST_FOREACH( keyList, l, listData ) + EINA_LIST_FOREACH(keyList, l, listData) { - if( static_cast< Ecore_Wl2_Window_Keygrab_Info* >( listData )->key == NULL ) + if(static_cast(listData)->key == NULL) { - DALI_LOG_ERROR( "input key list has null data!" ); + DALI_LOG_ERROR("input key list has null data!"); break; } - if( strcmp( static_cast< char* >( data ), static_cast< Ecore_Wl2_Window_Keygrab_Info* >( listData )->key ) == 0 ) + if(strcmp(static_cast(data), static_cast(listData)->key) == 0) { result[index] = false; } @@ -2276,51 +2268,51 @@ bool WindowBaseEcoreWl2::GrabKeyList( const Dali::Vector< Dali::KEY >& key, cons } } - delete [] info; + delete[] info; - eina_list_free( keyList ); - eina_list_free( grabList ); + eina_list_free(keyList); + eina_list_free(grabList); eina_shutdown(); return true; } -bool WindowBaseEcoreWl2::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) +bool WindowBaseEcoreWl2::UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) { int keyCount = key.Count(); - if( keyCount == 0 ) + if(keyCount == 0) { return false; } eina_init(); - Eina_List* keyList = NULL; - Ecore_Wl2_Window_Keygrab_Info* info = new Ecore_Wl2_Window_Keygrab_Info[keyCount]; + Eina_List* keyList = NULL; + Ecore_Wl2_Window_Keygrab_Info* info = new Ecore_Wl2_Window_Keygrab_Info[keyCount]; - for( int index = 0; index < keyCount; ++index ) + for(int index = 0; index < keyCount; ++index) { - info[index].key = const_cast< char* >( KeyLookup::GetKeyName( key[index] ) ); - keyList = eina_list_append( keyList, &info ); + info[index].key = const_cast(KeyLookup::GetKeyName(key[index])); + keyList = eina_list_append(keyList, &info); } - Eina_List* ungrabList = ecore_wl2_window_keygrab_list_unset( mEcoreWindow, keyList ); + Eina_List* ungrabList = ecore_wl2_window_keygrab_list_unset(mEcoreWindow, keyList); - result.Resize( keyCount, true ); + result.Resize(keyCount, true); - Eina_List* l = NULL; - Eina_List* m = NULL; - void *listData = NULL; - void *data = NULL; + Eina_List* l = NULL; + Eina_List* m = NULL; + void* listData = NULL; + void* data = NULL; - if( ungrabList != NULL ) + if(ungrabList != NULL) { - EINA_LIST_FOREACH( ungrabList, m, data ) + EINA_LIST_FOREACH(ungrabList, m, data) { int index = 0; - EINA_LIST_FOREACH( keyList, l, listData ) + EINA_LIST_FOREACH(keyList, l, listData) { - if( strcmp( static_cast< char* >( data ), static_cast< Ecore_Wl2_Window_Keygrab_Info* >( listData )->key ) == 0 ) + if(strcmp(static_cast(data), static_cast(listData)->key) == 0) { result[index] = false; } @@ -2329,28 +2321,28 @@ bool WindowBaseEcoreWl2::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Da } } - delete [] info; + delete[] info; - eina_list_free( keyList ); - eina_list_free( ungrabList ); + eina_list_free(keyList); + eina_list_free(ungrabList); eina_shutdown(); return true; } -void WindowBaseEcoreWl2::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void WindowBaseEcoreWl2::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; - Ecore_Wl2_Output* output = ecore_wl2_window_output_find( mEcoreWindow ); + Ecore_Wl2_Output* output = ecore_wl2_window_output_find(mEcoreWindow); // 1 inch = 25.4 millimeters - xres = ecore_wl2_output_dpi_get( output ); - yres = ecore_wl2_output_dpi_get( output ); + xres = ecore_wl2_output_dpi_get(output); + yres = ecore_wl2_output_dpi_get(output); - dpiHorizontal = int( xres + 0.5f ); // rounding - dpiVertical = int( yres + 0.5f ); + dpiHorizontal = int(xres + 0.5f); // rounding + dpiVertical = int(yres + 0.5f); } int WindowBaseEcoreWl2::GetOrientation() const @@ -2390,83 +2382,83 @@ void WindowBaseEcoreWl2::WindowRotationCompleted(int degree, int width, int heig ecore_wl2_window_rotation_change_done_send(mEcoreWindow, degree, width, height); } -void WindowBaseEcoreWl2::SetTransparency( bool transparent ) +void WindowBaseEcoreWl2::SetTransparency(bool transparent) { - ecore_wl2_window_alpha_set( mEcoreWindow, transparent ); + ecore_wl2_window_alpha_set(mEcoreWindow, transparent); } void WindowBaseEcoreWl2::InitializeEcoreElDBus() { #ifdef DALI_ELDBUS_AVAILABLE Eldbus_Object* object; - Eldbus_Proxy* manager; + Eldbus_Proxy* manager; - if( !( mSystemConnection = eldbus_connection_get( ELDBUS_CONNECTION_TYPE_SYSTEM ) ) ) + if(!(mSystemConnection = eldbus_connection_get(ELDBUS_CONNECTION_TYPE_SYSTEM))) { - DALI_LOG_ERROR( "Unable to get system bus\n" ); + DALI_LOG_ERROR("Unable to get system bus\n"); } - object = eldbus_object_get( mSystemConnection, BUS, PATH ); - if( !object ) + object = eldbus_object_get(mSystemConnection, BUS, PATH); + if(!object) { - DALI_LOG_ERROR( "Getting object failed\n" ); + DALI_LOG_ERROR("Getting object failed\n"); return; } - manager = eldbus_proxy_get( object, INTERFACE ); - if( !manager ) + manager = eldbus_proxy_get(object, INTERFACE); + if(!manager) { - DALI_LOG_ERROR( "Getting proxy failed\n" ); + DALI_LOG_ERROR("Getting proxy failed\n"); return; } - if( !eldbus_proxy_signal_handler_add( manager, "GestureDetected", EcoreElDBusAccessibilityNotification, this ) ) + if(!eldbus_proxy_signal_handler_add(manager, "GestureDetected", EcoreElDBusAccessibilityNotification, this)) { - DALI_LOG_ERROR( "No signal handler returned\n" ); + DALI_LOG_ERROR("No signal handler returned\n"); } #endif } -void WindowBaseEcoreWl2::CreateWindow( PositionSize positionSize ) +void WindowBaseEcoreWl2::CreateWindow(PositionSize positionSize) { - Ecore_Wl2_Display* display = ecore_wl2_display_connect( NULL ); - if( !display ) + Ecore_Wl2_Display* display = ecore_wl2_display_connect(NULL); + if(!display) { - DALI_ASSERT_ALWAYS( 0 && "Failed to get display" ); + DALI_ASSERT_ALWAYS(0 && "Failed to get display"); } - ecore_wl2_display_sync( display ); + ecore_wl2_display_sync(display); - mEcoreWindow = ecore_wl2_window_new( display, NULL, positionSize.x, positionSize.y, positionSize.width, positionSize.height ); + mEcoreWindow = ecore_wl2_window_new(display, NULL, positionSize.x, positionSize.y, positionSize.width, positionSize.height); - if ( mEcoreWindow == 0 ) + if(mEcoreWindow == 0) { - DALI_ASSERT_ALWAYS( 0 && "Failed to create Wayland window" ); + DALI_ASSERT_ALWAYS(0 && "Failed to create Wayland window"); } // Set default type - ecore_wl2_window_type_set( mEcoreWindow, ECORE_WL2_WINDOW_TYPE_TOPLEVEL ); + ecore_wl2_window_type_set(mEcoreWindow, ECORE_WL2_WINDOW_TYPE_TOPLEVEL); } -void WindowBaseEcoreWl2::SetParent( WindowBase* parentWinBase ) +void WindowBaseEcoreWl2::SetParent(WindowBase* parentWinBase) { Ecore_Wl2_Window* ecoreParent = NULL; - if( parentWinBase ) + if(parentWinBase) { - WindowBaseEcoreWl2* winBaseEcore2 = static_cast( parentWinBase ); - ecoreParent = winBaseEcore2->mEcoreWindow; + WindowBaseEcoreWl2* winBaseEcore2 = static_cast(parentWinBase); + ecoreParent = winBaseEcore2->mEcoreWindow; } - ecore_wl2_window_parent_set( mEcoreWindow, ecoreParent ); + ecore_wl2_window_parent_set(mEcoreWindow, ecoreParent); } int WindowBaseEcoreWl2::CreateFrameRenderedSyncFence() { - return wl_egl_window_tizen_create_commit_sync_fd( mEglWindow ); + return wl_egl_window_tizen_create_commit_sync_fd(mEglWindow); } int WindowBaseEcoreWl2::CreateFramePresentedSyncFence() { - return wl_egl_window_tizen_create_presentation_sync_fd( mEglWindow ); + return wl_egl_window_tizen_create_presentation_sync_fd(mEglWindow); } } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.h b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.h index 436a249..66582a8 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.h +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-base-ecore-wl2.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_WINDOW_BASE_ECORE_WL2_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,6 @@ namespace Internal { namespace Adaptor { - class WindowRenderSurface; class WindowRenderSurfaceEcoreWl2; @@ -48,11 +47,10 @@ class WindowRenderSurfaceEcoreWl2; class WindowBaseEcoreWl2 : public WindowBase { public: - /** * @brief Constructor */ - WindowBaseEcoreWl2( PositionSize positionSize, Any surface, bool isTransparent ); + WindowBaseEcoreWl2(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Destructor @@ -60,91 +58,90 @@ public: virtual ~WindowBaseEcoreWl2(); public: - /** * @brief Called when the window iconify state is changed. */ - Eina_Bool OnIconifyStateChanged( void* data, int type, void* event ); + Eina_Bool OnIconifyStateChanged(void* data, int type, void* event); /** * @brief Called when the window gains focus. */ - Eina_Bool OnFocusIn( void* data, int type, void* event ); + Eina_Bool OnFocusIn(void* data, int type, void* event); /** * @brief Called when the window loses focus. */ - Eina_Bool OnFocusOut( void* data, int type, void* event ); + Eina_Bool OnFocusOut(void* data, int type, void* event); /** * @brief Called when the output is transformed. */ - Eina_Bool OnOutputTransform( void* data, int type, void* event ); + Eina_Bool OnOutputTransform(void* data, int type, void* event); /** * @brief Called when the output transform should be ignored. */ - Eina_Bool OnIgnoreOutputTransform( void* data, int type, void* event ); + Eina_Bool OnIgnoreOutputTransform(void* data, int type, void* event); /** * @brief Called when a rotation event is recevied. */ - void OnRotation( void* data, int type, void* event ); + void OnRotation(void* data, int type, void* event); /** * @brief Called when a configure event is recevied. */ - void OnConfiguration( void* data, int type, void* event ); + void OnConfiguration(void* data, int type, void* event); /** * @brief Called when a touch down is received. */ - void OnMouseButtonDown( void* data, int type, void* event ); + void OnMouseButtonDown(void* data, int type, void* event); /** * @brief Called when a touch up is received. */ - void OnMouseButtonUp( void* data, int type, void* event ); + void OnMouseButtonUp(void* data, int type, void* event); /** * @brief Called when a touch motion is received. */ - void OnMouseButtonMove( void* data, int type, void* event ); + void OnMouseButtonMove(void* data, int type, void* event); /** * @brief Called when a touch is canceled. */ - void OnMouseButtonCancel( void* data, int type, void* event ); + void OnMouseButtonCancel(void* data, int type, void* event); /** * @brief Called when a mouse wheel is received. */ - void OnMouseWheel( void* data, int type, void* event ); + void OnMouseWheel(void* data, int type, void* event); /** * @brief Called when a detent rotation event is recevied. */ - void OnDetentRotation( void* data, int type, void* event ); + void OnDetentRotation(void* data, int type, void* event); /** * @brief Called when a key down is received. */ - void OnKeyDown( void* data, int type, void* event ); + void OnKeyDown(void* data, int type, void* event); /** * @brief Called when a key up is received. */ - void OnKeyUp( void* data, int type, void* event ); + void OnKeyUp(void* data, int type, void* event); /** * @brief Called when the source window notifies us the content in clipboard is selected. */ - void OnDataSend( void* data, int type, void* event ); + void OnDataSend(void* data, int type, void* event); /** * @brief Called when the source window sends us about the selected content. */ - void OnDataReceive( void* data, int type, void* event ); + void OnDataReceive(void* data, int type, void* event); /** * @brief Called when a font name is changed. @@ -159,7 +156,7 @@ public: /** * @brief Called when a transition effect-start/end event is received. */ - void OnTransitionEffectEvent( WindowEffectState state, WindowEffectType type ); + void OnTransitionEffectEvent(WindowEffectState state, WindowEffectType type); /** * @brief Called when a keyboard repeat event is changed. @@ -175,47 +172,45 @@ public: /** * @brief Called when Ecore ElDBus accessibility event is received. */ - void OnEcoreElDBusAccessibilityNotification( void* context, const Eldbus_Message* message ); + void OnEcoreElDBusAccessibilityNotification(void* context, const Eldbus_Message* message); #endif /** * @brief Called when a keymap is changed. */ - void KeymapChanged(void *data, int type, void *event); + void KeymapChanged(void* data, int type, void* event); /** * @brief RegistryGlobalCallback */ - void RegistryGlobalCallback( void* data, struct wl_registry *registry, uint32_t name, const char* interface, uint32_t version ); + void RegistryGlobalCallback(void* data, struct wl_registry* registry, uint32_t name, const char* interface, uint32_t version); /** * @brief RegistryGlobalCallbackRemove */ - void RegistryGlobalCallbackRemove( void* data, struct wl_registry* registry, uint32_t id ); + void RegistryGlobalCallbackRemove(void* data, struct wl_registry* registry, uint32_t id); /** * @brief TizenPolicyNotificationChangeDone */ - void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state ); + void TizenPolicyNotificationChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, int32_t level, uint32_t state); /** * @brief TizenPolicyScreenModeChangeDone */ - void TizenPolicyScreenModeChangeDone( void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state ); + void TizenPolicyScreenModeChangeDone(void* data, struct tizen_policy* tizenPolicy, struct wl_surface* surface, uint32_t mode, uint32_t state); /** * @brief DisplayPolicyBrightnessChangeDone */ - void DisplayPolicyBrightnessChangeDone( void* data, struct tizen_display_policy *displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state ); - + void DisplayPolicyBrightnessChangeDone(void* data, struct tizen_display_policy* displayPolicy, struct wl_surface* surface, int32_t brightness, uint32_t state); /** * @brief Gets the key code by keyName. */ - void GetKeyCode( std::string keyName, int32_t& keyCode ); + void GetKeyCode(std::string keyName, int32_t& keyCode); public: - /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNativeWindow() */ @@ -229,7 +224,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateEglWindow() */ - EGLNativeWindowType CreateEglWindow( int width, int height ) override; + EGLNativeWindowType CreateEglWindow(int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::DestroyEglWindow() @@ -239,22 +234,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowRotation() */ - void SetEglWindowRotation( int angle ) override; + void SetEglWindowRotation(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowBufferTransform() */ - void SetEglWindowBufferTransform( int angle ) override; + void SetEglWindowBufferTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowTransform() */ - void SetEglWindowTransform( int angle ) override; + void SetEglWindowTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::ResizeEglWindow() */ - void ResizeEglWindow( PositionSize positionSize ) override; + void ResizeEglWindow(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::IsEglWindowRotationSupported() @@ -264,22 +259,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::Move() */ - void Move( PositionSize positionSize ) override; + void Move(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Resize() */ - void Resize( PositionSize positionSize ) override; + void Resize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::MoveResize() */ - void MoveResize( PositionSize positionSize ) override; + void MoveResize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetClass() */ - void SetClass( const std::string& name, const std::string& className ) override; + void SetClass(const std::string& name, const std::string& className) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Raise() @@ -299,17 +294,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAvailableAnlges() */ - void SetAvailableAnlges( const std::vector< int >& angles ) override; + void SetAvailableAnlges(const std::vector& angles) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetPreferredAngle() */ - void SetPreferredAngle( int angle ) override; + void SetPreferredAngle(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ) override; + void SetAcceptFocus(bool accept) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Show() @@ -329,47 +324,47 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const override; + std::string GetSupportedAuxiliaryHint(unsigned int index) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) override; + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ) override; + bool RemoveAuxiliaryHint(unsigned int id) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) override; + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const override; + std::string GetAuxiliaryHintValue(unsigned int id) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const override; + unsigned int GetAuxiliaryHintId(const std::string& hint) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ) override; + void SetInputRegion(const Rect& inputRegion) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetType() */ - void SetType( Dali::WindowType type ) override; + void SetType(Dali::WindowType type) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetNotificationLevel() */ - bool SetNotificationLevel( Dali::WindowNotificationLevel level ) override; + bool SetNotificationLevel(Dali::WindowNotificationLevel level) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNotificationLevel() @@ -379,7 +374,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetOpaqueState() */ - void SetOpaqueState( bool opaque ) override; + void SetOpaqueState(bool opaque) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetScreenOffMode() @@ -394,7 +389,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetBrightness() */ - bool SetBrightness( int brightness ) override; + bool SetBrightness(int brightness) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetBrightness() @@ -404,27 +399,27 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) override; + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKey() */ - bool UngrabKey( Dali::KEY key ) override; + bool UngrabKey(Dali::KEY key) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKeyList() */ - bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) override; + bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKeyList() */ - bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) override; + bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetOrientation() @@ -439,22 +434,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetWindowRotationAngle() */ - void SetWindowRotationAngle( int degree ) override; + void SetWindowRotationAngle(int degree) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::WindowRotationCompleted() */ - void WindowRotationCompleted( int degree, int width, int height ) override; + void WindowRotationCompleted(int degree, int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetTransparency() */ - void SetTransparency( bool transparent ) override; + void SetTransparency(bool transparent) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetParent() */ - void SetParent( WindowBase* parentWinBase ) override; + void SetParent(WindowBase* parentWinBase) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateFrameRenderedSyncFence() @@ -467,11 +462,10 @@ public: int CreateFramePresentedSyncFence() override; private: - /** * Second stage initialization */ - void Initialize( PositionSize positionSize, Any surface, bool isTransparent ); + void Initialize(PositionSize positionSize, Any surface, bool isTransparent); /** * Initialize Ecore ElDBus @@ -481,10 +475,9 @@ private: /** * @brief Create window */ - void CreateWindow( PositionSize positionSize ); + void CreateWindow(PositionSize positionSize); protected: - // Undefined WindowBaseEcoreWl2(const WindowBaseEcoreWl2&) = delete; @@ -492,54 +485,53 @@ protected: WindowBaseEcoreWl2& operator=(const WindowBaseEcoreWl2& rhs) = delete; private: + typedef std::vector > AuxiliaryHints; - typedef std::vector< std::pair< std::string, std::string > > AuxiliaryHints; - - Dali::Vector< Ecore_Event_Handler* > mEcoreEventHandler; + Dali::Vector mEcoreEventHandler; - Ecore_Wl2_Window* mEcoreWindow; - wl_surface* mWlSurface; - wl_egl_window* mEglWindow; - wl_display* mDisplay; - wl_event_queue* mEventQueue; - tizen_policy* mTizenPolicy; - tizen_display_policy* mTizenDisplayPolicy; - xkb_keymap* mKeyMap; + Ecore_Wl2_Window* mEcoreWindow; + wl_surface* mWlSurface; + wl_egl_window* mEglWindow; + wl_display* mDisplay; + wl_event_queue* mEventQueue; + tizen_policy* mTizenPolicy; + tizen_display_policy* mTizenDisplayPolicy; + xkb_keymap* mKeyMap; - std::vector< std::string > mSupportedAuxiliaryHints; - AuxiliaryHints mAuxiliaryHints; + std::vector mSupportedAuxiliaryHints; + AuxiliaryHints mAuxiliaryHints; - int mNotificationLevel; - uint32_t mNotificationChangeState; - bool mNotificationLevelChangeDone; + int mNotificationLevel; + uint32_t mNotificationChangeState; + bool mNotificationLevelChangeDone; - int mScreenOffMode; - uint32_t mScreenOffModeChangeState; - bool mScreenOffModeChangeDone; + int mScreenOffMode; + uint32_t mScreenOffModeChangeState; + bool mScreenOffModeChangeDone; - int mBrightness; - uint32_t mBrightnessChangeState; - bool mBrightnessChangeDone; + int mBrightness; + uint32_t mBrightnessChangeState; + bool mBrightnessChangeDone; - bool mVisible:1; - Dali::PositionSize mWindowPositionSize; + bool mVisible : 1; + Dali::PositionSize mWindowPositionSize; - bool mOwnSurface; + bool mOwnSurface; - volatile uint32_t mMoveResizeSerial; - uint32_t mLastSubmittedMoveResizeSerial; + volatile uint32_t mMoveResizeSerial; + uint32_t mLastSubmittedMoveResizeSerial; - int mWindowRotationAngle; - int mScreenRotationAngle; - int mSupportedPreProtation; + int mWindowRotationAngle; + int mScreenRotationAngle; + int mSupportedPreProtation; #ifdef DALI_ELDBUS_AVAILABLE - Eldbus_Connection* mSystemConnection; + Eldbus_Connection* mSystemConnection; #endif // DALI_ELDBUS_AVAILABLE }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.cpp index ab72e47..fd69c46 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali { @@ -28,17 +28,16 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowBase > WindowFactoryEcoreWl2::CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr WindowFactoryEcoreWl2::CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowBaseEcoreWl2 >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } // this should be created from Window impl -std::unique_ptr< WindowFactory > GetWindowFactory() +std::unique_ptr GetWindowFactory() { // returns Window factory - return Utils::MakeUnique< WindowFactoryEcoreWl2 >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.h b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.h index f979c2c..835bbca 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.h +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-factory-ecore-wl2.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_WINDOW_FACTORY_ECORE_WL2_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,10 @@ namespace Internal { namespace Adaptor { - class WindowFactoryEcoreWl2 : public WindowFactory { public: - std::unique_ptr< WindowBase > CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) override; + std::unique_ptr CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-system-ecore-wl2.cpp b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-system-ecore-wl2.cpp index 4974602..b10af4c 100644 --- a/dali/internal/window-system/tizen-wayland/ecore-wl2/window-system-ecore-wl2.cpp +++ b/dali/internal/window-system/tizen-wayland/ecore-wl2/window-system-ecore-wl2.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,20 @@ */ // INTERNAL HEADERS -#include #include +#include // EXTERNAL_HEADERS #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowSystem { - void Initialize() { ecore_wl2_init(); @@ -44,30 +40,30 @@ void Shutdown() ecore_wl2_shutdown(); } -void GetScreenSize( int& width, int& height ) +void GetScreenSize(int& width, int& height) { - Ecore_Wl2_Display* display = ecore_wl2_display_connect( NULL ); - if( display ) + Ecore_Wl2_Display* display = ecore_wl2_display_connect(NULL); + if(display) { - ecore_wl2_display_screen_size_get( display, &width, &height ); - DALI_ASSERT_ALWAYS((width>0) && "screen width is 0"); - DALI_ASSERT_ALWAYS((height>0) && "screen height is 0"); + ecore_wl2_display_screen_size_get(display, &width, &height); + DALI_ASSERT_ALWAYS((width > 0) && "screen width is 0"); + DALI_ASSERT_ALWAYS((height > 0) && "screen height is 0"); } } -bool SetKeyboardRepeatInfo( float rate, float delay ) +bool SetKeyboardRepeatInfo(float rate, float delay) { - Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get( ecore_wl2_connected_display_get( NULL ) ); - return ecore_wl2_input_keyboard_repeat_set( input, static_cast( rate ), static_cast( delay ) ); + Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get(ecore_wl2_connected_display_get(NULL)); + return ecore_wl2_input_keyboard_repeat_set(input, static_cast(rate), static_cast(delay)); } -bool GetKeyboardRepeatInfo( float& rate, float& delay ) +bool GetKeyboardRepeatInfo(float& rate, float& delay) { - Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get( ecore_wl2_connected_display_get( NULL ) ); - double rateVal, delayVal; - bool ret = ecore_wl2_input_keyboard_repeat_get( input, &rateVal, &delayVal ); - rate = static_cast( rateVal ); - delay = static_cast( delayVal ); + Ecore_Wl2_Input* input = ecore_wl2_input_default_input_get(ecore_wl2_connected_display_get(NULL)); + double rateVal, delayVal; + bool ret = ecore_wl2_input_keyboard_repeat_get(input, &rateVal, &delayVal); + rate = static_cast(rateVal); + delay = static_cast(delayVal); return ret; } diff --git a/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.cpp b/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.cpp index 118b020..ad926ae 100644 --- a/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.cpp +++ b/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // EXTERNAL INCLUDES -#include #include +#include #ifdef ECORE_WAYLAND2 #include @@ -43,69 +43,67 @@ namespace Dali { - namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gNativeSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_NATIVE_RENDER_SURFACE"); #endif } // unnamed namespace -NativeRenderSurfaceEcoreWl::NativeRenderSurfaceEcoreWl( SurfaceSize surfaceSize, Any surface, bool isTransparent ) -: mRenderNotification( NULL ), - mGraphics( NULL ), - mEGL( nullptr ), - mEGLSurface( nullptr ), - mEGLContext( nullptr ), - mOwnSurface( false ), - mDrawableCompleted( false ), - mTbmQueue( NULL ), - mConsumeSurface( NULL ), - mThreadSynchronization( NULL ) +NativeRenderSurfaceEcoreWl::NativeRenderSurfaceEcoreWl(SurfaceSize surfaceSize, Any surface, bool isTransparent) +: mRenderNotification(NULL), + mGraphics(NULL), + mEGL(nullptr), + mEGLSurface(nullptr), + mEGLContext(nullptr), + mOwnSurface(false), + mDrawableCompleted(false), + mTbmQueue(NULL), + mConsumeSurface(NULL), + mThreadSynchronization(NULL) { Dali::Internal::Adaptor::WindowSystem::Initialize(); - if( surface.Empty() ) + if(surface.Empty()) { mSurfaceSize = surfaceSize; - mColorDepth = isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24; - mTbmFormat = isTransparent ? TBM_FORMAT_ARGB8888 : TBM_FORMAT_RGB888; + mColorDepth = isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24; + mTbmFormat = isTransparent ? TBM_FORMAT_ARGB8888 : TBM_FORMAT_RGB888; CreateNativeRenderable(); } else { - mTbmQueue = AnyCast< tbm_surface_queue_h >( surface ); + mTbmQueue = AnyCast(surface); - uint16_t width = static_cast( tbm_surface_queue_get_width( mTbmQueue ) ); - uint16_t height = static_cast( tbm_surface_queue_get_height( mTbmQueue ) ); - mSurfaceSize = SurfaceSize( width, height ); + uint16_t width = static_cast(tbm_surface_queue_get_width(mTbmQueue)); + uint16_t height = static_cast(tbm_surface_queue_get_height(mTbmQueue)); + mSurfaceSize = SurfaceSize(width, height); - mTbmFormat = tbm_surface_queue_get_format( mTbmQueue ); + mTbmFormat = tbm_surface_queue_get_format(mTbmQueue); - mColorDepth = ( mTbmFormat == TBM_FORMAT_ARGB8888 ) ? COLOR_DEPTH_32 : COLOR_DEPTH_24; + mColorDepth = (mTbmFormat == TBM_FORMAT_ARGB8888) ? COLOR_DEPTH_32 : COLOR_DEPTH_24; } } NativeRenderSurfaceEcoreWl::~NativeRenderSurfaceEcoreWl() { - if ( mEGLSurface ) + if(mEGLSurface) { DestroySurface(); } // release the surface if we own one - if( mOwnSurface ) + if(mOwnSurface) { ReleaseDrawable(); - if( mTbmQueue ) + if(mTbmQueue) { - tbm_surface_queue_destroy( mTbmQueue ); + tbm_surface_queue_destroy(mTbmQueue); } - DALI_LOG_INFO( gNativeSurfaceLogFilter, Debug::General, "Own tbm surface queue destroy\n" ); + DALI_LOG_INFO(gNativeSurfaceLogFilter, Debug::General, "Own tbm surface queue destroy\n"); } Dali::Internal::Adaptor::WindowSystem::Shutdown(); @@ -116,17 +114,17 @@ Any NativeRenderSurfaceEcoreWl::GetDrawable() return mConsumeSurface; } -void NativeRenderSurfaceEcoreWl::SetRenderNotification( TriggerEventInterface* renderNotification ) +void NativeRenderSurfaceEcoreWl::SetRenderNotification(TriggerEventInterface* renderNotification) { mRenderNotification = renderNotification; } void NativeRenderSurfaceEcoreWl::WaitUntilSurfaceReplaced() { - ConditionalWait::ScopedLock lock( mTbmSurfaceCondition ); - while( !mDrawableCompleted ) + ConditionalWait::ScopedLock lock(mTbmSurfaceCondition); + while(!mDrawableCompleted) { - mTbmSurfaceCondition.Wait( lock ); + mTbmSurfaceCondition.Wait(lock); } mDrawableCompleted = false; @@ -139,10 +137,10 @@ Any NativeRenderSurfaceEcoreWl::GetNativeRenderable() PositionSize NativeRenderSurfaceEcoreWl::GetPositionSize() const { - return PositionSize( 0, 0, static_cast( mSurfaceSize.GetWidth() ), static_cast( mSurfaceSize.GetHeight() ) ); + return PositionSize(0, 0, static_cast(mSurfaceSize.GetWidth()), static_cast(mSurfaceSize.GetHeight())); } -void NativeRenderSurfaceEcoreWl::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void NativeRenderSurfaceEcoreWl::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; @@ -157,8 +155,8 @@ void NativeRenderSurfaceEcoreWl::GetDpi( unsigned int& dpiHorizontal, unsigned i yres = ecore_wl_dpi_get(); #endif - dpiHorizontal = int( xres + 0.5f ); // rounding - dpiVertical = int( yres + 0.5f ); + dpiHorizontal = int(xres + 0.5f); // rounding + dpiVertical = int(yres + 0.5f); } int NativeRenderSurfaceEcoreWl::GetOrientation() const @@ -168,18 +166,18 @@ int NativeRenderSurfaceEcoreWl::GetOrientation() const void NativeRenderSurfaceEcoreWl::InitializeGraphics() { - DALI_LOG_TRACE_METHOD( gNativeSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); - mGraphics = &mAdaptor->GetGraphicsInterface(); - auto eglGraphics = static_cast(mGraphics); + mGraphics = &mAdaptor->GetGraphicsInterface(); + auto eglGraphics = static_cast(mGraphics); mEGL = &eglGraphics->GetEglInterface(); - if ( mEGLContext == NULL ) + if(mEGLContext == NULL) { // Create the OpenGL context for this window Internal::Adaptor::EglImplementation& eglImpl = static_cast(*mEGL); - eglImpl.CreateWindowContext( mEGLContext ); + eglImpl.CreateWindowContext(mEGLContext); // Create the OpenGL surface CreateSurface(); @@ -188,111 +186,111 @@ void NativeRenderSurfaceEcoreWl::InitializeGraphics() void NativeRenderSurfaceEcoreWl::CreateSurface() { - DALI_LOG_TRACE_METHOD( gNativeSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); - auto eglGraphics = static_cast(mGraphics); - Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - mEGLSurface = eglImpl.CreateSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( mTbmQueue ), mColorDepth ); + mEGLSurface = eglImpl.CreateSurfaceWindow(reinterpret_cast(mTbmQueue), mColorDepth); } void NativeRenderSurfaceEcoreWl::DestroySurface() { - DALI_LOG_TRACE_METHOD( gNativeSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); - auto eglGraphics = static_cast(mGraphics); - Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - eglImpl.DestroySurface( mEGLSurface ); + eglImpl.DestroySurface(mEGLSurface); } bool NativeRenderSurfaceEcoreWl::ReplaceGraphicsSurface() { - DALI_LOG_TRACE_METHOD( gNativeSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); - if( !mTbmQueue ) + if(!mTbmQueue) { return false; } - auto eglGraphics = static_cast(mGraphics); - Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - return eglImpl.ReplaceSurfaceWindow( reinterpret_cast< EGLNativeWindowType >( mTbmQueue ), mEGLSurface, mEGLContext ); + return eglImpl.ReplaceSurfaceWindow(reinterpret_cast(mTbmQueue), mEGLSurface, mEGLContext); } -void NativeRenderSurfaceEcoreWl::MoveResize( Dali::PositionSize positionSize ) +void NativeRenderSurfaceEcoreWl::MoveResize(Dali::PositionSize positionSize) { tbm_surface_queue_error_e error = TBM_SURFACE_QUEUE_ERROR_NONE; - error = tbm_surface_queue_reset( mTbmQueue, positionSize.width, positionSize.height, mTbmFormat ); + error = tbm_surface_queue_reset(mTbmQueue, positionSize.width, positionSize.height, mTbmFormat); - if( error != TBM_SURFACE_QUEUE_ERROR_NONE ) + if(error != TBM_SURFACE_QUEUE_ERROR_NONE) { - DALI_LOG_ERROR( "Failed to resize tbm_surface_queue" ); + DALI_LOG_ERROR("Failed to resize tbm_surface_queue"); } - mSurfaceSize.SetWidth( static_cast( positionSize.width ) ); - mSurfaceSize.SetHeight( static_cast( positionSize.height ) ); + mSurfaceSize.SetWidth(static_cast(positionSize.width)); + mSurfaceSize.SetHeight(static_cast(positionSize.height)); } void NativeRenderSurfaceEcoreWl::StartRender() { } -bool NativeRenderSurfaceEcoreWl::PreRender( bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect ) +bool NativeRenderSurfaceEcoreWl::PreRender(bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect) { //TODO: Need to support partial update return true; } -void NativeRenderSurfaceEcoreWl::PostRender( bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects ) +void NativeRenderSurfaceEcoreWl::PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects) { - auto eglGraphics = static_cast(mGraphics); - if (eglGraphics) + auto eglGraphics = static_cast(mGraphics); + if(eglGraphics) { Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - eglImpl.SwapBuffers( mEGLSurface, damagedRects ); + eglImpl.SwapBuffers(mEGLSurface, damagedRects); } //TODO: Move calling tbm_surface_queue_acruie to OffscreenWindow and Scene in EvasPlugin - if ( mOwnSurface ) + if(mOwnSurface) { - if( mThreadSynchronization ) + if(mThreadSynchronization) { mThreadSynchronization->PostRenderStarted(); } - if( tbm_surface_queue_can_acquire( mTbmQueue, 1 ) ) + if(tbm_surface_queue_can_acquire(mTbmQueue, 1)) { - if( tbm_surface_queue_acquire( mTbmQueue, &mConsumeSurface ) != TBM_SURFACE_QUEUE_ERROR_NONE ) + if(tbm_surface_queue_acquire(mTbmQueue, &mConsumeSurface) != TBM_SURFACE_QUEUE_ERROR_NONE) { - DALI_LOG_ERROR( "Failed to acquire a tbm_surface\n" ); + DALI_LOG_ERROR("Failed to acquire a tbm_surface\n"); return; } } - if ( mConsumeSurface ) + if(mConsumeSurface) { - tbm_surface_internal_ref( mConsumeSurface ); + tbm_surface_internal_ref(mConsumeSurface); } - if( replacingSurface ) + if(replacingSurface) { - ConditionalWait::ScopedLock lock( mTbmSurfaceCondition ); + ConditionalWait::ScopedLock lock(mTbmSurfaceCondition); mDrawableCompleted = true; - mTbmSurfaceCondition.Notify( lock ); + mTbmSurfaceCondition.Notify(lock); } - // create damage for client applications which wish to know the update timing - if( !replacingSurface && mRenderNotification ) + // create damage for client applications which wish to know the update timing + if(!replacingSurface && mRenderNotification) { // use notification trigger // Tell the event-thread to render the tbm_surface mRenderNotification->Trigger(); } - if( mThreadSynchronization ) + if(mThreadSynchronization) { // wait until the event-thread completed to use the tbm_surface mThreadSynchronization->PostRenderWaitForCompletion(); @@ -304,7 +302,7 @@ void NativeRenderSurfaceEcoreWl::PostRender( bool renderToFbo, bool replacingSur else { // create damage for client applications which wish to know the update timing - if( !replacingSurface && mRenderNotification ) + if(!replacingSurface && mRenderNotification) { // use notification trigger // Tell the event-thread to render the tbm_surface @@ -318,7 +316,7 @@ void NativeRenderSurfaceEcoreWl::StopRender() ReleaseLock(); } -void NativeRenderSurfaceEcoreWl::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization ) +void NativeRenderSurfaceEcoreWl::SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) { mThreadSynchronization = &threadSynchronization; } @@ -330,9 +328,9 @@ Dali::RenderSurfaceInterface::Type NativeRenderSurfaceEcoreWl::GetSurfaceType() void NativeRenderSurfaceEcoreWl::MakeContextCurrent() { - if ( mEGL != nullptr ) + if(mEGL != nullptr) { - mEGL->MakeContextCurrent( mEGLSurface, mEGLContext ); + mEGL->MakeContextCurrent(mEGLSurface, mEGLContext); } } @@ -348,7 +346,7 @@ Integration::StencilBufferAvailable NativeRenderSurfaceEcoreWl::GetStencilBuffer void NativeRenderSurfaceEcoreWl::ReleaseLock() { - if( mThreadSynchronization ) + if(mThreadSynchronization) { mThreadSynchronization->PostRenderComplete(); } @@ -356,15 +354,15 @@ void NativeRenderSurfaceEcoreWl::ReleaseLock() void NativeRenderSurfaceEcoreWl::CreateNativeRenderable() { - int width = static_cast( mSurfaceSize.GetWidth() ); - int height = static_cast( mSurfaceSize.GetHeight() ); + int width = static_cast(mSurfaceSize.GetWidth()); + int height = static_cast(mSurfaceSize.GetHeight()); // check we're creating one with a valid size - DALI_ASSERT_ALWAYS( width > 0 && height > 0 && "tbm_surface size is invalid" ); + DALI_ASSERT_ALWAYS(width > 0 && height > 0 && "tbm_surface size is invalid"); - mTbmQueue = tbm_surface_queue_create( 3, width, height, mTbmFormat, TBM_BO_DEFAULT ); + mTbmQueue = tbm_surface_queue_create(3, width, height, mTbmFormat, TBM_BO_DEFAULT); - if( mTbmQueue ) + if(mTbmQueue) { mOwnSurface = true; } @@ -376,13 +374,13 @@ void NativeRenderSurfaceEcoreWl::CreateNativeRenderable() void NativeRenderSurfaceEcoreWl::ReleaseDrawable() { - if( mConsumeSurface ) + if(mConsumeSurface) { - tbm_surface_internal_unref( mConsumeSurface ); + tbm_surface_internal_unref(mConsumeSurface); - if( tbm_surface_internal_is_valid( mConsumeSurface ) ) + if(tbm_surface_internal_is_valid(mConsumeSurface)) { - tbm_surface_queue_release( mTbmQueue, mConsumeSurface ); + tbm_surface_queue_release(mTbmQueue, mConsumeSurface); } mConsumeSurface = NULL; } diff --git a/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.h b/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.h index 595f1af..12c5cf4 100644 --- a/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.h +++ b/dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_TIZENWAYLAND_NATIVE_SURFACE_ECORE_WL_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,19 +19,18 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include // INTERNAL INCLUDES -#include #include #include #include +#include namespace Dali { - class DisplayConnection; class EglInterface; @@ -41,14 +40,13 @@ class EglInterface; class NativeRenderSurfaceEcoreWl : public Dali::NativeRenderSurface { public: - /** * Uses an Wayland surface to render to. * @param [in] surfaceSize the size of the surface * @param [in] surface the native surface handle * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit */ - NativeRenderSurfaceEcoreWl( SurfaceSize surfaceSize, Any surface, bool isTransparent = false ); + NativeRenderSurfaceEcoreWl(SurfaceSize surfaceSize, Any surface, bool isTransparent = false); /** * @brief Destructor @@ -56,7 +54,6 @@ public: virtual ~NativeRenderSurfaceEcoreWl(); public: // from WindowRenderSurface - /** * @copydoc Dali::NativeRenderSurface::GetSurface() */ @@ -65,7 +62,7 @@ public: // from WindowRenderSurface /** * @copydoc Dali::NativeRenderSurface::SetRenderNotification() */ - void SetRenderNotification( TriggerEventInterface* renderNotification ) override; + void SetRenderNotification(TriggerEventInterface* renderNotification) override; /** * @copydoc Dali::NativeRenderSurface::WaitUntilSurfaceReplaced() @@ -78,7 +75,6 @@ public: // from WindowRenderSurface virtual Any GetNativeRenderable() override; public: // from Dali::RenderSurfaceInterface - /** * @copydoc Dali::RenderSurfaceInterface::GetPositionSize() */ @@ -87,7 +83,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::RenderSurfaceInterface::GetOrientation() @@ -117,7 +113,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::MoveResize() */ - void MoveResize( Dali::PositionSize positionSize) override; + void MoveResize(Dali::PositionSize positionSize) override; /** * @copydoc Dali::RenderSurfaceInterface::StartRender() @@ -127,12 +123,12 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::PreRender() */ - bool PreRender( bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect ) override; + bool PreRender(bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect) override; /** * @copydoc Dali::RenderSurfaceInterface::PostRender() */ - void PostRender( bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects ) override; + void PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects) override; /** * @copydoc Dali::RenderSurfaceInterface::StopRender() @@ -142,7 +138,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::SetThreadSynchronization */ - void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization )override; + void SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) override; /** * @copydoc Dali::RenderSurfaceInterface::GetSurfaceType() @@ -165,7 +161,6 @@ public: // from Dali::RenderSurfaceInterface Integration::StencilBufferAvailable GetStencilBufferRequired() override; private: - /** * @copydoc Dali::RenderSurfaceInterface::ReleaseLock() */ @@ -182,23 +177,21 @@ private: void ReleaseDrawable() override; private: // Data - - SurfaceSize mSurfaceSize; - TriggerEventInterface* mRenderNotification; - Internal::Adaptor::GraphicsInterface* mGraphics; ///< The graphics interface - EglInterface* mEGL; - EGLSurface mEGLSurface; - EGLContext mEGLContext; - ColorDepth mColorDepth; - tbm_format mTbmFormat; - bool mOwnSurface; - bool mDrawableCompleted; - - tbm_surface_queue_h mTbmQueue; - tbm_surface_h mConsumeSurface; - ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization - ConditionalWait mTbmSurfaceCondition; - + SurfaceSize mSurfaceSize; + TriggerEventInterface* mRenderNotification; + Internal::Adaptor::GraphicsInterface* mGraphics; ///< The graphics interface + EglInterface* mEGL; + EGLSurface mEGLSurface; + EGLContext mEGLContext; + ColorDepth mColorDepth; + tbm_format mTbmFormat; + bool mOwnSurface; + bool mDrawableCompleted; + + tbm_surface_queue_h mTbmQueue; + tbm_surface_h mConsumeSurface; + ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization + ConditionalWait mTbmSurfaceCondition; }; } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.cpp b/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.cpp index bf544f6..c2fc46b 100644 --- a/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ namespace Internal { namespace Adaptor { - std::unique_ptr DisplayConnectionFactoryX::CreateDisplayConnection() { return Utils::MakeUnique(); @@ -37,6 +36,6 @@ std::unique_ptr GetDisplayConnectionFactory() return Utils::MakeUnique(); } -} -} -} +} // namespace Adaptor +} // namespace Internal +} // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.h b/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.h index 3e8e576..2b8bed6 100644 --- a/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.h +++ b/dali/internal/window-system/ubuntu-x11/display-connection-factory-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_FACTORY_ECORE_X_H /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class DisplayConnectionFactoryX : public DisplayConnectionFactory { public: @@ -42,5 +39,4 @@ public: } // namespace Dali - #endif // DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_FACTORY_ECORE_X_H diff --git a/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.cpp b/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.cpp index 78c3fc0..c3e9b20 100644 --- a/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,22 +19,19 @@ #include // EXTERNAL_HEADERS -#include #include +#include // INTERNAL HEADERS -#include #include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - DisplayConnection* DisplayConnectionX11::New() { //DisplayConnection* pDisplayConnection(new DisplayConnection()); @@ -44,8 +41,8 @@ DisplayConnection* DisplayConnectionX11::New() } DisplayConnectionX11::DisplayConnectionX11() -: mGraphics( nullptr ), - mDisplay( nullptr ) +: mGraphics(nullptr), + mDisplay(nullptr) { } @@ -72,23 +69,22 @@ void DisplayConnectionX11::ConsumeEvents() // Check if there are any events in the queue events = XEventsQueued(mDisplay, QueuedAfterFlush); - if (events > 0) + if(events > 0) { // Just flush event to prevent memory leak from event queue as the events get built up in // memory but are only deleted when we retrieve them XEvent ev; XNextEvent(mDisplay, &ev); } - } - while (events > 0); + } while(events > 0); } bool DisplayConnectionX11::InitializeGraphics() { - auto eglGraphics = static_cast(mGraphics); - EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - if (!eglImpl.InitializeGles(reinterpret_cast(mDisplay))) + if(!eglImpl.InitializeGles(reinterpret_cast(mDisplay))) { DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; @@ -97,16 +93,16 @@ bool DisplayConnectionX11::InitializeGraphics() return true; } -void DisplayConnectionX11::SetSurfaceType( Dali::RenderSurfaceInterface::Type type ) +void DisplayConnectionX11::SetSurfaceType(Dali::RenderSurfaceInterface::Type type) { - if( type == Dali::RenderSurfaceInterface::WINDOW_RENDER_SURFACE ) + if(type == Dali::RenderSurfaceInterface::WINDOW_RENDER_SURFACE) { // Because of DDK issue, we need to use separated x display instead of ecore default display mDisplay = XOpenDisplay(0); } } -void DisplayConnectionX11::SetGraphicsInterface( GraphicsInterface& graphics ) +void DisplayConnectionX11::SetGraphicsInterface(GraphicsInterface& graphics) { mGraphics = &graphics; } diff --git a/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.h b/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.h index 64ffb76..9ddd4e2 100644 --- a/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.h +++ b/dali/internal/window-system/ubuntu-x11/display-connection-impl-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_DISPLAY_CONNECTION_IMPL_ECORE_X_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,31 +24,24 @@ namespace Dali { - class DisplayConnection; namespace Internal { - namespace Adaptor { - - class Impl { public: - - XDisplay* mDisplay; ///< X-display for rendering + XDisplay* mDisplay; ///< X-display for rendering }; - /** * DisplayConnection implementation */ class DisplayConnectionX11 : public Dali::Internal::Adaptor::DisplayConnection { public: - /** * @brief Default constructor */ @@ -62,7 +55,6 @@ public: static DisplayConnection* New(); public: - /** * @copydoc Dali::DisplayConnection::GetDisplay */ @@ -81,22 +73,20 @@ public: /** * @copydoc Dali::Internal::Adaptor::DisplayConnection::SetSurfaceType */ - void SetSurfaceType( Dali::RenderSurfaceInterface::Type type ); + void SetSurfaceType(Dali::RenderSurfaceInterface::Type type); /** * @copydoc Dali::Internal::Adaptor::DisplayConnection::SetGraphicsInterface */ - void SetGraphicsInterface( GraphicsInterface& graphics ); + void SetGraphicsInterface(GraphicsInterface& graphics); public: - /** * Destructor */ virtual ~DisplayConnectionX11(); protected: - // Undefined DisplayConnectionX11(const DisplayConnectionX11&) = delete; @@ -104,18 +94,15 @@ protected: DisplayConnectionX11& operator=(const DisplayConnectionX11& rhs) = delete; private: - GraphicsInterface* mGraphics; ///< The graphics interface public: - - XDisplay* mDisplay; ///< X-display for rendering - + XDisplay* mDisplay; ///< X-display for rendering }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/ecore-x-types.h b/dali/internal/window-system/ubuntu-x11/ecore-x-types.h index e5bc6c9..580b7de 100644 --- a/dali/internal/window-system/ubuntu-x11/ecore-x-types.h +++ b/dali/internal/window-system/ubuntu-x11/ecore-x-types.h @@ -2,7 +2,7 @@ #define DALI_X11_TYPES_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,10 @@ namespace Dali { - -typedef ::Pixmap XPixmap; -typedef ::Window XWindow; +typedef ::Pixmap XPixmap; +typedef ::Window XWindow; typedef ::Display XDisplay; -typedef ::Screen XScreen; +typedef ::Screen XScreen; } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.cpp b/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.cpp index 462279a..1aa2b46 100644 --- a/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,11 +22,11 @@ #include #include #include -#include // for damage notify #include // for damage notify -#include -#include +#include // for damage notify #include +#include +#include // INTERNAL INCLUDES #include @@ -42,7 +42,6 @@ namespace Internal { namespace Adaptor { - #if defined(DEBUG_ENABLED) Debug::Filter* gPixmapRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_PIXMAP_RENDER_SURFACE_ECORE_X"); #endif @@ -51,29 +50,29 @@ namespace { static const int INITIAL_PRODUCE_BUFFER_INDEX = 0; static const int INITIAL_CONSUME_BUFFER_INDEX = 1; -} - -PixmapRenderSurfaceEcoreX::PixmapRenderSurfaceEcoreX( Dali::PositionSize positionSize, Any surface, bool isTransparent ) -: mGraphics( nullptr ), - mDisplayConnection( nullptr ), - mPosition( positionSize ), - mRenderNotification( NULL ), - mColorDepth( isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24 ), - mOwnSurface( false ), - mProduceBufferIndex( INITIAL_PRODUCE_BUFFER_INDEX ), - mConsumeBufferIndex( INITIAL_CONSUME_BUFFER_INDEX ), +} // namespace + +PixmapRenderSurfaceEcoreX::PixmapRenderSurfaceEcoreX(Dali::PositionSize positionSize, Any surface, bool isTransparent) +: mGraphics(nullptr), + mDisplayConnection(nullptr), + mPosition(positionSize), + mRenderNotification(NULL), + mColorDepth(isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24), + mOwnSurface(false), + mProduceBufferIndex(INITIAL_PRODUCE_BUFFER_INDEX), + mConsumeBufferIndex(INITIAL_CONSUME_BUFFER_INDEX), mX11Pixmaps(), mEglSurfaces(), - mThreadSynchronization( nullptr ), + mThreadSynchronization(nullptr), mPixmapCondition() { - for( int i = 0; i != BUFFER_COUNT; ++i ) + for(int i = 0; i != BUFFER_COUNT; ++i) { - mX11Pixmaps[i] = 0; + mX11Pixmaps[i] = 0; mEglSurfaces[i] = 0; } - Initialize( surface ); + Initialize(surface); } PixmapRenderSurfaceEcoreX::~PixmapRenderSurfaceEcoreX() @@ -81,26 +80,26 @@ PixmapRenderSurfaceEcoreX::~PixmapRenderSurfaceEcoreX() DestroySurface(); // release the surface if we own one - if( mOwnSurface ) + if(mOwnSurface) { - for (int i = 0; i < BUFFER_COUNT; ++i) + for(int i = 0; i < BUFFER_COUNT; ++i) { Ecore_X_Pixmap pixmap = mX11Pixmaps[i]; // if we did create the pixmap, delete the pixmap - DALI_LOG_INFO( gPixmapRenderSurfaceLogFilter, Debug::General, "Own pixmap (%x) freed\n", pixmap ); - ecore_x_pixmap_free( pixmap ); + DALI_LOG_INFO(gPixmapRenderSurfaceLogFilter, Debug::General, "Own pixmap (%x) freed\n", pixmap); + ecore_x_pixmap_free(pixmap); } } } -void PixmapRenderSurfaceEcoreX::Initialize( Any surface ) +void PixmapRenderSurfaceEcoreX::Initialize(Any surface) { // see if there is a surface in Any surface - unsigned int surfaceId = GetSurfaceId( surface ); + unsigned int surfaceId = GetSurfaceId(surface); // if the surface is empty, create a new one. - if ( surfaceId == 0 ) + if(surfaceId == 0) { // we own the surface about to created mOwnSurface = true; @@ -109,7 +108,7 @@ void PixmapRenderSurfaceEcoreX::Initialize( Any surface ) else { // XLib should already be initialized so no point in calling XInitThreads - UseExistingRenderable( surfaceId ); + UseExistingRenderable(surfaceId); } } @@ -117,11 +116,11 @@ Any PixmapRenderSurfaceEcoreX::GetSurface() { Ecore_X_Pixmap pixmap = 0; { - ConditionalWait::ScopedLock lock( mPixmapCondition ); + ConditionalWait::ScopedLock lock(mPixmapCondition); pixmap = mX11Pixmaps[mProduceBufferIndex]; } - return Any( pixmap ); + return Any(pixmap); } void PixmapRenderSurfaceEcoreX::SetRenderNotification(TriggerEventInterface* renderNotification) @@ -134,7 +133,7 @@ PositionSize PixmapRenderSurfaceEcoreX::GetPositionSize() const return mPosition; } -void PixmapRenderSurfaceEcoreX::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void PixmapRenderSurfaceEcoreX::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; @@ -143,8 +142,8 @@ void PixmapRenderSurfaceEcoreX::GetDpi( unsigned int& dpiHorizontal, unsigned in xres = ecore_x_dpi_get(); yres = ecore_x_dpi_get(); - dpiHorizontal = int( xres + 0.5f ); // rounding - dpiVertical = int( yres + 0.5f ); + dpiHorizontal = int(xres + 0.5f); // rounding + dpiVertical = int(yres + 0.5f); } int PixmapRenderSurfaceEcoreX::GetOrientation() const @@ -154,69 +153,68 @@ int PixmapRenderSurfaceEcoreX::GetOrientation() const void PixmapRenderSurfaceEcoreX::InitializeGraphics() { - mGraphics = &mAdaptor->GetGraphicsInterface(); + mGraphics = &mAdaptor->GetGraphicsInterface(); mDisplayConnection = &mAdaptor->GetDisplayConnectionInterface(); - - auto eglGraphics = static_cast(mGraphics); - Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); eglImpl.ChooseConfig(false, mColorDepth); } void PixmapRenderSurfaceEcoreX::CreateSurface() { - DALI_LOG_TRACE_METHOD( gPixmapRenderSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gPixmapRenderSurfaceLogFilter); - auto eglGraphics = static_cast(mGraphics); - Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - for (int i = 0; i < BUFFER_COUNT; ++i) + for(int i = 0; i < BUFFER_COUNT; ++i) { // create the EGL surface // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit - XPixmap pixmap = static_cast( mX11Pixmaps[i] ); - mEglSurfaces[i] = eglImpl.CreateSurfacePixmap( EGLNativePixmapType( pixmap ), mColorDepth ); // reinterpret_cast does not compile + XPixmap pixmap = static_cast(mX11Pixmaps[i]); + mEglSurfaces[i] = eglImpl.CreateSurfacePixmap(EGLNativePixmapType(pixmap), mColorDepth); // reinterpret_cast does not compile } } void PixmapRenderSurfaceEcoreX::DestroySurface() { - DALI_LOG_TRACE_METHOD( gPixmapRenderSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gPixmapRenderSurfaceLogFilter); - auto eglGraphics = static_cast(mGraphics); + auto eglGraphics = static_cast(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - for (int i = 0; i < BUFFER_COUNT; ++i) + for(int i = 0; i < BUFFER_COUNT; ++i) { // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit - XPixmap pixmap = static_cast( mX11Pixmaps[i] ); - eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mEglSurfaces[i] ); - eglImpl.DestroySurface( mEglSurfaces[i] ); + XPixmap pixmap = static_cast(mX11Pixmaps[i]); + eglImpl.MakeCurrent(EGLNativePixmapType(pixmap), mEglSurfaces[i]); + eglImpl.DestroySurface(mEglSurfaces[i]); } } bool PixmapRenderSurfaceEcoreX::ReplaceGraphicsSurface() { - DALI_LOG_TRACE_METHOD( gPixmapRenderSurfaceLogFilter ); + DALI_LOG_TRACE_METHOD(gPixmapRenderSurfaceLogFilter); bool contextLost = false; - auto eglGraphics = static_cast(mGraphics); + auto eglGraphics = static_cast(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - for (int i = 0; i < BUFFER_COUNT; ++i) + for(int i = 0; i < BUFFER_COUNT; ++i) { // a new surface for the new pixmap // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit - XPixmap pixmap = static_cast( mX11Pixmaps[i] ); - contextLost = eglImpl.ReplaceSurfacePixmap( EGLNativePixmapType( pixmap ), mEglSurfaces[i] ); // reinterpret_cast does not compile + XPixmap pixmap = static_cast(mX11Pixmaps[i]); + contextLost = eglImpl.ReplaceSurfacePixmap(EGLNativePixmapType(pixmap), mEglSurfaces[i]); // reinterpret_cast does not compile } // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit - XPixmap pixmap = static_cast( mX11Pixmaps[mProduceBufferIndex] ); - eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mEglSurfaces[mProduceBufferIndex] ); + XPixmap pixmap = static_cast(mX11Pixmaps[mProduceBufferIndex]); + eglImpl.MakeCurrent(EGLNativePixmapType(pixmap), mEglSurfaces[mProduceBufferIndex]); return contextLost; } @@ -225,38 +223,38 @@ void PixmapRenderSurfaceEcoreX::StartRender() { } -bool PixmapRenderSurfaceEcoreX::PreRender( bool, const std::vector>&, Rect& ) +bool PixmapRenderSurfaceEcoreX::PreRender(bool, const std::vector>&, Rect&) { // Nothing to do for pixmaps return true; } -void PixmapRenderSurfaceEcoreX::PostRender( bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects ) +void PixmapRenderSurfaceEcoreX::PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects) { - auto eglGraphics = static_cast(mGraphics); + auto eglGraphics = static_cast(mGraphics); // flush gl instruction queue Integration::GlAbstraction& glAbstraction = eglGraphics->GetGlAbstraction(); glAbstraction.Flush(); - if( mThreadSynchronization ) + if(mThreadSynchronization) { mThreadSynchronization->PostRenderStarted(); } { - ConditionalWait::ScopedLock lock( mPixmapCondition ); - mConsumeBufferIndex = __sync_fetch_and_xor( &mProduceBufferIndex, 1 ); // Swap buffer indexes. + ConditionalWait::ScopedLock lock(mPixmapCondition); + mConsumeBufferIndex = __sync_fetch_and_xor(&mProduceBufferIndex, 1); // Swap buffer indexes. Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); // need to cast to X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit - XPixmap pixmap = static_cast( mX11Pixmaps[mProduceBufferIndex] ); - eglImpl.MakeCurrent( EGLNativePixmapType( pixmap ), mEglSurfaces[mProduceBufferIndex] ); + XPixmap pixmap = static_cast(mX11Pixmaps[mProduceBufferIndex]); + eglImpl.MakeCurrent(EGLNativePixmapType(pixmap), mEglSurfaces[mProduceBufferIndex]); } // create damage for client applications which wish to know the update timing - if( mRenderNotification ) + if(mRenderNotification) { // use notification trigger // Tell the event-thread to render the pixmap @@ -265,32 +263,32 @@ void PixmapRenderSurfaceEcoreX::PostRender( bool renderToFbo, bool replacingSurf else { // as a fallback, send damage event. - Ecore_X_Drawable drawable = Ecore_X_Drawable( mX11Pixmaps[mProduceBufferIndex] ); + Ecore_X_Drawable drawable = Ecore_X_Drawable(mX11Pixmaps[mProduceBufferIndex]); - if( drawable ) + if(drawable) { - XRectangle rect; + XRectangle rect; XserverRegion region; - rect.x = 0; - rect.y = 0; - rect.width = mPosition.width; + rect.x = 0; + rect.y = 0; + rect.width = mPosition.width; rect.height = mPosition.height; XDisplay* display = AnyCast(mDisplayConnection->GetDisplay()); // make a fixes region as updated area - region = XFixesCreateRegion( display, &rect, 1 ); + region = XFixesCreateRegion(display, &rect, 1); // add damage event to updated drawable - Drawable xdrawable( drawable ); // ecore type is unsigned int whereas in 64bit linux Drawable is long unsigned int - XDamageAdd( display, xdrawable, region ); - XFixesDestroyRegion( display, region ); + Drawable xdrawable(drawable); // ecore type is unsigned int whereas in 64bit linux Drawable is long unsigned int + XDamageAdd(display, xdrawable, region); + XFixesDestroyRegion(display, region); - XFlush( display ); + XFlush(display); } } - if( mThreadSynchronization ) + if(mThreadSynchronization) { mThreadSynchronization->PostRenderWaitForCompletion(); } @@ -301,14 +299,14 @@ void PixmapRenderSurfaceEcoreX::StopRender() ReleaseLock(); } -void PixmapRenderSurfaceEcoreX::SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization ) +void PixmapRenderSurfaceEcoreX::SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) { mThreadSynchronization = &threadSynchronization; } void PixmapRenderSurfaceEcoreX::ReleaseLock() { - if( mThreadSynchronization ) + if(mThreadSynchronization) { mThreadSynchronization->PostRenderComplete(); } @@ -326,26 +324,26 @@ void PixmapRenderSurfaceEcoreX::MakeContextCurrent() void PixmapRenderSurfaceEcoreX::CreateRenderable() { // check we're creating one with a valid size - DALI_ASSERT_ALWAYS( mPosition.width > 0 && mPosition.height > 0 && "Pixmap size is invalid" ); + DALI_ASSERT_ALWAYS(mPosition.width > 0 && mPosition.height > 0 && "Pixmap size is invalid"); - for (int i = 0; i < BUFFER_COUNT; ++i) + for(int i = 0; i < BUFFER_COUNT; ++i) { // create the pixmap mX11Pixmaps[i] = ecore_x_pixmap_new(0, mPosition.width, mPosition.height, mColorDepth); // clear the pixmap unsigned int foreground; - Ecore_X_GC gc; + Ecore_X_GC gc; foreground = 0; - gc = ecore_x_gc_new( mX11Pixmaps[i], - ECORE_X_GC_VALUE_MASK_FOREGROUND, - &foreground ); + gc = ecore_x_gc_new(mX11Pixmaps[i], + ECORE_X_GC_VALUE_MASK_FOREGROUND, + &foreground); - DALI_ASSERT_ALWAYS( gc && "CreateRenderable(): failed to get gc" ); + DALI_ASSERT_ALWAYS(gc && "CreateRenderable(): failed to get gc"); - ecore_x_drawable_rectangle_fill( mX11Pixmaps[i], gc, 0, 0, mPosition.width, mPosition.height ); + ecore_x_drawable_rectangle_fill(mX11Pixmaps[i], gc, 0, 0, mPosition.width, mPosition.height); - DALI_ASSERT_ALWAYS( mX11Pixmaps[i] && "Failed to create X pixmap" ); + DALI_ASSERT_ALWAYS(mX11Pixmaps[i] && "Failed to create X pixmap"); // we SHOULD guarantee the xpixmap/x11 window was created in x server. ecore_x_sync(); @@ -354,28 +352,28 @@ void PixmapRenderSurfaceEcoreX::CreateRenderable() } } -void PixmapRenderSurfaceEcoreX::UseExistingRenderable( unsigned int surfaceId ) +void PixmapRenderSurfaceEcoreX::UseExistingRenderable(unsigned int surfaceId) { } -unsigned int PixmapRenderSurfaceEcoreX::GetSurfaceId( Any surface ) const +unsigned int PixmapRenderSurfaceEcoreX::GetSurfaceId(Any surface) const { unsigned int surfaceId = 0; - if ( surface.Empty() == false ) + if(surface.Empty() == false) { // check we have a valid type - DALI_ASSERT_ALWAYS( ( (surface.GetType() == typeid (XWindow) ) || - (surface.GetType() == typeid (Ecore_X_Window) ) ) - && "Surface type is invalid" ); + DALI_ASSERT_ALWAYS(((surface.GetType() == typeid(XWindow)) || + (surface.GetType() == typeid(Ecore_X_Window))) && + "Surface type is invalid"); - if ( surface.GetType() == typeid (Ecore_X_Window) ) + if(surface.GetType() == typeid(Ecore_X_Window)) { - surfaceId = AnyCast( surface ); + surfaceId = AnyCast(surface); } else { - surfaceId = AnyCast( surface ); + surfaceId = AnyCast(surface); } } return surfaceId; @@ -383,6 +381,6 @@ unsigned int PixmapRenderSurfaceEcoreX::GetSurfaceId( Any surface ) const } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.h b/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.h index c8a7163..c9a6906 100644 --- a/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.h +++ b/dali/internal/window-system/ubuntu-x11/pixmap-render-surface-ecore-x.h @@ -2,7 +2,7 @@ #define DALI_ECORE_X_PIXMAP_RENDER_SURFACE_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,13 @@ #include // INTERNAL INCLUDES -#include #include #include #include #include #include #include +#include namespace Dali { @@ -36,21 +36,19 @@ namespace Internal { namespace Adaptor { - /** * Ecore X11 Pixmap implementation of render surface. */ class PixmapRenderSurfaceEcoreX : public PixmapRenderSurface { public: - /** * Uses an X11 surface to render to. * @param [in] positionSize the position and size of the surface * @param [in] surface can be a X-window or X-pixmap (type must be unsigned int). * @param [in] isTransparent if it is true, surface has 32 bit color depth, otherwise, 24 bit */ - PixmapRenderSurfaceEcoreX( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ); + PixmapRenderSurfaceEcoreX(Dali::PositionSize positionSize, Any surface, bool isTransparent = false); /** * @brief Destructor @@ -58,7 +56,6 @@ public: virtual ~PixmapRenderSurfaceEcoreX(); public: // from WindowRenderSurface - /** * @copydoc Dali::Internal::Adaptor::PixmapRenderSurface::GetSurface() */ @@ -67,10 +64,9 @@ public: // from WindowRenderSurface /** * @copydoc Dali::Internal::Adaptor::PixmapRenderSurface::SetRenderNotification() */ - void SetRenderNotification( TriggerEventInterface* renderNotification ) override; + void SetRenderNotification(TriggerEventInterface* renderNotification) override; public: // from Dali::RenderSurfaceInterface - /** * @copydoc Dali::RenderSurfaceInterface::GetPositionSize() */ @@ -79,7 +75,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetOrientation() @@ -109,7 +105,9 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::MoveResize() */ - virtual void MoveResize( Dali::PositionSize positionSize) override {} + virtual void MoveResize(Dali::PositionSize positionSize) override + { + } /** * @copydoc Dali::RenderSurfaceInterface::StartRender() @@ -119,12 +117,12 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::PreRender() */ - bool PreRender( bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect ) override; + bool PreRender(bool resizingSurface, const std::vector>& damagedRects, Rect& clippingRect) override; /** * @copydoc Dali::RenderSurfaceInterface::PostRender() */ - void PostRender( bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects ) override; + void PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector>& damagedRects) override; /** * @copydoc Dali::RenderSurfaceInterface::StopRender() @@ -134,7 +132,7 @@ public: // from Dali::RenderSurfaceInterface /** * @copydoc Dali::RenderSurfaceInterface::SetThreadSynchronization */ - void SetThreadSynchronization( ThreadSynchronizationInterface& threadSynchronization ) override; + void SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) override; /** * @copydoc Dali::RenderSurfaceInterface::GetSurfaceType() @@ -147,7 +145,6 @@ public: // from Dali::RenderSurfaceInterface void MakeContextCurrent() override; private: // from PixmapRenderSurface - /** * @copydoc Dali::RenderSurfaceInterface::ReleaseLock() */ @@ -156,7 +153,7 @@ private: // from PixmapRenderSurface /** * @copydoc Dali::Internal::Adaptor::PixmapRenderSurface::Initialize() */ - void Initialize( Any surface ) override; + void Initialize(Any surface) override; /** * @copydoc Dali::Internal::Adaptor::PixmapRenderSurface::Initialize() @@ -166,38 +163,36 @@ private: // from PixmapRenderSurface /** * @copydoc Dali::Internal::Adaptor::PixmapRenderSurface::Initialize() */ - void UseExistingRenderable( unsigned int surfaceId ) override; + void UseExistingRenderable(unsigned int surfaceId) override; private: - /** * Get the surface id if the surface parameter is not empty * @param surface Any containing a surface id, or can be empty * @return surface id, or zero if surface is empty */ - unsigned int GetSurfaceId( Any surface ) const; + unsigned int GetSurfaceId(Any surface) const; private: // Data - - static const int BUFFER_COUNT = 2; - GraphicsInterface* mGraphics; ///< Graphics interface - Dali::DisplayConnection* mDisplayConnection; ///< Display connection - PositionSize mPosition; ///< Position - TriggerEventInterface* mRenderNotification; ///< Render notification trigger - ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit) - bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it) + static const int BUFFER_COUNT = 2; + GraphicsInterface* mGraphics; ///< Graphics interface + Dali::DisplayConnection* mDisplayConnection; ///< Display connection + PositionSize mPosition; ///< Position + TriggerEventInterface* mRenderNotification; ///< Render notification trigger + ColorDepth mColorDepth; ///< Color depth of surface (32 bit or 24 bit) + bool mOwnSurface; ///< Whether we own the surface (responsible for deleting it) int mProduceBufferIndex; int mConsumeBufferIndex; - XPixmap mX11Pixmaps[BUFFER_COUNT]; ///< X-Pixmap + XPixmap mX11Pixmaps[BUFFER_COUNT]; ///< X-Pixmap EGLSurface mEglSurfaces[BUFFER_COUNT]; - ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization - ConditionalWait mPixmapCondition; ///< condition to share pixmap + ThreadSynchronizationInterface* mThreadSynchronization; ///< A pointer to the thread-synchronization + ConditionalWait mPixmapCondition; ///< condition to share pixmap }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.cpp b/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.cpp index c5ba610..2a30299 100644 --- a/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,27 +33,26 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowRenderSurface > RenderSurfaceFactoryEcoreX::CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreX::CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowRenderSurface >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< PixmapRenderSurface > RenderSurfaceFactoryEcoreX::CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreX::CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< PixmapRenderSurfaceEcoreX >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< NativeRenderSurface > RenderSurfaceFactoryEcoreX::CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryEcoreX::CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent) { - return std::unique_ptr< NativeRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } // this should be created from somewhere -std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory() +std::unique_ptr GetRenderSurfaceFactory() { // returns Window factory - return Utils::MakeUnique< RenderSurfaceFactoryEcoreX >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.h b/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.h index 6fd5981..7d3bd48 100644 --- a/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.h +++ b/dali/internal/window-system/ubuntu-x11/render-surface-factory-ecore-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_RENDER_SURFACE_FACTORY_ECORE_X_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,15 +26,14 @@ namespace Internal { namespace Adaptor { - class RenderSurfaceFactoryEcoreX : public RenderSurfaceFactory { public: - std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.cpp b/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.cpp old mode 100755 new mode 100644 index 107c734..b12f37e --- a/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,48 +20,44 @@ // INTERNAL HEADERS #include -#include #include +#include #include // EXTERNAL_HEADERS -#include -#include #include #include +#include +#include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - -const std::string DEFAULT_DEVICE_NAME = ""; -const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE; +const std::string DEFAULT_DEVICE_NAME = ""; +const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE; const Device::Subclass::Type DEFAULT_DEVICE_SUBCLASS = Device::Subclass::NONE; -const unsigned int PRIMARY_TOUCH_BUTTON_ID( 1 ); +const unsigned int PRIMARY_TOUCH_BUTTON_ID(1); #if defined(DEBUG_ENABLED) -Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_WINDOW_BASE" ); +Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW_BASE"); #endif ///////////////////////////////////////////////////////////////////////////////////////////////// // Window Callbacks ///////////////////////////////////////////////////////////////////////////////////////////////// -static Eina_Bool EcoreEventWindowPropertyChanged( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowPropertyChanged(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - return windowBase->OnWindowPropertyChanged( data, type, event ); + return windowBase->OnWindowPropertyChanged(data, type, event); } return ECORE_CALLBACK_PASS_ON; @@ -70,10 +66,10 @@ static Eina_Bool EcoreEventWindowPropertyChanged( void* data, int type, void* ev /** * Called when the window receives a delete request */ -static Eina_Bool EcoreEventWindowDeleteRequest( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowDeleteRequest(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { windowBase->OnDeleteRequest(); } @@ -83,12 +79,12 @@ static Eina_Bool EcoreEventWindowDeleteRequest( void* data, int type, void* even /** * Called when the window gains focus. */ -static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowFocusIn(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnFocusIn( data, type, event ); + windowBase->OnFocusIn(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -96,12 +92,12 @@ static Eina_Bool EcoreEventWindowFocusIn( void* data, int type, void* event ) /** * Called when the window loses focus. */ -static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowFocusOut(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnFocusOut( data, type, event ); + windowBase->OnFocusOut(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -109,12 +105,12 @@ static Eina_Bool EcoreEventWindowFocusOut( void* data, int type, void* event ) /** * Called when the window is damaged. */ -static Eina_Bool EcoreEventWindowDamaged( void* data, int type, void* event ) +static Eina_Bool EcoreEventWindowDamaged(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnWindowDamaged( data, type, event ); + windowBase->OnWindowDamaged(data, type, event); } return ECORE_CALLBACK_PASS_ON; @@ -127,12 +123,12 @@ static Eina_Bool EcoreEventWindowDamaged( void* data, int type, void* event ) /** * Called when the source window notifies us the content in clipboard is selected. */ -static Eina_Bool EcoreEventSelectionClear( void* data, int type, void* event ) +static Eina_Bool EcoreEventSelectionClear(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnSelectionClear( data, type, event ); + windowBase->OnSelectionClear(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -141,12 +137,12 @@ static Eina_Bool EcoreEventSelectionClear( void* data, int type, void* event ) * Called when the source window sends us about the selected content. * For example, when dragged items are dragged INTO our window or when items are selected in the clipboard. */ -static Eina_Bool EcoreEventSelectionNotify( void* data, int type, void* event ) +static Eina_Bool EcoreEventSelectionNotify(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnSelectionNotify( data, type, event ); + windowBase->OnSelectionNotify(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -158,12 +154,12 @@ static Eina_Bool EcoreEventSelectionNotify( void* data, int type, void* event ) /** * Called when a touch down is received. */ -static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonDown(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonDown( data, type, event ); + windowBase->OnMouseButtonDown(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -171,12 +167,12 @@ static Eina_Bool EcoreEventMouseButtonDown( void* data, int type, void* event ) /** * Called when a touch up is received. */ -static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonUp(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonUp( data, type, event ); + windowBase->OnMouseButtonUp(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -184,12 +180,12 @@ static Eina_Bool EcoreEventMouseButtonUp( void* data, int type, void* event ) /** * Called when a touch motion is received. */ -static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseButtonMove(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseButtonMove( data, type, event ); + windowBase->OnMouseButtonMove(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -201,12 +197,12 @@ static Eina_Bool EcoreEventMouseButtonMove( void* data, int type, void* event ) /** * Called when a mouse wheel is received. */ -static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event ) +static Eina_Bool EcoreEventMouseWheel(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnMouseWheel( data, type, event ); + windowBase->OnMouseWheel(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -218,12 +214,12 @@ static Eina_Bool EcoreEventMouseWheel( void* data, int type, void* event ) /** * Called when a key down is received. */ -static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event ) +static Eina_Bool EcoreEventKeyDown(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnKeyDown( data, type, event ); + windowBase->OnKeyDown(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -231,12 +227,12 @@ static Eina_Bool EcoreEventKeyDown( void* data, int type, void* event ) /** * Called when a key up is received. */ -static Eina_Bool EcoreEventKeyUp( void* data, int type, void* event ) +static Eina_Bool EcoreEventKeyUp(void* data, int type, void* event) { - WindowBaseEcoreX* windowBase = static_cast< WindowBaseEcoreX* >( data ); - if( windowBase ) + WindowBaseEcoreX* windowBase = static_cast(data); + if(windowBase) { - windowBase->OnKeyUp( data, type, event ); + windowBase->OnKeyUp(data, type, event); } return ECORE_CALLBACK_PASS_ON; } @@ -256,124 +252,124 @@ WindowBaseEcoreX::WindowBaseEcoreX(Dali::PositionSize positionSize, Any surface, WindowBaseEcoreX::~WindowBaseEcoreX() { - for( Dali::Vector< Ecore_Event_Handler* >::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter ) + for(Dali::Vector::Iterator iter = mEcoreEventHandler.Begin(), endIter = mEcoreEventHandler.End(); iter != endIter; ++iter) { - ecore_event_handler_del( *iter ); + ecore_event_handler_del(*iter); } mEcoreEventHandler.Clear(); - if( mOwnSurface ) + if(mOwnSurface) { - ecore_x_window_free( mEcoreWindow ); + ecore_x_window_free(mEcoreWindow); WindowSystem::Shutdown(); } } -void WindowBaseEcoreX::Initialize( PositionSize positionSize, Any surface, bool isTransparent ) +void WindowBaseEcoreX::Initialize(PositionSize positionSize, Any surface, bool isTransparent) { // see if there is a surface in Any surface - unsigned int surfaceId = GetSurfaceId( surface ); + unsigned int surfaceId = GetSurfaceId(surface); // if the surface is empty, create a new one. - if( surfaceId == 0 ) + if(surfaceId == 0) { WindowSystem::Initialize(); // we own the surface about to created mOwnSurface = true; - CreateWindow( positionSize, isTransparent ); + CreateWindow(positionSize, isTransparent); } else { // XLib should already be initialized so no point in calling XInitThreads - mEcoreWindow = static_cast< Ecore_X_Window >( surfaceId ); + mEcoreWindow = static_cast(surfaceId); } // set up etc properties to match with ecore-evas - char *id = NULL; - if( ( id = getenv("DESKTOP_STARTUP_ID") ) ) + char* id = NULL; + if((id = getenv("DESKTOP_STARTUP_ID"))) { - ecore_x_netwm_startup_id_set( mEcoreWindow, id ); + ecore_x_netwm_startup_id_set(mEcoreWindow, id); } - ecore_x_icccm_hints_set( mEcoreWindow, - 1, // accepts_focus - ECORE_X_WINDOW_STATE_HINT_NORMAL, // initial_state - 0, // icon_pixmap - 0, // icon_mask - 0, // icon_window - 0, // window_group - 0 ); // is_urgent + ecore_x_icccm_hints_set(mEcoreWindow, + 1, // accepts_focus + ECORE_X_WINDOW_STATE_HINT_NORMAL, // initial_state + 0, // icon_pixmap + 0, // icon_mask + 0, // icon_window + 0, // window_group + 0); // is_urgent // we SHOULD guarantee the x11 window was created in x server. ecore_x_sync(); - ecore_x_input_multi_select( mEcoreWindow ); + ecore_x_input_multi_select(mEcoreWindow); // This ensures that we catch the window close (or delete) request - ecore_x_icccm_protocol_set( mEcoreWindow, ECORE_X_WM_PROTOCOL_DELETE_REQUEST, EINA_TRUE ); + ecore_x_icccm_protocol_set(mEcoreWindow, ECORE_X_WM_PROTOCOL_DELETE_REQUEST, EINA_TRUE); // Enable Drag & Drop - ecore_x_dnd_aware_set( mEcoreWindow, EINA_TRUE ); + ecore_x_dnd_aware_set(mEcoreWindow, EINA_TRUE); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_PROPERTY, EcoreEventWindowPropertyChanged, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_DELETE_REQUEST, EcoreEventWindowDeleteRequest, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_PROPERTY, EcoreEventWindowPropertyChanged, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_DELETE_REQUEST, EcoreEventWindowDeleteRequest, this)); // Register window focus events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_FOCUS_IN, EcoreEventWindowFocusIn, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_FOCUS_OUT, EcoreEventWindowFocusOut, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_FOCUS_IN, EcoreEventWindowFocusIn, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_FOCUS_OUT, EcoreEventWindowFocusOut, this)); // Register Window damage events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_WINDOW_DAMAGE, EcoreEventWindowDamaged, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_WINDOW_DAMAGE, EcoreEventWindowDamaged, this)); // Register Touch events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_OUT, EcoreEventMouseButtonUp, this ) ); // process mouse out event like up event + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN, EcoreEventMouseButtonDown, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_UP, EcoreEventMouseButtonUp, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_MOVE, EcoreEventMouseButtonMove, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_OUT, EcoreEventMouseButtonUp, this)); // process mouse out event like up event // Register Mouse wheel events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_MOUSE_WHEEL, EcoreEventMouseWheel, this)); // Register Key events - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_DOWN, EcoreEventKeyDown, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_EVENT_KEY_UP, EcoreEventKeyUp, this)); // Register Selection event - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_SELECTION_CLEAR, EcoreEventSelectionClear, this ) ); - mEcoreEventHandler.PushBack( ecore_event_handler_add( ECORE_X_EVENT_SELECTION_NOTIFY, EcoreEventSelectionNotify, this ) ); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_SELECTION_CLEAR, EcoreEventSelectionClear, this)); + mEcoreEventHandler.PushBack(ecore_event_handler_add(ECORE_X_EVENT_SELECTION_NOTIFY, EcoreEventSelectionNotify, this)); } -Eina_Bool WindowBaseEcoreX::OnWindowPropertyChanged( void* data, int type, void* event ) +Eina_Bool WindowBaseEcoreX::OnWindowPropertyChanged(void* data, int type, void* event) { - Ecore_X_Event_Window_Property* propertyChangedEvent = static_cast< Ecore_X_Event_Window_Property* >( event ); - Eina_Bool handled( ECORE_CALLBACK_PASS_ON ); + Ecore_X_Event_Window_Property* propertyChangedEvent = static_cast(event); + Eina_Bool handled(ECORE_CALLBACK_PASS_ON); - if( propertyChangedEvent->win == mEcoreWindow ) + if(propertyChangedEvent->win == mEcoreWindow) { - Ecore_X_Window_State_Hint state( ecore_x_icccm_state_get( propertyChangedEvent->win ) ); + Ecore_X_Window_State_Hint state(ecore_x_icccm_state_get(propertyChangedEvent->win)); - switch( state ) + switch(state) { case ECORE_X_WINDOW_STATE_HINT_WITHDRAWN: { // Window was hidden. - mIconifyChangedSignal.Emit( true ); + mIconifyChangedSignal.Emit(true); handled = ECORE_CALLBACK_DONE; break; } case ECORE_X_WINDOW_STATE_HINT_ICONIC: { // Window was iconified (minimised). - mIconifyChangedSignal.Emit( true ); + mIconifyChangedSignal.Emit(true); handled = ECORE_CALLBACK_DONE; break; } case ECORE_X_WINDOW_STATE_HINT_NORMAL: { // Window was shown. - mIconifyChangedSignal.Emit( false ); + mIconifyChangedSignal.Emit(false); handled = ECORE_CALLBACK_DONE; break; } @@ -393,236 +389,236 @@ void WindowBaseEcoreX::OnDeleteRequest() mDeleteRequestSignal.Emit(); } -void WindowBaseEcoreX::OnFocusIn( void* data, int type, void* event ) +void WindowBaseEcoreX::OnFocusIn(void* data, int type, void* event) { - Ecore_X_Event_Window_Focus_In* focusInEvent = static_cast< Ecore_X_Event_Window_Focus_In* >( event ); + Ecore_X_Event_Window_Focus_In* focusInEvent = static_cast(event); - if( focusInEvent->win == mEcoreWindow ) + if(focusInEvent->win == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusIn\n"); - mFocusChangedSignal.Emit( true ); + mFocusChangedSignal.Emit(true); } } -void WindowBaseEcoreX::OnFocusOut( void* data, int type, void* event ) +void WindowBaseEcoreX::OnFocusOut(void* data, int type, void* event) { - Ecore_X_Event_Window_Focus_Out* focusOutEvent = static_cast< Ecore_X_Event_Window_Focus_Out* >( event ); + Ecore_X_Event_Window_Focus_Out* focusOutEvent = static_cast(event); // If the window loses focus then hide the keyboard. - if( focusOutEvent->win == mEcoreWindow ) + if(focusOutEvent->win == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "Window EcoreEventWindowFocusOut\n"); - mFocusChangedSignal.Emit( false ); + mFocusChangedSignal.Emit(false); } } -void WindowBaseEcoreX::OnWindowDamaged( void* data, int type, void* event ) +void WindowBaseEcoreX::OnWindowDamaged(void* data, int type, void* event) { - Ecore_X_Event_Window_Damage* windowDamagedEvent = static_cast< Ecore_X_Event_Window_Damage* >( event ); + Ecore_X_Event_Window_Damage* windowDamagedEvent = static_cast(event); - if( windowDamagedEvent->win == mEcoreWindow ) + if(windowDamagedEvent->win == mEcoreWindow) { DamageArea area; - area.x = windowDamagedEvent->x; - area.y = windowDamagedEvent->y; - area.width = windowDamagedEvent->w; + area.x = windowDamagedEvent->x; + area.y = windowDamagedEvent->y; + area.width = windowDamagedEvent->w; area.height = windowDamagedEvent->h; - mWindowDamagedSignal.Emit( area ); + mWindowDamagedSignal.Emit(area); } } -void WindowBaseEcoreX::OnMouseButtonDown( void* data, int type, void* event ) +void WindowBaseEcoreX::OnMouseButtonDown(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == mEcoreWindow ) + if(touchEvent->window == mEcoreWindow) { - PointState::Type state ( PointState::DOWN ); + PointState::Type state(PointState::DOWN); Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( state ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( touchEvent->multi.angle ) ); - if( touchEvent->buttons) + point.SetDeviceId(touchEvent->multi.device); + point.SetState(state); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(touchEvent->multi.angle)); + if(touchEvent->buttons) { - point.SetMouseButton( static_cast< MouseButton::Type >( touchEvent->buttons) ); + point.SetMouseButton(static_cast(touchEvent->buttons)); } - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreX::OnMouseButtonUp( void* data, int type, void* event ) +void WindowBaseEcoreX::OnMouseButtonUp(void* data, int type, void* event) { - Ecore_Event_Mouse_Button* touchEvent = static_cast< Ecore_Event_Mouse_Button* >( event ); + Ecore_Event_Mouse_Button* touchEvent = static_cast(event); - if( touchEvent->window == mEcoreWindow ) + if(touchEvent->window == mEcoreWindow) { Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::UP ); - point.SetScreenPosition( Vector2( touchEvent->x, touchEvent->y ) ); - point.SetRadius( touchEvent->multi.radius, Vector2( touchEvent->multi.radius_x, touchEvent->multi.radius_y ) ); - point.SetPressure( touchEvent->multi.pressure ); - point.SetAngle( Degree( static_cast( touchEvent->multi.angle ) ) ); - if( touchEvent->buttons) + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::UP); + point.SetScreenPosition(Vector2(touchEvent->x, touchEvent->y)); + point.SetRadius(touchEvent->multi.radius, Vector2(touchEvent->multi.radius_x, touchEvent->multi.radius_y)); + point.SetPressure(touchEvent->multi.pressure); + point.SetAngle(Degree(static_cast(touchEvent->multi.angle))); + if(touchEvent->buttons) { - point.SetMouseButton( static_cast< MouseButton::Type >( touchEvent->buttons) ); + point.SetMouseButton(static_cast(touchEvent->buttons)); } - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreX::OnMouseButtonMove( void* data, int type, void* event ) +void WindowBaseEcoreX::OnMouseButtonMove(void* data, int type, void* event) { - Ecore_Event_Mouse_Move* touchEvent = static_cast< Ecore_Event_Mouse_Move* >( event ); + Ecore_Event_Mouse_Move* touchEvent = static_cast(event); - if( touchEvent->window == mEcoreWindow ) + if(touchEvent->window == mEcoreWindow) { Integration::Point point; - point.SetDeviceId( touchEvent->multi.device ); - point.SetState( PointState::MOTION ); - point.SetScreenPosition( Vector2( static_cast( touchEvent->x ), static_cast( touchEvent->y ) ) ); - point.SetRadius( static_cast( touchEvent->multi.radius ), Vector2( static_cast( touchEvent->multi.radius_x ), static_cast( touchEvent->multi.radius_y ) ) ); - point.SetPressure( static_cast( touchEvent->multi.pressure ) ); - point.SetAngle( Degree( static_cast( touchEvent->multi.angle ) ) ); + point.SetDeviceId(touchEvent->multi.device); + point.SetState(PointState::MOTION); + point.SetScreenPosition(Vector2(static_cast(touchEvent->x), static_cast(touchEvent->y))); + point.SetRadius(static_cast(touchEvent->multi.radius), Vector2(static_cast(touchEvent->multi.radius_x), static_cast(touchEvent->multi.radius_y))); + point.SetPressure(static_cast(touchEvent->multi.pressure)); + point.SetAngle(Degree(static_cast(touchEvent->multi.angle))); - mTouchEventSignal.Emit( point, touchEvent->timestamp ); + mTouchEventSignal.Emit(point, touchEvent->timestamp); } } -void WindowBaseEcoreX::OnMouseWheel( void* data, int type, void* event ) +void WindowBaseEcoreX::OnMouseWheel(void* data, int type, void* event) { - Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast< Ecore_Event_Mouse_Wheel* >( event ); + Ecore_Event_Mouse_Wheel* mouseWheelEvent = static_cast(event); - if( mouseWheelEvent->window == mEcoreWindow ) + if(mouseWheelEvent->window == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreX::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreX::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent->direction, mouseWheelEvent->modifiers, mouseWheelEvent->x, mouseWheelEvent->y, mouseWheelEvent->z); - Integration::WheelEvent wheelEvent( Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2( static_cast( mouseWheelEvent->x ), static_cast( mouseWheelEvent->y ) ), mouseWheelEvent->z, mouseWheelEvent->timestamp ); + Integration::WheelEvent wheelEvent(Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent->direction, mouseWheelEvent->modifiers, Vector2(static_cast(mouseWheelEvent->x), static_cast(mouseWheelEvent->y)), mouseWheelEvent->z, mouseWheelEvent->timestamp); - mWheelEventSignal.Emit( wheelEvent ); + mWheelEventSignal.Emit(wheelEvent); } } -void WindowBaseEcoreX::OnKeyDown( void* data, int type, void* event ) +void WindowBaseEcoreX::OnKeyDown(void* data, int type, void* event) { - Ecore_Event_Key* keyEvent = static_cast< Ecore_Event_Key* >( event ); + Ecore_Event_Key* keyEvent = static_cast(event); - if( keyEvent->window == mEcoreWindow ) + if(keyEvent->window == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreX::OnKeyDown\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseEcoreX::OnKeyDown\n"); - std::string keyName( keyEvent->keyname ); - std::string logicalKey( "" ); - std::string keyString( "" ); - std::string compose( "" ); + std::string keyName(keyEvent->keyname); + std::string logicalKey(""); + std::string keyString(""); + std::string compose(""); // Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string. - if( keyEvent->compose ) + if(keyEvent->compose) { compose = keyEvent->compose; } // Ensure key symbol is not NULL as keys like SHIFT have a null string. - if( keyEvent->key ) + if(keyEvent->key) { logicalKey = keyEvent->key; } - int keyCode = ecore_x_keysym_keycode_get( keyEvent->keyname ); - int modifier( keyEvent->modifiers ); + int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname); + int modifier(keyEvent->modifiers); unsigned long time = keyEvent->timestamp; // Ensure key event string is not NULL as keys like SHIFT have a null string. - if( keyEvent->string ) + if(keyEvent->string) { keyString = keyEvent->string; } - Integration::KeyEvent keyEvent( keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS ); + Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, compose, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseEcoreX::OnKeyUp( void* data, int type, void* event ) +void WindowBaseEcoreX::OnKeyUp(void* data, int type, void* event) { - Ecore_Event_Key* keyEvent = static_cast< Ecore_Event_Key* >( event ); + Ecore_Event_Key* keyEvent = static_cast(event); - if ( keyEvent->window == mEcoreWindow ) + if(keyEvent->window == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, " WindowBaseEcoreX::OnKeyUp\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, " WindowBaseEcoreX::OnKeyUp\n"); - std::string keyName( keyEvent->keyname ); - std::string logicalKey( "" ); - std::string keyString( "" ); - std::string compose( "" ); + std::string keyName(keyEvent->keyname); + std::string logicalKey(""); + std::string keyString(""); + std::string compose(""); // Ensure key compose string is not NULL as keys like SHIFT or arrow have a null string. - if( keyEvent->compose ) + if(keyEvent->compose) { compose = keyEvent->compose; } // Ensure key symbol is not NULL as keys like SHIFT have a null string. - if( keyEvent->key ) + if(keyEvent->key) { logicalKey = keyEvent->key; } - int keyCode = ecore_x_keysym_keycode_get( keyEvent->keyname ); - int modifier( keyEvent->modifiers ); - unsigned long time( keyEvent->timestamp ); + int keyCode = ecore_x_keysym_keycode_get(keyEvent->keyname); + int modifier(keyEvent->modifiers); + unsigned long time(keyEvent->timestamp); // Ensure key event string is not NULL as keys like SHIFT have a null string. - if( keyEvent->string ) + if(keyEvent->string) { keyString = keyEvent->string; } - Integration::KeyEvent keyEvent( keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS ); + Integration::KeyEvent keyEvent(keyName, logicalKey, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, compose, DEFAULT_DEVICE_NAME, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseEcoreX::OnSelectionClear( void* data, int type, void* event ) +void WindowBaseEcoreX::OnSelectionClear(void* data, int type, void* event) { - Ecore_X_Event_Selection_Clear* selectionClearEvent = static_cast< Ecore_X_Event_Selection_Clear* >( event ); + Ecore_X_Event_Selection_Clear* selectionClearEvent = static_cast(event); - if( selectionClearEvent->win == mEcoreWindow ) + if(selectionClearEvent->win == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, " WindowBaseEcoreX::OnSelectionClear\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, " WindowBaseEcoreX::OnSelectionClear\n"); - if( selectionClearEvent->selection == ECORE_X_SELECTION_SECONDARY ) + if(selectionClearEvent->selection == ECORE_X_SELECTION_SECONDARY) { // Request to get the content from Ecore. - ecore_x_selection_secondary_request( selectionClearEvent->win, ECORE_X_SELECTION_TARGET_TEXT ); + ecore_x_selection_secondary_request(selectionClearEvent->win, ECORE_X_SELECTION_TARGET_TEXT); } } } -void WindowBaseEcoreX::OnSelectionNotify( void* data, int type, void* event ) +void WindowBaseEcoreX::OnSelectionNotify(void* data, int type, void* event) { - Ecore_X_Event_Selection_Notify* selectionNotifyEvent = static_cast< Ecore_X_Event_Selection_Notify* >( event ); + Ecore_X_Event_Selection_Notify* selectionNotifyEvent = static_cast(event); - if( selectionNotifyEvent->win == mEcoreWindow ) + if(selectionNotifyEvent->win == mEcoreWindow) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::Concise, " WindowBaseEcoreX::OnSelectionNotify\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::Concise, " WindowBaseEcoreX::OnSelectionNotify\n"); - Ecore_X_Selection_Data* selectionData = static_cast< Ecore_X_Selection_Data* >( selectionNotifyEvent->data ); - if( selectionData->data ) + Ecore_X_Selection_Data* selectionData = static_cast(selectionNotifyEvent->data); + if(selectionData->data) { - if( selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY ) + if(selectionNotifyEvent->selection == ECORE_X_SELECTION_SECONDARY) { - mSelectionDataReceivedSignal.Emit( event ); + mSelectionDataReceivedSignal.Emit(event); } } } @@ -638,30 +634,30 @@ int WindowBaseEcoreX::GetNativeWindowId() return mEcoreWindow; } -EGLNativeWindowType WindowBaseEcoreX::CreateEglWindow( int width, int height ) +EGLNativeWindowType WindowBaseEcoreX::CreateEglWindow(int width, int height) { // need to create X handle as in 64bit system ECore handle is 32 bit whereas EGLnative and XWindow are 64 bit - XWindow window( mEcoreWindow ); - return reinterpret_cast< EGLNativeWindowType >( window ); + XWindow window(mEcoreWindow); + return reinterpret_cast(window); } void WindowBaseEcoreX::DestroyEglWindow() { } -void WindowBaseEcoreX::SetEglWindowRotation( int angle ) +void WindowBaseEcoreX::SetEglWindowRotation(int angle) { } -void WindowBaseEcoreX::SetEglWindowBufferTransform( int angle ) +void WindowBaseEcoreX::SetEglWindowBufferTransform(int angle) { } -void WindowBaseEcoreX::SetEglWindowTransform( int angle ) +void WindowBaseEcoreX::SetEglWindowTransform(int angle) { } -void WindowBaseEcoreX::ResizeEglWindow( PositionSize positionSize ) +void WindowBaseEcoreX::ResizeEglWindow(PositionSize positionSize) { } @@ -670,63 +666,63 @@ bool WindowBaseEcoreX::IsEglWindowRotationSupported() return false; } -void WindowBaseEcoreX::Move( PositionSize positionSize ) +void WindowBaseEcoreX::Move(PositionSize positionSize) { - ecore_x_window_move( mEcoreWindow, positionSize.x, positionSize.y ); + ecore_x_window_move(mEcoreWindow, positionSize.x, positionSize.y); } -void WindowBaseEcoreX::Resize( PositionSize positionSize ) +void WindowBaseEcoreX::Resize(PositionSize positionSize) { - ecore_x_window_resize( mEcoreWindow, positionSize.width, positionSize.height ); + ecore_x_window_resize(mEcoreWindow, positionSize.width, positionSize.height); } -void WindowBaseEcoreX::MoveResize( PositionSize positionSize ) +void WindowBaseEcoreX::MoveResize(PositionSize positionSize) { - ecore_x_window_move_resize( mEcoreWindow, positionSize.x, positionSize.y, positionSize.width, positionSize.height ); + ecore_x_window_move_resize(mEcoreWindow, positionSize.x, positionSize.y, positionSize.width, positionSize.height); } -void WindowBaseEcoreX::SetClass( const std::string& name, const std::string& className ) +void WindowBaseEcoreX::SetClass(const std::string& name, const std::string& className) { - ecore_x_icccm_title_set( mEcoreWindow, name.c_str() ); - ecore_x_netwm_name_set( mEcoreWindow, name.c_str() ); - ecore_x_icccm_name_class_set( mEcoreWindow, name.c_str(), className.c_str() ); + ecore_x_icccm_title_set(mEcoreWindow, name.c_str()); + ecore_x_netwm_name_set(mEcoreWindow, name.c_str()); + ecore_x_icccm_name_class_set(mEcoreWindow, name.c_str(), className.c_str()); } void WindowBaseEcoreX::Raise() { - ecore_x_window_raise( mEcoreWindow ); + ecore_x_window_raise(mEcoreWindow); } void WindowBaseEcoreX::Lower() { - ecore_x_window_lower( mEcoreWindow ); + ecore_x_window_lower(mEcoreWindow); } void WindowBaseEcoreX::Activate() { - ecore_x_netwm_client_active_request( ecore_x_window_root_get( mEcoreWindow ), mEcoreWindow, 1 /* request type, 1:application, 2:pager */, 0 ); + ecore_x_netwm_client_active_request(ecore_x_window_root_get(mEcoreWindow), mEcoreWindow, 1 /* request type, 1:application, 2:pager */, 0); } -void WindowBaseEcoreX::SetAvailableAnlges( const std::vector< int >& angles ) +void WindowBaseEcoreX::SetAvailableAnlges(const std::vector& angles) { } -void WindowBaseEcoreX::SetPreferredAngle( int angle ) +void WindowBaseEcoreX::SetPreferredAngle(int angle) { } -void WindowBaseEcoreX::SetAcceptFocus( bool accept ) +void WindowBaseEcoreX::SetAcceptFocus(bool accept) { } void WindowBaseEcoreX::Show() { - ecore_x_window_show( mEcoreWindow ); + ecore_x_window_show(mEcoreWindow); } void WindowBaseEcoreX::Hide() { - ecore_x_window_hide( mEcoreWindow ); + ecore_x_window_hide(mEcoreWindow); } unsigned int WindowBaseEcoreX::GetSupportedAuxiliaryHintCount() const @@ -734,55 +730,55 @@ unsigned int WindowBaseEcoreX::GetSupportedAuxiliaryHintCount() const return 0; } -std::string WindowBaseEcoreX::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string WindowBaseEcoreX::GetSupportedAuxiliaryHint(unsigned int index) const { return std::string(); } -unsigned int WindowBaseEcoreX::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int WindowBaseEcoreX::AddAuxiliaryHint(const std::string& hint, const std::string& value) { return 0; } -bool WindowBaseEcoreX::RemoveAuxiliaryHint( unsigned int id ) +bool WindowBaseEcoreX::RemoveAuxiliaryHint(unsigned int id) { return false; } -bool WindowBaseEcoreX::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool WindowBaseEcoreX::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { return false; } -std::string WindowBaseEcoreX::GetAuxiliaryHintValue( unsigned int id ) const +std::string WindowBaseEcoreX::GetAuxiliaryHintValue(unsigned int id) const { return std::string(); } -unsigned int WindowBaseEcoreX::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int WindowBaseEcoreX::GetAuxiliaryHintId(const std::string& hint) const { return 0; } -void WindowBaseEcoreX::SetInputRegion( const Rect< int >& inputRegion ) +void WindowBaseEcoreX::SetInputRegion(const Rect& inputRegion) { } -void WindowBaseEcoreX::SetType( Dali::WindowType type ) +void WindowBaseEcoreX::SetType(Dali::WindowType type) { } -bool WindowBaseEcoreX::SetNotificationLevel( Dali::WindowNotificationLevel level ) +bool WindowBaseEcoreX::SetNotificationLevel(Dali::WindowNotificationLevel level) { return false; } -Dali::WindowNotificationLevel WindowBaseEcoreX::GetNotificationLevel() const +Dali::WindowNotificationLevel WindowBaseEcoreX::GetNotificationLevel() const { return Dali::WindowNotificationLevel::NONE; } -void WindowBaseEcoreX::SetOpaqueState( bool opaque ) +void WindowBaseEcoreX::SetOpaqueState(bool opaque) { } @@ -796,7 +792,7 @@ WindowScreenOffMode WindowBaseEcoreX::GetScreenOffMode() const return WindowScreenOffMode::TIMEOUT; } -bool WindowBaseEcoreX::SetBrightness( int brightness ) +bool WindowBaseEcoreX::SetBrightness(int brightness) { return false; } @@ -806,27 +802,27 @@ int WindowBaseEcoreX::GetBrightness() const return 0; } -bool WindowBaseEcoreX::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) +bool WindowBaseEcoreX::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) { return false; } -bool WindowBaseEcoreX::UngrabKey( Dali::KEY key ) +bool WindowBaseEcoreX::UngrabKey(Dali::KEY key) { return false; } -bool WindowBaseEcoreX::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) +bool WindowBaseEcoreX::GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) { return false; } -bool WindowBaseEcoreX::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) +bool WindowBaseEcoreX::UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) { return false; } -void WindowBaseEcoreX::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void WindowBaseEcoreX::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // 1 inch = 25.4 millimeters // ecore does not account for differing DPI in the x and y axes, so only get for x is available @@ -845,74 +841,73 @@ int WindowBaseEcoreX::GetScreenRotationAngle() return 0; } -void WindowBaseEcoreX::SetWindowRotationAngle( int degree ) +void WindowBaseEcoreX::SetWindowRotationAngle(int degree) { mWindowRotationAngle = degree; } -void WindowBaseEcoreX::WindowRotationCompleted( int degree, int width, int height ) +void WindowBaseEcoreX::WindowRotationCompleted(int degree, int width, int height) { } -void WindowBaseEcoreX::SetTransparency( bool transparent ) +void WindowBaseEcoreX::SetTransparency(bool transparent) { } -unsigned int WindowBaseEcoreX::GetSurfaceId( Any surface ) const +unsigned int WindowBaseEcoreX::GetSurfaceId(Any surface) const { unsigned int surfaceId = 0; - if ( surface.Empty() == false ) + if(surface.Empty() == false) { // check we have a valid type - DALI_ASSERT_ALWAYS( ( (surface.GetType() == typeid (XWindow) ) || (surface.GetType() == typeid (Ecore_X_Window) ) ) - && "Surface type is invalid" ); + DALI_ASSERT_ALWAYS(((surface.GetType() == typeid(XWindow)) || (surface.GetType() == typeid(Ecore_X_Window))) && "Surface type is invalid"); - if ( surface.GetType() == typeid (Ecore_X_Window) ) + if(surface.GetType() == typeid(Ecore_X_Window)) { - surfaceId = AnyCast< Ecore_X_Window >( surface ); + surfaceId = AnyCast(surface); } else { - surfaceId = static_cast( AnyCast< XWindow >( surface ) ); + surfaceId = static_cast(AnyCast(surface)); } } return surfaceId; } -void WindowBaseEcoreX::CreateWindow( PositionSize positionSize, bool isTransparent ) +void WindowBaseEcoreX::CreateWindow(PositionSize positionSize, bool isTransparent) { - if( isTransparent ) - { - // create 32 bit window - mEcoreWindow = ecore_x_window_argb_new( 0, positionSize.x, positionSize.y, positionSize.width, positionSize.height ); - mIsTransparent = true; - } - else - { - // create 24 bit window - mEcoreWindow = ecore_x_window_new( 0, positionSize.x, positionSize.y, positionSize.width, positionSize.height ); - } + if(isTransparent) + { + // create 32 bit window + mEcoreWindow = ecore_x_window_argb_new(0, positionSize.x, positionSize.y, positionSize.width, positionSize.height); + mIsTransparent = true; + } + else + { + // create 24 bit window + mEcoreWindow = ecore_x_window_new(0, positionSize.x, positionSize.y, positionSize.width, positionSize.height); + } - if ( mEcoreWindow == 0 ) - { - DALI_ASSERT_ALWAYS( 0 && "Failed to create X window" ); - } + if(mEcoreWindow == 0) + { + DALI_ASSERT_ALWAYS(0 && "Failed to create X window"); + } } -void WindowBaseEcoreX::SetParent( WindowBase* parentWinBase ) +void WindowBaseEcoreX::SetParent(WindowBase* parentWinBase) { Ecore_X_Window ecoreParent = 0; - if( parentWinBase ) + if(parentWinBase) { - WindowBaseEcoreX* winBaseEcoreX = static_cast( parentWinBase ); - ecoreParent = winBaseEcoreX->mEcoreWindow; - ecore_x_icccm_transient_for_set( mEcoreWindow, ecoreParent ); + WindowBaseEcoreX* winBaseEcoreX = static_cast(parentWinBase); + ecoreParent = winBaseEcoreX->mEcoreWindow; + ecore_x_icccm_transient_for_set(mEcoreWindow, ecoreParent); } else { ecoreParent = 0; - ecore_x_icccm_transient_for_unset( mEcoreWindow ); + ecore_x_icccm_transient_for_unset(mEcoreWindow); } } diff --git a/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.h b/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.h index 44375dc..24081d6 100644 --- a/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.h +++ b/dali/internal/window-system/ubuntu-x11/window-base-ecore-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_WINDOW_BASE_ECORE_X_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ #include // EXTERNAL HEADERS -#include #include +#include namespace Dali { @@ -31,18 +31,16 @@ namespace Internal { namespace Adaptor { - /** * WindowBaseEcoreX class provides an WindowBase EcoreX implementation. */ class WindowBaseEcoreX : public WindowBase { public: - /** * @brief Constructor */ - WindowBaseEcoreX( PositionSize positionSize, Any surface, bool isTransparent ); + WindowBaseEcoreX(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Destructor @@ -50,11 +48,10 @@ public: virtual ~WindowBaseEcoreX(); public: - /** * @brief Called when the window property is changed. */ - Eina_Bool OnWindowPropertyChanged( void* data, int type, void* event ); + Eina_Bool OnWindowPropertyChanged(void* data, int type, void* event); /** * @brief Called when the window receives a delete request @@ -64,60 +61,59 @@ public: /** * @brief Called when the window gains focus. */ - void OnFocusIn( void* data, int type, void* event ); + void OnFocusIn(void* data, int type, void* event); /** * @brief Called when the window loses focus. */ - void OnFocusOut( void* data, int type, void* event ); + void OnFocusOut(void* data, int type, void* event); /** * @brief Called when the window is damaged. */ - void OnWindowDamaged( void* data, int type, void* event ); + void OnWindowDamaged(void* data, int type, void* event); /** * @brief Called when a touch down is received. */ - void OnMouseButtonDown( void* data, int type, void* event ); + void OnMouseButtonDown(void* data, int type, void* event); /** * @brief Called when a touch up is received. */ - void OnMouseButtonUp( void* data, int type, void* event ); + void OnMouseButtonUp(void* data, int type, void* event); /** * @brief Called when a touch motion is received. */ - void OnMouseButtonMove( void* data, int type, void* event ); + void OnMouseButtonMove(void* data, int type, void* event); /** * @brief Called when a mouse wheel is received. */ - void OnMouseWheel( void* data, int type, void* event ); + void OnMouseWheel(void* data, int type, void* event); /** * @brief Called when a key down is received. */ - void OnKeyDown( void* data, int type, void* event ); + void OnKeyDown(void* data, int type, void* event); /** * @brief Called when a key up is received. */ - void OnKeyUp( void* data, int type, void* event ); + void OnKeyUp(void* data, int type, void* event); /** * @brief Called when the source window notifies us the content in clipboard is selected. */ - void OnSelectionClear( void* data, int type, void* event ); + void OnSelectionClear(void* data, int type, void* event); /** * @brief Called when the source window sends us about the selected content. */ - void OnSelectionNotify( void* data, int type, void* event ); + void OnSelectionNotify(void* data, int type, void* event); public: - /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNativeWindow() */ @@ -131,7 +127,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateEglWindow() */ - EGLNativeWindowType CreateEglWindow( int width, int height ) override; + EGLNativeWindowType CreateEglWindow(int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::DestroyEglWindow() @@ -141,22 +137,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowRotation() */ - void SetEglWindowRotation( int angle ) override; + void SetEglWindowRotation(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowBufferTransform() */ - void SetEglWindowBufferTransform( int angle ) override; + void SetEglWindowBufferTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowTransform() */ - void SetEglWindowTransform( int angle ) override; + void SetEglWindowTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::ResizeEglWindow() */ - void ResizeEglWindow( PositionSize positionSize ) override; + void ResizeEglWindow(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::IsEglWindowRotationSupported() @@ -166,22 +162,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::Move() */ - void Move( PositionSize positionSize ) override; + void Move(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Resize() */ - void Resize( PositionSize positionSize ) override; + void Resize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::MoveResize() */ - void MoveResize( PositionSize positionSize ) override; + void MoveResize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetClass() */ - void SetClass( const std::string& name, const std::string& className ) override; + void SetClass(const std::string& name, const std::string& className) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Raise() @@ -201,17 +197,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAvailableAnlges() */ - void SetAvailableAnlges( const std::vector< int >& angles ) override; + void SetAvailableAnlges(const std::vector& angles) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetPreferredAngle() */ - void SetPreferredAngle( int angle ) override; + void SetPreferredAngle(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ) override; + void SetAcceptFocus(bool accept) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Show() @@ -231,47 +227,47 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const override; + std::string GetSupportedAuxiliaryHint(unsigned int index) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) override; + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ) override; + bool RemoveAuxiliaryHint(unsigned int id) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) override; + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const override; + std::string GetAuxiliaryHintValue(unsigned int id) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const override; + unsigned int GetAuxiliaryHintId(const std::string& hint) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ) override; + void SetInputRegion(const Rect& inputRegion) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetType() */ - void SetType( Dali::WindowType type ) override; + void SetType(Dali::WindowType type) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetNotificationLevel() */ - bool SetNotificationLevel( Dali::WindowNotificationLevel level ) override; + bool SetNotificationLevel(Dali::WindowNotificationLevel level) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNotificationLevel() @@ -281,7 +277,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetOpaqueState() */ - void SetOpaqueState( bool opaque ) override; + void SetOpaqueState(bool opaque) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetScreenOffMode() @@ -296,7 +292,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetBrightness() */ - bool SetBrightness( int brightness ) override; + bool SetBrightness(int brightness) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetBrightness() @@ -306,27 +302,27 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) override; + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKey() */ - bool UngrabKey( Dali::KEY key ) override; + bool UngrabKey(Dali::KEY key) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKeyList() */ - bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) override; + bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKeyList() */ - bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) override; + bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetOrientation() @@ -341,22 +337,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetWindowRotationAngle() */ - void SetWindowRotationAngle( int degree ) override; + void SetWindowRotationAngle(int degree) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::WindowRotationCompleted() */ - void WindowRotationCompleted( int degree, int width, int height ) override; + void WindowRotationCompleted(int degree, int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetTransparency() */ - void SetTransparency( bool transparent ) override; + void SetTransparency(bool transparent) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetParent() */ - void SetParent( WindowBase* parentWinBase ) override; + void SetParent(WindowBase* parentWinBase) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateFrameRenderedSyncFence() @@ -369,26 +365,24 @@ public: int CreateFramePresentedSyncFence() override; private: - /** * Second stage initialization */ - void Initialize( PositionSize positionSize, Any surface, bool isTransparent ); + void Initialize(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Get the surface id if the surface parameter is not empty * @param surface Any containing a surface id, or can be empty * @return surface id, or zero if surface is empty */ - unsigned int GetSurfaceId( Any surface ) const; + unsigned int GetSurfaceId(Any surface) const; /** * @brief Create window */ - void CreateWindow( PositionSize positionSize, bool isTransparent ); + void CreateWindow(PositionSize positionSize, bool isTransparent); protected: - // Undefined WindowBaseEcoreX(const WindowBaseEcoreX&) = delete; @@ -396,18 +390,17 @@ protected: WindowBaseEcoreX& operator=(const WindowBaseEcoreX& rhs) = delete; private: - - Dali::Vector< Ecore_Event_Handler* > mEcoreEventHandler; - Ecore_X_Window mEcoreWindow; ///< Native window handle - bool mOwnSurface:1; ///< Whether we own the surface (responsible for deleting it) - bool mIsTransparent; ///< Whether the window is transparent (32 bit or 24 bit) - bool mRotationAppSet:1; - int mWindowRotationAngle; + Dali::Vector mEcoreEventHandler; + Ecore_X_Window mEcoreWindow; ///< Native window handle + bool mOwnSurface : 1; ///< Whether we own the surface (responsible for deleting it) + bool mIsTransparent; ///< Whether the window is transparent (32 bit or 24 bit) + bool mRotationAppSet : 1; + int mWindowRotationAngle; }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.cpp b/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.cpp index 83e0f11..b3376c4 100644 --- a/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali { @@ -28,17 +28,16 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowBase > WindowFactoryEcoreX::CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr WindowFactoryEcoreX::CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowBaseEcoreX >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } // this should be created from Window impl -std::unique_ptr< WindowFactory > GetWindowFactory() +std::unique_ptr GetWindowFactory() { // returns Window factory - return Utils::MakeUnique< WindowFactoryEcoreX >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.h b/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.h index 55cd0f8..6958b41 100644 --- a/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.h +++ b/dali/internal/window-system/ubuntu-x11/window-factory-ecore-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_ECOREX_WINDOW_FACTORY_ECORE_X_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,10 @@ namespace Internal { namespace Adaptor { - class WindowFactoryEcoreX : public WindowFactory { public: - std::unique_ptr< WindowBase > CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) override; + std::unique_ptr CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.cpp b/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.cpp index 1b22155..bcb21d1 100644 --- a/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,16 +30,12 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace ECore { - namespace WindowInterface { // CONSTANTS @@ -47,131 +43,128 @@ const char* const CBHM_WINDOW = "CBHM_XWIN"; Ecore_X_Window GetWindow() { - Ecore_X_Atom xAtomCbhm = ecore_x_atom_get( CBHM_WINDOW ); + Ecore_X_Atom xAtomCbhm = ecore_x_atom_get(CBHM_WINDOW); Ecore_X_Window xCbhmWin = 0; - unsigned char *buf = NULL; - int num = 0; + unsigned char* buf = NULL; + int num = 0; // XA_WINDOW is a macro with C cast #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wold-style-cast" - int ret = ecore_x_window_prop_property_get( 0, xAtomCbhm, XA_WINDOW, 0, &buf, &num ); + int ret = ecore_x_window_prop_property_get(0, xAtomCbhm, XA_WINDOW, 0, &buf, &num); #pragma GCC diagnostic pop - if ( ret && num ) + if(ret && num) { - memcpy( &xCbhmWin, buf, sizeof( Ecore_X_Window ) ); + memcpy(&xCbhmWin, buf, sizeof(Ecore_X_Window)); } - if ( buf ) + if(buf) { - free( buf ); + free(buf); } return xCbhmWin; } -std::string GetWindowProperty( Ecore_X_Atom property, Ecore_X_Atom *xDataType, unsigned int num ) +std::string GetWindowProperty(Ecore_X_Atom property, Ecore_X_Atom* xDataType, unsigned int num) { - std::string data(""); - - if ( !property ) - { - return data; - } - - ecore_x_sync(); - - long unsigned int numRet = 0, bytes = 0; - int ret = 0, sizeRet; - unsigned int i; - unsigned char *propRet; - Ecore_X_Atom typeRet; - - // X11 Function to get window property - ret = XGetWindowProperty( static_cast(ecore_x_display_get()), // Display* X Server Connection - GetWindow(), // Window window in question - property, // Atom name of property - num, // long offset where required data is stored - LONG_MAX, // long length of data to retrieve - False, // Bool flag to delete data - ecore_x_window_prop_any_type(), // Atom atom id associated to property type - reinterpret_cast< Atom * >( &typeRet ), // Atom actual_type_return, atom id property type - &sizeRet, // int* format of property - &numRet, // unsigned long* number of items being returned in prop_return - &bytes, // unsigned long* remaining bytes if partial retrieval - &propRet ); // unsigned char** return data - if ( ret != Success ) - { - return data; - } - - if ( !numRet ) - { - XFree( propRet ); - return data; - } - - numRet--; // As propRet in XGetWindowProperty gets an extra 0 added for compatibility reasons. - - switch ( sizeRet ) // Format returned by XGetWindowProperty int, short, long - { - case 8: - { - for ( i = 0; i < numRet; i++ ) - { - data += propRet[i]; - } - } - break; - - case 16: - { - for ( i = 0; i < numRet; i++ ) - { - data += ( propRet )[i]; - } - } - break; - - case 32: - { - for ( i = 0; i < numRet; i++ ) - { - data += ( propRet )[i]; - } - } - break; - } - - XFree( propRet ); - - if ( xDataType ) - { - *xDataType = typeRet; - } - - return data; + std::string data(""); + + if(!property) + { + return data; + } + + ecore_x_sync(); + + long unsigned int numRet = 0, bytes = 0; + int ret = 0, sizeRet; + unsigned int i; + unsigned char* propRet; + Ecore_X_Atom typeRet; + + // X11 Function to get window property + ret = XGetWindowProperty(static_cast(ecore_x_display_get()), // Display* X Server Connection + GetWindow(), // Window window in question + property, // Atom name of property + num, // long offset where required data is stored + LONG_MAX, // long length of data to retrieve + False, // Bool flag to delete data + ecore_x_window_prop_any_type(), // Atom atom id associated to property type + reinterpret_cast(&typeRet), // Atom actual_type_return, atom id property type + &sizeRet, // int* format of property + &numRet, // unsigned long* number of items being returned in prop_return + &bytes, // unsigned long* remaining bytes if partial retrieval + &propRet); // unsigned char** return data + if(ret != Success) + { + return data; + } + + if(!numRet) + { + XFree(propRet); + return data; } -void SendXEvent(Ecore_X_Display* display, Ecore_X_Window window, bool propagate, - long int eventMask, Ecore_X_Atom messageType, int messageFormat, const char *msg ) + numRet--; // As propRet in XGetWindowProperty gets an extra 0 added for compatibility reasons. + + switch(sizeRet) // Format returned by XGetWindowProperty int, short, long + { + case 8: + { + for(i = 0; i < numRet; i++) + { + data += propRet[i]; + } + } + break; + + case 16: + { + for(i = 0; i < numRet; i++) + { + data += (propRet)[i]; + } + } + break; + + case 32: + { + for(i = 0; i < numRet; i++) + { + data += (propRet)[i]; + } + } + break; + } + + XFree(propRet); + + if(xDataType) + { + *xDataType = typeRet; + } + + return data; +} + +void SendXEvent(Ecore_X_Display* display, Ecore_X_Window window, bool propagate, long int eventMask, Ecore_X_Atom messageType, int messageFormat, const char* msg) { XClientMessageEvent message; - memset(&message, 0, sizeof( message ) ); - message.type = ClientMessage; - message.display = static_cast( display ); + memset(&message, 0, sizeof(message)); + message.type = ClientMessage; + message.display = static_cast(display); message.message_type = messageType; - message.format = messageFormat; - message.window = window; + message.format = messageFormat; + message.window = window; snprintf(message.data.b, 20, "%s", msg); - XSendEvent( static_cast( display ), window, propagate, eventMask, reinterpret_cast< XEvent* >( &message ) ); + XSendEvent(static_cast(display), window, propagate, eventMask, reinterpret_cast(&message)); } - } // namespace WindowInterface - } // namespace ECore } // namespace Adaptor diff --git a/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.h b/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.h index b9e0b3b..e16a595 100644 --- a/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.h +++ b/dali/internal/window-system/ubuntu-x11/window-interface-ecore-x.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_ECORE_X_RENDER_SURFACE_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,23 +21,19 @@ // EXTERNAL INCLUDES #include -#include #include +#include // INTERNAL INCLUDES namespace Dali { - namespace Internal { - namespace Adaptor { - namespace ECore { - namespace WindowInterface { /** @@ -48,18 +44,18 @@ namespace WindowInterface * Gets the Ecore X Window * @return window */ - Ecore_X_Window GetWindow(); +Ecore_X_Window GetWindow(); - /** +/** * Gets a specified X window property * @param[in] property the required property id * @param[in] xDataType the type * @param[in] num the offset / index of the property * @return string the property value */ - std::string GetWindowProperty( Ecore_X_Atom property, Ecore_X_Atom *xDataType, unsigned int num ); +std::string GetWindowProperty(Ecore_X_Atom property, Ecore_X_Atom* xDataType, unsigned int num); - /** +/** * Send an X Event * @param[in] display target display * @param[in] window target window @@ -69,17 +65,15 @@ namespace WindowInterface * @param[in] messageFormat format of message * @param[in] msg message to send */ - void SendXEvent(Ecore_X_Display* display, Ecore_X_Window window, bool propagate, - long int eventMask, Ecore_X_Atom messageType, int messageFormat, const char *msg ); +void SendXEvent(Ecore_X_Display* display, Ecore_X_Window window, bool propagate, long int eventMask, Ecore_X_Atom messageType, int messageFormat, const char* msg); } // namespace WindowInterface - } // namespace ECore } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/ubuntu-x11/window-system-ecore-x.cpp b/dali/internal/window-system/ubuntu-x11/window-system-ecore-x.cpp index 20b141c..aa91438 100644 --- a/dali/internal/window-system/ubuntu-x11/window-system-ecore-x.cpp +++ b/dali/internal/window-system/ubuntu-x11/window-system-ecore-x.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,27 +16,23 @@ */ // INTERNAL HEADERS -#include #include +#include // EXTERNAL_HEADERS #include namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowSystem { - void Initialize() { - ecore_x_init( NULL ); + ecore_x_init(NULL); } void Shutdown() @@ -44,17 +40,17 @@ void Shutdown() ecore_x_shutdown(); } -void GetScreenSize( int& width, int& height ) +void GetScreenSize(int& width, int& height) { - ecore_x_screen_size_get( ecore_x_default_screen_get(), &width, &height ); + ecore_x_screen_size_get(ecore_x_default_screen_get(), &width, &height); } -bool SetKeyboardRepeatInfo( float rate, float delay ) +bool SetKeyboardRepeatInfo(float rate, float delay) { return false; } -bool GetKeyboardRepeatInfo( float& rate, float& delay ) +bool GetKeyboardRepeatInfo(float& rate, float& delay) { return false; } diff --git a/dali/internal/window-system/windows/display-connection-factory-win.cpp b/dali/internal/window-system/windows/display-connection-factory-win.cpp old mode 100755 new mode 100644 index 8a93649..9b42b72 --- a/dali/internal/window-system/windows/display-connection-factory-win.cpp +++ b/dali/internal/window-system/windows/display-connection-factory-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,9 +25,6 @@ namespace Internal { namespace Adaptor { - - - std::unique_ptr DisplayConnectionFactoryWin::CreateDisplayConnection() { return Utils::MakeUnique(); @@ -40,6 +37,6 @@ std::unique_ptr GetDisplayConnectionFactory() return Utils::MakeUnique(); } -} -} -} \ No newline at end of file +} // namespace Adaptor +} // namespace Internal +} // namespace Dali \ No newline at end of file diff --git a/dali/internal/window-system/windows/display-connection-factory-win.h b/dali/internal/window-system/windows/display-connection-factory-win.h old mode 100755 new mode 100644 index 72b73ab..5637077 --- a/dali/internal/window-system/windows/display-connection-factory-win.h +++ b/dali/internal/window-system/windows/display-connection-factory-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_WIN_DISPLAY_CONNECTION_FACTORY_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - class DisplayConnectionFactoryWin : public DisplayConnectionFactory { public: @@ -42,5 +39,4 @@ public: } // namespace Dali - #endif // DALI_INTERNAL_WINDOWSYSTEM_WIN_DISPLAY_CONNECTION_FACTORY_WIN_H diff --git a/dali/internal/window-system/windows/display-connection-impl-win.cpp b/dali/internal/window-system/windows/display-connection-impl-win.cpp old mode 100755 new mode 100644 index 59babb4..4fd5d55 --- a/dali/internal/window-system/windows/display-connection-impl-win.cpp +++ b/dali/internal/window-system/windows/display-connection-impl-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,7 @@ * */ - // CLASS HEADER +// CLASS HEADER #include // EXTERNAL INCLUDES @@ -26,13 +26,10 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - DisplayConnection* DisplayConnectionWin::New() { DisplayConnection* pDisplayConnection(new DisplayConnectionWin()); @@ -60,11 +57,11 @@ void DisplayConnectionWin::ConsumeEvents() bool DisplayConnectionWin::InitializeEgl(EglInterface& egl) { - EglImplementation& eglImpl = static_cast( egl ); + EglImplementation& eglImpl = static_cast(egl); - if( !eglImpl.InitializeGles( reinterpret_cast( mDisplay ) ) ) + if(!eglImpl.InitializeGles(reinterpret_cast(mDisplay))) { - DALI_LOG_ERROR( "Failed to initialize GLES.\n" ); + DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; } @@ -73,27 +70,27 @@ bool DisplayConnectionWin::InitializeEgl(EglInterface& egl) bool DisplayConnectionWin::InitializeGraphics() { - auto eglGraphics = static_cast( mGraphics ); - EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); + auto eglGraphics = static_cast(mGraphics); + EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); - if( !eglImpl.InitializeGles( reinterpret_cast( mDisplay ) ) ) + if(!eglImpl.InitializeGles(reinterpret_cast(mDisplay))) { - DALI_LOG_ERROR( "Failed to initialize GLES.\n" ); + DALI_LOG_ERROR("Failed to initialize GLES.\n"); return false; } return true; } -void DisplayConnectionWin::SetSurfaceType( Dali::RenderSurfaceInterface::Type type ) +void DisplayConnectionWin::SetSurfaceType(Dali::RenderSurfaceInterface::Type type) { - if( type == Dali::RenderSurfaceInterface::WINDOW_RENDER_SURFACE ) + if(type == Dali::RenderSurfaceInterface::WINDOW_RENDER_SURFACE) { - mDisplay = GetDC( GetForegroundWindow() ); + mDisplay = GetDC(GetForegroundWindow()); } } -void DisplayConnectionWin::SetGraphicsInterface( GraphicsInterface& graphics ) +void DisplayConnectionWin::SetGraphicsInterface(GraphicsInterface& graphics) { mGraphics = &graphics; } diff --git a/dali/internal/window-system/windows/display-connection-impl-win.h b/dali/internal/window-system/windows/display-connection-impl-win.h old mode 100755 new mode 100644 index 636419e..f20e85e --- a/dali/internal/window-system/windows/display-connection-impl-win.h +++ b/dali/internal/window-system/windows/display-connection-impl-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WIN_DIPLAY_CONNECTION_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,29 +19,25 @@ */ // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { - class RenderSurface; class DisplayConnection; namespace Internal { - namespace Adaptor { - /** * DisplayConnection implementation */ class DisplayConnectionWin : public Dali::Internal::Adaptor::DisplayConnection { public: - /** * @brief Default constructor */ @@ -55,7 +51,6 @@ public: static DisplayConnection* New(); public: - /** * @copydoc Dali::DisplayConnection::GetDisplay */ @@ -79,22 +74,20 @@ public: /** * @copydoc Dali::Internal::Adaptor::DisplayConnection::SetSurfaceType */ - void SetSurfaceType( Dali::RenderSurfaceInterface::Type type ); + void SetSurfaceType(Dali::RenderSurfaceInterface::Type type); /** * @copydoc Dali::Internal::Adaptor::DisplayConnection::SetGraphicsInterface */ - void SetGraphicsInterface( GraphicsInterface& graphics ); + void SetGraphicsInterface(GraphicsInterface& graphics); public: - /** * Destructor */ virtual ~DisplayConnectionWin(); private: - // Undefined DisplayConnectionWin(const DisplayConnectionWin&) = delete; @@ -102,14 +95,13 @@ private: DisplayConnectionWin& operator=(const DisplayConnectionWin& rhs) = delete; private: - - GraphicsInterface *mGraphics; ///< The graphics interface - HDC mDisplay; + GraphicsInterface* mGraphics; ///< The graphics interface + HDC mDisplay; }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/windows/event-system-win.h b/dali/internal/window-system/windows/event-system-win.h old mode 100755 new mode 100644 index ddd7c6c..2986703 --- a/dali/internal/window-system/windows/event-system-win.h +++ b/dali/internal/window-system/windows/event-system-win.h @@ -2,7 +2,7 @@ #define _WINDOWEVENTSYSTEM_H_ /* -* Copyright (c) 2018 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,39 +17,36 @@ * limitations under the License. * */ -#define DEVICE_MOUSE 0 +#define DEVICE_MOUSE 0 // INTERNAL INCLUDES #include namespace Dali { - namespace Internal { - namespace Adaptor { - struct _Event_Mouse_Button { - WinWindowHandle window; /**< The main window where event happened */ + WinWindowHandle window; /**< The main window where event happened */ - uint32_t timestamp; /**< Time when the event occurred */ + uint32_t timestamp; /**< Time when the event occurred */ - int32_t x; /**< x coordinate relative to window where event happened */ - int32_t y; /**< y coordinate relative to window where event happened */ + int32_t x; /**< x coordinate relative to window where event happened */ + int32_t y; /**< y coordinate relative to window where event happened */ struct { - int32_t device; /**< 0 if normal mouse, 1+ for other mouse-devices (eg multi-touch - other fingers) */ - double radius, radius_x, radius_y; /**< radius of press point - radius_x and y if its an ellipse (radius is the average of the 2) */ - double pressure; /**< pressure - 1.0 == normal, > 1.0 == more, 0.0 == none */ - double angle; /**< angle relative to perpendicular (0.0 == perpendicular), in degrees */ - double x, y; /**< same as x, y, but with sub-pixel precision, if available */ + int32_t device; /**< 0 if normal mouse, 1+ for other mouse-devices (eg multi-touch - other fingers) */ + double radius, radius_x, radius_y; /**< radius of press point - radius_x and y if its an ellipse (radius is the average of the 2) */ + double pressure; /**< pressure - 1.0 == normal, > 1.0 == more, 0.0 == none */ + double angle; /**< angle relative to perpendicular (0.0 == perpendicular), in degrees */ + double x, y; /**< same as x, y, but with sub-pixel precision, if available */ struct { - double x, y; + double x, y; } root; /**< same as root.x, root.y, but with sub-pixel precision, if available */ } multi; }; @@ -60,22 +57,22 @@ struct _Event_Mouse_Button */ struct _Event_Mouse_Wheel { - WinWindowHandle window; /**< The main window where event happened */ - WinWindowHandle root_window; /**< The root window where event happened */ - WinWindowHandle event_window; /**< The child window where event happened */ + WinWindowHandle window; /**< The main window where event happened */ + WinWindowHandle root_window; /**< The root window where event happened */ + WinWindowHandle event_window; /**< The child window where event happened */ - uint32_t timestamp; /**< Time when the event occurred */ - uint32_t modifiers; /**< The combination of modifiers key (SHIFT,CTRL,ALT,..)*/ + uint32_t timestamp; /**< Time when the event occurred */ + uint32_t modifiers; /**< The combination of modifiers key (SHIFT,CTRL,ALT,..)*/ - int32_t direction; /**< Orientation of the wheel (horizontal/vertical) */ - int32_t z; /**< Value of the wheel event (+1/-1) */ + int32_t direction; /**< Orientation of the wheel (horizontal/vertical) */ + int32_t z; /**< Value of the wheel event (+1/-1) */ - int32_t x; /**< x coordinate relative to window where event happened */ - int32_t y; /**< y coordinate relative to window where event happened */ + int32_t x; /**< x coordinate relative to window where event happened */ + int32_t y; /**< y coordinate relative to window where event happened */ struct { - int32_t x; - int32_t y; + int32_t x; + int32_t y; } root; /**< Coordinates relative to root window */ }; @@ -84,24 +81,24 @@ typedef struct _Event_Mouse_Wheel Event_Mouse_Wheel; struct TWinEventInfo { - TWinEventInfo( uint64_t hWnd, uint32_t uMsg, uint64_t wParam, uint64_t lParam) + TWinEventInfo(uint64_t hWnd, uint32_t uMsg, uint64_t wParam, uint64_t lParam) { this->mWindow = (WinWindowHandle)hWnd; - this->uMsg = uMsg; - this->wParam = wParam; - this->lParam = lParam; + this->uMsg = uMsg; + this->wParam = wParam; + this->lParam = lParam; } WinWindowHandle mWindow; - uint32_t uMsg; - uint64_t wParam; - uint64_t lParam; + uint32_t uMsg; + uint64_t wParam; + uint64_t lParam; }; - -} // namespace Adaptor - -} // namespace internal - + +} // namespace Adaptor + +} // namespace Internal + } // namespace Dali #endif diff --git a/dali/internal/window-system/windows/platform-implement-win.cpp b/dali/internal/window-system/windows/platform-implement-win.cpp old mode 100755 new mode 100644 index 4a2a60b..658c64c --- a/dali/internal/window-system/windows/platform-implement-win.cpp +++ b/dali/internal/window-system/windows/platform-implement-win.cpp @@ -1,5 +1,5 @@ /* -* Copyright (c) 2018 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -32,53 +32,48 @@ constexpr float INCH = 25.4; namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowsPlatform { - -LRESULT CALLBACK WinProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) +LRESULT CALLBACK WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { - WindowImpl::ProcWinMessage( reinterpret_cast( hWnd ), uMsg, wParam, lParam ); + WindowImpl::ProcWinMessage(reinterpret_cast(hWnd), uMsg, wParam, lParam); - LRESULT ret = DefWindowProc( hWnd, uMsg, wParam, lParam ); + LRESULT ret = DefWindowProc(hWnd, uMsg, wParam, lParam); return ret; } namespace { - const std::string DALI_WINDOW_CLASS_NAME = "DaliWindow"; uint32_t sNumWindows = 0; void EnsureWindowClassRegistered() { - if (sNumWindows == 0) + if(sNumWindows == 0) { - WNDCLASS cs = { 0 }; - cs.cbClsExtra = 0; - cs.cbWndExtra = 0; + WNDCLASS cs = {0}; + cs.cbClsExtra = 0; + cs.cbWndExtra = 0; cs.hbrBackground = (HBRUSH)(COLOR_WINDOW + 2); - cs.hCursor = NULL; - cs.hIcon = NULL; - cs.hInstance = GetModuleHandle(NULL); - cs.lpfnWndProc = (WNDPROC)WinProc; + cs.hCursor = NULL; + cs.hIcon = NULL; + cs.hInstance = GetModuleHandle(NULL); + cs.lpfnWndProc = (WNDPROC)WinProc; cs.lpszClassName = DALI_WINDOW_CLASS_NAME.c_str(); - cs.lpszMenuName = NULL; - cs.style = CS_VREDRAW | CS_HREDRAW; + cs.lpszMenuName = NULL; + cs.style = CS_VREDRAW | CS_HREDRAW; RegisterClass(&cs); } } void EnsureWindowClassUnregistered() { - if (sNumWindows == 0) + if(sNumWindows == 0) { UnregisterClass(DALI_WINDOW_CLASS_NAME.c_str(), GetModuleHandle(NULL)); } @@ -89,24 +84,24 @@ std::map sHWndToListener; void RemoveListener(uint64_t hWnd) { std::map::iterator x = sHWndToListener.find(hWnd); - if (sHWndToListener.end() != x) + if(sHWndToListener.end() != x) { sHWndToListener.erase(x); } } -} +} // namespace -const uint32_t WindowImpl::STYLE = WS_OVERLAPPED; -const int32_t WindowImpl::EDGE_WIDTH = 8; -const int32_t WindowImpl::EDGE_HEIGHT = 18; +const uint32_t WindowImpl::STYLE = WS_OVERLAPPED; +const int32_t WindowImpl::EDGE_WIDTH = 8; +const int32_t WindowImpl::EDGE_HEIGHT = 18; WindowImpl::WindowImpl() { colorDepth = -1; - mHWnd = 0; - mHdc = 0; - listener = NULL; + mHWnd = 0; + mHdc = 0; + listener = NULL; } WindowImpl::~WindowImpl() @@ -114,62 +109,61 @@ WindowImpl::~WindowImpl() RemoveListener(mHWnd); } -void WindowImpl::ProcWinMessage( uint64_t hWnd, uint32_t uMsg, uint64_t wParam, uint64_t lParam ) +void WindowImpl::ProcWinMessage(uint64_t hWnd, uint32_t uMsg, uint64_t wParam, uint64_t lParam) { - std::map::iterator x = sHWndToListener.find( hWnd ); + std::map::iterator x = sHWndToListener.find(hWnd); - if( sHWndToListener.end() != x ) + if(sHWndToListener.end() != x) { CallbackBase* listener = x->second->listener; - if( NULL != listener ) + if(NULL != listener) { - TWinEventInfo eventInfo( hWnd, uMsg, wParam, lParam ); - CallbackBase::Execute( *listener, &eventInfo ); + TWinEventInfo eventInfo(hWnd, uMsg, wParam, lParam); + CallbackBase::Execute(*listener, &eventInfo); } } } -void WindowImpl::GetDPI( float &xDpi, float &yDpi ) +void WindowImpl::GetDPI(float& xDpi, float& yDpi) { - HDC hdcScreen = GetDC( reinterpret_cast( mHWnd ) ); + HDC hdcScreen = GetDC(reinterpret_cast(mHWnd)); - int32_t iX = GetDeviceCaps( hdcScreen, HORZRES ); // pixel - int32_t iY = GetDeviceCaps( hdcScreen, VERTRES ); // pixel - int32_t iPhsX = GetDeviceCaps( hdcScreen, HORZSIZE ); // mm - int32_t iPhsY = GetDeviceCaps( hdcScreen, VERTSIZE ); // mm + int32_t iX = GetDeviceCaps(hdcScreen, HORZRES); // pixel + int32_t iY = GetDeviceCaps(hdcScreen, VERTRES); // pixel + int32_t iPhsX = GetDeviceCaps(hdcScreen, HORZSIZE); // mm + int32_t iPhsY = GetDeviceCaps(hdcScreen, VERTSIZE); // mm - xDpi = static_cast( iX ) / static_cast( iPhsX ) * INCH; - yDpi = static_cast( iY ) / static_cast( iPhsY ) * INCH; + xDpi = static_cast(iX) / static_cast(iPhsX) * INCH; + yDpi = static_cast(iY) / static_cast(iPhsY) * INCH; } int WindowImpl::GetColorDepth() { - DALI_ASSERT_DEBUG( colorDepth >= 0 && "HWND hasn't been created, no color depth" ); + DALI_ASSERT_DEBUG(colorDepth >= 0 && "HWND hasn't been created, no color depth"); return colorDepth; } uint64_t WindowImpl::CreateHwnd( - _In_opt_ const char *lpWindowName, - _In_ int X, - _In_ int Y, - _In_ int nWidth, - _In_ int nHeight, - _In_opt_ uint64_t parent ) + _In_opt_ const char* lpWindowName, + _In_ int X, + _In_ int Y, + _In_ int nWidth, + _In_ int nHeight, + _In_opt_ uint64_t parent) { EnsureWindowClassRegistered(); ++sNumWindows; - HWND hWnd = CreateWindow( DALI_WINDOW_CLASS_NAME.c_str(), lpWindowName, STYLE, X, Y, - nWidth + 2 * EDGE_WIDTH, nHeight + 2 * EDGE_HEIGHT, NULL, NULL, GetModuleHandle(NULL), NULL ); - ::ShowWindow( hWnd, SW_SHOW ); + HWND hWnd = CreateWindow(DALI_WINDOW_CLASS_NAME.c_str(), lpWindowName, STYLE, X, Y, nWidth + 2 * EDGE_WIDTH, nHeight + 2 * EDGE_HEIGHT, NULL, NULL, GetModuleHandle(NULL), NULL); + ::ShowWindow(hWnd, SW_SHOW); return reinterpret_cast(hWnd); } void WindowImpl::DestroyHWnd(uint64_t hWnd) { - if (hWnd != 0) + if(hWnd != 0) { ::DestroyWindow(reinterpret_cast(hWnd)); @@ -178,7 +172,7 @@ void WindowImpl::DestroyHWnd(uint64_t hWnd) } } -void WindowImpl::SetListener( CallbackBase *callback ) +void WindowImpl::SetListener(CallbackBase* callback) { listener = callback; } @@ -186,23 +180,23 @@ void WindowImpl::SetListener( CallbackBase *callback ) bool WindowImpl::PostWinMessage( _In_ uint32_t Msg, _In_ uint64_t wParam, - _In_ uint64_t lParam ) + _In_ uint64_t lParam) { - return (bool)PostMessage( reinterpret_cast( mHWnd ), Msg, wParam, lParam ); + return (bool)PostMessage(reinterpret_cast(mHWnd), Msg, wParam, lParam); } -void WindowImpl::SetHWND( uint64_t inHWnd ) +void WindowImpl::SetHWND(uint64_t inHWnd) { - if (mHWnd != inHWnd) + if(mHWnd != inHWnd) { RemoveListener(mHWnd); - mHWnd = inHWnd; - mHdc = reinterpret_cast(GetDC(reinterpret_cast(mHWnd))); + mHWnd = inHWnd; + mHdc = reinterpret_cast(GetDC(reinterpret_cast(mHWnd))); colorDepth = GetDeviceCaps(reinterpret_cast(mHdc), BITSPIXEL) * GetDeviceCaps(reinterpret_cast(mHdc), PLANES); std::map::iterator x = sHWndToListener.find(mHWnd); - if (sHWndToListener.end() == x) + if(sHWndToListener.end() == x) { sHWndToListener.insert(std::make_pair(mHWnd, this)); } @@ -220,14 +214,14 @@ void WindowImpl::SetWinProc() GWLP_WNDPROC, reinterpret_cast(&WinProc)); - if (0 == ret) + if(0 == ret) { DWORD error = GetLastError(); return; } HMODULE module = GetModuleHandle(nullptr); - ret = SetWindowLongPtr((HWND)mHWnd, + ret = SetWindowLongPtr((HWND)mHWnd, GWLP_HINSTANCE, reinterpret_cast(&module)); } @@ -236,63 +230,63 @@ bool PostWinThreadMessage( _In_ uint32_t Msg, _In_ uint64_t wParam, _In_ uint64_t lParam, - _In_ uint64_t threadID/* = -1*/ ) + _In_ uint64_t threadID /* = -1*/) { - if( -1 == threadID ) + if(-1 == threadID) { threadID = GetCurrentThreadId(); } - return (bool)PostThreadMessage( threadID, Msg, wParam, lParam ); + return (bool)PostThreadMessage(threadID, Msg, wParam, lParam); } struct TTimerCallbackInfo { - void *data; + void* data; timerCallback callback; - HWND hWnd; + HWND hWnd; }; void CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT_PTR nTimerid, DWORD dwTime) { - TTimerCallbackInfo *info = (TTimerCallbackInfo*)nTimerid; - info->callback( info->data ); + TTimerCallbackInfo* info = (TTimerCallbackInfo*)nTimerid; + info->callback(info->data); } -intptr_t SetTimer(int interval, timerCallback callback, void *data) +intptr_t SetTimer(int interval, timerCallback callback, void* data) { HWND hwnd = GetActiveWindow(); - if (!hwnd) + if(!hwnd) { hwnd = FindWindow(DALI_WINDOW_CLASS_NAME.c_str(), nullptr); } - if (!hwnd) + if(!hwnd) { return -1; } - TTimerCallbackInfo *callbackInfo = new TTimerCallbackInfo; - callbackInfo->data = data; - callbackInfo->callback = callback; - callbackInfo->hWnd = hwnd; + TTimerCallbackInfo* callbackInfo = new TTimerCallbackInfo; + callbackInfo->data = data; + callbackInfo->callback = callback; + callbackInfo->hWnd = hwnd; INT_PTR timerID = (INT_PTR)callbackInfo; - ::SetTimer( hwnd, timerID, interval, TimerProc ); + ::SetTimer(hwnd, timerID, interval, TimerProc); return timerID; } void KillTimer(intptr_t id) { - TTimerCallbackInfo *info = (TTimerCallbackInfo*)id; - ::KillTimer( info->hWnd, id ); + TTimerCallbackInfo* info = (TTimerCallbackInfo*)id; + ::KillTimer(info->hWnd, id); delete info; } -std::string GetKeyName( int keyCode ) +std::string GetKeyName(int keyCode) { - switch( keyCode ) + switch(keyCode) { case VK_BACK: { @@ -372,7 +366,7 @@ std::string GetKeyName( int keyCode ) } default: { - if (keyCode > 0 && keyCode < 128) + if(keyCode > 0 && keyCode < 128) { return std::string(1u, static_cast(keyCode)); } @@ -383,46 +377,46 @@ std::string GetKeyName( int keyCode ) return ""; } -static LARGE_INTEGER cpuFrequency; -static LARGE_INTEGER *pCpuFrequency = NULL; +static LARGE_INTEGER cpuFrequency; +static LARGE_INTEGER* pCpuFrequency = NULL; uint64_t GetCurrentThreadId() { return ::GetCurrentThreadId(); } -void GetNanoseconds( uint64_t& timeInNanoseconds ) +void GetNanoseconds(uint64_t& timeInNanoseconds) { - if( NULL == pCpuFrequency ) + if(NULL == pCpuFrequency) { pCpuFrequency = &cpuFrequency; - QueryPerformanceFrequency( pCpuFrequency ); + QueryPerformanceFrequency(pCpuFrequency); } LARGE_INTEGER curTime; - QueryPerformanceCounter( &curTime ); + QueryPerformanceCounter(&curTime); timeInNanoseconds = static_cast(curTime.QuadPart) / static_cast(pCpuFrequency->QuadPart) * 1000000000; } -unsigned int GetCurrentMilliSeconds( void ) +unsigned int GetCurrentMilliSeconds(void) { - if( NULL == pCpuFrequency ) + if(NULL == pCpuFrequency) { pCpuFrequency = &cpuFrequency; - QueryPerformanceFrequency( pCpuFrequency ); + QueryPerformanceFrequency(pCpuFrequency); } LARGE_INTEGER curTime; - QueryPerformanceCounter( &curTime ); + QueryPerformanceCounter(&curTime); return curTime.QuadPart * 1000 / pCpuFrequency->QuadPart; } -} // namespace WindowsPlatformImplement +} // namespace WindowsPlatform } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/windows/platform-implement-win.h b/dali/internal/window-system/windows/platform-implement-win.h old mode 100755 new mode 100644 index d31099f..005d5af --- a/dali/internal/window-system/windows/platform-implement-win.h +++ b/dali/internal/window-system/windows/platform-implement-win.h @@ -2,7 +2,7 @@ #define PLATFORM_IMPLEMENT_WIN_INCLUDE /* -* Copyright (c) 2018 Samsung Electronics Co., Ltd. +* Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,97 +19,91 @@ */ // EXTERNAL_HEADERS +#include #include #include -#include -typedef uintptr_t WinWindowHandle; -typedef uint64_t WinPixmap; +typedef uintptr_t WinWindowHandle; +typedef uint64_t WinPixmap; namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowsPlatform { - bool PostWinThreadMessage( - _In_ uint32_t Msg, - _In_ uint64_t wParam, - _In_ uint64_t lParam, - _In_ uint64_t threadID = -1 ); + _In_ uint32_t Msg, + _In_ uint64_t wParam, + _In_ uint64_t lParam, + _In_ uint64_t threadID = -1); -using timerCallback = bool(*)(void *data); +using timerCallback = bool (*)(void* data); -intptr_t SetTimer(int interval, timerCallback callback, void *data); +intptr_t SetTimer(int interval, timerCallback callback, void* data); void KillTimer(intptr_t id); -std::string GetKeyName( int keyCode ); +std::string GetKeyName(int keyCode); uint64_t GetCurrentThreadId(); -void GetNanoseconds( uint64_t& timeInNanoseconds ); +void GetNanoseconds(uint64_t& timeInNanoseconds); -unsigned int GetCurrentMilliSeconds( void ); +unsigned int GetCurrentMilliSeconds(void); class WindowImpl { public: static const uint32_t STYLE; - static const int32_t EDGE_WIDTH; - static const int32_t EDGE_HEIGHT; + static const int32_t EDGE_WIDTH; + static const int32_t EDGE_HEIGHT; WindowImpl(); virtual ~WindowImpl(); - static void ProcWinMessage( uint64_t hWnd, uint32_t uMsg, uint64_t wParam, uint64_t lParam ); + static void ProcWinMessage(uint64_t hWnd, uint32_t uMsg, uint64_t wParam, uint64_t lParam); static uint64_t CreateHwnd( - _In_opt_ const char *lpWindowName, - _In_ int X, - _In_ int Y, - _In_ int nWidth, - _In_ int nHeight, - _In_opt_ uint64_t parent ); + _In_opt_ const char* lpWindowName, + _In_ int X, + _In_ int Y, + _In_ int nWidth, + _In_ int nHeight, + _In_opt_ uint64_t parent); static void DestroyHWnd(uint64_t hWnd); - void GetDPI( float &xDpi, float &yDpi ); + void GetDPI(float& xDpi, float& yDpi); int GetColorDepth(); - void SetListener( CallbackBase *callback ); + void SetListener(CallbackBase* callback); bool PostWinMessage( _In_ uint32_t Msg, _In_ uint64_t wParam, - _In_ uint64_t lParam ); + _In_ uint64_t lParam); void SetHWND(uint64_t inHWnd); void SetWinProc(); -protected: - private: - int colorDepth; + int colorDepth; uint64_t mHWnd; // no ownership, managed outside uint64_t mHdc; - CallbackBase *listener; + CallbackBase* listener; }; -} // namespace WindowsPlatformImplement +} // namespace WindowsPlatform } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/windows/render-surface-factory-win.cpp b/dali/internal/window-system/windows/render-surface-factory-win.cpp old mode 100755 new mode 100644 index 1864367..0f3a869 --- a/dali/internal/window-system/windows/render-surface-factory-win.cpp +++ b/dali/internal/window-system/windows/render-surface-factory-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,28 +33,27 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowRenderSurface > RenderSurfaceFactoryWin::CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryWin::CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowRenderSurface >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } -std::unique_ptr< PixmapRenderSurface > RenderSurfaceFactoryWin::CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryWin::CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent) { DALI_LOG_ERROR("Pixmap isn't been supported in Windows"); return nullptr; } -std::unique_ptr< NativeRenderSurface > RenderSurfaceFactoryWin::CreateNativeRenderSurface( SurfaceSize surfaceSize, Any surface, bool isTransparent ) +std::unique_ptr RenderSurfaceFactoryWin::CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent) { - return std::unique_ptr< NativeRenderSurface >( nullptr ); + return std::unique_ptr(nullptr); } // this should be created from somewhere -std::unique_ptr< RenderSurfaceFactory > GetRenderSurfaceFactory() +std::unique_ptr GetRenderSurfaceFactory() { // returns Window factory - return Utils::MakeUnique< RenderSurfaceFactoryWin >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/windows/render-surface-factory-win.h b/dali/internal/window-system/windows/render-surface-factory-win.h old mode 100755 new mode 100644 index a4e6626..ff94de5 --- a/dali/internal/window-system/windows/render-surface-factory-win.h +++ b/dali/internal/window-system/windows/render-surface-factory-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_WIN_RENDER_SURFACE_FACTORY_WIN_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,15 +26,14 @@ namespace Internal { namespace Adaptor { - class RenderSurfaceFactoryWin : public RenderSurfaceFactory { public: - std::unique_ptr< WindowRenderSurface > CreateWindowRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreateWindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< PixmapRenderSurface > CreatePixmapRenderSurface( Dali::PositionSize positionSize, Any surface, bool isTransparent = false ) override; + std::unique_ptr CreatePixmapRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent = false) override; - std::unique_ptr< NativeRenderSurface > CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) override; + std::unique_ptr CreateNativeRenderSurface(SurfaceSize surfaceSize, Any surface, bool isTransparent = false) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/windows/window-base-win.cpp b/dali/internal/window-system/windows/window-base-win.cpp old mode 100755 new mode 100644 index 9db4403..2b2f6bd --- a/dali/internal/window-system/windows/window-base-win.cpp +++ b/dali/internal/window-system/windows/window-base-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // EXTERNAL_HEADERS -#include #include +#include // INTERNAL HEADERS #include @@ -29,59 +29,55 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace { - -const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE; +const Device::Class::Type DEFAULT_DEVICE_CLASS = Device::Class::NONE; const Device::Subclass::Type DEFAULT_DEVICE_SUBCLASS = Device::Subclass::NONE; -const unsigned int PRIMARY_TOUCH_BUTTON_ID( 1 ); +const unsigned int PRIMARY_TOUCH_BUTTON_ID(1); #if defined(DEBUG_ENABLED) -Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_WINDOW_BASE" ); +Debug::Filter* gWindowBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_WINDOW_BASE"); #endif } // unnamed namespace -WindowBaseWin::WindowBaseWin( Dali::PositionSize positionSize, Any surface, bool isTransparent ) -: mWin32Window( 0 ), - mOwnSurface( false ), - mIsTransparent( false ), // Should only be set to true once we actually create a transparent window regardless of what isTransparent is. - mRotationAppSet( false ) +WindowBaseWin::WindowBaseWin(Dali::PositionSize positionSize, Any surface, bool isTransparent) +: mWin32Window(0), + mOwnSurface(false), + mIsTransparent(false), // Should only be set to true once we actually create a transparent window regardless of what isTransparent is. + mRotationAppSet(false) { - Initialize( positionSize, surface, isTransparent ); + Initialize(positionSize, surface, isTransparent); } WindowBaseWin::~WindowBaseWin() { - mWindowImpl.PostWinMessage( WM_CLOSE, 0, 0 ); + mWindowImpl.PostWinMessage(WM_CLOSE, 0, 0); } -void WindowBaseWin::Initialize( PositionSize positionSize, Any surface, bool isTransparent ) +void WindowBaseWin::Initialize(PositionSize positionSize, Any surface, bool isTransparent) { // see if there is a surface in Any surface - uintptr_t surfaceId = GetSurfaceId( surface ); + uintptr_t surfaceId = GetSurfaceId(surface); // if the surface is empty, create a new one. - if( surfaceId == 0 ) + if(surfaceId == 0) { // we own the surface about to created mOwnSurface = true; - CreateWinWindow( positionSize, isTransparent ); + CreateWinWindow(positionSize, isTransparent); } else { - SetWinWindow( surfaceId ); + SetWinWindow(surfaceId); } - mWindowImpl.SetListener( MakeCallback( this, &WindowBaseWin::EventEntry ) ); + mWindowImpl.SetListener(MakeCallback(this, &WindowBaseWin::EventEntry)); } void WindowBaseWin::OnDeleteRequest() @@ -89,158 +85,158 @@ void WindowBaseWin::OnDeleteRequest() mDeleteRequestSignal.Emit(); } -void WindowBaseWin::OnFocusIn( int type, TWinEventInfo *event ) +void WindowBaseWin::OnFocusIn(int type, TWinEventInfo* event) { } -void WindowBaseWin::OnFocusOut( int type, TWinEventInfo *event ) +void WindowBaseWin::OnFocusOut(int type, TWinEventInfo* event) { } -void WindowBaseWin::OnWindowDamaged( int type, TWinEventInfo *event ) +void WindowBaseWin::OnWindowDamaged(int type, TWinEventInfo* event) { - Event_Mouse_Button* windowDamagedEvent( (Event_Mouse_Button*)event ); + Event_Mouse_Button* windowDamagedEvent((Event_Mouse_Button*)event); - if( windowDamagedEvent->window == mWin32Window ) + if(windowDamagedEvent->window == mWin32Window) { DamageArea area; area.x = 0; area.y = 0; - WindowSystem::GetScreenSize( area.width, area.height ); + WindowSystem::GetScreenSize(area.width, area.height); - mWindowDamagedSignal.Emit( area ); + mWindowDamagedSignal.Emit(area); } } -void WindowBaseWin::OnMouseButtonDown( int type, TWinEventInfo *event ) +void WindowBaseWin::OnMouseButtonDown(int type, TWinEventInfo* event) { Event_Mouse_Button touchEvent = *((Event_Mouse_Button*)event); - touchEvent.timestamp = GetTickCount(); - touchEvent.x = LOWORD( event->lParam ); - touchEvent.y = HIWORD( event->lParam ); - touchEvent.multi.device = DEVICE_MOUSE; + touchEvent.timestamp = GetTickCount(); + touchEvent.x = LOWORD(event->lParam); + touchEvent.y = HIWORD(event->lParam); + touchEvent.multi.device = DEVICE_MOUSE; - if( touchEvent.window == mWin32Window ) + if(touchEvent.window == mWin32Window) { - PointState::Type state ( PointState::DOWN ); + PointState::Type state(PointState::DOWN); Integration::Point point; - point.SetDeviceId( touchEvent.multi.device ); - point.SetState( state ); - point.SetScreenPosition( Vector2( touchEvent.x, touchEvent.y + WindowsPlatform::WindowImpl::EDGE_HEIGHT ) ); - point.SetRadius( touchEvent.multi.radius, Vector2( touchEvent.multi.radius_x, touchEvent.multi.radius_y ) ); - point.SetPressure( touchEvent.multi.pressure ); - point.SetAngle( Degree( touchEvent.multi.angle ) ); - - mTouchEventSignal.Emit( point, touchEvent.timestamp ); + point.SetDeviceId(touchEvent.multi.device); + point.SetState(state); + point.SetScreenPosition(Vector2(touchEvent.x, touchEvent.y + WindowsPlatform::WindowImpl::EDGE_HEIGHT)); + point.SetRadius(touchEvent.multi.radius, Vector2(touchEvent.multi.radius_x, touchEvent.multi.radius_y)); + point.SetPressure(touchEvent.multi.pressure); + point.SetAngle(Degree(touchEvent.multi.angle)); + + mTouchEventSignal.Emit(point, touchEvent.timestamp); } } -void WindowBaseWin::OnMouseButtonUp( int type, TWinEventInfo *event ) +void WindowBaseWin::OnMouseButtonUp(int type, TWinEventInfo* event) { - Event_Mouse_Button touchEvent = *( (Event_Mouse_Button*)event ); - touchEvent.timestamp = GetTickCount(); - touchEvent.x = LOWORD( event->lParam ); - touchEvent.y = HIWORD( event->lParam ); - touchEvent.multi.device = DEVICE_MOUSE; + Event_Mouse_Button touchEvent = *((Event_Mouse_Button*)event); + touchEvent.timestamp = GetTickCount(); + touchEvent.x = LOWORD(event->lParam); + touchEvent.y = HIWORD(event->lParam); + touchEvent.multi.device = DEVICE_MOUSE; - if( touchEvent.window == mWin32Window ) + if(touchEvent.window == mWin32Window) { - PointState::Type state( PointState::UP ); + PointState::Type state(PointState::UP); Integration::Point point; - point.SetDeviceId( touchEvent.multi.device ); - point.SetState( state ); - point.SetScreenPosition( Vector2( touchEvent.x, touchEvent.y + WindowsPlatform::WindowImpl::EDGE_HEIGHT ) ); - point.SetRadius( touchEvent.multi.radius, Vector2( touchEvent.multi.radius_x, touchEvent.multi.radius_y ) ); - point.SetPressure( touchEvent.multi.pressure ); - point.SetAngle( Degree( touchEvent.multi.angle ) ); - - mTouchEventSignal.Emit( point, touchEvent.timestamp ); + point.SetDeviceId(touchEvent.multi.device); + point.SetState(state); + point.SetScreenPosition(Vector2(touchEvent.x, touchEvent.y + WindowsPlatform::WindowImpl::EDGE_HEIGHT)); + point.SetRadius(touchEvent.multi.radius, Vector2(touchEvent.multi.radius_x, touchEvent.multi.radius_y)); + point.SetPressure(touchEvent.multi.pressure); + point.SetAngle(Degree(touchEvent.multi.angle)); + + mTouchEventSignal.Emit(point, touchEvent.timestamp); } } -void WindowBaseWin::OnMouseButtonMove( int type, TWinEventInfo *event ) +void WindowBaseWin::OnMouseButtonMove(int type, TWinEventInfo* event) { Event_Mouse_Button touchEvent = *((Event_Mouse_Button*)event); - touchEvent.timestamp = GetTickCount(); - touchEvent.x = LOWORD( event->lParam ); - touchEvent.y = HIWORD( event->lParam ); - touchEvent.multi.device = DEVICE_MOUSE; + touchEvent.timestamp = GetTickCount(); + touchEvent.x = LOWORD(event->lParam); + touchEvent.y = HIWORD(event->lParam); + touchEvent.multi.device = DEVICE_MOUSE; - if( touchEvent.window == mWin32Window ) + if(touchEvent.window == mWin32Window) { - PointState::Type state( PointState::MOTION ); + PointState::Type state(PointState::MOTION); Integration::Point point; - point.SetDeviceId( touchEvent.multi.device ); - point.SetState( state ); - point.SetScreenPosition( Vector2( touchEvent.x, touchEvent.y + WindowsPlatform::WindowImpl::EDGE_HEIGHT) ); - point.SetRadius( touchEvent.multi.radius, Vector2( touchEvent.multi.radius_x, touchEvent.multi.radius_y ) ); - point.SetPressure( touchEvent.multi.pressure ); - point.SetAngle( Degree( touchEvent.multi.angle ) ); - - mTouchEventSignal.Emit( point, touchEvent.timestamp ); + point.SetDeviceId(touchEvent.multi.device); + point.SetState(state); + point.SetScreenPosition(Vector2(touchEvent.x, touchEvent.y + WindowsPlatform::WindowImpl::EDGE_HEIGHT)); + point.SetRadius(touchEvent.multi.radius, Vector2(touchEvent.multi.radius_x, touchEvent.multi.radius_y)); + point.SetPressure(touchEvent.multi.pressure); + point.SetAngle(Degree(touchEvent.multi.angle)); + + mTouchEventSignal.Emit(point, touchEvent.timestamp); } } -void WindowBaseWin::OnMouseWheel( int type, TWinEventInfo *event ) +void WindowBaseWin::OnMouseWheel(int type, TWinEventInfo* event) { - Event_Mouse_Wheel mouseWheelEvent = *((Event_Mouse_Wheel*)( event )); + Event_Mouse_Wheel mouseWheelEvent = *((Event_Mouse_Wheel*)(event)); - if( mouseWheelEvent.window == mWin32Window ) + if(mouseWheelEvent.window == mWin32Window) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseWin::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent.direction, mouseWheelEvent.modifiers, mouseWheelEvent.x, mouseWheelEvent.y, mouseWheelEvent.z ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseWin::OnMouseWheel: direction: %d, modifiers: %d, x: %d, y: %d, z: %d\n", mouseWheelEvent.direction, mouseWheelEvent.modifiers, mouseWheelEvent.x, mouseWheelEvent.y, mouseWheelEvent.z); - Integration::WheelEvent wheelEvent( Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent.direction, mouseWheelEvent.modifiers, Vector2( mouseWheelEvent.x, mouseWheelEvent.y ), mouseWheelEvent.z, mouseWheelEvent.timestamp ); + Integration::WheelEvent wheelEvent(Integration::WheelEvent::MOUSE_WHEEL, mouseWheelEvent.direction, mouseWheelEvent.modifiers, Vector2(mouseWheelEvent.x, mouseWheelEvent.y), mouseWheelEvent.z, mouseWheelEvent.timestamp); - mWheelEventSignal.Emit( wheelEvent ); + mWheelEventSignal.Emit(wheelEvent); } } -void WindowBaseWin::OnKeyDown( int type, TWinEventInfo *event ) +void WindowBaseWin::OnKeyDown(int type, TWinEventInfo* event) { - if( event->mWindow == mWin32Window ) + if(event->mWindow == mWin32Window) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseWin::OnKeyDown\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseWin::OnKeyDown\n"); - int keyCode = event->wParam; - std::string keyName( WindowsPlatform::GetKeyName( keyCode ) ); + int keyCode = event->wParam; + std::string keyName(WindowsPlatform::GetKeyName(keyCode)); std::string keyString; std::string emptyString; - int modifier( 0 ); - unsigned long time( 0 ); + int modifier(0); + unsigned long time(0); // Ensure key event string is not NULL as keys like SHIFT have a null string. - keyString.push_back( event->wParam ); + keyString.push_back(event->wParam); - Integration::KeyEvent keyEvent( keyName, emptyString, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, emptyString, emptyString, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS ); + Integration::KeyEvent keyEvent(keyName, emptyString, keyString, keyCode, modifier, time, Integration::KeyEvent::DOWN, emptyString, emptyString, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } -void WindowBaseWin::OnKeyUp( int type, TWinEventInfo *event ) +void WindowBaseWin::OnKeyUp(int type, TWinEventInfo* event) { - if( event->mWindow == mWin32Window ) + if(event->mWindow == mWin32Window) { - DALI_LOG_INFO( gWindowBaseLogFilter, Debug::General, "WindowBaseWin::OnKeyDown\n" ); + DALI_LOG_INFO(gWindowBaseLogFilter, Debug::General, "WindowBaseWin::OnKeyDown\n"); - int keyCode = event->wParam; - std::string keyName( WindowsPlatform::GetKeyName( keyCode ) ); + int keyCode = event->wParam; + std::string keyName(WindowsPlatform::GetKeyName(keyCode)); std::string keyString; std::string emptyString; - int modifier( 0 ); - unsigned long time( 0 ); + int modifier(0); + unsigned long time(0); // Ensure key event string is not NULL as keys like SHIFT have a null string. - keyString.push_back( event->wParam ); + keyString.push_back(event->wParam); - Integration::KeyEvent keyEvent( keyName, emptyString, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, emptyString, emptyString, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS ); + Integration::KeyEvent keyEvent(keyName, emptyString, keyString, keyCode, modifier, time, Integration::KeyEvent::UP, emptyString, emptyString, DEFAULT_DEVICE_CLASS, DEFAULT_DEVICE_SUBCLASS); - mKeyEventSignal.Emit( keyEvent ); + mKeyEventSignal.Emit(keyEvent); } } @@ -254,28 +250,28 @@ int WindowBaseWin::GetNativeWindowId() return mWin32Window; } -EGLNativeWindowType WindowBaseWin::CreateEglWindow( int width, int height ) +EGLNativeWindowType WindowBaseWin::CreateEglWindow(int width, int height) { - return reinterpret_cast< EGLNativeWindowType >( mWin32Window ); + return reinterpret_cast(mWin32Window); } void WindowBaseWin::DestroyEglWindow() { } -void WindowBaseWin::SetEglWindowRotation( int angle ) +void WindowBaseWin::SetEglWindowRotation(int angle) { } -void WindowBaseWin::SetEglWindowBufferTransform( int angle ) +void WindowBaseWin::SetEglWindowBufferTransform(int angle) { } -void WindowBaseWin::SetEglWindowTransform( int angle ) +void WindowBaseWin::SetEglWindowTransform(int angle) { } -void WindowBaseWin::ResizeEglWindow( PositionSize positionSize ) +void WindowBaseWin::ResizeEglWindow(PositionSize positionSize) { } @@ -284,20 +280,20 @@ bool WindowBaseWin::IsEglWindowRotationSupported() return false; } -void WindowBaseWin::Move( PositionSize positionSize ) +void WindowBaseWin::Move(PositionSize positionSize) { } -void WindowBaseWin::Resize( PositionSize positionSize ) +void WindowBaseWin::Resize(PositionSize positionSize) { - ::SetWindowPos( (HWND)mWin32Window, NULL, positionSize.x, positionSize.y, positionSize.width, positionSize.height, SWP_SHOWWINDOW ); + ::SetWindowPos((HWND)mWin32Window, NULL, positionSize.x, positionSize.y, positionSize.width, positionSize.height, SWP_SHOWWINDOW); } -void WindowBaseWin::MoveResize( PositionSize positionSize ) +void WindowBaseWin::MoveResize(PositionSize positionSize) { } -void WindowBaseWin::SetClass( const std::string& name, const std::string& className ) +void WindowBaseWin::SetClass(const std::string& name, const std::string& className) { } @@ -313,15 +309,15 @@ void WindowBaseWin::Activate() { } -void WindowBaseWin::SetAvailableAnlges( const std::vector< int >& angles ) +void WindowBaseWin::SetAvailableAnlges(const std::vector& angles) { } -void WindowBaseWin::SetPreferredAngle( int angle ) +void WindowBaseWin::SetPreferredAngle(int angle) { } -void WindowBaseWin::SetAcceptFocus( bool accept ) +void WindowBaseWin::SetAcceptFocus(bool accept) { } @@ -338,45 +334,45 @@ unsigned int WindowBaseWin::GetSupportedAuxiliaryHintCount() const return 0; } -std::string WindowBaseWin::GetSupportedAuxiliaryHint( unsigned int index ) const +std::string WindowBaseWin::GetSupportedAuxiliaryHint(unsigned int index) const { return std::string(); } -unsigned int WindowBaseWin::AddAuxiliaryHint( const std::string& hint, const std::string& value ) +unsigned int WindowBaseWin::AddAuxiliaryHint(const std::string& hint, const std::string& value) { return 0; } -bool WindowBaseWin::RemoveAuxiliaryHint( unsigned int id ) +bool WindowBaseWin::RemoveAuxiliaryHint(unsigned int id) { return false; } -bool WindowBaseWin::SetAuxiliaryHintValue( unsigned int id, const std::string& value ) +bool WindowBaseWin::SetAuxiliaryHintValue(unsigned int id, const std::string& value) { return false; } -std::string WindowBaseWin::GetAuxiliaryHintValue( unsigned int id ) const +std::string WindowBaseWin::GetAuxiliaryHintValue(unsigned int id) const { return std::string(); } -unsigned int WindowBaseWin::GetAuxiliaryHintId( const std::string& hint ) const +unsigned int WindowBaseWin::GetAuxiliaryHintId(const std::string& hint) const { return 0; } -void WindowBaseWin::SetInputRegion( const Rect< int >& inputRegion ) +void WindowBaseWin::SetInputRegion(const Rect& inputRegion) { } -void WindowBaseWin::SetType( Dali::WindowType type ) +void WindowBaseWin::SetType(Dali::WindowType type) { } -bool WindowBaseWin::SetNotificationLevel( Dali::WindowNotificationLevel level ) +bool WindowBaseWin::SetNotificationLevel(Dali::WindowNotificationLevel level) { return false; } @@ -386,7 +382,7 @@ Dali::WindowNotificationLevel WindowBaseWin::GetNotificationLevel() const return Dali::WindowNotificationLevel::NONE; } -void WindowBaseWin::SetOpaqueState( bool opaque ) +void WindowBaseWin::SetOpaqueState(bool opaque) { } @@ -400,7 +396,7 @@ WindowScreenOffMode WindowBaseWin::GetScreenOffMode() const return WindowScreenOffMode::TIMEOUT; } -bool WindowBaseWin::SetBrightness( int brightness ) +bool WindowBaseWin::SetBrightness(int brightness) { return false; } @@ -410,39 +406,39 @@ int WindowBaseWin::GetBrightness() const return 0; } -bool WindowBaseWin::GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) +bool WindowBaseWin::GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) { return false; } -bool WindowBaseWin::UngrabKey( Dali::KEY key ) +bool WindowBaseWin::UngrabKey(Dali::KEY key) { return false; } -bool WindowBaseWin::GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) +bool WindowBaseWin::GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) { return false; } -bool WindowBaseWin::UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) +bool WindowBaseWin::UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) { return false; } -void WindowBaseWin::GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) +void WindowBaseWin::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; //// 1 inch = 25.4 millimeters - mWindowImpl.GetDPI( xres, yres ); + mWindowImpl.GetDPI(xres, yres); xres *= 1.5f; yres *= 1.5f; - dpiHorizontal = static_cast( xres + 0.5f ); // rounding - dpiVertical = static_cast( yres + 0.5f ); + dpiHorizontal = static_cast(xres + 0.5f); // rounding + dpiVertical = static_cast(yres + 0.5f); } int WindowBaseWin::GetScreenRotationAngle() @@ -450,15 +446,15 @@ int WindowBaseWin::GetScreenRotationAngle() return 0; } -void WindowBaseWin::SetWindowRotationAngle( int degree ) +void WindowBaseWin::SetWindowRotationAngle(int degree) { } -void WindowBaseWin::WindowRotationCompleted( int degree, int width, int height ) +void WindowBaseWin::WindowRotationCompleted(int degree, int width, int height) { } -void WindowBaseWin::SetTransparency( bool transparent ) +void WindowBaseWin::SetTransparency(bool transparent) { } @@ -467,32 +463,31 @@ int WindowBaseWin::GetOrientation() const return 0; } -uintptr_t WindowBaseWin::GetSurfaceId( Any surface ) const +uintptr_t WindowBaseWin::GetSurfaceId(Any surface) const { uintptr_t surfaceId = 0; - if ( surface.Empty() == false ) + if(surface.Empty() == false) { // check we have a valid type - DALI_ASSERT_ALWAYS( (surface.GetType() == typeid ( WinWindowHandle ) ) - && "Surface type is invalid" ); + DALI_ASSERT_ALWAYS((surface.GetType() == typeid(WinWindowHandle)) && "Surface type is invalid"); - surfaceId = AnyCast< WinWindowHandle >( surface ); + surfaceId = AnyCast(surface); } return surfaceId; } -void WindowBaseWin::CreateWinWindow( PositionSize positionSize, bool isTransparent ) +void WindowBaseWin::CreateWinWindow(PositionSize positionSize, bool isTransparent) { - long hWnd = WindowsPlatform::WindowImpl::CreateHwnd( "Demo", positionSize.x, positionSize.y, positionSize.width, positionSize.height, NULL ); + long hWnd = WindowsPlatform::WindowImpl::CreateHwnd("Demo", positionSize.x, positionSize.y, positionSize.width, positionSize.height, NULL); mWindowImpl.SetHWND(hWnd); mWin32Window = static_cast(hWnd); - DALI_ASSERT_ALWAYS( mWin32Window != 0 && "There is no Windows window" ); + DALI_ASSERT_ALWAYS(mWin32Window != 0 && "There is no Windows window"); } -void WindowBaseWin::SetWinWindow( uintptr_t surfaceId ) +void WindowBaseWin::SetWinWindow(uintptr_t surfaceId) { HWND hWnd = (HWND)surfaceId; @@ -503,74 +498,73 @@ void WindowBaseWin::SetWinWindow( uintptr_t surfaceId ) mWindowImpl.SetWinProc(); } -void WindowBaseWin::EventEntry( TWinEventInfo *event ) +void WindowBaseWin::EventEntry(TWinEventInfo* event) { unsigned int uMsg = event->uMsg; - switch( uMsg ) - { - case WM_SETFOCUS: - { - OnFocusIn( uMsg, event ); - break; - } - - case WM_KILLFOCUS: - { - OnFocusOut( uMsg, event ); - break; - } - - case WM_PAINT: - { - OnWindowDamaged( uMsg, event ); - break; - } - - case WM_LBUTTONDOWN: - { - OnMouseButtonDown( uMsg, event ); - break; - } - - case WM_LBUTTONUP: - { - OnMouseButtonUp( uMsg, event ); - break; - } - - case WM_MOUSEMOVE: - { - OnMouseButtonMove( uMsg, event ); - break; - } - - case WM_MOUSEWHEEL: - { - OnMouseWheel( uMsg, event ); - break; - } - - case WM_KEYDOWN: - { - OnKeyDown( uMsg, event ); - break; - } - - case WM_KEYUP: + switch(uMsg) { - OnKeyUp( uMsg, event ); - break; - } - - default: - break; + case WM_SETFOCUS: + { + OnFocusIn(uMsg, event); + break; + } + + case WM_KILLFOCUS: + { + OnFocusOut(uMsg, event); + break; + } + + case WM_PAINT: + { + OnWindowDamaged(uMsg, event); + break; + } + + case WM_LBUTTONDOWN: + { + OnMouseButtonDown(uMsg, event); + break; + } + + case WM_LBUTTONUP: + { + OnMouseButtonUp(uMsg, event); + break; + } + + case WM_MOUSEMOVE: + { + OnMouseButtonMove(uMsg, event); + break; + } + + case WM_MOUSEWHEEL: + { + OnMouseWheel(uMsg, event); + break; + } + + case WM_KEYDOWN: + { + OnKeyDown(uMsg, event); + break; + } + + case WM_KEYUP: + { + OnKeyUp(uMsg, event); + break; + } + + default: + break; } } -void WindowBaseWin::SetParent( WindowBase* parentWinBase ) +void WindowBaseWin::SetParent(WindowBase* parentWinBase) { - } int WindowBaseWin::CreateFrameRenderedSyncFence() @@ -588,4 +582,3 @@ int WindowBaseWin::CreateFramePresentedSyncFence() } // namespace Internal } // namespace Dali - diff --git a/dali/internal/window-system/windows/window-base-win.h b/dali/internal/window-system/windows/window-base-win.h old mode 100755 new mode 100644 index 531386f..dedbccb --- a/dali/internal/window-system/windows/window-base-win.h +++ b/dali/internal/window-system/windows/window-base-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_WINDOW_BASE_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ // INTERNAL INCLUDES #include -#include #include +#include namespace Dali { @@ -29,7 +29,6 @@ namespace Internal { namespace Adaptor { - class Window; class WindowRenderSurface; class WindowRenderSurfaceWin; @@ -40,11 +39,10 @@ class WindowRenderSurfaceWin; class WindowBaseWin : public WindowBase { public: - /** * @brief Constructor */ - WindowBaseWin( PositionSize positionSize, Any surface, bool isTransparent ); + WindowBaseWin(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Destructor @@ -52,7 +50,6 @@ public: virtual ~WindowBaseWin(); public: - /** * Called when the window receives a delete request */ @@ -61,51 +58,49 @@ public: /** * @brief Called when the window gains focus. */ - void OnFocusIn( int type, TWinEventInfo *event ); + void OnFocusIn(int type, TWinEventInfo* event); /** * @brief Called when the window loses focus. */ - void OnFocusOut( int type, TWinEventInfo *event ); + void OnFocusOut(int type, TWinEventInfo* event); /** * @brief Called when the window is damaged. */ - void OnWindowDamaged( int type, TWinEventInfo *event ); + void OnWindowDamaged(int type, TWinEventInfo* event); /** * @brief Called when a touch down is received. */ - void OnMouseButtonDown( int type, TWinEventInfo *event ); + void OnMouseButtonDown(int type, TWinEventInfo* event); /** * @brief Called when a touch up is received. */ - void OnMouseButtonUp( int type, TWinEventInfo *event ); + void OnMouseButtonUp(int type, TWinEventInfo* event); /** * @brief Called when a touch motion is received. */ - void OnMouseButtonMove( int type, TWinEventInfo *event ); + void OnMouseButtonMove(int type, TWinEventInfo* event); /** * @brief Called when a mouse wheel is received. */ - void OnMouseWheel( int type, TWinEventInfo *event ); + void OnMouseWheel(int type, TWinEventInfo* event); /** * @brief Called when a key down is received. */ - void OnKeyDown( int type, TWinEventInfo *event ); + void OnKeyDown(int type, TWinEventInfo* event); /** * @brief Called when a key up is received. */ - void OnKeyUp( int type, TWinEventInfo *event ); - + void OnKeyUp(int type, TWinEventInfo* event); public: - /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNativeWindow() */ @@ -119,7 +114,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateEglWindow() */ - EGLNativeWindowType CreateEglWindow( int width, int height ) override; + EGLNativeWindowType CreateEglWindow(int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::DestroyEglWindow() @@ -129,22 +124,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowRotation() */ - void SetEglWindowRotation( int angle ) override; + void SetEglWindowRotation(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowBufferTransform() */ - void SetEglWindowBufferTransform( int angle ) override; + void SetEglWindowBufferTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetEglWindowTransform() */ - void SetEglWindowTransform( int angle ) override; + void SetEglWindowTransform(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::ResizeEglWindow() */ - void ResizeEglWindow( PositionSize positionSize ) override; + void ResizeEglWindow(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::IsEglWindowRotationSupported() @@ -154,22 +149,22 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::Move() */ - void Move( PositionSize positionSize ) override; + void Move(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Resize() */ - void Resize( PositionSize positionSize ) override; + void Resize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::MoveResize() */ - void MoveResize( PositionSize positionSize ) override; + void MoveResize(PositionSize positionSize) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetClass() */ - void SetClass( const std::string& name, const std::string& className ) override; + void SetClass(const std::string& name, const std::string& className) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Raise() @@ -189,17 +184,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAvailableAnlges() */ - void SetAvailableAnlges( const std::vector< int >& angles ) override; + void SetAvailableAnlges(const std::vector& angles) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetPreferredAngle() */ - void SetPreferredAngle( int angle ) override; + void SetPreferredAngle(int angle) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAcceptFocus() */ - void SetAcceptFocus( bool accept ) override; + void SetAcceptFocus(bool accept) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::Show() @@ -219,47 +214,47 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetSupportedAuxiliaryHint() */ - std::string GetSupportedAuxiliaryHint( unsigned int index ) const override; + std::string GetSupportedAuxiliaryHint(unsigned int index) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::AddAuxiliaryHint() */ - unsigned int AddAuxiliaryHint( const std::string& hint, const std::string& value ) override; + unsigned int AddAuxiliaryHint(const std::string& hint, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::RemoveAuxiliaryHint() */ - bool RemoveAuxiliaryHint( unsigned int id ) override; + bool RemoveAuxiliaryHint(unsigned int id) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetAuxiliaryHintValue() */ - bool SetAuxiliaryHintValue( unsigned int id, const std::string& value ) override; + bool SetAuxiliaryHintValue(unsigned int id, const std::string& value) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintValue() */ - std::string GetAuxiliaryHintValue( unsigned int id ) const override; + std::string GetAuxiliaryHintValue(unsigned int id) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetAuxiliaryHintId() */ - unsigned int GetAuxiliaryHintId( const std::string& hint ) const override; + unsigned int GetAuxiliaryHintId(const std::string& hint) const override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetInputRegion() */ - void SetInputRegion( const Rect< int >& inputRegion ) override; + void SetInputRegion(const Rect& inputRegion) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetType() */ - void SetType( Dali::WindowType type ) override; + void SetType(Dali::WindowType type) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetNotificationLevel() */ - bool SetNotificationLevel( Dali::WindowNotificationLevel level ) override; + bool SetNotificationLevel(Dali::WindowNotificationLevel level) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetNotificationLevel() @@ -269,7 +264,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetOpaqueState() */ - void SetOpaqueState( bool opaque ) override; + void SetOpaqueState(bool opaque) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetScreenOffMode() @@ -284,7 +279,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetBrightness() */ - bool SetBrightness( int brightness ) override; + bool SetBrightness(int brightness) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetBrightness() @@ -294,27 +289,27 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKey() */ - bool GrabKey( Dali::KEY key, KeyGrab::KeyGrabMode grabMode ) override; + bool GrabKey(Dali::KEY key, KeyGrab::KeyGrabMode grabMode) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKey() */ - bool UngrabKey( Dali::KEY key ) override; + bool UngrabKey(Dali::KEY key) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GrabKeyList() */ - bool GrabKeyList( const Dali::Vector< Dali::KEY >& key, const Dali::Vector< KeyGrab::KeyGrabMode >& grabMode, Dali::Vector< bool >& result ) override; + bool GrabKeyList(const Dali::Vector& key, const Dali::Vector& grabMode, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::UngrabKeyList() */ - bool UngrabKeyList( const Dali::Vector< Dali::KEY >& key, Dali::Vector< bool >& result ) override; + bool UngrabKeyList(const Dali::Vector& key, Dali::Vector& result) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetDpi() */ - void GetDpi( unsigned int& dpiHorizontal, unsigned int& dpiVertical ) override; + void GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetScreenRotationAngle() @@ -324,17 +319,17 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetWindowRotationAngle() */ - void SetWindowRotationAngle( int degree ) override; + void SetWindowRotationAngle(int degree) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::WindowRotationCompleted() */ - void WindowRotationCompleted( int degree, int width, int height ) override; + void WindowRotationCompleted(int degree, int width, int height) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetTransparency() */ - void SetTransparency( bool transparent ) override; + void SetTransparency(bool transparent) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::GetOrientation() @@ -344,7 +339,7 @@ public: /** * @copydoc Dali::Internal::Adaptor::WindowBase::SetParent() */ - void SetParent( WindowBase* parentWinBase ) override; + void SetParent(WindowBase* parentWinBase) override; /** * @copydoc Dali::Internal::Adaptor::WindowBase::CreateFrameRenderedSyncFence() @@ -357,31 +352,29 @@ public: int CreateFramePresentedSyncFence() override; private: - /** * Second stage initialization */ - void Initialize( PositionSize positionSize, Any surface, bool isTransparent ); + void Initialize(PositionSize positionSize, Any surface, bool isTransparent); /** * @brief Get the surface id if the surface parameter is not empty * @param surface Any containing a surface id, or can be empty * @return surface id, or zero if surface is empty */ - uintptr_t GetSurfaceId( Any surface ) const; + uintptr_t GetSurfaceId(Any surface) const; /** * @brief Create window */ - void CreateWinWindow( PositionSize positionSize, bool isTransparent ); + void CreateWinWindow(PositionSize positionSize, bool isTransparent); /** * @brief Sets up an already created window. */ - void SetWinWindow( uintptr_t surfaceId ); + void SetWinWindow(uintptr_t surfaceId); private: - // Undefined WindowBaseWin(const WindowBaseWin&) = delete; @@ -389,20 +382,20 @@ private: WindowBaseWin& operator=(const WindowBaseWin& rhs) = delete; private: - void EventEntry( TWinEventInfo *event ); + void EventEntry(TWinEventInfo* event); private: - WinWindowHandle mWin32Window; ///< Native window handle - bool mOwnSurface:1; ///< Whether we own the surface (responsible for deleting it) - bool mIsTransparent:1; ///< Whether the window is transparent (32 bit or 24 bit) - bool mRotationAppSet:1; + WinWindowHandle mWin32Window; ///< Native window handle + bool mOwnSurface : 1; ///< Whether we own the surface (responsible for deleting it) + bool mIsTransparent : 1; ///< Whether the window is transparent (32 bit or 24 bit) + bool mRotationAppSet : 1; WindowsPlatform::WindowImpl mWindowImpl; }; } // namespace Adaptor -} // namespace internal +} // namespace Internal } // namespace Dali diff --git a/dali/internal/window-system/windows/window-factory-win.cpp b/dali/internal/window-system/windows/window-factory-win.cpp old mode 100755 new mode 100644 index 4be2aaa..1c569d8 --- a/dali/internal/window-system/windows/window-factory-win.cpp +++ b/dali/internal/window-system/windows/window-factory-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ #include // INTERNAL HEADERS -#include #include +#include namespace Dali { @@ -28,17 +28,16 @@ namespace Internal { namespace Adaptor { - -std::unique_ptr< WindowBase > WindowFactoryWin::CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) +std::unique_ptr WindowFactoryWin::CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) { - return Utils::MakeUnique< WindowBaseWin >( positionSize, surface, isTransparent ); + return Utils::MakeUnique(positionSize, surface, isTransparent); } // this should be created from Window impl -std::unique_ptr< WindowFactory > GetWindowFactory() +std::unique_ptr GetWindowFactory() { // returns Window factory - return Utils::MakeUnique< WindowFactoryWin >(); + return Utils::MakeUnique(); } } // namespace Adaptor diff --git a/dali/internal/window-system/windows/window-factory-win.h b/dali/internal/window-system/windows/window-factory-win.h old mode 100755 new mode 100644 index 9b1b8de..93b0198 --- a/dali/internal/window-system/windows/window-factory-win.h +++ b/dali/internal/window-system/windows/window-factory-win.h @@ -2,7 +2,7 @@ #define DALI_INTERNAL_WINDOWSYSTEM_WINDOW_FACTORY_WIN_H /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,10 @@ namespace Internal { namespace Adaptor { - class WindowFactoryWin : public WindowFactory { public: - std::unique_ptr< WindowBase > CreateWindowBase( Dali::PositionSize positionSize, Any surface, bool isTransparent ) override; + std::unique_ptr CreateWindowBase(Dali::PositionSize positionSize, Any surface, bool isTransparent) override; }; } // namespace Adaptor diff --git a/dali/internal/window-system/windows/window-system-win.cpp b/dali/internal/window-system/windows/window-system-win.cpp old mode 100755 new mode 100644 index 1fcbc68..1536d0d --- a/dali/internal/window-system/windows/window-system-win.cpp +++ b/dali/internal/window-system/windows/window-system-win.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,32 +23,28 @@ namespace Dali { - namespace Internal { - namespace Adaptor { - namespace WindowSystem { - void Initialize() { } -void GetScreenSize( int& width, int& height ) +void GetScreenSize(int& width, int& height) { - width = GetSystemMetrics( SM_CXSCREEN ); - height = GetSystemMetrics( SM_CYSCREEN ); + width = GetSystemMetrics(SM_CXSCREEN); + height = GetSystemMetrics(SM_CYSCREEN); } -bool SetKeyboardRepeatInfo( float rate, float delay ) +bool SetKeyboardRepeatInfo(float rate, float delay) { return false; } -bool GetKeyboardRepeatInfo( float& rate, float& delay ) +bool GetKeyboardRepeatInfo(float& rate, float& delay) { return false; } @@ -60,4 +56,3 @@ bool GetKeyboardRepeatInfo( float& rate, float& delay ) } // namespace Internal } // namespace Dali - diff --git a/dali/public-api/adaptor-framework/input-method.h b/dali/public-api/adaptor-framework/input-method.h index 0cf9b1a..40741c4 100644 --- a/dali/public-api/adaptor-framework/input-method.h +++ b/dali/public-api/adaptor-framework/input-method.h @@ -2,7 +2,7 @@ #define DALI_INPUT_MEHTOD_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,15 +109,15 @@ namespace ButtonAction */ enum Type { - DEFAULT, ///< Default action @SINCE_1_3.20 - DONE, ///< Done @SINCE_1_3.20 - GO, ///< Go action @SINCE_1_3.20 - JOIN, ///< Join action @SINCE_1_3.20 - LOGIN, ///< Login action @SINCE_1_3.20 - NEXT, ///< Next action @SINCE_1_3.20 - SEARCH, ///< Search action @SINCE_1_3.20 - SEND, ///< Send action @SINCE_1_3.20 - SIGNIN ///< Sign in action @SINCE_1_3.20 + DEFAULT, ///< Default action @SINCE_1_3.20 + DONE, ///< Done @SINCE_1_3.20 + GO, ///< Go action @SINCE_1_3.20 + JOIN, ///< Join action @SINCE_1_3.20 + LOGIN, ///< Login action @SINCE_1_3.20 + NEXT, ///< Next action @SINCE_1_3.20 + SEARCH, ///< Search action @SINCE_1_3.20 + SEND, ///< Send action @SINCE_1_3.20 + SIGNIN ///< Sign in action @SINCE_1_3.20 }; } // namespace ButtonAction diff --git a/dali/public-api/adaptor-framework/window-enumerations.h b/dali/public-api/adaptor-framework/window-enumerations.h index 0abae45..22895ca 100644 --- a/dali/public-api/adaptor-framework/window-enumerations.h +++ b/dali/public-api/adaptor-framework/window-enumerations.h @@ -2,7 +2,7 @@ #define DALI_WINDOW_ENUMERATIONS_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,6 +93,6 @@ enum class WindowEffectType HIDE, ///< Window hide effect. @SINCE_2_0.0 }; -} +} // namespace Dali #endif // DALI_WINDOW_ENUMERATIONS_H diff --git a/dali/public-api/adaptor-framework/window.h b/dali/public-api/adaptor-framework/window.h index 527da6b..759dfcd 100644 --- a/dali/public-api/adaptor-framework/window.h +++ b/dali/public-api/adaptor-framework/window.h @@ -2,7 +2,7 @@ #define DALI_WINDOW_H /* - * Copyright (c) 2020 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ */ // EXTERNAL INCLUDES +#include #include #include #include @@ -26,7 +27,6 @@ #include #include #include -#include #include // INTERNAL INCLUDES @@ -79,7 +79,6 @@ public: using TouchEventSignalType = Signal; ///< Touch signal type @SINCE_1_9.28 public: - // Methods /** diff --git a/dali/public-api/dali-adaptor-version.cpp b/dali/public-api/dali-adaptor-version.cpp index 774b3ef..956b322 100644 --- a/dali/public-api/dali-adaptor-version.cpp +++ b/dali/public-api/dali-adaptor-version.cpp @@ -27,7 +27,7 @@ namespace Dali { const unsigned int ADAPTOR_MAJOR_VERSION = 2; const unsigned int ADAPTOR_MINOR_VERSION = 0; -const unsigned int ADAPTOR_MICRO_VERSION = 11; +const unsigned int ADAPTOR_MICRO_VERSION = 12; const char* const ADAPTOR_BUILD_DATE = __DATE__ " " __TIME__; #ifdef DEBUG_ENABLED diff --git a/doc/dali-adaptor-doc.h b/doc/dali-adaptor-doc.h index bdded7b..955b856 100644 --- a/doc/dali-adaptor-doc.h +++ b/doc/dali-adaptor-doc.h @@ -2,7 +2,7 @@ #define DALI_ADAPTOR_DOC_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,4 +66,4 @@ * @} */ -#endif /* DALI_ADAPTOR_DOC_H */ +#endif /* DALI_ADAPTOR_DOC_H */ diff --git a/packaging/dali-adaptor.spec b/packaging/dali-adaptor.spec index 68e8a93..f5cd49f 100644 --- a/packaging/dali-adaptor.spec +++ b/packaging/dali-adaptor.spec @@ -17,7 +17,7 @@ Name: dali2-adaptor Summary: The DALi Tizen Adaptor -Version: 2.0.11 +Version: 2.0.12 Release: 1 Group: System/Libraries License: Apache-2.0 and BSD-3-Clause and MIT diff --git a/plugins/dali-feedback.cpp b/plugins/dali-feedback.cpp index 68dcc04..f4c79b6 100644 --- a/plugins/dali-feedback.cpp +++ b/plugins/dali-feedback.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,15 @@ #include "dali-feedback.h" // EXTERNAL INCLUDES -#include -#include #include #include #include +#include +#include #include -#define DEBUG_PRINTF(fmt, arg...) LOGD(" " fmt, ##arg) +#define DEBUG_PRINTF(fmt, arg...) LOGD(" " fmt, ##arg) using std::string; using namespace Dali; @@ -42,10 +42,8 @@ extern "C" DALI_ADAPTOR_API Dali::FeedbackPlugin* CreateFeedbackPlugin(void) namespace Dali { - namespace Plugin { - DaliFeedback::DaliFeedback() { feedback_initialize(); @@ -56,11 +54,11 @@ DaliFeedback::~DaliFeedback() feedback_deinitialize(); } -void DaliFeedback::PlayHaptic( const std::string& filePath ) +void DaliFeedback::PlayHaptic(const std::string& filePath) { } -void DaliFeedback::PlayHapticMonotone( unsigned int duration ) +void DaliFeedback::PlayHapticMonotone(unsigned int duration) { } @@ -68,41 +66,40 @@ void DaliFeedback::StopHaptic() { } -int DaliFeedback::PlaySound( const std::string& fileName ) +int DaliFeedback::PlaySound(const std::string& fileName) { - int handle = -1; - int errorCode = mm_sound_play_keysound( fileName.c_str(), VOLUME_TYPE_SYSTEM & VOLUME_GAIN_TOUCH ); - if( errorCode < 0 ) + int handle = -1; + int errorCode = mm_sound_play_keysound(fileName.c_str(), VOLUME_TYPE_SYSTEM & VOLUME_GAIN_TOUCH); + if(errorCode < 0) { - DEBUG_PRINTF( "PlaySound() %s failed with error code = %d\n", fileName.c_str(), errorCode ); + DEBUG_PRINTF("PlaySound() %s failed with error code = %d\n", fileName.c_str(), errorCode); } return handle; } -void DaliFeedback::StopSound( int handle ) +void DaliFeedback::StopSound(int handle) { - int errorCode = mm_sound_stop_keysound( NULL ); - if( errorCode < 0 ) + int errorCode = mm_sound_stop_keysound(NULL); + if(errorCode < 0) { - DEBUG_PRINTF( "StopSound() handle = %d failed with error code = %d\n", handle, errorCode); + DEBUG_PRINTF("StopSound() handle = %d failed with error code = %d\n", handle, errorCode); } else { - DEBUG_PRINTF( "stop handle %d success\n", handle ); + DEBUG_PRINTF("stop handle %d success\n", handle); } } -void DaliFeedback::PlayFeedbackPattern( int type, int pattern ) +void DaliFeedback::PlayFeedbackPattern(int type, int pattern) { - int errorCode = feedback_play_type( static_cast(type), static_cast(pattern) ); - if( errorCode != 0 ) + int errorCode = feedback_play_type(static_cast(type), static_cast(pattern)); + if(errorCode != 0) { - DEBUG_PRINTF( "DaliFeedback::PlayFeedbackPattern() with type = %d, pattern = %d returned with error = %d\n", (int)type, (int)pattern, errorCode ); + DEBUG_PRINTF("DaliFeedback::PlayFeedbackPattern() with type = %d, pattern = %d returned with error = %d\n", (int)type, (int)pattern, errorCode); } } } // namespace Plugin } // namespace Dali - diff --git a/plugins/dali-feedback.h b/plugins/dali-feedback.h index 93c63d2..03b9de2 100644 --- a/plugins/dali-feedback.h +++ b/plugins/dali-feedback.h @@ -2,7 +2,7 @@ #define FEEDBACK_PLUGIN_H /* - * Copyright (c) 2019 Samsung Electronics Co., Ltd. + * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,18 +23,14 @@ namespace Dali { - namespace Plugin { - /** * Plays feedback effects for Dali-Toolkit UI Controls. */ class DaliFeedback : public Dali::FeedbackPlugin { - public: // Construction & Destruction - /** * Constructor */ @@ -46,16 +42,15 @@ public: // Construction & Destruction virtual ~DaliFeedback(); public: // FeedbackPlugin overrides - /** * @copydoc Dali::Integration::FeedbackPlugin::PlayHaptic() */ - void PlayHaptic( const std::string& filePath ); + void PlayHaptic(const std::string& filePath); /** * @copydoc Dali::FeedbackPlugin::PlayHapticMonotone() */ - void PlayHapticMonotone( unsigned int duration ); + void PlayHapticMonotone(unsigned int duration); /** * @copydoc Dali::FeedbackPlugin::StopHaptic() @@ -65,21 +60,21 @@ public: // FeedbackPlugin overrides /** * @copydoc Dali::FeedbackPlugin::PlaySound() */ - int PlaySound( const std::string& fileName ); + int PlaySound(const std::string& fileName); /** * @copydoc Dali::FeedbackPlugin::StopSound() */ - void StopSound( int handle ); + void StopSound(int handle); /** * @copydoc Dali::FeedbackPlugin::PlayFeedbackPattern() */ - void PlayFeedbackPattern( int type, int pattern ); + void PlayFeedbackPattern(int type, int pattern); }; -} // namespace Plugin +} // namespace Plugin -} // namespace Dali +} // namespace Dali #endif // FEEDBACK_PLUGIN_H