From f2039d47f9bed8104575da80a2ecf0bb6e37ff8d Mon Sep 17 00:00:00 2001 From: Adeel Kazmi Date: Wed, 3 Feb 2021 16:49:03 +0000 Subject: [PATCH] Updated all cpp files to new format Change-Id: If92183926ff6584c5d05efda672b422b9dd9a322 --- .../src/dali-toolkit/utc-Dali-Alignment.cpp | 10 +- .../src/dali-toolkit/utc-Dali-BubbleEmitter.cpp | 4 +- dali-scene-loader/internal/gltf2-asset.cpp | 55 +- dali-scene-loader/internal/hash.cpp | 20 +- dali-scene-loader/internal/json-reader.cpp | 27 +- dali-scene-loader/internal/json-util.cpp | 352 +++-- .../public-api/alpha-function-helper.cpp | 23 +- dali-scene-loader/public-api/animated-property.cpp | 15 +- .../public-api/animation-definition.cpp | 26 +- .../public-api/blend-shape-details.cpp | 25 +- dali-scene-loader/public-api/camera-parameters.cpp | 97 +- dali-scene-loader/public-api/customization.cpp | 32 +- dali-scene-loader/public-api/dli-loader.cpp | 980 +++++++------ .../public-api/environment-definition.cpp | 24 +- dali-scene-loader/public-api/gltf2-loader.cpp | 748 +++++----- dali-scene-loader/public-api/ktx-loader.cpp | 296 ++-- .../public-api/material-definition.cpp | 116 +- dali-scene-loader/public-api/matrix-stack.cpp | 11 +- dali-scene-loader/public-api/mesh-definition.cpp | 454 +++--- dali-scene-loader/public-api/node-definition.cpp | 55 +- .../public-api/parse-renderer-state.cpp | 98 +- dali-scene-loader/public-api/renderer-state.cpp | 30 +- dali-scene-loader/public-api/resource-bundle.cpp | 78 +- dali-scene-loader/public-api/scene-definition.cpp | 631 ++++---- .../public-api/shader-definition-factory.cpp | 154 +- dali-scene-loader/public-api/shader-definition.cpp | 51 +- dali-scene-loader/public-api/skinning-details.cpp | 11 +- dali-scene-loader/public-api/string-callback.cpp | 7 +- dali-scene-loader/public-api/utils.cpp | 48 +- dali-scene-loader/public-api/view-projection.cpp | 9 +- dali-toolkit/devel-api/builder/tree-node.cpp | 3 +- dali-toolkit/devel-api/controls/control-devel.cpp | 164 +-- .../web-view/web-back-forward-list-item.cpp | 7 +- .../controls/web-view/web-back-forward-list.cpp | 15 +- .../devel-api/controls/web-view/web-context.cpp | 27 +- .../controls/web-view/web-cookie-manager.cpp | 15 +- .../devel-api/controls/web-view/web-settings.cpp | 43 +- .../devel-api/controls/web-view/web-view.cpp | 24 +- dali-toolkit/devel-api/layouting/flex-node.cpp | 4 +- .../shader-effects/alpha-discard-effect.cpp | 3 +- .../devel-api/shader-effects/dissolve-effect.cpp | 8 +- .../shader-effects/distance-field-effect.cpp | 6 +- .../shader-effects/image-region-effect.cpp | 7 +- .../shader-effects/motion-blur-effect.cpp | 10 +- .../shader-effects/motion-stretch-effect.cpp | 10 +- dali-toolkit/devel-api/text/text-utils-devel.cpp | 9 +- .../accessibility-manager-impl.cpp | 101 +- .../internal/builder/builder-animations.cpp | 258 ++-- .../internal/builder/builder-impl-debug.cpp | 26 +- dali-toolkit/internal/builder/builder-impl.cpp | 898 ++++++------ .../internal/builder/builder-set-property.cpp | 264 ++-- dali-toolkit/internal/builder/builder-signals.cpp | 376 ++--- dali-toolkit/internal/builder/json-parser-impl.cpp | 71 +- .../internal/builder/json-parser-state.cpp | 269 ++-- dali-toolkit/internal/builder/replacement.cpp | 315 ++-- dali-toolkit/internal/builder/style.cpp | 127 +- .../internal/builder/tree-node-manipulator.cpp | 122 +- .../internal/controls/alignment/alignment-impl.cpp | 133 +- .../controls/bloom-view/bloom-view-impl.cpp | 309 ++-- .../controls/bubble-effect/bubble-emitter-impl.cpp | 259 ++-- .../controls/bubble-effect/bubble-renderer.cpp | 89 +- .../internal/controls/buttons/button-impl.cpp | 860 ++++++----- .../controls/buttons/check-box-button-impl.cpp | 42 +- .../internal/controls/buttons/push-button-impl.cpp | 133 +- .../controls/buttons/radio-button-impl.cpp | 46 +- .../controls/buttons/toggle-button-impl.cpp | 258 ++-- .../controls/control/control-data-impl.cpp | 1413 +++++++++--------- .../internal/controls/control/control-debug.cpp | 174 +-- .../controls/control/control-renderers.cpp | 122 +- .../controls/effects-view/effects-view-impl.cpp | 406 ++--- .../flex-container/flex-container-impl.cpp | 567 ++++--- .../gaussian-blur-view/gaussian-blur-view-impl.cpp | 336 ++--- .../controls/image-view/image-view-impl.cpp | 365 +++-- .../internal/controls/magnifier/magnifier-impl.cpp | 157 +- .../controls/model3d-view/model3d-view-impl.cpp | 231 ++- .../internal/controls/model3d-view/obj-loader.cpp | 367 +++-- .../navigation-view/navigation-view-impl.cpp | 38 +- .../controls/page-turn-view/page-turn-effect.cpp | 114 +- .../page-turn-landscape-view-impl.cpp | 51 +- .../page-turn-portrait-view-impl.cpp | 86 +- .../page-turn-view/page-turn-view-impl.cpp | 707 +++++---- .../controls/popup/confirmation-popup-impl.cpp | 113 +- .../internal/controls/popup/popup-impl.cpp | 1100 +++++++------- .../controls/progress-bar/progress-bar-impl.cpp | 448 +++--- .../internal/controls/scene3d-view/gltf-loader.cpp | 1449 +++++++++--------- .../controls/scene3d-view/scene3d-view-impl.cpp | 194 ++- .../controls/scroll-bar/scroll-bar-impl.cpp | 418 +++--- .../controls/scrollable/bouncing-effect-actor.cpp | 81 +- .../controls/scrollable/item-view/depth-layout.cpp | 317 ++-- .../controls/scrollable/item-view/grid-layout.cpp | 439 +++--- .../scrollable/item-view/item-view-impl.cpp | 851 ++++++----- .../scrollable/item-view/spiral-layout.cpp | 329 ++--- .../scrollable/scroll-view/scroll-base-impl.cpp | 19 +- .../scroll-overshoot-indicator-impl.cpp | 171 ++- .../scroll-view/scroll-view-effect-impl.cpp | 11 +- .../scrollable/scroll-view/scroll-view-impl.cpp | 1260 ++++++++-------- .../scroll-view-page-path-effect-impl.cpp | 54 +- .../controls/scrollable/scrollable-impl.cpp | 136 +- .../controls/shadow-view/shadow-view-impl.cpp | 201 ++- .../internal/controls/slider/slider-impl.cpp | 813 +++++----- .../super-blur-view/super-blur-view-impl.cpp | 259 ++-- .../controls/table-view/table-view-impl.cpp | 1037 +++++++------ .../controls/text-controls/text-editor-impl.cpp | 1416 +++++++++--------- .../controls/text-controls/text-field-impl.cpp | 1330 +++++++++-------- .../controls/text-controls/text-label-impl.cpp | 805 +++++----- .../text-controls/text-selection-popup-impl.cpp | 823 ++++++----- .../text-controls/text-selection-toolbar-impl.cpp | 262 ++-- .../internal/controls/tool-bar/tool-bar-impl.cpp | 164 +-- dali-toolkit/internal/controls/tooltip/tooltip.cpp | 454 +++--- .../controls/video-view/video-view-impl.cpp | 515 ++++--- .../internal/controls/web-view/web-view-impl.cpp | 414 +++--- .../drag-and-drop-detector-impl.cpp | 92 +- dali-toolkit/internal/feedback/feedback-style.cpp | 197 ++- .../internal/filters/blur-two-pass-filter.cpp | 200 ++- dali-toolkit/internal/filters/emboss-filter.cpp | 180 ++- dali-toolkit/internal/filters/image-filter.cpp | 52 +- dali-toolkit/internal/filters/spread-filter.cpp | 117 +- .../focus-manager/keyboard-focus-manager-impl.cpp | 434 +++--- .../focus-manager/keyinput-focus-manager-impl.cpp | 89 +- dali-toolkit/internal/helpers/color-conversion.cpp | 56 +- dali-toolkit/internal/helpers/property-helper.cpp | 15 +- .../image-loader/async-image-loader-impl.cpp | 67 +- .../internal/image-loader/atlas-packer.cpp | 196 ++- .../internal/image-loader/image-atlas-impl.cpp | 214 ++- .../internal/image-loader/image-load-thread.cpp | 162 +- .../internal/styling/style-manager-impl.cpp | 245 ++-- .../internal/text/bidirectional-support.cpp | 201 ++- .../internal/text/character-set-conversion.cpp | 214 +-- dali-toolkit/internal/text/color-segmentation.cpp | 75 +- .../internal/text/cursor-helper-functions.cpp | 487 +++--- .../internal/text/decorator/text-decorator.cpp | 1551 ++++++++++---------- .../internal/text/glyph-metrics-helper.cpp | 63 +- dali-toolkit/internal/text/hidden-text.cpp | 127 +- .../internal/text/layouts/layout-engine.cpp | 1266 ++++++++-------- dali-toolkit/internal/text/logical-model-impl.cpp | 360 +++-- .../internal/text/markup-processor-color.cpp | 19 +- .../text/markup-processor-embedded-item.cpp | 39 +- .../internal/text/markup-processor-font.cpp | 55 +- .../text/markup-processor-helper-functions.cpp | 185 ++- dali-toolkit/internal/text/markup-processor.cpp | 417 +++--- .../text/multi-language-helper-functions.cpp | 115 +- .../internal/text/multi-language-support-impl.cpp | 476 +++--- .../internal/text/multi-language-support.cpp | 55 +- .../internal/text/property-string-parser.cpp | 23 +- .../rendering/atlas/atlas-glyph-manager-impl.cpp | 175 ++- .../text/rendering/atlas/atlas-glyph-manager.cpp | 66 +- .../text/rendering/atlas/atlas-manager-impl.cpp | 370 +++-- .../text/rendering/atlas/atlas-manager.cpp | 78 +- .../text/rendering/atlas/atlas-mesh-factory.cpp | 126 +- .../text/rendering/atlas/text-atlas-renderer.cpp | 940 ++++++------ .../internal/text/rendering/text-backend-impl.cpp | 30 +- .../internal/text/rendering/text-backend.cpp | 19 +- .../internal/text/rendering/text-renderer.cpp | 3 - .../internal/text/rendering/text-typesetter.cpp | 559 ++++--- .../vector-based/glyphy-shader/glyphy-shader.cpp | 315 ++-- .../vector-based/vector-based-renderer.cpp | 280 ++-- .../vector-based/vector-blob-atlas-share.cpp | 51 +- .../rendering/vector-based/vector-blob-atlas.cpp | 135 +- .../internal/text/rendering/view-model.cpp | 119 +- dali-toolkit/internal/text/segmentation.cpp | 105 +- dali-toolkit/internal/text/shaper.cpp | 161 +- .../text/text-controller-event-handler.cpp | 477 +++--- .../text/text-controller-impl-event-handler.cpp | 609 ++++---- .../internal/text/text-controller-impl.cpp | 1494 ++++++++++--------- .../text/text-controller-input-font-handler.cpp | 308 ++-- .../text/text-controller-placeholder-handler.cpp | 259 ++-- .../internal/text/text-controller-relayouter.cpp | 465 +++--- .../internal/text/text-controller-text-updater.cpp | 340 +++-- dali-toolkit/internal/text/text-controller.cpp | 847 ++++++----- dali-toolkit/internal/text/text-effects-style.cpp | 480 +++--- .../internal/text/text-enumerations-impl.cpp | 65 +- dali-toolkit/internal/text/text-font-style.cpp | 340 +++-- dali-toolkit/internal/text/text-io.cpp | 43 +- dali-toolkit/internal/text/text-model.cpp | 29 +- dali-toolkit/internal/text/text-scroller.cpp | 194 ++- .../text/text-selection-handle-controller.cpp | 326 ++-- .../internal/text/text-vertical-scroller.cpp | 34 +- dali-toolkit/internal/text/text-view-interface.cpp | 3 - dali-toolkit/internal/text/text-view.cpp | 193 ++- dali-toolkit/internal/text/visual-model-impl.cpp | 250 ++-- dali-toolkit/internal/text/xhtml-entities.cpp | 535 ++++--- .../cube-transition-cross-effect-impl.cpp | 89 +- .../cube-transition-effect-impl.cpp | 335 +++-- .../cube-transition-fold-effect-impl.cpp | 78 +- .../cube-transition-wave-effect-impl.cpp | 113 +- .../animated-gradient/animated-gradient-visual.cpp | 538 ++++--- .../animated-image/animated-image-visual.cpp | 446 +++--- .../visuals/animated-image/fixed-image-cache.cpp | 98 +- .../visuals/animated-image/image-cache.cpp | 21 +- .../rolling-animated-image-cache.cpp | 160 +- .../visuals/animated-image/rolling-image-cache.cpp | 149 +- .../animated-vector-image-visual.cpp | 362 +++-- .../vector-animation-manager.cpp | 66 +- .../vector-animation-task.cpp | 344 +++-- .../vector-animation-thread.cpp | 214 ++- .../vector-rasterize-thread.cpp | 64 +- dali-toolkit/internal/visuals/arc/arc-visual.cpp | 154 +- .../internal/visuals/border/border-visual.cpp | 201 +-- .../internal/visuals/color/color-visual.cpp | 113 +- .../internal/visuals/gradient/gradient-visual.cpp | 337 ++--- .../internal/visuals/gradient/gradient.cpp | 107 +- .../internal/visuals/gradient/linear-gradient.cpp | 20 +- .../internal/visuals/gradient/radial-gradient.cpp | 14 +- .../internal/visuals/image-atlas-manager.cpp | 81 +- .../visuals/image-visual-shader-factory.cpp | 64 +- .../internal/visuals/image/image-visual.cpp | 539 ++++--- dali-toolkit/internal/visuals/mesh/mesh-visual.cpp | 301 ++-- dali-toolkit/internal/visuals/npatch-data.cpp | 43 +- dali-toolkit/internal/visuals/npatch-loader.cpp | 76 +- .../internal/visuals/npatch/npatch-visual.cpp | 480 +++--- .../visuals/primitive/primitive-visual.cpp | 1057 +++++++------ .../internal/visuals/svg/svg-rasterize-thread.cpp | 114 +- dali-toolkit/internal/visuals/svg/svg-visual.cpp | 148 +- dali-toolkit/internal/visuals/text/text-visual.cpp | 581 ++++---- .../internal/visuals/texture-manager-impl.cpp | 863 +++++------ .../internal/visuals/texture-upload-observer.cpp | 9 +- .../internal/visuals/transition-data-impl.cpp | 234 ++- .../internal/visuals/visual-base-data-impl.cpp | 287 ++-- dali-toolkit/internal/visuals/visual-base-impl.cpp | 396 +++-- .../internal/visuals/visual-factory-cache.cpp | 143 +- .../internal/visuals/visual-factory-impl.cpp | 221 ++- .../internal/visuals/visual-string-constants.cpp | 247 ++-- dali-toolkit/internal/visuals/visual-url.cpp | 169 +-- .../visuals/wireframe/wireframe-visual.cpp | 133 +- dali-toolkit/public-api/controls/control-impl.cpp | 51 +- docs/content/example-code/properties.cpp | 69 +- 226 files changed, 29504 insertions(+), 30507 deletions(-) mode change 100755 => 100644 dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp mode change 100755 => 100644 dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp mode change 100755 => 100644 dali-toolkit/devel-api/controls/web-view/web-context.cpp mode change 100755 => 100644 dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp mode change 100755 => 100644 dali-toolkit/devel-api/controls/web-view/web-settings.cpp mode change 100755 => 100644 dali-toolkit/devel-api/controls/web-view/web-view.cpp mode change 100755 => 100644 dali-toolkit/devel-api/text/text-utils-devel.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/control/control-data-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/flex-container/flex-container-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/scrollable/item-view/depth-layout.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/scrollable/item-view/grid-layout.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/table-view/table-view-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/text-controls/text-label-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/video-view/video-view-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/controls/web-view/web-view-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/text/bidirectional-support.cpp mode change 100755 => 100644 dali-toolkit/internal/text/glyph-metrics-helper.cpp mode change 100755 => 100644 dali-toolkit/internal/text/layouts/layout-engine.cpp mode change 100755 => 100644 dali-toolkit/internal/text/logical-model-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/text/markup-processor-embedded-item.cpp mode change 100755 => 100644 dali-toolkit/internal/text/markup-processor-helper-functions.cpp mode change 100755 => 100644 dali-toolkit/internal/text/markup-processor.cpp mode change 100755 => 100644 dali-toolkit/internal/text/multi-language-support-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.cpp mode change 100755 => 100644 dali-toolkit/internal/text/rendering/text-typesetter.cpp mode change 100755 => 100644 dali-toolkit/internal/text/rendering/view-model.cpp mode change 100755 => 100644 dali-toolkit/internal/text/shaper.cpp mode change 100755 => 100644 dali-toolkit/internal/text/text-effects-style.cpp mode change 100755 => 100644 dali-toolkit/internal/text/text-model.cpp mode change 100755 => 100644 dali-toolkit/internal/text/text-scroller.cpp mode change 100755 => 100644 dali-toolkit/internal/text/text-view.cpp mode change 100755 => 100644 dali-toolkit/internal/text/visual-model-impl.cpp mode change 100755 => 100644 dali-toolkit/internal/text/xhtml-entities.cpp mode change 100755 => 100644 dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.cpp mode change 100755 => 100644 dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp mode change 100755 => 100644 dali-toolkit/internal/visuals/text/text-visual.cpp mode change 100755 => 100644 dali-toolkit/internal/visuals/visual-base-impl.cpp diff --git a/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp b/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp index d3aba7e..f4b809d 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-Alignment.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-Alignment.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. @@ -844,7 +844,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } try @@ -855,7 +855,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } try @@ -866,7 +866,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } try @@ -877,7 +877,7 @@ int UtcDaliAlignmentSetPaddingNegative(void) } catch (DaliException& e) { - DALI_TEST_ASSERT(e, "( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f )", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "(padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)", TEST_LOCATION ); } END_TEST; } diff --git a/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp b/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp index 1c46455..b5a0d5f 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-BubbleEmitter.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. @@ -259,7 +259,7 @@ int UtcDaliBubbleEmitterSetBubbleDensity02(void) catch(Dali::DaliException& e) { DALI_TEST_PRINT_ASSERT( e ); - DALI_TEST_ASSERT(e, "density>0 && density<=9", TEST_LOCATION ); + DALI_TEST_ASSERT(e, "density > 0 && density <= 9", TEST_LOCATION ); } END_TEST; } diff --git a/dali-scene-loader/internal/gltf2-asset.cpp b/dali-scene-loader/internal/gltf2-asset.cpp index e77a6f5..d0e183a 100644 --- a/dali-scene-loader/internal/gltf2-asset.cpp +++ b/dali-scene-loader/internal/gltf2-asset.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,11 +15,14 @@ * */ #include "dali-scene-loader/internal/gltf2-asset.h" -#include "dali/public-api/math/matrix.h" #include #include +#include "dali/public-api/math/matrix.h" -#define ENUM_STRING_MAPPING(t, x) { #x, t::x } +#define ENUM_STRING_MAPPING(t, x) \ + { \ +#x, t::x \ + } using namespace Dali; @@ -27,7 +30,6 @@ namespace gltf2 { namespace { - constexpr uint32_t ACCESSOR_TYPE_ELEMENT_COUNT[]{ 1, 2, @@ -36,8 +38,7 @@ constexpr uint32_t ACCESSOR_TYPE_ELEMENT_COUNT[]{ 4, 9, 16, - static_cast(-1) -}; + static_cast(-1)}; const std::map ACCESSOR_TYPES{ ENUM_STRING_MAPPING(AccessorType, SCALAR), @@ -79,7 +80,7 @@ const std::map ANIMATION_CHA ENUM_STRING_MAPPING(Animation::Channel::Target::Type, WEIGHTS), }; -} +} // namespace bool Component::IsUnsigned(Type t) { @@ -88,19 +89,19 @@ bool Component::IsUnsigned(Type t) uint32_t Component::Size(Type t) { - switch (t) + switch(t) { - case BYTE: - case UNSIGNED_BYTE: - return 1; - case SHORT: - case UNSIGNED_SHORT: - return 2; - case UNSIGNED_INT: - case FLOAT: - return 4; - default: - return -1; + case BYTE: + case UNSIGNED_BYTE: + return 1; + case SHORT: + case UNSIGNED_SHORT: + return 2; + case UNSIGNED_INT: + case FLOAT: + return 4; + default: + return -1; } } @@ -112,7 +113,7 @@ uint32_t AccessorType::ElementCount(Type t) AccessorType::Type AccessorType::FromString(const char* s, size_t len) { auto iFind = ACCESSOR_TYPES.find(std::string_view(s, len)); - if (iFind != ACCESSOR_TYPES.end()) + if(iFind != ACCESSOR_TYPES.end()) { return iFind->second; } @@ -122,7 +123,7 @@ AccessorType::Type AccessorType::FromString(const char* s, size_t len) AlphaMode::Type AlphaMode::FromString(const char* s, size_t len) { auto iFind = ALPHA_MODE_TYPES.find(std::string_view(s, len)); - if (iFind != ALPHA_MODE_TYPES.end()) + if(iFind != ALPHA_MODE_TYPES.end()) { return iFind->second; } @@ -132,7 +133,7 @@ AlphaMode::Type AlphaMode::FromString(const char* s, size_t len) Attribute::Type Attribute::FromString(const char* s, size_t len) { auto iFind = ATTRIBUTE_TYPES.find(std::string_view(s, len)); - if (iFind != ATTRIBUTE_TYPES.end()) + if(iFind != ATTRIBUTE_TYPES.end()) { return iFind->second; } @@ -142,7 +143,7 @@ Attribute::Type Attribute::FromString(const char* s, size_t len) Animation::Sampler::Interpolation::Type Animation::Sampler::Interpolation::FromString(const char* s, size_t len) { auto iFind = ANIMATION_SAMPLER_INTERPOLATION.find(std::string_view(s, len)); - if (iFind != ANIMATION_SAMPLER_INTERPOLATION.end()) + if(iFind != ANIMATION_SAMPLER_INTERPOLATION.end()) { return iFind->second; } @@ -160,7 +161,7 @@ Animation::Channel::Target::Type Animation::Channel::Target::FromString(const ch std::transform(target.begin(), target.end(), target.begin(), ::toupper); auto iFind = ANIMATION_CHANNEL_TARGET_PATH_TYPES.find(std::string_view(target.c_str(), len)); - if (iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end()) + if(iFind != ANIMATION_CHANNEL_TARGET_PATH_TYPES.end()) { return iFind->second; } @@ -172,9 +173,9 @@ void Node::SetMatrix(const Matrix& m) m.GetTransformComponents(mTranslation, mRotation, mScale); } -Quaternion ReadQuaternion(const json_value_s & j) +Quaternion ReadQuaternion(const json_value_s& j) { - return Quaternion(ReadDaliVector(j)); + return Quaternion(ReadDaliVector(j)); } -} +} // namespace gltf2 diff --git a/dali-scene-loader/internal/hash.cpp b/dali-scene-loader/internal/hash.cpp index e863f0a..43d410f 100644 --- a/dali-scene-loader/internal/hash.cpp +++ b/dali-scene-loader/internal/hash.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,10 +20,10 @@ namespace Dali { namespace SceneLoader { - Hash::Hash(uint64_t initial) : mValue(initial) -{} +{ +} Hash& Hash::Add(bool b) { @@ -54,26 +54,26 @@ Hash& Hash::Add(float f) return AddObjectBytes(f); } -Hash& Hash::Add(const char * cStr) +Hash& Hash::Add(const char* cStr) { return Add(cStr, strlen(cStr)); } -Hash& Hash::Add(const char * cStr, size_t len) +Hash& Hash::Add(const char* cStr, size_t len) { auto i0 = reinterpret_cast(cStr); return AddBytes(i0, i0 + len); } -Hash& Hash::Add(const std::string & str) +Hash& Hash::Add(const std::string& str) { auto i0 = reinterpret_cast(str.c_str()); return AddBytes(i0, i0 + str.size()); } -Hash& Hash::AddBytes(const uint8_t * i0, const uint8_t * i1) +Hash& Hash::AddBytes(const uint8_t* i0, const uint8_t* i1) { - while (i0 != i1) + while(i0 != i1) { mValue = Concatenate(*i0); ++i0; @@ -91,5 +91,5 @@ uint64_t Hash::Concatenate(uint64_t value) return mValue * 31 + value; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/internal/json-reader.cpp b/dali-scene-loader/internal/json-reader.cpp index 6b12d1d..0353817 100644 --- a/dali-scene-loader/internal/json-reader.cpp +++ b/dali-scene-loader/internal/json-reader.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,28 +20,25 @@ namespace json { - int StrCmp(const json_string_s& js, const char* s) { - auto sSize = strlen(s); + auto sSize = strlen(s); auto shorter = std::min(js.string_size, sSize); - auto base = strncmp(js.string, s, shorter); - return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? - -s[shorter] : js.string[shorter]); + auto base = strncmp(js.string, s, shorter); + return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]); } int StrCmp(const json_string_s& js, const std::string& s) { - auto sSize = s.size(); + auto sSize = s.size(); auto shorter = std::min(js.string_size, sSize); - auto base = strncmp(js.string, s.c_str(), shorter); - return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? - -s[shorter] : js.string[shorter]); + auto base = strncmp(js.string, s.c_str(), shorter); + return ((base != 0) || (sSize == js.string_size)) ? base : ((js.string_size < sSize) ? -s[shorter] : js.string[shorter]); } -void Validate(const json_value_s & jv, json_type_e type) +void Validate(const json_value_s& jv, json_type_e type) { - if (jv.type != type) + if(jv.type != type) { throw std::runtime_error("Invalid type; expected: " + std::to_string(type) + ", got: " + std::to_string(jv.type)); } @@ -50,9 +47,9 @@ void Validate(const json_value_s & jv, json_type_e type) json_value_s* FindObjectChild(const std::string& key, json_object_s& obj) { auto i = obj.start; - while (i) + while(i) { - if (0 == StrCmp(*i->name, key)) + if(0 == StrCmp(*i->name, key)) { return i->value; } @@ -61,4 +58,4 @@ json_value_s* FindObjectChild(const std::string& key, json_object_s& obj) return nullptr; } -} +} // namespace json diff --git a/dali-scene-loader/internal/json-util.cpp b/dali-scene-loader/internal/json-util.cpp index 613a764..765568d 100644 --- a/dali-scene-loader/internal/json-util.cpp +++ b/dali-scene-loader/internal/json-util.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. @@ -17,16 +17,16 @@ #include "dali-scene-loader/internal/json-util.h" // EXTERNAL INCLUDES +#include +#include "dali/devel-api/common/map-wrapper.h" #include "dali/public-api/common/extents.h" -#include "dali/public-api/math/matrix3.h" #include "dali/public-api/math/matrix.h" +#include "dali/public-api/math/matrix3.h" #include "dali/public-api/math/quaternion.h" #include "dali/public-api/math/radian.h" #include "dali/public-api/math/vector2.h" #include "dali/public-api/math/vector3.h" #include "dali/public-api/object/property-value.h" -#include "dali/devel-api/common/map-wrapper.h" -#include namespace Dali { @@ -36,24 +36,23 @@ namespace SceneLoader { namespace { - -template -Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool(*reader)(const TreeNode*, T&)) +template +Property::Value ReadPrimitiveHelper(const TreeNode* tn, bool (*reader)(const TreeNode*, T&)) { T value; - if (reader(tn, value)) + if(reader(tn, value)) { return Property::Value(value); } return Property::Value(); } -template +template Property::Value ReadVectorHelper(const TreeNode* tn) { static_assert(sizeof(T) % sizeof(float) == 0, ""); T value; - if (ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float))) + if(ReadVector(tn, value.AsFloat(), sizeof(T) / sizeof(float))) { return Property::Value(value); } @@ -63,7 +62,7 @@ Property::Value ReadVectorHelper(const TreeNode* tn) Property::Value ReadVectorSingleFloatHelper(const TreeNode* tn) { float value; - if (ReadVector(tn, &value, 1u)) + if(ReadVector(tn, &value, 1u)) { return Property::Value(value); } @@ -72,39 +71,39 @@ Property::Value ReadVectorSingleFloatHelper(const TreeNode* tn) Property::Value ReadRotationHelper(const TreeNode* tn) { - switch (tn->Size()) - { - case 3: - { - // degrees as per spec - Vector3 rotation; - ReadVector(tn, rotation.AsFloat(), 3u); - return Property::Value(Quaternion(Radian(Degree(rotation.x)), - Radian(Degree(rotation.y)), - Radian(Degree(rotation.z)))); - } - case 4: + switch(tn->Size()) { - Vector4 v; - ReadVector(tn, v.AsFloat(), 4u); - //Quaternion - return Property::Value(Quaternion(v)); - } - default: - return Property::Value(); + case 3: + { + // degrees as per spec + Vector3 rotation; + ReadVector(tn, rotation.AsFloat(), 3u); + return Property::Value(Quaternion(Radian(Degree(rotation.x)), + Radian(Degree(rotation.y)), + Radian(Degree(rotation.z)))); + } + case 4: + { + Vector4 v; + ReadVector(tn, v.AsFloat(), 4u); + //Quaternion + return Property::Value(Quaternion(v)); + } + default: + return Property::Value(); } } -template +template bool ReadQuadHelper(const TreeNode* tn, const std::array& quad) { - auto i = quad.begin(); - auto iEnd = quad.end(); + auto i = quad.begin(); + auto iEnd = quad.end(); auto iJson = tn->CBegin(); - while (iJson != tn->CEnd() && i != iEnd) + while(iJson != tn->CEnd() && i != iEnd) { int value; - if (ReadInt(&(*iJson).second, value) && value <= std::numeric_limits::max()) + if(ReadInt(&(*iJson).second, value) && value <= std::numeric_limits::max()) { **i = value; ++i; @@ -118,66 +117,65 @@ bool ReadQuadHelper(const TreeNode* tn, const std::array& quad) return true; } -const std::map kTypeIds { +const std::map kTypeIds{ // NONE - { "boolean", [](const TreeNode* tn) { - return ReadPrimitiveHelper(tn, ReadBool); - }}, - { "float", [](const TreeNode* tn) { - return ReadPrimitiveHelper(tn, ReadFloat); - }}, - { "integer", [](const TreeNode* tn) { - return ReadPrimitiveHelper(tn, ReadInt); - }}, - { "vector2", ReadVectorHelper }, - { "vector3", ReadVectorHelper }, - { "vector4", ReadVectorHelper }, - { "matrix3", ReadVectorHelper }, - { "matrix", ReadVectorHelper }, - { "rectangle", [](const TreeNode* tn) { - Rect value; - if (ReadQuadHelper(tn, { &value.x, &value.y, &value.width, &value.height })) - { - return Property::Value(value); - } - return Property::Value(); - }}, - { "rotation", ReadRotationHelper }, + {"boolean", [](const TreeNode* tn) { + return ReadPrimitiveHelper(tn, ReadBool); + }}, + {"float", [](const TreeNode* tn) { + return ReadPrimitiveHelper(tn, ReadFloat); + }}, + {"integer", [](const TreeNode* tn) { + return ReadPrimitiveHelper(tn, ReadInt); + }}, + {"vector2", ReadVectorHelper}, + {"vector3", ReadVectorHelper}, + {"vector4", ReadVectorHelper}, + {"matrix3", ReadVectorHelper}, + {"matrix", ReadVectorHelper}, + {"rectangle", [](const TreeNode* tn) { + Rect value; + if(ReadQuadHelper(tn, {&value.x, &value.y, &value.width, &value.height})) + { + return Property::Value(value); + } + return Property::Value(); + }}, + {"rotation", ReadRotationHelper}, // STRING - not particularly animatable // ARRAY - not particularly animatable // MAP - not particularly animatable - { "extents", [](const TreeNode* tn) { - Extents value; - if (ReadQuadHelper(tn, { &value.start, &value.end, &value.top, &value.bottom })) - { - return Property::Value(value); - } - return Property::Value(); - }}, + {"extents", [](const TreeNode* tn) { + Extents value; + if(ReadQuadHelper(tn, {&value.start, &value.end, &value.top, &value.bottom})) + { + return Property::Value(value); + } + return Property::Value(); + }}, }; -Property::Value(* const kArrayPropertyProcessors[])(const TreeNode*) { +Property::Value (*const kArrayPropertyProcessors[])(const TreeNode*){ ReadVectorHelper, ReadVectorHelper, ReadVectorHelper, ReadVectorHelper, ReadVectorHelper, - ReadVectorSingleFloatHelper -}; + ReadVectorSingleFloatHelper}; -} // nonamespace +} // namespace bool ReadBool(const TreeNode* node, bool& num) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::BOOLEAN) + if(node->GetType() == TreeNode::BOOLEAN) { - num = node->GetBoolean(); + num = node->GetBoolean(); returnValue = true; } @@ -186,20 +184,20 @@ bool ReadBool(const TreeNode* node, bool& num) bool ReadInt(const TreeNode* node, int& num) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::INTEGER) + if(node->GetType() == TreeNode::INTEGER) { - num = node->GetInteger(); + num = node->GetInteger(); returnValue = true; } - else if (node->GetType() == TreeNode::FLOAT) + else if(node->GetType() == TreeNode::FLOAT) { - num = static_cast(node->GetFloat()); + num = static_cast(node->GetFloat()); returnValue = true; } @@ -208,20 +206,20 @@ bool ReadInt(const TreeNode* node, int& num) bool ReadFloat(const TreeNode* node, float& num) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::FLOAT) + if(node->GetType() == TreeNode::FLOAT) { - num = node->GetFloat(); + num = node->GetFloat(); returnValue = true; } - else if (node->GetType() == TreeNode::INTEGER) + else if(node->GetType() == TreeNode::INTEGER) { - num = static_cast(node->GetInteger()); + num = static_cast(node->GetInteger()); returnValue = true; } @@ -231,7 +229,7 @@ bool ReadFloat(const TreeNode* node, float& num) bool ReadIndex(const Toolkit::TreeNode* node, Index& num) { bool returnValue = node && node->GetType() == TreeNode::INTEGER; - if (returnValue) + if(returnValue) { num = static_cast(node->GetInteger()); } @@ -241,19 +239,19 @@ bool ReadIndex(const Toolkit::TreeNode* node, Index& num) bool ReadBlob(const Toolkit::TreeNode* node, unsigned int& offset, unsigned int& length) { - if (!node) + if(!node) { return false; } - int iOffset, iLength; + int iOffset, iLength; bool success = ReadInt(node->GetChild("byteOffset"), iOffset) && - ReadInt(node->GetChild("byteLength"), iLength) && - iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage. - if (success) + ReadInt(node->GetChild("byteLength"), iLength) && + iOffset >= 0 && iLength >= 0; // 0 length might not be sensible, but is not an error at this stage. + if(success) { - offset = static_cast( iOffset ); - length = static_cast( iLength ); + offset = static_cast(iOffset); + length = static_cast(iLength); } return success; } @@ -261,11 +259,11 @@ bool ReadBlob(const Toolkit::TreeNode* node, unsigned int& offset, unsigned int& size_t GetNumericalArraySize(const TreeNode* node) { size_t size = 0; - if (node->GetType() == TreeNode::ARRAY) + if(node->GetType() == TreeNode::ARRAY) { - for (auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 && - ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER); - ++i0) + for(auto i0 = node->CBegin(), i1 = node->CEnd(); i0 != i1 && + ((*i0).second.GetType() == TreeNode::FLOAT || (*i0).second.GetType() == TreeNode::INTEGER); + ++i0) { ++size; } @@ -275,19 +273,19 @@ size_t GetNumericalArraySize(const TreeNode* node) bool ReadVector(const TreeNode* node, float* num, unsigned int size) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) + if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) { unsigned int offset = 0u; - for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) + for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) { const TreeNode& coord = (*it).second; - if (!ReadFloat(&coord, *(num + offset))) + if(!ReadFloat(&coord, *(num + offset))) { return false; } @@ -300,19 +298,19 @@ bool ReadVector(const TreeNode* node, float* num, unsigned int size) bool ReadVector(const Toolkit::TreeNode* node, int* num, unsigned int size) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if ((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) + if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) { unsigned int offset = 0u; - for (TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) + for(TreeNode::ConstIterator it = node->CBegin(); offset < size; ++it, ++offset) { const TreeNode& coord = (*it).second; - if (!ReadInt(&coord, *(num + offset))) + if(!ReadInt(&coord, *(num + offset))) { return false; } @@ -325,14 +323,14 @@ bool ReadVector(const Toolkit::TreeNode* node, int* num, unsigned int size) bool ReadColor(const TreeNode* node, Vector4& color) { - if (nullptr == node) + if(nullptr == node) { return false; } - if (!ReadVector(node, color.AsFloat(), 4)) + if(!ReadVector(node, color.AsFloat(), 4)) { - if (!ReadVector(node, color.AsFloat(), 3)) + if(!ReadVector(node, color.AsFloat(), 3)) { return false; } @@ -344,12 +342,12 @@ bool ReadColor(const TreeNode* node, Vector4& color) bool ReadTimePeriod(const TreeNode* node, TimePeriod& timePeriod) { - if (!node) + if(!node) { return false; } - if (!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds)) + if(!ReadFloat(node->GetChild("delay"), timePeriod.delaySeconds) || !ReadFloat(node->GetChild("duration"), timePeriod.durationSeconds)) { return false; } @@ -358,15 +356,15 @@ bool ReadTimePeriod(const TreeNode* node, TimePeriod& timePeriod) bool ReadString(const TreeNode* node, std::string& strValue) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::STRING) + if(node->GetType() == TreeNode::STRING) { - strValue = node->GetString(); + strValue = node->GetString(); returnValue = true; } return returnValue; @@ -374,18 +372,18 @@ bool ReadString(const TreeNode* node, std::string& strValue) bool ReadStringVector(const TreeNode* node, std::vector& strvector) { - if (!node) + if(!node) { return false; } bool returnValue = false; - if (node->GetType() == TreeNode::ARRAY) + if(node->GetType() == TreeNode::ARRAY) { - for (TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it) + for(TreeNode::ConstIterator it = node->CBegin(); it != node->CEnd(); ++it) { const TreeNode& strNode = (*it).second; - if (strNode.GetType() == TreeNode::STRING) + if(strNode.GetType() == TreeNode::STRING) { strvector.push_back(strNode.GetString()); } @@ -401,60 +399,60 @@ bool ReadStringVector(const TreeNode* node, std::vector& strvector) Property::Value ReadPropertyValue(const Property::Type& propType, const TreeNode& tn) { - switch (propType) + switch(propType) { - case Property::BOOLEAN: - return ReadPrimitiveHelper(&tn, ReadBool); + case Property::BOOLEAN: + return ReadPrimitiveHelper(&tn, ReadBool); - case Property::FLOAT: - return ReadPrimitiveHelper(&tn, ReadFloat); + case Property::FLOAT: + return ReadPrimitiveHelper(&tn, ReadFloat); - case Property::INTEGER: - return ReadPrimitiveHelper(&tn, ReadInt); + case Property::INTEGER: + return ReadPrimitiveHelper(&tn, ReadInt); - case Property::VECTOR2: - return ReadVectorHelper(&tn); + case Property::VECTOR2: + return ReadVectorHelper(&tn); - case Property::VECTOR3: - return ReadVectorHelper(&tn); + case Property::VECTOR3: + return ReadVectorHelper(&tn); - case Property::VECTOR4: - return ReadVectorHelper(&tn); + case Property::VECTOR4: + return ReadVectorHelper(&tn); - case Property::MATRIX3: - return ReadVectorHelper(&tn); + case Property::MATRIX3: + return ReadVectorHelper(&tn); - case Property::MATRIX: - return ReadVectorHelper(&tn); + case Property::MATRIX: + return ReadVectorHelper(&tn); - case Property::RECTANGLE: - { - Rect value; - if (ReadQuadHelper(&tn, { &value.x, &value.y, &value.width, &value.height })) + case Property::RECTANGLE: { - return Property::Value(value); + Rect value; + if(ReadQuadHelper(&tn, {&value.x, &value.y, &value.width, &value.height})) + { + return Property::Value(value); + } + break; } - break; - } - case Property::ROTATION: - return ReadRotationHelper(&tn); + case Property::ROTATION: + return ReadRotationHelper(&tn); - case Property::EXTENTS: - { - Extents value; - if (ReadQuadHelper(&tn, { &value.start, &value.end, &value.top, &value.bottom })) + case Property::EXTENTS: { - return Property::Value(value); + Extents value; + if(ReadQuadHelper(&tn, {&value.start, &value.end, &value.top, &value.bottom})) + { + return Property::Value(value); + } + break; } - break; - } - case Property::NONE: // fall - default: - { - DALI_ASSERT_ALWAYS(!"Property type incorrect"); - } + case Property::NONE: // fall + default: + { + DALI_ASSERT_ALWAYS(!"Property type incorrect"); + } } return Property::Value(); } @@ -462,45 +460,45 @@ Property::Value ReadPropertyValue(const Property::Type& propType, const TreeNode Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn) { Property::Value propValue; - if (tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type. + if(tn.GetType() == TreeNode::OBJECT) // attempt to disambiguate type. { auto jsonType = tn.GetChild("type"); - if (jsonType && jsonType->GetType() == TreeNode::STRING) + if(jsonType && jsonType->GetType() == TreeNode::STRING) { auto iFind = kTypeIds.find(jsonType->GetString()); - if (iFind != kTypeIds.end()) + if(iFind != kTypeIds.end()) { propValue = iFind->second(tn.GetChild("value")); } } } - if (propValue.GetType() == Property::NONE) + if(propValue.GetType() == Property::NONE) { - if (tn.Size() == 0) + if(tn.Size() == 0) { - switch (tn.GetType()) + switch(tn.GetType()) { - case TreeNode::BOOLEAN: - propValue = ReadPrimitiveHelper(&tn, ReadBool); - break; + case TreeNode::BOOLEAN: + propValue = ReadPrimitiveHelper(&tn, ReadBool); + break; - case TreeNode::INTEGER: - propValue = ReadPrimitiveHelper(&tn, ReadInt); - break; + case TreeNode::INTEGER: + propValue = ReadPrimitiveHelper(&tn, ReadInt); + break; - case TreeNode::FLOAT: - propValue = ReadPrimitiveHelper(&tn, ReadFloat); - break; + case TreeNode::FLOAT: + propValue = ReadPrimitiveHelper(&tn, ReadFloat); + break; - default: - break; + default: + break; } } else { bool allNumbers = true; - for (auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0) + for(auto i0 = tn.CBegin(), i1 = tn.CEnd(); i0 != i1; ++i0) { auto type = (*i0).second.GetType(); if(!(type == TreeNode::FLOAT || type == TreeNode::INTEGER)) @@ -510,13 +508,13 @@ Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn) } } - if (allNumbers) + if(allNumbers) { // NOTE: rotations / rectangles / extents must be disambiguated in all circumstances. - for (auto& r : kArrayPropertyProcessors) + for(auto& r : kArrayPropertyProcessors) { propValue = r(&tn); - if (propValue.GetType() != Property::NONE) + if(propValue.GetType() != Property::NONE) { break; } @@ -527,5 +525,5 @@ Property::Value ReadPropertyValue(const Toolkit::TreeNode& tn) return propValue; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/alpha-function-helper.cpp b/dali-scene-loader/public-api/alpha-function-helper.cpp index 33ad3db..b5168e0 100644 --- a/dali-scene-loader/public-api/alpha-function-helper.cpp +++ b/dali-scene-loader/public-api/alpha-function-helper.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,10 +23,11 @@ namespace SceneLoader { namespace { - +// clang-format off #define DALI_ALPHA_FUNCTION_ENTRY(x) { #x, AlphaFunction::x } +// clang-format on -std::unordered_map sFunctions { +std::unordered_map sFunctions{ DALI_ALPHA_FUNCTION_ENTRY(DEFAULT), DALI_ALPHA_FUNCTION_ENTRY(LINEAR), DALI_ALPHA_FUNCTION_ENTRY(REVERSE), @@ -45,24 +46,24 @@ std::unordered_map sFunctions { #undef DALI_ALPHA_FUNCTION_ENTRY -} // nonamespace +} // namespace AlphaFunction GetAlphaFunction(const std::string& name, bool* found) { - auto iFind = sFunctions.find(name); + auto iFind = sFunctions.find(name); bool success = iFind != sFunctions.end(); - if (found) + if(found) { *found = success; } return success ? iFind->second : AlphaFunction(AlphaFunction::DEFAULT); } -void RegisterAlphaFunction(const std::string & name, AlphaFunction alphaFn) +void RegisterAlphaFunction(const std::string& name, AlphaFunction alphaFn) { - DALI_ASSERT_ALWAYS(sFunctions.insert({ name, alphaFn }).second && - "Function with given key already exists."); + DALI_ASSERT_ALWAYS(sFunctions.insert({name, alphaFn}).second && + "Function with given key already exists."); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/animated-property.cpp b/dali-scene-loader/public-api/animated-property.cpp index 1e8a592..3d1542d 100644 --- a/dali-scene-loader/public-api/animated-property.cpp +++ b/dali-scene-loader/public-api/animated-property.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,19 +20,18 @@ namespace Dali { namespace SceneLoader { - void AnimatedProperty::Animate(Animation& anim, GetActor getActor) { - if (Actor actor = getActor(mNodeName)) + if(Actor actor = getActor(mNodeName)) { Property prop = GetProperty(actor); - if (mKeyFrames) + if(mKeyFrames) { anim.AnimateBetween(prop, mKeyFrames, mAlphaFunction, mTimePeriod); } - else if (mValue) + else if(mValue) { - if (mValue->mIsRelative) + if(mValue->mIsRelative) { anim.AnimateBy(prop, mValue->mValue, mAlphaFunction, mTimePeriod); } @@ -44,5 +43,5 @@ void AnimatedProperty::Animate(Animation& anim, GetActor getActor) } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/animation-definition.cpp b/dali-scene-loader/public-api/animation-definition.cpp index ee2b519..850dd00 100644 --- a/dali-scene-loader/public-api/animation-definition.cpp +++ b/dali-scene-loader/public-api/animation-definition.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,9 +20,8 @@ namespace Dali { namespace SceneLoader { - const float AnimationDefinition::DEFAULT_DURATION_SECONDS = 1.f; -const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f; +const float AnimationDefinition::MIN_DURATION_SECONDS = 1e-2f; Animation::EndAction AnimationDefinition::StopForModification(Animation& anim) { @@ -43,12 +42,13 @@ AnimationDefinition::AnimationDefinition(AnimationDefinition&& other) mSpeedFactor(other.mSpeedFactor), mPlayRange(other.mPlayRange), mProperties(std::move(other.mProperties)) -{} +{ +} void AnimationDefinition::Animate(Animation& animation, AnimatedProperty::GetActor getActor) { DALI_ASSERT_ALWAYS(animation); - for (auto& ap : mProperties) + for(auto& ap : mProperties) { ap.Animate(animation, getActor); } @@ -72,16 +72,16 @@ Animation AnimationDefinition::ReAnimate(AnimatedProperty::GetActor getActor) AnimationDefinition& AnimationDefinition::operator=(AnimationDefinition&& other) { AnimationDefinition tmp(std::move(other)); - mName = std::move(tmp.mName); - mDuration = tmp.mDuration; - mLoopCount = tmp.mLoopCount; + mName = std::move(tmp.mName); + mDuration = tmp.mDuration; + mLoopCount = tmp.mLoopCount; mDisconnectAction = tmp.mDisconnectAction; - mEndAction = tmp.mEndAction; - mSpeedFactor = tmp.mSpeedFactor; - mPlayRange = tmp.mPlayRange; + mEndAction = tmp.mEndAction; + mSpeedFactor = tmp.mSpeedFactor; + mPlayRange = tmp.mPlayRange; mProperties.swap(tmp.mProperties); return *this; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/blend-shape-details.cpp b/dali-scene-loader/public-api/blend-shape-details.cpp index 3308d37..9e76924 100644 --- a/dali-scene-loader/public-api/blend-shape-details.cpp +++ b/dali-scene-loader/public-api/blend-shape-details.cpp @@ -1,6 +1,6 @@ /* -* 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,7 +30,6 @@ namespace Dali { namespace SceneLoader { - const std::string BlendShapes::NUMBER_OF_BLEND_SHAPES("uNumberOfBlendShapes"); const std::string BlendShapes::UNNORMALIZE_FACTOR("uBlendShapeUnnormalizeFactor"); const std::string BlendShapes::COMPONENT_SIZE("uBlendShapeComponentSize"); @@ -43,27 +42,27 @@ void BlendShapes::ConfigureProperties(const std::pair mCustomizations; }; Customization::Map::Map() -: mImpl{ new Impl } -{} +: mImpl{new Impl} +{ +} Customization::Map::~Map() = default; @@ -41,8 +42,8 @@ Customization* Customization::Map::Set(Tag tag, Customization&& customization) const Customization* Customization::Map::Get(Tag tag) const { auto& customizations = mImpl->mCustomizations; - auto iFind = customizations.find(tag); - if (iFind != customizations.end()) + auto iFind = customizations.find(tag); + if(iFind != customizations.end()) { return &iFind->second; } @@ -52,8 +53,8 @@ const Customization* Customization::Map::Get(Tag tag) const Customization* Customization::Map::Get(Tag tag) { auto& customizations = mImpl->mCustomizations; - auto iFind = customizations.find(tag); - if (iFind != customizations.end()) + auto iFind = customizations.find(tag); + if(iFind != customizations.end()) { return &iFind->second; } @@ -76,8 +77,9 @@ struct Customization::Choices::Impl }; Customization::Choices::Choices() -: mImpl{ new Impl } -{} +: mImpl{new Impl} +{ +} Customization::Choices::~Choices() = default; @@ -89,8 +91,8 @@ void Customization::Choices::Set(Tag tag, OptionType option) Customization::OptionType Customization::Choices::Get(Tag tag) const { auto& options = mImpl->mOptions; - auto iFind = options.find(tag); - if (iFind != options.end()) + auto iFind = options.find(tag); + if(iFind != options.end()) { return iFind->second; } @@ -107,5 +109,5 @@ void Customization::Choices::Clear() mImpl->mOptions.clear(); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/dli-loader.cpp b/dali-scene-loader/public-api/dli-loader.cpp index 11dc036..18214dd 100644 --- a/dali-scene-loader/public-api/dli-loader.cpp +++ b/dali-scene-loader/public-api/dli-loader.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,29 +19,29 @@ #include "dali-scene-loader/public-api/dli-loader.h" // EXTERNAL INCLUDES -#include "dali/public-api/object/property-array.h" -#include "dali/devel-api/common/map-wrapper.h" -#include "dali-toolkit/devel-api/builder/json-parser.h" -#include "dali/integration-api/debug.h" +#include +#include #include #include -#include #include -#include +#include "dali-toolkit/devel-api/builder/json-parser.h" +#include "dali/devel-api/common/map-wrapper.h" +#include "dali/integration-api/debug.h" +#include "dali/public-api/object/property-array.h" // INTERNAL INCLUDES -#include "dali-scene-loader/public-api/parse-renderer-state.h" -#include "dali-scene-loader/public-api/skinning-details.h" -#include "dali-scene-loader/public-api/load-result.h" -#include "dali-scene-loader/public-api/scene-definition.h" -#include "dali-scene-loader/public-api/animation-definition.h" +#include "dali-scene-loader/internal/json-util.h" #include "dali-scene-loader/public-api/alpha-function-helper.h" -#include "dali-scene-loader/public-api/camera-parameters.h" -#include "dali-scene-loader/public-api/light-parameters.h" +#include "dali-scene-loader/public-api/animation-definition.h" #include "dali-scene-loader/public-api/blend-shape-details.h" +#include "dali-scene-loader/public-api/camera-parameters.h" #include "dali-scene-loader/public-api/ktx-loader.h" +#include "dali-scene-loader/public-api/light-parameters.h" +#include "dali-scene-loader/public-api/load-result.h" +#include "dali-scene-loader/public-api/parse-renderer-state.h" +#include "dali-scene-loader/public-api/scene-definition.h" +#include "dali-scene-loader/public-api/skinning-details.h" #include "dali-scene-loader/public-api/utils.h" -#include "dali-scene-loader/internal/json-util.h" #define DLI_0_1_COMPATIBILITY @@ -51,18 +51,17 @@ using namespace Toolkit; namespace SceneLoader { - namespace rs = RendererState; namespace { -const std::string NODES = "nodes"; -const std::string SCENES = "scenes"; -const std::string NODE = "node"; -const std::string URI = "uri"; -const std::string URL = "url"; +const std::string NODES = "nodes"; +const std::string SCENES = "scenes"; +const std::string NODE = "node"; +const std::string URI = "uri"; +const std::string URL = "url"; const std::string CUSTOMIZATION = "customization"; -const std::string HINTS = "hints"; +const std::string HINTS = "hints"; const std::string NAME("name"); const std::string BLEND_SHAPE_HEADER("blendShapeHeader"); const std::string BLEND_SHAPES("blendShapes"); @@ -70,29 +69,29 @@ const std::string BLEND_SHAPE_VERSION_1_0("1.0"); const std::string BLEND_SHAPE_VERSION_2_0("2.0"); const std::string VERSION("version"); -const char* const SHADOW_MAP_SIZE = "shadowMapSize"; +const char* const SHADOW_MAP_SIZE = "shadowMapSize"; const char* const ORTHOGRAPHIC_SIZE = "orthographicSize"; -const char* const PIXEL_UNITS = "px"; +const char* const PIXEL_UNITS = "px"; const char SLASH = '/'; void ReadModelTransform(const TreeNode* node, Quaternion& orientation, Vector3& translation, Vector3& scale) { - float num[16u] = { .0f }; + float num[16u] = {.0f}; - if (ReadVector(node->GetChild("matrix"), num, 16u)) + if(ReadVector(node->GetChild("matrix"), num, 16u)) { Matrix mat(num); mat.GetTransformComponents(translation, orientation, scale); } else { - if (ReadVector(node->GetChild("angle"), num, 3u)) + if(ReadVector(node->GetChild("angle"), num, 3u)) { orientation = Quaternion(Radian(Degree(num[0u])), Radian(Degree(num[1u])), Radian(Degree(num[2u]))); } - if (ReadVector(node->GetChild("position"), num, 3u)) + if(ReadVector(node->GetChild("position"), num, 3u)) { translation = Vector3(num); } @@ -109,10 +108,9 @@ bool ReadAttribAccessor(const TreeNode* node, MeshDefinition::Accessor& accessor return ReadBlob(node, accessor.mBlob.mOffset, accessor.mBlob.mLength); } -bool ReadColorCode(const TreeNode* node, Vector4& color, - DliLoader::ConvertColorCode convertColorCode) +bool ReadColorCode(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode) { - if (!node || !convertColorCode) + if(!node || !convertColorCode) { return false; } @@ -122,20 +120,19 @@ bool ReadColorCode(const TreeNode* node, Vector4& color, return true; } -bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, - DliLoader::ConvertColorCode convertColorCode) +bool ReadColorCodeOrColor(const TreeNode* node, Vector4& color, DliLoader::ConvertColorCode convertColorCode) { return ReadColorCode(node->GetChild("colorCode"), color, convertColorCode) || - ReadColor(node->GetChild("color"), color); + ReadColor(node->GetChild("color"), color); } RendererState::Type ReadRendererState(const TreeNode& tnRendererState) { - if (tnRendererState.GetType() == TreeNode::INTEGER) + if(tnRendererState.GetType() == TreeNode::INTEGER) { return static_cast(tnRendererState.GetInteger()); } - else if (tnRendererState.GetType() == TreeNode::STRING) + else if(tnRendererState.GetType() == TreeNode::STRING) { return RendererState::Parse(tnRendererState.GetString()); } @@ -159,12 +156,12 @@ void ReadArcField(const TreeNode* eArc, ArcNode& arc) ReadFloat(eArc->GetChild("endAngle"), arc.mEndAngleDegrees); } -const TreeNode *GetNthChild(const TreeNode *node, uint32_t index) +const TreeNode* GetNthChild(const TreeNode* node, uint32_t index) { uint32_t i = 0; - for (TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i) + for(TreeNode::ConstIterator it = (*node).CBegin(); it != (*node).CEnd(); ++it, ++i) { - if (i == index) + if(i == index) { return &((*it).second); } @@ -175,11 +172,11 @@ const TreeNode *GetNthChild(const TreeNode *node, uint32_t index) const TreeNode* RequireChild(const TreeNode* node, const std::string& childName) { auto child = node->GetChild(childName); - if (!child) + if(!child) { ExceptionFlinger flinger(ASSERT_LOCATION); flinger << "Failed to find child node '" << childName << "'"; - if (auto nodeName = node->GetName()) + if(auto nodeName = node->GetName()) { flinger << " on '" << nodeName << "'"; } @@ -193,43 +190,55 @@ void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array); void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map) { DALI_ASSERT_DEBUG(node.GetType() == TreeNode::OBJECT); - for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) + for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) { auto kv = *i0; - switch (kv.second.GetType()) - { - case TreeNode::ARRAY: + switch(kv.second.GetType()) { - Property::Array array; - ParseProperties(kv.second, array); - map.Insert(kv.first, array); - } break; + case TreeNode::ARRAY: + { + Property::Array array; + ParseProperties(kv.second, array); + map.Insert(kv.first, array); + break; + } - case TreeNode::OBJECT: - { - Property::Map innerMap; - ParseProperties(kv.second, innerMap); - map.Insert(kv.first, innerMap); - } break; + case TreeNode::OBJECT: + { + Property::Map innerMap; + ParseProperties(kv.second, innerMap); + map.Insert(kv.first, innerMap); + break; + } - case TreeNode::STRING: - map.Insert(kv.first, kv.second.GetString()); - break; + case TreeNode::STRING: + { + map.Insert(kv.first, kv.second.GetString()); + break; + } - case TreeNode::INTEGER: - map.Insert(kv.first, kv.second.GetInteger()); - break; + case TreeNode::INTEGER: + { + map.Insert(kv.first, kv.second.GetInteger()); + break; + } - case TreeNode::BOOLEAN: - map.Insert(kv.first, kv.second.GetBoolean()); - break; + case TreeNode::BOOLEAN: + { + map.Insert(kv.first, kv.second.GetBoolean()); + break; + } - case TreeNode::FLOAT: - map.Insert(kv.first, kv.second.GetFloat()); - break; + case TreeNode::FLOAT: + { + map.Insert(kv.first, kv.second.GetFloat()); + break; + } - case TreeNode::IS_NULL: - break; + case TreeNode::IS_NULL: + { + break; + } } } } @@ -237,58 +246,70 @@ void ParseProperties(const Toolkit::TreeNode& node, Property::Map& map) void ParseProperties(const Toolkit::TreeNode& node, Property::Array& array) { DALI_ASSERT_DEBUG(node.GetType() == TreeNode::ARRAY); - for (auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) + for(auto i0 = node.CBegin(), i1 = node.CEnd(); i0 != i1; ++i0) { auto kv = *i0; - switch (kv.second.GetType()) - { - case TreeNode::ARRAY: + switch(kv.second.GetType()) { - Property::Array innerArray; - ParseProperties(kv.second, innerArray); - array.PushBack(innerArray); - } break; + case TreeNode::ARRAY: + { + Property::Array innerArray; + ParseProperties(kv.second, innerArray); + array.PushBack(innerArray); + break; + } - case TreeNode::OBJECT: - { - Property::Map map; - ParseProperties(kv.second, map); - array.PushBack(map); - } break; + case TreeNode::OBJECT: + { + Property::Map map; + ParseProperties(kv.second, map); + array.PushBack(map); + break; + } - case TreeNode::STRING: - array.PushBack(kv.second.GetString()); - break; + case TreeNode::STRING: + { + array.PushBack(kv.second.GetString()); + break; + } - case TreeNode::INTEGER: - array.PushBack(kv.second.GetInteger()); - break; + case TreeNode::INTEGER: + { + array.PushBack(kv.second.GetInteger()); + break; + } - case TreeNode::BOOLEAN: - array.PushBack(kv.second.GetBoolean()); - break; + case TreeNode::BOOLEAN: + { + array.PushBack(kv.second.GetBoolean()); + break; + } - case TreeNode::FLOAT: - array.PushBack(kv.second.GetFloat()); - break; + case TreeNode::FLOAT: + { + array.PushBack(kv.second.GetFloat()); + break; + } - case TreeNode::IS_NULL: - break; + case TreeNode::IS_NULL: + { + break; + } } } } -}//namespace +} //namespace struct DliLoader::Impl { - StringCallback mOnError = DefaultErrorCallback; + StringCallback mOnError = DefaultErrorCallback; Toolkit::JsonParser mParser; void ParseScene(LoadParams& params); private: - std::map mInverseBindMatrices; + std::map mInverseBindMatrices; /** * @brief Due to .dli nodes being processed in depth-first traversal with orphans being @@ -306,29 +327,26 @@ private: * index. * @return Whether the operation was successful. */ - virtual bool Map(Index iDli, Index iScene) =0; + virtual bool Map(Index iDli, Index iScene) = 0; /** * @return The scene index for the node's @a dli index. */ - virtual Index Resolve(Index iDli) =0; + virtual Index Resolve(Index iDli) = 0; }; /** * @brief Traverses the DOM tree created by LoadDocument() in an attempt to create * an intermediate representation of resources and nodes. */ - void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, - const Toolkit::TreeNode* tnNodes, LoadParams& params); + void ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params); void ParseSkeletons(const Toolkit::TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources); void ParseEnvironments(const Toolkit::TreeNode* environments, ResourceBundle& resources); - void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, - ResourceBundle& resources); + void ParseMaterials(const Toolkit::TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources); void ParseNodes(const Toolkit::TreeNode* nodes, Index index, LoadParams& params); - void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, - std::vector& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper); + void ParseNodesInternal(const Toolkit::TreeNode* nodes, Index index, std::vector& inOutParentStack, LoadParams& params, IIndexMapper& indexMapper); void ParseAnimations(const Toolkit::TreeNode* animations, LoadParams& params); void ParseAnimationGroups(const Toolkit::TreeNode* animationGroups, LoadParams& params); @@ -341,8 +359,9 @@ private: }; DliLoader::DliLoader() -: mImpl{ new Impl } -{} +: mImpl{new Impl} +{ +} DliLoader::~DliLoader() = default; @@ -356,8 +375,8 @@ bool DliLoader::LoadScene(const std::string& uri, LoadParams& params) std::string daliBuffer = LoadTextFile(uri.c_str()); auto& parser = mImpl->mParser; - parser = JsonParser::New(); - if (!parser.Parse(daliBuffer)) + parser = JsonParser::New(); + if(!parser.Parse(daliBuffer)) { return false; } @@ -371,7 +390,7 @@ std::string DliLoader::GetParseError() const std::stringstream stream; auto& parser = mImpl->mParser; - if (parser.ParseError()) + if(parser.ParseError()) { stream << "position: " << parser.GetErrorPosition() << ", line: " << parser.GetErrorLineNumber() << ", column: " << parser.GetErrorColumn() << ", description: " << parser.GetErrorDescription() << "."; } @@ -381,36 +400,36 @@ std::string DliLoader::GetParseError() const void DliLoader::Impl::ParseScene(LoadParams& params) { - auto& input = params.input; + auto& input = params.input; auto& output = params.output; // get index of root node. auto docRoot = mParser.GetRoot(); // Process resources first - these are shared - if (auto environments = docRoot->GetChild("environment")) + if(auto environments = docRoot->GetChild("environment")) { - ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials + ParseEnvironments(environments, output.mResources); // NOTE: must precede parsing of materials } - if (auto meshes = docRoot->GetChild("meshes")) + if(auto meshes = docRoot->GetChild("meshes")) { ParseMeshes(meshes, output.mResources); } - if (auto shaders = docRoot->GetChild("shaders")) + if(auto shaders = docRoot->GetChild("shaders")) { ParseShaders(shaders, output.mResources); } - if (auto materials = docRoot->GetChild("materials")) + if(auto materials = docRoot->GetChild("materials")) { ParseMaterials(materials, input.mConvertColorCode, output.mResources); } - for (auto& c : input.mPreNodeCategoryProcessors) + for(auto& c : input.mPreNodeCategoryProcessors) { - if (auto node = docRoot->GetChild(c.first)) + if(auto node = docRoot->GetChild(c.first)) { Property::Array array; ParseProperties(*node, array); @@ -419,11 +438,11 @@ void DliLoader::Impl::ParseScene(LoadParams& params) } // Process scenes - Index iScene = 0; // default scene + Index iScene = 0; // default scene ReadIndex(docRoot->GetChild("scene"), iScene); auto tnScenes = RequireChild(docRoot, "scenes"); - auto tnNodes = RequireChild(docRoot, "nodes"); + auto tnNodes = RequireChild(docRoot, "nodes"); ParseSceneInternal(iScene, tnScenes, tnNodes, params); ParseSkeletons(docRoot->GetChild("skeletons"), output.mScene, output.mResources); @@ -436,9 +455,9 @@ void DliLoader::Impl::ParseScene(LoadParams& params) GetLightParameters(output.mLightParameters); // Post-node processors and animations last - for (auto& c : input.mPostNodeCategoryProcessors) + for(auto& c : input.mPostNodeCategoryProcessors) { - if (auto node = docRoot->GetChild(c.first)) + if(auto node = docRoot->GetChild(c.first)) { Property::Array array; ParseProperties(*node, array); @@ -446,58 +465,54 @@ void DliLoader::Impl::ParseScene(LoadParams& params) } } - if (auto animations = docRoot->GetChild("animations")) + if(auto animations = docRoot->GetChild("animations")) { ParseAnimations(animations, params); } - if (!output.mAnimationDefinitions.empty()) + if(!output.mAnimationDefinitions.empty()) { - if (auto animationGroups = docRoot->GetChild("animationGroups")) + if(auto animationGroups = docRoot->GetChild("animationGroups")) { ParseAnimationGroups(animationGroups, params); } } } -void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, - const Toolkit::TreeNode* tnNodes, LoadParams& params) +void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* tnScenes, const Toolkit::TreeNode* tnNodes, LoadParams& params) { auto getSceneRootIdx = [tnScenes, tnNodes](Index iScene) { - auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object - if (!tn) + auto tn = GetNthChild(tnScenes, iScene); // now a "scene" object + if(!tn) { ExceptionFlinger(ASSERT_LOCATION) << iScene << " is out of bounds access into " << SCENES << "."; } - tn = RequireChild(tn, NODES); // now a "nodes" array - if (tn->GetType() != TreeNode::ARRAY) + tn = RequireChild(tn, NODES); // now a "nodes" array + if(tn->GetType() != TreeNode::ARRAY) { - ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << - " has an invalid type; array required."; + ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid type; array required."; } - if (tn->Size() < 1) + if(tn->Size() < 1) { - ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << - " must define a node id."; + ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " must define a node id."; } - tn = GetNthChild(tn, 0); // now the first element of the array + tn = GetNthChild(tn, 0); // now the first element of the array Index iRootNode; - if (!ReadIndex(tn, iRootNode)) + if(!ReadIndex(tn, iRootNode)) { - ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << - " has an invalid value for root node index: '" << iRootNode << "'."; + ExceptionFlinger(ASSERT_LOCATION) << SCENES << "[" << iScene << "]." << NODES << " has an invalid value for root node index: '" << iRootNode << "'."; } - if (iRootNode >= tnNodes->Size()) + if(iRootNode >= tnNodes->Size()) { ExceptionFlinger(ASSERT_LOCATION) << "Root node index << " << iRootNode << " of scene " << iScene << " is out of bounds."; } - tn = GetNthChild(tnNodes, iRootNode); // now a "node" object - if (tn->GetType() != TreeNode::OBJECT) + tn = GetNthChild(tnNodes, iRootNode); // now a "node" object + if(tn->GetType() != TreeNode::OBJECT) { ExceptionFlinger(ASSERT_LOCATION) << "Root node of scene " << iScene << " is of invalid JSON type; object required"; } @@ -511,19 +526,19 @@ void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* auto& scene = params.output.mScene; scene.AddRootNode(0); - for (Index i = 0; i < iScene; ++i) + for(Index i = 0; i < iScene; ++i) { - Index iRootNode = getSceneRootIdx(i); - const Index iRoot = scene.GetNodeCount(); + Index iRootNode = getSceneRootIdx(i); + const Index iRoot = scene.GetNodeCount(); ParseNodes(tnNodes, iRootNode, params); scene.AddRootNode(iRoot); } auto numScenes = tnScenes->Size(); - for (Index i = iScene + 1; i < numScenes; ++i) + for(Index i = iScene + 1; i < numScenes; ++i) { - Index iRootNode = getSceneRootIdx(i); - const Index iRoot = scene.GetNodeCount(); + Index iRootNode = getSceneRootIdx(i); + const Index iRoot = scene.GetNodeCount(); ParseNodes(tnNodes, iRootNode, params); scene.AddRootNode(iRoot); } @@ -531,36 +546,36 @@ void DliLoader::Impl::ParseSceneInternal(Index iScene, const Toolkit::TreeNode* void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& scene, ResourceBundle& resources) { - if (skeletons) + if(skeletons) { auto iStart = skeletons->CBegin(); - for (auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0) + for(auto i0 = iStart, i1 = skeletons->CEnd(); i0 != i1; ++i0) { - auto& node = (*i0).second; + auto& node = (*i0).second; std::string skeletonRootName; - if (ReadString(node.GetChild(NODE), skeletonRootName)) + if(ReadString(node.GetChild(NODE), skeletonRootName)) { SkeletonDefinition skeleton; - if (!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx)) + if(!scene.FindNode(skeletonRootName, &skeleton.mRootNodeIdx)) { ExceptionFlinger(ASSERT_LOCATION) << FormatString("Skeleton %d: node '%s' not defined.", resources.mSkeletons.size(), skeletonRootName.c_str()); } - uint32_t jointCount = 0; + uint32_t jointCount = 0; std::function visitFn; - auto& ibms = mInverseBindMatrices; - visitFn = [&](Index id) { + auto& ibms = mInverseBindMatrices; + visitFn = [&](Index id) { auto node = scene.GetNode(id); jointCount += ibms.find(id) != ibms.end(); - for (auto i : node->mChildren) + for(auto i : node->mChildren) { visitFn(i); } }; visitFn(skeleton.mRootNodeIdx); - if (jointCount > Skinning::MAX_JOINTS) + if(jointCount > Skinning::MAX_JOINTS) { mOnError(FormatString("Skeleton %d: joint count exceeds supported limit.", resources.mSkeletons.size())); jointCount = Skinning::MAX_JOINTS; @@ -570,13 +585,13 @@ void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& visitFn = [&](Index id) { auto iFind = ibms.find(id); - if (iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS) + if(iFind != ibms.end() && skeleton.mJoints.size() < Skinning::MAX_JOINTS) { - skeleton.mJoints.push_back({ id, iFind->second }); + skeleton.mJoints.push_back({id, iFind->second}); } auto node = scene.GetNode(id); - for (auto i : node->mChildren) + for(auto i : node->mChildren) { visitFn(i); } @@ -587,8 +602,7 @@ void DliLoader::Impl::ParseSkeletons(const TreeNode* skeletons, SceneDefinition& } else { - ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << - ": Missing required attribute '"<< NODE <<"'."; + ExceptionFlinger(ASSERT_LOCATION) << "skeleton " << std::distance(iStart, i0) << ": Missing required attribute '" << NODE << "'."; } } } @@ -598,7 +612,7 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu { Matrix cubeOrientation(Matrix::IDENTITY); - for (auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0) + for(auto i0 = environments->CBegin(), i1 = environments->CEnd(); i0 != i1; ++i0) { auto& node = (*i0).second; @@ -609,7 +623,7 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu ToUnixFileSeparators(envDef.mDiffuseMapPath); envDef.mIblIntensity = 1.0f; ReadFloat(node.GetChild("iblIntensity"), envDef.mIblIntensity); - if (ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u)) + if(ReadVector(node.GetChild("cubeInitialOrientation"), cubeOrientation.AsFloat(), 16u)) { envDef.mCubeOrientation = Quaternion(cubeOrientation); } @@ -618,7 +632,7 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu } // NOTE: guarantees environmentMaps to have an empty environment. - if (resources.mEnvironmentMaps.empty()) + if(resources.mEnvironmentMaps.empty()) { resources.mEnvironmentMaps.emplace_back(EnvironmentDefinition(), EnvironmentDefinition::Textures()); } @@ -627,9 +641,9 @@ void DliLoader::Impl::ParseEnvironments(const TreeNode* environments, ResourceBu void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& resources) { uint32_t iShader = 0; - for (auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader) + for(auto i0 = shaders->CBegin(), i1 = shaders->CEnd(); i0 != i1; ++i0, ++iShader) { - auto& node = (*i0).second; + auto& node = (*i0).second; ShaderDefinition shaderDef; ReadStringVector(node.GetChild("defines"), shaderDef.mDefines); @@ -638,94 +652,96 @@ void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& reso // "OUTPUT_IS_TRANSPARENT" Might generate transparent alpha from opaque inputs. // "MODIFIES_GEOMETRY" Might change position of vertices, this option disables any culling optimizations. - ReadStringVector(node.GetChild( HINTS ), shaderDef.mHints); + ReadStringVector(node.GetChild(HINTS), shaderDef.mHints); - if (ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) && - ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath)) + if(ReadString(node.GetChild("vertex"), shaderDef.mVertexShaderPath) && + ReadString(node.GetChild("fragment"), shaderDef.mFragmentShaderPath)) { ToUnixFileSeparators(shaderDef.mVertexShaderPath); ToUnixFileSeparators(shaderDef.mFragmentShaderPath); - for (TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0) + for(TreeNode::ConstIterator j0 = node.CBegin(), j1 = node.CEnd(); j0 != j1; ++j0) { const TreeNode::KeyNodePair& keyValue = *j0; - const std::string& key = keyValue.first; - const TreeNode& value = keyValue.second; + const std::string& key = keyValue.first; + const TreeNode& value = keyValue.second; Property::Value uniformValue; - if (key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0) + if(key.compare("vertex") == 0 || key.compare("fragment") == 0 || key.compare("defines") == 0 || key.compare(HINTS) == 0) { continue; } - else if (key.compare("rendererState") == 0) + else if(key.compare("rendererState") == 0) { shaderDef.mRendererState = ReadRendererState(keyValue.second); } - else if (value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT) + else if(value.GetType() == TreeNode::INTEGER || value.GetType() == TreeNode::FLOAT) { float f = 0.f; ReadFloat(&value, f); uniformValue = f; } - else if (value.GetType() == TreeNode::BOOLEAN) + else if(value.GetType() == TreeNode::BOOLEAN) { DALI_LOG_WARNING("\"bool\" uniforms are handled as floats in shader"); bool value = false; - if (ReadBool(&keyValue.second, value)) + if(ReadBool(&keyValue.second, value)) { uniformValue = value ? 1.0f : 0.0f; } } - else switch (auto size = GetNumericalArraySize(&value)) - { - case 16: - { - Matrix m; - ReadVector(&value, m.AsFloat(), size); - uniformValue = m; - break; - } + else + switch(auto size = GetNumericalArraySize(&value)) + { + case 16: + { + Matrix m; + ReadVector(&value, m.AsFloat(), size); + uniformValue = m; + break; + } - case 9: - { - Matrix3 m; - ReadVector(&value, m.AsFloat(), size); - uniformValue = m; - break; - } + case 9: + { + Matrix3 m; + ReadVector(&value, m.AsFloat(), size); + uniformValue = m; + break; + } - case 4: - { - Vector4 v; - ReadVector(&value, v.AsFloat(), size); - uniformValue = v; - break; - } + case 4: + { + Vector4 v; + ReadVector(&value, v.AsFloat(), size); + uniformValue = v; + break; + } - case 3: - { - Vector3 v; - ReadVector(&value, v.AsFloat(), size); - uniformValue = v; - break; - } + case 3: + { + Vector3 v; + ReadVector(&value, v.AsFloat(), size); + uniformValue = v; + break; + } - case 2: - { - Vector2 v; - ReadVector(&value, v.AsFloat(), size); - uniformValue = v; - break; - } + case 2: + { + Vector2 v; + ReadVector(&value, v.AsFloat(), size); + uniformValue = v; + break; + } - default: - mOnError(FormatString( - "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.", - iShader, key.c_str())); - break; - } + default: + mOnError(FormatString( + "shader %d: Ignoring uniform '%s': failed to infer type from %d elements.", + iShader, + key.c_str())); + break; + } - if (Property::NONE != uniformValue.GetType()) + if(Property::NONE != uniformValue.GetType()) { shaderDef.mUniforms.Insert(key, uniformValue); } @@ -735,116 +751,114 @@ void DliLoader::Impl::ParseShaders(const TreeNode* shaders, ResourceBundle& reso } else { - ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << - ": Missing vertex / fragment shader definition."; + ExceptionFlinger(ASSERT_LOCATION) << "shader " << iShader << ": Missing vertex / fragment shader definition."; } } } void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resources) { - for (auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0) + for(auto i0 = meshes->CBegin(), i1 = meshes->CEnd(); i0 != i1; ++i0) { auto& node = (*i0).second; - MeshDefinition meshDef; - if (!ReadString(node.GetChild(URI), meshDef.mUri)) + MeshDefinition meshDef; + if(!ReadString(node.GetChild(URI), meshDef.mUri)) { - ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << - ": Missing required attribute '" << URI << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "mesh " << resources.mMeshes.size() << ": Missing required attribute '" << URI << "'."; } ToUnixFileSeparators(meshDef.mUri); std::string primitive; - if (ReadString(node.GetChild("primitive"), primitive)) + if(ReadString(node.GetChild("primitive"), primitive)) { - if (primitive == "LINES") + if(primitive == "LINES") { meshDef.mPrimitiveType = Geometry::LINES; } - else if (primitive == "POINTS") + else if(primitive == "POINTS") { meshDef.mPrimitiveType = Geometry::POINTS; } - else if (primitive != "TRIANGLES") + else if(primitive != "TRIANGLES") { mOnError(FormatString( "mesh %d: Using TRIANGLES instead of unsupported primitive type '%s'.", - resources.mMeshes.size(), primitive.c_str())); + resources.mMeshes.size(), + primitive.c_str())); } } int attributes; - if (ReadInt(node.GetChild("attributes"), attributes)) + if(ReadInt(node.GetChild("attributes"), attributes)) { - if (MaskMatch(attributes, MeshDefinition::INDICES) && - !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices)) + if(MaskMatch(attributes, MeshDefinition::INDICES) && + !ReadAttribAccessor(node.GetChild("indices"), meshDef.mIndices)) { ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.", - resources.mMeshes.size(), "indices"); + resources.mMeshes.size(), + "indices"); } - if (MaskMatch(attributes, MeshDefinition::POSITIONS) && - !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions)) + if(MaskMatch(attributes, MeshDefinition::POSITIONS) && + !ReadAttribAccessor(node.GetChild("positions"), meshDef.mPositions)) { ExceptionFlinger(ASSERT_LOCATION) << FormatString("mesh %d: Failed to read %s.", - resources.mMeshes.size(), "positions"); + resources.mMeshes.size(), + "positions"); } - if (MaskMatch(attributes, MeshDefinition::NORMALS) && - !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals)) + if(MaskMatch(attributes, MeshDefinition::NORMALS) && + !ReadAttribAccessor(node.GetChild("normals"), meshDef.mNormals)) { - mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), - "normals")); + mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "normals")); } - if (MaskMatch(attributes, MeshDefinition::TEX_COORDS) && - !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords)) + if(MaskMatch(attributes, MeshDefinition::TEX_COORDS) && + !ReadAttribAccessor(node.GetChild("textures"), meshDef.mTexCoords)) { - mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), - "textures")); + mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "textures")); } - if (MaskMatch(attributes, MeshDefinition::TANGENTS) && - !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents)) + if(MaskMatch(attributes, MeshDefinition::TANGENTS) && + !ReadAttribAccessor(node.GetChild("tangents"), meshDef.mTangents)) { - mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), - "tangents")); + mOnError(FormatString("mesh %d: Failed to read %s.", resources.mMeshes.size(), "tangents")); } // NOTE: we're no longer reading bitangents as these are calculated in the shaders. - if (ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx)) + if(ReadIndex(node.GetChild("skeleton"), meshDef.mSkeletonIdx)) { - if (!MaskMatch(attributes, MeshDefinition::JOINTS_0) && - !MaskMatch(attributes, MeshDefinition::WEIGHTS_0)) + if(!MaskMatch(attributes, MeshDefinition::JOINTS_0) && + !MaskMatch(attributes, MeshDefinition::WEIGHTS_0)) { mOnError(FormatString("mesh %d: Expected joints0 / weights0 attribute(s) missing.", - resources.mMeshes.size())); + resources.mMeshes.size())); } - else if (!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) || - !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0)) + else if(!ReadAttribAccessor(node.GetChild("joints0"), meshDef.mJoints0) || + !ReadAttribAccessor(node.GetChild("weights0"), meshDef.mWeights0)) { mOnError(FormatString("mesh %d: Failed to read skinning information.", - resources.mMeshes.size())); + resources.mMeshes.size())); } } - if (auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER)) + if(auto blendshapeHeader = node.GetChild(BLEND_SHAPE_HEADER)) { std::string blendShapeVersion; ReadString(blendshapeHeader->GetChild(VERSION), blendShapeVersion); - if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0)) + if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_1_0)) { meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_1_0; } - else if (0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0)) + else if(0u == blendShapeVersion.compare(BLEND_SHAPE_VERSION_2_0)) { meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0; } - switch (meshDef.mBlendShapeVersion) + switch(meshDef.mBlendShapeVersion) { case BlendShapes::Version::VERSION_1_0: case BlendShapes::Version::VERSION_2_0: // FALL THROUGH @@ -860,12 +874,12 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour } } - if (auto blendShapes = node.GetChild(BLEND_SHAPES) ) + if(auto blendShapes = node.GetChild(BLEND_SHAPES)) { meshDef.mBlendShapes.resize(blendShapes->Size()); auto index = 0u; - for (auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index) + for(auto it = blendShapes->CBegin(), endIt = blendShapes->CEnd(); it != endIt; ++it, ++index) { // Each blend shape is stored as the difference with the original mesh. @@ -873,15 +887,15 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour auto& blendShape = meshDef.mBlendShapes[index]; ReadString(blendShapeNode.GetChild("name"), blendShape.name); - if (auto position = blendShapeNode.GetChild("positions")) + if(auto position = blendShapeNode.GetChild("positions")) { ReadAttribAccessor(position, blendShape.deltas); } - if (auto normals = blendShapeNode.GetChild("normals")) + if(auto normals = blendShapeNode.GetChild("normals")) { ReadAttribAccessor(normals, blendShape.normals); } - if (auto tangents = blendShapeNode.GetChild("tangents")) + if(auto tangents = blendShapeNode.GetChild("tangents")) { ReadAttribAccessor(tangents, blendShape.tangents); } @@ -890,7 +904,7 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour } bool flipV; - if (ReadBool(node.GetChild("flipV"), flipV)) + if(ReadBool(node.GetChild("flipV"), flipV)) { meshDef.mFlags |= flipV * MeshDefinition::FLIP_UVS_VERTICAL; } @@ -900,111 +914,108 @@ void DliLoader::Impl::ParseMeshes(const TreeNode* meshes, ResourceBundle& resour } } -void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, - ResourceBundle& resources) +void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode convertColorCode, ResourceBundle& resources) { - for (auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0) + for(auto i0 = materials->CBegin(), i1 = materials->CEnd(); i0 != i1; ++i0) { auto& node = (*i0).second; MaterialDefinition materialDef; - if (auto eEnvironment = node.GetChild("environment")) + if(auto eEnvironment = node.GetChild("environment")) { ReadIndex(eEnvironment, materialDef.mEnvironmentIdx); - if (static_cast(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size()) + if(static_cast(materialDef.mEnvironmentIdx) >= resources.mEnvironmentMaps.size()) { - ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << - ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << - resources.mEnvironmentMaps.size() << ")."; + ExceptionFlinger(ASSERT_LOCATION) << "material " << resources.mMaterials.size() << ": Environment index " << materialDef.mEnvironmentIdx << " out of bounds (" << resources.mEnvironmentMaps.size() << ")."; } } //TODO : need to consider AGIF std::vector texturePaths; - std::string texturePath; - if (ReadString(node.GetChild("albedoMap"), texturePath)) + std::string texturePath; + if(ReadString(node.GetChild("albedoMap"), texturePath)) { ToUnixFileSeparators(texturePath); const auto semantic = MaterialDefinition::ALBEDO; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); - materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY. + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); + materialDef.mFlags |= semantic | MaterialDefinition::TRANSPARENCY; // NOTE: only in dli does single / separate ALBEDO texture mean TRANSPARENCY. } - if (ReadString(node.GetChild("albedoMetallicMap"), texturePath)) + if(ReadString(node.GetChild("albedoMetallicMap"), texturePath)) { ToUnixFileSeparators(texturePath); - if (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "albedo")); } const auto semantic = MaterialDefinition::ALBEDO | MaterialDefinition::METALLIC; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic; } - if (ReadString(node.GetChild("metallicRoughnessMap"), texturePath)) + if(ReadString(node.GetChild("metallicRoughnessMap"), texturePath)) { ToUnixFileSeparators(texturePath); - if (MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "metallic")); } const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic | - // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow. - (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); + // We have a metallic-roughhness map and the first texture did not have albedo semantics - we're in the transparency workflow. + (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); } - if (ReadString(node.GetChild("normalMap"), texturePath)) + if(ReadString(node.GetChild("normalMap"), texturePath)) { ToUnixFileSeparators(texturePath); const auto semantic = MaterialDefinition::NORMAL; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic | - // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow. - (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); + // We have a standalone normal map and the first texture did not have albedo semantics - we're in the transparency workflow. + (MaskMatch(materialDef.mFlags, MaterialDefinition::ALBEDO) * MaterialDefinition::TRANSPARENCY); } - if (ReadString(node.GetChild("normalRoughnessMap"), texturePath)) + if(ReadString(node.GetChild("normalRoughnessMap"), texturePath)) { ToUnixFileSeparators(texturePath); - if (MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::NORMAL)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "normal")); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "roughness")); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY)) { mOnError(FormatString("material %d: conflicting semantics; already set %s.", resources.mMaterials.size(), "transparency")); } const auto semantic = MaterialDefinition::NORMAL | MaterialDefinition::ROUGHNESS; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic; } - if (ReadString(node.GetChild("subsurfaceMap"), texturePath)) + if(ReadString(node.GetChild("subsurfaceMap"), texturePath)) { ToUnixFileSeparators(texturePath); const auto semantic = MaterialDefinition::SUBSURFACE; - materialDef.mTextureStages.push_back({ semantic, TextureDefinition{ std::move(texturePath) } }); + materialDef.mTextureStages.push_back({semantic, TextureDefinition{std::move(texturePath)}}); materialDef.mFlags |= semantic; } - if (ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) && - materialDef.mColor.a < 1.0f) + if(ReadColorCodeOrColor(&node, materialDef.mColor, convertColorCode) && + materialDef.mColor.a < 1.0f) { materialDef.mFlags |= MaterialDefinition::TRANSPARENCY; } @@ -1013,9 +1024,9 @@ void DliLoader::Impl::ParseMaterials(const TreeNode* materials, ConvertColorCode ReadFloat(node.GetChild("roughness"), materialDef.mRoughness); bool mipmaps; - if (ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps) + if(ReadBool(node.GetChild("mipmap"), mipmaps) && mipmaps) { - for (auto& ts : materialDef.mTextureStages) + for(auto& ts : materialDef.mTextureStages) { ts.mTexture.mSamplerFlags |= SamplerFlags::FILTER_MIPMAP_LINEAR; } @@ -1039,13 +1050,13 @@ void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadP virtual bool Map(Index iDli, Index iScene) override { - Entry idx{ iDli, iScene }; - auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx); - if (iInsert == mIndices.end() || iInsert->iDli != iDli) + Entry idx{iDli, iScene}; + auto iInsert = std::lower_bound(mIndices.begin(), mIndices.end(), idx); + if(iInsert == mIndices.end() || iInsert->iDli != iDli) { mIndices.insert(iInsert, idx); } - else if (iInsert->iScene != iScene) + else if(iInsert->iScene != iScene) { return false; } @@ -1054,10 +1065,9 @@ void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadP virtual unsigned int Resolve(Index iDli) override { - auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, - [](const Entry& idx, Index iDli) { - return idx.iDli < iDli; - }); + auto iFind = std::lower_bound(mIndices.begin(), mIndices.end(), iDli, [](const Entry& idx, Index iDli) { + return idx.iDli < iDli; + }); DALI_ASSERT_ALWAYS(iFind != mIndices.end()); return iFind->iScene; } @@ -1078,24 +1088,28 @@ void DliLoader::Impl::ParseNodes(const TreeNode* const nodes, Index index, LoadP ParseNodesInternal(nodes, index, parents, params, mapper); auto& scene = params.output.mScene; - for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0) + for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 < i1; ++i0) { - for (auto& c : scene.GetNode(i0)->mConstraints) + for(auto& c : scene.GetNode(i0)->mConstraints) { c.mSourceIdx = mapper.Resolve(c.mSourceIdx); } } } -void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, - std::vector& inOutParentStack, LoadParams& params, IIndexMapper& mapper) +void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index index, std::vector& inOutParentStack, LoadParams& params, IIndexMapper& mapper) { // Properties that may be resolved from a JSON value with ReadInt() -- or default to 0. - struct IndexProperty { ResourceType::Value type; const TreeNode* source; Index& target; }; + struct IndexProperty + { + ResourceType::Value type; + const TreeNode* source; + Index& target; + }; std::vector resourceIds; resourceIds.reserve(4); - if (auto node = GetNthChild(nodes, index)) + if(auto node = GetNthChild(nodes, index)) { NodeDefinition nodeDef; nodeDef.mParentIdx = inOutParentStack.empty() ? INVALID_INDEX : inOutParentStack.back(); @@ -1115,32 +1129,32 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde // not successful then reads it as a vector2. ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 3) || ReadVector(node->GetChild("size"), nodeDef.mSize.AsFloat(), 2) || - ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) || - ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2); + ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 3) || + ReadVector(node->GetChild("bounds"), nodeDef.mSize.AsFloat(), 2); // visibility ReadBool(node->GetChild("visible"), nodeDef.mIsVisible); // type classification - if (auto eCustomization = node->GetChild("customization")) // customization + if(auto eCustomization = node->GetChild("customization")) // customization { std::string tag; - if (ReadString(eCustomization->GetChild("tag"), tag)) + if(ReadString(eCustomization->GetChild("tag"), tag)) { - nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{ tag }); + nodeDef.mCustomization.reset(new NodeDefinition::CustomizationDefinition{tag}); } } else // something renderable maybe { std::unique_ptr renderable; - ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type. + ModelNode* modelNode = nullptr; // no ownership, aliasing renderable for the right type. - const TreeNode* eRenderable = nullptr; - if ((eRenderable = node->GetChild("model"))) + const TreeNode* eRenderable = nullptr; + if((eRenderable = node->GetChild("model"))) { // check for mesh before allocating - this can't be missing. auto eMesh = eRenderable->GetChild("mesh"); - if (!eMesh) + if(!eMesh) { ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition."; } @@ -1148,13 +1162,13 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde modelNode = new ModelNode(); renderable.reset(modelNode); - resourceIds.push_back({ ResourceType::Mesh, eMesh, modelNode->mMeshIdx }); + resourceIds.push_back({ResourceType::Mesh, eMesh, modelNode->mMeshIdx}); } - else if ((eRenderable = node->GetChild("arc"))) + else if((eRenderable = node->GetChild("arc"))) { // check for mesh before allocating - this can't be missing. auto eMesh = eRenderable->GetChild("mesh"); - if (!eMesh) + if(!eMesh) { ExceptionFlinger(ASSERT_LOCATION) << "node " << nodeDef.mName << ": Missing mesh definition."; } @@ -1163,26 +1177,26 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde renderable.reset(arcNode); modelNode = arcNode; - resourceIds.push_back({ ResourceType::Mesh, eMesh, arcNode->mMeshIdx }); + resourceIds.push_back({ResourceType::Mesh, eMesh, arcNode->mMeshIdx}); ReadArcField(eRenderable, *arcNode); } - if (renderable) // process common properties of all renderables + register payload + if(renderable) // process common properties of all renderables + register payload { // shader renderable->mShaderIdx = 0; - auto eShader = eRenderable->GetChild("shader"); - resourceIds.push_back({ ResourceType::Shader, eShader, renderable->mShaderIdx }); + auto eShader = eRenderable->GetChild("shader"); + resourceIds.push_back({ResourceType::Shader, eShader, renderable->mShaderIdx}); // color - if (modelNode) + if(modelNode) { - modelNode->mMaterialIdx = 0; // must offer default of 0 - auto eMaterial = eRenderable->GetChild("material"); - resourceIds.push_back({ ResourceType::Material, eMaterial, modelNode->mMaterialIdx }); + modelNode->mMaterialIdx = 0; // must offer default of 0 + auto eMaterial = eRenderable->GetChild("material"); + resourceIds.push_back({ResourceType::Material, eMaterial, modelNode->mMaterialIdx}); - if (!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode)) + if(!ReadColorCodeOrColor(eRenderable, modelNode->mColor, params.input.mConvertColorCode)) { ReadColorCodeOrColor(node, modelNode->mColor, params.input.mConvertColorCode); } @@ -1194,82 +1208,83 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde // Resolve ints - default to 0 if undefined auto& output = params.output; - for (auto& idRes : resourceIds) + for(auto& idRes : resourceIds) { Index iCheck = 0; - switch (idRes.type) + switch(idRes.type) { - case ResourceType::Shader: - iCheck = output.mResources.mShaders.size(); - break; + case ResourceType::Shader: + iCheck = output.mResources.mShaders.size(); + break; - case ResourceType::Mesh: - iCheck = output.mResources.mMeshes.size(); - break; + case ResourceType::Mesh: + iCheck = output.mResources.mMeshes.size(); + break; - case ResourceType::Material: - iCheck = output.mResources.mMaterials.size(); - break; + case ResourceType::Material: + iCheck = output.mResources.mMaterials.size(); + break; - default: - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << - idRes.type << " (Programmer error)"; + default: + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid resource type: " << idRes.type << " (Programmer error)"; } - if (!idRes.source) + if(!idRes.source) { idRes.target = 0; } - else if (idRes.source->GetType() != TreeNode::INTEGER) + else if(idRes.source->GetType() != TreeNode::INTEGER) { - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << - GetResourceTypeName(idRes.type) << " index type."; + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": Invalid " << GetResourceTypeName(idRes.type) << " index type."; } else { idRes.target = idRes.source->GetInteger(); } - if (idRes.target >= iCheck) + if(idRes.target >= iCheck) { - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << - GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << - iCheck << ")."; + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ": " << GetResourceTypeName(idRes.type) << " index " << idRes.target << " out of bounds (" << iCheck << ")."; } } resourceIds.clear(); // Extra properties - if (auto eExtras = node->GetChild("extras")) + if(auto eExtras = node->GetChild("extras")) { auto& extras = nodeDef.mExtras; extras.reserve(eExtras->Size()); NodeDefinition::Extra e; - for (auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0) + for(auto i0 = eExtras->CBegin(), i1 = eExtras->CEnd(); i0 != i1; ++i0) { auto eExtra = *i0; - e.mKey = eExtra.first; - if (e.mKey.empty()) + e.mKey = eExtra.first; + if(e.mKey.empty()) { mOnError(FormatString("node %d: empty string is invalid for name of extra %d; ignored.", - index, extras.size())); + index, + extras.size())); continue; } e.mValue = ReadPropertyValue(eExtra.second); - if (e.mValue.GetType() == Property::Type::NONE) + if(e.mValue.GetType() == Property::Type::NONE) { mOnError(FormatString("node %d: failed to interpret value of extra '%s' : %s; ignored.", - index, e.mKey.c_str(), eExtra.second.GetString())); + index, + e.mKey.c_str(), + eExtra.second.GetString())); } else { auto iInsert = std::lower_bound(extras.begin(), extras.end(), e); - if (iInsert != extras.end() && iInsert->mKey == e.mKey) + if(iInsert != extras.end() && iInsert->mKey == e.mKey) { mOnError(FormatString("node %d: extra '%s' already defined; overriding with %s.", - index, e.mKey.c_str(), eExtra.second.GetString())); + index, + e.mKey.c_str(), + eExtra.second.GetString())); *iInsert = std::move(e); } else @@ -1281,29 +1296,33 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde } // Constraints - if (auto eConstraints = node->GetChild("constraints")) + if(auto eConstraints = node->GetChild("constraints")) { auto& constraints = nodeDef.mConstraints; constraints.reserve(eConstraints->Size()); ConstraintDefinition cDef; - for (auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0) + for(auto i0 = eConstraints->CBegin(), i1 = eConstraints->CEnd(); i0 != i1; ++i0) { auto eConstraint = *i0; - if (!ReadIndex(&eConstraint.second, cDef.mSourceIdx)) + if(!ReadIndex(&eConstraint.second, cDef.mSourceIdx)) { mOnError(FormatString("node %d: node ID %s for constraint %d is invalid; ignored.", - index, eConstraint.second.GetString(), constraints.size())); + index, + eConstraint.second.GetString(), + constraints.size())); } else { cDef.mProperty = eConstraint.first; auto iInsert = std::lower_bound(constraints.begin(), constraints.end(), cDef); - if (iInsert != constraints.end() && *iInsert == cDef) + if(iInsert != constraints.end() && *iInsert == cDef) { mOnError(FormatString("node %d: constraint %s@%d already defined; ignoring.", - index, cDef.mProperty.c_str(), cDef.mSourceIdx)); + index, + cDef.mProperty.c_str(), + cDef.mSourceIdx)); } else { @@ -1315,53 +1334,52 @@ void DliLoader::Impl::ParseNodesInternal(const TreeNode* const nodes, Index inde // Determine index for mapping const unsigned int myIndex = output.mScene.GetNodeCount(); - if (!mapper.Map(index, myIndex)) + if(!mapper.Map(index, myIndex)) { mOnError(FormatString("node %d: error mapping dli index %d: node has multiple parents. Ignoring subtree.")); return; } // if the node is a bone in a skeletal animation, it will have the inverse bind pose matrix. - Matrix invBindMatrix{ false }; - if (ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking? + Matrix invBindMatrix{false}; + if(ReadVector(node->GetChild("inverseBindPoseMatrix"), invBindMatrix.AsFloat(), 16u)) // TODO: more robust error checking? { mInverseBindMatrices[myIndex] = invBindMatrix; } // Register nodeDef auto rawDef = output.mScene.AddNode(std::make_unique(std::move(nodeDef))); - if (rawDef) // NOTE: no ownership. Guaranteed to stay in scope. + if(rawDef) // NOTE: no ownership. Guaranteed to stay in scope. { // ...And only then parse children. - if (auto children = node->GetChild("children")) + if(auto children = node->GetChild("children")) { inOutParentStack.push_back(myIndex); rawDef->mChildren.reserve(children->Size()); uint32_t iChild = 0; - for (auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild) + for(auto j0 = children->CBegin(), j1 = children->CEnd(); j0 != j1; ++j0, ++iChild) { auto& child = (*j0).second; - if (child.GetType() == TreeNode::INTEGER) + if(child.GetType() == TreeNode::INTEGER) { ParseNodesInternal(nodes, child.GetInteger(), inOutParentStack, params, mapper); // child object is created in scene definition. } else { - ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << - ": invalid index type."; + ExceptionFlinger(ASSERT_LOCATION) << "node " << index << ", child " << iChild << ": invalid index type."; } } inOutParentStack.pop_back(); } - else if (rawDef->mCustomization) + else if(rawDef->mCustomization) { mOnError(FormatString("node %d: not an actual customization without children.", index)); } - if (auto proc = params.input.mNodePropertyProcessor) // optional processing + if(auto proc = params.input.mNodePropertyProcessor) // optional processing { // WARNING: constraint IDs are not resolved at this point. Property::Map nodeData; @@ -1381,19 +1399,19 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& auto& definitions = params.output.mAnimationDefinitions; definitions.reserve(definitions.size() + tnAnimations->Size()); - for (TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd(); - iAnim != iAnimEnd; ++iAnim) + for(TreeNode::ConstIterator iAnim = tnAnimations->CBegin(), iAnimEnd = tnAnimations->CEnd(); + iAnim != iAnimEnd; + ++iAnim) { - const TreeNode& tnAnim = (*iAnim).second; + const TreeNode& tnAnim = (*iAnim).second; AnimationDefinition animDef; ReadString(tnAnim.GetChild(NAME), animDef.mName); - auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, - [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { + auto iFind = std::lower_bound(definitions.begin(), definitions.end(), animDef, [](const AnimationDefinition& ad0, const AnimationDefinition& ad1) { return ad0.mName < ad1.mName; }); const bool overwrite = iFind != definitions.end() && iFind->mName == animDef.mName; - if (overwrite) + if(overwrite) { mOnError(FormatString("Pre-existing animation with name '%s' is being overwritten.", animDef.mName.c_str())); } @@ -1403,103 +1421,107 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& // than our frame delay) to not be restrictive WRT replaying. If anything needs // to occur more frequently, then Animations are likely not your solution anyway. animDef.mDuration = AnimationDefinition::MIN_DURATION_SECONDS; - if (!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration)) + if(!ReadFloat(tnAnim.GetChild("duration"), animDef.mDuration)) { mOnError(FormatString("Animation '%s' fails to define '%s', defaulting to %f.", - animDef.mName.c_str(), "duration", animDef.mDuration)); + animDef.mName.c_str(), + "duration", + animDef.mDuration)); } // Get loop count - # of playbacks. Default is once. 0 means repeat indefinitely. animDef.mLoopCount = 1; - if (ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) && - animDef.mLoopCount < 0) + if(ReadInt(tnAnim.GetChild("loopCount"), animDef.mLoopCount) && + animDef.mLoopCount < 0) { animDef.mLoopCount = 0; } std::string endAction; - if (ReadString(tnAnim.GetChild("endAction"), endAction)) + if(ReadString(tnAnim.GetChild("endAction"), endAction)) { - if ("BAKE" == endAction) + if("BAKE" == endAction) { animDef.mEndAction = Animation::BAKE; } - else if ("DISCARD" == endAction) + else if("DISCARD" == endAction) { animDef.mEndAction = Animation::DISCARD; } - else if ("BAKE_FINAL" == endAction) + else if("BAKE_FINAL" == endAction) { animDef.mEndAction = Animation::BAKE_FINAL; } } - if (ReadString(tnAnim.GetChild("disconnectAction"), endAction)) + if(ReadString(tnAnim.GetChild("disconnectAction"), endAction)) { - if ("BAKE" == endAction) + if("BAKE" == endAction) { animDef.mDisconnectAction = Animation::BAKE; } - else if ("DISCARD" == endAction) + else if("DISCARD" == endAction) { animDef.mDisconnectAction = Animation::DISCARD; } - else if ("BAKE_FINAL" == endAction) + else if("BAKE_FINAL" == endAction) { animDef.mDisconnectAction = Animation::BAKE_FINAL; } } - if (const TreeNode* tnProperties = tnAnim.GetChild("properties")) + if(const TreeNode* tnProperties = tnAnim.GetChild("properties")) { animDef.mProperties.reserve(tnProperties->Size()); - for (TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd(); - iProperty != iPropertyEnd; ++iProperty) + for(TreeNode::ConstIterator iProperty = tnProperties->CBegin(), iPropertyEnd = tnProperties->CEnd(); + iProperty != iPropertyEnd; + ++iProperty) { - const TreeNode &tnProperty = (*iProperty).second; + const TreeNode& tnProperty = (*iProperty).second; AnimatedProperty animProp; - if (!ReadString(tnProperty.GetChild("node"), animProp.mNodeName)) + if(!ReadString(tnProperty.GetChild("node"), animProp.mNodeName)) { mOnError(FormatString("Animation '%s': Failed to read the 'node' tag.", animDef.mName.c_str())); continue; } - if (!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName)) + if(!ReadString(tnProperty.GetChild("property"), animProp.mPropertyName)) { mOnError(FormatString("Animation '%s': Failed to read the 'property' tag", animDef.mName.c_str())); continue; } // these are the defaults - animProp.mTimePeriod.delaySeconds = 0.f; + animProp.mTimePeriod.delaySeconds = 0.f; animProp.mTimePeriod.durationSeconds = animDef.mDuration; - if (!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod)) + if(!ReadTimePeriod(tnProperty.GetChild("timePeriod"), animProp.mTimePeriod)) { mOnError(FormatString("Animation '%s': timePeriod missing in Property #%d: defaulting to %f.", - animDef.mName.c_str(), animDef.mProperties.size(), animProp.mTimePeriod.durationSeconds)); + animDef.mName.c_str(), + animDef.mProperties.size(), + animProp.mTimePeriod.durationSeconds)); } std::string alphaFunctionValue; - if (ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue)) + if(ReadString(tnProperty.GetChild("alphaFunction"), alphaFunctionValue)) { animProp.mAlphaFunction = GetAlphaFunction(alphaFunctionValue); } - if (const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin")) + if(const TreeNode* tnKeyFramesBin = tnProperty.GetChild("keyFramesBin")) { DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name"); std::ifstream binAniFile; - std::string animationFilename; - if (ReadString(tnKeyFramesBin->GetChild(URL), animationFilename)) + std::string animationFilename; + if(ReadString(tnKeyFramesBin->GetChild(URL), animationFilename)) { std::string animationFullPath = params.input.mAnimationsPath + animationFilename; binAniFile.open(animationFullPath, std::ios::binary); - if (binAniFile.fail()) + if(binAniFile.fail()) { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << - animationFullPath << "'"; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to open animation data '" << animationFullPath << "'"; } } @@ -1519,12 +1541,12 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& //so, if it is vector3 we assume is position or scale keys, if it is vector4 we assume is rotation, // otherwise are blend shape weight keys. // TODO support for binary header with size information - Property::Type propType = Property::FLOAT; // assume blend shape weights - if (animProp.mPropertyName == "orientation") + Property::Type propType = Property::FLOAT; // assume blend shape weights + if(animProp.mPropertyName == "orientation") { propType = Property::VECTOR4; } - else if ((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale")) + else if((animProp.mPropertyName == "position") || (animProp.mPropertyName == "scale")) { propType = Property::VECTOR3; } @@ -1533,18 +1555,18 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& // NOTE: right now we're just using AlphaFunction::LINEAR. unsigned char dummyAlphaFunction; - float progress; + float progress; Property::Value propValue; - for (int key = 0; key < numKeys; key++) + for(int key = 0; key < numKeys; key++) { binAniFile.read(reinterpret_cast(&progress), sizeof(float)); - if (propType == Property::VECTOR3) + if(propType == Property::VECTOR3) { Vector3 value; binAniFile.read(reinterpret_cast(value.AsFloat()), sizeof(float) * 3); propValue = Property::Value(value); } - else if (propType == Property::VECTOR4) + else if(propType == Property::VECTOR4) { Vector4 value; binAniFile.read(reinterpret_cast(value.AsFloat()), sizeof(float) * 4); @@ -1562,16 +1584,16 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& animProp.mKeyFrames.Add(progress, propValue, AlphaFunction::LINEAR); } } - else if (const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames")) + else if(const TreeNode* tnKeyFrames = tnProperty.GetChild("keyFrames")) { DALI_ASSERT_ALWAYS(!animProp.mPropertyName.empty() && "Animation must specify a property name"); animProp.mKeyFrames = KeyFrames::New(); float progress = 0.0f; - for (auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0) + for(auto i0 = tnKeyFrames->CBegin(), i1 = tnKeyFrames->CEnd(); i1 != i0; ++i0) { const TreeNode::KeyNodePair& kfKeyChild = *i0; - bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress); + bool readResult = ReadFloat(kfKeyChild.second.GetChild("progress"), progress); DALI_ASSERT_ALWAYS(readResult && "Key frame entry must have 'progress'"); const TreeNode* tnValue = kfKeyChild.second.GetChild("value"); @@ -1580,8 +1602,8 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& // For the "orientation" property, convert from Vector4 -> Rotation value // This work-around is preferable to a null-pointer exception in the DALi update thread Property::Value propValue(ReadPropertyValue(*tnValue)); - if (propValue.GetType() == Property::VECTOR4 && - animProp.mPropertyName == "orientation") + if(propValue.GetType() == Property::VECTOR4 && + animProp.mPropertyName == "orientation") { Vector4 v; propValue.Get(v); @@ -1589,8 +1611,8 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& } AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT); - std::string alphaFuncStr; - if (ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr)) + std::string alphaFuncStr; + if(ReadString(kfKeyChild.second.GetChild("alphaFunction"), alphaFuncStr)) { kfAlphaFunction = GetAlphaFunction(alphaFuncStr); } @@ -1601,14 +1623,14 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& else { const TreeNode* tnValue = tnProperty.GetChild("value"); - if (tnValue) + if(tnValue) { - animProp.mValue.reset(new AnimatedProperty::Value{ ReadPropertyValue(*tnValue) }); + animProp.mValue.reset(new AnimatedProperty::Value{ReadPropertyValue(*tnValue)}); } else { mOnError(FormatString("Property '%s' fails to define target value.", - animProp.mPropertyName.c_str())); + animProp.mPropertyName.c_str())); } ReadBool(tnProperty.GetChild("relative"), animProp.mValue->mIsRelative); @@ -1618,7 +1640,7 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& } } - if (overwrite) + if(overwrite) { *iFind = std::move(animDef); } @@ -1627,7 +1649,7 @@ void DliLoader::Impl::ParseAnimations(const TreeNode* tnAnimations, LoadParams& iFind = definitions.insert(iFind, std::move(animDef)); } - if (auto proc = params.input.mAnimationPropertyProcessor) // optional processing + if(auto proc = params.input.mAnimationPropertyProcessor) // optional processing { Property::Map map; ParseProperties(tnAnim, map); @@ -1641,23 +1663,23 @@ void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationG auto& animGroups = params.output.mAnimationGroupDefinitions; int numGroups = 0; - for (auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd(); - iGroups != iGroupsEnd; ++iGroups, ++numGroups) + for(auto iGroups = tnAnimationGroups->CBegin(), iGroupsEnd = tnAnimationGroups->CEnd(); + iGroups != iGroupsEnd; + ++iGroups, ++numGroups) { const auto& tnGroup = *iGroups; - auto tnName = tnGroup.second.GetChild(NAME); + auto tnName = tnGroup.second.GetChild(NAME); std::string groupName; - if (!tnName || !ReadString(tnName, groupName)) + if(!tnName || !ReadString(tnName, groupName)) { mOnError(FormatString("Failed to get the name for the Animation group %d; ignoring.", numGroups)); continue; } - auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, - [](const AnimationGroupDefinition& group, const std::string& name) { + auto iFind = std::lower_bound(animGroups.begin(), animGroups.end(), groupName, [](const AnimationGroupDefinition& group, const std::string& name) { return group.mName < name; }); - if (iFind != animGroups.end() && iFind->mName == groupName) + if(iFind != animGroups.end() && iFind->mName == groupName) { mOnError(FormatString("Animation group with name '%s' already exists; new entries will be merged.", groupName.c_str())); } @@ -1669,11 +1691,11 @@ void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationG iFind->mName = groupName; auto tnAnims = tnGroup.second.GetChild("animations"); - if (tnAnims && tnAnims->Size() > 0) + if(tnAnims && tnAnims->Size() > 0) { auto& anims = iFind->mAnimations; anims.reserve(anims.size() + tnAnims->Size()); - for (auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims) + for(auto iAnims = tnAnims->CBegin(), iAnimsEnd = tnAnims->CEnd(); iAnims != iAnimsEnd; ++iAnims) { anims.push_back((*iAnims).second.GetString()); } @@ -1683,23 +1705,23 @@ void DliLoader::Impl::ParseAnimationGroups(const Toolkit::TreeNode* tnAnimationG void DliLoader::Impl::GetCameraParameters(std::vector& cameras) const { - if (const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras")) + if(const TreeNode* jsonCameras = mParser.GetRoot()->GetChild("cameras")) { cameras.resize(jsonCameras->Size()); auto iCamera = cameras.begin(); - for (auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0) + for(auto i0 = jsonCameras->CBegin(), i1 = jsonCameras->CEnd(); i0 != i1; ++i0) { auto& jsonCamera = (*i0).second; ReadFloat(jsonCamera.GetChild("fov"), iCamera->yFov); ReadFloat(jsonCamera.GetChild("near"), iCamera->zNear); ReadFloat(jsonCamera.GetChild("far"), iCamera->zFar); - if (ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u)) + if(ReadVector(jsonCamera.GetChild("orthographic"), iCamera->orthographicSize.AsFloat(), 4u)) { iCamera->isPerspective = false; } - if (auto jsonMatrix = jsonCamera.GetChild("matrix")) + if(auto jsonMatrix = jsonCamera.GetChild("matrix")) { ReadVector(jsonMatrix, iCamera->matrix.AsFloat(), 16u); } @@ -1711,62 +1733,64 @@ void DliLoader::Impl::GetCameraParameters(std::vector& cameras void DliLoader::Impl::GetLightParameters(std::vector& lights) const { - if (const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights")) + if(const TreeNode* jsonLights = mParser.GetRoot()->GetChild("lights")) { lights.resize(jsonLights->Size()); auto iLight = lights.begin(); - for (auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0) + for(auto i0 = jsonLights->CBegin(), i1 = jsonLights->CEnd(); i0 != i1; ++i0) { auto& jsonLight = (*i0).second; - if (!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16)) + if(!ReadVector(jsonLight.GetChild("matrix"), iLight->transform.AsFloat(), 16)) { mOnError( FormatString("Failed to parse light %d - \"matrix\" child with 16 floats expected.\n", - std::distance(jsonLights->CBegin(), i0))); + std::distance(jsonLights->CBegin(), i0))); continue; } int shadowMapSize = 0; - if (ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0) + if(ReadInt(jsonLight.GetChild(SHADOW_MAP_SIZE), shadowMapSize) && shadowMapSize < 0) { mOnError( FormatString("Failed to parse light %d - %s has an invalid value.", - std::distance(jsonLights->CBegin(), i0), SHADOW_MAP_SIZE)); + std::distance(jsonLights->CBegin(), i0), + SHADOW_MAP_SIZE)); continue; } iLight->shadowMapSize = shadowMapSize; float orthoSize = 0.f; - if (ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) && - (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize))) + if(ReadFloat(jsonLight.GetChild(ORTHOGRAPHIC_SIZE), orthoSize) && + (orthoSize < .0f || std::isnan(orthoSize) || std::isinf(orthoSize))) { mOnError( FormatString("Failed to parse light %d - %s has an invalid value.", - std::distance(jsonLights->CBegin(), i0), ORTHOGRAPHIC_SIZE)); + std::distance(jsonLights->CBegin(), i0), + ORTHOGRAPHIC_SIZE)); continue; } iLight->orthographicSize = orthoSize; - if ((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f)) + if((iLight->shadowMapSize > 0) != (iLight->orthographicSize > .0f)) { mOnError(FormatString( "Light %d: Both shadow map size and orthographic size must be set for shadows to work.", - std::distance(jsonLights->CBegin(), i0))); + std::distance(jsonLights->CBegin(), i0))); } - if (!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional + if(!ReadVector(jsonLight.GetChild("color"), iLight->color.AsFloat(), 3)) // color is optional { - iLight->color = Vector3::ONE; // default to white + iLight->color = Vector3::ONE; // default to white } - if (!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional + if(!ReadFloat(jsonLight.GetChild("intensity"), iLight->intensity)) // intensity is optional { - iLight->intensity = 1.0f; // default to 1.0 + iLight->intensity = 1.0f; // default to 1.0 } - if (!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional + if(!ReadFloat(jsonLight.GetChild("shadowIntensity"), iLight->shadowIntensity)) // intensity is optional { - iLight->shadowIntensity = 1.0f; // default to 1.0 + iLight->shadowIntensity = 1.0f; // default to 1.0 } ++iLight; @@ -1774,5 +1798,5 @@ void DliLoader::Impl::GetLightParameters(std::vector& lights) c } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/environment-definition.cpp b/dali-scene-loader/public-api/environment-definition.cpp index 16c8e2c..c95883f 100644 --- a/dali-scene-loader/public-api/environment-definition.cpp +++ b/dali-scene-loader/public-api/environment-definition.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,24 +23,22 @@ namespace Dali { namespace SceneLoader { - EnvironmentDefinition::RawData - EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const +EnvironmentDefinition::LoadRaw(const std::string& environmentsPath) const { RawData raw; - auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) { - if (path.empty()) + auto loadFn = [&environmentsPath](const std::string& path, CubeData& cd) { + if(path.empty()) { cd.data.resize(6); - for (auto& face : cd.data) + for(auto& face : cd.data) { - face.push_back(PixelData::New(new uint8_t[3]{ 0xff, 0xff, 0xff }, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY)); + face.push_back(PixelData::New(new uint8_t[3]{0xff, 0xff, 0xff}, 3, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY)); } } else if(!LoadCubeMapData(environmentsPath + path, cd)) { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" << - path << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to load cubemap texture from '" << path << "'."; } }; @@ -54,18 +52,18 @@ EnvironmentDefinition::Textures EnvironmentDefinition::Load(RawData&& raw) const Textures textures; // This texture should have 6 faces and only one mipmap - if (!raw.mDiffuse.data.empty()) + if(!raw.mDiffuse.data.empty()) { textures.mDiffuse = raw.mDiffuse.CreateTexture(); } // This texture should have 6 faces and 6 mipmaps - if (!raw.mSpecular.data.empty()) + if(!raw.mSpecular.data.empty()) { textures.mSpecular = raw.mSpecular.CreateTexture(); } return textures; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/gltf2-loader.cpp b/dali-scene-loader/public-api/gltf2-loader.cpp index 451060b..18923cf 100644 --- a/dali-scene-loader/public-api/gltf2-loader.cpp +++ b/dali-scene-loader/public-api/gltf2-loader.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. @@ -14,17 +14,20 @@ * limitations under the License. * */ +#include "dali-scene-loader/public-api/gltf2-loader.h" +#include +#include "dali-scene-loader/internal/gltf2-asset.h" #include "dali-scene-loader/public-api/load-result.h" -#include "dali-scene-loader/public-api/scene-definition.h" #include "dali-scene-loader/public-api/resource-bundle.h" -#include "dali-scene-loader/public-api/gltf2-loader.h" -#include "dali-scene-loader/public-api/utils.h" +#include "dali-scene-loader/public-api/scene-definition.h" #include "dali-scene-loader/public-api/shader-definition-factory.h" -#include "dali-scene-loader/internal/gltf2-asset.h" +#include "dali-scene-loader/public-api/utils.h" #include "dali/public-api/math/quaternion.h" -#include -#define ENUM_STRING_MAPPING(t, x) { #x, t::x } +#define ENUM_STRING_MAPPING(t, x) \ + { \ +#x, t::x \ + } namespace gt = gltf2; namespace js = json; @@ -47,20 +50,19 @@ const Geometry::Type GLTF2_TO_DALI_PRIMITIVES[]{ Geometry::LINE_STRIP, Geometry::TRIANGLES, Geometry::TRIANGLE_STRIP, - Geometry::TRIANGLE_FAN -}; //...because Dali swaps the last two. + Geometry::TRIANGLE_FAN}; //...because Dali swaps the last two. struct AttributeMapping { - gt::Attribute::Type mType; - MeshDefinition::Accessor MeshDefinition::* mAccessor; - uint16_t mElementSizeRequired; + gt::Attribute::Type mType; + MeshDefinition::Accessor MeshDefinition::*mAccessor; + uint16_t mElementSizeRequired; } ATTRIBUTE_MAPPINGS[]{ - { gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3) }, - { gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3) }, - { gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2) }, - { gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4) }, - { gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4) }, + {gt::Attribute::NORMAL, &MeshDefinition::mNormals, sizeof(Vector3)}, + {gt::Attribute::TANGENT, &MeshDefinition::mTangents, sizeof(Vector3)}, + {gt::Attribute::TEXCOORD_0, &MeshDefinition::mTexCoords, sizeof(Vector2)}, + {gt::Attribute::JOINTS_0, &MeshDefinition::mJoints0, sizeof(Vector4)}, + {gt::Attribute::WEIGHTS_0, &MeshDefinition::mWeights0, sizeof(Vector4)}, }; std::vector ReadAnimationArray(const json_value_s& j) @@ -70,9 +72,9 @@ std::vector ReadAnimationArray(const json_value_s& j) auto results = js::Read::Array::Read>(j); - for (auto& animation : results) + for(auto& animation : results) { - for (auto& channel : animation.mChannels) + for(auto& channel : animation.mChannels) { channel.mSampler.UpdateVector(animation.mSamplers); } @@ -89,124 +91,110 @@ void ApplyAccessorMinMax(const gt::Accessor& acc, float* values) } const auto BUFFER_READER = std::move(js::Reader() - .Register(*js::MakeProperty("byteLength", js::Read::Number, >::Buffer::mByteLength)) - .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri)) -); + .Register(*js::MakeProperty("byteLength", js::Read::Number, >::Buffer::mByteLength)) + .Register(*js::MakeProperty("uri", js::Read::StringView, >::Buffer::mUri))); const auto BUFFER_VIEW_READER = std::move(js::Reader() - .Register(*js::MakeProperty("buffer", gt::RefReader::Read, >::BufferView::mBuffer)) - .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferView::mByteOffset)) - .Register(*js::MakeProperty("byteLength", js::Read::Number, >::BufferView::mByteLength)) - .Register(*js::MakeProperty("byteStride", js::Read::Number, >::BufferView::mByteStride)) - .Register(*js::MakeProperty("target", js::Read::Number, >::BufferView::mTarget)) -); + .Register(*js::MakeProperty("buffer", gt::RefReader::Read, >::BufferView::mBuffer)) + .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferView::mByteOffset)) + .Register(*js::MakeProperty("byteLength", js::Read::Number, >::BufferView::mByteLength)) + .Register(*js::MakeProperty("byteStride", js::Read::Number, >::BufferView::mByteStride)) + .Register(*js::MakeProperty("target", js::Read::Number, >::BufferView::mTarget))); const auto BUFFER_VIEW_CLIENT_READER = std::move(js::Reader() - .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::BufferViewClient::mBufferView)) - .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferViewClient::mByteOffset)) -); + .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::BufferViewClient::mBufferView)) + .Register(*js::MakeProperty("byteOffset", js::Read::Number, >::BufferViewClient::mByteOffset))); const auto COMPONENT_TYPED_BUFFER_VIEW_CLIENT_READER = std::move(js::Reader() - .Register(*new js::Property>("bufferView", gt::RefReader::Read, >::ComponentTypedBufferViewClient::mBufferView)) - .Register(*new js::Property("byteOffset", js::Read::Number, >::ComponentTypedBufferViewClient::mByteOffset)) - .Register(*js::MakeProperty("componentType", js::Read::Enum, >::ComponentTypedBufferViewClient::mComponentType)) -); + .Register(*new js::Property>("bufferView", gt::RefReader::Read, >::ComponentTypedBufferViewClient::mBufferView)) + .Register(*new js::Property("byteOffset", js::Read::Number, >::ComponentTypedBufferViewClient::mByteOffset)) + .Register(*js::MakeProperty("componentType", js::Read::Enum, >::ComponentTypedBufferViewClient::mComponentType))); const auto ACCESSOR_SPARSE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::Sparse::mCount)) - .Register(*js::MakeProperty("indices", js::ObjectReader::Read, - >::Accessor::Sparse::mIndices)) - .Register(*js::MakeProperty("values", js::ObjectReader::Read, - >::Accessor::Sparse::mValues)) -); + .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::Sparse::mCount)) + .Register(*js::MakeProperty("indices", js::ObjectReader::Read, >::Accessor::Sparse::mIndices)) + .Register(*js::MakeProperty("values", js::ObjectReader::Read, >::Accessor::Sparse::mValues))); const auto ACCESSOR_READER = std::move(js::Reader() - .Register(*new js::Property>("bufferView", - gt::RefReader::Read, >::Accessor::mBufferView)) - .Register(*new js::Property("byteOffset", - js::Read::Number, >::Accessor::mByteOffset)) - .Register(*new js::Property("componentType", - js::Read::Enum, >::Accessor::mComponentType)) - .Register(*new js::Property("name", js::Read::StringView, >::Accessor::mName)) - .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::mCount)) - .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized)) - .Register(*js::MakeProperty("type", gt::ReadStringEnum, >::Accessor::mType)) - .Register(*js::MakeProperty("min", js::Read::Array, >::Accessor::mMin)) - .Register(*js::MakeProperty("max", js::Read::Array, >::Accessor::mMax)) - .Register(*new js::Property("sparse", js::ObjectReader::Read, - >::Accessor::SetSparse)) -); + .Register(*new js::Property>("bufferView", + gt::RefReader::Read, + >::Accessor::mBufferView)) + .Register(*new js::Property("byteOffset", + js::Read::Number, + >::Accessor::mByteOffset)) + .Register(*new js::Property("componentType", + js::Read::Enum, + >::Accessor::mComponentType)) + .Register(*new js::Property("name", js::Read::StringView, >::Accessor::mName)) + .Register(*js::MakeProperty("count", js::Read::Number, >::Accessor::mCount)) + .Register(*js::MakeProperty("normalized", js::Read::Boolean, >::Accessor::mNormalized)) + .Register(*js::MakeProperty("type", gt::ReadStringEnum, >::Accessor::mType)) + .Register(*js::MakeProperty("min", js::Read::Array, >::Accessor::mMin)) + .Register(*js::MakeProperty("max", js::Read::Array, >::Accessor::mMax)) + .Register(*new js::Property("sparse", js::ObjectReader::Read, >::Accessor::SetSparse))); const auto IMAGE_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) - .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri)) - .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType)) - .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::Image::mBufferView)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) + .Register(*js::MakeProperty("uri", js::Read::StringView, >::Image::mUri)) + .Register(*js::MakeProperty("mimeType", js::Read::StringView, >::Image::mMimeType)) + .Register(*js::MakeProperty("bufferView", gt::RefReader::Read, >::Image::mBufferView))); const auto SAMPLER_READER = std::move(js::Reader() - .Register(*js::MakeProperty("minFilter", js::Read::Enum, >::Sampler::mMinFilter)) - .Register(*js::MakeProperty("magFilter", js::Read::Enum, >::Sampler::mMagFilter)) - .Register(*js::MakeProperty("wrapS", js::Read::Enum, >::Sampler::mWrapS)) - .Register(*js::MakeProperty("wrapT", js::Read::Enum, >::Sampler::mWrapT)) -); + .Register(*js::MakeProperty("minFilter", js::Read::Enum, >::Sampler::mMinFilter)) + .Register(*js::MakeProperty("magFilter", js::Read::Enum, >::Sampler::mMagFilter)) + .Register(*js::MakeProperty("wrapS", js::Read::Enum, >::Sampler::mWrapS)) + .Register(*js::MakeProperty("wrapT", js::Read::Enum, >::Sampler::mWrapT))); const auto TEXURE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("source", gt::RefReader::Read, >::Texture::mSource)) - .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Texture::mSampler)) -); + .Register(*js::MakeProperty("source", gt::RefReader::Read, >::Texture::mSource)) + .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Texture::mSampler))); const auto TEXURE_INFO_READER = std::move(js::Reader() - .Register(*js::MakeProperty("index", gt::RefReader::Read, >::TextureInfo::mTexture)) - .Register(*js::MakeProperty("texCoord", js::Read::Number, >::TextureInfo::mTexCoord)) - .Register(*js::MakeProperty("scale", js::Read::Number, >::TextureInfo::mScale)) -); + .Register(*js::MakeProperty("index", gt::RefReader::Read, >::TextureInfo::mTexture)) + .Register(*js::MakeProperty("texCoord", js::Read::Number, >::TextureInfo::mTexCoord)) + .Register(*js::MakeProperty("scale", js::Read::Number, >::TextureInfo::mScale))); const auto MATERIAL_PBR_READER = std::move(js::Reader() - .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector, >::Material::Pbr::mBaseColorFactor)) - .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader::Read, - >::Material::Pbr::mBaseColorTexture)) - .Register(*js::MakeProperty("metallicFactor", js::Read::Number, >::Material::Pbr::mMetallicFactor)) - .Register(*js::MakeProperty("roughnessFactor", js::Read::Number, >::Material::Pbr::mRoughnessFactor)) - .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader::Read, - >::Material::Pbr::mMetallicRoughnessTexture)) -); + .Register(*js::MakeProperty("baseColorFactor", gt::ReadDaliVector, >::Material::Pbr::mBaseColorFactor)) + .Register(*js::MakeProperty("baseColorTexture", js::ObjectReader::Read, >::Material::Pbr::mBaseColorTexture)) + .Register(*js::MakeProperty("metallicFactor", js::Read::Number, >::Material::Pbr::mMetallicFactor)) + .Register(*js::MakeProperty("roughnessFactor", js::Read::Number, >::Material::Pbr::mRoughnessFactor)) + .Register(*js::MakeProperty("metallicRoughnessTexture", js::ObjectReader::Read, >::Material::Pbr::mMetallicRoughnessTexture))); const auto MATERIAL_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) - .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader::Read, >::Material::mPbrMetallicRoughness)) - .Register(*js::MakeProperty("normalTexture", js::ObjectReader::Read, >::Material::mNormalTexture)) - .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader::Read, >::Material::mOcclusionTexture)) - .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader::Read, >::Material::mEmissiveTexture)) - .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector, >::Material::mEmissiveFactor)) - .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum, >::Material::mAlphaMode)) - .Register(*js::MakeProperty("alphaCutoff", js::Read::Number, >::Material::mAlphaCutoff)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Material::mName)) + .Register(*js::MakeProperty("pbrMetallicRoughness", js::ObjectReader::Read, >::Material::mPbrMetallicRoughness)) + .Register(*js::MakeProperty("normalTexture", js::ObjectReader::Read, >::Material::mNormalTexture)) + .Register(*js::MakeProperty("occlusionTexture", js::ObjectReader::Read, >::Material::mOcclusionTexture)) + .Register(*js::MakeProperty("emissiveTexture", js::ObjectReader::Read, >::Material::mEmissiveTexture)) + .Register(*js::MakeProperty("emissiveFactor", gt::ReadDaliVector, >::Material::mEmissiveFactor)) + .Register(*js::MakeProperty("alphaMode", gt::ReadStringEnum, >::Material::mAlphaMode)) + .Register(*js::MakeProperty("alphaCutoff", js::Read::Number, >::Material::mAlphaCutoff))); std::map> ReadMeshPrimitiveAttributes(const json_value_s& j) { - auto& jo = js::Cast(j); + auto& jo = js::Cast(j); std::map> result; auto i = jo.start; - while (i) + while(i) { - auto jstr = *i->name; + auto jstr = *i->name; result[gt::Attribute::FromString(jstr.string, jstr.string_size)] = gt::RefReader::Read(*i->value); - i = i->next; + i = i->next; } return result; } std::vector>> ReadMeshPrimitiveTargets(const json_value_s& j) { - auto& jo = js::Cast(j); + auto& jo = js::Cast(j); std::vector>> result; result.reserve(jo.length); auto i = jo.start; - while (i) + while(i) { result.push_back(std::move(ReadMeshPrimitiveAttributes(*i->value))); i = i->next; @@ -216,128 +204,129 @@ std::vector>> ReadMeshPrimit } const auto MESH_PRIMITIVE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes)) - .Register(*js::MakeProperty("indices", gt::RefReader::Read, >::Mesh::Primitive::mIndices)) - .Register(*js::MakeProperty("material", gt::RefReader::Read, >::Mesh::Primitive::mMaterial)) - .Register(*js::MakeProperty("mode", js::Read::Enum, >::Mesh::Primitive::mMode)) - .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets)) -); + .Register(*js::MakeProperty("attributes", ReadMeshPrimitiveAttributes, >::Mesh::Primitive::mAttributes)) + .Register(*js::MakeProperty("indices", gt::RefReader::Read, >::Mesh::Primitive::mIndices)) + .Register(*js::MakeProperty("material", gt::RefReader::Read, >::Mesh::Primitive::mMaterial)) + .Register(*js::MakeProperty("mode", js::Read::Enum, >::Mesh::Primitive::mMode)) + .Register(*js::MakeProperty("targets", ReadMeshPrimitiveTargets, >::Mesh::Primitive::mTargets))); const auto MESH_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Mesh::mName)) - .Register(*js::MakeProperty("primitives", - js::Read::Array::Read>, >::Mesh::mPrimitives)) - .Register(*js::MakeProperty("weights", js::Read::Array, >::Mesh::mWeights)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Mesh::mName)) + .Register(*js::MakeProperty("primitives", + js::Read::Array::Read>, + >::Mesh::mPrimitives)) + .Register(*js::MakeProperty("weights", js::Read::Array, >::Mesh::mWeights))); const auto SKIN_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Skin::mName)) - .Register(*js::MakeProperty("inverseBindMatrices", - gt::RefReader::Read, >::Skin::mInverseBindMatrices)) - .Register(*js::MakeProperty("skeleton", - gt::RefReader::Read, >::Skin::mSkeleton)) - .Register(*js::MakeProperty("joints", - js::Read::Array, gt::RefReader::Read>, >::Skin::mJoints)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Skin::mName)) + .Register(*js::MakeProperty("inverseBindMatrices", + gt::RefReader::Read, + >::Skin::mInverseBindMatrices)) + .Register(*js::MakeProperty("skeleton", + gt::RefReader::Read, + >::Skin::mSkeleton)) + .Register(*js::MakeProperty("joints", + js::Read::Array, gt::RefReader::Read>, + >::Skin::mJoints))); const auto CAMERA_PERSPECTIVE_READER = std::move(js::Reader() - .Register(*js::MakeProperty("aspectRatio", js::Read::Number, >::Camera::Perspective::mAspectRatio)) - .Register(*js::MakeProperty("yfov", js::Read::Number, >::Camera::Perspective::mYFov)) - .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Perspective::mZFar)) - .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Perspective::mZNear)) -); // TODO: infinite perspective projection, where znear is omitted + .Register(*js::MakeProperty("aspectRatio", js::Read::Number, >::Camera::Perspective::mAspectRatio)) + .Register(*js::MakeProperty("yfov", js::Read::Number, >::Camera::Perspective::mYFov)) + .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Perspective::mZFar)) + .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Perspective::mZNear))); // TODO: infinite perspective projection, where znear is omitted const auto CAMERA_ORTHOGRAPHIC_READER = std::move(js::Reader() - .Register(*js::MakeProperty("xmag", js::Read::Number, >::Camera::Orthographic::mXMag)) - .Register(*js::MakeProperty("ymag", js::Read::Number, >::Camera::Orthographic::mXMag)) - .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Orthographic::mZFar)) - .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Orthographic::mZNear)) -); + .Register(*js::MakeProperty("xmag", js::Read::Number, >::Camera::Orthographic::mXMag)) + .Register(*js::MakeProperty("ymag", js::Read::Number, >::Camera::Orthographic::mXMag)) + .Register(*js::MakeProperty("zfar", js::Read::Number, >::Camera::Orthographic::mZFar)) + .Register(*js::MakeProperty("znear", js::Read::Number, >::Camera::Orthographic::mZNear))); const auto CAMERA_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Camera::mName)) - .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType)) - .Register(*js::MakeProperty("perspective", js::ObjectReader::Read, >::Camera::mPerspective)) - .Register(*js::MakeProperty("orthographic", js::ObjectReader::Read, >::Camera::mOrthographic)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Camera::mName)) + .Register(*js::MakeProperty("type", js::Read::StringView, >::Camera::mType)) + .Register(*js::MakeProperty("perspective", js::ObjectReader::Read, >::Camera::mPerspective)) + .Register(*js::MakeProperty("orthographic", js::ObjectReader::Read, >::Camera::mOrthographic))); const auto NODE_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Node::mName)) - .Register(*js::MakeProperty("translation", gt::ReadDaliVector, >::Node::mTranslation)) - .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation)) - .Register(*js::MakeProperty("scale", gt::ReadDaliVector, >::Node::mScale)) - .Register(*new js::Property("matrix", gt::ReadDaliVector, >::Node::SetMatrix)) - .Register(*js::MakeProperty("camera", gt::RefReader::Read, - >::Node::mCamera)) - .Register(*js::MakeProperty("children", js::Read::Array, gt::RefReader::Read>, - >::Node::mChildren)) - .Register(*js::MakeProperty("mesh", gt::RefReader::Read, >::Node::mMesh)) - .Register(*js::MakeProperty("skin", gt::RefReader::Read, >::Node::mSkin)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Node::mName)) + .Register(*js::MakeProperty("translation", gt::ReadDaliVector, >::Node::mTranslation)) + .Register(*js::MakeProperty("rotation", gt::ReadQuaternion, >::Node::mRotation)) + .Register(*js::MakeProperty("scale", gt::ReadDaliVector, >::Node::mScale)) + .Register(*new js::Property("matrix", gt::ReadDaliVector, >::Node::SetMatrix)) + .Register(*js::MakeProperty("camera", gt::RefReader::Read, >::Node::mCamera)) + .Register(*js::MakeProperty("children", js::Read::Array, gt::RefReader::Read>, >::Node::mChildren)) + .Register(*js::MakeProperty("mesh", gt::RefReader::Read, >::Node::mMesh)) + .Register(*js::MakeProperty("skin", gt::RefReader::Read, >::Node::mSkin))); const auto ANIMATION_SAMPLER_READER = std::move(js::Reader() - .Register(*js::MakeProperty("input", gt::RefReader::Read, - >::Animation::Sampler::mInput)) - .Register(*js::MakeProperty("output", gt::RefReader::Read, - >::Animation::Sampler::mOutput)) - .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum, >::Animation::Sampler::mInterpolation)) -); + .Register(*js::MakeProperty("input", gt::RefReader::Read, >::Animation::Sampler::mInput)) + .Register(*js::MakeProperty("output", gt::RefReader::Read, >::Animation::Sampler::mOutput)) + .Register(*js::MakeProperty("interpolation", gt::ReadStringEnum, >::Animation::Sampler::mInterpolation))); const auto ANIMATION_TARGET_READER = std::move(js::Reader() - .Register(*js::MakeProperty("node", gt::RefReader::Read, - >::Animation::Channel::Target::mNode)) - .Register(*js::MakeProperty("path", gt::ReadStringEnum, - >::Animation::Channel::Target::mPath)) -); + .Register(*js::MakeProperty("node", gt::RefReader::Read, >::Animation::Channel::Target::mNode)) + .Register(*js::MakeProperty("path", gt::ReadStringEnum, >::Animation::Channel::Target::mPath))); const auto ANIMATION_CHANNEL_READER = std::move(js::Reader() - .Register(*js::MakeProperty("target", js::ObjectReader::Read, >::Animation::Channel::mTarget)) - .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Animation::Channel::mSampler)) -); + .Register(*js::MakeProperty("target", js::ObjectReader::Read, >::Animation::Channel::mTarget)) + .Register(*js::MakeProperty("sampler", gt::RefReader::Read, >::Animation::Channel::mSampler))); const auto ANIMATION_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Animation::mName)) - .Register(*js::MakeProperty("samplers", - js::Read::Array::Read>, >::Animation::mSamplers)) - .Register(*js::MakeProperty("channels", - js::Read::Array::Read>, >::Animation::mChannels)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Animation::mName)) + .Register(*js::MakeProperty("samplers", + js::Read::Array::Read>, + >::Animation::mSamplers)) + .Register(*js::MakeProperty("channels", + js::Read::Array::Read>, + >::Animation::mChannels))); const auto SCENE_READER = std::move(js::Reader() - .Register(*new js::Property("name", js::Read::StringView, >::Scene::mName)) - .Register(*js::MakeProperty("nodes", - js::Read::Array, gt::RefReader::Read>, >::Scene::mNodes)) -); + .Register(*new js::Property("name", js::Read::StringView, >::Scene::mName)) + .Register(*js::MakeProperty("nodes", + js::Read::Array, gt::RefReader::Read>, + >::Scene::mNodes))); const auto DOCUMENT_READER = std::move(js::Reader() - .Register(*js::MakeProperty("buffers", - js::Read::Array::Read>, >::Document::mBuffers)) - .Register(*js::MakeProperty("bufferViews", - js::Read::Array::Read>, >::Document::mBufferViews)) - .Register(*js::MakeProperty("accessors", - js::Read::Array::Read>, >::Document::mAccessors)) - .Register(*js::MakeProperty("images", - js::Read::Array::Read>, >::Document::mImages)) - .Register(*js::MakeProperty("samplers", - js::Read::Array::Read>, >::Document::mSamplers)) - .Register(*js::MakeProperty("textures", - js::Read::Array::Read>, >::Document::mTextures)) - .Register(*js::MakeProperty("materials", - js::Read::Array::Read>, >::Document::mMaterials)) - .Register(*js::MakeProperty("meshes", - js::Read::Array::Read>, >::Document::mMeshes)) - .Register(*js::MakeProperty("skins", - js::Read::Array::Read>, >::Document::mSkins)) - .Register(*js::MakeProperty("cameras", - js::Read::Array::Read>, >::Document::mCameras)) - .Register(*js::MakeProperty("nodes", - js::Read::Array::Read>, >::Document::mNodes)) - .Register(*js::MakeProperty("animations", - ReadAnimationArray, >::Document::mAnimations)) - .Register(*js::MakeProperty("scenes", - js::Read::Array::Read>, >::Document::mScenes)) - .Register(*js::MakeProperty("scene", gt::RefReader::Read, >::Document::mScene)) -); + .Register(*js::MakeProperty("buffers", + js::Read::Array::Read>, + >::Document::mBuffers)) + .Register(*js::MakeProperty("bufferViews", + js::Read::Array::Read>, + >::Document::mBufferViews)) + .Register(*js::MakeProperty("accessors", + js::Read::Array::Read>, + >::Document::mAccessors)) + .Register(*js::MakeProperty("images", + js::Read::Array::Read>, + >::Document::mImages)) + .Register(*js::MakeProperty("samplers", + js::Read::Array::Read>, + >::Document::mSamplers)) + .Register(*js::MakeProperty("textures", + js::Read::Array::Read>, + >::Document::mTextures)) + .Register(*js::MakeProperty("materials", + js::Read::Array::Read>, + >::Document::mMaterials)) + .Register(*js::MakeProperty("meshes", + js::Read::Array::Read>, + >::Document::mMeshes)) + .Register(*js::MakeProperty("skins", + js::Read::Array::Read>, + >::Document::mSkins)) + .Register(*js::MakeProperty("cameras", + js::Read::Array::Read>, + >::Document::mCameras)) + .Register(*js::MakeProperty("nodes", + js::Read::Array::Read>, + >::Document::mNodes)) + .Register(*js::MakeProperty("animations", + ReadAnimationArray, + >::Document::mAnimations)) + .Register(*js::MakeProperty("scenes", + js::Read::Array::Read>, + >::Document::mScenes)) + .Register(*js::MakeProperty("scene", gt::RefReader::Read, >::Document::mScene))); struct NodeMapping { @@ -353,7 +342,7 @@ bool operator<(const NodeMapping& mapping, Index gltfIdx) class NodeIndexMapper { public: - NodeIndexMapper() = default; + NodeIndexMapper() = default; NodeIndexMapper(const NodeIndexMapper&) = delete; NodeIndexMapper& operator=(const NodeIndexMapper&) = delete; @@ -362,18 +351,18 @@ public: /// save growing a vector. void RegisterMapping(Index gltfIdx, Index runtimeIdx) { - if (gltfIdx != runtimeIdx) + if(gltfIdx != runtimeIdx) { auto iInsert = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); DALI_ASSERT_DEBUG(iInsert == mNodes.end() || iInsert->gltfIdx != gltfIdx); - mNodes.insert(iInsert, NodeMapping{ gltfIdx, runtimeIdx }); + mNodes.insert(iInsert, NodeMapping{gltfIdx, runtimeIdx}); } } ///@brief Retrieves the runtime index of a Node, mapped to the given @a gltfIdx. Index GetRuntimeId(Index gltfIdx) const { - auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator< + auto iFind = std::lower_bound(mNodes.begin(), mNodes.end(), gltfIdx); // using custom operator< return (iFind != mNodes.end() && iFind->gltfIdx == gltfIdx) ? iFind->runtimeIdx : gltfIdx; } @@ -383,39 +372,35 @@ private: struct ConversionContext { - LoadResult& mOutput; + LoadResult& mOutput; std::string mPath; - Index mDefaultMaterial; + Index mDefaultMaterial; - std::vector mMeshIds; - NodeIndexMapper mNodeIndices; + std::vector mMeshIds; + NodeIndexMapper mNodeIndices; }; SamplerFlags::Type ConvertWrapMode(gt::Wrap::Type w) { - switch (w) + switch(w) { - case gt::Wrap::REPEAT: - return SamplerFlags::WRAP_REPEAT; - case gt::Wrap::CLAMP_TO_EDGE: - return SamplerFlags::WRAP_CLAMP; - case gt::Wrap::MIRRORED_REPEAT: - return SamplerFlags::WRAP_MIRROR; - default: - throw std::runtime_error("Invalid wrap type."); + case gt::Wrap::REPEAT: + return SamplerFlags::WRAP_REPEAT; + case gt::Wrap::CLAMP_TO_EDGE: + return SamplerFlags::WRAP_CLAMP; + case gt::Wrap::MIRRORED_REPEAT: + return SamplerFlags::WRAP_MIRROR; + default: + throw std::runtime_error("Invalid wrap type."); } } SamplerFlags::Type ConvertSampler(const gt::Ref& s) { - if (s) + if(s) { - return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : - ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | - ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | - (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | - (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT); + return (s->mMinFilter < gt::Filter::NEAREST_MIPMAP_NEAREST) ? (s->mMinFilter - gt::Filter::NEAREST) : ((s->mMinFilter - gt::Filter::NEAREST_MIPMAP_NEAREST) + 2) | ((s->mMagFilter - gt::Filter::NEAREST) << SamplerFlags::FILTER_MAG_SHIFT) | (ConvertWrapMode(s->mWrapS) << SamplerFlags::WRAP_S_SHIFT) | (ConvertWrapMode(s->mWrapT) << SamplerFlags::WRAP_T_SHIFT); } else { @@ -424,13 +409,13 @@ SamplerFlags::Type ConvertSampler(const gt::Ref& s) // "What is an auto filtering", I hear you ask. Since there's nothing else to determine mipmapping from - including glTF image // properties, if not in some extension -, we will simply assume linear filtering. return SamplerFlags::FILTER_LINEAR | (SamplerFlags::FILTER_LINEAR << SamplerFlags::FILTER_MAG_SHIFT) | - (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT); + (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_S_SHIFT) | (SamplerFlags::WRAP_REPEAT << SamplerFlags::WRAP_T_SHIFT); } } TextureDefinition ConvertTextureInfo(const gt::TextureInfo& mm) { - return TextureDefinition{ std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler) }; + return TextureDefinition{std::string(mm.mTexture->mSource->mUri), ConvertSampler(mm.mTexture->mSampler)}; } void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials)& outMaterials) @@ -438,12 +423,12 @@ void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials) MaterialDefinition matDef; auto& pbr = m.mPbrMetallicRoughness; - if (m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f) + if(m.mAlphaMode != gt::AlphaMode::OPAQUE || pbr.mBaseColorFactor.a < 1.f) { matDef.mFlags |= MaterialDefinition::TRANSPARENCY; } - if (m.mAlphaMode == gt::AlphaMode::MASK) + if(m.mAlphaMode == gt::AlphaMode::MASK) { matDef.SetAlphaCutoff(std::min(1.f, std::max(0.f, m.mAlphaCutoff))); } @@ -451,30 +436,30 @@ void ConvertMaterial(const gt::Material& m, decltype(ResourceBundle::mMaterials) matDef.mColor = pbr.mBaseColorFactor; matDef.mTextureStages.reserve(!!pbr.mBaseColorTexture + !!pbr.mMetallicRoughnessTexture + !!m.mNormalTexture); - if (pbr.mBaseColorTexture) + if(pbr.mBaseColorTexture) { const auto semantic = MaterialDefinition::ALBEDO; - matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mBaseColorTexture) }); + matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mBaseColorTexture)}); // TODO: and there had better be one matDef.mFlags |= semantic; } - matDef.mMetallic = pbr.mMetallicFactor; + matDef.mMetallic = pbr.mMetallicFactor; matDef.mRoughness = pbr.mRoughnessFactor; - if (pbr.mMetallicRoughnessTexture) + if(pbr.mMetallicRoughnessTexture) { const auto semantic = MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS | - MaterialDefinition::GLTF_CHANNELS; - matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture) }); + MaterialDefinition::GLTF_CHANNELS; + matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(pbr.mMetallicRoughnessTexture)}); // TODO: and there had better be one matDef.mFlags |= semantic; } - if (m.mNormalTexture) + if(m.mNormalTexture) { const auto semantic = MaterialDefinition::NORMAL; - matDef.mTextureStages.push_back({ semantic, ConvertTextureInfo(m.mNormalTexture) }); + matDef.mTextureStages.push_back({semantic, ConvertTextureInfo(m.mNormalTexture)}); // TODO: and there had better be one matDef.mFlags |= semantic; } @@ -489,7 +474,7 @@ void ConvertMaterials(const gt::Document& doc, ConversionContext& cctx) auto& outMaterials = cctx.mOutput.mResources.mMaterials; outMaterials.reserve(doc.mMaterials.size()); - for (auto& m : doc.mMaterials) + for(auto& m : doc.mMaterials) { ConvertMaterial(m, outMaterials); } @@ -498,42 +483,41 @@ void ConvertMaterials(const gt::Document& doc, ConversionContext& cctx) MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc) { DALI_ASSERT_ALWAYS((acc.mBufferView && - (acc.mBufferView->mByteStride < std::numeric_limits::max())) || - (acc.mSparse && !acc.mBufferView)); + (acc.mBufferView->mByteStride < std::numeric_limits::max())) || + (acc.mSparse && !acc.mBufferView)); DALI_ASSERT_ALWAYS(!acc.mSparse || - ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits::max())) && - (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits::max())))); - + ((acc.mSparse->mIndices.mBufferView && (acc.mSparse->mIndices.mBufferView->mByteStride < std::numeric_limits::max())) && + (acc.mSparse->mValues.mBufferView && (acc.mSparse->mValues.mBufferView->mByteStride < std::numeric_limits::max())))); MeshDefinition::SparseBlob sparseBlob; - if (acc.mSparse) + if(acc.mSparse) { - const gt::Accessor::Sparse& sparse = *acc.mSparse; + const gt::Accessor::Sparse& sparse = *acc.mSparse; const gt::ComponentTypedBufferViewClient& indices = sparse.mIndices; - const gt::BufferViewClient& values = sparse.mValues; + const gt::BufferViewClient& values = sparse.mValues; MeshDefinition::Blob indicesBlob( indices.mBufferView->mByteOffset + indices.mByteOffset, sparse.mCount * indices.GetBytesPerComponent(), static_cast(indices.mBufferView->mByteStride), static_cast(indices.GetBytesPerComponent()), - {}, {} - ); + {}, + {}); MeshDefinition::Blob valuesBlob( values.mBufferView->mByteOffset + values.mByteOffset, sparse.mCount * acc.GetElementSizeBytes(), static_cast(values.mBufferView->mByteStride), static_cast(acc.GetElementSizeBytes()), - {}, {} - ); + {}, + {}); sparseBlob = std::move(MeshDefinition::SparseBlob(std::move(indicesBlob), std::move(valuesBlob), acc.mSparse->mCount)); } uint32_t bufferViewOffset = 0u; uint32_t bufferViewStride = 0u; - if (acc.mBufferView) + if(acc.mBufferView) { bufferViewOffset = acc.mBufferView->mByteOffset; bufferViewStride = acc.mBufferView->mByteStride; @@ -541,19 +525,19 @@ MeshDefinition::Accessor ConvertMeshPrimitiveAccessor(const gt::Accessor& acc) return MeshDefinition::Accessor{ std::move(MeshDefinition::Blob{bufferViewOffset + acc.mByteOffset, - acc.GetBytesLength(), - static_cast(bufferViewStride), - static_cast(acc.GetElementSizeBytes()), - acc.mMin, - acc.mMax}), - std::move(sparseBlob) }; + acc.GetBytesLength(), + static_cast(bufferViewStride), + static_cast(acc.GetElementSizeBytes()), + acc.mMin, + acc.mMax}), + std::move(sparseBlob)}; } void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx) { uint32_t meshCount = 0; cctx.mMeshIds.reserve(doc.mMeshes.size()); - for (auto& m : doc.mMeshes) + for(auto& m : doc.mMeshes) { cctx.mMeshIds.push_back(meshCount); meshCount += m.mPrimitives.size(); @@ -561,94 +545,94 @@ void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx) auto& outMeshes = cctx.mOutput.mResources.mMeshes; outMeshes.reserve(meshCount); - for (auto& m : doc.mMeshes) + for(auto& m : doc.mMeshes) { - for (auto& p : m.mPrimitives) + for(auto& p : m.mPrimitives) { MeshDefinition meshDef; - auto& attribs = p.mAttributes; - meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri; + auto& attribs = p.mAttributes; + meshDef.mUri = attribs.begin()->second->mBufferView->mBuffer->mUri; meshDef.mPrimitiveType = GLTF2_TO_DALI_PRIMITIVES[p.mMode]; auto& accPositions = *attribs.find(gt::Attribute::POSITION)->second; meshDef.mPositions = ConvertMeshPrimitiveAccessor(accPositions); const bool needNormalsTangents = accPositions.mType == gt::AccessorType::VEC3; - for (auto& am : ATTRIBUTE_MAPPINGS) + for(auto& am : ATTRIBUTE_MAPPINGS) { auto iFind = attribs.find(am.mType); - if (iFind != attribs.end()) + if(iFind != attribs.end()) { DALI_ASSERT_DEBUG(iFind->second->mBufferView->mBuffer->mUri.compare(meshDef.mUri) == 0); auto& accessor = meshDef.*(am.mAccessor); - accessor = ConvertMeshPrimitiveAccessor(*iFind->second); + accessor = ConvertMeshPrimitiveAccessor(*iFind->second); // Fixing up -- a few of glTF2 sample models have VEC4 tangents; we need VEC3s. - if (iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired)) + if(iFind->first == gt::Attribute::TANGENT && (accessor.mBlob.mElementSizeHint > am.mElementSizeRequired)) { - accessor.mBlob.mStride = std::max(static_cast(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired), - accessor.mBlob.mElementSizeHint); + accessor.mBlob.mStride = std::max(static_cast(accessor.mBlob.mStride + accessor.mBlob.mElementSizeHint - am.mElementSizeRequired), + accessor.mBlob.mElementSizeHint); accessor.mBlob.mElementSizeHint = am.mElementSizeRequired; } - if (iFind->first == gt::Attribute::JOINTS_0) + if(iFind->first == gt::Attribute::JOINTS_0) { meshDef.mFlags |= (iFind->second->mComponentType == gt::Component::UNSIGNED_SHORT) * MeshDefinition::U16_JOINT_IDS; DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U16_JOINT_IDS) || iFind->second->mComponentType == gt::Component::FLOAT); } } - else if (needNormalsTangents) + else if(needNormalsTangents) { - switch (am.mType) + switch(am.mType) { - case gt::Attribute::NORMAL: - meshDef.RequestNormals(); - break; + case gt::Attribute::NORMAL: + meshDef.RequestNormals(); + break; - case gt::Attribute::TANGENT: - meshDef.RequestTangents(); - break; + case gt::Attribute::TANGENT: + meshDef.RequestTangents(); + break; - default: - break; + default: + break; } } } - if (p.mIndices) + if(p.mIndices) { meshDef.mIndices = ConvertMeshPrimitiveAccessor(*p.mIndices); meshDef.mFlags |= (p.mIndices->mComponentType == gt::Component::UNSIGNED_INT) * MeshDefinition::U32_INDICES; DALI_ASSERT_DEBUG(MaskMatch(meshDef.mFlags, MeshDefinition::U32_INDICES) || p.mIndices->mComponentType == gt::Component::UNSIGNED_SHORT); } - if (!p.mTargets.empty()) + if(!p.mTargets.empty()) { meshDef.mBlendShapes.reserve(p.mTargets.size()); meshDef.mBlendShapeVersion = BlendShapes::Version::VERSION_2_0; - for (const auto& target : p.mTargets) + for(const auto& target : p.mTargets) { MeshDefinition::BlendShape blendShape; auto endIt = target.end(); - auto it = target.find(gt::Attribute::POSITION); - if (it != endIt) + auto it = target.find(gt::Attribute::POSITION); + if(it != endIt) { blendShape.deltas = ConvertMeshPrimitiveAccessor(*it->second); } it = target.find(gt::Attribute::NORMAL); - if (it != endIt) + if(it != endIt) { blendShape.normals = ConvertMeshPrimitiveAccessor(*it->second); } it = target.find(gt::Attribute::TANGENT); - if (it != endIt) + if(it != endIt) { blendShape.tangents = ConvertMeshPrimitiveAccessor(*it->second); } - if (!m.mWeights.empty()) + if(!m.mWeights.empty()) { blendShape.weight = m.mWeights[meshDef.mBlendShapes.size()]; } @@ -657,7 +641,7 @@ void ConvertMeshes(const gt::Document& doc, ConversionContext& cctx) } } - outMeshes.push_back({ std::move(meshDef), MeshGeometry{} }); + outMeshes.push_back({std::move(meshDef), MeshGeometry{}}); } } } @@ -666,15 +650,15 @@ ModelNode* MakeModelNode(const gt::Mesh::Primitive& prim, ConversionContext& cct { auto modelNode = new ModelNode(); - modelNode->mShaderIdx = 0; // TODO: further thought + modelNode->mShaderIdx = 0; // TODO: further thought auto materialIdx = prim.mMaterial.GetIndex(); - if (INVALID_INDEX == materialIdx) + if(INVALID_INDEX == materialIdx) { // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#default-material - if (INVALID_INDEX == cctx.mDefaultMaterial) + if(INVALID_INDEX == cctx.mDefaultMaterial) { - auto& outMaterials = cctx.mOutput.mResources.mMaterials; + auto& outMaterials = cctx.mOutput.mResources.mMaterials; cctx.mDefaultMaterial = outMaterials.size(); ConvertMaterial(gt::Material{}, outMaterials); @@ -691,51 +675,51 @@ ModelNode* MakeModelNode(const gt::Mesh::Primitive& prim, ConversionContext& cct void ConvertCamera(const gt::Camera& camera, CameraParameters& camParams) { camParams.isPerspective = camera.mType.compare("perspective") == 0; - if (camParams.isPerspective) + if(camParams.isPerspective) { auto& perspective = camera.mPerspective; - camParams.yFov = Degree(Radian(perspective.mYFov)).degree; - camParams.zNear = perspective.mZNear; - camParams.zFar = perspective.mZFar; + camParams.yFov = Degree(Radian(perspective.mYFov)).degree; + camParams.zNear = perspective.mZNear; + camParams.zFar = perspective.mZFar; // TODO: yes, we seem to ignore aspectRatio in CameraParameters. } else { - auto& ortho = camera.mOrthographic; + auto& ortho = camera.mOrthographic; camParams.orthographicSize = Vector4(-ortho.mXMag, ortho.mXMag, ortho.mYMag, -ortho.mYMag) * .5f; - camParams.zNear = ortho.mZNear; - camParams.zFar = ortho.mZFar; + camParams.zNear = ortho.mZNear; + camParams.zFar = ortho.mZFar; } } void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, ConversionContext& cctx) { - auto& output = cctx.mOutput; - auto& scene = output.mScene; + auto& output = cctx.mOutput; + auto& scene = output.mScene; auto& resources = output.mResources; - const auto idx = scene.GetNodeCount(); - auto weakNode = scene.AddNode([&]() { - std::unique_ptr nodeDef{ new NodeDefinition() }; + const auto idx = scene.GetNodeCount(); + auto weakNode = scene.AddNode([&]() { + std::unique_ptr nodeDef{new NodeDefinition()}; nodeDef->mParentIdx = parentIdx; - nodeDef->mName = node.mName; - if (nodeDef->mName.empty()) + nodeDef->mName = node.mName; + if(nodeDef->mName.empty()) { // TODO: Production quality generation of unique names. nodeDef->mName = std::to_string(reinterpret_cast(nodeDef.get())); } - if (!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms. + if(!node.mSkin) // Nodes with skinned meshes are not supposed to have local transforms. { - nodeDef->mPosition = node.mTranslation; + nodeDef->mPosition = node.mTranslation; nodeDef->mOrientation = node.mRotation; - nodeDef->mScale = node.mScale; + nodeDef->mScale = node.mScale; } return nodeDef; }()); - if (!weakNode) + if(!weakNode) { ExceptionFlinger(ASSERT_LOCATION) << "Node name '" << node.mName << "' is not unique; scene is invalid."; } @@ -743,25 +727,25 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con cctx.mNodeIndices.RegisterMapping(gltfIdx, idx); Index skeletonIdx = node.mSkin ? node.mSkin.GetIndex() : INVALID_INDEX; - if (node.mMesh && !node.mMesh->mPrimitives.empty()) + if(node.mMesh && !node.mMesh->mPrimitives.empty()) { auto& mesh = *node.mMesh; - auto iPrim = mesh.mPrimitives.begin(); - auto modelNode = MakeModelNode(*iPrim, cctx); - auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()]; + auto iPrim = mesh.mPrimitives.begin(); + auto modelNode = MakeModelNode(*iPrim, cctx); + auto meshIdx = cctx.mMeshIds[node.mMesh.GetIndex()]; modelNode->mMeshIdx = meshIdx; weakNode->mRenderable.reset(modelNode); DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX || - resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); + resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx; // As does model-exporter, we'll create anonymous child nodes for additional mesh( primitiv)es. - while (++iPrim != mesh.mPrimitives.end()) + while(++iPrim != mesh.mPrimitives.end()) { - std::unique_ptr child{ new NodeDefinition }; + std::unique_ptr child{new NodeDefinition}; child->mParentIdx = idx; auto childModel = MakeModelNode(*iPrim, cctx); @@ -774,12 +758,12 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con scene.AddNode(std::move(child)); DALI_ASSERT_DEBUG(resources.mMeshes[meshIdx].first.mSkeletonIdx == INVALID_INDEX || - resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); + resources.mMeshes[meshIdx].first.mSkeletonIdx == skeletonIdx); resources.mMeshes[meshIdx].first.mSkeletonIdx = skeletonIdx; } } - if (node.mCamera) + if(node.mCamera) { CameraParameters camParams; ConvertCamera(*node.mCamera, camParams); @@ -788,7 +772,7 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con output.mCameraParameters.push_back(camParams); } - for (auto& n : node.mChildren) + for(auto& n : node.mChildren) { ConvertNode(*n, n.GetIndex(), idx, cctx); } @@ -797,26 +781,26 @@ void ConvertNode(gt::Node const& node, const Index gltfIdx, Index parentIdx, Con void ConvertSceneNodes(const gt::Scene& scene, ConversionContext& cctx) { auto& outScene = cctx.mOutput.mScene; - Index rootIdx = outScene.GetNodeCount(); - switch (scene.mNodes.size()) + Index rootIdx = outScene.GetNodeCount(); + switch(scene.mNodes.size()) { - case 0: - break; + case 0: + break; - case 1: - ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx); - outScene.AddRootNode(rootIdx); - break; + case 1: + ConvertNode(*scene.mNodes[0], scene.mNodes[0].GetIndex(), INVALID_INDEX, cctx); + outScene.AddRootNode(rootIdx); + break; - default: + default: { - std::unique_ptr sceneRoot{ new NodeDefinition() }; + std::unique_ptr sceneRoot{new NodeDefinition()}; sceneRoot->mName = "GLTF_LOADER_SCENE_ROOT_" + std::to_string(outScene.GetRoots().size()); outScene.AddNode(std::move(sceneRoot)); outScene.AddRootNode(rootIdx); - for (auto& n : scene.mNodes) + for(auto& n : scene.mNodes) { ConvertNode(*n, n.GetIndex(), rootIdx, cctx); } @@ -829,23 +813,23 @@ void ConvertNodes(const gt::Document& doc, ConversionContext& cctx) { ConvertSceneNodes(*doc.mScene, cctx); - for (uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i) + for(uint32_t i = 0, i1 = doc.mScene.GetIndex(); i < i1; ++i) { ConvertSceneNodes(doc.mScenes[i], cctx); } - for (uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i) + for(uint32_t i = doc.mScene.GetIndex() + 1; i < doc.mScenes.size(); ++i) { ConvertSceneNodes(doc.mScenes[i], cctx); } } -template +template void LoadDataFromAccessor(const std::string& path, Vector& dataBuffer, uint32_t offset, uint32_t size) { std::ifstream animationBinaryFile(path, std::ifstream::binary); - if (!animationBinaryFile.is_open()) + if(!animationBinaryFile.is_open()) { throw std::runtime_error("Failed to load " + path); } @@ -855,19 +839,17 @@ void LoadDataFromAccessor(const std::string& path, Vector& dataBuffer, uint32 animationBinaryFile.close(); } -template +template float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& input, const gltf2::Accessor& output, Vector& inputDataBuffer, Vector& outputDataBuffer) { inputDataBuffer.Resize(input.mCount); outputDataBuffer.Resize(output.mCount); - const uint32_t inputDataBufferSize = input.GetBytesLength(); + const uint32_t inputDataBufferSize = input.GetBytesLength(); const uint32_t outputDataBufferSize = output.GetBytesLength(); - LoadDataFromAccessor(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, - input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize); - LoadDataFromAccessor(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, - output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize); + LoadDataFromAccessor(path + std::string(input.mBufferView->mBuffer->mUri), inputDataBuffer, input.mBufferView->mByteOffset + input.mByteOffset, inputDataBufferSize); + LoadDataFromAccessor(path + std::string(output.mBufferView->mBuffer->mUri), outputDataBuffer, output.mBufferView->mByteOffset + output.mByteOffset, outputDataBufferSize); ApplyAccessorMinMax(output, reinterpret_cast(outputDataBuffer.begin())); return inputDataBuffer[input.mCount - 1u]; @@ -876,15 +858,15 @@ float LoadDataFromAccessors(const std::string& path, const gltf2::Accessor& inpu template float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& channel, KeyFrames& keyFrames, gt::Animation::Channel::Target::Type type) { - const gltf2::Accessor& input = *channel.mSampler->mInput; + const gltf2::Accessor& input = *channel.mSampler->mInput; const gltf2::Accessor& output = *channel.mSampler->mOutput; Vector inputDataBuffer; - Vector outputDataBuffer; + Vector outputDataBuffer; const float duration = LoadDataFromAccessors(path, input, output, inputDataBuffer, outputDataBuffer); - for (uint32_t i = 0; i < input.mCount; ++i) + for(uint32_t i = 0; i < input.mCount; ++i) { keyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i]); } @@ -894,7 +876,7 @@ float LoadKeyFrames(const std::string& path, const gt::Animation::Channel& chann float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Channel& channel, const std::string& nodeName, uint32_t& propertyIndex, std::vector& properties) { - const gltf2::Accessor& input = *channel.mSampler->mInput; + const gltf2::Accessor& input = *channel.mSampler->mInput; const gltf2::Accessor& output = *channel.mSampler->mOutput; Vector inputDataBuffer; @@ -902,11 +884,11 @@ float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Chan const float duration = LoadDataFromAccessors(path, input, output, inputDataBuffer, outputDataBuffer); - char weightNameBuffer[32]; - auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str()); - char* const pWeightName = weightNameBuffer + prefixSize; - const auto remainingSize = sizeof(weightNameBuffer) - prefixSize; - for (uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex) + char weightNameBuffer[32]; + auto prefixSize = snprintf(weightNameBuffer, sizeof(weightNameBuffer), "%s[", BLEND_SHAPE_WEIGHTS_UNIFORM.c_str()); + char* const pWeightName = weightNameBuffer + prefixSize; + const auto remainingSize = sizeof(weightNameBuffer) - prefixSize; + for(uint32_t weightIndex = 0u, endWeightIndex = channel.mSampler->mOutput->mCount / channel.mSampler->mInput->mCount; weightIndex < endWeightIndex; ++weightIndex) { AnimatedProperty& animatedProperty = properties[propertyIndex++]; @@ -915,12 +897,12 @@ float LoadBlendShapeKeyFrames(const std::string& path, const gt::Animation::Chan animatedProperty.mPropertyName = std::string(weightNameBuffer); animatedProperty.mKeyFrames = KeyFrames::New(); - for (uint32_t i = 0; i < input.mCount; ++i) + for(uint32_t i = 0; i < input.mCount; ++i) { - animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i*endWeightIndex + weightIndex]); + animatedProperty.mKeyFrames.Add(inputDataBuffer[i] / duration, outputDataBuffer[i * endWeightIndex + weightIndex]); } - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; } return duration; @@ -932,78 +914,78 @@ void ConvertAnimations(const gt::Document& doc, ConversionContext& cctx) output.mAnimationDefinitions.reserve(output.mAnimationDefinitions.size() + doc.mAnimations.size()); - for (const auto& animation : doc.mAnimations) + for(const auto& animation : doc.mAnimations) { AnimationDefinition animationDef; - if (!animation.mName.empty()) + if(!animation.mName.empty()) { animationDef.mName = animation.mName; } uint32_t numberOfProperties = 0u; - for (const auto& channel : animation.mChannels) + for(const auto& channel : animation.mChannels) { numberOfProperties += channel.mSampler->mOutput->mCount; } animationDef.mProperties.resize(numberOfProperties); Index propertyIndex = 0u; - for (const auto& channel : animation.mChannels) + for(const auto& channel : animation.mChannels) { std::string nodeName; - if (!channel.mTarget.mNode->mName.empty()) + if(!channel.mTarget.mNode->mName.empty()) { nodeName = channel.mTarget.mNode->mName; } else { Index index = cctx.mNodeIndices.GetRuntimeId(channel.mTarget.mNode.GetIndex()); - nodeName = cctx.mOutput.mScene.GetNode(index)->mName; + nodeName = cctx.mOutput.mScene.GetNode(index)->mName; } float duration = 0.f; - switch (channel.mTarget.mPath) + switch(channel.mTarget.mPath) { case gt::Animation::Channel::Target::TRANSLATION: { AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex]; - animatedProperty.mNodeName = nodeName; + animatedProperty.mNodeName = nodeName; animatedProperty.mPropertyName = POSITION_PROPERTY; animatedProperty.mKeyFrames = KeyFrames::New(); - duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); + duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; break; } case gt::Animation::Channel::Target::ROTATION: { AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex]; - animatedProperty.mNodeName = nodeName; + animatedProperty.mNodeName = nodeName; animatedProperty.mPropertyName = ORIENTATION_PROPERTY; animatedProperty.mKeyFrames = KeyFrames::New(); - duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); + duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; break; } case gt::Animation::Channel::Target::SCALE: { AnimatedProperty& animatedProperty = animationDef.mProperties[propertyIndex]; - animatedProperty.mNodeName = nodeName; + animatedProperty.mNodeName = nodeName; animatedProperty.mPropertyName = SCALE_PROPERTY; animatedProperty.mKeyFrames = KeyFrames::New(); - duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); + duration = LoadKeyFrames(cctx.mPath, channel, animatedProperty.mKeyFrames, channel.mTarget.mPath); - animatedProperty.mTimePeriod = { 0.f, duration }; + animatedProperty.mTimePeriod = {0.f, duration}; break; } case gt::Animation::Channel::Target::WEIGHTS: @@ -1035,13 +1017,15 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) // otherwise we'll set identity matrices for inverse bind pose. struct IInverseBindMatrixProvider { - virtual ~IInverseBindMatrixProvider() {} + virtual ~IInverseBindMatrixProvider() + { + } virtual void Provide(Matrix& ibm) = 0; }; struct InverseBindMatrixAccessor : public IInverseBindMatrixProvider { - std::ifstream mStream; + std::ifstream mStream; const uint32_t mElementSizeBytes; InverseBindMatrixAccessor(const gt::Accessor& accessor, const std::string& path) @@ -1071,10 +1055,10 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) auto& resources = cctx.mOutput.mResources; resources.mSkeletons.reserve(doc.mSkins.size()); - for (auto& s : doc.mSkins) + for(auto& s : doc.mSkins) { std::unique_ptr ibmProvider; - if (s.mInverseBindMatrices) + if(s.mInverseBindMatrices) { ibmProvider.reset(new InverseBindMatrixAccessor(*s.mInverseBindMatrices, cctx.mPath)); } @@ -1084,14 +1068,14 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) } SkeletonDefinition skeleton; - if (s.mSkeleton.GetIndex() != INVALID_INDEX) + if(s.mSkeleton.GetIndex() != INVALID_INDEX) { skeleton.mRootNodeIdx = cctx.mNodeIndices.GetRuntimeId(s.mSkeleton.GetIndex()); } skeleton.mJoints.resize(s.mJoints.size()); auto iJoint = skeleton.mJoints.begin(); - for (auto& j : s.mJoints) + for(auto& j : s.mJoints) { iJoint->mNodeIdx = cctx.mNodeIndices.GetRuntimeId(j.GetIndex()); @@ -1106,10 +1090,10 @@ void ProcessSkins(const gt::Document& doc, ConversionContext& cctx) void ProduceShaders(ShaderDefinitionFactory& shaderFactory, SceneDefinition& scene) { - for (size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0) + for(size_t i0 = 0, i1 = scene.GetNodeCount(); i0 != i1; ++i0) { auto nodeDef = scene.GetNode(i0); - if (auto renderable = nodeDef->mRenderable.get()) + if(auto renderable = nodeDef->mRenderable.get()) { renderable->mShaderIdx = shaderFactory.ProduceShader(*nodeDef); } @@ -1144,25 +1128,25 @@ void SetObjectReaders() js::SetObjectReader(SCENE_READER); } -} // nonamespace +} // namespace void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactory, LoadResult& params) { bool failed = false; - auto js = LoadTextFile(url.c_str(), &failed); - if (failed) + auto js = LoadTextFile(url.c_str(), &failed); + if(failed) { throw std::runtime_error("Failed to load " + url); } json::unique_ptr root(json_parse(js.c_str(), js.size())); - if (!root) + if(!root) { throw std::runtime_error("Failed to parse " + url); } static bool setObjectReaders = true; - if (setObjectReaders) + if(setObjectReaders) { // NOTE: only referencing own, anonymous namespace, const objects; the pointers will never need to change. SetObjectReaders(); @@ -1171,16 +1155,16 @@ void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactor gt::Document doc; - auto& rootObj = js::Cast(*root); - auto jsAsset = js::FindObjectChild("asset", rootObj); - auto jsAssetVersion = js::FindObjectChild("version", js::Cast(*jsAsset)); - doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion); + auto& rootObj = js::Cast(*root); + auto jsAsset = js::FindObjectChild("asset", rootObj); + auto jsAssetVersion = js::FindObjectChild("version", js::Cast(*jsAsset)); + doc.mAsset.mVersion = js::Read::StringView(*jsAssetVersion); gt::SetRefReaderObject(doc); DOCUMENT_READER.Read(rootObj, doc); - auto path = url.substr(0, url.rfind('/') + 1); - ConversionContext cctx{ params, path, INVALID_INDEX }; + auto path = url.substr(0, url.rfind('/') + 1); + ConversionContext cctx{params, path, INVALID_INDEX}; ConvertMaterials(doc, cctx); ConvertMeshes(doc, cctx); @@ -1193,5 +1177,5 @@ void LoadGltfScene(const std::string& url, ShaderDefinitionFactory& shaderFactor params.mScene.EnsureUniqueSkinningShaderInstances(params.mResources); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/ktx-loader.cpp b/dali-scene-loader/public-api/ktx-loader.cpp index 839c03c..147b3fd 100644 --- a/dali-scene-loader/public-api/ktx-loader.cpp +++ b/dali-scene-loader/public-api/ktx-loader.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,26 +15,24 @@ * */ - // FILE HEADER +// FILE HEADER #include "dali-scene-loader/public-api/ktx-loader.h" - // EXTERNAL INCLUDES -#include "dali/public-api/rendering/texture.h" +// EXTERNAL INCLUDES #include #include +#include "dali/public-api/rendering/texture.h" namespace Dali { - namespace { - // http://github.khronos.org/KTX-Specification/ -const uint8_t KTX_ID_HEAD[] = { 0xAB, 0x4B, 0x54, 0x58, 0x20 }; -const uint8_t KTX_ID_TAIL[] = { 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; +const uint8_t KTX_ID_HEAD[] = {0xAB, 0x4B, 0x54, 0x58, 0x20}; +const uint8_t KTX_ID_TAIL[] = {0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; -const uint8_t KTX_VERSION_1_1[] = { 0x31, 0x31 }; -const uint8_t KTX_VERSION_2_0[] = { 0x32, 0x30 }; +const uint8_t KTX_VERSION_1_1[] = {0x31, 0x31}; +const uint8_t KTX_VERSION_2_0[] = {0x32, 0x30}; static_assert(sizeof(KTX_ID_HEAD) + sizeof(KTX_ID_TAIL) == 10); static_assert(sizeof(KTX_VERSION_1_1) == 2); @@ -50,27 +48,27 @@ namespace SceneLoader { struct KtxFileHeader { - uint8_t identifier[12]; - uint32_t endianness; - uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.) - uint32_t glTypeSize; - uint32_t glFormat; //(RGB, RGBA, BGRA, etc.) - uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D - uint32_t glBaseInternalFormat; - uint32_t pixelWidth; - uint32_t pixelHeight; - uint32_t pixelDepth; - uint32_t numberOfArrayElements; - uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z. - uint32_t numberOfMipmapLevels; - uint32_t bytesOfKeyValueData; + uint8_t identifier[12]; + uint32_t endianness; + uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.) + uint32_t glTypeSize; + uint32_t glFormat; //(RGB, RGBA, BGRA, etc.) + uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D + uint32_t glBaseInternalFormat; + uint32_t pixelWidth; + uint32_t pixelHeight; + uint32_t pixelDepth; + uint32_t numberOfArrayElements; + uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z. + uint32_t numberOfMipmapLevels; + uint32_t bytesOfKeyValueData; bool IsIdentifierValid() const { return std::equal(KTX_ID_HEAD, std::end(KTX_ID_HEAD), identifier) && - (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) || - std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) && - std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1))); + (std::equal(KTX_VERSION_1_1, std::end(KTX_VERSION_1_1), identifier + sizeof(KTX_ID_HEAD)) || + std::equal(KTX_VERSION_2_0, std::end(KTX_VERSION_2_0), identifier + sizeof(KTX_ID_HEAD))) && + std::equal(KTX_ID_TAIL, std::end(KTX_ID_TAIL), identifier + (sizeof(KTX_ID_HEAD) + sizeof(KTX_VERSION_1_1))); } }; @@ -79,107 +77,107 @@ struct KtxFileHeader */ bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Pixel::Format& format) { - switch (ktxPixelFormat) - { - case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4 - { - format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR; - break; - } - case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4 - { - format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR; - break; - } - case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR; - break; - } - case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR; - break; - } - case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6 - { - format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR; - break; - } - case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR; - break; - } - case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6 - { - format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR; - break; - } - case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8 - { - format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR; - break; - } - case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR; - break; - } - case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR; - break; - } - case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR; - break; - } - case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10 - { - format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR; - break; - } - case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10 - { - format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR; - break; - } - case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12 - { - format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR; - break; - } - case 0x881B: // GL_RGB16F + switch(ktxPixelFormat) { - format = Pixel::RGB16F; - break; - } - case 0x8815: // GL_RGB32F - { - format = Pixel::RGB32F; - break; - } - case 0x8C3A: // GL_R11F_G11F_B10F - { - format = Pixel::RGB32F; - break; - } - case 0x8D7C: // GL_RGBA8UI - { - format = Pixel::RGBA8888; - break; - } - case 0x8D7D: // GL_RGB8UI - { - format = Pixel::RGB888; - break; - } - default: - { - return false; - } + case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4 + { + format = Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR; + break; + } + case 0x93B1: // GL_COMPRESSED_RGBA_ASTC_5x4 + { + format = Pixel::COMPRESSED_RGBA_ASTC_5x4_KHR; + break; + } + case 0x93B2: // GL_COMPRESSED_RGBA_ASTC_5x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_5x5_KHR; + break; + } + case 0x93B3: // GL_COMPRESSED_RGBA_ASTC_6x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_6x5_KHR; + break; + } + case 0x93B4: // GL_COMPRESSED_RGBA_ASTC_6x6 + { + format = Pixel::COMPRESSED_RGBA_ASTC_6x6_KHR; + break; + } + case 0x93B5: // GL_COMPRESSED_RGBA_ASTC_8x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_8x5_KHR; + break; + } + case 0x93B6: // GL_COMPRESSED_RGBA_ASTC_8x6 + { + format = Pixel::COMPRESSED_RGBA_ASTC_8x6_KHR; + break; + } + case 0x93B7: // GL_COMPRESSED_RGBA_ASTC_8x8 + { + format = Pixel::COMPRESSED_RGBA_ASTC_8x8_KHR; + break; + } + case 0x93B8: // GL_COMPRESSED_RGBA_ASTC_10x5 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x5_KHR; + break; + } + case 0x93B9: // GL_COMPRESSED_RGBA_ASTC_10x6 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x6_KHR; + break; + } + case 0x93BA: // GL_COMPRESSED_RGBA_ASTC_10x8 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x8_KHR; + break; + } + case 0x93BB: // GL_COMPRESSED_RGBA_ASTC_10x10 + { + format = Pixel::COMPRESSED_RGBA_ASTC_10x10_KHR; + break; + } + case 0x93BC: // GL_COMPRESSED_RGBA_ASTC_12x10 + { + format = Pixel::COMPRESSED_RGBA_ASTC_12x10_KHR; + break; + } + case 0x93BD: // GL_COMPRESSED_RGBA_ASTC_12x12 + { + format = Pixel::COMPRESSED_RGBA_ASTC_12x12_KHR; + break; + } + case 0x881B: // GL_RGB16F + { + format = Pixel::RGB16F; + break; + } + case 0x8815: // GL_RGB32F + { + format = Pixel::RGB32F; + break; + } + case 0x8C3A: // GL_R11F_G11F_B10F + { + format = Pixel::RGB32F; + break; + } + case 0x8D7C: // GL_RGBA8UI + { + format = Pixel::RGBA8888; + break; + } + case 0x8D7D: // GL_RGB8UI + { + format = Pixel::RGB888; + break; + } + default: + { + return false; + } } return true; @@ -187,15 +185,13 @@ bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Pixel::Format& format) Texture CubeData::CreateTexture() const { - Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(), - data[0][0].GetWidth(), data[0][0].GetHeight()); - for (size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide) + Texture texture = Texture::New(TextureType::TEXTURE_CUBE, data[0][0].GetPixelFormat(), data[0][0].GetWidth(), data[0][0].GetHeight()); + for(size_t iSide = 0u, iEndSize = data.size(); iSide < iEndSize; ++iSide) { auto& side = data[iSide]; - for (size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel) + for(size_t iMipLevel = 0u, iEndMipLevel = data[0].size(); iMipLevel < iEndMipLevel; ++iMipLevel) { - texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel, - 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight()); + texture.Upload(side[iMipLevel], CubeMapLayer::POSITIVE_X + iSide, iMipLevel, 0u, 0u, side[iMipLevel].GetWidth(), side[iMipLevel].GetHeight()); } } @@ -205,35 +201,35 @@ Texture CubeData::CreateTexture() const bool LoadCubeMapData(const std::string& path, CubeData& cubedata) { std::fstream fp(path, std::ios::in | std::ios::binary); - if (fp.is_open() == false) + if(fp.is_open() == false) { return false; } KtxFileHeader header; - if (fp.read(reinterpret_cast(&header), sizeof(KtxFileHeader)).good() == false) + if(fp.read(reinterpret_cast(&header), sizeof(KtxFileHeader)).good() == false) { return false; } - if (!header.IsIdentifierValid()) + if(!header.IsIdentifierValid()) { return false; } // Skip the key-values: - if (fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false) + if(fp.seekg(header.bytesOfKeyValueData, fp.cur).good() == false) { return false; } - header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u); + header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u); header.numberOfArrayElements = std::max(header.numberOfArrayElements, 1u); - header.pixelDepth = std::max(header.pixelDepth, 1u); - header.pixelHeight = std::max(header.pixelHeight, 1u); + header.pixelDepth = std::max(header.pixelDepth, 1u); + header.pixelHeight = std::max(header.pixelHeight, 1u); cubedata.data.resize(header.numberOfFaces); - for (uint32_t face = 0u; face < header.numberOfFaces; ++face) + for(uint32_t face = 0u; face < header.numberOfFaces; ++face) { cubedata.data[face].resize(header.numberOfMipmapLevels); } @@ -242,25 +238,25 @@ bool LoadCubeMapData(const std::string& path, CubeData& cubedata) ConvertPixelFormat(header.glInternalFormat, daliformat); - for (uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel) + for(uint32_t mipmapLevel = 0u; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel) { uint32_t byteSize = 0u; - if (fp.read(reinterpret_cast(&byteSize), sizeof(byteSize)).good() == false) + if(fp.read(reinterpret_cast(&byteSize), sizeof(byteSize)).good() == false) { return false; } - if (0u != byteSize % 4u) + if(0u != byteSize % 4u) { byteSize += 4u - byteSize % 4u; } - for (uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1 + for(uint32_t arrayElement = 0u; arrayElement < header.numberOfArrayElements; ++arrayElement) //arrayElement must be 0 or 1 { - for (uint32_t face = 0u; face < header.numberOfFaces; ++face) + for(uint32_t face = 0u; face < header.numberOfFaces; ++face) { - std::unique_ptrimg(new uint8_t[byteSize], FreeBuffer); - if (fp.read(reinterpret_cast(img.get()), byteSize).good() == false) + std::unique_ptr img(new uint8_t[byteSize], FreeBuffer); + if(fp.read(reinterpret_cast(img.get()), byteSize).good() == false) { return false; } @@ -275,5 +271,5 @@ bool LoadCubeMapData(const std::string& path, CubeData& cubedata) return true; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/material-definition.cpp b/dali-scene-loader/public-api/material-definition.cpp index 952a824..c0e816c 100644 --- a/dali-scene-loader/public-api/material-definition.cpp +++ b/dali-scene-loader/public-api/material-definition.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,7 +29,6 @@ namespace SceneLoader { namespace { - constexpr SamplerFlags::Type FILTER_MODES_FROM_DALI[]{ SamplerFlags::FILTER_LINEAR | SamplerFlags::FILTER_MIPMAP_NEAREST, SamplerFlags::FILTER_LINEAR, @@ -48,7 +47,7 @@ constexpr SamplerFlags::Type WRAP_MODES_FROM_DALI[]{ SamplerFlags::WRAP_MIRROR, }; -constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{ +constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{ FilterMode::NEAREST, FilterMode::LINEAR, FilterMode::NEAREST_MIPMAP_NEAREST, @@ -60,16 +59,15 @@ constexpr FilterMode::Type FILTER_MODES_TO_DALI[]{ constexpr WrapMode::Type WRAP_MODES_TO_DALI[]{ WrapMode::REPEAT, WrapMode::CLAMP_TO_EDGE, - WrapMode::MIRRORED_REPEAT -}; + WrapMode::MIRRORED_REPEAT}; const SamplerFlags::Type SINGLE_VALUE_SAMPLER = SamplerFlags::Encode(FilterMode::NEAREST, FilterMode::NEAREST, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE); -} +} // namespace SamplerFlags::Type SamplerFlags::Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT) { return FILTER_MODES_FROM_DALI[minFilter] | ((FILTER_MODES_FROM_DALI[magFilter] & FILTER_MAG_BITS) << FILTER_MAG_SHIFT) | - (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT); + (WRAP_MODES_FROM_DALI[wrapS] << WRAP_S_SHIFT) | (WRAP_MODES_FROM_DALI[wrapT] << WRAP_T_SHIFT); } FilterMode::Type SamplerFlags::GetMinFilter(Type flags) @@ -103,120 +101,119 @@ Sampler SamplerFlags::MakeSampler(Type flags) TextureDefinition::TextureDefinition(const std::string& imageUri, SamplerFlags::Type samplerFlags) : mImageUri(imageUri), mSamplerFlags(samplerFlags) -{} +{ +} MaterialDefinition::RawData - MaterialDefinition::LoadRaw(const std::string& imagesPath) const +MaterialDefinition::LoadRaw(const std::string& imagesPath) const { RawData raw; const bool hasTransparency = MaskMatch(mFlags, TRANSPARENCY); - uint32_t numBuffers = mTextureStages.size() + (hasTransparency ? - !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) : - !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS)); - if (numBuffers == 0) + uint32_t numBuffers = mTextureStages.size() + (hasTransparency ? !CheckTextures(ALBEDO) + !CheckTextures(METALLIC | ROUGHNESS) + !CheckTextures(NORMAL) : !CheckTextures(ALBEDO | METALLIC) + !CheckTextures(NORMAL | ROUGHNESS)); + if(numBuffers == 0) { return raw; } raw.mTextures.reserve(numBuffers); // Load textures - auto iTexture = mTextureStages.cbegin(); + auto iTexture = mTextureStages.cbegin(); auto checkStage = [&](uint32_t flags) { return iTexture != mTextureStages.end() && MaskMatch(iTexture->mSemantic, flags); }; // Check for compulsory textures: Albedo, Metallic, Roughness, Normal - if (checkStage(ALBEDO | METALLIC)) + if(checkStage(ALBEDO | METALLIC)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; - if (checkStage(NORMAL | ROUGHNESS)) + if(checkStage(NORMAL | ROUGHNESS)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } else // single value normal-roughness { const auto bufferSize = 4; - uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1 - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1 + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } } else { - if (checkStage(ALBEDO)) + if(checkStage(ALBEDO)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } else // single value albedo, albedo-alpha or albedo-metallic { uint32_t bufferSize = 4; - uint8_t* buffer = nullptr; - auto format = Pixel::Format::RGBA8888; - if (hasTransparency) // albedo-alpha + uint8_t* buffer = nullptr; + auto format = Pixel::Format::RGBA8888; + if(hasTransparency) // albedo-alpha { - buffer = new uint8_t[bufferSize]; + buffer = new uint8_t[bufferSize]; buffer[3] = static_cast(mColor.a * 255.f); } - else if (!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic + else if(!checkStage(METALLIC | ROUGHNESS)) // albedo-metallic { - buffer = new uint8_t[bufferSize]; - buffer[3] = 0xff; // metallic of 1.0 + buffer = new uint8_t[bufferSize]; + buffer[3] = 0xff; // metallic of 1.0 } - else // albedo + else // albedo { bufferSize = 3; - buffer = new uint8_t[bufferSize]; - format = Pixel::Format::RGB888; + buffer = new uint8_t[bufferSize]; + format = Pixel::Format::RGB888; } buffer[0] = static_cast(mColor.r * 255.f); buffer[1] = static_cast(mColor.g * 255.f); buffer[2] = static_cast(mColor.b * 255.f); - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, format, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } // If we have transparency, or an image based albedo map, we will have to continue with separate metallicRoughness + normal. const bool createMetallicRoughnessAndNormal = hasTransparency || std::distance(mTextureStages.begin(), iTexture) > 0; - if (checkStage(METALLIC | ROUGHNESS)) + if(checkStage(METALLIC | ROUGHNESS)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } - else if (createMetallicRoughnessAndNormal) + else if(createMetallicRoughnessAndNormal) { // NOTE: we want to set both metallic and roughness to 1.0; dli uses the R & A channels, // glTF2 uses B & G, so we might as well just set all components to 1.0. const auto bufferSize = 4; - uint8_t* buffer = new uint8_t[bufferSize]{ 0xff, 0xff, 0xff, 0xff }; - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0xff, 0xff, 0xff, 0xff}; + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } - if (checkStage(NORMAL)) + if(checkStage(NORMAL)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } - else if (createMetallicRoughnessAndNormal) + else if(createMetallicRoughnessAndNormal) { const auto bufferSize = 3; - uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff }; // normal of (0, 0, 1) - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff}; // normal of (0, 0, 1) + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGB888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } else // single-value normal-roughness { const auto bufferSize = 4; - uint8_t* buffer = new uint8_t[bufferSize]{ 0x7f, 0x7f, 0xff, 0xff }; // normal of (0, 0, 1), roughness of 1.0 - raw.mTextures.push_back({ PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER }); + uint8_t* buffer = new uint8_t[bufferSize]{0x7f, 0x7f, 0xff, 0xff}; // normal of (0, 0, 1), roughness of 1.0 + raw.mTextures.push_back({PixelData::New(buffer, bufferSize, 1, 1, Pixel::RGBA8888, PixelData::DELETE_ARRAY), SINGLE_VALUE_SAMPLER}); } } // Extra textures. TODO: emissive, occlusion etc. - if (checkStage(SUBSURFACE)) + if(checkStage(SUBSURFACE)) { - raw.mTextures.push_back({ SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags }); + raw.mTextures.push_back({SyncImageLoader::Load(imagesPath + iTexture->mTexture.mImageUri), iTexture->mTexture.mSamplerFlags}); ++iTexture; } @@ -228,12 +225,12 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ auto textureSet = TextureSet::New(); uint32_t n = 0; - for (auto& tData : raw.mTextures) + for(auto& tData : raw.mTextures) { - auto& pixels = tData.mPixels; - auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight()); + auto& pixels = tData.mPixels; + auto texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight()); texture.Upload(tData.mPixels, 0, 0, 0, 0, pixels.GetWidth(), pixels.GetHeight()); - if (tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK) + if(tData.mSamplerFlags & SamplerFlags::MIPMAP_MASK) { texture.GenerateMipmaps(); } @@ -245,16 +242,16 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ } // Assign textures to slots -- starting with 2D ones, then cubemaps, if any. - if (mEnvironmentIdx < environments.size()) + if(mEnvironmentIdx < environments.size()) { auto& envTextures = environments[mEnvironmentIdx].second; - if (envTextures.mDiffuse) + if(envTextures.mDiffuse) { textureSet.SetTexture(n, envTextures.mDiffuse); ++n; } - if (envTextures.mSpecular) + if(envTextures.mSpecular) { auto specularSampler = Sampler::New(); specularSampler.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE); @@ -266,8 +263,7 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ } else { - ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << - environments.size() << ")."; + ExceptionFlinger(ASSERT_LOCATION) << "Environment index (" << mEnvironmentIdx << ") out of bounds (" << environments.size() << ")."; } return textureSet; @@ -276,9 +272,9 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ bool MaterialDefinition::CheckTextures(uint32_t flags) const { return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts) { - return MaskMatch(ts.mSemantic, flags); - }) != mTextureStages.end(); + return MaskMatch(ts.mSemantic, flags); + }) != mTextureStages.end(); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/matrix-stack.cpp b/dali-scene-loader/public-api/matrix-stack.cpp index 9d4454f..eb2316e 100644 --- a/dali-scene-loader/public-api/matrix-stack.cpp +++ b/dali-scene-loader/public-api/matrix-stack.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,7 +21,6 @@ namespace Dali { namespace SceneLoader { - MatrixStack::MatrixStack() { mStack.reserve(16); @@ -34,13 +33,13 @@ bool MatrixStack::IsEmpty() const void MatrixStack::Push(const Matrix& model) { - if (mStack.empty()) + if(mStack.empty()) { mStack.push_back(model); } else { - Matrix m{ false }; + Matrix m{false}; Matrix::Multiply(m, model, mStack.back()); mStack.push_back(m); } @@ -62,5 +61,5 @@ void MatrixStack::PopAll() mStack.clear(); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/mesh-definition.cpp b/dali-scene-loader/public-api/mesh-definition.cpp index 2cea908..69292e2 100644 --- a/dali-scene-loader/public-api/mesh-definition.cpp +++ b/dali-scene-loader/public-api/mesh-definition.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 "dali-scene-loader/public-api/mesh-definition.h" // EXTERNAL INCLUDES -#include "dali/devel-api/adaptor-framework/pixel-buffer.h" -#include #include +#include +#include "dali/devel-api/adaptor-framework/pixel-buffer.h" namespace Dali { @@ -29,7 +29,6 @@ namespace SceneLoader { namespace { - using Uint16Vector4 = uint16_t[4]; class IndexProvider @@ -38,7 +37,8 @@ public: IndexProvider(const uint16_t* indices) : mData(reinterpret_cast(indices)), mFunc(indices ? IncrementPointer : Increment) - {} + { + } uint16_t operator()() { @@ -53,40 +53,39 @@ private: static uint16_t IncrementPointer(uintptr_t& data) { - auto iPtr = reinterpret_cast(data); + auto iPtr = reinterpret_cast(data); auto result = *iPtr; - data = reinterpret_cast(++iPtr); + data = reinterpret_cast(++iPtr); return result; } uintptr_t mData; - uint16_t(*mFunc)(uintptr_t&); + uint16_t (*mFunc)(uintptr_t&); }; - const std::string QUAD("quad"); ///@brief Reads a blob from the given stream @a source into @a target, which must have /// at least @a descriptor.length bytes. bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint8_t* target) { - if (!source.seekg(descriptor.mOffset, std::istream::beg)) + if(!source.seekg(descriptor.mOffset, std::istream::beg)) { return false; } - if (descriptor.IsConsecutive()) + if(descriptor.IsConsecutive()) { return !!source.read(reinterpret_cast(target), descriptor.mLength); } else { DALI_ASSERT_DEBUG(descriptor.mStride > descriptor.mElementSizeHint); - const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint; - uint32_t readSize = 0; - while (readSize < descriptor.mLength && - source.read(reinterpret_cast(target), descriptor.mElementSizeHint) && - source.seekg(diff, std::istream::cur)) + const uint32_t diff = descriptor.mStride - descriptor.mElementSizeHint; + uint32_t readSize = 0; + while(readSize < descriptor.mLength && + source.read(reinterpret_cast(target), descriptor.mElementSizeHint) && + source.seekg(diff, std::istream::cur)) { readSize += descriptor.mStride; target += descriptor.mElementSizeHint; @@ -95,11 +94,11 @@ bool ReadBlob(const MeshDefinition::Blob& descriptor, std::istream& source, uint } } -template +template void ReadValues(const std::vector& valuesBuffer, const std::vector& indicesBuffer, uint8_t* target, uint32_t count, uint32_t elementSizeHint) { const T* const indicesPtr = reinterpret_cast(indicesBuffer.data()); - for (uint32_t index = 0u; index < count; ++index) + for(uint32_t index = 0u; index < count; ++index) { uint32_t valuesIndex = indicesPtr[index] * elementSizeHint; memcpy(target + valuesIndex, &valuesBuffer[index * elementSizeHint], elementSizeHint); @@ -110,60 +109,60 @@ bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source { bool success = false; - if (accessor.mBlob.IsDefined()) + if(accessor.mBlob.IsDefined()) { success = ReadBlob(accessor.mBlob, source, target); - if (!success) + if(!success) { return false; } } - if (accessor.mSparse) + if(accessor.mSparse) { const MeshDefinition::Blob& indices = accessor.mSparse->mIndices; - const MeshDefinition::Blob& values = accessor.mSparse->mValues; + const MeshDefinition::Blob& values = accessor.mSparse->mValues; - if (!indices.IsDefined() || !values.IsDefined()) + if(!indices.IsDefined() || !values.IsDefined()) { return false; } - const auto indicesBufferSize = indices.GetBufferSize(); + const auto indicesBufferSize = indices.GetBufferSize(); std::vector indicesBuffer(indicesBufferSize); success = ReadBlob(indices, source, indicesBuffer.data()); - if (!success) + if(!success) { return false; } - const auto valuesBufferSize = values.GetBufferSize(); + const auto valuesBufferSize = values.GetBufferSize(); std::vector valuesBuffer(valuesBufferSize); success = ReadBlob(values, source, valuesBuffer.data()); - if (!success) + if(!success) { return false; } - switch (indices.mElementSizeHint) + switch(indices.mElementSizeHint) { - case 1u: - { - ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); - break; - } - case 2u: - { - ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); - break; - } - case 4u: - { - ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); - break; - } - default: - DALI_ASSERT_DEBUG(!"Unsupported type for an index"); + case 1u: + { + ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); + break; + } + case 2u: + { + ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); + break; + } + case 4u: + { + ReadValues(valuesBuffer, indicesBuffer, target, accessor.mSparse->mCount, values.mElementSizeHint); + break; + } + default: + DALI_ASSERT_DEBUG(!"Unsupported type for an index"); } } @@ -173,7 +172,7 @@ bool ReadAccessor(const MeshDefinition::Accessor& accessor, std::istream& source void GenerateNormals(MeshDefinition::RawData& raw) { auto& attribs = raw.mAttribs; - DALI_ASSERT_DEBUG(attribs.size() > 0); // positions + DALI_ASSERT_DEBUG(attribs.size() > 0); // positions IndexProvider getIndex(raw.mIndices.data()); const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size(); @@ -181,12 +180,12 @@ void GenerateNormals(MeshDefinition::RawData& raw) auto* positions = reinterpret_cast(attribs[0].mData.data()); std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto normals = reinterpret_cast(buffer.data()); + auto normals = reinterpret_cast(buffer.data()); - for (uint32_t i = 0; i < numIndices; i += 3) + for(uint32_t i = 0; i < numIndices; i += 3) { - uint16_t indices[]{ getIndex(), getIndex(), getIndex() }; - Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] }; + uint16_t indices[]{getIndex(), getIndex(), getIndex()}; + Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]}; Vector3 a = pos[1] - pos[0]; Vector3 b = pos[2] - pos[0]; @@ -198,34 +197,34 @@ void GenerateNormals(MeshDefinition::RawData& raw) } auto iEnd = normals + attribs[0].mNumElements; - while (normals != iEnd) + while(normals != iEnd) { normals->Normalize(); ++normals; } - attribs.push_back({ "aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) }); + attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)}); } void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) { auto& attribs = raw.mAttribs; - DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs + DALI_ASSERT_DEBUG(attribs.size() > 2); // positions, normals, uvs IndexProvider getIndex(raw.mIndices.data()); const uint32_t numIndices = raw.mIndices.empty() ? attribs[0].mNumElements : raw.mIndices.size(); auto* positions = reinterpret_cast(attribs[0].mData.data()); - auto* uvs = reinterpret_cast(attribs[2].mData.data()); + auto* uvs = reinterpret_cast(attribs[2].mData.data()); std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto tangents = reinterpret_cast(buffer.data()); + auto tangents = reinterpret_cast(buffer.data()); - for (uint32_t i = 0; i < numIndices; i += 3) + for(uint32_t i = 0; i < numIndices; i += 3) { - uint16_t indices[]{ getIndex(), getIndex(), getIndex() }; - Vector3 pos[]{ positions[indices[0]], positions[indices[1]], positions[indices[2]] }; - Vector2 uv[]{ uvs[indices[0]], uvs[indices[1]], uvs[indices[2]] }; + uint16_t indices[]{getIndex(), getIndex(), getIndex()}; + Vector3 pos[]{positions[indices[0]], positions[indices[1]], positions[indices[2]]}; + Vector2 uv[]{uvs[indices[0]], uvs[indices[1]], uvs[indices[2]]}; float x0 = pos[1].x - pos[0].x; float y0 = pos[1].y - pos[0].y; @@ -241,7 +240,7 @@ void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) float s1 = uv[2].x - uv[0].x; float t1 = uv[2].y - uv[0].y; - float r = 1.f / (s0 * t1 - t0 * s1); + float r = 1.f / (s0 * t1 - t0 * s1); Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r); tangents[indices[0]] += tangent; tangents[indices[1]] += tangent; @@ -249,8 +248,8 @@ void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) } auto* normals = reinterpret_cast(attribs[1].mData.data()); - auto iEnd = normals + attribs[1].mNumElements; - while (normals != iEnd) + auto iEnd = normals + attribs[1].mNumElements; + while(normals != iEnd) { *tangents -= *normals * normals->Dot(*tangents); tangents->Normalize(); @@ -258,23 +257,23 @@ void GenerateTangentsWithUvs(MeshDefinition::RawData& raw) ++tangents; ++normals; } - attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) }); + attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)}); } void GenerateTangents(MeshDefinition::RawData& raw) { auto& attribs = raw.mAttribs; - DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals + DALI_ASSERT_DEBUG(attribs.size() > 1); // positions, normals auto* normals = reinterpret_cast(attribs[1].mData.data()); std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto tangents = reinterpret_cast(buffer.data()); + auto tangents = reinterpret_cast(buffer.data()); auto iEnd = normals + attribs[1].mNumElements; - while (normals != iEnd) + while(normals != iEnd) { - Vector3 t[]{ normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS) }; + Vector3 t[]{normals->Cross(Vector3::XAXIS), normals->Cross(Vector3::YAXIS)}; *tangents = t[t[1].LengthSquared() > t[0].LengthSquared()]; *tangents -= *normals * normals->Dot(*tangents); @@ -283,7 +282,7 @@ void GenerateTangents(MeshDefinition::RawData& raw) ++tangents; ++normals; } - attribs.push_back({ "aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer) }); + attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)}); } void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uint32_t& textureHeight) @@ -293,74 +292,74 @@ void CalculateTextureSize(uint32_t totalTextureSize, uint32_t& textureWidth, uin // Calculate the dimensions of the texture. // The total size of the texture is the length of the blend shapes blob. - textureWidth = 0u; + textureWidth = 0u; textureHeight = 0u; - if (0u == totalTextureSize) + if(0u == totalTextureSize) { // nothing to do. return; } - const uint32_t pow2 = static_cast(ceil(log2(totalTextureSize))); - const uint32_t powWidth = pow2 >> 1u; + const uint32_t pow2 = static_cast(ceil(log2(totalTextureSize))); + const uint32_t powWidth = pow2 >> 1u; const uint32_t powHeight = pow2 - powWidth; - textureWidth = 1u << powWidth; + textureWidth = 1u << powWidth; textureHeight = 1u << powHeight; } void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, const std::vector& blendShapes, uint32_t numberOfVertices, float& blendShapeUnnormalizeFactor) { uint32_t geometryBufferIndex = 0u; - float maxDistance = 0.f; - Vector3* geometryBufferV3 = reinterpret_cast(geometryBuffer); - for (const auto& blendShape : blendShapes) + float maxDistance = 0.f; + Vector3* geometryBufferV3 = reinterpret_cast(geometryBuffer); + for(const auto& blendShape : blendShapes) { - if (blendShape.deltas.IsDefined()) + if(blendShape.deltas.IsDefined()) { DALI_ASSERT_ALWAYS(((blendShape.deltas.mBlob.mLength % sizeof(Vector3) == 0u) || - blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) && - "Blend Shape position buffer length not a multiple of element size"); + blendShape.deltas.mBlob.mStride >= sizeof(Vector3)) && + "Blend Shape position buffer length not a multiple of element size"); - const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize(); + const auto bufferSize = blendShape.deltas.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (ReadAccessor(blendShape.deltas, binFile, buffer.data())) + if(ReadAccessor(blendShape.deltas, binFile, buffer.data())) { blendShape.deltas.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); // Calculate the difference with the original mesh. // Find the max distance to normalize the deltas. const Vector3* const deltasBuffer = reinterpret_cast(buffer.data()); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta = deltasBuffer[index]; + delta = deltasBuffer[index]; maxDistance = std::max(maxDistance, delta.LengthSquared()); } } } - if (blendShape.normals.IsDefined()) + if(blendShape.normals.IsDefined()) { DALI_ASSERT_ALWAYS(((blendShape.normals.mBlob.mLength % sizeof(Vector3) == 0u) || - blendShape.normals.mBlob.mStride >= sizeof(Vector3)) && - "Blend Shape normals buffer length not a multiple of element size"); + blendShape.normals.mBlob.mStride >= sizeof(Vector3)) && + "Blend Shape normals buffer length not a multiple of element size"); - const auto bufferSize = blendShape.normals.mBlob.GetBufferSize(); + const auto bufferSize = blendShape.normals.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (ReadAccessor(blendShape.normals, binFile, buffer.data())) + if(ReadAccessor(blendShape.normals, binFile, buffer.data())) { blendShape.normals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); // Calculate the difference with the original mesh, and translate to make all values positive. const Vector3* const deltasBuffer = reinterpret_cast(buffer.data()); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta = deltasBuffer[index]; + delta = deltasBuffer[index]; delta.x *= 0.5f; delta.y *= 0.5f; @@ -373,25 +372,25 @@ void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, } } - if (blendShape.tangents.IsDefined()) + if(blendShape.tangents.IsDefined()) { DALI_ASSERT_ALWAYS(((blendShape.tangents.mBlob.mLength % sizeof(Vector3) == 0u) || - blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) && - "Blend Shape tangents buffer length not a multiple of element size"); + blendShape.tangents.mBlob.mStride >= sizeof(Vector3)) && + "Blend Shape tangents buffer length not a multiple of element size"); - const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize(); + const auto bufferSize = blendShape.tangents.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (ReadAccessor(blendShape.tangents, binFile, buffer.data())) + if(ReadAccessor(blendShape.tangents, binFile, buffer.data())) { blendShape.tangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); // Calculate the difference with the original mesh, and translate to make all values positive. const Vector3* const deltasBuffer = reinterpret_cast(buffer.data()); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta = deltasBuffer[index]; + delta = deltasBuffer[index]; delta.x *= 0.5f; delta.y *= 0.5f; @@ -406,81 +405,77 @@ void CalculateGltf2BlendShapes(uint8_t* geometryBuffer, std::ifstream& binFile, } geometryBufferIndex = 0u; - for (const auto& blendShape : blendShapes) + for(const auto& blendShape : blendShapes) { // Normalize all the deltas and translate to a possitive value. // Deltas are going to be passed to the shader in a color texture // whose values that are less than zero are clamped. - if (blendShape.deltas.IsDefined()) + if(blendShape.deltas.IsDefined()) { - const float normalizeFactor = (fabsf(maxDistance) < Math::MACHINE_EPSILON_1000) ? 1.f : (0.5f / sqrtf(maxDistance)); - for (uint32_t index = 0u; index < numberOfVertices; ++index) + for(uint32_t index = 0u; index < numberOfVertices; ++index) { Vector3& delta = geometryBufferV3[geometryBufferIndex++]; - delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f); - delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f); - delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f); + delta.x = Clamp(((delta.x * normalizeFactor) + 0.5f), 0.f, 1.f); + delta.y = Clamp(((delta.y * normalizeFactor) + 0.5f), 0.f, 1.f); + delta.z = Clamp(((delta.z * normalizeFactor) + 0.5f), 0.f, 1.f); } // Calculate and store the unnormalize factor. blendShapeUnnormalizeFactor = 1.f / normalizeFactor; } - if (blendShape.normals.IsDefined()) + if(blendShape.normals.IsDefined()) { geometryBufferIndex += numberOfVertices; } - if (blendShape.tangents.IsDefined()) + if(blendShape.tangents.IsDefined()) { geometryBufferIndex += numberOfVertices; } } } -} +} // namespace MeshDefinition::SparseBlob::SparseBlob(const Blob& indices, const Blob& values, uint32_t count) : mIndices{indices}, mValues{values}, mCount{count} -{} +{ +} -MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob, - const MeshDefinition::SparseBlob& sparse) +MeshDefinition::Accessor::Accessor(const MeshDefinition::Blob& blob, + const MeshDefinition::SparseBlob& sparse) : mBlob{blob}, mSparse{(sparse.mIndices.IsDefined() && sparse.mValues.IsDefined()) ? new SparseBlob{sparse} : nullptr} -{} +{ +} -void MeshDefinition::Blob::ApplyMinMax(const std::vector& min, const std::vector& max, - uint32_t count, float* values) +void MeshDefinition::Blob::ApplyMinMax(const std::vector& min, const std::vector& max, uint32_t count, float* values) { DALI_ASSERT_DEBUG(max.size() == min.size() || max.size() * min.size() == 0); const auto numComponents = std::max(min.size(), max.size()); - using ClampFn = void(*)(const float*, const float*, uint32_t, float&); - ClampFn clampFn = min.empty() ? - (max.empty() ? - static_cast(nullptr) : - [](const float* min, const float* max, uint32_t i, float& value) { - value = std::min(max[i], value); - }) : - (max.empty() ? - [](const float* min, const float* max, uint32_t i, float& value) { - value = std::max(min[i], value); - } : - [](const float* min, const float* max, uint32_t i, float& value) { - value = std::min(std::max(min[i], value), max[i]); - }); + using ClampFn = void (*)(const float*, const float*, uint32_t, float&); + ClampFn clampFn = min.empty() ? (max.empty() ? static_cast(nullptr) : [](const float* min, const float* max, uint32_t i, float& value) { + value = std::min(max[i], value); + }) + : (max.empty() ? [](const float* min, const float* max, uint32_t i, float& value) { + value = std::max(min[i], value); + } + : [](const float* min, const float* max, uint32_t i, float& value) { + value = std::min(std::max(min[i], value), max[i]); + }); auto end = values + count * numComponents; - while (values != end) + while(values != end) { - auto nextElement = values + numComponents; - uint32_t i = 0; - while (values != nextElement) + auto nextElement = values + numComponents; + uint32_t i = 0; + while(values != nextElement) { clampFn(min.data(), max.data(), i, *values); ++values; @@ -496,7 +491,8 @@ MeshDefinition::Blob::Blob(uint32_t offset, uint32_t length, uint16_t stride, ui mElementSizeHint(elementSizeHint), mMin(min), mMax(max) -{} +{ +} uint32_t MeshDefinition::Blob::GetBufferSize() const { @@ -511,7 +507,7 @@ void MeshDefinition::Blob::ApplyMinMax(uint32_t count, float* values) const void MeshDefinition::RawData::Attrib::AttachBuffer(Geometry& g) const { Property::Map attribMap; - attribMap[mName] = mType; + attribMap[mName] = mType; VertexBuffer attribBuffer = VertexBuffer::New(attribMap); attribBuffer.SetData(mData.data(), mNumElements); @@ -544,39 +540,39 @@ void MeshDefinition::RequestTangents() } MeshDefinition::RawData - MeshDefinition::LoadRaw(const std::string& modelsPath) const +MeshDefinition::LoadRaw(const std::string& modelsPath) const { RawData raw; - if (IsQuad()) + if(IsQuad()) { return raw; } const std::string meshPath = modelsPath + mUri; - std::ifstream binFile(meshPath, std::ios::binary); - if (!binFile) + std::ifstream binFile(meshPath, std::ios::binary); + if(!binFile) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read geometry data from '" << meshPath << "'"; } - if (mIndices.IsDefined()) + if(mIndices.IsDefined()) { - if (MaskMatch(mFlags, U32_INDICES)) + if(MaskMatch(mFlags, U32_INDICES)) { DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(uint32_t) == 0) || - mIndices.mBlob.mStride >= sizeof(uint32_t)) && - "Index buffer length not a multiple of element size"); + mIndices.mBlob.mStride >= sizeof(uint32_t)) && + "Index buffer length not a multiple of element size"); const auto indexCount = mIndices.mBlob.GetBufferSize() / sizeof(uint32_t); - raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially. - if (!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) + raw.mIndices.resize(indexCount * 2); // NOTE: we need space for uint32_ts initially. + if(!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'."; } auto u16s = raw.mIndices.data(); auto u32s = reinterpret_cast(raw.mIndices.data()); - auto end = u32s + indexCount; - while (u32s != end) + auto end = u32s + indexCount; + while(u32s != end) { *u16s = static_cast(*u32s); ++u16s; @@ -588,10 +584,10 @@ MeshDefinition::RawData else { DALI_ASSERT_ALWAYS(((mIndices.mBlob.mLength % sizeof(unsigned short) == 0) || - mIndices.mBlob.mStride >= sizeof(unsigned short)) && - "Index buffer length not a multiple of element size"); + mIndices.mBlob.mStride >= sizeof(unsigned short)) && + "Index buffer length not a multiple of element size"); raw.mIndices.resize(mIndices.mBlob.mLength / sizeof(unsigned short)); - if (!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) + if(!ReadAccessor(mIndices, binFile, reinterpret_cast(raw.mIndices.data()))) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read indices from '" << meshPath << "'."; } @@ -599,14 +595,14 @@ MeshDefinition::RawData } std::vector positions; - if (mPositions.IsDefined()) + if(mPositions.IsDefined()) { DALI_ASSERT_ALWAYS(((mPositions.mBlob.mLength % sizeof(Vector3) == 0) || - mPositions.mBlob.mStride >= sizeof(Vector3)) && - "Position buffer length not a multiple of element size"); - const auto bufferSize = mPositions.mBlob.GetBufferSize(); + mPositions.mBlob.mStride >= sizeof(Vector3)) && + "Position buffer length not a multiple of element size"); + const auto bufferSize = mPositions.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mPositions, binFile, buffer.data())) + if(!ReadAccessor(mPositions, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read positions from '" << meshPath << "'."; } @@ -614,35 +610,34 @@ MeshDefinition::RawData uint32_t numVector3 = bufferSize / sizeof(Vector3); mPositions.mBlob.ApplyMinMax(numVector3, reinterpret_cast(buffer.data())); - if (HasBlendShapes()) + if(HasBlendShapes()) { positions.resize(numVector3); std::copy(buffer.data(), buffer.data() + buffer.size(), reinterpret_cast(positions.data())); } - raw.mAttribs.push_back({ "aPosition", Property::VECTOR3, numVector3, std::move(buffer) }); + raw.mAttribs.push_back({"aPosition", Property::VECTOR3, numVector3, std::move(buffer)}); } const auto isTriangles = mPrimitiveType == Geometry::TRIANGLES; - auto hasNormals = mNormals.IsDefined(); - if (hasNormals) + auto hasNormals = mNormals.IsDefined(); + if(hasNormals) { DALI_ASSERT_ALWAYS(((mNormals.mBlob.mLength % sizeof(Vector3) == 0) || - mNormals.mBlob.mStride >= sizeof(Vector3)) && - "Normal buffer length not a multiple of element size"); - const auto bufferSize = mNormals.mBlob.GetBufferSize(); + mNormals.mBlob.mStride >= sizeof(Vector3)) && + "Normal buffer length not a multiple of element size"); + const auto bufferSize = mNormals.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mNormals, binFile, buffer.data())) + if(!ReadAccessor(mNormals, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read normals from '" << meshPath << "'."; } mNormals.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); - raw.mAttribs.push_back({ "aNormal", Property::VECTOR3, - static_cast(bufferSize / sizeof(Vector3)), std::move(buffer) }); + raw.mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast(bufferSize / sizeof(Vector3)), std::move(buffer)}); } - else if (mNormals.mBlob.mLength != 0 && isTriangles) + else if(mNormals.mBlob.mLength != 0 && isTriangles) { DALI_ASSERT_DEBUG(mNormals.mBlob.mLength == mPositions.mBlob.GetBufferSize()); GenerateNormals(raw); @@ -650,24 +645,24 @@ MeshDefinition::RawData } const auto hasUvs = mTexCoords.IsDefined(); - if (hasUvs) + if(hasUvs) { DALI_ASSERT_ALWAYS(((mTexCoords.mBlob.mLength % sizeof(Vector2) == 0) || - mTexCoords.mBlob.mStride >= sizeof(Vector2)) && - "Normal buffer length not a multiple of element size"); - const auto bufferSize = mTexCoords.mBlob.GetBufferSize(); + mTexCoords.mBlob.mStride >= sizeof(Vector2)) && + "Normal buffer length not a multiple of element size"); + const auto bufferSize = mTexCoords.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mTexCoords, binFile, buffer.data())) + if(!ReadAccessor(mTexCoords, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read uv-s from '" << meshPath << "'."; } const auto uvCount = bufferSize / sizeof(Vector2); - if (MaskMatch(mFlags, FLIP_UVS_VERTICAL)) + if(MaskMatch(mFlags, FLIP_UVS_VERTICAL)) { - auto uv = reinterpret_cast(buffer.data()); + auto uv = reinterpret_cast(buffer.data()); auto uvEnd = uv + uvCount; - while (uv != uvEnd) + while(uv != uvEnd) { uv->y = 1.0f - uv->y; ++uv; @@ -676,89 +671,84 @@ MeshDefinition::RawData mTexCoords.mBlob.ApplyMinMax(bufferSize / sizeof(Vector2), reinterpret_cast(buffer.data())); - raw.mAttribs.push_back({ "aTexCoord", Property::VECTOR2, static_cast(uvCount), - std::move(buffer) }); + raw.mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast(uvCount), std::move(buffer)}); } - if (mTangents.IsDefined()) + if(mTangents.IsDefined()) { DALI_ASSERT_ALWAYS(((mTangents.mBlob.mLength % sizeof(Vector3) == 0) || - mTangents.mBlob.mStride >= sizeof(Vector3)) && - "Tangents buffer length not a multiple of element size"); - const auto bufferSize = mTangents.mBlob.GetBufferSize(); + mTangents.mBlob.mStride >= sizeof(Vector3)) && + "Tangents buffer length not a multiple of element size"); + const auto bufferSize = mTangents.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mTangents, binFile, buffer.data())) + if(!ReadAccessor(mTangents, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read tangents from '" << meshPath << "'."; } mTangents.mBlob.ApplyMinMax(bufferSize / sizeof(Vector3), reinterpret_cast(buffer.data())); - raw.mAttribs.push_back({ "aTangent", Property::VECTOR3, - static_cast(bufferSize / sizeof(Vector3)), std::move(buffer) }); + raw.mAttribs.push_back({"aTangent", Property::VECTOR3, static_cast(bufferSize / sizeof(Vector3)), std::move(buffer)}); } - else if (mTangents.mBlob.mLength != 0 && hasNormals && isTriangles) + else if(mTangents.mBlob.mLength != 0 && hasNormals && isTriangles) { DALI_ASSERT_DEBUG(mTangents.mBlob.mLength == mNormals.mBlob.GetBufferSize()); hasUvs ? GenerateTangentsWithUvs(raw) : GenerateTangents(raw); } - if (IsSkinned()) + if(IsSkinned()) { - if (MaskMatch(mFlags, U16_JOINT_IDS)) + if(MaskMatch(mFlags, U16_JOINT_IDS)) { DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Uint16Vector4) == 0) || - mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) && - "Joints buffer length not a multiple of element size"); - const auto inBufferSize = mJoints0.mBlob.GetBufferSize(); + mJoints0.mBlob.mStride >= sizeof(Uint16Vector4)) && + "Joints buffer length not a multiple of element size"); + const auto inBufferSize = mJoints0.mBlob.GetBufferSize(); std::vector buffer(inBufferSize * 2); - auto u16s = buffer.data() + inBufferSize; - if (!ReadAccessor(mJoints0, binFile, u16s)) + auto u16s = buffer.data() + inBufferSize; + if(!ReadAccessor(mJoints0, binFile, u16s)) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'."; } auto floats = reinterpret_cast(buffer.data()); - auto end = u16s + inBufferSize; - while (u16s != end) + auto end = u16s + inBufferSize; + while(u16s != end) { auto value = *reinterpret_cast(u16s); - *floats = static_cast(value); + *floats = static_cast(value); u16s += sizeof(uint16_t); ++floats; } - raw.mAttribs.push_back({ "aJoints", Property::VECTOR4, - static_cast(buffer.size() / sizeof(Vector4)), std::move(buffer) }); + raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast(buffer.size() / sizeof(Vector4)), std::move(buffer)}); } else { DALI_ASSERT_ALWAYS(((mJoints0.mBlob.mLength % sizeof(Vector4) == 0) || - mJoints0.mBlob.mStride >= sizeof(Vector4)) && - "Joints buffer length not a multiple of element size"); - const auto bufferSize = mJoints0.mBlob.GetBufferSize(); + mJoints0.mBlob.mStride >= sizeof(Vector4)) && + "Joints buffer length not a multiple of element size"); + const auto bufferSize = mJoints0.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mJoints0, binFile, buffer.data())) + if(!ReadAccessor(mJoints0, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read joints from '" << meshPath << "'."; } - raw.mAttribs.push_back({ "aJoints", Property::VECTOR4, - static_cast(bufferSize / sizeof(Vector4)), std::move(buffer) }); + raw.mAttribs.push_back({"aJoints", Property::VECTOR4, static_cast(bufferSize / sizeof(Vector4)), std::move(buffer)}); } DALI_ASSERT_ALWAYS(((mWeights0.mBlob.mLength % sizeof(Vector4) == 0) || - mWeights0.mBlob.mStride >= sizeof(Vector4)) && - "Weights buffer length not a multiple of element size"); - const auto bufferSize = mWeights0.mBlob.GetBufferSize(); + mWeights0.mBlob.mStride >= sizeof(Vector4)) && + "Weights buffer length not a multiple of element size"); + const auto bufferSize = mWeights0.mBlob.GetBufferSize(); std::vector buffer(bufferSize); - if (!ReadAccessor(mWeights0, binFile, buffer.data())) + if(!ReadAccessor(mWeights0, binFile, buffer.data())) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to read weights from '" << meshPath << "'."; } - raw.mAttribs.push_back({ "aWeights", Property::VECTOR4, - static_cast(bufferSize / sizeof(Vector4)), std::move(buffer) }); + raw.mAttribs.push_back({"aWeights", Property::VECTOR4, static_cast(bufferSize / sizeof(Vector4)), std::move(buffer)}); } // Calculate the Blob for the blend shapes. @@ -766,11 +756,11 @@ MeshDefinition::RawData blendShapesBlob.mOffset = std::numeric_limits::max(); blendShapesBlob.mLength = 0u; - for (const auto& blendShape : mBlendShapes) + for(const auto& blendShape : mBlendShapes) { - for (auto i : { &blendShape.deltas, &blendShape.normals, &blendShape.tangents }) + for(auto i : {&blendShape.deltas, &blendShape.normals, &blendShape.tangents}) { - if (i->IsDefined()) + if(i->IsDefined()) { blendShapesBlob.mOffset = std::min(blendShapesBlob.mOffset, i->mBlob.mOffset); blendShapesBlob.mLength += i->mBlob.mLength; @@ -778,18 +768,18 @@ MeshDefinition::RawData } } - if (HasBlendShapes()) + if(HasBlendShapes()) { const uint32_t numberOfVertices = mPositions.mBlob.mLength / sizeof(Vector3); // Calculate the size of one buffer inside the texture. raw.mBlendShapeBufferOffset = numberOfVertices; - bool calculateGltf2BlendShapes = false; - uint32_t textureWidth = 0u; - uint32_t textureHeight = 0u; + bool calculateGltf2BlendShapes = false; + uint32_t textureWidth = 0u; + uint32_t textureHeight = 0u; - if (!mBlendShapeHeader.IsDefined()) + if(!mBlendShapeHeader.IsDefined()) { CalculateTextureSize(blendShapesBlob.mLength / sizeof(Vector3), textureWidth, textureHeight); calculateGltf2BlendShapes = true; @@ -798,7 +788,7 @@ MeshDefinition::RawData { uint16_t header[2u]; ReadBlob(mBlendShapeHeader, binFile, reinterpret_cast(header)); - textureWidth = header[0u]; + textureWidth = header[0u]; textureHeight = header[1u]; } @@ -806,9 +796,9 @@ MeshDefinition::RawData raw.mBlendShapeUnnormalizeFactor.Resize(numberOfBlendShapes); Devel::PixelBuffer geometryPixelBuffer = Devel::PixelBuffer::New(textureWidth, textureHeight, Pixel::RGB32F); - uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer(); + uint8_t* geometryBuffer = geometryPixelBuffer.GetBuffer(); - if (calculateGltf2BlendShapes) + if(calculateGltf2BlendShapes) { CalculateGltf2BlendShapes(geometryBuffer, binFile, mBlendShapes, numberOfVertices, raw.mBlendShapeUnnormalizeFactor[0u]); } @@ -817,16 +807,16 @@ MeshDefinition::RawData Blob unnormalizeFactorBlob; unnormalizeFactorBlob.mLength = sizeof(float) * ((BlendShapes::Version::VERSION_2_0 == mBlendShapeVersion) ? 1u : numberOfBlendShapes); - if (blendShapesBlob.IsDefined()) + if(blendShapesBlob.IsDefined()) { - if (ReadBlob(blendShapesBlob, binFile, geometryBuffer)) + if(ReadBlob(blendShapesBlob, binFile, geometryBuffer)) { unnormalizeFactorBlob.mOffset = blendShapesBlob.mOffset + blendShapesBlob.mLength; } } // Read the unnormalize factors. - if (unnormalizeFactorBlob.IsDefined()) + if(unnormalizeFactorBlob.IsDefined()) { ReadBlob(unnormalizeFactorBlob, binFile, reinterpret_cast(&raw.mBlendShapeUnnormalizeFactor[0u])); } @@ -843,32 +833,32 @@ MeshGeometry MeshDefinition::Load(RawData&& raw) const meshGeometry.geometry = Geometry::New(); meshGeometry.geometry.SetType(mPrimitiveType); - if (IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers. + if(IsQuad()) // TODO: do this in raw data; provide MakeTexturedQuadGeometry() that only creates buffers. { - auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0; + auto options = MaskMatch(mFlags, FLIP_UVS_VERTICAL) ? TexturedQuadOptions::FLIP_VERTICAL : 0; meshGeometry.geometry = MakeTexturedQuadGeometry(options); } else { - if (!raw.mIndices.empty()) + if(!raw.mIndices.empty()) { meshGeometry.geometry.SetIndexBuffer(raw.mIndices.data(), raw.mIndices.size()); } - for (auto& a : raw.mAttribs) + for(auto& a : raw.mAttribs) { a.AttachBuffer(meshGeometry.geometry); } - if (HasBlendShapes()) + if(HasBlendShapes()) { - meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset; + meshGeometry.blendShapeBufferOffset = raw.mBlendShapeBufferOffset; meshGeometry.blendShapeUnnormalizeFactor = std::move(raw.mBlendShapeUnnormalizeFactor); - meshGeometry.blendShapeGeometry = Texture::New( TextureType::TEXTURE_2D, - raw.mBlendShapeData.GetPixelFormat(), - raw.mBlendShapeData.GetWidth(), - raw.mBlendShapeData.GetHeight()); + meshGeometry.blendShapeGeometry = Texture::New(TextureType::TEXTURE_2D, + raw.mBlendShapeData.GetPixelFormat(), + raw.mBlendShapeData.GetWidth(), + raw.mBlendShapeData.GetHeight()); meshGeometry.blendShapeGeometry.Upload(raw.mBlendShapeData); } } @@ -876,5 +866,5 @@ MeshGeometry MeshDefinition::Load(RawData&& raw) const return meshGeometry; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/node-definition.cpp b/dali-scene-loader/public-api/node-definition.cpp index a277371..45e0b23 100644 --- a/dali-scene-loader/public-api/node-definition.cpp +++ b/dali-scene-loader/public-api/node-definition.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,6 @@ namespace Dali { namespace SceneLoader { - void NodeDefinition::Renderable::RegisterResources(IResourceReceiver& receiver) const { receiver.Register(ResourceType::Shader, mShaderIdx); @@ -35,15 +34,14 @@ void NodeDefinition::Renderable::ReflectResources(IResourceReflector& reflector) reflector.Reflect(ResourceType::Shader, mShaderIdx); } -void NodeDefinition::Renderable::OnCreate(const NodeDefinition& node, CreateParams& params, - Actor& actor) const +void NodeDefinition::Renderable::OnCreate(const NodeDefinition& node, CreateParams& params, Actor& actor) const { DALI_ASSERT_DEBUG(mShaderIdx != INVALID_INDEX); - auto& resources = params.mResources; - Shader shader = resources.mShaders[mShaderIdx].second; + auto& resources = params.mResources; + Shader shader = resources.mShaders[mShaderIdx].second; static Geometry defaultGeometry = Geometry::New(); - Renderer renderer = Renderer::New(defaultGeometry, shader); + Renderer renderer = Renderer::New(defaultGeometry, shader); RendererState::Apply(resources.mShaders[mShaderIdx].first.mRendererState, renderer); @@ -66,19 +64,19 @@ Actor NodeDefinition::CreateActor(CreateParams& params) const actor.RegisterProperty(ORIGINAL_MATRIX_PROPERTY_NAME, GetLocalSpace(), Property::AccessMode::READ_ONLY); - if (mRenderable) + if(mRenderable) { mRenderable->OnCreate(*this, params, actor); } - for (auto& e : mExtras) + for(auto& e : mExtras) { actor.RegisterProperty(e.mKey, e.mValue); } - for (auto& c : mConstraints) + for(auto& c : mConstraints) { - params.mConstrainables.push_back(ConstraintRequest{ &c, actor }); + params.mConstrainables.push_back(ConstraintRequest{&c, actor}); } return actor; @@ -86,7 +84,7 @@ Actor NodeDefinition::CreateActor(CreateParams& params) const Matrix NodeDefinition::GetLocalSpace() const { - Matrix localSpace{ false }; + Matrix localSpace{false}; localSpace.SetTransformComponents(mScale, mOrientation, mPosition); return localSpace; } @@ -111,34 +109,34 @@ void ModelNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParam Renderable::OnCreate(node, params, actor); auto& resources = params.mResources; - auto& mesh = resources.mMeshes[mMeshIdx]; + auto& mesh = resources.mMeshes[mMeshIdx]; - auto renderer = actor.GetRendererAt(0); + auto renderer = actor.GetRendererAt(0); Geometry geometry = mesh.second.geometry; renderer.SetGeometry(geometry); auto shader = renderer.GetShader(); - if (mesh.first.IsSkinned()) + if(mesh.first.IsSkinned()) { - params.mSkinnables.push_back(SkinningShaderConfigurationRequest{ mesh.first.mSkeletonIdx, shader }); + params.mSkinnables.push_back(SkinningShaderConfigurationRequest{mesh.first.mSkeletonIdx, shader}); } - if (mesh.first.HasBlendShapes()) + if(mesh.first.HasBlendShapes()) { - params.mBlendshapeRequests.push_back(BlendshapeShaderConfigurationRequest{ node.mName, mMeshIdx, shader }); + params.mBlendshapeRequests.push_back(BlendshapeShaderConfigurationRequest{node.mName, mMeshIdx, shader}); } TextureSet textures = resources.mMaterials[mMaterialIdx].second; // Set the blend shape texture. - if (mesh.second.blendShapeGeometry) + if(mesh.second.blendShapeGeometry) { TextureSet newTextureSet = TextureSet::New(); newTextureSet.SetTexture(0u, mesh.second.blendShapeGeometry); const unsigned int numberOfTextures = textures.GetTextureCount(); - for (unsigned int index = 0u; index < numberOfTextures; ++index) + for(unsigned int index = 0u; index < numberOfTextures; ++index) { const unsigned int newIndex = index + 1u; newTextureSet.SetTexture(newIndex, textures.GetTexture(index)); @@ -160,14 +158,13 @@ void ModelNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParam actor.RegisterProperty("uIblIntensity", resources.mEnvironmentMaps[envIdx].first.mIblIntensity); const auto alphaCutoff = matDef.GetAlphaCutoff(); - if (alphaCutoff > 0.f) + if(alphaCutoff > 0.f) { actor.RegisterProperty("uAlphaThreshold", alphaCutoff); } } -void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params, - Actor& actor) const +void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& params, Actor& actor) const { ModelNode::OnCreate(node, params, actor); @@ -176,11 +173,11 @@ void ArcNode::OnCreate(const NodeDefinition& node, NodeDefinition::CreateParams& actor.RegisterProperty("radius", mRadius); const float startAngleRadians = mStartAngleDegrees * Math::PI_OVER_180; - Vector2 startPolar{ std::cos(startAngleRadians), std::sin(startAngleRadians) }; + Vector2 startPolar{std::cos(startAngleRadians), std::sin(startAngleRadians)}; actor.RegisterProperty("startAngle", startPolar); const float endAngleRadians = mEndAngleDegrees * Math::PI_OVER_180; - Vector2 endPolar{ std::cos(endAngleRadians), std::sin(endAngleRadians) }; + Vector2 endPolar{std::cos(endAngleRadians), std::sin(endAngleRadians)}; actor.RegisterProperty("endAngle", endPolar); } @@ -188,12 +185,12 @@ void ArcNode::GetEndVectorWithDiffAngle(float startAngle, float diffAngle, Vecto { float endAngle = 0.f; - if (diffAngle <= 0.001f) + if(diffAngle <= 0.001f) { //0.001 is used to ensure is empty arc when startAngle = endAngle + 360 * N endAngle = startAngle + 0.001f; } - else if (diffAngle >= 360.f) + else if(diffAngle >= 360.f) { endAngle = diffAngle + 359.99f; } @@ -205,5 +202,5 @@ void ArcNode::GetEndVectorWithDiffAngle(float startAngle, float diffAngle, Vecto endVector.y = sinf(endAngle * Math::PI_OVER_180); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/parse-renderer-state.cpp b/dali-scene-loader/public-api/parse-renderer-state.cpp index c60b1d4..815dfaf 100644 --- a/dali-scene-loader/public-api/parse-renderer-state.cpp +++ b/dali-scene-loader/public-api/parse-renderer-state.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,8 +16,8 @@ */ #include "dali-scene-loader/public-api/parse-renderer-state.h" -#include "dali/devel-api/common/map-wrapper.h" #include +#include "dali/devel-api/common/map-wrapper.h" namespace Dali { @@ -27,9 +27,8 @@ namespace RendererState { namespace { - std::map COMPARISONS{ -#define DECL_COMPARISON(x) { #x, Comparison::x } +#define DECL_COMPARISON(x) {#x, Comparison::x} DECL_COMPARISON(NEVER), DECL_COMPARISON(ALWAYS), DECL_COMPARISON(LESS), @@ -45,7 +44,7 @@ Type InterpretComparison(const std::string_view& str) { Type value = 0x0; auto iFind = COMPARISONS.find(str); - if (iFind != COMPARISONS.end()) + if(iFind != COMPARISONS.end()) { value = iFind->second; } @@ -53,7 +52,7 @@ Type InterpretComparison(const std::string_view& str) } std::map BLEND_FACTORS{ -#define DECL_BLEND_FACTOR(x) { #x, SceneLoader::BlendFactor::x } +#define DECL_BLEND_FACTOR(x) {#x, SceneLoader::BlendFactor::x} DECL_BLEND_FACTOR(ZERO), DECL_BLEND_FACTOR(ONE), DECL_BLEND_FACTOR(SRC_COLOR), @@ -76,7 +75,7 @@ Type InterpretBlendFactor(const std::string_view& str, uint8_t item) { Type value = 0x0; auto iFind = BLEND_FACTORS.find(str); - if (iFind != BLEND_FACTORS.end()) + if(iFind != BLEND_FACTORS.end()) { value = iFind->second << (BLEND_FACTOR_BASE_SHIFT + BLEND_FACTOR_ITEM_BITS * item); } @@ -84,7 +83,7 @@ Type InterpretBlendFactor(const std::string_view& str, uint8_t item) } std::map BUFFER_MODES{ -#define DECL_BUFFER_MODE(x) { #x, BufferMode::x } +#define DECL_BUFFER_MODE(x) {#x, BufferMode::x} DECL_BUFFER_MODE(NONE), DECL_BUFFER_MODE(AUTO), DECL_BUFFER_MODE(COLOR), @@ -96,63 +95,62 @@ Type InterpretBufferMode(const std::string_view& str) { Type value = 0x0; auto iFind = BUFFER_MODES.find(str); - if (iFind != BUFFER_MODES.end()) + if(iFind != BUFFER_MODES.end()) { value = iFind->second << BUFFER_MODE_SHIFT; } return value; } -std::map RENDERER_STATE_PROCESSORS{ - { "DEPTH_WRITE", [](const std::string_view&) -> Type { return DEPTH_WRITE; } }, - { "DEPTH_TEST", [](const std::string_view&) -> Type { return DEPTH_TEST; } }, - { "CULL_FRONT", [](const std::string_view&) -> Type { return CULL_FRONT; } }, - { "CULL_BACK", [](const std::string_view&) -> Type { return CULL_BACK; } }, - { "ALPHA_BLEND", [](const std::string_view&) -> Type { return ALPHA_BLEND; } }, - { "DEPTH_FUNC", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? - (InterpretComparison(std::string_view(arg.data() + 1, arg.size() - 1)) << DEPTH_FUNCTION_SHIFT) : 0x0; - return value; - } }, - { "BLEND_SRC_RGB", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 0) : 0x0; - return value; - }}, - { "BLEND_DST_RGB", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 1) : 0x0; - return value; - }}, - { "BLEND_SRC_ALPHA", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 2) : 0x0; - return value; - }}, - { "BLEND_DST_ALPHA", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 3) : 0x0; - return value; - }}, - { "BUFFER_MODE", [](const std::string_view& arg) -> Type { - Type value = (arg[0] == ':') ? InterpretBufferMode(std::string_view(arg.data() + 1, arg.size() - 1)) : 0x0; - return value; - }}, +std::map RENDERER_STATE_PROCESSORS{ + {"DEPTH_WRITE", [](const std::string_view&) -> Type { return DEPTH_WRITE; }}, + {"DEPTH_TEST", [](const std::string_view&) -> Type { return DEPTH_TEST; }}, + {"CULL_FRONT", [](const std::string_view&) -> Type { return CULL_FRONT; }}, + {"CULL_BACK", [](const std::string_view&) -> Type { return CULL_BACK; }}, + {"ALPHA_BLEND", [](const std::string_view&) -> Type { return ALPHA_BLEND; }}, + {"DEPTH_FUNC", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? (InterpretComparison(std::string_view(arg.data() + 1, arg.size() - 1)) << DEPTH_FUNCTION_SHIFT) : 0x0; + return value; + }}, + {"BLEND_SRC_RGB", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 0) : 0x0; + return value; + }}, + {"BLEND_DST_RGB", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 1) : 0x0; + return value; + }}, + {"BLEND_SRC_ALPHA", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 2) : 0x0; + return value; + }}, + {"BLEND_DST_ALPHA", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBlendFactor(std::string_view(arg.data() + 1, arg.size() - 1), 3) : 0x0; + return value; + }}, + {"BUFFER_MODE", [](const std::string_view& arg) -> Type { + Type value = (arg[0] == ':') ? InterpretBufferMode(std::string_view(arg.data() + 1, arg.size() - 1)) : 0x0; + return value; + }}, }; -} +} // namespace Type Parse(const char* string, size_t length, StringCallback onError) { - if (length == 0) + if(length == 0) { length = strlen(string); } Type value = 0x0; - auto iEnd = string + length; - while (string != iEnd) + auto iEnd = string + length; + while(string != iEnd) { auto iNextToken = std::find(string, iEnd, '|'); - auto iColon = std::find(string, iNextToken, ':'); - auto i = RENDERER_STATE_PROCESSORS.find(std::string_view(string, iColon - string)); - if (i != RENDERER_STATE_PROCESSORS.end() && size_t(std::distance(string, iNextToken)) >= i->first.size()) + auto iColon = std::find(string, iNextToken, ':'); + auto i = RENDERER_STATE_PROCESSORS.find(std::string_view(string, iColon - string)); + if(i != RENDERER_STATE_PROCESSORS.end() && size_t(std::distance(string, iNextToken)) >= i->first.size()) { value |= i->second(std::string_view(string + i->first.size(), iNextToken - iColon)); } @@ -167,6 +165,6 @@ Type Parse(const char* string, size_t length, StringCallback onError) return value; } -} // RendererState -} -} +} // namespace RendererState +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/renderer-state.cpp b/dali-scene-loader/public-api/renderer-state.cpp index c3888a0..80178b5 100644 --- a/dali-scene-loader/public-api/renderer-state.cpp +++ b/dali-scene-loader/public-api/renderer-state.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 SceneLoader namespace { // NOTE: values for BlendFactor aren't contiguous, hence we need a mapping. -const Dali::BlendFactor::Type kBlendFactors[] = { +const Dali::BlendFactor::Type kBlendFactors[] = { Dali::BlendFactor::ZERO, Dali::BlendFactor::ONE, Dali::BlendFactor::SRC_COLOR, @@ -41,7 +41,7 @@ const Dali::BlendFactor::Type kBlendFactors[] = { Dali::BlendFactor::CONSTANT_ALPHA, Dali::BlendFactor::ONE_MINUS_CONSTANT_ALPHA, }; -} +} // namespace namespace RendererState { @@ -55,48 +55,46 @@ void Apply(Type rendererState, Renderer& renderer) RENDERER_SET_PROPERTY(BLEND_MODE, MaskMatch(rendererState, ALPHA_BLEND) ? BlendMode::ON : BlendMode::OFF); const bool cullBack = MaskMatch(rendererState, CULL_BACK); - RENDERER_SET_PROPERTY(FACE_CULLING_MODE, MaskMatch(rendererState, CULL_FRONT) ? - (cullBack ? FaceCullingMode::FRONT_AND_BACK : FaceCullingMode::FRONT) : - (cullBack ? FaceCullingMode::BACK : FaceCullingMode::NONE)); + RENDERER_SET_PROPERTY(FACE_CULLING_MODE, MaskMatch(rendererState, CULL_FRONT) ? (cullBack ? FaceCullingMode::FRONT_AND_BACK : FaceCullingMode::FRONT) : (cullBack ? FaceCullingMode::BACK : FaceCullingMode::NONE)); - if (auto depthFunc = (rendererState & DEPTH_FUNCTION_MASK) >> DEPTH_FUNCTION_SHIFT) + if(auto depthFunc = (rendererState & DEPTH_FUNCTION_MASK) >> DEPTH_FUNCTION_SHIFT) { RENDERER_SET_PROPERTY(DEPTH_FUNCTION, static_cast(depthFunc - 1)); } - if (auto blendFactors = (rendererState & BLEND_FACTOR_MASK) >> BLEND_FACTOR_BASE_SHIFT) + if(auto blendFactors = (rendererState & BLEND_FACTOR_MASK) >> BLEND_FACTOR_BASE_SHIFT) { - if (auto srcRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto srcRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_SRC_RGB, kBlendFactors[static_cast(srcRgb - 1)]); } blendFactors >>= BLEND_FACTOR_ITEM_BITS; - if (auto dstRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto dstRgb = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_DEST_RGB, kBlendFactors[static_cast(dstRgb - 1)]); } blendFactors >>= BLEND_FACTOR_ITEM_BITS; - if (auto srcAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto srcAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_SRC_ALPHA, kBlendFactors[static_cast(srcAlpha - 1)]); } blendFactors >>= BLEND_FACTOR_ITEM_BITS; - if (auto dstAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) + if(auto dstAlpha = (blendFactors & BLEND_FACTOR_ITEM_MASK)) { RENDERER_SET_PROPERTY(BLEND_FACTOR_DEST_ALPHA, kBlendFactors[static_cast(dstAlpha - 1)]); } } - if (auto bufferMode = (rendererState & BUFFER_MODE_MASK) >> BUFFER_MODE_SHIFT) + if(auto bufferMode = (rendererState & BUFFER_MODE_MASK) >> BUFFER_MODE_SHIFT) { RENDERER_SET_PROPERTY(RENDER_MODE, static_cast(bufferMode - 1)); } } -} // RendererState +} // namespace RendererState -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/resource-bundle.cpp b/dali-scene-loader/public-api/resource-bundle.cpp index 9ff10f6..98b08bb 100644 --- a/dali-scene-loader/public-api/resource-bundle.cpp +++ b/dali-scene-loader/public-api/resource-bundle.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,12 +19,11 @@ #include "dali-scene-loader/public-api/resource-bundle.h" // EXTERNAL -#include "dali/public-api/rendering/sampler.h" -#include "dali-toolkit/public-api/image-loader/sync-image-loader.h" -#include -#include #include #include +#include +#include "dali-toolkit/public-api/image-loader/sync-image-loader.h" +#include "dali/public-api/rendering/sampler.h" namespace Dali { @@ -34,7 +33,6 @@ namespace SceneLoader { namespace { - const char* const RESOURCE_TYPE_NAMES[] = { "Environment", "Shader", @@ -42,7 +40,7 @@ const char* const RESOURCE_TYPE_NAMES[] = { "Material", }; -} // nonamespace +} // namespace const char* GetResourceTypeName(ResourceType::Value type) { @@ -64,9 +62,9 @@ void ResourceBundle::CountEnvironmentReferences(ResourceRefCounts& refCounts) co auto& environmentRefCounts = refCounts[ResourceType::Environment]; const auto& materialRefs = refCounts[ResourceType::Material]; - for (uint32_t i = 0, iEnd = materialRefs.Size(); i != iEnd; ++i) + for(uint32_t i = 0, iEnd = materialRefs.Size(); i != iEnd; ++i) { - if (materialRefs[i] > 0) + if(materialRefs[i] > 0) { ++environmentRefCounts[mMaterials[i].first.mEnvironmentIdx]; } @@ -75,36 +73,36 @@ void ResourceBundle::CountEnvironmentReferences(ResourceRefCounts& refCounts) co void ResourceBundle::LoadResources(const ResourceRefCounts& refCounts, PathProvider pathProvider, Options::Type options) { - const auto kForceLoad = MaskMatch(options, Options::ForceReload); + const auto kForceLoad = MaskMatch(options, Options::ForceReload); const auto kKeepUnused = MaskMatch(options, Options::KeepUnused); - const auto& refCountEnvMaps = refCounts[ResourceType::Environment]; - auto environmentsPath = pathProvider(ResourceType::Environment); - for (uint32_t i = 0, iEnd = refCountEnvMaps.Size(); i != iEnd; ++i) + const auto& refCountEnvMaps = refCounts[ResourceType::Environment]; + auto environmentsPath = pathProvider(ResourceType::Environment); + for(uint32_t i = 0, iEnd = refCountEnvMaps.Size(); i != iEnd; ++i) { - auto refCount = refCountEnvMaps[i]; - auto& iEnvMap = mEnvironmentMaps[i]; - if (refCount > 0 && (kForceLoad || !iEnvMap.second.IsLoaded())) + auto refCount = refCountEnvMaps[i]; + auto& iEnvMap = mEnvironmentMaps[i]; + if(refCount > 0 && (kForceLoad || !iEnvMap.second.IsLoaded())) { - auto raw = iEnvMap.first.LoadRaw(environmentsPath); + auto raw = iEnvMap.first.LoadRaw(environmentsPath); iEnvMap.second = iEnvMap.first.Load(std::move(raw)); } - else if (!kKeepUnused && refCount == 0 && iEnvMap.second.IsLoaded()) + else if(!kKeepUnused && refCount == 0 && iEnvMap.second.IsLoaded()) { - iEnvMap.second.mDiffuse = Texture(); + iEnvMap.second.mDiffuse = Texture(); iEnvMap.second.mSpecular = Texture(); } } const auto& refCountShaders = refCounts[ResourceType::Shader]; - auto shadersPath = pathProvider(ResourceType::Shader); - for (uint32_t i = 0, iEnd = refCountShaders.Size(); i != iEnd; ++i) + auto shadersPath = pathProvider(ResourceType::Shader); + for(uint32_t i = 0, iEnd = refCountShaders.Size(); i != iEnd; ++i) { - auto refCount = refCountShaders[i]; - auto& iShader = mShaders[i]; - if (refCount > 0 && (kForceLoad || !iShader.second)) + auto refCount = refCountShaders[i]; + auto& iShader = mShaders[i]; + if(refCount > 0 && (kForceLoad || !iShader.second)) { - auto raw = iShader.first.LoadRaw(shadersPath); + auto raw = iShader.first.LoadRaw(shadersPath); iShader.second = iShader.first.Load(std::move(raw)); } else if(!kKeepUnused && refCount == 0 && iShader.second) @@ -114,39 +112,39 @@ void ResourceBundle::LoadResources(const ResourceRefCounts& refCounts, PathProvi } const auto& refCountMeshes = refCounts[ResourceType::Mesh]; - auto modelsPath = pathProvider(ResourceType::Mesh); - for (uint32_t i = 0, iEnd = refCountMeshes.Size(); i != iEnd; ++i) + auto modelsPath = pathProvider(ResourceType::Mesh); + for(uint32_t i = 0, iEnd = refCountMeshes.Size(); i != iEnd; ++i) { - auto refCount = refCountMeshes[i]; - auto& iMesh = mMeshes[i]; - if (refCount > 0 && (kForceLoad || !iMesh.second.geometry)) + auto refCount = refCountMeshes[i]; + auto& iMesh = mMeshes[i]; + if(refCount > 0 && (kForceLoad || !iMesh.second.geometry)) { - auto raw = iMesh.first.LoadRaw(modelsPath); + auto raw = iMesh.first.LoadRaw(modelsPath); iMesh.second = iMesh.first.Load(std::move(raw)); } - else if (!kKeepUnused && refCount == 0 && iMesh.second.geometry) + else if(!kKeepUnused && refCount == 0 && iMesh.second.geometry) { iMesh.second.geometry = Geometry(); } } const auto& refCountMaterials = refCounts[ResourceType::Material]; - auto imagesPath = pathProvider(ResourceType::Material); - for (uint32_t i = 0, iEnd = refCountMaterials.Size(); i != iEnd; ++i) + auto imagesPath = pathProvider(ResourceType::Material); + for(uint32_t i = 0, iEnd = refCountMaterials.Size(); i != iEnd; ++i) { - auto refCount = refCountMaterials[i]; + auto refCount = refCountMaterials[i]; auto& iMaterial = mMaterials[i]; - if (refCount > 0 && (kForceLoad || !iMaterial.second)) + if(refCount > 0 && (kForceLoad || !iMaterial.second)) { - auto raw = iMaterial.first.LoadRaw(imagesPath); + auto raw = iMaterial.first.LoadRaw(imagesPath); iMaterial.second = iMaterial.first.Load(mEnvironmentMaps, std::move(raw)); } - else if (!kKeepUnused && refCount == 0 && iMaterial.second) + else if(!kKeepUnused && refCount == 0 && iMaterial.second) { iMaterial.second = TextureSet(); } } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/scene-definition.cpp b/dali-scene-loader/public-api/scene-definition.cpp index 54aa0c9..9da16fc 100644 --- a/dali-scene-loader/public-api/scene-definition.cpp +++ b/dali-scene-loader/public-api/scene-definition.cpp @@ -16,15 +16,15 @@ */ // EXTERNAL -#include "dali/public-api/animation/constraints.h" #include "dali/devel-api/common/map-wrapper.h" +#include "dali/public-api/animation/constraints.h" // INTERNAL -#include "dali-scene-loader/public-api/scene-definition.h" +#include "dali-scene-loader/internal/graphics/builtin-shader-extern-gen.h" #include "dali-scene-loader/public-api/blend-shape-details.h" -#include "dali-scene-loader/public-api/utils.h" +#include "dali-scene-loader/public-api/scene-definition.h" #include "dali-scene-loader/public-api/skinning-details.h" -#include "dali-scene-loader/internal/graphics/builtin-shader-extern-gen.h" +#include "dali-scene-loader/public-api/utils.h" //#define DEBUG_SCENE_DEFINITION //#define DEBUG_JOINTS @@ -35,7 +35,7 @@ #define DEBUG_ONLY(x) #endif -#define LOGD(x) DEBUG_ONLY(printf x ; printf("\n"); fflush(stdout)) +#define LOGD(x) DEBUG_ONLY(printf x; printf("\n"); fflush(stdout)) namespace Dali { @@ -43,104 +43,84 @@ namespace SceneLoader { namespace { - -const std::string JOINT_MATRIX{ "jointMatrix" }; - -const std::map sConstraintFactory = { - { - Property::Type::BOOLEAN, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, [](bool& current, const PropertyInputContainer& inputs) { - current = inputs[0]->GetBoolean(); - }); - } - }, - { - Property::Type::INTEGER, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, [](int& current, const PropertyInputContainer& inputs) { - current = inputs[0]->GetInteger(); - }); - } - }, - { - Property::Type::FLOAT, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::VECTOR2, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::VECTOR3, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::VECTOR4, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::MATRIX, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::MATRIX3, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, - { - Property::Type::ROTATION, - [](Actor& a, Property::Index i) { - return Constraint::New(a, i, EqualToConstraint()); - } - }, +const std::string JOINT_MATRIX{"jointMatrix"}; + +const std::map sConstraintFactory = { + {Property::Type::BOOLEAN, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, [](bool& current, const PropertyInputContainer& inputs) { + current = inputs[0]->GetBoolean(); + }); + }}, + {Property::Type::INTEGER, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, [](int& current, const PropertyInputContainer& inputs) { + current = inputs[0]->GetInteger(); + }); + }}, + {Property::Type::FLOAT, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::VECTOR2, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::VECTOR3, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::VECTOR4, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::MATRIX, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::MATRIX3, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, + {Property::Type::ROTATION, + [](Actor& a, Property::Index i) { + return Constraint::New(a, i, EqualToConstraint()); + }}, }; struct ResourceReflector : IResourceReflector { - Index* iMesh = nullptr; + Index* iMesh = nullptr; Index* iShader = nullptr; void Reflect(ResourceType::Value type, Index& id) { - switch (type) + switch(type) { - case ResourceType::Shader: - DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!"); - iShader = &id; - break; + case ResourceType::Shader: + DALI_ASSERT_ALWAYS(!iShader && "Shader index already assigned!"); + iShader = &id; + break; - case ResourceType::Mesh: - DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!"); - iMesh = &id; - break; + case ResourceType::Mesh: + DALI_ASSERT_ALWAYS(!iMesh && "Mesh index already assigned!"); + iMesh = &id; + break; - default: // Other resource types are not relevant to the problem at hand. - break; + default: // Other resource types are not relevant to the problem at hand. + break; } } }; - #ifdef DEBUG_JOINTS Shader sJointDebugShader; -int sNumScenes = 0; +int sNumScenes = 0; void EnsureJointDebugShaderCreated() { - if (0 == sNumScenes) + if(0 == sNumScenes) { sJointDebugShader = Shader::New(SHADER_SCENE_LOADER_JOINT_DEBUG_VERT, SHADER_SCENE_LOADER_JOINT_DEBUG_FRAG); } @@ -151,24 +131,24 @@ void AddJointDebugVisual(Actor aJoint) { Property::Map attribs; attribs["aPosition"] = Property::Type::VECTOR3; - attribs["aColor"] = Property::Type::FLOAT; + attribs["aColor"] = Property::Type::FLOAT; PropertyBuffer vbo = PropertyBuffer::New(attribs); struct Vertex { Vector3 pos; - float color; + float color; } vertices[] = { - { Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f }, - { Vector3::XAXIS, .999f }, - { Vector3::YAXIS, .999f * 256.f }, - { Vector3::ZAXIS, .999f * 256.f * 256.f }, + {Vector3::ZERO, .999f + .999f * 256.f + .999f * 256.f * 256.f}, + {Vector3::XAXIS, .999f}, + {Vector3::YAXIS, .999f * 256.f}, + {Vector3::ZAXIS, .999f * 256.f * 256.f}, }; vbo.SetData(&vertices, std::extent::value); - uint16_t indices[] = { 0, 1, 0, 2, 0, 3 }; + uint16_t indices[] = {0, 1, 0, 2, 0, 3}; Geometry geo = Geometry::New(); geo.AddVertexBuffer(vbo); @@ -180,21 +160,22 @@ void AddJointDebugVisual(Actor aJoint) aJoint.SetVisible(true); } -#endif //DEBUG_JOINTS +#endif //DEBUG_JOINTS class ActorCreatorVisitor : public NodeDefinition::IConstVisitor { public: ActorCreatorVisitor(NodeDefinition::CreateParams& params) : mCreationContext(params) - {} + { + } void Start(const NodeDefinition& n) { mCreationContext.mXforms.modelStack.Push(n.GetLocalSpace()); Actor a = n.CreateActor(mCreationContext); - if (!mActorStack.empty()) + if(!mActorStack.empty()) { mActorStack.back().Add(a); } @@ -218,16 +199,16 @@ public: private: NodeDefinition::CreateParams& mCreationContext; - std::vector mActorStack; - Actor mRoot; + std::vector mActorStack; + Actor mRoot; }; bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index rootHint = INVALID_INDEX) { bool isAncestor = false; - while (node != rootHint && !isAncestor) + while(node != rootHint && !isAncestor) { - node = scene.GetNode(node)->mParentIdx; + node = scene.GetNode(node)->mParentIdx; isAncestor = ancestor == node; } return isAncestor; @@ -236,7 +217,7 @@ bool IsAncestor(const SceneDefinition& scene, Index ancestor, Index node, Index void InsertUniqueSorted(std::vector& data, Index value) { auto iInsert = std::lower_bound(data.begin(), data.end(), value); - if (iInsert == data.end() || *iInsert != value) + if(iInsert == data.end() || *iInsert != value) { data.insert(iInsert, value); } @@ -245,7 +226,7 @@ void InsertUniqueSorted(std::vector& data, Index value) void RemoveFromSorted(std::vector& data, Index value) { auto iRemove = std::lower_bound(data.begin(), data.end(), value); - if (iRemove != data.end() && *iRemove == value) + if(iRemove != data.end() && *iRemove == value) { data.erase(iRemove); } @@ -254,26 +235,24 @@ void RemoveFromSorted(std::vector& data, Index value) Property::Index ConfigureJointMatrix(Actor actor, Actor ancestor, Property::Index propJointMatrix) { Actor parent = actor.GetParent(); - if (parent != ancestor) + if(parent != ancestor) { propJointMatrix = ConfigureJointMatrix(parent, ancestor, propJointMatrix); } auto myPropJointMatrix = actor.GetPropertyIndex(JOINT_MATRIX); - if (myPropJointMatrix == Property::INVALID_INDEX) + if(myPropJointMatrix == Property::INVALID_INDEX) { - myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{ false }); - Constraint constraint = Constraint::New(actor, propJointMatrix, - [](Matrix& output, const PropertyInputContainer& inputs) - { - Matrix jointMatrix{ false }; - jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); - - Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix()); - }); - constraint.AddSource(Source{ actor, Actor::Property::ORIENTATION }); - constraint.AddSource(Source{ actor, Actor::Property::POSITION }); - constraint.AddSource(Source{ parent, propJointMatrix }); + myPropJointMatrix = actor.RegisterProperty(JOINT_MATRIX, Matrix{false}); + Constraint constraint = Constraint::New(actor, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) { + Matrix jointMatrix{false}; + jointMatrix.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); + + Matrix::Multiply(output, jointMatrix, inputs[2]->GetMatrix()); + }); + constraint.AddSource(Source{actor, Actor::Property::ORIENTATION}); + constraint.AddSource(Source{actor, Actor::Property::POSITION}); + constraint.AddSource(Source{parent, propJointMatrix}); constraint.Apply(); } @@ -286,38 +265,38 @@ void SortAndDeduplicateSkinningRequests(std::vectormShader; - Index skeletonIdx = i->mSkeletonIdx; + auto i = requests.begin(); + auto iEnd = requests.end(); + Shader s = i->mShader; + Index skeletonIdx = i->mSkeletonIdx; ++i; do { // Multiple identical shader instances are removed. - while (i != iEnd && i->mShader == s) + while(i != iEnd && i->mShader == s) { // Cannot have multiple skeletons input to the same shader. // NOTE: DliModel now makes sure this doesn't happen. DALI_ASSERT_ALWAYS(i->mSkeletonIdx == skeletonIdx && - "Skinning shader must not be shared between different skeletons."); + "Skinning shader must not be shared between different skeletons."); i->mShader = Shader(); ++i; } - if (i == iEnd) + if(i == iEnd) { break; } - s = i->mShader; + s = i->mShader; skeletonIdx = i->mSkeletonIdx; ++i; - } while (true); + } while(true); - requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) - { - return !sscr.mShader; - }), requests.end()); + requests.erase(std::remove_if(requests.begin(), requests.end(), [](const SkinningShaderConfigurationRequest& sscr) { + return !sscr.mShader; + }), + requests.end()); } void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& boneIdx) @@ -326,40 +305,38 @@ void ConfigureBoneMatrix(const Matrix& ibm, Actor joint, Shader& shader, Index& char propertyNameBuffer[32]; snprintf(propertyNameBuffer, sizeof(propertyNameBuffer), "%s[%d]", Skinning::BONE_UNIFORM_NAME.c_str(), boneIdx); DALI_ASSERT_DEBUG(shader.GetPropertyIndex(propertyNameBuffer) == Property::INVALID_INDEX); - auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{ false }); + auto propBoneXform = shader.RegisterProperty(propertyNameBuffer, Matrix{false}); // Constrain bone matrix to joint transform. - Constraint constraint = Constraint::New(shader, propBoneXform, - [ibm](Matrix& output, const PropertyInputContainer& inputs) - { - Matrix::Multiply(output, ibm, inputs[0]->GetMatrix()); - }); + Constraint constraint = Constraint::New(shader, propBoneXform, [ibm](Matrix& output, const PropertyInputContainer& inputs) { + Matrix::Multiply(output, ibm, inputs[0]->GetMatrix()); + }); auto propJointMatrix = joint.GetPropertyIndex(JOINT_MATRIX); - constraint.AddSource(Source{ joint, propJointMatrix }); + constraint.AddSource(Source{joint, propJointMatrix}); constraint.Apply(); ++boneIdx; } -template +template void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v, SceneDefinition& sd) { auto& node = *sd.GetNode(iNode); v.Start(node); - if (node.mCustomization) + if(node.mCustomization) { - if (!node.mChildren.empty()) + if(!node.mChildren.empty()) { - auto choice = choices.Get(node.mCustomization->mTag); - Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast(node.mChildren.size() - 1)); + auto choice = choices.Get(node.mCustomization->mTag); + Index i = std::min(choice != Customization::NONE ? choice : 0, static_cast(node.mChildren.size() - 1)); sd.Visit(node.mChildren[i], choices, v); } } else { - for (auto i : node.mChildren) + for(auto i : node.mChildren) { sd.Visit(i, choices, v); } @@ -368,7 +345,7 @@ void VisitInternal(Index iNode, const Customization::Choices& choices, Visitor& v.Finish(node); } -} // nonamespace +} // namespace SceneDefinition::SceneDefinition() { @@ -392,7 +369,7 @@ SceneDefinition::~SceneDefinition() { #ifdef DEBUG_JOINTS --sNumScenes; - if (sNumScenes == 0) + if(sNumScenes == 0) { sJointDebugShader = Shader(); } @@ -401,7 +378,7 @@ SceneDefinition::~SceneDefinition() uint32_t SceneLoader::SceneDefinition::AddRootNode(Index iNode) { - if (iNode < mNodes.size()) + if(iNode < mNodes.size()) { uint32_t result = mRootNodeIds.size(); mRootNodeIds.push_back(iNode); @@ -421,7 +398,7 @@ const std::vector& SceneDefinition::GetRoots() const void SceneDefinition::RemoveRootNode(Index iRoot) { - if (iRoot < mRootNodeIds.size()) + if(iRoot < mRootNodeIds.size()) { mRootNodeIds.erase(mRootNodeIds.begin() + iRoot); } @@ -474,14 +451,15 @@ void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choice void Start(const NodeDefinition& n) { - if (n.mRenderable) + if(n.mRenderable) { n.mRenderable->RegisterResources(counter); } } void Finish(const NodeDefinition& n) - {} + { + } } refCounterVisitor; refCounterVisitor.counter.refCounts = &refCounts; @@ -489,8 +467,7 @@ void SceneDefinition::CountResourceRefs(Index iNode, const Customization::Choice Visit(iNode, choices, refCounterVisitor); } -Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices & choices, - NodeDefinition::CreateParams& params) const +Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices& choices, NodeDefinition::CreateParams& params) const { ActorCreatorVisitor actorCreatorVisitor(params); @@ -500,44 +477,46 @@ Actor SceneDefinition::CreateNodes(Index iNode, const Customization::Choices & c } void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choices, - Customization::Map& outCustomizationOptions, Customization::Choices* outMissingChoices) const + Customization::Map& outCustomizationOptions, + Customization::Choices* outMissingChoices) const { struct : NodeDefinition::IConstVisitor { - const Customization::Choices* choices; // choices that we know about. - Customization::Map* options; // tags are registered here. NO OWNERSHIP. - Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP. + const Customization::Choices* choices; // choices that we know about. + Customization::Map* options; // tags are registered here. NO OWNERSHIP. + Customization::Choices* missingChoices; // tags will be registered with the default 0. NO OWNERSHIP. void Start(const NodeDefinition& n) { - if (n.mCustomization) + if(n.mCustomization) { const std::string& tag = n.mCustomization->mTag; - if (missingChoices != nullptr && choices->Get(tag) == Customization::NONE) + if(missingChoices != nullptr && choices->Get(tag) == Customization::NONE) { missingChoices->Set(tag, 0); } auto customization = options->Get(tag); - if (!customization) + if(!customization) { customization = options->Set(tag, {}); } customization->nodes.push_back(n.mName); customization->numOptions = std::max(customization->numOptions, - static_cast(n.mChildren.size())); + static_cast(n.mChildren.size())); } } void Finish(const NodeDefinition& n) - {} + { + } } customizationRegistrationVisitor; - customizationRegistrationVisitor.choices = &choices; - customizationRegistrationVisitor.options = &outCustomizationOptions; + customizationRegistrationVisitor.choices = &choices; + customizationRegistrationVisitor.options = &outCustomizationOptions; customizationRegistrationVisitor.missingChoices = outMissingChoices; - for (auto i : mRootNodeIds) + for(auto i : mRootNodeIds) { Visit(i, choices, customizationRegistrationVisitor); } @@ -545,13 +524,13 @@ void SceneDefinition::GetCustomizationOptions(const Customization::Choices& choi NodeDefinition* SceneDefinition::AddNode(std::unique_ptr&& nodeDef) { - if (FindNode(nodeDef->mName)) + if(FindNode(nodeDef->mName)) { return nullptr; } // add next index (to which we're about to push) as a child to the designated parent, if any. - if (nodeDef->mParentIdx != INVALID_INDEX) + if(nodeDef->mParentIdx != INVALID_INDEX) { mNodes[nodeDef->mParentIdx]->mChildren.push_back(mNodes.size()); } @@ -565,20 +544,20 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n { LOGD(("reparenting %s to %s @ %d", name.c_str(), newParentName.c_str(), siblingOrder)); - std::unique_ptr* nodePtr = nullptr; + std::unique_ptr* nodePtr = nullptr; std::unique_ptr* newParentPtr = nullptr; - if (!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr)) + if(!FindNode(name, &nodePtr) || !FindNode(newParentName, &newParentPtr)) { return false; } - auto& node = *nodePtr; - auto iNode = std::distance(mNodes.data(), nodePtr); + auto& node = *nodePtr; + auto iNode = std::distance(mNodes.data(), nodePtr); DEBUG_ONLY(auto dumpNode = [](NodeDefinition const& n) { std::ostringstream stream; stream << n.mName << " (" << n.mParentIdx << "):"; - for (auto i : n.mChildren) + for(auto i : n.mChildren) { stream << i << ", "; } @@ -586,7 +565,7 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n };) // Remove node from children of previous parent (if any). - if (node->mParentIdx != INVALID_INDEX) + if(node->mParentIdx != INVALID_INDEX) { LOGD(("old parent:")); DEBUG_ONLY(dumpNode(*mNodes[node->mParentIdx]);) @@ -601,7 +580,7 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n LOGD(("new parent:")); DEBUG_ONLY(dumpNode(**newParentPtr);) auto& children = (*newParentPtr)->mChildren; - if (siblingOrder > children.size()) + if(siblingOrder > children.size()) { siblingOrder = children.size(); } @@ -611,7 +590,7 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n // Update parent index. LOGD(("node:")); DEBUG_ONLY(dumpNode(*node);) - auto iParent = std::distance(mNodes.data(), newParentPtr); + auto iParent = std::distance(mNodes.data(), newParentPtr); node->mParentIdx = iParent; DEBUG_ONLY(dumpNode(*node);) return true; @@ -620,33 +599,33 @@ bool SceneDefinition::ReparentNode(const std::string& name, const std::string& n bool SceneDefinition::RemoveNode(const std::string& name) { std::unique_ptr* node = nullptr; - if (!FindNode(name, &node)) + if(!FindNode(name, &node)) { return false; } // Reset node def pointers recursively. - auto& thisNodes = mNodes; - unsigned int numReset = 0; + auto& thisNodes = mNodes; + unsigned int numReset = 0; std::function&)> resetFn = [&thisNodes, &resetFn, &numReset](std::unique_ptr& nd) { - LOGD(("resetting %d", &nd - thisNodes.data())); - for (auto i : nd->mChildren) - { - resetFn(thisNodes[i]); - } - nd.reset(); - ++numReset; - }; + LOGD(("resetting %d", &nd - thisNodes.data())); + for(auto i : nd->mChildren) + { + resetFn(thisNodes[i]); + } + nd.reset(); + ++numReset; + }; resetFn(*node); // Gather indices of dead nodes into a vector which we sort on insertion. std::vector offsets; offsets.reserve(numReset); - for (auto& n : mNodes) + for(auto& n : mNodes) { - if (!n) + if(!n) { offsets.push_back(std::distance(mNodes.data(), &n)); } @@ -656,10 +635,13 @@ bool SceneDefinition::RemoveNode(const std::string& name) mNodes.erase(std::remove(mNodes.begin(), mNodes.end(), decltype(mNodes)::value_type()), mNodes.end()); // Offset all indices (parent and child) by the index they'd sort into in offsets. - enum { INDEX_FOR_REMOVAL = INVALID_INDEX }; + enum + { + INDEX_FOR_REMOVAL = INVALID_INDEX + }; auto offsetter = [&offsets](Index& i) { auto iFind = std::lower_bound(offsets.begin(), offsets.end(), i); - if (iFind != offsets.end() && *iFind == i) + if(iFind != offsets.end() && *iFind == i) { LOGD(("marking %d for removal.", i)); i = INDEX_FOR_REMOVAL; @@ -668,7 +650,7 @@ bool SceneDefinition::RemoveNode(const std::string& name) else { auto distance = std::distance(offsets.begin(), iFind); - if (distance > 0) + if(distance > 0) { LOGD(("offsetting %d by %d.", i, distance)); i -= distance; @@ -677,13 +659,13 @@ bool SceneDefinition::RemoveNode(const std::string& name) } }; - for (auto& nd : mNodes) + for(auto& nd : mNodes) { bool parentOffsetResult = offsetter(nd->mParentIdx); - DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point. + DALI_ASSERT_ALWAYS(parentOffsetResult); // since nodes were recursively removed, we should not be finding invalid parents at this point. auto& children = nd->mChildren; - for (auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0) + for(auto i0 = children.begin(), i1 = children.end(); i0 != i1; ++i0) { offsetter(*i0); } @@ -696,10 +678,10 @@ bool SceneDefinition::RemoveNode(const std::string& name) void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const { - auto& thisNodes = mNodes; + auto& thisNodes = mNodes; std::function buildStack = [&model, &thisNodes, &buildStack](int i) { auto node = thisNodes[i].get(); - if (node->mParentIdx != INVALID_INDEX) + if(node->mParentIdx != INVALID_INDEX) { buildStack(node->mParentIdx); } @@ -708,32 +690,32 @@ void SceneDefinition::GetNodeModelStack(Index index, MatrixStack& model) const buildStack(index); } -NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* outIndex) +NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) { auto iBegin = mNodes.begin(); - auto iEnd = mNodes.end(); - auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { + auto iEnd = mNodes.end(); + auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { return nd->mName == name; }); auto result = iFind != iEnd ? iFind->get() : nullptr; - if (result && outIndex) + if(result && outIndex) { *outIndex = std::distance(iBegin, iFind); } return result; } -const NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* outIndex) const +const NodeDefinition* SceneDefinition::FindNode(const std::string& name, Index* outIndex) const { auto iBegin = mNodes.begin(); - auto iEnd = mNodes.end(); - auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { + auto iEnd = mNodes.end(); + auto iFind = std::find_if(iBegin, iEnd, [&name](const std::unique_ptr& nd) { return nd->mName == name; }); auto result = iFind != iEnd ? iFind->get() : nullptr; - if (result && outIndex) + if(result && outIndex) { *outIndex = std::distance(iBegin, iFind); } @@ -743,24 +725,23 @@ const NodeDefinition* SceneDefinition::FindNode(const std::string &name, Index* Index SceneDefinition::FindNodeIndex(const NodeDefinition& node) const { auto iBegin = mNodes.begin(); - auto iEnd = mNodes.end(); - auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr& n) { + auto iEnd = mNodes.end(); + auto iFind = std::find_if(iBegin, iEnd, [&node](const std::unique_ptr& n) { return n.get() == &node; }); return iFind != iEnd ? std::distance(iBegin, iFind) : INVALID_INDEX; } -void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, - unsigned int limit) +void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, unsigned int limit) { unsigned int n = 0; - for (auto& defp : mNodes) + for(auto& defp : mNodes) { - if (predicate(*defp)) + if(predicate(*defp)) { consumer(*defp); ++n; - if (n == limit) + if(n == limit) { break; } @@ -768,17 +749,16 @@ void SceneDefinition::FindNodes(NodePredicate predicate, NodeConsumer consumer, } } -void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, - unsigned int limit) const +void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consumer, unsigned int limit) const { unsigned int n = 0; - for (auto& defp : mNodes) + for(auto& defp : mNodes) { - if (predicate(*defp)) + if(predicate(*defp)) { consumer(*defp); ++n; - if (n == limit) + if(n == limit) { break; } @@ -786,51 +766,59 @@ void SceneDefinition::FindNodes(NodePredicate predicate, ConstNodeConsumer consu } } -void SceneDefinition::ApplyConstraints(Actor& root, - std::vector&& constrainables, StringCallback onError) const +void SceneDefinition::ApplyConstraints(Actor& root, + std::vector&& constrainables, + StringCallback onError) const { - for (auto& cr : constrainables) + for(auto& cr : constrainables) { - auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx]; - auto sourceName = nodeDef->mName.c_str(); - Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty); - if (iTarget != Property::INVALID_INDEX) + auto& nodeDef = mNodes[cr.mConstraint->mSourceIdx]; + auto sourceName = nodeDef->mName.c_str(); + Property::Index iTarget = cr.mTarget.GetPropertyIndex(cr.mConstraint->mProperty); + if(iTarget != Property::INVALID_INDEX) { auto propertyType = cr.mTarget.GetPropertyType(iTarget); - auto iFind = sConstraintFactory.find(propertyType); - if (iFind == sConstraintFactory.end()) + auto iFind = sConstraintFactory.find(propertyType); + if(iFind == sConstraintFactory.end()) { onError(FormatString("node '%s': Property '%s' has unsupported type '%s'; ignored.", - sourceName, cr.mConstraint->mProperty.c_str(), PropertyTypes::GetName(propertyType))); + sourceName, + cr.mConstraint->mProperty.c_str(), + PropertyTypes::GetName(propertyType))); continue; } Constraint constraint = iFind->second(cr.mTarget, iTarget); Actor source = root.FindChildByName(nodeDef->mName); - if (!source) + if(!source) { auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get(); onError(FormatString("node '%s': Failed to locate constraint source %s@%s; ignored.", - sourceName, cr.mConstraint->mProperty.c_str(), targetName.c_str())); + sourceName, + cr.mConstraint->mProperty.c_str(), + targetName.c_str())); continue; } - else if (source == cr.mTarget) + else if(source == cr.mTarget) { onError(FormatString("node '%s': Cyclic constraint definition for property '%s'; ignored.", - sourceName, cr.mConstraint->mProperty.c_str())); + sourceName, + cr.mConstraint->mProperty.c_str())); continue; } Property::Index iSource = source.GetPropertyIndex(cr.mConstraint->mProperty); - constraint.AddSource(Source{ source, iSource }); + constraint.AddSource(Source{source, iSource}); constraint.Apply(); } else { auto targetName = cr.mTarget.GetProperty(Actor::Property::NAME).Get(); onError(FormatString("node '%s': Failed to create constraint for property %s@%s; ignored.", - sourceName, cr.mConstraint->mProperty.c_str(), targetName.c_str())); + sourceName, + cr.mConstraint->mProperty.c_str(), + targetName.c_str())); } } } @@ -841,29 +829,28 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi // to the refcount of each node we have visited, in our temporary registry. Those with refcount 1 // are the leaves, while the most descendant node with the highest refcount is the root of the skeleton. std::map> rootsJoints; - std::vector path; + std::vector path; path.reserve(16); - for (auto& s : skeletons) + for(auto& s : skeletons) { - std::map jointRefs; - for (auto& j : s.mJoints) + std::map jointRefs; + for(auto& j : s.mJoints) { auto nodeIdx = j.mNodeIdx; do // Traverse upwards and record each node we have visited until we reach the scene root. { path.push_back(nodeIdx); - if (nodeIdx == iRoot) + if(nodeIdx == iRoot) { break; } auto node = GetNode(nodeIdx); - nodeIdx = node->mParentIdx; - } - while (nodeIdx != INVALID_INDEX); + nodeIdx = node->mParentIdx; + } while(nodeIdx != INVALID_INDEX); - if (nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes. + if(nodeIdx == iRoot) // If the joint is in the correct scene, increment the reference count for all visited nodes. { - for (auto i : path) + for(auto i : path) { ++jointRefs[i]; } @@ -873,31 +860,31 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi } // Only record the skeleton if we have encountered the root of the current scene. - if (jointRefs.empty()) + if(jointRefs.empty()) { continue; } - Index root = s.mRootNodeIdx; + Index root = s.mRootNodeIdx; uint32_t maxRef = 0; - auto iFind = jointRefs.find(root); - if (iFind != jointRefs.end()) + auto iFind = jointRefs.find(root); + if(iFind != jointRefs.end()) { maxRef = iFind->second; } std::vector joints; - for (auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be. + for(auto& j : jointRefs) // NOTE: jointRefs are sorted, so joints will also be. { // The most descendant node with the highest ref count is the root of the skeleton. - if (j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot))) + if(j.second > maxRef || (j.second == maxRef && IsAncestor(*this, root, j.first, iRoot))) { maxRef = j.second; RemoveFromSorted(joints, root); root = j.first; } - else if (j.second == 1) // This one's a leaf. + else if(j.second == 1) // This one's a leaf. { InsertUniqueSorted(joints, j.first); } @@ -905,20 +892,20 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi // Merge skeletons that share the same root. auto& finalJoints = rootsJoints[root]; - for (auto j : joints) + for(auto j : joints) { - if (std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) { - return IsAncestor(*this, j, jj, root); - }) != finalJoints.end()) + if(std::find_if(finalJoints.begin(), finalJoints.end(), [this, j, root](Index jj) { + return IsAncestor(*this, j, jj, root); + }) != finalJoints.end()) { - continue; // if the joint is found to be an ancestor of another joint already registered, move on. + continue; // if the joint is found to be an ancestor of another joint already registered, move on. } auto i = j; - while (i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove. + while(i != root) // See if the current joint is a better leaf, i.e. descended from another leaf - which we'll then remove. { auto node = GetNode(i); - i = node->mParentIdx; + i = node->mParentIdx; RemoveFromSorted(finalJoints, i); } @@ -929,42 +916,43 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi // 2, Merge records where one root joint is descendant of another. Handle leaf node changes - remove previous // leaf nodes that now have descendants, and add new ones. - auto iRoots = rootsJoints.begin(); + auto iRoots = rootsJoints.begin(); auto iRootsEnd = rootsJoints.end(); - while (iRoots != iRootsEnd) + while(iRoots != iRootsEnd) { - auto i = iRoots->first; + auto i = iRoots->first; bool merged = false; - while (i != iRoot) // Starting with the root joint of the skeleton, traverse upwards. + while(i != iRoot) // Starting with the root joint of the skeleton, traverse upwards. { auto node = GetNode(i); - i = node->mParentIdx; + i = node->mParentIdx; auto iFind = rootsJoints.find(i); - if (iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton. + if(iFind != rootsJoints.end()) // Check if we've reached the root of another skeleton. { // Now find out which leaf of iFind is an ancestor, if any. auto iFindLeaf = std::find_if(iFind->second.begin(), iFind->second.end(), [this, iRoots, iFind](Index j) { return IsAncestor(*this, j, iRoots->first, iFind->first); }); - if (iFindLeaf != iFind->second.end()) + if(iFindLeaf != iFind->second.end()) { - iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it. + iFind->second.erase(iFindLeaf); // Will no longer be a leaf -- remove it. } // Merge iRoots with iFind auto& targetJoints = iFind->second; - if (iRoots->second.empty()) // The root is a leaf. + if(iRoots->second.empty()) // The root is a leaf. { InsertUniqueSorted(targetJoints, iRoots->first); } - else for (auto j : iRoots->second) - { - InsertUniqueSorted(targetJoints, j); - } + else + for(auto j : iRoots->second) + { + InsertUniqueSorted(targetJoints, j); + } merged = true; - break; // Traverse no more + break; // Traverse no more } } @@ -972,26 +960,24 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi } // 3, For each root, register joint matrices and constraints - for (auto r : rootsJoints) + for(auto r : rootsJoints) { - auto node = GetNode(r.first); + auto node = GetNode(r.first); auto rootJoint = root.FindChildByName(node->mName); DALI_ASSERT_ALWAYS(!!rootJoint); DALI_ASSERT_DEBUG(rootJoint.GetPropertyIndex(JOINT_MATRIX) == Property::INVALID_INDEX); - auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{ false }); - Constraint constraint = Constraint::New(rootJoint, propJointMatrix, - [](Matrix& output, const PropertyInputContainer& inputs) - { - output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); - }); + auto propJointMatrix = rootJoint.RegisterProperty(JOINT_MATRIX, Matrix{false}); + Constraint constraint = Constraint::New(rootJoint, propJointMatrix, [](Matrix& output, const PropertyInputContainer& inputs) { + output.SetTransformComponents(Vector3::ONE, inputs[0]->GetQuaternion(), inputs[1]->GetVector3()); + }); constraint.AddSource(Source(rootJoint, Actor::Property::ORIENTATION)); constraint.AddSource(Source(rootJoint, Actor::Property::POSITION)); constraint.Apply(); - for (auto j : r.second) + for(auto j : r.second) { - node = GetNode(j); + node = GetNode(j); auto joint = rootJoint.FindChildByName(node->mName); ConfigureJointMatrix(joint, rootJoint, propJointMatrix); } @@ -1001,17 +987,17 @@ void SceneDefinition::ConfigureSkeletonJoints(uint32_t iRoot, const SkeletonDefi void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resources) const { std::map>> skinningShaderUsers; - for (auto& node : mNodes) + for(auto& node : mNodes) { - if (node->mRenderable) + if(node->mRenderable) { ResourceReflector reflector; node->mRenderable->ReflectResources(reflector); - if (reflector.iMesh) + if(reflector.iMesh) { const auto& mesh = resources.mMeshes[*reflector.iMesh].first; - if (mesh.IsSkinned()) + if(mesh.IsSkinned()) { skinningShaderUsers[*reflector.iShader][mesh.mSkeletonIdx].push_back(reflector.iShader); } @@ -1022,22 +1008,22 @@ void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resour // For each shader, and each skeleton using the same shader as the first skeleton, // update the shader references (from nodes with skinned meshes) with a new copy of // the shader definition from the node using the first skeleton. - for (auto& users : skinningShaderUsers) + for(auto& users : skinningShaderUsers) { - auto& skeletons = users.second; - auto iterSkeleton = skeletons.begin(); + auto& skeletons = users.second; + auto iterSkeleton = skeletons.begin(); // skipping the first skeleton. ++iterSkeleton; resources.mShaders.reserve(resources.mShaders.size() + std::distance(iterSkeleton, skeletons.end())); const ShaderDefinition& shaderDef = resources.mShaders[users.first].first; - while (iterSkeleton != skeletons.end()) + while(iterSkeleton != skeletons.end()) { Index iShader = resources.mShaders.size(); - resources.mShaders.push_back({ shaderDef, Shader() }); + resources.mShaders.push_back({shaderDef, Shader()}); - for (auto& i : iterSkeleton->second) + for(auto& i : iterSkeleton->second) { *i = iShader; } @@ -1046,40 +1032,42 @@ void SceneDefinition::EnsureUniqueSkinningShaderInstances(ResourceBundle& resour } } -void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources, - Actor rootActor, std::vector&& requests) const +void SceneDefinition::ConfigureSkinningShaders(const ResourceBundle& resources, + Actor rootActor, + std::vector&& requests) const { - if (requests.empty()) + if(requests.empty()) { return; } SortAndDeduplicateSkinningRequests(requests); - for (auto& i : requests) + for(auto& i : requests) { auto& skeleton = resources.mSkeletons[i.mSkeletonIdx]; - if (skeleton.mJoints.empty()) + if(skeleton.mJoints.empty()) { LOGD(("Skeleton %d has no joints.", i.mSkeletonIdx)); continue; } Index boneIdx = 0; - for (auto& j : skeleton.mJoints) + for(auto& j : skeleton.mJoints) { - auto node = GetNode(j.mNodeIdx); + auto node = GetNode(j.mNodeIdx); Actor actor = rootActor.FindChildByName(node->mName); ConfigureBoneMatrix(j.mInverseBindMatrix, actor, i.mShader, boneIdx); } } } -bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources, - Actor rootActor, std::vector&& requests, - StringCallback onError ) const +bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources, + Actor rootActor, + std::vector&& requests, + StringCallback onError) const { - if (requests.empty()) + if(requests.empty()) { return true; } @@ -1088,45 +1076,45 @@ bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources std::sort(requests.begin(), requests.end()); // Remove duplicates. - auto i = requests.begin(); - auto iEnd = requests.end(); - Shader s = i->mShader; + auto i = requests.begin(); + auto iEnd = requests.end(); + Shader s = i->mShader; ++i; do { // Multiple identical shader instances are removed. - while (i != iEnd && i->mShader == s) + while(i != iEnd && i->mShader == s) { i->mShader = Shader(); ++i; } - if (i == iEnd) + if(i == iEnd) { break; } s = i->mShader; ++i; - } while (true); + } while(true); - requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr) - { - return !bscr.mShader; - }), requests.end()); + requests.erase(std::remove_if(requests.begin(), requests.end(), [](const BlendshapeShaderConfigurationRequest& bscr) { + return !bscr.mShader; + }), + requests.end()); // Configure the rest. bool ok = true; - for (auto& i : requests) + for(auto& i : requests) { Index iNode; - if (FindNode(i.mNodeName, &iNode)) + if(FindNode(i.mNodeName, &iNode)) { const auto& node = GetNode(iNode); const auto& mesh = resources.mMeshes[i.mMeshIdx]; - if (mesh.first.HasBlendShapes()) + if(mesh.first.HasBlendShapes()) { Actor actor = rootActor.FindChildByName(node->mName); @@ -1142,17 +1130,17 @@ bool SceneDefinition::ConfigureBlendshapeShaders(const ResourceBundle& resources void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& resources) const { std::map>> blendShapeShaderUsers; - for (auto& node : mNodes) + for(auto& node : mNodes) { - if (node->mRenderable) + if(node->mRenderable) { ResourceReflector reflector; node->mRenderable->ReflectResources(reflector); - if (reflector.iMesh) + if(reflector.iMesh) { const auto& mesh = resources.mMeshes[*reflector.iMesh].first; - if (mesh.HasBlendShapes()) + if(mesh.HasBlendShapes()) { blendShapeShaderUsers[*reflector.iShader][node->mName].push_back(reflector.iShader); } @@ -1160,22 +1148,22 @@ void SceneDefinition::EnsureUniqueBlendShapeShaderInstances(ResourceBundle& reso } } - for (auto& users : blendShapeShaderUsers) + for(auto& users : blendShapeShaderUsers) { resources.mShaders.reserve(resources.mShaders.size() + users.second.size() - 1u); const ShaderDefinition& shaderDef = resources.mShaders[users.first].first; - auto nodesIt = users.second.begin(); + auto nodesIt = users.second.begin(); auto nodesEndIt = users.second.end(); // skipping the first node. ++nodesIt; while(nodesIt != nodesEndIt) { Index iShader = resources.mShaders.size(); - resources.mShaders.push_back({ shaderDef, Shader() }); + resources.mShaders.push_back({shaderDef, Shader()}); auto& nodes = *nodesIt; - for (auto& shader : nodes.second) + for(auto& shader : nodes.second) { *shader = iShader; } @@ -1197,13 +1185,12 @@ bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr& nd) { - return nd->mName == name; - }).base(); + auto iFind = std::find_if(mNodes.rbegin(), mNodes.rend(), [&name](const std::unique_ptr& nd) { + return nd->mName == name; + }).base(); const bool success = iFind != mNodes.begin(); - if (success && result) + if(success && result) { --iFind; *result = &*iFind; @@ -1212,5 +1199,5 @@ bool SceneDefinition::FindNode(const std::string& name, std::unique_ptr +#include "dali-scene-loader/internal/hash.h" #include "dali-scene-loader/public-api/blend-shape-details.h" +#include "dali-scene-loader/public-api/node-definition.h" #include "dali/devel-api/common/map-wrapper.h" -#include namespace Dali { @@ -29,28 +29,29 @@ namespace { struct ResourceReceiver : IResourceReceiver { - const ResourceBundle& mResources; - const MeshDefinition* mMeshDef = nullptr; + const ResourceBundle& mResources; + const MeshDefinition* mMeshDef = nullptr; const MaterialDefinition* mMaterialDef = nullptr; ResourceReceiver(const ResourceBundle& resources) : mResources(resources) - {} + { + } void Register(ResourceType::Value type, Index id) override { - switch (type) + switch(type) { - case ResourceType::Mesh: - mMeshDef = &mResources.mMeshes[id].first; - break; + case ResourceType::Mesh: + mMeshDef = &mResources.mMeshes[id].first; + break; - case ResourceType::Material: - mMaterialDef = &mResources.mMaterials[id].first; - break; + case ResourceType::Material: + mMaterialDef = &mResources.mMaterials[id].first; + break; - default: - break; + default: + break; } } }; @@ -59,11 +60,11 @@ const std::string PBR_SHADER_NAME = "dli_pbr"; void RetrieveBlendShapeComponents(const std::vector& blendShapes, bool& hasPositions, bool& hasNormals, bool& hasTangents) { - for (const auto& blendShape : blendShapes) + for(const auto& blendShape : blendShapes) { hasPositions = hasPositions || blendShape.deltas.IsDefined(); - hasNormals = hasNormals || blendShape.normals.IsDefined(); - hasTangents = hasTangents || blendShape.tangents.IsDefined(); + hasNormals = hasNormals || blendShape.normals.IsDefined(); + hasTangents = hasTangents || blendShape.tangents.IsDefined(); } } @@ -77,65 +78,65 @@ uint64_t HashNode(const NodeDefinition& nodeDef, const MaterialDefinition& mater const bool hasTransparency = MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY); hash.Add(hasTransparency); - if (hasTransparency || - materialDef.CheckTextures(MaterialDefinition::ALBEDO) || - materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || - materialDef.CheckTextures(MaterialDefinition::NORMAL)) + if(hasTransparency || + materialDef.CheckTextures(MaterialDefinition::ALBEDO) || + materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || + materialDef.CheckTextures(MaterialDefinition::NORMAL)) { hash.Add("3TEX"); } - if (materialDef.GetAlphaCutoff() > 0.f) + if(materialDef.GetAlphaCutoff() > 0.f) { - hash.Add("ALPH"/*A_TEST*/); + hash.Add("ALPH" /*A_TEST*/); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) { hash.Add("SSS"); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::GLTF_CHANNELS)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::GLTF_CHANNELS)) { - hash.Add("GLTF"/*_CHANNELS*/); + hash.Add("GLTF" /*_CHANNELS*/); } - if (meshDef.IsSkinned()) + if(meshDef.IsSkinned()) { - hash.Add("SKIN"/*NING*/); + hash.Add("SKIN" /*NING*/); } - if (MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) + if(MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) { - hash.Add("FLIP"/*_V*/); + hash.Add("FLIP" /*_V*/); } - if (meshDef.HasBlendShapes()) + if(meshDef.HasBlendShapes()) { bool hasPositions = false; - bool hasNormals = false; - bool hasTangents = false; + bool hasNormals = false; + bool hasTangents = false; RetrieveBlendShapeComponents(meshDef.mBlendShapes, hasPositions, hasNormals, hasTangents); - if (hasPositions) + if(hasPositions) { hash.Add("MORPHPOS"); } - if (hasNormals) + if(hasNormals) { hash.Add("MORPHNOR"); } - if (hasTangents) + if(hasTangents) { hash.Add("MORPHTAN"); } - if (hasPositions || hasNormals || hasTangents) + if(hasPositions || hasNormals || hasTangents) { hash.Add("MORPH"); - if (BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) + if(BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) { hash.Add("MORPHV2"); } @@ -144,17 +145,18 @@ uint64_t HashNode(const NodeDefinition& nodeDef, const MaterialDefinition& mater return hash; } -} +} // namespace struct ShaderDefinitionFactory::Impl { - ResourceBundle* mResources; // no ownership + ResourceBundle* mResources; // no ownership std::map mShaderMap; }; ShaderDefinitionFactory::ShaderDefinitionFactory() -: mImpl{ new Impl() } -{} +: mImpl{new Impl()} +{ +} ShaderDefinitionFactory::~ShaderDefinitionFactory() = default; @@ -168,106 +170,106 @@ Index ShaderDefinitionFactory::ProduceShader(const NodeDefinition& nodeDef) { DALI_ASSERT_DEBUG(nodeDef.mRenderable); - auto& resources = *mImpl->mResources; - ResourceReceiver receiver{ resources }; + auto& resources = *mImpl->mResources; + ResourceReceiver receiver{resources}; nodeDef.mRenderable->RegisterResources(receiver); - if (!(receiver.mMeshDef && receiver.mMaterialDef)) + if(!(receiver.mMeshDef && receiver.mMaterialDef)) { return INVALID_INDEX; } - auto& shaderMap = mImpl->mShaderMap; - uint64_t hash = HashNode(nodeDef, *receiver.mMaterialDef, *receiver.mMeshDef); - auto iFind = shaderMap.find(hash); - if (iFind != shaderMap.end()) + auto& shaderMap = mImpl->mShaderMap; + uint64_t hash = HashNode(nodeDef, *receiver.mMaterialDef, *receiver.mMeshDef); + auto iFind = shaderMap.find(hash); + if(iFind != shaderMap.end()) { return iFind->second; } ShaderDefinition shaderDef; - shaderDef.mVertexShaderPath = PBR_SHADER_NAME + ".vsh"; + shaderDef.mVertexShaderPath = PBR_SHADER_NAME + ".vsh"; shaderDef.mFragmentShaderPath = PBR_SHADER_NAME + ".fsh"; - shaderDef.mRendererState = RendererState::DEPTH_TEST | RendererState::DEPTH_WRITE | RendererState::CULL_BACK; + shaderDef.mRendererState = RendererState::DEPTH_TEST | RendererState::DEPTH_WRITE | RendererState::CULL_BACK; - auto& materialDef = *receiver.mMaterialDef; + auto& materialDef = *receiver.mMaterialDef; const bool hasTransparency = MaskMatch(materialDef.mFlags, MaterialDefinition::TRANSPARENCY); - if (hasTransparency) + if(hasTransparency) { // TODO: this requires more granularity shaderDef.mRendererState = (shaderDef.mRendererState | RendererState::ALPHA_BLEND) & ~RendererState::DEPTH_WRITE; } - if (hasTransparency || - materialDef.CheckTextures(MaterialDefinition::ALBEDO) || - materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || - materialDef.CheckTextures(MaterialDefinition::NORMAL)) + if(hasTransparency || + materialDef.CheckTextures(MaterialDefinition::ALBEDO) || + materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS) || + materialDef.CheckTextures(MaterialDefinition::NORMAL)) { shaderDef.mDefines.push_back("THREE_TEX"); } - if (materialDef.GetAlphaCutoff() > 0.f) + if(materialDef.GetAlphaCutoff() > 0.f) { shaderDef.mDefines.push_back("ALPHA_TEST"); } - if (MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) + if(MaskMatch(materialDef.mFlags, MaterialDefinition::SUBSURFACE)) { shaderDef.mDefines.push_back("SSS"); } - if (MaskMatch(receiver.mMaterialDef->mFlags, MaterialDefinition::GLTF_CHANNELS)) + if(MaskMatch(receiver.mMaterialDef->mFlags, MaterialDefinition::GLTF_CHANNELS)) { shaderDef.mDefines.push_back("GLTF_CHANNELS"); } const auto& meshDef = *receiver.mMeshDef; - if (meshDef.IsSkinned()) + if(meshDef.IsSkinned()) { shaderDef.mDefines.push_back("SKINNING"); } - if (MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) + if(MaskMatch(meshDef.mFlags, MeshDefinition::FLIP_UVS_VERTICAL)) { shaderDef.mDefines.push_back("FLIP_V"); } - if (meshDef.HasBlendShapes()) + if(meshDef.HasBlendShapes()) { bool hasPositions = false; - bool hasNormals = false; - bool hasTangents = false; + bool hasNormals = false; + bool hasTangents = false; RetrieveBlendShapeComponents(meshDef.mBlendShapes, hasPositions, hasNormals, hasTangents); - if (hasPositions) + if(hasPositions) { shaderDef.mDefines.push_back("MORPH_POSITION"); } - if (hasNormals) + if(hasNormals) { shaderDef.mDefines.push_back("MORPH_NORMAL"); } - if (hasTangents) + if(hasTangents) { shaderDef.mDefines.push_back("MORPH_TANGENT"); } - if (hasPositions || hasNormals || hasTangents) + if(hasPositions || hasNormals || hasTangents) { shaderDef.mDefines.push_back("MORPH"); - if (BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) + if(BlendShapes::Version::VERSION_2_0 == meshDef.mBlendShapeVersion) { shaderDef.mDefines.push_back("MORPH_VERSION_2_0"); } } } - shaderDef.mUniforms["uMaxLOD"] = 6.f; + shaderDef.mUniforms["uMaxLOD"] = 6.f; shaderDef.mUniforms["uCubeMatrix"] = Matrix::IDENTITY; - Index result = resources.mShaders.size(); + Index result = resources.mShaders.size(); shaderMap[hash] = result; resources.mShaders.emplace_back(std::move(shaderDef), Shader()); @@ -275,5 +277,5 @@ Index ShaderDefinitionFactory::ProduceShader(const NodeDefinition& nodeDef) return result; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/shader-definition.cpp b/dali-scene-loader/public-api/shader-definition.cpp index 5fbec33..73c18ba 100644 --- a/dali-scene-loader/public-api/shader-definition.cpp +++ b/dali-scene-loader/public-api/shader-definition.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,11 +25,10 @@ namespace SceneLoader { namespace { - const std::string SHADER_HINT_OUTPUT_IS_TRANSPARENT("OUTPUT_IS_TRANSPARENT"); ///< Might generate transparent alpha from opaque inputs. -const std::string SHADER_HINT_MODIFIES_GEOMETRY("MODIFIES_GEOMETRY"); ///< Might change position of vertices, this option disables any culling optimizations. +const std::string SHADER_HINT_MODIFIES_GEOMETRY("MODIFIES_GEOMETRY"); ///< Might change position of vertices, this option disables any culling optimizations. -} +} // namespace ShaderDefinition::ShaderDefinition(const ShaderDefinition& other) : mRendererState(other.mRendererState), @@ -38,31 +37,32 @@ ShaderDefinition::ShaderDefinition(const ShaderDefinition& other) mDefines(other.mDefines), mHints(other.mHints), mUniforms(other.mUniforms) -{} +{ +} void ShaderDefinition::ApplyDefine(std::string& shaderCode, const std::string& definevar) { const std::string IF_1 = "#if 1"; std::size_t found = shaderCode.find(definevar); - while (found != std::string::npos) + while(found != std::string::npos) { // Greater then "@" character means is a letter, // therefore is not has the definevar we looking for. - if ((found + definevar.length()) < shaderCode.length() && shaderCode.at(found + definevar.length()) > '@') + if((found + definevar.length()) < shaderCode.length() && shaderCode.at(found + definevar.length()) > '@') { found = shaderCode.find(definevar, found + definevar.length()); continue; } - if (found > 0u && shaderCode.at(found - 1) > '@') + if(found > 0u && shaderCode.at(found - 1) > '@') { found = shaderCode.find(definevar, found + definevar.length()); continue; } - std::size_t defidx = shaderCode.rfind("#ifdef", found); + std::size_t defidx = shaderCode.rfind("#ifdef", found); std::size_t newlineidx = shaderCode.rfind("\n", found); - if (newlineidx < defidx && defidx != std::string::npos) + if(newlineidx < defidx && defidx != std::string::npos) { shaderCode.replace(defidx, found - defidx + definevar.length(), IF_1); found = defidx + IF_1.length(); @@ -76,18 +76,18 @@ void ShaderDefinition::ApplyDefine(std::string& shaderCode, const std::string& d } ShaderDefinition::RawData - ShaderDefinition::LoadRaw(const std::string& shadersPath) const +ShaderDefinition::LoadRaw(const std::string& shadersPath) const { RawData raw; - bool fail = false; + bool fail = false; raw.mVertexShaderSource = LoadTextFile((shadersPath + mVertexShaderPath).c_str(), &fail); - if (!fail) + if(!fail) { raw.mFragmentShaderSource = LoadTextFile((shadersPath + mFragmentShaderPath).c_str(), &fail); - if (!fail) + if(!fail) { - for (auto definevar : mDefines) + for(auto definevar : mDefines) { ApplyDefine(raw.mVertexShaderSource, definevar); ApplyDefine(raw.mFragmentShaderSource, definevar); @@ -95,14 +95,12 @@ ShaderDefinition::RawData } else { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << - shadersPath + mFragmentShaderPath << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << shadersPath + mFragmentShaderPath << "'."; } } else { - ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << - shadersPath + mVertexShaderPath << "'."; + ExceptionFlinger(ASSERT_LOCATION) << "Failed to load shader source from '" << shadersPath + mVertexShaderPath << "'."; } return raw; } @@ -110,21 +108,20 @@ ShaderDefinition::RawData Shader ShaderDefinition::Load(RawData&& raw) const { uint32_t hints = Shader::Hint::NONE; - for (const auto& hint : mHints) + for(const auto& hint : mHints) { - if (hint == SHADER_HINT_OUTPUT_IS_TRANSPARENT) + if(hint == SHADER_HINT_OUTPUT_IS_TRANSPARENT) { hints |= Shader::Hint::OUTPUT_IS_TRANSPARENT; } - else if (hint == SHADER_HINT_MODIFIES_GEOMETRY) + else if(hint == SHADER_HINT_MODIFIES_GEOMETRY) { hints |= Shader::Hint::MODIFIES_GEOMETRY; } } - Shader shader = Shader::New(raw.mVertexShaderSource, raw.mFragmentShaderSource, - static_cast(hints)); - for (Property::Map::SizeType i0 = 0, i1 = mUniforms.Count(); i0 != i1; ++i0) + Shader shader = Shader::New(raw.mVertexShaderSource, raw.mFragmentShaderSource, static_cast(hints)); + for(Property::Map::SizeType i0 = 0, i1 = mUniforms.Count(); i0 != i1; ++i0) { auto pair = mUniforms.GetKeyValue(i0); DALI_ASSERT_ALWAYS(pair.first.type == Property::Key::STRING); @@ -134,5 +131,5 @@ Shader ShaderDefinition::Load(RawData&& raw) const return shader; } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/skinning-details.cpp b/dali-scene-loader/public-api/skinning-details.cpp index 92ded02..0edb58b 100644 --- a/dali-scene-loader/public-api/skinning-details.cpp +++ b/dali-scene-loader/public-api/skinning-details.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,18 +15,17 @@ * */ #include "dali-scene-loader/public-api/skinning-details.h" -#include "dali/public-api/rendering/shader.h" -#include "dali/public-api/object/property.h" #include "dali/public-api/animation/constraints.h" +#include "dali/public-api/object/property.h" +#include "dali/public-api/rendering/shader.h" namespace Dali { namespace SceneLoader { - const unsigned int Skinning::MAX_JOINTS = 64; const std::string Skinning::BONE_UNIFORM_NAME = "uBone"; -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/string-callback.cpp b/dali-scene-loader/public-api/string-callback.cpp index d13fc15..8bf02e6 100644 --- a/dali-scene-loader/public-api/string-callback.cpp +++ b/dali-scene-loader/public-api/string-callback.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,11 +21,10 @@ namespace Dali { namespace SceneLoader { - void DefaultErrorCallback(const std::string& message) { DALI_LOG_ERROR("%s", message.c_str()); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/utils.cpp b/dali-scene-loader/public-api/utils.cpp index 8b8132e..4d4396d 100644 --- a/dali-scene-loader/public-api/utils.cpp +++ b/dali-scene-loader/public-api/utils.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,12 +19,12 @@ #include "dali-scene-loader/public-api/utils.h" // EXTERNAL -#include "dali/public-api/common/vector-wrapper.h" -#include "dali/public-api/animation/constraints.h" -#include -#include -#include #include +#include +#include +#include +#include "dali/public-api/animation/constraints.h" +#include "dali/public-api/common/vector-wrapper.h" namespace Dali { @@ -46,10 +46,11 @@ ExceptionFlinger::Impl::~Impl() noexcept(false) } ExceptionFlinger::ExceptionFlinger(const char* location) noexcept(true) -: mImpl{ location }, +: mImpl{location}, mStreamBuffer(GetMessageBuffer(), MESSAGE_BUFFER_SIZE - 1), mStream(&mStreamBuffer) -{} +{ +} ExceptionFlinger::~ExceptionFlinger() noexcept(false) { @@ -79,16 +80,16 @@ std::string FormatString(const char* format, ...) return result; } -std::string LoadTextFile(const char * path, bool* fail) +std::string LoadTextFile(const char* path, bool* fail) { std::ifstream inFile(path); - if (inFile) + if(inFile) { std::istreambuf_iterator eos; std::istreambuf_iterator i(inFile.rdbuf()); return std::string(i, eos); } - else if (fail) + else if(fail) { *fail = true; } @@ -102,32 +103,31 @@ Geometry MakeTexturedQuadGeometry(TexturedQuadOptions::Type options) properties.Insert("aTexCoord", Property::VECTOR2); std::vector bytes; - size_t stride = 0; - size_t uvOffset = 0; + size_t stride = 0; + size_t uvOffset = 0; struct { Vector3 aPosition; Vector2 aTexCoord; } vertices[] = { - { Vector3(-0.5f, 0.5f, 0.0f), Vector2(0.0f, .0f) }, - { Vector3(0.5f, 0.5f, 0.0f), Vector2(1.0f, .0f) }, - { Vector3(-0.5f, -0.5f, 0.0f), Vector2(0.0f, 1.0f) }, - { Vector3(0.5f, -0.5f, 0.0f), Vector2(1.0f, 1.0f) } - }; + {Vector3(-0.5f, 0.5f, 0.0f), Vector2(0.0f, .0f)}, + {Vector3(0.5f, 0.5f, 0.0f), Vector2(1.0f, .0f)}, + {Vector3(-0.5f, -0.5f, 0.0f), Vector2(0.0f, 1.0f)}, + {Vector3(0.5f, -0.5f, 0.0f), Vector2(1.0f, 1.0f)}}; bytes.resize(sizeof(vertices)); - stride = sizeof(vertices[0]); + stride = sizeof(vertices[0]); uvOffset = reinterpret_cast(&vertices[0].aTexCoord) - reinterpret_cast(&vertices[0]); std::memcpy(bytes.data(), vertices, sizeof(vertices)); - if (MaskMatch(options, TexturedQuadOptions::FLIP_VERTICAL)) + if(MaskMatch(options, TexturedQuadOptions::FLIP_VERTICAL)) { Vector2* uv = reinterpret_cast(reinterpret_cast(bytes.data()) + uvOffset); - for (int i = 0; i < 4; ++i) + for(int i = 0; i < 4; ++i) { uv->y = 1.0f - uv->y; - uv = reinterpret_cast(reinterpret_cast(uv) + stride); + uv = reinterpret_cast(reinterpret_cast(uv) + stride); } } @@ -145,5 +145,5 @@ void ToUnixFileSeparators(std::string& path) std::replace(path.begin(), path.end(), '\\', '/'); } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-scene-loader/public-api/view-projection.cpp b/dali-scene-loader/public-api/view-projection.cpp index ed8cbe3..ce2e6b0 100644 --- a/dali-scene-loader/public-api/view-projection.cpp +++ b/dali-scene-loader/public-api/view-projection.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,17 +21,16 @@ namespace Dali { namespace SceneLoader { - void ViewProjection::Update() { Matrix::Multiply(mViewProjection, mView, mProjection); mInvProjection = mProjection; - if (!mInvProjection.Invert()) + if(!mInvProjection.Invert()) { ExceptionFlinger(ASSERT_LOCATION) << "Failed to find inverse of projection matrix " << mProjection << "."; } } -} -} +} // namespace SceneLoader +} // namespace Dali diff --git a/dali-toolkit/devel-api/builder/tree-node.cpp b/dali-toolkit/devel-api/builder/tree-node.cpp index 0d04753..571816a 100644 --- a/dali-toolkit/devel-api/builder/tree-node.cpp +++ b/dali-toolkit/devel-api/builder/tree-node.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. @@ -27,7 +27,6 @@ namespace Dali { - /** * return true if the lower cased ASCII strings are equal. */ diff --git a/dali-toolkit/devel-api/controls/control-devel.cpp b/dali-toolkit/devel-api/controls/control-devel.cpp index 0670e68..157051b 100644 --- a/dali-toolkit/devel-api/controls/control-devel.cpp +++ b/dali-toolkit/devel-api/controls/control-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. @@ -25,8 +25,8 @@ // INTERNAL INCLUDES #include #include -#include #include +#include namespace Dali { @@ -122,230 +122,230 @@ Dali::Property GetVisualProperty(Control control, Dali::Property::Index index, D return controlDataImpl.GetVisualProperty(index, visualPropertyKey); } -static Toolkit::Internal::Control::Impl *GetControlImplementationIfAny( Dali::Actor actor) +static Toolkit::Internal::Control::Impl* GetControlImplementationIfAny(Dali::Actor actor) { - Dali::Toolkit::Control c = Toolkit::Control::DownCast( actor ); - if ( c ) + Dali::Toolkit::Control c = Toolkit::Control::DownCast(actor); + if(c) { - auto &impl1 = Toolkit::Internal::GetImplementation( c ); - auto &impl2 = Toolkit::Internal::Control::Impl::Get( impl1 ); + auto& impl1 = Toolkit::Internal::GetImplementation(c); + auto& impl2 = Toolkit::Internal::Control::Impl::Get(impl1); return &impl2; } return nullptr; } -Toolkit::DevelControl::AccessibilityActivateSignalType &AccessibilityActivateSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityActivateSignalType& AccessibilityActivateSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityActivateSignal; } -Toolkit::DevelControl::AccessibilityReadingSkippedSignalType &AccessibilityReadingSkippedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingSkippedSignalType& AccessibilityReadingSkippedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingSkippedSignal; } -Toolkit::DevelControl::AccessibilityReadingPausedSignalType &AccessibilityReadingPausedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingPausedSignalType& AccessibilityReadingPausedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingPausedSignal; } -Toolkit::DevelControl::AccessibilityReadingResumedSignalType &AccessibilityReadingResumedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingResumedSignalType& AccessibilityReadingResumedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingResumedSignal; } -Toolkit::DevelControl::AccessibilityReadingCancelledSignalType &AccessibilityReadingCancelledSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingCancelledSignalType& AccessibilityReadingCancelledSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingCancelledSignal; } -Toolkit::DevelControl::AccessibilityReadingStoppedSignalType &AccessibilityReadingStoppedSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityReadingStoppedSignalType& AccessibilityReadingStoppedSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityReadingStoppedSignal; } -Toolkit::DevelControl::AccessibilityGetNameSignalType &AccessibilityGetNameSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityGetNameSignalType& AccessibilityGetNameSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityGetNameSignal; } -Toolkit::DevelControl::AccessibilityGetDescriptionSignalType &AccessibilityGetDescriptionSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityGetDescriptionSignalType& AccessibilityGetDescriptionSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityGetDescriptionSignal; } -Toolkit::DevelControl::AccessibilityDoGestureSignalType &AccessibilityDoGestureSignal( Toolkit::Control control ) +Toolkit::DevelControl::AccessibilityDoGestureSignalType& AccessibilityDoGestureSignal(Toolkit::Control control) { - auto ac = GetControlImplementationIfAny ( control ); + auto ac = GetControlImplementationIfAny(control); return ac->mAccessibilityDoGestureSignal; } -void AppendAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) +void AppendAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { auto index = static_cast(relation); - if (index >= ac->mAccessibilityRelations.size()) + if(index >= ac->mAccessibilityRelations.size()) { - DALI_LOG_ERROR( "Relation index exceeds vector size." ); - return; + DALI_LOG_ERROR("Relation index exceeds vector size."); + return; } auto obj = ac->GetAccessibilityObject(destination); - if (obj) + if(obj) ac->mAccessibilityRelations[index].push_back(obj->GetAddress()); } } -void RemoveAccessibilityRelation( Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) +void RemoveAccessibilityRelation(Dali::Actor control, Actor destination, Dali::Accessibility::RelationType relation) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { auto index = static_cast(relation); - if (index >= ac->mAccessibilityRelations.size()) + if(index >= ac->mAccessibilityRelations.size()) { - DALI_LOG_ERROR( "Relation index exceeds vector size." ); - return; + DALI_LOG_ERROR("Relation index exceeds vector size."); + return; } auto obj = ac->GetAccessibilityObject(destination); - if (!obj) + if(!obj) return; auto address = obj->GetAddress(); - auto &targets = ac->mAccessibilityRelations[index]; - for (auto i = 0u; i < targets.size(); ++i) { - if (targets[i].ToString() == address.ToString()) - { - targets[i] = targets.back(); - targets.erase(targets.end() - 1); - } + auto& targets = ac->mAccessibilityRelations[index]; + for(auto i = 0u; i < targets.size(); ++i) + { + if(targets[i].ToString() == address.ToString()) + { + targets[i] = targets.back(); + targets.erase(targets.end() - 1); + } } } } -std::vector> GetAccessibilityRelations( Dali::Actor control ) +std::vector> GetAccessibilityRelations(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { return ac->mAccessibilityRelations; } return {}; } -void ClearAccessibilityRelations( Dali::Actor control ) +void ClearAccessibilityRelations(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - for (auto &it : ac->mAccessibilityRelations) + for(auto& it : ac->mAccessibilityRelations) it.clear(); } } -void SetAccessibilityConstructor( Dali::Actor control, - std::function< std::unique_ptr< Dali::Accessibility::Accessible >( Dali::Actor ) > constructor ) +void SetAccessibilityConstructor(Dali::Actor control, + std::function(Dali::Actor)> constructor) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { ac->accessibilityConstructor = constructor; } } -void AppendAccessibilityAttribute( Dali::Actor control, const std::string& key, - const std::string value ) +void AppendAccessibilityAttribute(Dali::Actor control, const std::string& key, const std::string value) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->AppendAccessibilityAttribute( key, value ); + ac->AppendAccessibilityAttribute(key, value); } } -void RemoveAccessibilityAttribute( Dali::Actor control, const std::string& key ) +void RemoveAccessibilityAttribute(Dali::Actor control, const std::string& key) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->RemoveAccessibilityAttribute( key ); + ac->RemoveAccessibilityAttribute(key); } } -void ClearAccessibilityAttributes( Dali::Actor control ) +void ClearAccessibilityAttributes(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { ac->ClearAccessibilityAttributes(); } } -void SetAccessibilityReadingInfoType( Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types ) +void SetAccessibilityReadingInfoType(Dali::Actor control, const Dali::Accessibility::ReadingInfoTypes types) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->SetAccessibilityReadingInfoType( types ); + ac->SetAccessibilityReadingInfoType(types); } } -Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control ) +Dali::Accessibility::ReadingInfoTypes GetAccessibilityReadingInfoType(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { return ac->GetAccessibilityReadingInfoType(); } return {}; } -bool ClearAccessibilityHighlight( Dali::Actor control ) +bool ClearAccessibilityHighlight(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - auto ptr = dynamic_cast( ac->GetAccessibilityObject() ); - if( ptr ) + auto ptr = dynamic_cast(ac->GetAccessibilityObject()); + if(ptr) return ptr->ClearHighlight(); } return false; } -bool GrabAccessibilityHighlight( Dali::Actor control ) +bool GrabAccessibilityHighlight(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - auto ptr = dynamic_cast( ac->GetAccessibilityObject() ); - if( ptr ) + auto ptr = dynamic_cast(ac->GetAccessibilityObject()); + if(ptr) return ptr->GrabHighlight(); } return false; } -Dali::Accessibility::States GetAccessibilityStates( Dali::Actor control ) +Dali::Accessibility::States GetAccessibilityStates(Dali::Actor control) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - auto ptr = dynamic_cast( ac->GetAccessibilityObject() ); + auto ptr = dynamic_cast(ac->GetAccessibilityObject()); if(ptr) return ptr->GetStates(); } return {}; } -void NotifyAccessibilityStateChange( Dali::Actor control, Dali::Accessibility::States states, bool doRecursive ) +void NotifyAccessibilityStateChange(Dali::Actor control, Dali::Accessibility::States states, bool doRecursive) { - if ( auto ac = GetControlImplementationIfAny ( control ) ) + if(auto ac = GetControlImplementationIfAny(control)) { - ac->GetAccessibilityObject()->NotifyAccessibilityStateChange( std::move(states), doRecursive ); + ac->GetAccessibilityObject()->NotifyAccessibilityStateChange(std::move(states), doRecursive); } } -Dali::Accessibility::Accessible *GetBoundAccessibilityObject( Dali::Actor control ) +Dali::Accessibility::Accessible* GetBoundAccessibilityObject(Dali::Actor control) { - return Dali::Accessibility::Accessible::Get( control ); + return Dali::Accessibility::Accessible::Get(control); } } // namespace DevelControl diff --git a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp old mode 100755 new mode 100644 index c8f9aeb..f50a912 --- a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list-item.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,11 +25,10 @@ namespace Dali { namespace Toolkit { - const std::string EMPTY_STRING; -WebBackForwardListItem::WebBackForwardListItem( const Dali::WebEngineBackForwardListItem* item ) -: mWebEngineBackForwardListItem( item ) +WebBackForwardListItem::WebBackForwardListItem(const Dali::WebEngineBackForwardListItem* item) +: mWebEngineBackForwardListItem(item) { } diff --git a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp old mode 100755 new mode 100644 index fe4e33b..75014f0 --- a/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-back-forward-list.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,10 +26,9 @@ namespace Dali { namespace Toolkit { - -WebBackForwardList::WebBackForwardList( const Dali::WebEngineBackForwardList& list ) -: mWebEngineBackForwardList( list ) -, mWebBackForwardListItem( 0 ) +WebBackForwardList::WebBackForwardList(const Dali::WebEngineBackForwardList& list) +: mWebEngineBackForwardList(list), + mWebBackForwardListItem(0) { } @@ -39,13 +38,13 @@ WebBackForwardList::~WebBackForwardList() WebBackForwardListItem* WebBackForwardList::GetCurrentItem() { - mWebBackForwardListItem = WebBackForwardListItem( &mWebEngineBackForwardList.GetCurrentItem() ); + mWebBackForwardListItem = WebBackForwardListItem(&mWebEngineBackForwardList.GetCurrentItem()); return &mWebBackForwardListItem; } -WebBackForwardListItem* WebBackForwardList::GetItemAtIndex( uint32_t index ) +WebBackForwardListItem* WebBackForwardList::GetItemAtIndex(uint32_t index) { - mWebBackForwardListItem = WebBackForwardListItem( &mWebEngineBackForwardList.GetItemAtIndex( index ) ); + mWebBackForwardListItem = WebBackForwardListItem(&mWebEngineBackForwardList.GetItemAtIndex(index)); return &mWebBackForwardListItem; } diff --git a/dali-toolkit/devel-api/controls/web-view/web-context.cpp b/dali-toolkit/devel-api/controls/web-view/web-context.cpp old mode 100755 new mode 100644 index 1e0cbbd..c72012c --- a/dali-toolkit/devel-api/controls/web-view/web-context.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-context.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,9 +22,8 @@ namespace Dali { namespace Toolkit { - -WebContext::WebContext( Dali::WebEngineContext& context) -: mWebEngineContext( context ) +WebContext::WebContext(Dali::WebEngineContext& context) +: mWebEngineContext(context) { } @@ -37,29 +36,29 @@ Dali::WebEngineContext::CacheModel WebContext::GetCacheModel() const return mWebEngineContext.GetCacheModel(); } -void WebContext::SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel ) +void WebContext::SetCacheModel(Dali::WebEngineContext::CacheModel cacheModel) { - mWebEngineContext.SetCacheModel( cacheModel ); + mWebEngineContext.SetCacheModel(cacheModel); } -void WebContext::SetProxyUri( const std::string& uri ) +void WebContext::SetProxyUri(const std::string& uri) { - mWebEngineContext.SetProxyUri( uri ); + mWebEngineContext.SetProxyUri(uri); } -void WebContext::SetCertificateFilePath( const std::string& certificatePath ) +void WebContext::SetCertificateFilePath(const std::string& certificatePath) { - mWebEngineContext.SetCertificateFilePath( certificatePath ); + mWebEngineContext.SetCertificateFilePath(certificatePath); } -void WebContext::DisableCache( bool cacheDisabled ) +void WebContext::DisableCache(bool cacheDisabled) { - mWebEngineContext.DisableCache( cacheDisabled ); + mWebEngineContext.DisableCache(cacheDisabled); } -void WebContext::SetDefaultProxyAuth( const std::string& username, const std::string& password ) +void WebContext::SetDefaultProxyAuth(const std::string& username, const std::string& password) { - mWebEngineContext.SetDefaultProxyAuth( username, password ); + mWebEngineContext.SetDefaultProxyAuth(username, password); } void WebContext::DeleteWebDatabase() diff --git a/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp b/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp old mode 100755 new mode 100644 index ef6bd64..fba924a --- a/dali-toolkit/devel-api/controls/web-view/web-cookie-manager.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-cookie-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. @@ -22,9 +22,8 @@ namespace Dali { namespace Toolkit { - -WebCookieManager::WebCookieManager( Dali::WebEngineCookieManager& manager ) -: mWebEngineCookieManager( manager ) +WebCookieManager::WebCookieManager(Dali::WebEngineCookieManager& manager) +: mWebEngineCookieManager(manager) { } @@ -32,9 +31,9 @@ WebCookieManager::~WebCookieManager() { } -void WebCookieManager::SetCookieAcceptPolicy( Dali::WebEngineCookieManager::CookieAcceptPolicy cookieAcceptPolicy ) +void WebCookieManager::SetCookieAcceptPolicy(Dali::WebEngineCookieManager::CookieAcceptPolicy cookieAcceptPolicy) { - mWebEngineCookieManager.SetCookieAcceptPolicy( cookieAcceptPolicy ); + mWebEngineCookieManager.SetCookieAcceptPolicy(cookieAcceptPolicy); } Dali::WebEngineCookieManager::CookieAcceptPolicy WebCookieManager::GetCookieAcceptPolicy() const @@ -47,9 +46,9 @@ void WebCookieManager::ClearCookies() mWebEngineCookieManager.ClearCookies(); } -void WebCookieManager::SetPersistentStorage( const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage ) +void WebCookieManager::SetPersistentStorage(const std::string& path, Dali::WebEngineCookieManager::CookiePersistentStorage storage) { - mWebEngineCookieManager.SetPersistentStorage( path, storage ); + mWebEngineCookieManager.SetPersistentStorage(path, storage); } } // namespace Toolkit diff --git a/dali-toolkit/devel-api/controls/web-view/web-settings.cpp b/dali-toolkit/devel-api/controls/web-view/web-settings.cpp old mode 100755 new mode 100644 index 7b6dc13..bdd191a --- a/dali-toolkit/devel-api/controls/web-view/web-settings.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-settings.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,9 +25,8 @@ namespace Dali { namespace Toolkit { - -WebSettings::WebSettings( Dali::WebEngineSettings& settings ) -: mWebEngineSettings( settings ) +WebSettings::WebSettings(Dali::WebEngineSettings& settings) +: mWebEngineSettings(settings) { } @@ -35,14 +34,14 @@ WebSettings::~WebSettings() { } -void WebSettings::AllowMixedContents( bool allowed ) +void WebSettings::AllowMixedContents(bool allowed) { - mWebEngineSettings.AllowMixedContents( allowed ); + mWebEngineSettings.AllowMixedContents(allowed); } -void WebSettings::EnableSpatialNavigation( bool enabled ) +void WebSettings::EnableSpatialNavigation(bool enabled) { - mWebEngineSettings.AllowMixedContents( enabled ); + mWebEngineSettings.AllowMixedContents(enabled); } int WebSettings::GetDefaultFontSize() const @@ -50,19 +49,19 @@ int WebSettings::GetDefaultFontSize() const return mWebEngineSettings.GetDefaultFontSize(); } -void WebSettings::SetDefaultFontSize( int defaultFontSize ) +void WebSettings::SetDefaultFontSize(int defaultFontSize) { - mWebEngineSettings.SetDefaultFontSize( defaultFontSize ); + mWebEngineSettings.SetDefaultFontSize(defaultFontSize); } -void WebSettings::EnableWebSecurity( bool enabled ) +void WebSettings::EnableWebSecurity(bool enabled) { - mWebEngineSettings.EnableWebSecurity( enabled ); + mWebEngineSettings.EnableWebSecurity(enabled); } -void WebSettings::AllowFileAccessFromExternalUrl( bool allowed ) +void WebSettings::AllowFileAccessFromExternalUrl(bool allowed) { - mWebEngineSettings.AllowFileAccessFromExternalUrl( allowed ); + mWebEngineSettings.AllowFileAccessFromExternalUrl(allowed); } bool WebSettings::IsJavaScriptEnabled() const @@ -70,14 +69,14 @@ bool WebSettings::IsJavaScriptEnabled() const return mWebEngineSettings.IsJavaScriptEnabled(); } -void WebSettings::EnableJavaScript( bool enabled ) +void WebSettings::EnableJavaScript(bool enabled) { - mWebEngineSettings.EnableJavaScript( enabled ); + mWebEngineSettings.EnableJavaScript(enabled); } -void WebSettings::AllowScriptsOpenWindows( bool allowed ) +void WebSettings::AllowScriptsOpenWindows(bool allowed) { - mWebEngineSettings.AllowScriptsOpenWindows( allowed ); + mWebEngineSettings.AllowScriptsOpenWindows(allowed); } bool WebSettings::AreImagesLoadedAutomatically() const @@ -85,9 +84,9 @@ bool WebSettings::AreImagesLoadedAutomatically() const return mWebEngineSettings.AreImagesLoadedAutomatically(); } -void WebSettings::AllowImagesLoadAutomatically( bool automatic ) +void WebSettings::AllowImagesLoadAutomatically(bool automatic) { - mWebEngineSettings.AllowImagesLoadAutomatically( automatic ); + mWebEngineSettings.AllowImagesLoadAutomatically(automatic); } std::string WebSettings::GetDefaultTextEncodingName() const @@ -95,9 +94,9 @@ std::string WebSettings::GetDefaultTextEncodingName() const return mWebEngineSettings.GetDefaultTextEncodingName(); } -void WebSettings::SetDefaultTextEncodingName( const std::string& defaultTextEncodingName ) +void WebSettings::SetDefaultTextEncodingName(const std::string& defaultTextEncodingName) { - mWebEngineSettings.SetDefaultTextEncodingName( defaultTextEncodingName ); + mWebEngineSettings.SetDefaultTextEncodingName(defaultTextEncodingName); } } // namespace Toolkit diff --git a/dali-toolkit/devel-api/controls/web-view/web-view.cpp b/dali-toolkit/devel-api/controls/web-view/web-view.cpp old mode 100755 new mode 100644 index a0672ae..c3a9d40 --- a/dali-toolkit/devel-api/controls/web-view/web-view.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-view.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. @@ -59,9 +59,9 @@ WebView WebView::New(const std::string& locale, const std::string& timezoneId) return Internal::WebView::New(locale, timezoneId); } -WebView WebView::New( int argc, char** argv ) +WebView WebView::New(int argc, char** argv) { - return Internal::WebView::New( argc, argv ); + return Internal::WebView::New(argc, argv); } WebView WebView::DownCast(BaseHandle handle) @@ -71,27 +71,27 @@ WebView WebView::DownCast(BaseHandle handle) Dali::Toolkit::WebSettings* WebView::GetSettings() const { - return Dali::Toolkit::GetImpl( *this ).GetSettings(); + return Dali::Toolkit::GetImpl(*this).GetSettings(); } Dali::Toolkit::WebContext* WebView::GetContext() const { - return Dali::Toolkit::GetImpl( *this ).GetContext(); + return Dali::Toolkit::GetImpl(*this).GetContext(); } Dali::Toolkit::WebCookieManager* WebView::GetCookieManager() const { - return Dali::Toolkit::GetImpl( *this ).GetCookieManager(); + return Dali::Toolkit::GetImpl(*this).GetCookieManager(); } Dali::Toolkit::WebBackForwardList* WebView::GetBackForwardList() const { - return Dali::Toolkit::GetImpl( *this ).GetBackForwardList(); + return Dali::Toolkit::GetImpl(*this).GetBackForwardList(); } Dali::Toolkit::ImageView& WebView::GetFavicon() { - return Dali::Toolkit::GetImpl( *this ).GetFavicon(); + return Dali::Toolkit::GetImpl(*this).GetFavicon(); } void WebView::LoadUrl(const std::string& url) @@ -124,9 +124,9 @@ void WebView::Resume() Dali::Toolkit::GetImpl(*this).Resume(); } -void WebView::ScrollBy( int deltaX, int deltaY ) +void WebView::ScrollBy(int deltaX, int deltaY) { - Dali::Toolkit::GetImpl( *this ).ScrollBy( deltaX, deltaY ); + Dali::Toolkit::GetImpl(*this).ScrollBy(deltaX, deltaY); } bool WebView::CanGoForward() @@ -166,7 +166,7 @@ void WebView::AddJavaScriptMessageHandler(const std::string& exposedObjectName, void WebView::ClearAllTilesResources() { - Dali::Toolkit::GetImpl( *this ).ClearAllTilesResources(); + Dali::Toolkit::GetImpl(*this).ClearAllTilesResources(); } void WebView::ClearHistory() @@ -191,7 +191,7 @@ WebView::WebViewPageLoadErrorSignalType& WebView::PageLoadErrorSignal() WebView::WebViewScrollEdgeReachedSignalType& WebView::ScrollEdgeReachedSignal() { - return Dali::Toolkit::GetImpl( *this ).ScrollEdgeReachedSignal(); + return Dali::Toolkit::GetImpl(*this).ScrollEdgeReachedSignal(); } WebView::WebView(Internal::WebView& implementation) diff --git a/dali-toolkit/devel-api/layouting/flex-node.cpp b/dali-toolkit/devel-api/layouting/flex-node.cpp index aa46e6f..c3636dc 100644 --- a/dali-toolkit/devel-api/layouting/flex-node.cpp +++ b/dali-toolkit/devel-api/layouting/flex-node.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. @@ -162,7 +162,7 @@ SizeTuple Node::MeasureNode(float width, int widthMode, float height, int height Toolkit::Flex::SizeTuple nodeSize{8, 8}; // Default size set to 8,8 to aid bug detection. if(mImpl->mMeasureCallback && mImpl->mActor.GetHandle()) { - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode MeasureCallback executing on %s\n", mImpl->mActor.GetHandle().GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode MeasureCallback executing on %s\n", mImpl->mActor.GetHandle().GetProperty(Dali::Actor::Property::NAME).c_str()); mImpl->mMeasureCallback(mImpl->mActor.GetHandle(), width, widthMode, height, heightMode, &nodeSize); } DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MeasureNode nodeSize width:%f height:%f\n", nodeSize.width, nodeSize.height); diff --git a/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp b/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp index 2e049f1..3b3933b 100644 --- a/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/alpha-discard-effect.cpp @@ -18,14 +18,13 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - Property::Map CreateAlphaDiscardEffect() { Property::Map map; diff --git a/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp b/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp index e8c1b7e..153dc5f 100644 --- a/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/dissolve-effect.cpp @@ -25,11 +25,9 @@ namespace Dali { - namespace Toolkit { - -void DissolveEffectSetCentralLine( Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress ) +void DissolveEffectSetCentralLine(Actor& actor, const Vector2& position, const Vector2& displacement, float initialProgress) { // the line passes through 'position' and has the direction of 'displacement' float coefA, coefB, coefC; //line equation: Ax+By+C=0; @@ -100,12 +98,12 @@ void DissolveEffectSetCentralLine( Actor& actor, const Vector2& position, const actor.RegisterProperty("uPercentage", initialProgress, Dali::Property::ANIMATABLE); } -Property::Map CreateDissolveEffect( bool useHighPrecision ) +Property::Map CreateDissolveEffect(bool useHighPrecision) { const char* prefixHighPrecision("precision highp float;\n"); const char* prefixMediumPrecision("precision mediump float;\n"); - const char* vertexShader = SHADER_DISSOLVE_EFFECT_VERT.data(); + const char* vertexShader = SHADER_DISSOLVE_EFFECT_VERT.data(); const char* fragmentShader = SHADER_DISSOLVE_EFFECT_FRAG.data(); Property::Map map; diff --git a/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp b/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp index 597dc7c..a05fd4a 100644 --- a/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/distance-field-effect.cpp @@ -18,19 +18,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - Dali::Property::Map CreateDistanceFieldEffect() { const char* fragmentShaderPrefix("#extension GL_OES_standard_derivatives : enable\n"); diff --git a/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp b/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp index bab97f2..2d446d3 100644 --- a/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/image-region-effect.cpp @@ -18,14 +18,13 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - Property::Map CreateImageRegionEffect() { Property::Map map; @@ -37,6 +36,6 @@ Property::Map CreateImageRegionEffect() return map; } -} // Toolkit +} // namespace Toolkit -} // Dali +} // namespace Dali diff --git a/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp b/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp index 430832e..a987243 100644 --- a/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/motion-blur-effect.cpp @@ -22,15 +22,14 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - -void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples ) +void SetMotionBlurProperties(Actor& actor, unsigned int numBlurSamples) { actor.RegisterProperty("uBlurTexCoordScale", 0.125f); actor.RegisterProperty("uGeometryStretchFactor", 0.05f); @@ -48,7 +47,6 @@ void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples ) constraint.Apply(); } - Property::Map CreateMotionBlurEffect() { Property::Map map; @@ -66,5 +64,5 @@ Property::Map CreateMotionBlurEffect() return map; } -} // Toolkit -} // Dali +} // namespace Toolkit +} // namespace Dali diff --git a/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp b/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp index bdd21f7..9d736a3 100644 --- a/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp +++ b/dali-toolkit/devel-api/shader-effects/motion-stretch-effect.cpp @@ -24,15 +24,14 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { namespace Toolkit { - -void SetMotionStretchProperties( Actor& actor ) +void SetMotionStretchProperties(Actor& actor) { actor.RegisterProperty("uGeometryStretchFactor", 0.5f); actor.RegisterProperty("uSpeedScalingFactor", 0.5f); @@ -63,6 +62,5 @@ Property::Map CreateMotionStretchEffect() return map; } - -} // Toolkit -} // Dali +} // namespace Toolkit +} // namespace Dali diff --git a/dali-toolkit/devel-api/text/text-utils-devel.cpp b/dali-toolkit/devel-api/text/text-utils-devel.cpp old mode 100755 new mode 100644 index e5ad925..0112e32 --- a/dali-toolkit/devel-api/text/text-utils-devel.cpp +++ b/dali-toolkit/devel-api/text/text-utils-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. @@ -1013,12 +1013,11 @@ Size LayoutText(const RendererParameters& textParameters, TextAbstraction::TextR // Set the layout parameters. Size textLayoutArea = Size(static_cast(textParameters.textWidth), - static_cast(textParameters.textHeight)); + static_cast(textParameters.textHeight)); // padding - Extents padding = textParameters.padding; - internalDataModel.textLayoutArea = Size(textLayoutArea.x - ( padding.start + padding.end ), textLayoutArea.y - ( padding.top + padding.bottom ) ); - + Extents padding = textParameters.padding; + internalDataModel.textLayoutArea = Size(textLayoutArea.x - (padding.start + padding.end), textLayoutArea.y - (padding.top + padding.bottom)); if(isCircularTextLayout) { diff --git a/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp b/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp index 80a6865..e3f4209 100644 --- a/dali-toolkit/internal/accessibility-manager/accessibility-manager-impl.cpp +++ b/dali-toolkit/internal/accessibility-manager/accessibility-manager-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,26 +19,23 @@ #include "accessibility-manager-impl.h" // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - AccessibilityManager::AccessibilityManager() { - mFocusOrder.push_back( {} ); // zero has a special meaning + mFocusOrder.push_back({}); // zero has a special meaning } AccessibilityManager::~AccessibilityManager() @@ -47,71 +44,71 @@ AccessibilityManager::~AccessibilityManager() void AccessibilityManager::SetAccessibilityAttribute(Actor actor, Toolkit::AccessibilityManager::AccessibilityAttribute type, const std::string& text) { - switch ( type ) + switch(type) { - case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: - actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, text ); - break; - - case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: - actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, text ); - break; - - case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: - case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: - default: - break; + case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, text); + break; + + case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, text); + break; + + case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: + case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: + default: + break; } } std::string AccessibilityManager::GetAccessibilityAttribute(Actor actor, Toolkit::AccessibilityManager::AccessibilityAttribute type) const { - switch ( type ) + switch(type) { - case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: - return actor.GetProperty< std::string >( Toolkit::DevelControl::Property::ACCESSIBILITY_NAME ); + case Toolkit::AccessibilityManager::ACCESSIBILITY_LABEL: + return actor.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_NAME); - case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: - return actor.GetProperty< std::string >( Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION ); + case Toolkit::AccessibilityManager::ACCESSIBILITY_HINT: + return actor.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION); - case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: - case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: - default: - return ""; + case Toolkit::AccessibilityManager::ACCESSIBILITY_TRAIT: + case Toolkit::AccessibilityManager::ACCESSIBILITY_VALUE: + default: + return ""; } } void AccessibilityManager::SetFocusOrder(Actor actor, const unsigned int order) { - if (order == 0) + if(order == 0) return; - if (order >= mFocusOrder.size()) + if(order >= mFocusOrder.size()) mFocusOrder.resize(order + 1); auto it = mFocusOrder.begin() + order; mFocusOrder.insert(it, actor); - if (order > 0) + if(order > 0) { Actor prev = mFocusOrder[order - 1]; - DevelControl::AppendAccessibilityRelation( prev, actor, Accessibility::RelationType::FLOWS_TO ); - DevelControl::AppendAccessibilityRelation( actor, prev, Accessibility::RelationType::FLOWS_FROM ); + DevelControl::AppendAccessibilityRelation(prev, actor, Accessibility::RelationType::FLOWS_TO); + DevelControl::AppendAccessibilityRelation(actor, prev, Accessibility::RelationType::FLOWS_FROM); } - if (order + 1 < mFocusOrder.size()) + if(order + 1 < mFocusOrder.size()) { Actor next = mFocusOrder[order + 1]; - DevelControl::AppendAccessibilityRelation( actor, next, Accessibility::RelationType::FLOWS_TO ); - DevelControl::AppendAccessibilityRelation( next, actor, Accessibility::RelationType::FLOWS_FROM ); + DevelControl::AppendAccessibilityRelation(actor, next, Accessibility::RelationType::FLOWS_TO); + DevelControl::AppendAccessibilityRelation(next, actor, Accessibility::RelationType::FLOWS_FROM); } } unsigned int AccessibilityManager::GetFocusOrder(Actor actor) const { - for (auto it = mFocusOrder.begin(); it != mFocusOrder.end(); ++it) + for(auto it = mFocusOrder.begin(); it != mFocusOrder.end(); ++it) { - if (actor == *it) + if(actor == *it) return it - mFocusOrder.begin(); } @@ -127,7 +124,7 @@ Actor AccessibilityManager::GetActorByFocusOrder(const unsigned int order) { Actor actor; - if (order > 0 && order < mFocusOrder.size()) + if(order > 0 && order < mFocusOrder.size()) actor = mFocusOrder[order]; return actor; @@ -152,11 +149,11 @@ Actor AccessibilityManager::GetCurrentFocusGroup() unsigned int AccessibilityManager::GetCurrentFocusOrder() { - auto actor = GetCurrentFocusActor(); + auto actor = GetCurrentFocusActor(); unsigned order = 0; - if (actor) - order = GetFocusOrder( actor ); + if(actor) + order = GetFocusOrder(actor); return order; } @@ -165,7 +162,7 @@ bool AccessibilityManager::MoveFocusForward() { unsigned current = GetCurrentFocusOrder(); - if (current + 1 < mFocusOrder.size()) + if(current + 1 < mFocusOrder.size()) return SetCurrentFocusActor(mFocusOrder[current + 1]); return false; @@ -175,7 +172,7 @@ bool AccessibilityManager::MoveFocusBackward() { unsigned current = GetCurrentFocusOrder(); - if (current > 1) // zero has a special meaning + if(current > 1) // zero has a special meaning return SetCurrentFocusActor(mFocusOrder[current - 1]); return false; @@ -184,24 +181,24 @@ bool AccessibilityManager::MoveFocusBackward() void AccessibilityManager::ClearFocus() { auto actor = GetCurrentFocusActor(); - Toolkit::DevelControl::ClearAccessibilityHighlight( actor ); + Toolkit::DevelControl::ClearAccessibilityHighlight(actor); } void AccessibilityManager::Reset() { ClearFocus(); - for (std::size_t i = 2; i < mFocusOrder.size(); ++i) + for(std::size_t i = 2; i < mFocusOrder.size(); ++i) { Actor prev = mFocusOrder[i - 1]; Actor next = mFocusOrder[i]; - DevelControl::RemoveAccessibilityRelation( prev, next, Accessibility::RelationType::FLOWS_TO ); - DevelControl::RemoveAccessibilityRelation( next, prev, Accessibility::RelationType::FLOWS_FROM ); + DevelControl::RemoveAccessibilityRelation(prev, next, Accessibility::RelationType::FLOWS_TO); + DevelControl::RemoveAccessibilityRelation(next, prev, Accessibility::RelationType::FLOWS_FROM); } mFocusOrder.clear(); - mFocusOrder.push_back( {} ); + mFocusOrder.push_back({}); } void AccessibilityManager::SetFocusGroup(Actor actor, bool isFocusGroup) @@ -243,7 +240,7 @@ bool AccessibilityManager::GetWrapMode() const void AccessibilityManager::SetFocusIndicatorActor(Actor indicator) { - Dali::Accessibility::Accessible::SetHighlightActor( indicator ); + Dali::Accessibility::Accessible::SetHighlightActor(indicator); } Actor AccessibilityManager::GetFocusIndicatorActor() diff --git a/dali-toolkit/internal/builder/builder-animations.cpp b/dali-toolkit/internal/builder/builder-animations.cpp index c917d06..cd20832 100644 --- a/dali-toolkit/internal/builder/builder-animations.cpp +++ b/dali-toolkit/internal/builder/builder-animations.cpp @@ -16,380 +16,373 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include #include namespace // unnamed namespace { - using namespace Dali; -TimePeriod GetTimePeriod( const TreeNode& child, const Toolkit::Internal::Replacement& constant ) +TimePeriod GetTimePeriod(const TreeNode& child, const Toolkit::Internal::Replacement& constant) { - OptionalFloat delay = constant.IsFloat( IsChild(child, "delay" ) ); - OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) ); - DALI_ASSERT_ALWAYS( duration && "Time period must have at least a duration" ); + OptionalFloat delay = constant.IsFloat(IsChild(child, "delay")); + OptionalFloat duration = constant.IsFloat(IsChild(child, "duration")); + DALI_ASSERT_ALWAYS(duration && "Time period must have at least a duration"); - if( delay ) + if(delay) { - return TimePeriod( *delay, *duration ); + return TimePeriod(*delay, *duration); } else { - return TimePeriod( *duration ); + return TimePeriod(*duration); } } -Property::Value GetPropertyValue( const Property::Type& propType, const TreeNode& child ) +Property::Value GetPropertyValue(const Property::Type& propType, const TreeNode& child) { - switch ( propType ) + switch(propType) { case Property::BOOLEAN: { - return Property::Value( GetBoolean( child ) ); + return Property::Value(GetBoolean(child)); } case Property::FLOAT: { - return Property::Value( GetFloat( child ) ); + return Property::Value(GetFloat(child)); } case Property::VECTOR2: { - return Property::Value( GetVector2( child ) ); + return Property::Value(GetVector2(child)); } case Property::VECTOR3: { - return Property::Value( GetVector3( child ) ); + return Property::Value(GetVector3(child)); } case Property::VECTOR4: { - return Property::Value( GetVector4( child ) ); + return Property::Value(GetVector4(child)); } case Property::ROTATION: { - if( 4 == child.Size() ) + if(4 == child.Size()) { Vector4 v(GetVector4(child)); // angle, axis as per spec - return Property::Value( Quaternion(Radian(Degree(v[3])), - Vector3(v[0],v[1],v[2])) ); + return Property::Value(Quaternion(Radian(Degree(v[3])), + Vector3(v[0], v[1], v[2]))); } else { // degrees as per spec - Vector3 rotation = GetVector3( child ); - return Property::Value( Quaternion(Radian(Degree(rotation.x)), - Radian(Degree(rotation.y)), - Radian(Degree(rotation.z))) ); + Vector3 rotation = GetVector3(child); + return Property::Value(Quaternion(Radian(Degree(rotation.x)), + Radian(Degree(rotation.y)), + Radian(Degree(rotation.z)))); } } case Property::NONE: // fall default: { - DALI_ASSERT_ALWAYS( !"Property type incorrect" ); + DALI_ASSERT_ALWAYS(!"Property type incorrect"); } } } -AlphaFunction GetAlphaFunction( const std::string& alphaFunction ) +AlphaFunction GetAlphaFunction(const std::string& alphaFunction) { - typedef std::map< const std::string, Dali::AlphaFunction > AlphaFunctionLut; - static AlphaFunctionLut alphaFunctionLut; + typedef std::map AlphaFunctionLut; + static AlphaFunctionLut alphaFunctionLut; - if( 0 == alphaFunctionLut.size() ) + if(0 == alphaFunctionLut.size()) { // coding convention is uppercase enums - alphaFunctionLut["DEFAULT"] = AlphaFunction(AlphaFunction::DEFAULT); - alphaFunctionLut["LINEAR"] = AlphaFunction(AlphaFunction::LINEAR); - alphaFunctionLut["REVERSE"] = AlphaFunction(AlphaFunction::REVERSE); - alphaFunctionLut["EASE_IN_SQUARE"] = AlphaFunction(AlphaFunction::EASE_IN_SQUARE); - alphaFunctionLut["EASE_OUT_SQUARE"] = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE); - alphaFunctionLut["EASE_IN"] = AlphaFunction(AlphaFunction::EASE_IN); - alphaFunctionLut["EASE_OUT"] = AlphaFunction(AlphaFunction::EASE_OUT); - alphaFunctionLut["EASE_IN_OUT"] = AlphaFunction(AlphaFunction::EASE_IN_OUT); - alphaFunctionLut["EASE_IN_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_SINE); - alphaFunctionLut["EASE_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_OUT_SINE); - alphaFunctionLut["EASE_IN_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE); - alphaFunctionLut["BOUNCE"] = AlphaFunction(AlphaFunction::BOUNCE); - alphaFunctionLut["SIN"] = AlphaFunction(AlphaFunction::SIN); - alphaFunctionLut["EASE_OUT_BACK"] = AlphaFunction(AlphaFunction::EASE_OUT_BACK); + alphaFunctionLut["DEFAULT"] = AlphaFunction(AlphaFunction::DEFAULT); + alphaFunctionLut["LINEAR"] = AlphaFunction(AlphaFunction::LINEAR); + alphaFunctionLut["REVERSE"] = AlphaFunction(AlphaFunction::REVERSE); + alphaFunctionLut["EASE_IN_SQUARE"] = AlphaFunction(AlphaFunction::EASE_IN_SQUARE); + alphaFunctionLut["EASE_OUT_SQUARE"] = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE); + alphaFunctionLut["EASE_IN"] = AlphaFunction(AlphaFunction::EASE_IN); + alphaFunctionLut["EASE_OUT"] = AlphaFunction(AlphaFunction::EASE_OUT); + alphaFunctionLut["EASE_IN_OUT"] = AlphaFunction(AlphaFunction::EASE_IN_OUT); + alphaFunctionLut["EASE_IN_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_SINE); + alphaFunctionLut["EASE_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_OUT_SINE); + alphaFunctionLut["EASE_IN_OUT_SINE"] = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE); + alphaFunctionLut["BOUNCE"] = AlphaFunction(AlphaFunction::BOUNCE); + alphaFunctionLut["SIN"] = AlphaFunction(AlphaFunction::SIN); + alphaFunctionLut["EASE_OUT_BACK"] = AlphaFunction(AlphaFunction::EASE_OUT_BACK); } - const AlphaFunctionLut::const_iterator iter( alphaFunctionLut.find( alphaFunction ) ); + const AlphaFunctionLut::const_iterator iter(alphaFunctionLut.find(alphaFunction)); - if( iter != alphaFunctionLut.end() ) + if(iter != alphaFunctionLut.end()) { return iter->second; } else { - DALI_ASSERT_ALWAYS( iter != alphaFunctionLut.end() && "Unknown Alpha Constant" ); + DALI_ASSERT_ALWAYS(iter != alphaFunctionLut.end() && "Unknown Alpha Constant"); return Dali::AlphaFunction::DEFAULT; } } } // unnamed namespace - namespace Dali { - namespace Toolkit { - namespace Internal { - -Animation CreateAnimation( const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot, Builder* const builder ) +Animation CreateAnimation(const TreeNode& child, const Replacement& constant, Dali::Actor searchRoot, Builder* const builder) { float durationSum = 0.f; Dali::Actor searchActor = searchRoot ? searchRoot : Dali::Stage::GetCurrent().GetRootLayer(); - Animation animation( Animation::New( 0.f ) ); + Animation animation(Animation::New(0.f)); // duration needs to be set before AnimateTo calls for correct operation when AnimateTo has no "timePeriod". - OptionalFloat duration = constant.IsFloat( IsChild(child, "duration" ) ); + OptionalFloat duration = constant.IsFloat(IsChild(child, "duration")); - if( duration ) + if(duration) { - animation.SetDuration( *duration ); + animation.SetDuration(*duration); } - if( OptionalBoolean looping = constant.IsBoolean( IsChild(child, "loop" ) ) ) + if(OptionalBoolean looping = constant.IsBoolean(IsChild(child, "loop"))) { - animation.SetLooping( *looping ); + animation.SetLooping(*looping); } - if( OptionalString endAction = constant.IsString( IsChild(child, "endAction" ) ) ) + if(OptionalString endAction = constant.IsString(IsChild(child, "endAction"))) { if("BAKE" == *endAction) { - animation.SetEndAction( Animation::BAKE ); + animation.SetEndAction(Animation::BAKE); } else if("DISCARD" == *endAction) { - animation.SetEndAction( Animation::DISCARD ); + animation.SetEndAction(Animation::DISCARD); } else if("BAKE_FINAL" == *endAction) { - animation.SetEndAction( Animation::BAKE_FINAL ); + animation.SetEndAction(Animation::BAKE_FINAL); } } - if( OptionalString endAction = constant.IsString( IsChild(child, "disconnectAction" ) ) ) + if(OptionalString endAction = constant.IsString(IsChild(child, "disconnectAction"))) { if("BAKE" == *endAction) { - animation.SetDisconnectAction( Animation::BAKE ); + animation.SetDisconnectAction(Animation::BAKE); } else if("DISCARD" == *endAction) { - animation.SetDisconnectAction( Animation::DISCARD ); + animation.SetDisconnectAction(Animation::DISCARD); } else if("BAKE_FINAL" == *endAction) { - animation.SetDisconnectAction( Animation::BAKE_FINAL ); + animation.SetDisconnectAction(Animation::BAKE_FINAL); } } - OptionalChild propertiesNode = IsChild(child, "properties" ); + OptionalChild propertiesNode = IsChild(child, "properties"); if(propertiesNode) { const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd(); - for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& pKeyChild = *iter; - OptionalString actorName( constant.IsString( IsChild(pKeyChild.second, "actor" ) ) ); - OptionalString property( constant.IsString( IsChild(pKeyChild.second, "property" ) ) ); - DALI_ASSERT_ALWAYS( actorName && "Animation must specify actor name" ); + OptionalString actorName(constant.IsString(IsChild(pKeyChild.second, "actor"))); + OptionalString property(constant.IsString(IsChild(pKeyChild.second, "property"))); + DALI_ASSERT_ALWAYS(actorName && "Animation must specify actor name"); - Handle targetHandle = searchActor.FindChildByName( *actorName ); - DALI_ASSERT_ALWAYS( targetHandle && "Actor must exist for property" ); + Handle targetHandle = searchActor.FindChildByName(*actorName); + DALI_ASSERT_ALWAYS(targetHandle && "Actor must exist for property"); Property::Value propValue; Property::Index propIndex = Property::INVALID_INDEX; - if( property ) + if(property) { - propIndex = targetHandle.GetPropertyIndex( *property ); + propIndex = targetHandle.GetPropertyIndex(*property); // if the property is not found from the (actor) handle, try to downcast it to renderable actor // to allow animating shader uniforms - if( propIndex == Property::INVALID_INDEX ) + if(propIndex == Property::INVALID_INDEX) { - DALI_SCRIPT_WARNING( "Cannot find property on object\n" ); - continue; + DALI_SCRIPT_WARNING("Cannot find property on object\n"); + continue; } } // these are the defaults - AlphaFunction alphaFunction( AlphaFunction::DEFAULT ); - TimePeriod timePeriod( 0.f ); + AlphaFunction alphaFunction(AlphaFunction::DEFAULT); + TimePeriod timePeriod(0.f); - OptionalChild timeChild = IsChild( pKeyChild.second, "timePeriod" ); + OptionalChild timeChild = IsChild(pKeyChild.second, "timePeriod"); - if( timeChild ) + if(timeChild) { - timePeriod = GetTimePeriod( *timeChild, constant ); + timePeriod = GetTimePeriod(*timeChild, constant); } - durationSum = std::max( durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds ); + durationSum = std::max(durationSum, timePeriod.delaySeconds + timePeriod.durationSeconds); - if( OptionalString alphaChild = constant.IsString( IsChild(pKeyChild.second, "alphaFunction" ) ) ) + if(OptionalString alphaChild = constant.IsString(IsChild(pKeyChild.second, "alphaFunction"))) { - alphaFunction = GetAlphaFunction( *alphaChild ); + alphaFunction = GetAlphaFunction(*alphaChild); } - if( OptionalChild keyFrameChild = IsChild(pKeyChild.second, "keyFrames") ) + if(OptionalChild keyFrameChild = IsChild(pKeyChild.second, "keyFrames")) { - DALI_ASSERT_ALWAYS( property && "Animation must specify a property name" ); - Property prop = Property( targetHandle, propIndex ); + DALI_ASSERT_ALWAYS(property && "Animation must specify a property name"); + Property prop = Property(targetHandle, propIndex); KeyFrames keyframes = KeyFrames::New(); const TreeNode::ConstIterator endIter = (*keyFrameChild).CEnd(); - for( TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*keyFrameChild).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& kfKeyChild = *iter; - OptionalFloat kfProgress = constant.IsFloat( IsChild(kfKeyChild.second, "progress" ) ); - DALI_ASSERT_ALWAYS( kfProgress && "Key frame entry must have 'progress'" ); + OptionalFloat kfProgress = constant.IsFloat(IsChild(kfKeyChild.second, "progress")); + DALI_ASSERT_ALWAYS(kfProgress && "Key frame entry must have 'progress'"); - OptionalChild kfValue = IsChild( kfKeyChild.second, "value" ); - DALI_ASSERT_ALWAYS( kfValue && "Key frame entry must have 'value'" ); + OptionalChild kfValue = IsChild(kfKeyChild.second, "value"); + DALI_ASSERT_ALWAYS(kfValue && "Key frame entry must have 'value'"); try { - propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *kfValue ); + propValue = GetPropertyValue(prop.object.GetPropertyType(prop.propertyIndex), *kfValue); } catch(...) { - DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n", - (*property).c_str(), - PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex)) ); + DALI_LOG_WARNING("Property:'%s' type does not match value type '%s'\n", + (*property).c_str(), + PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex))); throw; } - AlphaFunction kfAlphaFunction( AlphaFunction::DEFAULT ); - if( OptionalString alphaFuncStr = constant.IsString( IsChild(pKeyChild.second, "alphaFunction") ) ) + AlphaFunction kfAlphaFunction(AlphaFunction::DEFAULT); + if(OptionalString alphaFuncStr = constant.IsString(IsChild(pKeyChild.second, "alphaFunction"))) { - kfAlphaFunction = GetAlphaFunction( *alphaFuncStr ); + kfAlphaFunction = GetAlphaFunction(*alphaFuncStr); } - keyframes.Add( *kfProgress, propValue, kfAlphaFunction ); + keyframes.Add(*kfProgress, propValue, kfAlphaFunction); } - if( timeChild ) + if(timeChild) { - animation.AnimateBetween( prop, keyframes, alphaFunction, timePeriod ); + animation.AnimateBetween(prop, keyframes, alphaFunction, timePeriod); } else { - animation.AnimateBetween( prop, keyframes, alphaFunction ); + animation.AnimateBetween(prop, keyframes, alphaFunction); } } - else if( OptionalString pathChild = IsString(pKeyChild.second, "path") ) + else if(OptionalString pathChild = IsString(pKeyChild.second, "path")) { //Get path Path path = builder->GetPath(*pathChild); - if( path ) + if(path) { //Get forward vector if specified - Vector3 forward( 0.0f, 0.0f, 0.0f ); - OptionalVector3 forwardProperty = constant.IsVector3( IsChild(pKeyChild.second, "forward" ) ); - if( forwardProperty ) + Vector3 forward(0.0f, 0.0f, 0.0f); + OptionalVector3 forwardProperty = constant.IsVector3(IsChild(pKeyChild.second, "forward")); + if(forwardProperty) { forward = *forwardProperty; } - Actor actor = Actor::DownCast( targetHandle ); - if( actor ) + Actor actor = Actor::DownCast(targetHandle); + if(actor) { - if( timeChild ) + if(timeChild) { - animation.Animate( actor, path, forward, alphaFunction, timePeriod ); + animation.Animate(actor, path, forward, alphaFunction, timePeriod); } else { - animation.Animate( actor, path, forward, alphaFunction ); + animation.Animate(actor, path, forward, alphaFunction); } - } } else { //Path not found - DALI_SCRIPT_WARNING( "Cannot find animation path '%s'\n", (*pathChild).c_str() ); + DALI_SCRIPT_WARNING("Cannot find animation path '%s'\n", (*pathChild).c_str()); } } else { - DALI_ASSERT_ALWAYS( property && "Animation must specify a property name" ); + DALI_ASSERT_ALWAYS(property && "Animation must specify a property name"); - Property prop = Property( targetHandle, propIndex ); + Property prop = Property(targetHandle, propIndex); try { - propValue = GetPropertyValue( prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value") ); + propValue = GetPropertyValue(prop.object.GetPropertyType(prop.propertyIndex), *IsChild(pKeyChild.second, "value")); } catch(...) { - DALI_LOG_WARNING( "Property:'%s' type does not match value type '%s'\n", (*property).c_str(), - PropertyTypes::GetName( prop.object.GetPropertyType(prop.propertyIndex) ) ); + DALI_LOG_WARNING("Property:'%s' type does not match value type '%s'\n", (*property).c_str(), PropertyTypes::GetName(prop.object.GetPropertyType(prop.propertyIndex))); throw; } - if( OptionalBoolean relative = constant.IsBoolean( IsChild(pKeyChild.second, "relative") ) ) + if(OptionalBoolean relative = constant.IsBoolean(IsChild(pKeyChild.second, "relative"))) { - if( timeChild ) + if(timeChild) { - animation.AnimateBy( prop, propValue, alphaFunction, timePeriod ); + animation.AnimateBy(prop, propValue, alphaFunction, timePeriod); } else { - animation.AnimateBy( prop, propValue, alphaFunction ); + animation.AnimateBy(prop, propValue, alphaFunction); } } else { - if( timeChild ) + if(timeChild) { - animation.AnimateTo( prop, propValue, alphaFunction, timePeriod ); + animation.AnimateTo(prop, propValue, alphaFunction, timePeriod); } else { - animation.AnimateTo( prop, propValue, alphaFunction ); + animation.AnimateTo(prop, propValue, alphaFunction); } } } } } - if( !duration ) + if(!duration) { - animation.SetDuration( durationSum ); + animation.SetDuration(durationSum); } return animation; } -Animation CreateAnimation( const TreeNode& child, Builder* const builder ) +Animation CreateAnimation(const TreeNode& child, Builder* const builder) { Replacement replacement; - return CreateAnimation( child, replacement, Stage::GetCurrent().GetRootLayer(), builder ); + return CreateAnimation(child, replacement, Stage::GetCurrent().GetRootLayer(), builder); } } // namespace Internal @@ -397,4 +390,3 @@ Animation CreateAnimation( const TreeNode& child, Builder* const builder ) } // namespace Toolkit } // namespace Dali - diff --git a/dali-toolkit/internal/builder/builder-impl-debug.cpp b/dali-toolkit/internal/builder/builder-impl-debug.cpp index 2e89d71..d543669 100644 --- a/dali-toolkit/internal/builder/builder-impl-debug.cpp +++ b/dali-toolkit/internal/builder/builder-impl-debug.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. @@ -15,11 +15,11 @@ */ #ifdef DEBUG_ENABLED +#include #include #include -#include -#include #include +#include namespace Dali { @@ -27,16 +27,16 @@ namespace Toolkit { namespace Internal { - -void LogTree( const Toolkit::JsonParser& parser ) +void LogTree(const Toolkit::JsonParser& parser) { - if( OptionalChild constants = IsChild(parser.GetRoot(), "constants") ) + if(OptionalChild constants = IsChild(parser.GetRoot(), "constants")) { for(TreeNode::ConstIterator iter = (*constants).CBegin(); - iter != (*constants).CEnd(); ++iter) + iter != (*constants).CEnd(); + ++iter) { - if( ( (*iter).first && strcmp( (*iter).first, "DUMP_TREE" ) == 0 ) || - ( (*iter).second.GetType() == TreeNode::STRING && strcmp( (*iter).second.GetString(), "DUMP_TREE" ) == 0 ) ) + if(((*iter).first && strcmp((*iter).first, "DUMP_TREE") == 0) || + ((*iter).second.GetType() == TreeNode::STRING && strcmp((*iter).second.GetString(), "DUMP_TREE") == 0)) { std::ostringstream oss; parser.Write(oss, 2); @@ -46,7 +46,7 @@ void LogTree( const Toolkit::JsonParser& parser ) } } -std::string PropertyValueToString( const Property::Value& value ) +std::string PropertyValueToString(const Property::Value& value) { std::ostringstream oss; oss << value; @@ -54,8 +54,8 @@ std::string PropertyValueToString( const Property::Value& value ) return oss.str(); } -} // Internal -} // Toolkit -} // Dali +} // namespace Internal +} // namespace Toolkit +} // namespace Dali #endif // DEBUG_ENABLED diff --git a/dali-toolkit/internal/builder/builder-impl.cpp b/dali-toolkit/internal/builder/builder-impl.cpp index 88c51b6..9ddab28 100644 --- a/dali-toolkit/internal/builder/builder-impl.cpp +++ b/dali-toolkit/internal/builder/builder-impl.cpp @@ -22,6 +22,10 @@ #include #include +#include +#include +#include +#include #include #include #include @@ -30,15 +34,11 @@ #include #include #include -#include -#include -#include -#include // INTERNAL INCLUDES -#include #include #include +#include #include #include @@ -50,28 +50,24 @@ namespace Dali { - namespace Toolkit { - namespace Internal { class Replacement; -extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder ); +extern Animation CreateAnimation(const TreeNode& child, const Replacement& replacements, const Dali::Actor searchRoot, Builder* const builder); -extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); - -extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); +extern Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); +extern Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); #if defined(DEBUG_ENABLED) -Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT"); +Integration::Log::Filter* gFilterScript = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_SCRIPT"); #endif namespace { - #define TOKEN_STRING(x) #x const std::string KEYNAME_ACTORS = "actors"; @@ -89,23 +85,22 @@ const std::string KEYNAME_TRANSITIONS = "transitions"; const std::string KEYNAME_TYPE = "type"; const std::string KEYNAME_VISUALS = "visuals"; -const std::string PROPERTIES = "properties"; +const std::string PROPERTIES = "properties"; const std::string ANIMATABLE_PROPERTIES = "animatableProperties"; typedef std::vector TreeNodeList; - -bool GetMappingKey( const std::string& str, std::string& key ) +bool GetMappingKey(const std::string& str, std::string& key) { - bool result = false; - std::string test( str ); - if( ! test.empty() ) + bool result = false; + std::string test(str); + if(!test.empty()) { - if( test.at(0) == '<' ) + if(test.at(0) == '<') { - if( test.at(test.length()-1) == '>' ) + if(test.at(test.length() - 1) == '>') { - key = test.substr( 1, test.length()-2 ); + key = test.substr(1, test.length() - 2); result = true; } } @@ -120,27 +115,27 @@ bool GetMappingKey( const std::string& str, std::string& key ) * style The style array to begin the collection from * styleList The style list to add nodes to apply */ -void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList ) +void CollectAllStyles(const TreeNode& stylesCollection, const TreeNode& style, TreeNodeList& styleList) { // style is an array of style names - if( TreeNode::ARRAY == style.GetType() ) + if(TreeNode::ARRAY == style.GetType()) { for(TreeNode::ConstIterator iter = style.CBegin(); iter != style.CEnd(); ++iter) { - if( OptionalString styleName = IsString( (*iter).second ) ) + if(OptionalString styleName = IsString((*iter).second)) { - if( OptionalChild node = IsChildIgnoreCase( stylesCollection, *styleName) ) + if(OptionalChild node = IsChildIgnoreCase(stylesCollection, *styleName)) { - styleList.push_back( &(*node) ); + styleList.push_back(&(*node)); - OptionalChild subStyle = IsChild( *node, KEYNAME_INHERIT ); - if( ! subStyle ) + OptionalChild subStyle = IsChild(*node, KEYNAME_INHERIT); + if(!subStyle) { - subStyle = IsChild( *node, KEYNAME_STYLES ); + subStyle = IsChild(*node, KEYNAME_STYLES); } - if( subStyle ) + if(subStyle) { - CollectAllStyles( stylesCollection, *subStyle, styleList ); + CollectAllStyles(stylesCollection, *subStyle, styleList); } } } @@ -148,12 +143,10 @@ void CollectAllStyles( const TreeNode& stylesCollection, const TreeNode& style, } } - -} // namespace anon - +} // namespace Builder::Builder() -: mSlotDelegate( this ) +: mSlotDelegate(this) { mParser = Dali::Toolkit::JsonParser::New(); @@ -169,56 +162,56 @@ Builder::Builder() AddConstants(defaultConstants); } -void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::UIFormat format ) +void Builder::LoadFromString(std::string const& data, Dali::Toolkit::Builder::UIFormat format) { // parser to get constants and includes only Dali::Toolkit::JsonParser parser = Dali::Toolkit::JsonParser::New(); - if( !parser.Parse( data ) ) + if(!parser.Parse(data)) { - DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n", - parser.GetErrorLineNumber(), - parser.GetErrorColumn(), - parser.GetErrorDescription().c_str() ); + DALI_LOG_WARNING("JSON Parse Error:%d:%d:'%s'\n", + parser.GetErrorLineNumber(), + parser.GetErrorColumn(), + parser.GetErrorDescription().c_str()); DALI_ASSERT_ALWAYS(!"Cannot parse JSON"); } else { // load constant map (allows the user to override the constants in the json after loading) - LoadConstants( *parser.GetRoot(), mReplacementMap ); + LoadConstants(*parser.GetRoot(), mReplacementMap); // load configuration map - LoadConfiguration( *parser.GetRoot(), mConfigurationMap ); + LoadConfiguration(*parser.GetRoot(), mConfigurationMap); // merge includes - if( OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES) ) + if(OptionalChild includes = IsChild(*parser.GetRoot(), KEYNAME_INCLUDES)) { - Replacement replacer( mReplacementMap ); + Replacement replacer(mReplacementMap); for(TreeNode::ConstIterator iter = (*includes).CBegin(); iter != (*includes).CEnd(); ++iter) { - OptionalString filename = replacer.IsString( (*iter).second ); + OptionalString filename = replacer.IsString((*iter).second); - if( filename ) + if(filename) { #if defined(DEBUG_ENABLED) DALI_SCRIPT_VERBOSE("Loading Include '%s'\n", (*filename).c_str()); #endif - LoadFromString( GetFileContents(*filename) ); + LoadFromString(GetFileContents(*filename)); } } } - if( mParser.Parse( data ) ) + if(mParser.Parse(data)) { // Drop the styles and get them to be rebuilt against the new parse tree as required. mStyles.Clear(); } else { - DALI_LOG_WARNING( "JSON Parse Error:%d:%d:'%s'\n", - mParser.GetErrorLineNumber(), - mParser.GetErrorColumn(), - mParser.GetErrorDescription().c_str() ); + DALI_LOG_WARNING("JSON Parse Error:%d:%d:'%s'\n", + mParser.GetErrorLineNumber(), + mParser.GetErrorColumn(), + mParser.GetErrorDescription().c_str()); DALI_ASSERT_ALWAYS(!"Cannot parse JSON"); } @@ -230,12 +223,12 @@ void Builder::LoadFromString( std::string const& data, Dali::Toolkit::Builder::U DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Cannot parse JSON"); } -void Builder::AddConstants( const Property::Map& map ) +void Builder::AddConstants(const Property::Map& map) { - mReplacementMap.Merge( map ); + mReplacementMap.Merge(map); } -void Builder::AddConstant( const std::string& key, const Property::Value& value ) +void Builder::AddConstant(const std::string& key, const Property::Value& value) { mReplacementMap[key] = value; } @@ -250,10 +243,10 @@ const Property::Map& Builder::GetConstants() const return mReplacementMap; } -const Property::Value& Builder::GetConstant( const std::string& key ) const +const Property::Value& Builder::GetConstant(const std::string& key) const { - Property::Value* match = mReplacementMap.Find( key ); - if( match ) + Property::Value* match = mReplacementMap.Find(key); + if(match) { return (*match); } @@ -264,107 +257,107 @@ const Property::Value& Builder::GetConstant( const std::string& key ) const } } -Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor ) +Animation Builder::CreateAnimation(const std::string& animationName, const Property::Map& map, Dali::Actor sourceActor) { Replacement replacement(map, mReplacementMap); - return CreateAnimation( animationName, replacement, sourceActor); + return CreateAnimation(animationName, replacement, sourceActor); } -Animation Builder::CreateAnimation( const std::string& animationName, const Property::Map& map ) +Animation Builder::CreateAnimation(const std::string& animationName, const Property::Map& map) { Replacement replacement(map, mReplacementMap); - return CreateAnimation( animationName, replacement, Stage::GetCurrent().GetRootLayer() ); + return CreateAnimation(animationName, replacement, Stage::GetCurrent().GetRootLayer()); } -Animation Builder::CreateAnimation( const std::string& animationName, Dali::Actor sourceActor ) +Animation Builder::CreateAnimation(const std::string& animationName, Dali::Actor sourceActor) { - Replacement replacement( mReplacementMap ); + Replacement replacement(mReplacementMap); - return CreateAnimation( animationName, replacement, sourceActor ); + return CreateAnimation(animationName, replacement, sourceActor); } -Animation Builder::CreateAnimation( const std::string& animationName ) +Animation Builder::CreateAnimation(const std::string& animationName) { - Replacement replacement( mReplacementMap ); + Replacement replacement(mReplacementMap); - return CreateAnimation( animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer() ); + return CreateAnimation(animationName, replacement, Dali::Stage::GetCurrent().GetRootLayer()); } -BaseHandle Builder::Create( const std::string& templateName ) +BaseHandle Builder::Create(const std::string& templateName) { - Replacement replacement( mReplacementMap ); - return Create( templateName, replacement ); + Replacement replacement(mReplacementMap); + return Create(templateName, replacement); } -BaseHandle Builder::Create( const std::string& templateName, const Property::Map& map ) +BaseHandle Builder::Create(const std::string& templateName, const Property::Map& map) { - Replacement replacement( map, mReplacementMap ); - return Create( templateName, replacement ); + Replacement replacement(map, mReplacementMap); + return Create(templateName, replacement); } -BaseHandle Builder::CreateFromJson( const std::string& json ) +BaseHandle Builder::CreateFromJson(const std::string& json) { BaseHandle ret; // merge in new template, hoping no one else has one named '@temp@' std::string newTemplate = - std::string("{\"templates\":{\"@temp@\":") + \ - json + \ + std::string("{\"templates\":{\"@temp@\":") + + json + std::string("}}"); - if( mParser.Parse(newTemplate) ) + if(mParser.Parse(newTemplate)) { - Replacement replacement( mReplacementMap ); - ret = Create( "@temp@", replacement ); + Replacement replacement(mReplacementMap); + ret = Create("@temp@", replacement); } return ret; } -bool Builder::ApplyFromJson( Handle& handle, const std::string& json ) +bool Builder::ApplyFromJson(Handle& handle, const std::string& json) { bool ret = false; // merge new style, hoping no one else has one named '@temp@' std::string newStyle = - std::string("{\"styles\":{\"@temp@\":") + \ - json + \ + std::string("{\"styles\":{\"@temp@\":") + + json + std::string("}}"); - if( mParser.Parse(newStyle) ) + if(mParser.Parse(newStyle)) { - Replacement replacement( mReplacementMap ); - ret = ApplyStyle( "@temp@", handle, replacement ); + Replacement replacement(mReplacementMap); + ret = ApplyStyle("@temp@", handle, replacement); } return ret; } -bool Builder::ApplyStyle( const std::string& styleName, Handle& handle ) +bool Builder::ApplyStyle(const std::string& styleName, Handle& handle) { - Replacement replacer( mReplacementMap ); - return ApplyStyle( styleName, handle, replacer ); + Replacement replacer(mReplacementMap); + return ApplyStyle(styleName, handle, replacer); } -bool Builder::LookupStyleName( const std::string& styleName ) +bool Builder::LookupStyleName(const std::string& styleName) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); - OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES ); - OptionalChild style = IsChildIgnoreCase( *styles, styleName ); + OptionalChild styles = IsChild(*mParser.GetRoot(), KEYNAME_STYLES); + OptionalChild style = IsChildIgnoreCase(*styles, styleName); - if( styles && style ) + if(styles && style) { return true; } return false; } -const StylePtr Builder::GetStyle( const std::string& styleName ) +const StylePtr Builder::GetStyle(const std::string& styleName) { - const StylePtr* style = mStyles.FindConst( styleName ); + const StylePtr* style = mStyles.FindConst(styleName); - if( style==NULL ) + if(style == NULL) { return StylePtr(NULL); } @@ -374,50 +367,50 @@ const StylePtr Builder::GetStyle( const std::string& styleName ) } } -void Builder::AddActors( Actor toActor ) +void Builder::AddActors(Actor toActor) { // 'stage' is the default/by convention section to add from - AddActors( "stage", toActor ); + AddActors("stage", toActor); } -void Builder::AddActors( const std::string §ionName, Actor toActor ) +void Builder::AddActors(const std::string& sectionName, Actor toActor) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); Property::Map overrideMap; - Replacement replacements(overrideMap, mReplacementMap); + Replacement replacements(overrideMap, mReplacementMap); OptionalChild add = IsChild(*mParser.GetRoot(), sectionName); - if( add ) + if(add) { - for( TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = (*add).CBegin(); iter != (*add).CEnd(); ++iter) { // empty actor adds directly to the stage - BaseHandle baseHandle = DoCreate( *mParser.GetRoot(), (*iter).second, Actor(), replacements ); - Actor actor = Actor::DownCast(baseHandle); + BaseHandle baseHandle = DoCreate(*mParser.GetRoot(), (*iter).second, Actor(), replacements); + Actor actor = Actor::DownCast(baseHandle); if(actor) { - toActor.Add( actor ); + toActor.Add(actor); } } // if were adding the 'stage' section then also check for a render task called stage // to add automatically - if( "stage" == sectionName ) + if("stage" == sectionName) { - if( OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks") ) + if(OptionalChild renderTasks = IsChild(*mParser.GetRoot(), "renderTasks")) { - if( OptionalChild tasks = IsChild(*renderTasks, "stage") ) + if(OptionalChild tasks = IsChild(*renderTasks, "stage")) { - CreateRenderTask( "stage" ); + CreateRenderTask("stage"); } } } } } -void Builder::CreateRenderTask( const std::string &name ) +void Builder::CreateRenderTask(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); @@ -434,10 +427,10 @@ void Builder::CreateRenderTask( const std::string &name ) // to setup task zero and onwards. Although this does overwrite // the properties of the current task. // - if( OptionalChild renderTask = IsChild(*tasks, name ) ) + if(OptionalChild renderTask = IsChild(*tasks, name)) { - RenderTaskList list = stage.GetRenderTaskList(); - unsigned int start = list.GetTaskCount(); + RenderTaskList list = stage.GetRenderTaskList(); + unsigned int start = list.GetTaskCount(); RenderTask task; if(0 == start) @@ -449,61 +442,61 @@ void Builder::CreateRenderTask( const std::string &name ) } TreeNode::ConstIterator iter = (*renderTask).CBegin(); - task = list.GetTask( start - 1 ); + task = list.GetTask(start - 1); - SetupTask( task, (*iter).second, constant ); + SetupTask(task, (*iter).second, constant); ++iter; - for(; iter != (*renderTask).CEnd(); ++iter ) + for(; iter != (*renderTask).CEnd(); ++iter) { task = list.CreateTask(); - SetupTask( task, (*iter).second, constant ); + SetupTask(task, (*iter).second, constant); } } } } -Path Builder::GetPath( const std::string& name ) +Path Builder::GetPath(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); Path ret; - PathLut::const_iterator iter( mPathLut.find( name ) ); - if( iter != mPathLut.end() ) + PathLut::const_iterator iter(mPathLut.find(name)); + if(iter != mPathLut.end()) { ret = iter->second; } else { - if( OptionalChild paths = IsChild( *mParser.GetRoot(), "paths") ) + if(OptionalChild paths = IsChild(*mParser.GetRoot(), "paths")) { - if( OptionalChild path = IsChild( *paths, name ) ) + if(OptionalChild path = IsChild(*paths, name)) { //points property - if( OptionalChild pointsProperty = IsChild( *path, "points") ) + if(OptionalChild pointsProperty = IsChild(*path, "points")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { ret = Path::New(); - ret.SetProperty( Path::Property::POINTS, points); + ret.SetProperty(Path::Property::POINTS, points); //controlPoints property - if( OptionalChild pointsProperty = IsChild( *path, "controlPoints") ) + if(OptionalChild pointsProperty = IsChild(*path, "controlPoints")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { - ret.SetProperty( Path::Property::CONTROL_POINTS, points); + ret.SetProperty(Path::Property::CONTROL_POINTS, points); } } else { //Curvature float curvature(0.25f); - if( OptionalFloat pointsProperty = IsFloat( *path, "curvature") ) + if(OptionalFloat pointsProperty = IsFloat(*path, "curvature")) { curvature = *pointsProperty; } @@ -511,31 +504,30 @@ Path Builder::GetPath( const std::string& name ) } //Add the new path to the hash table for paths - mPathLut[ name ] = ret; + mPathLut[name] = ret; } } else { //Interpolation points not specified - DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Interpolation points not specified for path '%s'\n", name.c_str()); } } - } } return ret; } -PathConstrainer Builder::GetPathConstrainer( const std::string& name ) +PathConstrainer Builder::GetPathConstrainer(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); //Search the pathConstrainer in the LUT - size_t count( mPathConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mPathConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mPathConstrainerLut[i].name == name ) + if(mPathConstrainerLut[i].name == name) { //PathConstrainer has already been created return mPathConstrainerLut[i].pathConstrainer; @@ -544,62 +536,62 @@ PathConstrainer Builder::GetPathConstrainer( const std::string& name ) //Create a new PathConstrainer PathConstrainer ret; - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild pathConstrainer = IsChild( *constrainers, name ) ) + if(OptionalChild pathConstrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*pathConstrainer, "type"))); if(!constrainerType) { - DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str()); } - else if( *constrainerType == "PathConstrainer") + else if(*constrainerType == "PathConstrainer") { //points property - if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "points") ) + if(OptionalChild pointsProperty = IsChild(*pathConstrainer, "points")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { ret = PathConstrainer::New(); - ret.SetProperty( PathConstrainer::Property::POINTS, points); + ret.SetProperty(PathConstrainer::Property::POINTS, points); //controlPoints property - if( OptionalChild pointsProperty = IsChild( *pathConstrainer, "controlPoints") ) + if(OptionalChild pointsProperty = IsChild(*pathConstrainer, "controlPoints")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { - ret.SetProperty( PathConstrainer::Property::CONTROL_POINTS, points); + ret.SetProperty(PathConstrainer::Property::CONTROL_POINTS, points); } //Forward vector - OptionalVector3 forward( IsVector3( IsChild(*pathConstrainer, "forward" ) ) ); - if( forward ) + OptionalVector3 forward(IsVector3(IsChild(*pathConstrainer, "forward"))); + if(forward) { - ret.SetProperty( PathConstrainer::Property::FORWARD, *forward); + ret.SetProperty(PathConstrainer::Property::FORWARD, *forward); } //Add the new constrainer to the vector of PathConstrainer - PathConstrainerEntry entry = {name,ret}; - mPathConstrainerLut.push_back( entry ); + PathConstrainerEntry entry = {name, ret}; + mPathConstrainerLut.push_back(entry); } else { //Control points not specified - DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Control points not specified for pathConstrainer '%s'\n", name.c_str()); } } } else { //Interpolation points not specified - DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Interpolation points not specified for pathConstrainer '%s'\n", name.c_str()); } } else { - DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer '%s' is not a PathConstrainer\n", name.c_str()); } } } @@ -607,21 +599,20 @@ PathConstrainer Builder::GetPathConstrainer( const std::string& name ) return ret; } - -bool Builder::IsPathConstrainer( const std::string& name ) +bool Builder::IsPathConstrainer(const std::string& name) { - size_t count( mPathConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mPathConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mPathConstrainerLut[i].name == name ) + if(mPathConstrainerLut[i].name == name) { return true; } } - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild constrainer = IsChild( *constrainers, name ) ) + if(OptionalChild constrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*constrainer, "type"))); if(!constrainerType) @@ -630,22 +621,22 @@ bool Builder::IsPathConstrainer( const std::string& name ) } else { - return *constrainerType == "PathConstrainer"; + return *constrainerType == "PathConstrainer"; } } } return false; } -Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name ) +Dali::LinearConstrainer Builder::GetLinearConstrainer(const std::string& name) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); //Search the LinearConstrainer in the LUT - size_t count( mLinearConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mLinearConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mLinearConstrainerLut[i].name == name ) + if(mLinearConstrainerLut[i].name == name) { //LinearConstrainer has already been created return mLinearConstrainerLut[i].linearConstrainer; @@ -654,49 +645,49 @@ Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name ) //Create a new LinearConstrainer LinearConstrainer ret; - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild linearConstrainer = IsChild( *constrainers, name ) ) + if(OptionalChild linearConstrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*linearConstrainer, "type"))); if(!constrainerType) { - DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer type not specified for constrainer '%s'\n", name.c_str()); } - else if( *constrainerType == "LinearConstrainer") + else if(*constrainerType == "LinearConstrainer") { //points property - if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "value") ) + if(OptionalChild pointsProperty = IsChild(*linearConstrainer, "value")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { ret = Dali::LinearConstrainer::New(); - ret.SetProperty( LinearConstrainer::Property::VALUE, points); + ret.SetProperty(LinearConstrainer::Property::VALUE, points); //controlPoints property - if( OptionalChild pointsProperty = IsChild( *linearConstrainer, "progress") ) + if(OptionalChild pointsProperty = IsChild(*linearConstrainer, "progress")) { Dali::Property::Value points(Property::ARRAY); - if( DeterminePropertyFromNode( *pointsProperty, Property::ARRAY, points ) ) + if(DeterminePropertyFromNode(*pointsProperty, Property::ARRAY, points)) { - ret.SetProperty( LinearConstrainer::Property::PROGRESS, points); + ret.SetProperty(LinearConstrainer::Property::PROGRESS, points); } } //Add the new constrainer to vector of LinearConstrainer - LinearConstrainerEntry entry = {name,ret}; - mLinearConstrainerLut.push_back( entry ); + LinearConstrainerEntry entry = {name, ret}; + mLinearConstrainerLut.push_back(entry); } } else { //Interpolation points not specified - DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str() ); + DALI_SCRIPT_WARNING("Values not specified for LinearConstrainer '%s'\n", name.c_str()); } } else { - DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str() ); + DALI_SCRIPT_WARNING("Constrainer '%s' is not a LinearConstrainer\n", name.c_str()); } } } @@ -704,21 +695,21 @@ Dali::LinearConstrainer Builder::GetLinearConstrainer( const std::string& name ) return ret; } -bool Builder::IsLinearConstrainer( const std::string& name ) +bool Builder::IsLinearConstrainer(const std::string& name) { // Search the LinearConstrainer in the LUT - size_t count( mLinearConstrainerLut.size() ); - for( size_t i(0); i!=count; ++i ) + size_t count(mLinearConstrainerLut.size()); + for(size_t i(0); i != count; ++i) { - if( mLinearConstrainerLut[i].name == name ) + if(mLinearConstrainerLut[i].name == name) { return true; } } - if( OptionalChild constrainers = IsChild( *mParser.GetRoot(), "constrainers") ) + if(OptionalChild constrainers = IsChild(*mParser.GetRoot(), "constrainers")) { - if( OptionalChild constrainer = IsChild( *constrainers, name ) ) + if(OptionalChild constrainer = IsChild(*constrainers, name)) { OptionalString constrainerType(IsString(IsChild(*constrainer, "type"))); if(!constrainerType) @@ -727,7 +718,7 @@ bool Builder::IsLinearConstrainer( const std::string& name ) } else { - return *constrainerType == "LinearConstrainer"; + return *constrainerType == "LinearConstrainer"; } } } @@ -748,54 +739,55 @@ Builder::~Builder() { } -void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap ) +void Builder::LoadConfiguration(const TreeNode& root, Property::Map& intoMap) { Replacement replacer(intoMap); - if( OptionalChild constants = IsChild(root, "config") ) + if(OptionalChild constants = IsChild(root, "config")) { for(TreeNode::ConstIterator iter = (*constants).CBegin(); - iter != (*constants).CEnd(); ++iter) + iter != (*constants).CEnd(); + ++iter) { Dali::Property::Value property; - if( (*iter).second.GetName() ) + if((*iter).second.GetName()) { - DeterminePropertyFromNode( (*iter).second, property, replacer ); + DeterminePropertyFromNode((*iter).second, property, replacer); // If config is string, find constant and replace it to original value. - if( (*iter).second.GetType() == TreeNode::STRING ) + if((*iter).second.GetType() == TreeNode::STRING) { std::string stringConfigValue; - if( property.Get( stringConfigValue ) ) + if(property.Get(stringConfigValue)) { std::size_t pos = 0; - while( pos < stringConfigValue.size() ) + while(pos < stringConfigValue.size()) { // If we can't find "{","}" pair in stringConfigValue, will out loop. - std::size_t leftPos = stringConfigValue.find( "{", pos ); - if( leftPos != std::string::npos ) + std::size_t leftPos = stringConfigValue.find("{", pos); + if(leftPos != std::string::npos) { - std::size_t rightPos = stringConfigValue.find( "}", pos+1 ); + std::size_t rightPos = stringConfigValue.find("}", pos + 1); - if( rightPos != std::string::npos ) + if(rightPos != std::string::npos) { // If we find "{","}" pair but can't find matched constant // try to find other "{","}" pair after current left position. - pos = leftPos+1; + pos = leftPos + 1; - for( uint32_t i = 0; i < mReplacementMap.Count() ; i++ ) + for(uint32_t i = 0; i < mReplacementMap.Count(); i++) { Property::Key constant = mReplacementMap.GetKeyAt(i); // Compare string which is between "{" and "}" with constant string // If they are same, change string in stringConfigValue to mapped constant value. - if ( 0 == stringConfigValue.compare( leftPos+1, rightPos-leftPos-1, constant.stringKey ) ) + if(0 == stringConfigValue.compare(leftPos + 1, rightPos - leftPos - 1, constant.stringKey)) { std::string replaceString; - mReplacementMap.GetValue(i).Get( replaceString ); + mReplacementMap.GetValue(i).Get(replaceString); - stringConfigValue.replace( leftPos, rightPos-leftPos+1, replaceString ); + stringConfigValue.replace(leftPos, rightPos - leftPos + 1, replaceString); pos = leftPos + replaceString.size(); break; } @@ -813,87 +805,88 @@ void Builder::LoadConfiguration( const TreeNode& root, Property::Map& intoMap ) pos = stringConfigValue.size(); } } - property = Property::Value( stringConfigValue ); + property = Property::Value(stringConfigValue); } } - intoMap[ (*iter).second.GetName() ] = property; + intoMap[(*iter).second.GetName()] = property; } } } } -void Builder::LoadConstants( const TreeNode& root, Property::Map& intoMap ) +void Builder::LoadConstants(const TreeNode& root, Property::Map& intoMap) { Replacement replacer(intoMap); - if( OptionalChild constants = IsChild(root, "constants") ) + if(OptionalChild constants = IsChild(root, "constants")) { for(TreeNode::ConstIterator iter = (*constants).CBegin(); - iter != (*constants).CEnd(); ++iter) + iter != (*constants).CEnd(); + ++iter) { Dali::Property::Value property; - if( (*iter).second.GetName() ) + if((*iter).second.GetName()) { #if defined(DEBUG_ENABLED) DALI_SCRIPT_VERBOSE("Constant set from json '%s'\n", (*iter).second.GetName()); #endif - DeterminePropertyFromNode( (*iter).second, property, replacer ); - intoMap[ (*iter).second.GetName() ] = property; + DeterminePropertyFromNode((*iter).second, property, replacer); + intoMap[(*iter).second.GetName()] = property; } } } #if defined(DEBUG_ENABLED) - Property::Value* iter = intoMap.Find( "CONFIG_SCRIPT_LOG_LEVEL" ); - if( iter && iter->GetType() == Property::STRING ) + Property::Value* iter = intoMap.Find("CONFIG_SCRIPT_LOG_LEVEL"); + if(iter && iter->GetType() == Property::STRING) { - std::string logLevel( iter->Get< std::string >() ); - if( logLevel == "NoLogging" ) + std::string logLevel(iter->Get()); + if(logLevel == "NoLogging") { - gFilterScript->SetLogLevel( Integration::Log::NoLogging ); + gFilterScript->SetLogLevel(Integration::Log::NoLogging); } - else if( logLevel == "Concise" ) + else if(logLevel == "Concise") { - gFilterScript->SetLogLevel( Integration::Log::Concise ); + gFilterScript->SetLogLevel(Integration::Log::Concise); } - else if( logLevel == "General" ) + else if(logLevel == "General") { - gFilterScript->SetLogLevel( Integration::Log::General ); + gFilterScript->SetLogLevel(Integration::Log::General); } - else if( logLevel == "Verbose" ) + else if(logLevel == "Verbose") { - gFilterScript->SetLogLevel( Integration::Log::Verbose ); + gFilterScript->SetLogLevel(Integration::Log::Verbose); } } #endif } -Animation Builder::CreateAnimation( const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor ) +Animation Builder::CreateAnimation(const std::string& animationName, const Replacement& replacement, Dali::Actor sourceActor) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); Animation anim; - if( OptionalChild animations = IsChild(*mParser.GetRoot(), "animations") ) + if(OptionalChild animations = IsChild(*mParser.GetRoot(), "animations")) { - if( OptionalChild animation = IsChild(*animations, animationName) ) + if(OptionalChild animation = IsChild(*animations, animationName)) { - anim = Dali::Toolkit::Internal::CreateAnimation( *animation, replacement, sourceActor, this ); + anim = Dali::Toolkit::Internal::CreateAnimation(*animation, replacement, sourceActor, this); } else { - DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed\n", animationName.c_str() ); + DALI_SCRIPT_WARNING("Request for Animation called '%s' failed\n", animationName.c_str()); } } else { - DALI_SCRIPT_WARNING( "Request for Animation called '%s' failed (no animation section)\n", animationName.c_str() ); + DALI_SCRIPT_WARNING("Request for Animation called '%s' failed (no animation section)\n", animationName.c_str()); } return anim; } -BaseHandle Builder::Create( const std::string& templateName, const Replacement& constant ) +BaseHandle Builder::Create(const std::string& templateName, const Replacement& constant) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); @@ -901,7 +894,7 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& OptionalChild templates = IsChild(*mParser.GetRoot(), KEYNAME_TEMPLATES); - if( !templates ) + if(!templates) { DALI_SCRIPT_WARNING("No template section found to CreateFromTemplate\n"); } @@ -914,7 +907,7 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& } else { - OptionalString type = constant.IsString( IsChild(*childTemplate, KEYNAME_TYPE) ); + OptionalString type = constant.IsString(IsChild(*childTemplate, KEYNAME_TYPE)); if(!type) { @@ -922,7 +915,7 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& } else { - baseHandle = DoCreate( *mParser.GetRoot(), *childTemplate, Actor(), constant ); + baseHandle = DoCreate(*mParser.GetRoot(), *childTemplate, Actor(), constant); } } } @@ -935,31 +928,30 @@ BaseHandle Builder::Create( const std::string& templateName, const Replacement& * If parent given and an actor type was created then add it to the parent and * recursively add nodes children. */ -BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, - Actor parent, const Replacement& replacements ) +BaseHandle Builder::DoCreate(const TreeNode& root, const TreeNode& node, Actor parent, const Replacement& replacements) { - BaseHandle baseHandle; - TypeInfo typeInfo; + BaseHandle baseHandle; + TypeInfo typeInfo; const TreeNode* templateNode = NULL; - if( OptionalString typeName = IsString(node, KEYNAME_TYPE) ) + if(OptionalString typeName = IsString(node, KEYNAME_TYPE)) { - typeInfo = TypeRegistry::Get().GetTypeInfo( *typeName ); + typeInfo = TypeRegistry::Get().GetTypeInfo(*typeName); - if( !typeInfo ) + if(!typeInfo) { // a template name is also allowed inplace of the type name - OptionalChild templates = IsChild( root, KEYNAME_TEMPLATES); + OptionalChild templates = IsChild(root, KEYNAME_TEMPLATES); - if( templates ) + if(templates) { - if( OptionalChild isTemplate = IsChild( *templates, *typeName ) ) + if(OptionalChild isTemplate = IsChild(*templates, *typeName)) { templateNode = &(*isTemplate); - if( OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE) ) + if(OptionalString templateTypeName = IsString(*templateNode, KEYNAME_TYPE)) { - typeInfo = TypeRegistry::Get().GetTypeInfo( *templateTypeName ); + typeInfo = TypeRegistry::Get().GetTypeInfo(*templateTypeName); } } } @@ -972,13 +964,12 @@ BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, } else { - baseHandle = typeInfo.CreateInstance(); - Handle handle = Handle::DownCast(baseHandle); - Actor actor = Actor::DownCast(handle); + baseHandle = typeInfo.CreateInstance(); + Handle handle = Handle::DownCast(baseHandle); + Actor actor = Actor::DownCast(handle); if(handle) { - DALI_SCRIPT_VERBOSE("Create:%s\n", typeInfo.GetName().c_str()); #if defined(DEBUG_ENABLED) @@ -990,52 +981,52 @@ BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, if(actor) { - DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty< int >( Actor::Property::ID )); + DALI_SCRIPT_VERBOSE(" Is Actor id=%d\n", actor.GetProperty(Actor::Property::ID)); } - Toolkit::Control control = Toolkit::Control::DownCast(handle); + Toolkit::Control control = Toolkit::Control::DownCast(handle); if(control) { - DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty< int >( Actor::Property::ID )); + DALI_SCRIPT_VERBOSE(" Is Control id=%d\n", actor.GetProperty(Actor::Property::ID)); } #endif // DEBUG_ENABLED - if( templateNode ) + if(templateNode) { - ApplyProperties( root, *templateNode, handle, replacements ); + ApplyProperties(root, *templateNode, handle, replacements); - if( OptionalChild actors = IsChild( *templateNode, KEYNAME_ACTORS ) ) + if(OptionalChild actors = IsChild(*templateNode, KEYNAME_ACTORS)) { - for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter ) + for(TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter) { - DoCreate( root, (*iter).second, actor, replacements ); + DoCreate(root, (*iter).second, actor, replacements); } } } - if( actor ) + if(actor) { // add children of all the styles - if( OptionalChild actors = IsChild( node, KEYNAME_ACTORS ) ) + if(OptionalChild actors = IsChild(node, KEYNAME_ACTORS)) { - for( TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter ) + for(TreeConstIter iter = (*actors).CBegin(); iter != (*actors).CEnd(); ++iter) { - DoCreate( root, (*iter).second, actor, replacements ); + DoCreate(root, (*iter).second, actor, replacements); } } // apply style on top as they need the children to exist - ApplyAllStyleProperties( root, node, actor, replacements ); + ApplyAllStyleProperties(root, node, actor, replacements); // then add to parent - if( parent ) + if(parent) { - parent.Add( actor ); + parent.Add(actor); } } else { - ApplyProperties( root, node, handle, replacements ); + ApplyProperties(root, node, handle, replacements); } } else @@ -1047,46 +1038,46 @@ BaseHandle Builder::DoCreate( const TreeNode& root, const TreeNode& node, return baseHandle; } -void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replacement& constant ) +void Builder::SetupTask(RenderTask& task, const TreeNode& node, const Replacement& constant) { const Stage& stage = Stage::GetCurrent(); - Layer root = stage.GetRootLayer(); + Layer root = stage.GetRootLayer(); - if( OptionalString s = constant.IsString( IsChild(node, "sourceActor") ) ) + if(OptionalString s = constant.IsString(IsChild(node, "sourceActor"))) { Actor actor = root.FindChildByName(*s); if(actor) { - task.SetSourceActor( actor ); + task.SetSourceActor(actor); } else { - DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str() ); + DALI_SCRIPT_WARNING("Cannot find source actor on stage for render task called '%s'\n", (*s).c_str()); } } - if( OptionalString s = constant.IsString( IsChild(node, "cameraActor") ) ) + if(OptionalString s = constant.IsString(IsChild(node, "cameraActor"))) { - CameraActor actor = CameraActor::DownCast( root.FindChildByName(*s) ); + CameraActor actor = CameraActor::DownCast(root.FindChildByName(*s)); if(actor) { - task.SetCameraActor( actor ); + task.SetCameraActor(actor); } else { - DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str() ); + DALI_SCRIPT_WARNING("Cannot find camera actor on stage for render task called '%s'\n", (*s).c_str()); } } - if( OptionalString s = constant.IsString( IsChild(node, "screenToFrameBufferFunction") ) ) + if(OptionalString s = constant.IsString(IsChild(node, "screenToFrameBufferFunction"))) { if("DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION" == *s) { - task.SetScreenToFrameBufferFunction( RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION ); + task.SetScreenToFrameBufferFunction(RenderTask::DEFAULT_SCREEN_TO_FRAMEBUFFER_FUNCTION); } else if("FULLSCREEN_FRAMEBUFFER_FUNCTION" == *s) { - task.SetScreenToFrameBufferFunction( RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION ); + task.SetScreenToFrameBufferFunction(RenderTask::FULLSCREEN_FRAMEBUFFER_FUNCTION); } else { @@ -1095,21 +1086,21 @@ void Builder::SetupTask( RenderTask& task, const TreeNode& node, const Replaceme } // other setup is via the property system - SetProperties( node, task, constant ); + SetProperties(node, task, constant); } -bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Replacement& replacement ) +bool Builder::ApplyStyle(const std::string& styleName, Handle& handle, const Replacement& replacement) { DALI_ASSERT_ALWAYS(mParser.GetRoot() && "Builder script not loaded"); - OptionalChild styles = IsChild( *mParser.GetRoot(), KEYNAME_STYLES ); + OptionalChild styles = IsChild(*mParser.GetRoot(), KEYNAME_STYLES); - std::string styleNameLower(styleName); - OptionalChild style = IsChildIgnoreCase( *styles, styleNameLower ); + std::string styleNameLower(styleName); + OptionalChild style = IsChildIgnoreCase(*styles, styleNameLower); - if( styles && style ) + if(styles && style) { - ApplyAllStyleProperties( *mParser.GetRoot(), *style, handle, replacement ); + ApplyAllStyleProperties(*mParser.GetRoot(), *style, handle, replacement); return true; } else @@ -1118,38 +1109,37 @@ bool Builder::ApplyStyle( const std::string& styleName, Handle& handle, const Re } } -void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& node, - Dali::Handle& handle, const Replacement& constant ) +void Builder::ApplyAllStyleProperties(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant) { const char* styleName = node.GetName(); StylePtr style = Style::New(); StylePtr* matchedStyle = NULL; - if( styleName ) + if(styleName) { - matchedStyle = mStyles.Find( styleName ); - if( ! matchedStyle ) + matchedStyle = mStyles.Find(styleName); + if(!matchedStyle) { - OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES); + OptionalChild styleNodes = IsChild(root, KEYNAME_STYLES); OptionalChild inheritFromNode = IsChild(node, KEYNAME_INHERIT); - if( !inheritFromNode ) + if(!inheritFromNode) { - inheritFromNode = IsChild( node, KEYNAME_STYLES ); + inheritFromNode = IsChild(node, KEYNAME_STYLES); } - if( styleNodes ) + if(styleNodes) { - if( inheritFromNode ) + if(inheritFromNode) { TreeNodeList additionalStyleNodes; - CollectAllStyles( *styleNodes, *inheritFromNode, additionalStyleNodes ); + CollectAllStyles(*styleNodes, *inheritFromNode, additionalStyleNodes); #if defined(DEBUG_ENABLED) for(TreeNode::ConstIterator iter = (*inheritFromNode).CBegin(); iter != (*inheritFromNode).CEnd(); ++iter) { - if( OptionalString styleName = IsString( (*iter).second ) ) + if(OptionalString styleName = IsString((*iter).second)) { DALI_SCRIPT_VERBOSE("Style Applied '%s'\n", (*styleName).c_str()); } @@ -1159,123 +1149,123 @@ void Builder::ApplyAllStyleProperties( const TreeNode& root, const TreeNode& nod // a style may have other styles, which has other styles etc so we apply in reverse by convention. for(TreeNodeList::reverse_iterator iter = additionalStyleNodes.rbegin(); iter != additionalStyleNodes.rend(); ++iter) { - RecordStyle( style, *(*iter), handle, constant ); - ApplySignals( root, *(*iter), handle ); - ApplyStylesByActor( root, *(*iter), handle, constant ); + RecordStyle(style, *(*iter), handle, constant); + ApplySignals(root, *(*iter), handle); + ApplyStylesByActor(root, *(*iter), handle, constant); } } - RecordStyle( style, node, handle, constant ); - mStyles.Add( styleName, style ); // shallow copy + RecordStyle(style, node, handle, constant); + mStyles.Add(styleName, style); // shallow copy matchedStyle = &style; } } } - if( matchedStyle ) + if(matchedStyle) { - StylePtr style( *matchedStyle ); + StylePtr style(*matchedStyle); Dictionary instancedProperties; - style->ApplyVisualsAndPropertiesRecursively( handle, instancedProperties ); + style->ApplyVisualsAndPropertiesRecursively(handle, instancedProperties); } else // If there were no styles, instead set properties { - SetProperties( node, handle, constant ); + SetProperties(node, handle, constant); } - ApplySignals( root, node, handle ); - ApplyStylesByActor( root, node, handle, constant ); + ApplySignals(root, node, handle); + ApplyStylesByActor(root, node, handle, constant); } -void Builder::RecordStyle( StylePtr style, - const TreeNode& node, - Dali::Handle& handle, - const Replacement& replacements ) +void Builder::RecordStyle(StylePtr style, + const TreeNode& node, + Dali::Handle& handle, + const Replacement& replacements) { // With repeated calls, accumulate inherited states, visuals and properties // but override any with same name - for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter) { const TreeNode::KeyNodePair& keyValue = *iter; - std::string key( keyValue.first ); - if( key == KEYNAME_STATES ) + std::string key(keyValue.first); + if(key == KEYNAME_STATES) { const TreeNode& states = keyValue.second; - if( states.GetType() != TreeNode::OBJECT ) + if(states.GetType() != TreeNode::OBJECT) { - DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str() ); + DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON object\n", key.c_str()); continue; } - for( TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = states.CBegin(); iter != states.CEnd(); ++iter) { const TreeNode& stateNode = (*iter).second; - const char* stateName = stateNode.GetName(); - if( stateNode.GetType() != TreeNode::OBJECT ) + const char* stateName = stateNode.GetName(); + if(stateNode.GetType() != TreeNode::OBJECT) { - DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON object\n", stateName ); + DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON object\n", stateName); continue; } - StylePtr* stylePtr = style->subStates.Find( stateName ); - if( stylePtr ) + StylePtr* stylePtr = style->subStates.Find(stateName); + if(stylePtr) { StylePtr style(*stylePtr); - RecordStyle( style, stateNode, handle, replacements ); + RecordStyle(style, stateNode, handle, replacements); } else { StylePtr subState = Style::New(); - RecordStyle( subState, stateNode, handle, replacements ); - style->subStates.Add( stateName, subState ); + RecordStyle(subState, stateNode, handle, replacements); + style->subStates.Add(stateName, subState); } } } - else if( key == KEYNAME_VISUALS ) + else if(key == KEYNAME_VISUALS) { - for( TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = keyValue.second.CBegin(); iter != keyValue.second.CEnd(); ++iter) { // Each key in this table should be a property name matching a visual. const TreeNode::KeyNodePair& visual = *iter; - Dali::Property::Value property(Property::MAP); - if( DeterminePropertyFromNode( visual.second, Property::MAP, property, replacements ) ) + Dali::Property::Value property(Property::MAP); + if(DeterminePropertyFromNode(visual.second, Property::MAP, property, replacements)) { - Property::Map* mapPtr = style->visuals.Find( visual.first ); - if( mapPtr ) + Property::Map* mapPtr = style->visuals.Find(visual.first); + if(mapPtr) { // Override existing visuals mapPtr->Clear(); - mapPtr->Merge( *property.GetMap() ); + mapPtr->Merge(*property.GetMap()); } else { Property::Map* map = property.GetMap(); - if( map ) + if(map) { - style->visuals.Add( visual.first, *map ); + style->visuals.Add(visual.first, *map); } } } } } - else if( key == KEYNAME_ENTRY_TRANSITION ) + else if(key == KEYNAME_ENTRY_TRANSITION) { - RecordTransitionData( keyValue, style->entryTransition, replacements ); + RecordTransitionData(keyValue, style->entryTransition, replacements); } - else if( key == KEYNAME_EXIT_TRANSITION ) + else if(key == KEYNAME_EXIT_TRANSITION) { - RecordTransitionData( keyValue, style->exitTransition, replacements ); + RecordTransitionData(keyValue, style->exitTransition, replacements); } - else if( key == KEYNAME_TRANSITIONS ) + else if(key == KEYNAME_TRANSITIONS) { - RecordTransitions( keyValue, style->transitions, replacements ); + RecordTransitions(keyValue, style->transitions, replacements); } - else if( key == KEYNAME_TYPE || - key == KEYNAME_ACTORS || - key == KEYNAME_SIGNALS || - key == KEYNAME_STYLES || - key == KEYNAME_MAPPINGS || - key == KEYNAME_INHERIT ) + else if(key == KEYNAME_TYPE || + key == KEYNAME_ACTORS || + key == KEYNAME_SIGNALS || + key == KEYNAME_STYLES || + key == KEYNAME_MAPPINGS || + key == KEYNAME_INHERIT) { continue; } @@ -1283,16 +1273,16 @@ void Builder::RecordStyle( StylePtr style, { Property::Index index; Property::Value value; - if( MapToTargetProperty( handle, key, keyValue.second, replacements, index, value ) ) + if(MapToTargetProperty(handle, key, keyValue.second, replacements, index, value)) { - Property::Value* existingValuePtr = style->properties.Find( index ); - if( existingValuePtr != NULL ) + Property::Value* existingValuePtr = style->properties.Find(index); + if(existingValuePtr != NULL) { *existingValuePtr = value; // Overwrite existing property. } else { - style->properties.Add( index, value ); + style->properties.Add(index, value); } } } @@ -1301,108 +1291,104 @@ void Builder::RecordStyle( StylePtr style, void Builder::RecordTransitions( const TreeNode::KeyNodePair& keyValue, - Property::Array& value, - const Replacement& replacements ) + Property::Array& value, + const Replacement& replacements) { //@todo add new transitions to style.transitions // override existing transitions. A transition matches on target & property name const TreeNode& node = keyValue.second; - if( node.GetType() == TreeNode::ARRAY ) + if(node.GetType() == TreeNode::ARRAY) { Dali::Property::Value property(Property::ARRAY); - if( DeterminePropertyFromNode( node, Property::ARRAY, property, replacements ) ) + if(DeterminePropertyFromNode(node, Property::ARRAY, property, replacements)) { value = *property.GetArray(); } } - else if( node.GetType() == TreeNode::OBJECT ) + else if(node.GetType() == TreeNode::OBJECT) { Dali::Property::Value property(Property::MAP); - if( DeterminePropertyFromNode( node, Property::MAP, property, replacements ) ) + if(DeterminePropertyFromNode(node, Property::MAP, property, replacements)) { Property::Array propertyArray; - propertyArray.Add( property ); + propertyArray.Add(property); value = propertyArray; } } else { - DALI_LOG_WARNING( "RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first ); + DALI_LOG_WARNING("RecordStyle() Node \"%s\" is not a JSON array or object\n", keyValue.first); } } void Builder::RecordTransitionData( const TreeNode::KeyNodePair& keyValue, - Toolkit::TransitionData& transitionData, - const Replacement& replacements ) + Toolkit::TransitionData& transitionData, + const Replacement& replacements) { const TreeNode& node = keyValue.second; - if( node.GetType() == TreeNode::ARRAY ) + if(node.GetType() == TreeNode::ARRAY) { Dali::Property::Value property(Property::ARRAY); - if( DeterminePropertyFromNode( keyValue.second, Property::ARRAY, property, replacements ) ) + if(DeterminePropertyFromNode(keyValue.second, Property::ARRAY, property, replacements)) { - transitionData = Toolkit::TransitionData::New( *property.GetArray() ); + transitionData = Toolkit::TransitionData::New(*property.GetArray()); } } - else if( node.GetType() == TreeNode::OBJECT ) + else if(node.GetType() == TreeNode::OBJECT) { Dali::Property::Value property(Property::MAP); - if( DeterminePropertyFromNode( keyValue.second, Property::MAP, property, replacements ) ) + if(DeterminePropertyFromNode(keyValue.second, Property::MAP, property, replacements)) { - transitionData = Toolkit::TransitionData::New( *property.GetMap() ); + transitionData = Toolkit::TransitionData::New(*property.GetMap()); } } } - // Set properties from node on handle. -void Builder::ApplyProperties( const TreeNode& root, const TreeNode& node, - Dali::Handle& handle, const Replacement& constant ) +void Builder::ApplyProperties(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant) { - SetProperties( node, handle, constant ); - ApplySignals( root, node, handle ); + SetProperties(node, handle, constant); + ApplySignals(root, node, handle); } -void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle ) +void Builder::ApplySignals(const TreeNode& root, const TreeNode& node, Dali::Handle& handle) { Actor actor = Actor::DownCast(handle); - if( actor ) + if(actor) { // add signals - SetupSignalAction( mSlotDelegate.GetConnectionTracker(), root, node, actor, this ); - SetupPropertyNotification( mSlotDelegate.GetConnectionTracker(), root, node, actor, this ); + SetupSignalAction(mSlotDelegate.GetConnectionTracker(), root, node, actor, this); + SetupPropertyNotification(mSlotDelegate.GetConnectionTracker(), root, node, actor, this); } } - // Appling by style helper // use FindChildByName() to apply properties referenced in KEYNAME_ACTORS in the node -void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node, - Dali::Handle& handle, const Replacement& constant ) +void Builder::ApplyStylesByActor(const TreeNode& root, const TreeNode& node, Dali::Handle& handle, const Replacement& constant) { - if( Dali::Actor actor = Dali::Actor::DownCast( handle ) ) + if(Dali::Actor actor = Dali::Actor::DownCast(handle)) { - if( const TreeNode* actors = node.GetChild( KEYNAME_ACTORS ) ) + if(const TreeNode* actors = node.GetChild(KEYNAME_ACTORS)) { // in a style the actor subtree properties referenced by actor name - for( TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter ) + for(TreeConstIter iter = actors->CBegin(); iter != actors->CEnd(); ++iter) { Dali::Actor foundActor; - if( (*iter).first ) + if((*iter).first) { - foundActor = actor.FindChildByName( (*iter).first ); + foundActor = actor.FindChildByName((*iter).first); } - if( !foundActor ) + if(!foundActor) { DALI_SCRIPT_VERBOSE("Cannot find actor in style application '%s'\n", (*iter).first); } else { DALI_SCRIPT_VERBOSE("Styles applied to actor '%s'\n", (*iter).first); - ApplyProperties( root, (*iter).second, foundActor, constant ); + ApplyProperties(root, (*iter).second, foundActor, constant); } } } @@ -1412,28 +1398,28 @@ void Builder::ApplyStylesByActor( const TreeNode& root, const TreeNode& node, /* * Sets the handle properties found in the tree node */ -void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replacement& constant ) +void Builder::SetProperties(const TreeNode& node, Handle& handle, const Replacement& constant) { - if( handle ) + if(handle) { - for( TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = node.CBegin(); iter != node.CEnd(); ++iter) { const TreeNode::KeyNodePair& keyChild = *iter; - std::string key( keyChild.first ); + std::string key(keyChild.first); // ignore special fields; - if( key == KEYNAME_TYPE || - key == KEYNAME_ACTORS || - key == KEYNAME_SIGNALS || - key == KEYNAME_STYLES || - key == KEYNAME_MAPPINGS || - key == KEYNAME_INHERIT || - key == KEYNAME_STATES || - key == KEYNAME_VISUALS || - key == KEYNAME_ENTRY_TRANSITION || - key == KEYNAME_EXIT_TRANSITION || - key == KEYNAME_TRANSITIONS ) + if(key == KEYNAME_TYPE || + key == KEYNAME_ACTORS || + key == KEYNAME_SIGNALS || + key == KEYNAME_STYLES || + key == KEYNAME_MAPPINGS || + key == KEYNAME_INHERIT || + key == KEYNAME_STATES || + key == KEYNAME_VISUALS || + key == KEYNAME_ENTRY_TRANSITION || + key == KEYNAME_EXIT_TRANSITION || + key == KEYNAME_TRANSITIONS) { continue; } @@ -1441,12 +1427,12 @@ void Builder::SetProperties( const TreeNode& node, Handle& handle, const Replace Property::Index index; Property::Value value; - bool mapped = MapToTargetProperty( handle, key, keyChild.second, constant, index, value ); - if( mapped ) + bool mapped = MapToTargetProperty(handle, key, keyChild.second, constant, index, value); + if(mapped) { - DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str() ); + DALI_SCRIPT_VERBOSE("SetProperty '%s' Index=:%d Value Type=%d Value '%s'\n", key.c_str(), index, value.GetType(), PropertyValueToString(value).c_str()); - handle.SetProperty( index, value ); + handle.SetProperty(index, value); } // Add custom properties @@ -1467,33 +1453,33 @@ bool Builder::MapToTargetProperty( const TreeNode& node, const Replacement& constant, Property::Index& index, - Property::Value& value ) + Property::Value& value) { bool mapped = false; - index = propertyObject.GetPropertyIndex( key ); - if( Property::INVALID_INDEX != index ) + index = propertyObject.GetPropertyIndex(key); + if(Property::INVALID_INDEX != index) { Property::Type type = propertyObject.GetPropertyType(index); // if node.value is a mapping, get the property value from the "mappings" table - if( node.GetType() == TreeNode::STRING ) + if(node.GetType() == TreeNode::STRING) { std::string mappingKey; - if( GetMappingKey( node.GetString(), mappingKey) ) + if(GetMappingKey(node.GetString(), mappingKey)) { - OptionalChild mappingRoot = IsChild( mParser.GetRoot(), KEYNAME_MAPPINGS ); - mapped = GetPropertyMap( *mappingRoot, mappingKey.c_str(), type, value ); + OptionalChild mappingRoot = IsChild(mParser.GetRoot(), KEYNAME_MAPPINGS); + mapped = GetPropertyMap(*mappingRoot, mappingKey.c_str(), type, value); } } - if( ! mapped ) + if(!mapped) { - mapped = DeterminePropertyFromNode( node, type, value, constant ); - if( ! mapped ) + mapped = DeterminePropertyFromNode(node, type, value, constant); + if(!mapped) { // Just determine the property from the node and if it's valid, let the property object handle it - DeterminePropertyFromNode( node, value, constant ); - mapped = ( value.GetType() != Property::NONE ); + DeterminePropertyFromNode(node, value, constant); + mapped = (value.GetType() != Property::NONE); } } } @@ -1504,35 +1490,35 @@ bool Builder::MapToTargetProperty( return mapped; } -bool Builder::GetPropertyMap( const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value ) +bool Builder::GetPropertyMap(const TreeNode& mappingRoot, const char* theKey, Property::Type propertyType, Property::Value& value) { KeyStack keyStack; - return RecursePropertyMap( mappingRoot, keyStack, theKey, propertyType, value ); + return RecursePropertyMap(mappingRoot, keyStack, theKey, propertyType, value); } -bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value ) +bool Builder::RecursePropertyMap(const TreeNode& mappingRoot, KeyStack& keyStack, const char* theKey, Property::Type propertyType, Property::Value& value) { - Replacement replacer( mReplacementMap ); - bool result = false; + Replacement replacer(mReplacementMap); + bool result = false; - keyStack.push_back( theKey ); + keyStack.push_back(theKey); - for( TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter ) + for(TreeNode::ConstIterator iter = mappingRoot.CBegin(); iter != mappingRoot.CEnd(); ++iter) { - std::string aKey( (*iter).first ); - if( aKey.compare( theKey ) == 0 ) + std::string aKey((*iter).first); + if(aKey.compare(theKey) == 0) { - if( propertyType == Property::NONE ) + if(propertyType == Property::NONE) { - DeterminePropertyFromNode( (*iter).second, value, replacer ); + DeterminePropertyFromNode((*iter).second, value, replacer); result = true; } else { - result = DeterminePropertyFromNode( (*iter).second, propertyType, value, replacer ); + result = DeterminePropertyFromNode((*iter).second, propertyType, value, replacer); } - if( result ) + if(result) { ConvertChildValue(mappingRoot, keyStack, value); } @@ -1544,39 +1530,39 @@ bool Builder::RecursePropertyMap( const TreeNode& mappingRoot, KeyStack& keyStac return result; } -bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child ) +bool Builder::ConvertChildValue(const TreeNode& mappingRoot, KeyStack& keyStack, Property::Value& child) { bool result = false; - switch( child.GetType() ) + switch(child.GetType()) { case Property::STRING: { std::string value; - if( child.Get( value ) ) + if(child.Get(value)) { std::string key; - if( GetMappingKey( value, key ) ) + if(GetMappingKey(value, key)) { // Check key for cycles: - result=true; - for( KeyStack::iterator iter = keyStack.begin() ; iter != keyStack.end(); ++iter ) + result = true; + for(KeyStack::iterator iter = keyStack.begin(); iter != keyStack.end(); ++iter) { - if( key.compare(*iter) == 0 ) + if(key.compare(*iter) == 0) { // key is already in stack; stop. DALI_LOG_WARNING("Detected cycle in stylesheet mapping table:%s\n", key.c_str()); - child = Property::Value(""); - result=false; + child = Property::Value(""); + result = false; break; } } - if( result ) + if(result) { // The following call will overwrite the child with the value // from the mapping. - RecursePropertyMap( mappingRoot, keyStack, key.c_str(), Property::NONE, child ); + RecursePropertyMap(mappingRoot, keyStack, key.c_str(), Property::NONE, child); result = true; } } @@ -1587,9 +1573,9 @@ bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack case Property::MAP: { Property::Map* map = child.GetMap(); - if( map ) + if(map) { - for( Property::Map::SizeType i=0; i < map->Count(); ++i ) + for(Property::Map::SizeType i = 0; i < map->Count(); ++i) { Property::Value& child = map->GetValue(i); ConvertChildValue(mappingRoot, keyStack, child); @@ -1601,9 +1587,9 @@ bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack case Property::ARRAY: { Property::Array* array = child.GetArray(); - if( array ) + if(array) { - for( Property::Array::SizeType i=0; i < array->Count(); ++i ) + for(Property::Array::SizeType i = 0; i < array->Count(); ++i) { Property::Value& child = array->GetElementAt(i); ConvertChildValue(mappingRoot, keyStack, child); @@ -1620,28 +1606,26 @@ bool Builder::ConvertChildValue( const TreeNode& mappingRoot, KeyStack& keyStack return result; } -void Builder::SetCustomProperties( const TreeNode& node, Handle& handle, const Replacement& constant, - const std::string& childName, Property::AccessMode accessMode ) +void Builder::SetCustomProperties(const TreeNode& node, Handle& handle, const Replacement& constant, const std::string& childName, Property::AccessMode accessMode) { // Add custom properties - if( OptionalChild customPropertiesChild = IsChild(node, childName) ) + if(OptionalChild customPropertiesChild = IsChild(node, childName)) { - const TreeNode& customPropertiesNode = *customPropertiesChild; - const TreeConstIter endIter = customPropertiesNode.CEnd(); - for( TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter ) + const TreeNode& customPropertiesNode = *customPropertiesChild; + const TreeConstIter endIter = customPropertiesNode.CEnd(); + for(TreeConstIter iter = customPropertiesNode.CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& keyChild = *iter; - std::string key( keyChild.first ); - Property::Value value; - DeterminePropertyFromNode( keyChild.second, value, constant ); + std::string key(keyChild.first); + Property::Value value; + DeterminePropertyFromNode(keyChild.second, value, constant); // Register/Set property. - handle.RegisterProperty( key, value, accessMode ); + handle.RegisterProperty(key, value, accessMode); } } } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/builder-set-property.cpp b/dali-toolkit/internal/builder/builder-set-property.cpp index 367c527..d00ca12 100644 --- a/dali-toolkit/internal/builder/builder-set-property.cpp +++ b/dali-toolkit/internal/builder/builder-set-property.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. @@ -16,26 +16,23 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include -#include +#include #include +#include #include namespace Dali { - namespace Toolkit { - namespace Internal { - /** * A property value type can be forced when its unknown by a disambiguation convention in the json * ie "myarray": [1,2,3,4] ; would be a vector but @@ -45,61 +42,61 @@ namespace Internal * @param replacement The user overriding constant map * @return True if child contained a disambiguated string that could be converted. */ -bool Disambiguated(const TreeNode& child, +bool Disambiguated(const TreeNode& child, Dali::Property::Value& value, - const Replacement& replacement ) + const Replacement& replacement) { - OptionalString childType = IsString( IsChild(child, "typeCast") ); - OptionalChild childValue = IsChild(child, "value"); + OptionalString childType = IsString(IsChild(child, "typeCast")); + OptionalChild childValue = IsChild(child, "value"); - if( childType && childValue && (2 == child.Size()) ) + if(childType && childValue && (2 == child.Size())) { // this case allows disambiguation but normally the type is guessed // 2 == child.count() is an extra check as the user could have a user dictionary/map with // type-cast and value keys. If they do then a work around is to add a bogus key to not run this case. if(*childType == "boolean") { - return DeterminePropertyFromNode( *childValue, Dali::Property::BOOLEAN, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::BOOLEAN, value, replacement); } else if(*childType == "float") { - return DeterminePropertyFromNode( *childValue, Dali::Property::FLOAT, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::FLOAT, value, replacement); } else if(*childType == "vector2") { - return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR2, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR2, value, replacement); } else if(*childType == "vector3") { - return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR3, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR3, value, replacement); } else if(*childType == "vector4") { - return DeterminePropertyFromNode( *childValue, Dali::Property::VECTOR4, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::VECTOR4, value, replacement); } else if(*childType == "rotation") { - return DeterminePropertyFromNode( *childValue, Dali::Property::ROTATION, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::ROTATION, value, replacement); } else if(*childType == "rect") { - return DeterminePropertyFromNode( *childValue, Dali::Property::RECTANGLE, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::RECTANGLE, value, replacement); } else if(*childType == "string") { - return DeterminePropertyFromNode( *childValue, Dali::Property::STRING, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::STRING, value, replacement); } else if(*childType == "map") { - return DeterminePropertyFromNode( *childValue, Dali::Property::MAP, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::MAP, value, replacement); } else if(*childType == "array") { - return DeterminePropertyFromNode( *childValue, Dali::Property::ARRAY, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::ARRAY, value, replacement); } else if(*childType == "extents") { - return DeterminePropertyFromNode( *childValue, Dali::Property::EXTENTS, value, replacement); + return DeterminePropertyFromNode(*childValue, Dali::Property::EXTENTS, value, replacement); } } @@ -107,15 +104,13 @@ bool Disambiguated(const TreeNode& child, return false; } - -bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Property::Value& value) +bool DeterminePropertyFromNode(const TreeNode& node, Property::Type type, Property::Value& value) { Replacement noReplacement; - return DeterminePropertyFromNode( node, type, value, noReplacement ); + return DeterminePropertyFromNode(node, type, value, noReplacement); } -bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Property::Value& value, - const Replacement& replacer ) +bool DeterminePropertyFromNode(const TreeNode& node, Property::Type type, Property::Value& value, const Replacement& replacer) { bool done = false; @@ -123,110 +118,110 @@ bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Prope { case Property::BOOLEAN: { - if( OptionalBoolean v = replacer.IsBoolean(node) ) + if(OptionalBoolean v = replacer.IsBoolean(node)) { value = *v; - done = true; + done = true; } break; } case Property::FLOAT: { - if( OptionalFloat v = replacer.IsFloat(node) ) + if(OptionalFloat v = replacer.IsFloat(node)) { value = *v; - done = true; + done = true; } break; } case Property::INTEGER: { - if( OptionalInteger v = replacer.IsInteger(node) ) + if(OptionalInteger v = replacer.IsInteger(node)) { value = *v; - done = true; + done = true; } break; } case Property::VECTOR2: { - if( OptionalVector2 v = replacer.IsVector2(node) ) + if(OptionalVector2 v = replacer.IsVector2(node)) { value = *v; - done = true; + done = true; } break; } case Property::VECTOR3: { - if( OptionalVector3 v = replacer.IsVector3(node) ) + if(OptionalVector3 v = replacer.IsVector3(node)) { value = *v; - done = true; + done = true; } break; } case Property::VECTOR4: { - if( OptionalVector4 v = replacer.IsVector4(node) ) + if(OptionalVector4 v = replacer.IsVector4(node)) { value = *v; - done = true; + done = true; } - else if( OptionalString s = replacer.IsString(node) ) + else if(OptionalString s = replacer.IsString(node)) { Vector4 color; - done = ConvertStringToColor( *s, color ); + done = ConvertStringToColor(*s, color); value = color; } - else if( TreeNode::OBJECT == node.GetType() ) + else if(TreeNode::OBJECT == node.GetType()) { // check for "r", "g" and "b" child color component nodes - OptionalInteger r = replacer.IsInteger( IsChild(node, "r") ); - OptionalInteger g = replacer.IsInteger( IsChild(node, "g") ); - OptionalInteger b = replacer.IsInteger( IsChild(node, "b") ); - if( r && g && b ) + OptionalInteger r = replacer.IsInteger(IsChild(node, "r")); + OptionalInteger g = replacer.IsInteger(IsChild(node, "g")); + OptionalInteger b = replacer.IsInteger(IsChild(node, "b")); + if(r && g && b) { - float red( (*r) * (1.0f/255.0f) ); - float green( (*g) * (1.0f/255.0f) ); - float blue( (*b) * (1.0f/255.0f) ); + float red((*r) * (1.0f / 255.0f)); + float green((*g) * (1.0f / 255.0f)); + float blue((*b) * (1.0f / 255.0f)); // check for optional "a" (alpha) node, default to fully opaque if it is not found. - float alpha( 1.0f ); - OptionalInteger a = replacer.IsInteger( IsChild(node, "a") ); - if( a ) + float alpha(1.0f); + OptionalInteger a = replacer.IsInteger(IsChild(node, "a")); + if(a) { - alpha = (*a) * (1.0f/255.0f); + alpha = (*a) * (1.0f / 255.0f); } - value = Vector4( red, green, blue, alpha ); - done = true; + value = Vector4(red, green, blue, alpha); + done = true; } } break; } case Property::MATRIX3: { - if( OptionalMatrix3 v = replacer.IsMatrix3(node) ) + if(OptionalMatrix3 v = replacer.IsMatrix3(node)) { value = *v; - done = true; + done = true; } break; } case Property::MATRIX: { - if( OptionalMatrix v = replacer.IsMatrix(node) ) + if(OptionalMatrix v = replacer.IsMatrix(node)) { value = *v; - done = true; + done = true; } break; } case Property::RECTANGLE: { - if( OptionalRect v = replacer.IsRect(node) ) + if(OptionalRect v = replacer.IsRect(node)) { value = *v; - done = true; + done = true; } break; } @@ -234,99 +229,99 @@ bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Prope { if(4 == node.Size()) { - if( OptionalVector4 ov = replacer.IsVector4(node) ) + if(OptionalVector4 ov = replacer.IsVector4(node)) { const Vector4& v = *ov; // angle, axis as per spec value = Quaternion(Radian(Degree(v[3])), - Vector3(v[0],v[1],v[2])); - done = true; + Vector3(v[0], v[1], v[2])); + done = true; } } else { // degrees Euler as per spec - if( OptionalVector3 v = replacer.IsVector3(node) ) + if(OptionalVector3 v = replacer.IsVector3(node)) { value = Quaternion(Radian(Degree((*v).x)), Radian(Degree((*v).y)), Radian(Degree((*v).z))); - done = true; + done = true; } } break; } case Property::STRING: { - if( OptionalString v = replacer.IsString(node) ) + if(OptionalString v = replacer.IsString(node)) { value = *v; - done = true; + done = true; } break; } case Property::ARRAY: { - if( replacer.IsArray( node, value ) ) + if(replacer.IsArray(node, value)) { done = true; } else if(node.Size()) { - value = Property::Value(Property::ARRAY); + value = Property::Value(Property::ARRAY); Property::Array* array = value.GetArray(); - unsigned int i = 0; + unsigned int i = 0; TreeNode::ConstIterator iter(node.CBegin()); - if( array ) + if(array) { - for( ; i < node.Size(); ++i, ++iter) + for(; i < node.Size(); ++i, ++iter) { Property::Value childValue; - DeterminePropertyFromNode( (*iter).second, childValue, replacer ); - array->PushBack( childValue ); + DeterminePropertyFromNode((*iter).second, childValue, replacer); + array->PushBack(childValue); } - done = ( array->Count() == node.Size() ); + done = (array->Count() == node.Size()); } } break; } case Property::MAP: { - if( replacer.IsMap( node, value ) ) + if(replacer.IsMap(node, value)) { done = true; } else if(node.Size()) { - value = Property::Value(Property::MAP); + value = Property::Value(Property::MAP); Property::Map* map = value.GetMap(); - unsigned int i = 0; + unsigned int i = 0; TreeNode::ConstIterator iter(node.CBegin()); - if( map ) + if(map) { - for( ; i < node.Size(); ++i, ++iter) + for(; i < node.Size(); ++i, ++iter) { Property::Value childValue; - DeterminePropertyFromNode( (*iter).second, childValue, replacer ); - map->Insert( (*iter).first, childValue ); + DeterminePropertyFromNode((*iter).second, childValue, replacer); + map->Insert((*iter).first, childValue); } - done = ( map->Count() == node.Size() ); + done = (map->Count() == node.Size()); } } break; } case Property::EXTENTS: { - if( OptionalExtents v = replacer.IsExtents(node) ) + if(OptionalExtents v = replacer.IsExtents(node)) { value = *v; - done = true; + done = true; } break; } @@ -339,22 +334,20 @@ bool DeterminePropertyFromNode( const TreeNode& node, Property::Type type, Prope return done; } -void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value ) +void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value) { Replacement replacer; - DeterminePropertyFromNode( node, value, replacer ); + DeterminePropertyFromNode(node, value, replacer); } -void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, - const Replacement& replacer ) +void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value, const Replacement& replacer) { - TreeNode::NodeType nodeType = node.GetType(); // Some values are ambiguous as we have no Property::Type but can be disambiguated in the JSON. // Currently Rotations and Rectangle must always be disambiguated when a type isn't available - if( !Disambiguated( node, value, replacer ) ) + if(!Disambiguated(node, value, replacer)) { bool done = false; @@ -365,75 +358,75 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, // 4) If no match still; Create as array. // First handle nodes with children. - if( node.Size() ) + if(node.Size()) { // Handle array types. - if( nodeType == TreeNode::ARRAY ) + if(nodeType == TreeNode::ARRAY) { // our current heuristic for deciding an array is actually a vector and not say a map // is to check if the values are all floats bool allNumbers = true; - for( TreeConstIter iter = node.CBegin(); iter != node.CEnd(); ++iter ) + for(TreeConstIter iter = node.CBegin(); iter != node.CEnd(); ++iter) { - OptionalFloat checkFloat = IsFloat( ( *iter ).second ); - if( !checkFloat ) + OptionalFloat checkFloat = IsFloat((*iter).second); + if(!checkFloat) { allNumbers = false; break; } } - if( allNumbers ) + if(allNumbers) { // prefer finding vectors over presuming composite Property::Array... - if( OptionalMatrix v = IsMatrix( node ) ) + if(OptionalMatrix v = IsMatrix(node)) { value = *v; - done = true; + done = true; } - else if( OptionalMatrix3 v = IsMatrix3( node ) ) + else if(OptionalMatrix3 v = IsMatrix3(node)) { value = *v; - done = true; + done = true; } - else if( OptionalVector4 v = IsVector4( node ) ) + else if(OptionalVector4 v = IsVector4(node)) { value = *v; - done = true; + done = true; } - else if( OptionalVector3 v = IsVector3( node ) ) + else if(OptionalVector3 v = IsVector3(node)) { value = *v; - done = true; + done = true; } - else if( OptionalVector2 v = IsVector2( node ) ) + else if(OptionalVector2 v = IsVector2(node)) { value = *v; - done = true; + done = true; } - else if( 4 == node.Size() ) + else if(4 == node.Size()) { - if( OptionalVector4 v = IsVector4( node ) ) + if(OptionalVector4 v = IsVector4(node)) { value = *v; - done = true; + done = true; } } } } } // if node.size() - else if( ( nodeType != TreeNode::OBJECT ) && ( nodeType != TreeNode::ARRAY ) ) + else if((nodeType != TreeNode::OBJECT) && (nodeType != TreeNode::ARRAY)) { // no children so either one of bool, float, integer, string - OptionalBoolean aBool = replacer.IsBoolean( node ); - OptionalInteger anInt = replacer.IsInteger( node ); - OptionalFloat aFloat = replacer.IsFloat( node ); - OptionalString aString = replacer.IsString( node ); + OptionalBoolean aBool = replacer.IsBoolean(node); + OptionalInteger anInt = replacer.IsInteger(node); + OptionalFloat aFloat = replacer.IsFloat(node); + OptionalString aString = replacer.IsString(node); - if( aBool ) + if(aBool) { // a bool is also an int but here we presume int - if( anInt ) + if(anInt) { value = *anInt; } @@ -448,11 +441,11 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, // {"value":"123"} // {"value":123} // This means we can't have a string with purely numeric content without disambiguation. - if( aFloat ) + if(aFloat) { value = *aFloat; } - else if( anInt ) + else if(anInt) { value = *anInt; } @@ -466,27 +459,27 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, } // if( node.size() ) // If we have not created a value so far, attempt to create a Map or Array. - if( !done ) + if(!done) { // We are guaranteed to have at least one entry as this has been checked already. TreeConstIter containerIterator = node.CBegin(); - TreeConstIter containerEnd = node.CEnd(); + TreeConstIter containerEnd = node.CEnd(); // The TreeNode::OBJECT type implies a Property::Map. - if( nodeType == TreeNode::OBJECT ) + if(nodeType == TreeNode::OBJECT) { // We have a key, treat container as a Map. - value = Property::Value( Property::MAP ); + value = Property::Value(Property::MAP); Property::Map* map = value.GetMap(); - if( map ) + if(map) { // Iterate through container to add all entries. - for( ; containerIterator != containerEnd; ++containerIterator ) + for(; containerIterator != containerEnd; ++containerIterator) { Property::Value childValue; - DeterminePropertyFromNode( ( *containerIterator ).second, childValue, replacer ); - map->Insert( ( *containerIterator ).first, childValue ); + DeterminePropertyFromNode((*containerIterator).second, childValue, replacer); + map->Insert((*containerIterator).first, childValue); } } } @@ -495,25 +488,24 @@ void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value, // We don't have a key, treat container as an array. // Note: We don't check if the node type is array here, as we want to cope with unknowns by creating an array also. // This is the fall-back if no other types could be created. - value = Property::Value( Property::ARRAY ); + value = Property::Value(Property::ARRAY); Property::Array* array = value.GetArray(); - if( array ) + if(array) { // Iterate through container to add all entries. - for( ; containerIterator != containerEnd; ++containerIterator ) + for(; containerIterator != containerEnd; ++containerIterator) { Property::Value childValue; - DeterminePropertyFromNode( ( *containerIterator ).second, childValue, replacer ); - array->PushBack( childValue ); + DeterminePropertyFromNode((*containerIterator).second, childValue, replacer); + array->PushBack(childValue); } } } } // if !done - } // if !Disambiguated() + } // if !Disambiguated() } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/builder-signals.cpp b/dali-toolkit/internal/builder/builder-signals.cpp index d38e1d4..c4af9d4 100644 --- a/dali-toolkit/internal/builder/builder-signals.cpp +++ b/dali-toolkit/internal/builder/builder-signals.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,18 +16,18 @@ */ // EXTERNAL INCLUDES +#include #include #include -#include #include -#include +#include #include #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { @@ -35,11 +35,11 @@ namespace Toolkit { namespace Internal { -extern Animation CreateAnimation( const TreeNode& child, Dali::Toolkit::Internal::Builder* const builder ); -extern void DeterminePropertyFromNode( const TreeNode& node, Property::Value& value ); -} -} -} +extern Animation CreateAnimation(const TreeNode& child, Dali::Toolkit::Internal::Builder* const builder); +extern void DeterminePropertyFromNode(const TreeNode& node, Property::Value& value); +} // namespace Internal +} // namespace Toolkit +} // namespace Dali namespace { @@ -52,9 +52,9 @@ using namespace Dali; // Action on child actor. The child is found by name struct ChildActorAction { - std::string actorName; - std::string actionName; - std::string childName; + std::string actorName; + std::string actionName; + std::string childName; Property::Map parameters; void operator()(void) @@ -80,8 +80,8 @@ struct ChildActorAction // Action to set a property struct PropertySetAction { - std::string actorName; - std::string propertyName; + std::string actorName; + std::string propertyName; Property::Value value; void operator()(void) @@ -92,15 +92,15 @@ struct PropertySetAction { Property::Index idx = actor.GetPropertyIndex(propertyName); - if( idx != Property::INVALID_INDEX ) + if(idx != Property::INVALID_INDEX) { - if( actor.GetPropertyType(idx) != value.GetType() ) + if(actor.GetPropertyType(idx) != value.GetType()) { DALI_SCRIPT_WARNING("Set property action has different type for property '%s'\n", propertyName.c_str()); } else { - actor.SetProperty( idx, value ); + actor.SetProperty(idx, value); } } else @@ -114,8 +114,8 @@ struct PropertySetAction // Generic action on a handle (Animation & Actor) struct GenericAction { - std::string actorName; - std::string actionName; + std::string actorName; + std::string actionName; Property::Map parameters; void operator()(void) @@ -125,7 +125,6 @@ struct GenericAction { actor.DoAction(actionName, parameters); } - }; }; @@ -142,12 +141,12 @@ struct QuitAction // Delay an animation play; ie wait as its not on stage yet struct DelayedAnimationPlay { - OptionalChild animNode; - Dali::IntrusivePtr builder; + OptionalChild animNode; + Dali::IntrusivePtr builder; void operator()(void) { - Animation anim = Toolkit::Internal::CreateAnimation(*animNode, builder.Get() ); + Animation anim = Toolkit::Internal::CreateAnimation(*animNode, builder.Get()); if(anim) { anim.Play(); @@ -158,16 +157,16 @@ struct DelayedAnimationPlay // Delay a pathConstrainer apply struct DelayedConstrainerApply { - std::string constrainerName; + std::string constrainerName; std::vector targetActorNames; std::vector sourceActorNames; std::vector targetPropertyNames; std::vector sourcePropertyNames; - std::vector ranges; - std::vector wrapRanges; + std::vector ranges; + std::vector wrapRanges; - Dali::IntrusivePtr builder; + Dali::IntrusivePtr builder; /* * Helper function to get the parameters to apply each constraint @@ -177,43 +176,43 @@ struct DelayedConstrainerApply * @param[out] sourceActor Source actor for the constraint * @param[out] sourcePropertyIndex Source property index for the constraint */ - bool GetApplyParameters( size_t i, - Actor& targetActor, Property::Index& targetPropertyIndex, - Actor& sourceActor, Property::Index& sourcePropertyIndex) + bool GetApplyParameters(size_t i, + Actor& targetActor, + Property::Index& targetPropertyIndex, + Actor& sourceActor, + Property::Index& sourcePropertyIndex) { - - targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]); + targetActor = Stage::GetCurrent().GetRootLayer().FindChildByName(targetActorNames[i]); targetPropertyIndex = Property::INVALID_INDEX; if(targetActor) { targetPropertyIndex = targetActor.GetPropertyIndex(targetPropertyNames[i]); - if( targetPropertyIndex == Property::INVALID_INDEX ) + if(targetPropertyIndex == Property::INVALID_INDEX) { - DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", targetPropertyNames[i].c_str(), targetActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", targetPropertyNames[i].c_str(), targetActorNames[i].c_str()); return false; } } else { - DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str()); return false; } - - sourceActor = Stage::GetCurrent().GetRootLayer().FindChildByName(sourceActorNames[i]); + sourceActor = Stage::GetCurrent().GetRootLayer().FindChildByName(sourceActorNames[i]); sourcePropertyIndex = Property::INVALID_INDEX; if(sourceActor) { sourcePropertyIndex = sourceActor.GetPropertyIndex(sourcePropertyNames[i]); - if( sourcePropertyIndex == Property::INVALID_INDEX ) + if(sourcePropertyIndex == Property::INVALID_INDEX) { - DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", sourcePropertyNames[i].c_str(), sourceActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Property '%s' not founded in actor '%s'\n", sourcePropertyNames[i].c_str(), sourceActorNames[i].c_str()); return false; } } else { - DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str() ); + DALI_SCRIPT_WARNING("Actor '%s' not founded\n", targetActorNames[i].c_str()); return false; } return true; @@ -221,24 +220,23 @@ struct DelayedConstrainerApply void operator()(void) { - Actor sourceActor, targetActor; + Actor sourceActor, targetActor; Property::Index targetPropertyIndex(Property::INVALID_INDEX); Property::Index sourcePropertyIndex(Property::INVALID_INDEX); - size_t actorCount( targetActorNames.size() ); - if( builder.Get()->IsPathConstrainer( constrainerName )) + size_t actorCount(targetActorNames.size()); + if(builder.Get()->IsPathConstrainer(constrainerName)) { PathConstrainer constrainer = builder.Get()->GetPathConstrainer(constrainerName); - if( constrainer ) + if(constrainer) { - for(size_t i(0); iIsLinearConstrainer( constrainerName ) ) + else if(builder.Get()->IsLinearConstrainer(constrainerName)) { - Dali::LinearConstrainer constrainer( builder.Get()->GetLinearConstrainer(constrainerName)); - if( constrainer ) + Dali::LinearConstrainer constrainer(builder.Get()->GetLinearConstrainer(constrainerName)); + if(constrainer) { - for(size_t i(0); i targetActorNames; - Dali::IntrusivePtr builder; + std::string constrainerName; + std::vector targetActorNames; + Dali::IntrusivePtr builder; void operator()(void) { - size_t actorCount( targetActorNames.size() ); - if( builder.Get()->IsPathConstrainer( constrainerName )) + size_t actorCount(targetActorNames.size()); + if(builder.Get()->IsPathConstrainer(constrainerName)) { PathConstrainer constrainer = builder.Get()->GetPathConstrainer(constrainerName); - if( constrainer ) + if(constrainer) { - for(size_t i(0); iIsLinearConstrainer( constrainerName )) + else if(builder.Get()->IsLinearConstrainer(constrainerName)) { LinearConstrainer constrainer = builder.Get()->GetLinearConstrainer(constrainerName); - if( constrainer ) + if(constrainer) { - for(size_t i(0); i( Dali::Toolkit::Internal::DeterminePropertyFromNode( child, ret ) ); + static_cast(Dali::Toolkit::Internal::DeterminePropertyFromNode(child, ret)); } else if(1 == nChildren) { // {"property": {"quaternion":[1,2,3,4]} } // {"property": {"angle":22, "axis": [1,2,3]} } - OptionalChild quaternion = IsChild(&child, "quaternion"); - OptionalChild axis = IsChild(&child, "axis"); - OptionalChild angle = IsChild(&child, "angle"); + OptionalChild quaternion = IsChild(&child, "quaternion"); + OptionalChild axis = IsChild(&child, "axis"); + OptionalChild angle = IsChild(&child, "angle"); if(quaternion) { @@ -382,14 +379,13 @@ Property::Value GetPropertyValue(const TreeNode &child) return ret; } - /* * Gets Parmeter list from child * params is be cleared before insertion */ void GetParameters(const TreeNode& child, Property::Map& params) { - if( OptionalChild c = IsChild(child, "parameters") ) + if(OptionalChild c = IsChild(child, "parameters")) { const TreeNode& node = *c; @@ -397,18 +393,21 @@ void GetParameters(const TreeNode& child, Property::Map& params) for(TreeNode::ConstIterator iter(node.CBegin()); iter != node.CEnd(); ++iter) { - params[ (*iter).first ] = GetPropertyValue( (*iter).second ); + params[(*iter).first] = GetPropertyValue((*iter).second); } } } // Shim for the property notifcation signal -template +template struct PropertyNotifcationSignalShim { T mFunctor; - PropertyNotifcationSignalShim(T& functor) : mFunctor(functor) {} + PropertyNotifcationSignalShim(T& functor) + : mFunctor(functor) + { + } void operator()(PropertyNotification& /* source */) { @@ -417,105 +416,115 @@ struct PropertyNotifcationSignalShim }; // Specializations for the different signal connection calls between actor & PropertyNotification -template -struct SignalConnector {}; +template +struct SignalConnector +{ +}; // Actor specialization -template <> -struct SignalConnector { - Actor& mActor; +template<> +struct SignalConnector +{ + Actor& mActor; ConnectionTracker* mTracker; const std::string& mName; SignalConnector(ConnectionTracker* tracker, Actor& actor, const std::string& name) - : mActor(actor), mTracker(tracker), mName(name) {} + : mActor(actor), + mTracker(tracker), + mName(name) + { + } - template + template void Connect(T& functor) { - mActor.ConnectSignal( mTracker, mName, functor); + mActor.ConnectSignal(mTracker, mName, functor); } }; // PropertyNotification specialization -template <> +template<> struct SignalConnector { PropertyNotification& mNotification; - ConnectionTracker* mTracker; + ConnectionTracker* mTracker; - SignalConnector(ConnectionTracker* tracker, PropertyNotification ¬ification) - : mNotification(notification), mTracker(tracker) {} + SignalConnector(ConnectionTracker* tracker, PropertyNotification& notification) + : mNotification(notification), + mTracker(tracker) + { + } - template + template void Connect(T& functor) { - mNotification.NotifySignal().Connect( mTracker, PropertyNotifcationSignalShim(functor) ); + mNotification.NotifySignal().Connect(mTracker, PropertyNotifcationSignalShim(functor)); } }; /** * Set an action functor on a signal */ -template -void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder, SignalConnector& connector) +template +void SetActionOnSignal(const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder, SignalConnector& connector) { - OptionalString childActorName(IsString( IsChild(&child, "childActor")) ); - OptionalString actorName(IsString( IsChild(&child, "actor")) ); - OptionalString propertyName(IsString( IsChild(&child, "property")) ); - OptionalChild valueChild( IsChild(&child, "value") ); + OptionalString childActorName(IsString(IsChild(&child, "childActor"))); + OptionalString actorName(IsString(IsChild(&child, "actor"))); + OptionalString propertyName(IsString(IsChild(&child, "property"))); + OptionalChild valueChild(IsChild(&child, "value")); - OptionalString actionName = IsString( IsChild(&child, "action") ); + OptionalString actionName = IsString(IsChild(&child, "action")); DALI_ASSERT_ALWAYS(actionName && "Signal must have an action"); if(childActorName) { ChildActorAction action; - action.actorName = *actorName; - action.childName = *childActorName; - action.actionName = *actionName; + action.actorName = *actorName; + action.childName = *childActorName; + action.actionName = *actionName; GetParameters(child, action.parameters); - connector.Connect( action ); + connector.Connect(action); } else if(actorName) { - if(propertyName && valueChild && ("set" == *actionName) ) + if(propertyName && valueChild && ("set" == *actionName)) { PropertySetAction action; - action.actorName = *actorName; - action.propertyName = *propertyName; + action.actorName = *actorName; + action.propertyName = *propertyName; // actor may not exist yet so we can't check the property type - Dali::Toolkit::Internal::DeterminePropertyFromNode( *valueChild, action.value ); - connector.Connect( action ); + Dali::Toolkit::Internal::DeterminePropertyFromNode(*valueChild, action.value); + connector.Connect(action); } else { GenericAction action; - action.actorName = *actorName; - action.actionName = *actionName; + action.actorName = *actorName; + action.actionName = *actionName; GetParameters(child, action.parameters); - connector.Connect( action ); + connector.Connect(action); } } else if("quit" == *actionName) { QuitAction action; action.builder = builder; - connector.Connect( action ); + connector.Connect(action); } else if("play" == *actionName) { - OptionalChild animations = IsChild( root, "animations" ); - OptionalString animationName = IsString( IsChild(child, "animation") ); - if( animations && animationName ) + OptionalChild animations = IsChild(root, "animations"); + OptionalString animationName = IsString(IsChild(child, "animation")); + if(animations && animationName) { - if( OptionalChild animNode = IsChild(*animations, *animationName) ) + if(OptionalChild animNode = IsChild(*animations, *animationName)) { DelayedAnimationPlay action; action.animNode = animNode; - action.builder = builder; + action.builder = builder; // @todo; put constants into the map - connector.Connect( action ); + connector.Connect(action); } else { @@ -527,32 +536,32 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, DALI_SCRIPT_WARNING("Cannot find animations section\n"); } } - else if("applyConstraint" == *actionName ) + else if("applyConstraint" == *actionName) { - OptionalString constrainerName = IsString( IsChild(child, "constrainer") ); - if( !constrainerName ) + OptionalString constrainerName = IsString(IsChild(child, "constrainer")); + if(!constrainerName) { DALI_SCRIPT_WARNING("Need to specify a constrainer\n"); } else { DelayedConstrainerApply action; - action.constrainerName = *constrainerName; - action.builder = builder; + action.constrainerName = *constrainerName; + action.builder = builder; OptionalChild propertiesNode = IsChild(child, "properties"); if(propertiesNode) { const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd(); - for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& pKeyChild = *iter; - OptionalString sourceActorName(IsString(IsChild(pKeyChild.second, "source"))); + OptionalString sourceActorName(IsString(IsChild(pKeyChild.second, "source"))); if(!sourceActorName) { DALI_SCRIPT_WARNING("Need to specify source actor to apply the constraint\n"); continue; } - OptionalString sourcePropertyName( IsString( IsChild(pKeyChild.second, "sourceProperty" ) ) ); + OptionalString sourcePropertyName(IsString(IsChild(pKeyChild.second, "sourceProperty"))); if(!sourcePropertyName) { DALI_SCRIPT_WARNING("Need to specify source property to apply the constraint\n"); @@ -566,7 +575,7 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, continue; } - OptionalString targetPropertyName( IsString( IsChild(pKeyChild.second, "targetProperty" ) ) ); + OptionalString targetPropertyName(IsString(IsChild(pKeyChild.second, "targetProperty"))); if(!targetPropertyName) { DALI_SCRIPT_WARNING("Need to specify target property name to apply the constraint\n"); @@ -580,7 +589,7 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, continue; } - Vector2 wrap(-std::numeric_limits::max(), std::numeric_limits::max()); + Vector2 wrap(-std::numeric_limits::max(), std::numeric_limits::max()); OptionalVector2 wrapRange(IsVector2(IsChild(pKeyChild.second, "wrap"))); if(wrapRange) { @@ -598,27 +607,26 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, } } } - else if("removeConstraints" == *actionName ) + else if("removeConstraints" == *actionName) { - OptionalString constrainerName = IsString( IsChild(child, "constrainer") ); - if( !constrainerName ) + OptionalString constrainerName = IsString(IsChild(child, "constrainer")); + if(!constrainerName) { DALI_SCRIPT_WARNING("Need to specify a constrainer\n"); } else { - DelayedConstrainerRemove action; - action.constrainerName = *constrainerName; - action.builder = builder; + action.constrainerName = *constrainerName; + action.builder = builder; OptionalChild propertiesNode = IsChild(child, "properties"); if(propertiesNode) { const TreeNode::ConstIterator endIter = (*propertiesNode).CEnd(); - for( TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter ) + for(TreeNode::ConstIterator iter = (*propertiesNode).CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& pKeyChild = *iter; - OptionalString targetActorName(IsString(IsChild(pKeyChild.second, "target"))); + OptionalString targetActorName(IsString(IsChild(pKeyChild.second, "target"))); if(targetActorName) { action.targetActorNames.push_back(*targetActorName); @@ -637,28 +645,27 @@ void SetActionOnSignal(const TreeNode &root, const TreeNode &child, Actor actor, { // no named actor; presume self GenericAction action; - action.actorName = actor.GetProperty< std::string >( Dali::Actor::Property::NAME ); - action.actionName = *actionName; + action.actorName = actor.GetProperty(Dali::Actor::Property::NAME); + action.actionName = *actionName; GetParameters(child, action.parameters); - connector.Connect( action ); + connector.Connect(action); } } - /** * Get a notification condition argument0 as 'arg0' 'value' or 'min' */ -float GetConditionArg0(const TreeNode &child) +float GetConditionArg0(const TreeNode& child) { - OptionalFloat f = IsFloat( IsChild(child, "arg0") ); + OptionalFloat f = IsFloat(IsChild(child, "arg0")); // allowing some human preferable alternatives if(!f) { - f = IsFloat( IsChild(child, "value") ); + f = IsFloat(IsChild(child, "value")); } if(!f) { - f = IsFloat( IsChild(child, "min") ); + f = IsFloat(IsChild(child, "min")); } DALI_ASSERT_ALWAYS(f && "Notification condition for arg0 not specified"); @@ -669,13 +676,13 @@ float GetConditionArg0(const TreeNode &child) /** * Get a notification condition argument1 as 'arg1' or 'max' */ -float GetConditionArg1(const TreeNode &child) +float GetConditionArg1(const TreeNode& child) { - OptionalFloat f = IsFloat( IsChild(child, "arg1") ); + OptionalFloat f = IsFloat(IsChild(child, "arg1")); // allowing some human preferable alternatives if(!f) { - f = IsFloat( IsChild(child, "max") ); + f = IsFloat(IsChild(child, "max")); } DALI_ASSERT_ALWAYS(f && "Notification condition for arg1 not specified"); @@ -683,9 +690,7 @@ float GetConditionArg1(const TreeNode &child) return *f; } - - -}; // anon namespace +}; // namespace namespace Dali { @@ -693,28 +698,27 @@ namespace Toolkit { namespace Internal { - -Actor SetupSignalAction(const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ); -Actor SetupPropertyNotification(const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ); +Actor SetupSignalAction(const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); +Actor SetupPropertyNotification(const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder); /** * Setup signals and actions on an actor */ -Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ) +Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder) { DALI_ASSERT_ALWAYS(actor); if(OptionalChild signalsChild = IsChild(child, "signals")) { - const TreeNode& signalsNode = *signalsChild; - const TreeConstIter endIter = signalsNode.CEnd(); - for( TreeConstIter iter = signalsNode.CBegin(); endIter != iter; ++iter ) + const TreeNode& signalsNode = *signalsChild; + const TreeConstIter endIter = signalsNode.CEnd(); + for(TreeConstIter iter = signalsNode.CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& key_child = *iter; - DALI_SCRIPT_INFO(" Creating Signal for: %s\n", actor.GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str()); + DALI_SCRIPT_INFO(" Creating Signal for: %s\n", actor.GetProperty(Dali::Actor::Property::NAME).c_str()); - OptionalString name( IsString( IsChild( key_child.second, "name")) ); + OptionalString name(IsString(IsChild(key_child.second, "name"))); DALI_ASSERT_ALWAYS(name && "Signal must have a name"); SignalConnector connector(tracker, actor, *name); @@ -728,61 +732,66 @@ Actor SetupSignalAction(ConnectionTracker* tracker, const TreeNode &root, const /** * Setup Property notifications for an actor */ -Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root, const TreeNode &child, Actor actor, Dali::Toolkit::Internal::Builder* const builder ) +Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode& root, const TreeNode& child, Actor actor, Dali::Toolkit::Internal::Builder* const builder) { DALI_ASSERT_ALWAYS(actor); - if(OptionalChild notificationsChild = IsChild(child,"notifications")) + if(OptionalChild notificationsChild = IsChild(child, "notifications")) { - const TreeNode& notificationsNode = *notificationsChild; - const TreeNode::ConstIterator endIter = notificationsNode.CEnd(); - for( TreeNode::ConstIterator iter = notificationsNode.CBegin(); endIter != iter; ++iter ) + const TreeNode& notificationsNode = *notificationsChild; + const TreeNode::ConstIterator endIter = notificationsNode.CEnd(); + for(TreeNode::ConstIterator iter = notificationsNode.CBegin(); endIter != iter; ++iter) { const TreeNode::KeyNodePair& key_child = *iter; - OptionalString prop(IsString( IsChild(key_child.second, "property")) ); + OptionalString prop(IsString(IsChild(key_child.second, "property"))); DALI_ASSERT_ALWAYS(prop && "Notification signal must specify a property"); Property::Index prop_index = actor.GetPropertyIndex(*prop); DALI_ASSERT_ALWAYS(prop_index != Property::INVALID_INDEX && "Notification signal specifies an unknown property"); - OptionalString cond(IsString( IsChild(key_child.second, "condition"))); + OptionalString cond(IsString(IsChild(key_child.second, "condition"))); DALI_ASSERT_ALWAYS(cond && "Notification signal must specify a condition"); if("False" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - LessThanCondition(1.f) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + LessThanCondition(1.f)); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("LessThan" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - LessThanCondition(GetConditionArg0(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + LessThanCondition(GetConditionArg0(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("GreaterThan" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - GreaterThanCondition(GetConditionArg0(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + GreaterThanCondition(GetConditionArg0(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("Inside" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - InsideCondition(GetConditionArg0(key_child.second), - GetConditionArg1(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + InsideCondition(GetConditionArg0(key_child.second), + GetConditionArg1(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } else if("Outside" == *cond) { - PropertyNotification notification = actor.AddPropertyNotification( actor.GetPropertyIndex(*prop), - OutsideCondition(GetConditionArg0(key_child.second), - GetConditionArg1(key_child.second)) ); + PropertyNotification notification = actor.AddPropertyNotification(actor.GetPropertyIndex(*prop), + OutsideCondition(GetConditionArg0(key_child.second), + GetConditionArg1(key_child.second))); + SignalConnector connector(tracker, notification); SetActionOnSignal(root, key_child.second, actor, builder, connector); } @@ -797,7 +806,6 @@ Actor SetupPropertyNotification(ConnectionTracker* tracker, const TreeNode &root } // AddPropertyNotification - } // namespace Internal } // namespace Toolkit } // namespace Dali diff --git a/dali-toolkit/internal/builder/json-parser-impl.cpp b/dali-toolkit/internal/builder/json-parser-impl.cpp index fdec738..d1fe2ae 100644 --- a/dali-toolkit/internal/builder/json-parser-impl.cpp +++ b/dali-toolkit/internal/builder/json-parser-impl.cpp @@ -22,59 +22,54 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const char ERROR_DESCRIPTION_NONE[] = "No Error"; -template +template inline IteratorType Advance(IteratorType& iter, EndIteratorType& end, int n) { - for(int i =0; i < n; ++i) + for(int i = 0; i < n; ++i) { ++iter; } return iter; } -} // anon namespace - +} // namespace JsonParser::JsonParser() - : mRoot(NULL), - mErrorDescription(ERROR_DESCRIPTION_NONE), - mErrorPosition(0), - mErrorLine(0), - mErrorColumn(0), - mNumberOfChars(0), - mNumberOfNodes(0) +: mRoot(NULL), + mErrorDescription(ERROR_DESCRIPTION_NONE), + mErrorPosition(0), + mErrorLine(0), + mErrorColumn(0), + mNumberOfChars(0), + mNumberOfNodes(0) { } JsonParser::JsonParser(const TreeNode& tree) - : mRoot(NULL), - mErrorDescription(ERROR_DESCRIPTION_NONE), - mErrorPosition(0), - mErrorLine(0), - mErrorColumn(0), - mNumberOfChars(0), - mNumberOfNodes(0) +: mRoot(NULL), + mErrorDescription(ERROR_DESCRIPTION_NONE), + mErrorPosition(0), + mErrorLine(0), + mErrorColumn(0), + mNumberOfChars(0), + mNumberOfNodes(0) { - mRoot = TreeNodeManipulator::Copy( tree, mNumberOfNodes, mNumberOfChars ); + mRoot = TreeNodeManipulator::Copy(tree, mNumberOfNodes, mNumberOfChars); - mSources.push_back( VectorChar( (sizeof(char) * mNumberOfChars) ) ); + mSources.push_back(VectorChar((sizeof(char) * mNumberOfChars))); VectorChar& buffer = mSources.back(); @@ -98,40 +93,39 @@ JsonParser::~JsonParser() bool JsonParser::Parse(const std::string& source) { - mSources.push_back( VectorChar(source.begin(), source.end()) ); + mSources.push_back(VectorChar(source.begin(), source.end())); JsonParserState parserState(mRoot); - if( parserState.ParseJson(mSources.back()) ) + if(parserState.ParseJson(mSources.back())) { mRoot = parserState.GetRoot(); mNumberOfChars += parserState.GetParsedStringSize(); mNumberOfNodes += parserState.GetCreatedNodeCount(); - mErrorDescription = ERROR_DESCRIPTION_NONE; - mErrorPosition = 0; - mErrorLine = 0; - mErrorColumn = 0; + mErrorDescription = ERROR_DESCRIPTION_NONE; + mErrorPosition = 0; + mErrorLine = 0; + mErrorColumn = 0; } else { mRoot = NULL; - mErrorDescription = parserState.GetErrorDescription(); + mErrorDescription = parserState.GetErrorDescription(); if(NULL == mErrorDescription) { mErrorDescription = ERROR_DESCRIPTION_NONE; } - mErrorPosition = parserState.GetErrorPosition(); - mErrorLine = parserState.GetErrorLineNumber(); - mErrorColumn = parserState.GetErrorColumn(); + mErrorPosition = parserState.GetErrorPosition(); + mErrorLine = parserState.GetErrorLineNumber(); + mErrorColumn = parserState.GetErrorColumn(); } return mRoot != NULL; } - const TreeNode* JsonParser::GetRoot() const { return mRoot; @@ -164,7 +158,7 @@ int JsonParser::GetErrorColumn() const void JsonParser::Pack(void) { - mSources.push_back( VectorChar( (sizeof(char) * mNumberOfChars) ) ); + mSources.push_back(VectorChar((sizeof(char) * mNumberOfChars))); VectorChar& buffer = mSources.back(); @@ -174,7 +168,7 @@ void JsonParser::Pack(void) modify.MoveStrings(start, buffer.end()); - mSources.erase( mSources.begin(), --mSources.end() ); + mSources.erase(mSources.begin(), --mSources.end()); } void JsonParser::Write(std::ostream& output, int indent) const @@ -183,7 +177,6 @@ void JsonParser::Write(std::ostream& output, int indent) const modify.Write(output, indent); } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/builder/json-parser-state.cpp b/dali-toolkit/internal/builder/json-parser-state.cpp index 40ec632..3262a81 100644 --- a/dali-toolkit/internal/builder/json-parser-state.cpp +++ b/dali-toolkit/internal/builder/json-parser-state.cpp @@ -19,21 +19,17 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // true if character represent a digit inline bool IsDigit(char c) { @@ -41,30 +37,30 @@ inline bool IsDigit(char c) } // convert string to integer -bool StringToInteger(const char *first, const char *last, int& out) +bool StringToInteger(const char* first, const char* last, int& out) { int sign = 1; - if (first != last) + if(first != last) { - if (*first == '-') + if(*first == '-') { sign = -1; ++first; } - else if (*first == '+') + else if(*first == '+') { ++first; } } // json error for int starting with zero - if( 0 == (*first - '0') && (first+1 != last)) + if(0 == (*first - '0') && (first + 1 != last)) { return false; } int result = 0; - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { result = 10 * result + (*first - '0'); } @@ -81,21 +77,21 @@ bool StringToInteger(const char *first, const char *last, int& out) } // convert hexadecimal string to unsigned integer -bool HexStringToUnsignedInteger(const char *first, const char *last, unsigned int& out) +bool HexStringToUnsignedInteger(const char* first, const char* last, unsigned int& out) { unsigned int result = 0; - for (; first != last; ++first) + for(; first != last; ++first) { int digit; - if (IsDigit(*first)) + if(IsDigit(*first)) { digit = *first - '0'; } - else if (*first >= 'a' && *first <= 'f') + else if(*first >= 'a' && *first <= 'f') { digit = *first - 'a' + 10; } - else if (*first >= 'A' && *first <= 'F') + else if(*first >= 'A' && *first <= 'F') { digit = *first - 'A' + 10; } @@ -122,14 +118,14 @@ bool StringToFloat(const char* first, const char* last, float& out) { // sign float sign = 1; - if (first != last) + if(first != last) { - if (*first == '-') + if(*first == '-') { sign = -1; ++first; } - else if (*first == '+') + else if(*first == '+') { ++first; } @@ -137,18 +133,18 @@ bool StringToFloat(const char* first, const char* last, float& out) // integer part float result = 0; - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { result = 10 * result + (*first - '0'); } // fraction part - if (first != last && *first == '.') + if(first != last && *first == '.') { ++first; float inv_base = 0.1f; - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { result += (*first - '0') * inv_base; inv_base *= 0.1f; @@ -160,17 +156,17 @@ bool StringToFloat(const char* first, const char* last, float& out) // exponent bool exponent_negative = false; - int exponent = 0; - if (first != last && (*first == 'e' || *first == 'E')) + int exponent = 0; + if(first != last && (*first == 'e' || *first == 'E')) { ++first; - if (*first == '-') + if(*first == '-') { exponent_negative = true; ++first; } - else if (*first == '+') + else if(*first == '+') { ++first; } @@ -180,21 +176,21 @@ bool StringToFloat(const char* first, const char* last, float& out) return false; } - for (; first != last && IsDigit(*first); ++first) + for(; first != last && IsDigit(*first); ++first) { exponent = 10 * exponent + (*first - '0'); } } - if (exponent) + if(exponent) { float power_of_ten = 10; - for (; exponent > 1; exponent--) + for(; exponent > 1; exponent--) { power_of_ten *= 10; } - if (exponent_negative) + if(exponent_negative) { result /= power_of_ten; } @@ -216,11 +212,10 @@ bool StringToFloat(const char* first, const char* last, float& out) } } - bool IsNumber(char c) { bool ret = false; - switch( c ) + switch(c) { case '0': case '1': @@ -244,14 +239,19 @@ bool IsNumber(char c) return ret; } -} // anon namespace - +} // namespace JsonParserState::JsonParserState(TreeNode* _root) - : mRoot(_root), mCurrent(_root), - mErrorDescription(nullptr), mErrorNewLine(0), mErrorColumn(0), mErrorPosition(0), - mNumberOfParsedChars(0), mNumberOfCreatedNodes(0), mFirstParse(false), - mState(STATE_START) +: mRoot(_root), + mCurrent(_root), + mErrorDescription(nullptr), + mErrorNewLine(0), + mErrorColumn(0), + mErrorPosition(0), + mNumberOfParsedChars(0), + mNumberOfCreatedNodes(0), + mFirstParse(false), + mState(STATE_START) { if(_root == nullptr) { @@ -281,7 +281,6 @@ TreeNode* JsonParserState::CreateNewNode(const char* name, TreeNode::NodeType ty ++mNumberOfCreatedNodes; return node; - } TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type) @@ -299,7 +298,7 @@ TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type) if(name) { const TreeNode* found = mCurrent.GetChild(name); - if( nullptr != found ) + if(nullptr != found) { node = const_cast(found); } @@ -307,7 +306,7 @@ TreeNode* JsonParserState::NewNode(const char* name, TreeNode::NodeType type) else { // if root node - if( mCurrent.GetParent() == nullptr ) + if(mCurrent.GetParent() == nullptr) { node = mRoot; } @@ -356,7 +355,7 @@ bool JsonParserState::ParseWhiteSpace() bool c_comment = false; bool cpp_comment = false; - if( mIter == mEnd ) + if(mIter == mEnd) { return true; } @@ -372,7 +371,7 @@ bool JsonParserState::ParseWhiteSpace() NewLine(); } - if( AtLeast(2) ) + if(AtLeast(2)) { nextChar = mIter[1]; } @@ -381,43 +380,43 @@ bool JsonParserState::ParseWhiteSpace() nextChar = 0; } - if( cpp_comment ) + if(cpp_comment) { - if( '\n' == c ) + if('\n' == c) { cpp_comment = false; Advance(1); continue; // rather than carry on as comments may be back to back } } - else if( !c_comment && (c == '/' && nextChar == '/') ) + else if(!c_comment && (c == '/' && nextChar == '/')) { cpp_comment = true; } - if( c_comment ) + if(c_comment) { - if( c == '*' && nextChar == '/' ) + if(c == '*' && nextChar == '/') { c_comment = false; Advance(2); continue; } } - else if( !cpp_comment && (c == '/' && nextChar == '*') ) + else if(!cpp_comment && (c == '/' && nextChar == '*')) { c_comment = true; } - if( ! (c_comment || cpp_comment) ) + if(!(c_comment || cpp_comment)) { - if( ! (c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA' ) ) + if(!(c == '\x20' || c == '\x9' || c == '\xD' || c == '\xA')) { break; } } - if( AdvanceEnded(1) ) + if(AdvanceEnded(1)) { break; } @@ -429,9 +428,9 @@ bool JsonParserState::ParseWhiteSpace() bool JsonParserState::ParseSymbol(const std::string& symbol) { - if( AtLeast( symbol.size() ) ) + if(AtLeast(symbol.size())) { - for(int i = 0; i < static_cast( symbol.size() ); ++i) + for(int i = 0; i < static_cast(symbol.size()); ++i) { if(*mIter != symbol[i]) { @@ -449,7 +448,7 @@ bool JsonParserState::ParseSymbol(const std::string& symbol) bool JsonParserState::ParseTrue() { - if( ParseSymbol("true") ) + if(ParseSymbol("true")) { mCurrent.SetInteger(1); mCurrent.SetType(TreeNode::BOOLEAN); @@ -463,7 +462,7 @@ bool JsonParserState::ParseTrue() bool JsonParserState::ParseFalse() { - if( ParseSymbol("false") ) + if(ParseSymbol("false")) { mCurrent.SetInteger(0); mCurrent.SetType(TreeNode::BOOLEAN); @@ -477,7 +476,7 @@ bool JsonParserState::ParseFalse() bool JsonParserState::ParseNULL() { - if( ParseSymbol("null") ) + if(ParseSymbol("null")) { mCurrent.SetType(TreeNode::IS_NULL); return true; @@ -490,30 +489,30 @@ bool JsonParserState::ParseNULL() bool JsonParserState::ParseNumber() { - mCurrent.SetType( TreeNode::INTEGER ); + mCurrent.SetType(TreeNode::INTEGER); VectorCharIter first = mIter; - char c = Char(); + char c = Char(); - if( !(c == '-' || IsNumber(c) ) ) + if(!(c == '-' || IsNumber(c))) { return Error("Number must start with '-' or 0-9"); } - while ( IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-' ) + while(IsNumber(c) || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-') { - if (c == '.' || c == 'e' || c == 'E') + if(c == '.' || c == 'e' || c == 'E') { - mCurrent.SetType( TreeNode::FLOAT ); + mCurrent.SetType(TreeNode::FLOAT); } Advance(1); c = Char(); } - if( mCurrent.GetType() == TreeNode::INTEGER ) + if(mCurrent.GetType() == TreeNode::INTEGER) { int i = 0; - if( StringToInteger(&(*first), &(*mIter), i ) ) + if(StringToInteger(&(*first), &(*mIter), i)) { mCurrent.SetInteger(i); } @@ -526,7 +525,7 @@ bool JsonParserState::ParseNumber() if(mCurrent.GetType() == TreeNode::FLOAT) { float f = 0.f; - if( StringToFloat(&(*first), &(*mIter), f) ) + if(StringToFloat(&(*first), &(*mIter), f)) { mCurrent.SetFloat(f); } @@ -536,25 +535,25 @@ bool JsonParserState::ParseNumber() } } - return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT); + return (mCurrent.GetType() == TreeNode::INTEGER) || (mCurrent.GetType() == TreeNode::FLOAT); } char* JsonParserState::EncodeString() { - int substitution = 0; - VectorCharIter first = mIter; - VectorCharIter last = mIter; + int substitution = 0; + VectorCharIter first = mIter; + VectorCharIter last = mIter; - while (*mIter) + while(*mIter) { - if (static_cast(*mIter) < '\x20') + if(static_cast(*mIter) < '\x20') { - static_cast( Error("Control characters not allowed in strings") ); + static_cast(Error("Control characters not allowed in strings")); return nullptr; } - else if (*mIter == '\\' && AtLeast(2)) + else if(*mIter == '\\' && AtLeast(2)) { - switch (*(mIter+1)) + switch(*(mIter + 1)) { case '"': { @@ -599,31 +598,31 @@ char* JsonParserState::EncodeString() case 'u': { unsigned int codepoint; - if( !AtLeast(6) ) + if(!AtLeast(6)) { - static_cast( Error("Bad unicode codepoint; not enough characters") ); + static_cast(Error("Bad unicode codepoint; not enough characters")); return nullptr; } - if ( !HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint) ) + if(!HexStringToUnsignedInteger(&(*(mIter + 2)), &(*(mIter + 6)), codepoint)) { - static_cast( Error("Bad unicode codepoint") ); + static_cast(Error("Bad unicode codepoint")); return nullptr; } - if (codepoint <= 0x7F) + if(codepoint <= 0x7F) { *last = (char)codepoint; } - else if (codepoint <= 0x7FF) + else if(codepoint <= 0x7FF) { *last++ = (char)(0xC0 | (codepoint >> 6)); - *last = (char)(0x80 | (codepoint & 0x3F)); + *last = (char)(0x80 | (codepoint & 0x3F)); } - else if (codepoint <= 0xFFFF) + else if(codepoint <= 0xFFFF) { *last++ = (char)(0xE0 | (codepoint >> 12)); *last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F)); - *last = (char)(0x80 | (codepoint & 0x3F)); + *last = (char)(0x80 | (codepoint & 0x3F)); } Advance(4); @@ -632,7 +631,7 @@ char* JsonParserState::EncodeString() default: { - static_cast( Error("Unrecognized escape sequence") ); + static_cast(Error("Unrecognized escape sequence")); return nullptr; } } @@ -640,7 +639,7 @@ char* JsonParserState::EncodeString() ++last; Advance(2); } - else if (*mIter == '{') + else if(*mIter == '{') { if((0 == substitution) && (*last != '\\')) { @@ -649,7 +648,7 @@ char* JsonParserState::EncodeString() *last++ = *mIter; Advance(1); } - else if (*mIter == '}') + else if(*mIter == '}') { if(substitution) { @@ -658,7 +657,7 @@ char* JsonParserState::EncodeString() *last++ = *mIter; Advance(1); } - else if (*mIter == '"') + else if(*mIter == '"') { *last = 0; Advance(1); @@ -673,9 +672,9 @@ char* JsonParserState::EncodeString() } // while(*mIter) mNumberOfParsedChars += last - first; - mNumberOfParsedChars += 1 ; // null terminator + mNumberOfParsedChars += 1; // null terminator - mCurrent.SetSubstitution( substitution > 1 ); + mCurrent.SetSubstitution(substitution > 1); // return true; return &(*first); @@ -684,12 +683,12 @@ char* JsonParserState::EncodeString() bool JsonParserState::HandleStartState(const char* name, const char currentChar) { - if( '{' == currentChar ) + if('{' == currentChar) { NewNode(name, TreeNode::OBJECT); mState = STATE_OBJECT; } - else if( '[' == currentChar ) + else if('[' == currentChar) { NewNode(name, TreeNode::ARRAY); mState = STATE_VALUE; @@ -705,20 +704,20 @@ bool JsonParserState::HandleStartState(const char* name, const char currentChar) bool JsonParserState::HandleObjectState(const char currentChar, const char lastCharacter) { - if( '}' == currentChar ) + if('}' == currentChar) { if(',' == lastCharacter) { return Error("Unexpected comma"); } - if( !UpToParent() ) + if(!UpToParent()) { return false; } mState = STATE_VALUE; } - else if ( '"' == currentChar ) + else if('"' == currentChar) { mState = STATE_KEY; } @@ -734,19 +733,19 @@ bool JsonParserState::HandleObjectState(const char currentChar, const char lastC bool JsonParserState::HandleKeyState(char*& name) { name = EncodeString(); - if( nullptr == name ) + if(nullptr == name) { return false; } - if( !ParseWhiteSpace() ) + if(!ParseWhiteSpace()) { return false; } - if( ':' != Char()) + if(':' != Char()) { return Error("Expected ':'"); } - if( !ParseWhiteSpace() ) + if(!ParseWhiteSpace()) { return false; } @@ -760,7 +759,7 @@ bool JsonParserState::HandleCharacterQuote(char*& name) { Advance(1); NewNode(name, TreeNode::STRING); - if( char* value = EncodeString() ) + if(char* value = EncodeString()) { mCurrent.SetString(value); } @@ -768,7 +767,7 @@ bool JsonParserState::HandleCharacterQuote(char*& name) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -779,11 +778,11 @@ bool JsonParserState::HandleCharacterQuote(char*& name) bool JsonParserState::HandleCharacterNumberOrHyphen(const char* name) { NewNode(name, TreeNode::IS_NULL); - if( !ParseNumber() ) + if(!ParseNumber()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -795,43 +794,43 @@ bool JsonParserState::HandleValueState(char*& name, const char currentChar, cons { bool handled = true; - if( '"' == currentChar ) + if('"' == currentChar) { handled = HandleCharacterQuote(name); } - else if( IsNumber(currentChar) || currentChar == '-' ) + else if(IsNumber(currentChar) || currentChar == '-') { handled = HandleCharacterNumberOrHyphen(name); } - else if( '{' == currentChar ) + else if('{' == currentChar) { handled = HandleCharacterBracesStart(name, lastCharacter); } - else if( '}' == currentChar ) + else if('}' == currentChar) { handled = HandleCharacterBracesEnd(lastCharacter); } - else if( '[' == currentChar ) + else if('[' == currentChar) { handled = HandleCharacterSquareBracketStart(name); } - else if( ']' == currentChar ) + else if(']' == currentChar) { handled = HandleCharacterSquareBracketEnd(lastCharacter); } - else if( 't' == currentChar ) + else if('t' == currentChar) { handled = HandleCharacterLowercaseT(name); } - else if( 'n' == currentChar ) + else if('n' == currentChar) { handled = HandleCharacterLowercaseN(name); } - else if( 'f' == currentChar) + else if('f' == currentChar) { handled = HandleCharacterLowercaseF(name); } - else if( ',' == currentChar ) + else if(',' == currentChar) { handled = HandleCharacterComma(name); } @@ -852,7 +851,7 @@ bool JsonParserState::ParseJson(VectorChar& source) { Reset(); - if( 0 == source.size() ) + if(0 == source.size()) { return Error("Empty source buffer to parse"); } @@ -860,11 +859,11 @@ bool JsonParserState::ParseJson(VectorChar& source) mIter = source.begin(); mEnd = source.end(); - char* name = nullptr; - char currentChar = 0; - char lastCharacter = 0; + char* name = nullptr; + char currentChar = 0; + char lastCharacter = 0; - if( !ParseWhiteSpace() ) + if(!ParseWhiteSpace()) { return false; } @@ -872,9 +871,9 @@ bool JsonParserState::ParseJson(VectorChar& source) while(mIter != mEnd) { lastCharacter = currentChar; - currentChar = Char(); + currentChar = Char(); - switch( mState ) + switch(mState) { case STATE_START: { @@ -918,7 +917,7 @@ bool JsonParserState::ParseJson(VectorChar& source) } // while(1) // - if( mState != STATE_END ) + if(mState != STATE_END) { return Error("Unexpected termination character"); } @@ -933,15 +932,15 @@ void JsonParserState::Reset() { mCurrent = TreeNodeManipulator(mRoot); - mErrorDescription = nullptr; - mErrorNewLine = 0; - mErrorColumn = 0; - mErrorPosition = 0; + mErrorDescription = nullptr; + mErrorNewLine = 0; + mErrorColumn = 0; + mErrorPosition = 0; } bool JsonParserState::HandleCharacterBracesStart(const char* name, const char lastCharacter) { - if( '}' == lastCharacter ) + if('}' == lastCharacter) { return Error("Expected a comma"); } @@ -972,7 +971,7 @@ bool JsonParserState::HandleCharacterBracesEnd(const char lastCharacter) } else { - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1007,7 +1006,7 @@ bool JsonParserState::HandleCharacterSquareBracketEnd(const char lastCharacter) } else { - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1019,11 +1018,11 @@ bool JsonParserState::HandleCharacterSquareBracketEnd(const char lastCharacter) bool JsonParserState::HandleCharacterLowercaseT(const char* name) { NewNode(name, TreeNode::BOOLEAN); - if( !ParseTrue() ) + if(!ParseTrue()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1034,11 +1033,11 @@ bool JsonParserState::HandleCharacterLowercaseT(const char* name) bool JsonParserState::HandleCharacterLowercaseN(const char* name) { NewNode(name, TreeNode::IS_NULL); - if( !ParseNULL() ) + if(!ParseNULL()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1049,11 +1048,11 @@ bool JsonParserState::HandleCharacterLowercaseN(const char* name) bool JsonParserState::HandleCharacterLowercaseF(const char* name) { NewNode(name, TreeNode::BOOLEAN); - if( !ParseFalse() ) + if(!ParseFalse()) { return false; } - if( !UpToParent() ) + if(!UpToParent()) { return false; } @@ -1063,7 +1062,7 @@ bool JsonParserState::HandleCharacterLowercaseF(const char* name) bool JsonParserState::HandleCharacterComma(const char* name) { - if( 0 == mCurrent.Size() ) + if(0 == mCurrent.Size()) { return Error("Missing Value"); } diff --git a/dali-toolkit/internal/builder/replacement.cpp b/dali-toolkit/internal/builder/replacement.cpp index a15ef21..5825da5 100644 --- a/dali-toolkit/internal/builder/replacement.cpp +++ b/dali-toolkit/internal/builder/replacement.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,29 +16,25 @@ */ // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - -namespace // anon +namespace // anon { - -Property::Value* FindReplacement( const std::string &str, const Property::Map& overrideMap, const Property::Map& defaultMap ) +Property::Value* FindReplacement(const std::string& str, const Property::Map& overrideMap, const Property::Map& defaultMap) { - Property::Value* ret = overrideMap.Find( str ); + Property::Value* ret = overrideMap.Find(str); - if ( !ret ) + if(!ret) { - ret = defaultMap.Find( str ); + ret = defaultMap.Find(str); // @ todo // try localized text ie dgettext. Look for colon {DOMAIN:TEXT} {LC_MESSAGE:ID_XXXX} @@ -47,17 +43,17 @@ Property::Value* FindReplacement( const std::string &str, const Property::Map& o return ret; } -std::size_t FirstUnescapedChar(const std::string &initialValue, const std::size_t& startPos, const char c) +std::size_t FirstUnescapedChar(const std::string& initialValue, const std::size_t& startPos, const char c) { - std::size_t pos = initialValue.find( c, startPos ); + std::size_t pos = initialValue.find(c, startPos); if(pos > 0) { - while( pos != std::string::npos ) + while(pos != std::string::npos) { - if( '\\' == initialValue.at( pos-1 ) ) + if('\\' == initialValue.at(pos - 1)) { - pos = initialValue.find( c, pos ); + pos = initialValue.find(c, pos); } else { @@ -69,11 +65,11 @@ std::size_t FirstUnescapedChar(const std::string &initialValue, const std::size_ return pos; } -bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &startPos, std::size_t &size ) +bool GetSubstitutionPosition(const std::string& initialValue, std::size_t& startPos, std::size_t& size) { std::size_t pos = FirstUnescapedChar(initialValue, 0, '{'); - if( std::string::npos == pos ) + if(std::string::npos == pos) { startPos = std::string::npos; return false; @@ -85,7 +81,7 @@ bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &star pos = FirstUnescapedChar(initialValue, startPos, '}'); - if( std::string::npos == pos ) + if(std::string::npos == pos) { size = std::string::npos; return false; @@ -98,11 +94,9 @@ bool GetSubstitutionPosition( const std::string &initialValue, std::size_t &star return true; } -bool ResolvePartialReplacement( const std::string &initialValue, Property::Value &out, - const Property::Map& overrideMap, const Property::Map& defaultMap ) +bool ResolvePartialReplacement(const std::string& initialValue, Property::Value& out, const Property::Map& overrideMap, const Property::Map& defaultMap) { - - if( initialValue.size() >= 2 ) + if(initialValue.size() >= 2) { // eg '{"constants": { "IMAGE_DIR": "/share/images" }, // ... @@ -111,36 +105,37 @@ bool ResolvePartialReplacement( const std::string &initialValue, Property::Value std::size_t startPos = 0; std::size_t size = std::string::npos; - if( !GetSubstitutionPosition( initialValue, startPos, size ) ) + if(!GetSubstitutionPosition(initialValue, startPos, size)) { out = initialValue; return true; } else { - const std::string str( initialValue.substr( startPos, size ) ); + const std::string str(initialValue.substr(startPos, size)); - Property::Value* value = FindReplacement( str, overrideMap, defaultMap ); + Property::Value* value = FindReplacement(str, overrideMap, defaultMap); - if( !value ) + if(!value) { - DALI_SCRIPT_WARNING( "Cannot find replacement for '%s'\n", str.c_str() ); + DALI_SCRIPT_WARNING("Cannot find replacement for '%s'\n", str.c_str()); } else { - if( Property::STRING != value->GetType() ) + if(Property::STRING != value->GetType()) { - DALI_SCRIPT_WARNING( "Cannot replace substring in non string property type='%s'. Initial value '%s'\n", - PropertyTypes::GetName( out.GetType() ), initialValue.c_str() ); + DALI_SCRIPT_WARNING("Cannot replace substring in non string property type='%s'. Initial value '%s'\n", + PropertyTypes::GetName(out.GetType()), + initialValue.c_str()); } else { - std::string newString = \ + std::string newString = initialValue.substr(0, startPos - 1) + - value->Get< std::string >() + - initialValue.substr( startPos + size + 1 ); + value->Get() + + initialValue.substr(startPos + size + 1); - return ResolvePartialReplacement( newString, out, overrideMap, defaultMap ); + return ResolvePartialReplacement(newString, out, overrideMap, defaultMap); } } } @@ -150,13 +145,12 @@ bool ResolvePartialReplacement( const std::string &initialValue, Property::Value return false; } -} // namespace anon +} // namespace - -Replacement::Replacement( const Property::Map& overrideMap, const Property::Map& defaultMap ) - : mOverrideMap( &overrideMap ), mDefaultMap( &defaultMap ) +Replacement::Replacement(const Property::Map& overrideMap, const Property::Map& defaultMap) +: mOverrideMap(&overrideMap), + mDefaultMap(&defaultMap) { - } namespace @@ -164,46 +158,46 @@ namespace Property::Map noMap; } -Replacement::Replacement( const Property::Map& defaultMap ) - : mOverrideMap( &noMap ), mDefaultMap( &defaultMap ) +Replacement::Replacement(const Property::Map& defaultMap) +: mOverrideMap(&noMap), + mDefaultMap(&defaultMap) { - } -Replacement::Replacement( ) - : mOverrideMap( &noMap ), mDefaultMap( &noMap ) +Replacement::Replacement() +: mOverrideMap(&noMap), + mDefaultMap(&noMap) { - } -OptionalString Replacement::HasFullReplacement( const TreeNode & node ) const +OptionalString Replacement::HasFullReplacement(const TreeNode& node) const { OptionalString ret; - if( node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()) ) + if(node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count())) { - OptionalString v = ::IsString( node ); - if( v ) + OptionalString v = ::IsString(node); + if(v) { const std::string& initialValue = *v; - if( (initialValue[ 0 ] == '{') && (initialValue[ initialValue.size() -1 ] == '}') ) + if((initialValue[0] == '{') && (initialValue[initialValue.size() - 1] == '}')) { - ret = initialValue.substr( 1, initialValue.size() - 2 ); + ret = initialValue.substr(1, initialValue.size() - 2); } } } return ret; } -Property::Value Replacement::GetFullReplacement( const std::string& replacementString ) const +Property::Value Replacement::GetFullReplacement(const std::string& replacementString) const { Property::Value out; - DALI_ASSERT_DEBUG( mOverrideMap && "missing map"); - DALI_ASSERT_DEBUG( mDefaultMap && "missing map"); + DALI_ASSERT_DEBUG(mOverrideMap && "missing map"); + DALI_ASSERT_DEBUG(mDefaultMap && "missing map"); - Property::Value* value = FindReplacement( replacementString, *mOverrideMap, *mDefaultMap ); + Property::Value* value = FindReplacement(replacementString, *mOverrideMap, *mDefaultMap); - if( !value ) + if(!value) { DALI_SCRIPT_WARNING("Cannot find replacement for '%s'\n", replacementString.c_str()); } @@ -213,36 +207,36 @@ Property::Value Replacement::GetFullReplacement( const std::string& replacementS #if defined(DEBUG_ENABLED) DALI_SCRIPT_VERBOSE(" Full replacement for '%s' => to Type '%s'\n", replacementString.c_str(), - PropertyTypes::GetName( out.GetType()) ); + PropertyTypes::GetName(out.GetType())); #endif } return out; } -OptionalBoolean Replacement::IsBoolean( const TreeNode & node ) const +OptionalBoolean Replacement::IsBoolean(const TreeNode& node) const { OptionalBoolean ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::BOOLEAN == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::BOOLEAN == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsBoolean( node ); + ret = ::IsBoolean(node); } return ret; } -OptionalBoolean Replacement::IsBoolean( OptionalChild child ) const +OptionalBoolean Replacement::IsBoolean(OptionalChild child) const { - if( child ) + if(child) { - return IsBoolean( *child ); + return IsBoolean(*child); } else { @@ -250,39 +244,39 @@ OptionalBoolean Replacement::IsBoolean( OptionalChild child ) const } } -OptionalFloat Replacement::IsFloat( const TreeNode & node ) const +OptionalFloat Replacement::IsFloat(const TreeNode& node) const { OptionalFloat ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::FLOAT == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::FLOAT == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsFloat( node ); + ret = ::IsFloat(node); } return ret; } -OptionalString Replacement::IsString( const TreeNode& node ) const +OptionalString Replacement::IsString(const TreeNode& node) const { OptionalString ret; - DALI_ASSERT_DEBUG( mOverrideMap && "missing map"); - DALI_ASSERT_DEBUG( mDefaultMap && "missing map"); + DALI_ASSERT_DEBUG(mOverrideMap && "missing map"); + DALI_ASSERT_DEBUG(mDefaultMap && "missing map"); - if( node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count()) ) + if(node.HasSubstitution() && ((*mOverrideMap).Count() || (*mDefaultMap).Count())) { - if( OptionalString v = ::IsString( node ) ) + if(OptionalString v = ::IsString(node)) { Property::Value value; - if( ResolvePartialReplacement( *v, value, *mOverrideMap, *mDefaultMap ) ) + if(ResolvePartialReplacement(*v, value, *mOverrideMap, *mDefaultMap)) { - if( Property::STRING == value.GetType() ) + if(Property::STRING == value.GetType()) { ret = value.Get(); #if defined(DEBUG_ENABLED) @@ -298,160 +292,160 @@ OptionalString Replacement::IsString( const TreeNode& node ) const } else { - ret = ::IsString( node ); + ret = ::IsString(node); } return ret; } -OptionalInteger Replacement::IsInteger( const TreeNode & node ) const +OptionalInteger Replacement::IsInteger(const TreeNode& node) const { OptionalInteger ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::INTEGER == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::INTEGER == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsInteger( node ); + ret = ::IsInteger(node); } return ret; } -OptionalVector2 Replacement::IsVector2( const TreeNode & node ) const +OptionalVector2 Replacement::IsVector2(const TreeNode& node) const { OptionalVector2 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::VECTOR2 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::VECTOR2 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsVector2( node ); + ret = ::IsVector2(node); } return ret; } -OptionalVector3 Replacement::IsVector3( const TreeNode & node ) const +OptionalVector3 Replacement::IsVector3(const TreeNode& node) const { OptionalVector3 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::VECTOR3 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::VECTOR3 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsVector3( node ); + ret = ::IsVector3(node); } return ret; } -OptionalVector4 Replacement::IsVector4( const TreeNode & node ) const +OptionalVector4 Replacement::IsVector4(const TreeNode& node) const { OptionalVector4 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::VECTOR4 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::VECTOR4 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsVector4( node ); + ret = ::IsVector4(node); } return ret; } -OptionalMatrix Replacement::IsMatrix( const TreeNode & node ) const +OptionalMatrix Replacement::IsMatrix(const TreeNode& node) const { OptionalMatrix ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::MATRIX == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::MATRIX == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsMatrix( node ); + ret = ::IsMatrix(node); } return ret; } -OptionalMatrix3 Replacement::IsMatrix3( const TreeNode & node ) const +OptionalMatrix3 Replacement::IsMatrix3(const TreeNode& node) const { OptionalMatrix3 ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::MATRIX3 == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::MATRIX3 == value.GetType()) { ret = value.Get(); } } else { - ret = ::IsMatrix3( node ); + ret = ::IsMatrix3(node); } return ret; } -OptionalRect Replacement::IsRect( const TreeNode & node ) const +OptionalRect Replacement::IsRect(const TreeNode& node) const { OptionalRect ret; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::RECTANGLE == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::RECTANGLE == value.GetType()) { ret = value.Get >(); } } else { - ret = ::IsRect( node ); + ret = ::IsRect(node); } return ret; } -OptionalExtents Replacement::IsExtents( const TreeNode & node ) const +OptionalExtents Replacement::IsExtents(const TreeNode& node) const { OptionalExtents extents; - if( OptionalString replace = HasFullReplacement( node ) ) + if(OptionalString replace = HasFullReplacement(node)) { - Property::Value value = GetFullReplacement( *replace ); - if( Property::EXTENTS == value.GetType() ) + Property::Value value = GetFullReplacement(*replace); + if(Property::EXTENTS == value.GetType()) { extents = value.Get(); } } else { - extents = ::IsExtents( node ); + extents = ::IsExtents(node); } return extents; } -OptionalFloat Replacement::IsFloat( OptionalChild child ) const +OptionalFloat Replacement::IsFloat(OptionalChild child) const { - if( child ) + if(child) { - return IsFloat( *child ); + return IsFloat(*child); } else { @@ -459,12 +453,11 @@ OptionalFloat Replacement::IsFloat( OptionalChild child ) const } } - -OptionalString Replacement::IsString( OptionalChild child ) const +OptionalString Replacement::IsString(OptionalChild child) const { - if( child ) + if(child) { - return IsString( *child ); + return IsString(*child); } else { @@ -472,11 +465,11 @@ OptionalString Replacement::IsString( OptionalChild child ) const } } -OptionalInteger Replacement::IsInteger( OptionalChild child ) const +OptionalInteger Replacement::IsInteger(OptionalChild child) const { - if( child ) + if(child) { - return IsInteger( *child ); + return IsInteger(*child); } else { @@ -484,11 +477,11 @@ OptionalInteger Replacement::IsInteger( OptionalChild child ) const } } -OptionalVector2 Replacement::IsVector2( OptionalChild child ) const +OptionalVector2 Replacement::IsVector2(OptionalChild child) const { - if( child ) + if(child) { - return IsVector2( *child ); + return IsVector2(*child); } else { @@ -496,11 +489,11 @@ OptionalVector2 Replacement::IsVector2( OptionalChild child ) const } } -OptionalVector3 Replacement::IsVector3( OptionalChild child ) const +OptionalVector3 Replacement::IsVector3(OptionalChild child) const { - if( child ) + if(child) { - return IsVector3( *child ); + return IsVector3(*child); } else { @@ -508,11 +501,11 @@ OptionalVector3 Replacement::IsVector3( OptionalChild child ) const } } -OptionalVector4 Replacement::IsVector4( OptionalChild child ) const +OptionalVector4 Replacement::IsVector4(OptionalChild child) const { - if( child ) + if(child) { - return IsVector4( *child ); + return IsVector4(*child); } else { @@ -520,11 +513,11 @@ OptionalVector4 Replacement::IsVector4( OptionalChild child ) const } } -OptionalMatrix Replacement::IsMatrix( OptionalChild child ) const +OptionalMatrix Replacement::IsMatrix(OptionalChild child) const { - if( child ) + if(child) { - return IsMatrix( *child ); + return IsMatrix(*child); } else { @@ -532,11 +525,11 @@ OptionalMatrix Replacement::IsMatrix( OptionalChild child ) const } } -OptionalMatrix3 Replacement::IsMatrix3( OptionalChild child ) const +OptionalMatrix3 Replacement::IsMatrix3(OptionalChild child) const { - if( child ) + if(child) { - return IsMatrix3( *child ); + return IsMatrix3(*child); } else { @@ -544,11 +537,11 @@ OptionalMatrix3 Replacement::IsMatrix3( OptionalChild child ) const } } -OptionalRect Replacement::IsRect( OptionalChild child ) const +OptionalRect Replacement::IsRect(OptionalChild child) const { - if( child ) + if(child) { - return IsRect( *child ); + return IsRect(*child); } else { @@ -556,16 +549,16 @@ OptionalRect Replacement::IsRect( OptionalChild child ) const } } -bool Replacement::IsMap( OptionalChild child, Property::Value& out ) const +bool Replacement::IsMap(OptionalChild child, Property::Value& out) const { bool ret = false; - if( child ) + if(child) { - if( OptionalString replace = HasFullReplacement( *child ) ) + if(OptionalString replace = HasFullReplacement(*child)) { - out = GetFullReplacement( *replace ); - if( Property::MAP == out.GetType() ) + out = GetFullReplacement(*replace); + if(Property::MAP == out.GetType()) { ret = true; } @@ -575,16 +568,16 @@ bool Replacement::IsMap( OptionalChild child, Property::Value& out ) const return ret; } -bool Replacement::IsArray( OptionalChild child, Property::Value& out ) const +bool Replacement::IsArray(OptionalChild child, Property::Value& out) const { bool ret = false; - if( child ) + if(child) { - if( OptionalString replace = HasFullReplacement( *child ) ) + if(OptionalString replace = HasFullReplacement(*child)) { - out = GetFullReplacement( *replace ); - if( Property::ARRAY == out.GetType() ) + out = GetFullReplacement(*replace); + if(Property::ARRAY == out.GetType()) { ret = true; } @@ -594,11 +587,11 @@ bool Replacement::IsArray( OptionalChild child, Property::Value& out ) const return ret; } -OptionalExtents Replacement::IsExtents( OptionalChild child ) const +OptionalExtents Replacement::IsExtents(OptionalChild child) const { - if( child ) + if(child) { - return IsExtents( *child ); + return IsExtents(*child); } else { diff --git a/dali-toolkit/internal/builder/style.cpp b/dali-toolkit/internal/builder/style.cpp index a5ced1b..b834b13 100644 --- a/dali-toolkit/internal/builder/style.cpp +++ b/dali-toolkit/internal/builder/style.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,70 +14,68 @@ * limitations under the License. */ -#include -#include -#include #include -#include #include #include +#include +#include +#include +#include namespace Dali { namespace Toolkit { - namespace Internal { - extern const Dali::Scripting::StringEnum ControlStateTable[]; -extern const unsigned int ControlStateTableCount; +extern const unsigned int ControlStateTableCount; StylePtr Style::New() { - StylePtr stylePtr( new Style() ); + StylePtr stylePtr(new Style()); return stylePtr; } void Style::ApplyVisualsAndPropertiesRecursively( - Handle handle, - const Dictionary& instancedProperties ) const + Handle handle, + const Dictionary& instancedProperties) const { - ApplyVisuals( handle, instancedProperties ); - ApplyProperties( handle ); + ApplyVisuals(handle, instancedProperties); + ApplyProperties(handle); Toolkit::Control control = Toolkit::Control::DownCast(handle); - if( control ) + if(control) { - std::string stateName; - Property::Value value = control.GetProperty(DevelControl::Property::STATE); + std::string stateName; + Property::Value value = control.GetProperty(DevelControl::Property::STATE); Dali::Toolkit::DevelControl::State state = static_cast(value.Get()); - stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( state, ControlStateTable, ControlStateTableCount ); + stateName = Scripting::GetEnumerationName(state, ControlStateTable, ControlStateTableCount); - if( ! stateName.empty() ) + if(!stateName.empty()) { // Look up state in states table: - const StylePtr* stylePtr = subStates.FindConst( stateName ); - if( stylePtr ) + const StylePtr* stylePtr = subStates.FindConst(stateName); + if(stylePtr) { const StylePtr statePtr(*stylePtr); // We have a state match. - statePtr->ApplyVisuals( handle, instancedProperties ); - statePtr->ApplyProperties( handle ); + statePtr->ApplyVisuals(handle, instancedProperties); + statePtr->ApplyProperties(handle); // Apply substate visuals Property::Value value = control.GetProperty(DevelControl::Property::SUB_STATE); - std::string subStateName; - if( value.Get( subStateName ) && ! subStateName.empty() ) + std::string subStateName; + if(value.Get(subStateName) && !subStateName.empty()) { - const StylePtr* stylePtr = statePtr->subStates.FindConst( subStateName ); - if( stylePtr ) + const StylePtr* stylePtr = statePtr->subStates.FindConst(subStateName); + if(stylePtr) { const StylePtr subStatePtr(*stylePtr); // We have a sub-state match. - subStatePtr->ApplyVisuals( handle, instancedProperties ); - subStatePtr->ApplyProperties( handle ); + subStatePtr->ApplyVisuals(handle, instancedProperties); + subStatePtr->ApplyProperties(handle); } } } @@ -86,57 +84,57 @@ void Style::ApplyVisualsAndPropertiesRecursively( } void Style::ApplyVisuals( - Handle handle, - const Dictionary& instancedProperties ) const + Handle handle, + const Dictionary& instancedProperties) const { - ApplyVisuals( handle, visuals, instancedProperties ); + ApplyVisuals(handle, visuals, instancedProperties); } void Style::ApplyVisuals( - Handle handle, + Handle handle, const Dictionary& visualMaps, - const Dictionary& instancedProperties ) + const Dictionary& instancedProperties) { - for( Dictionary::iterator iter = visualMaps.Begin(); iter != visualMaps.End() ; ++iter ) + for(Dictionary::iterator iter = visualMaps.Begin(); iter != visualMaps.End(); ++iter) { - const std::string& visualName = (*iter).key; - Property::Map map = (*iter).entry; - Property::Map* instancedMap = instancedProperties.Find( visualName ); - ApplyVisual( handle, visualName, map, instancedMap ); + const std::string& visualName = (*iter).key; + Property::Map map = (*iter).entry; + Property::Map* instancedMap = instancedProperties.Find(visualName); + ApplyVisual(handle, visualName, map, instancedMap); } } void Style::ApplyVisual( - Handle handle, - const std::string& visualName, + Handle handle, + const std::string& visualName, const Property::Map& visualMap, - const Property::Map* instancedProperties ) + const Property::Map* instancedProperties) { // Check if this visual name is a valid property of handle - Dali::Property::Index index = handle.GetPropertyIndex( visualName ); - if( index != Property::INVALID_INDEX ) + Dali::Property::Index index = handle.GetPropertyIndex(visualName); + if(index != Property::INVALID_INDEX) { const Property::Map* applyMap = &visualMap; - Property::Map mergedMap; + Property::Map mergedMap; // If there are instanced properties, and the visual types match, // merge them into the visual map - if( instancedProperties ) + if(instancedProperties) { - Property::Value* instanceTypeValue = instancedProperties->Find( Toolkit::Visual::Property::TYPE); - Property::Value* newTypeValue = visualMap.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE ); - if( instanceTypeValue && newTypeValue ) + Property::Value* instanceTypeValue = instancedProperties->Find(Toolkit::Visual::Property::TYPE); + Property::Value* newTypeValue = visualMap.Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE); + if(instanceTypeValue && newTypeValue) { - int instanceVisualType=-1; - int newVisualType=-1; - Scripting::GetEnumerationProperty( *instanceTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, instanceVisualType ); - Scripting::GetEnumerationProperty( *newTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, newVisualType ); + int instanceVisualType = -1; + int newVisualType = -1; + Scripting::GetEnumerationProperty(*instanceTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, instanceVisualType); + Scripting::GetEnumerationProperty(*newTypeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, newVisualType); - if( instanceVisualType == newVisualType ) + if(instanceVisualType == newVisualType) { // Same type - merge remaining instance data - mergedMap.Merge( visualMap ); - mergedMap.Merge( *instancedProperties ); + mergedMap.Merge(visualMap); + mergedMap.Merge(*instancedProperties); applyMap = &mergedMap; } } @@ -144,18 +142,18 @@ void Style::ApplyVisual( // Apply the visual property map to the handle const Property::Value value(const_cast(*applyMap)); - handle.SetProperty( index, value ); + handle.SetProperty(index, value); } } -void Style::ApplyProperties( Handle handle ) const +void Style::ApplyProperties(Handle handle) const { - for( Property::Map::SizeType i=0; imName = from->mName; - to->mType = from->mType; - to->mSubstituion = from->mSubstituion; + to->mName = from->mName; + to->mType = from->mType; + to->mSubstituion = from->mSubstituion; switch(from->mType) { case TreeNode::INTEGER: @@ -117,7 +113,6 @@ void TreeNodeManipulator::ShallowCopy(const TreeNode* from, TreeNode* to) } } } - } void TreeNodeManipulator::MoveNodeStrings(VectorCharIter& start, const VectorCharIter& sentinel) @@ -169,11 +164,11 @@ void TreeNodeManipulator::RemoveChildren() CollectNodes collector; - DepthFirst( mNode, collector ); + DepthFirst(mNode, collector); for(CollectNodes::iterator iter = collector.nodes.begin(); iter != collector.nodes.end(); ++iter) { - if( *iter != mNode) + if(*iter != mNode) { delete *iter; } @@ -211,7 +206,7 @@ void TreeNodeManipulator::CopyChildren(const TreeNode* from, TreeNode* to, int& DALI_ASSERT_DEBUG(from && "Operation on NULL JSON node"); DALI_ASSERT_DEBUG(to); - for( TreeNode::ConstIterator iter = from->CBegin(); iter != from->CEnd(); ++iter) + for(TreeNode::ConstIterator iter = from->CBegin(); iter != from->CEnd(); ++iter) { const TreeNode* child = &((*iter).second); if(child->mName) @@ -238,12 +233,12 @@ void TreeNodeManipulator::CopyChildren(const TreeNode* from, TreeNode* to, int& } } -TreeNode *TreeNodeManipulator::AddChild(TreeNode *rhs) +TreeNode* TreeNodeManipulator::AddChild(TreeNode* rhs) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); rhs->mParent = mNode; - if (mNode->mLastChild) + if(mNode->mLastChild) { mNode->mLastChild = mNode->mLastChild->mNextSibling = rhs; } @@ -268,36 +263,36 @@ size_t TreeNodeManipulator::Size() const return mNode->Size(); } -void TreeNodeManipulator::SetType( TreeNode::NodeType type) +void TreeNodeManipulator::SetType(TreeNode::NodeType type) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); - if( mNode->mType != type ) + if(mNode->mType != type) { mNode->mType = type; - if( NULL != mNode->mFirstChild ) + if(NULL != mNode->mFirstChild) { // value types have no children - bool removeChildren = ! (TreeNode::OBJECT == type || TreeNode::ARRAY == type); + bool removeChildren = !(TreeNode::OBJECT == type || TreeNode::ARRAY == type); // ie if swapping array for object removeChildren = (removeChildren == true) ? true : type != mNode->mType; // so remove any children - if( removeChildren && NULL != mNode->mFirstChild) + if(removeChildren && NULL != mNode->mFirstChild) { RemoveChildren(); } } } - else if( TreeNode::ARRAY == mNode->mType ) + else if(TreeNode::ARRAY == mNode->mType) { - if( mNode->mFirstChild != NULL ) + if(mNode->mFirstChild != NULL) { TreeNode::NodeType type = mNode->mFirstChild->GetType(); - if( TreeNode::FLOAT == type || TreeNode::INTEGER == type ) + if(TreeNode::FLOAT == type || TreeNode::INTEGER == type) { // Arrays of numbers should be replaced, not appended to. RemoveChildren(); @@ -306,13 +301,13 @@ void TreeNodeManipulator::SetType( TreeNode::NodeType type) } } -void TreeNodeManipulator::SetName( const char* name ) +void TreeNodeManipulator::SetName(const char* name) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); mNode->mName = name; } -void TreeNodeManipulator::SetSubstitution( bool b ) +void TreeNodeManipulator::SetSubstitution(bool b) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); mNode->mSubstituion = b; @@ -330,28 +325,28 @@ const TreeNode* TreeNodeManipulator::GetChild(const std::string& name) const return NULL == mNode ? NULL : mNode->GetChild(name); } -void TreeNodeManipulator::SetString( const char* string ) +void TreeNodeManipulator::SetString(const char* string) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::STRING); mNode->mStringValue = string; } -void TreeNodeManipulator::SetInteger( int i ) +void TreeNodeManipulator::SetInteger(int i) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::INTEGER); mNode->mIntValue = i; } -void TreeNodeManipulator::SetFloat( float f ) +void TreeNodeManipulator::SetFloat(float f) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::FLOAT); mNode->mFloatValue = f; } -void TreeNodeManipulator::SetBoolean( bool b ) +void TreeNodeManipulator::SetBoolean(bool b) { DALI_ASSERT_DEBUG(mNode && "Operation on NULL JSON node"); SetType(TreeNode::BOOLEAN); @@ -364,7 +359,7 @@ void TreeNodeManipulator::Write(std::ostream& output, int indent) const DoWrite(mNode, output, 0, indent, false); } -void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, int level, int indentWidth, bool groupChildren) const +void TreeNodeManipulator::DoWrite(const TreeNode* value, std::ostream& output, int level, int indentWidth, bool groupChildren) const { DALI_ASSERT_DEBUG(value && "Operation on NULL JSON node"); @@ -373,7 +368,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i Indent(output, level, indentWidth); } - if (value->GetName()) + if(value->GetName()) { output << "\"" << value->GetName() << "\":"; } @@ -387,7 +382,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i { output << ", "; } - if( !groupChildren ) + if(!groupChildren) { output << std::endl; } @@ -398,14 +393,14 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i { bool groupMyChildren = false; - if( TreeNode::ARRAY == value->GetType() && value->mFirstChild && - ( TreeNode::INTEGER == value->mFirstChild->GetType() || - TreeNode::FLOAT == value->mFirstChild->GetType() ) ) + if(TreeNode::ARRAY == value->GetType() && value->mFirstChild && + (TreeNode::INTEGER == value->mFirstChild->GetType() || + TreeNode::FLOAT == value->mFirstChild->GetType())) { groupMyChildren = true; } - if( value->GetType() == TreeNode::OBJECT) + if(value->GetType() == TreeNode::OBJECT) { output << std::endl; Indent(output, level, indentWidth); @@ -413,7 +408,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i } else { - if( !groupMyChildren ) + if(!groupMyChildren) { output << std::endl; Indent(output, level, indentWidth); @@ -421,7 +416,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i output << "["; } - if( groupMyChildren ) + if(groupMyChildren) { output << " "; } @@ -430,17 +425,17 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i output << std::endl; } - for (TreeNode::ConstIterator it = value->CBegin(); it != value->CEnd(); ++it) + for(TreeNode::ConstIterator it = value->CBegin(); it != value->CEnd(); ++it) { - DoWrite( &((*it).second), output, level+1, indentWidth, groupMyChildren ); + DoWrite(&((*it).second), output, level + 1, indentWidth, groupMyChildren); } - if( !groupMyChildren ) + if(!groupMyChildren) { Indent(output, level, indentWidth); } - if( value->GetType() == TreeNode::OBJECT ) + if(value->GetType() == TreeNode::OBJECT) { output << "}"; } @@ -449,12 +444,12 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i output << "]"; } - if( NULL != value->mNextSibling ) + if(NULL != value->mNextSibling) { output << ","; } - if( !groupChildren ) + if(!groupChildren) { output << std::endl; } @@ -471,7 +466,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i output << ","; } - if( groupChildren ) + if(groupChildren) { output << " "; } @@ -489,7 +484,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i output << ","; } - if( groupChildren ) + if(groupChildren) { output << " "; } @@ -501,15 +496,15 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i } case TreeNode::FLOAT: { - output.setf( std::ios::floatfield ); + output.setf(std::ios::floatfield); output << value->GetFloat(); - output.unsetf( std::ios::floatfield ); + output.unsetf(std::ios::floatfield); if(NULL != value->mNextSibling) { output << ","; } - if( groupChildren ) + if(groupChildren) { output << " "; } @@ -521,7 +516,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i } case TreeNode::BOOLEAN: { - if( value->GetInteger() ) + if(value->GetInteger()) { output << "true"; } @@ -535,7 +530,7 @@ void TreeNodeManipulator::DoWrite(const TreeNode *value, std::ostream& output, i output << ","; } - if( groupChildren ) + if(groupChildren) { output << " "; } @@ -555,9 +550,9 @@ const TreeNode* FindIt(std::string_view childName, const TreeNode* node) const TreeNode* found = NULL; - if( node ) + if(node) { - if( NULL != (found = node->GetChild(childName)) ) + if(NULL != (found = node->GetChild(childName))) { return found; } @@ -565,7 +560,7 @@ const TreeNode* FindIt(std::string_view childName, const TreeNode* node) { for(TreeNode::ConstIterator iter = node->CBegin(); iter != node->CEnd(); ++iter) { - if( NULL != (found = FindIt(childName, &((*iter).second)) ) ) + if(NULL != (found = FindIt(childName, &((*iter).second)))) { return found; } @@ -575,13 +570,13 @@ const TreeNode* FindIt(std::string_view childName, const TreeNode* node) return found; } -char *CopyString( const char *fromString, VectorCharIter& iter, const VectorCharIter& sentinel) +char* CopyString(const char* fromString, VectorCharIter& iter, const VectorCharIter& sentinel) { DALI_ASSERT_DEBUG(fromString); DALI_ASSERT_DEBUG(iter != sentinel); - char *start= &(*iter); - const char *ptr = fromString; + char* start = &(*iter); + const char* ptr = fromString; if(ptr) { @@ -596,8 +591,7 @@ char *CopyString( const char *fromString, VectorCharIter& iter, const VectorChar return start; } - -} // namespace internal +} // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/controls/alignment/alignment-impl.cpp b/dali-toolkit/internal/controls/alignment/alignment-impl.cpp index 407eb42..ac7a72f 100644 --- a/dali-toolkit/internal/controls/alignment/alignment-impl.cpp +++ b/dali-toolkit/internal/controls/alignment/alignment-impl.cpp @@ -20,8 +20,8 @@ // EXTERNAL INCLUDES #include -#include #include +#include #include // INTERNAL INCLUDES @@ -29,23 +29,19 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - //Type Registration BaseHandle Create() { return Toolkit::Alignment::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Alignment, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Alignment, Toolkit::Control, Create) DALI_TYPE_REGISTRATION_END() /** @@ -55,12 +51,11 @@ DALI_TYPE_REGISTRATION_END() * @param currentSize of the object * @param parentSize */ -inline Vector3 GetPosition( const Toolkit::Alignment::Padding& padding, Toolkit::Alignment::Type horizontalAlignment, Toolkit::Alignment::Type verticalAlignment, - const Vector2& currentSize, const Vector2& parentSize ) +inline Vector3 GetPosition(const Toolkit::Alignment::Padding& padding, Toolkit::Alignment::Type horizontalAlignment, Toolkit::Alignment::Type verticalAlignment, const Vector2& currentSize, const Vector2& parentSize) { - Vector3 position( 0.f, 0.f, 0.f ); + Vector3 position(0.f, 0.f, 0.f); - switch( horizontalAlignment ) + switch(horizontalAlignment) { case Dali::Toolkit::Alignment::HORIZONTAL_LEFT: { @@ -73,17 +68,17 @@ inline Vector3 GetPosition( const Toolkit::Alignment::Padding& padding, Toolkit: break; } case Dali::Toolkit::Alignment::HORIZONTAL_CENTER: // FALLTHROUGH - default: // use center as default + default: // use center as default { - if( currentSize.width + padding.left + padding.right >= parentSize.width ) + if(currentSize.width + padding.left + padding.right >= parentSize.width) { - position.x += 0.5f * ( padding.left - padding.right ); + position.x += 0.5f * (padding.left - padding.right); } break; } } - switch( verticalAlignment ) + switch(verticalAlignment) { case Dali::Toolkit::Alignment::VERTICAL_TOP: { @@ -96,11 +91,11 @@ inline Vector3 GetPosition( const Toolkit::Alignment::Padding& padding, Toolkit: break; } case Dali::Toolkit::Alignment::VERTICAL_CENTER: // FALLTHROUGH - default: // use center as default + default: // use center as default { - if( currentSize.height + padding.top + padding.bottom >= parentSize.height ) + if(currentSize.height + padding.top + padding.bottom >= parentSize.height) { - position.y += 0.5f * ( padding.top - padding.bottom ); + position.y += 0.5f * (padding.top - padding.bottom); } break; } @@ -111,13 +106,13 @@ inline Vector3 GetPosition( const Toolkit::Alignment::Padding& padding, Toolkit: } // namespace -Toolkit::Alignment Alignment::New( Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical ) +Toolkit::Alignment Alignment::New(Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical) { // Create the implementation, temporarily owned on stack - IntrusivePtr< Alignment > internalAlignment = new Alignment( horizontal, vertical ); + IntrusivePtr internalAlignment = new Alignment(horizontal, vertical); // Pass ownership to Toolkit::Alignment - Toolkit::Alignment alignment( *internalAlignment ); + Toolkit::Alignment alignment(*internalAlignment); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -126,32 +121,32 @@ Toolkit::Alignment Alignment::New( Toolkit::Alignment::Type horizontal, Toolkit: return alignment; } -void Alignment::SetAlignmentType( Toolkit::Alignment::Type type ) +void Alignment::SetAlignmentType(Toolkit::Alignment::Type type) { // Horizontal Alignment - if( type & Toolkit::Alignment::HORIZONTAL_RIGHT ) + if(type & Toolkit::Alignment::HORIZONTAL_RIGHT) { mHorizontal = Toolkit::Alignment::HORIZONTAL_RIGHT; } - if( type & Toolkit::Alignment::HORIZONTAL_LEFT ) + if(type & Toolkit::Alignment::HORIZONTAL_LEFT) { mHorizontal = Toolkit::Alignment::HORIZONTAL_LEFT; } - if( type & Toolkit::Alignment::HORIZONTAL_CENTER ) + if(type & Toolkit::Alignment::HORIZONTAL_CENTER) { mHorizontal = Toolkit::Alignment::HORIZONTAL_CENTER; } // Vertical Alignment - if( type & Toolkit::Alignment::VERTICAL_BOTTOM ) + if(type & Toolkit::Alignment::VERTICAL_BOTTOM) { mVertical = Toolkit::Alignment::VERTICAL_BOTTOM; } - if( type & Toolkit::Alignment::VERTICAL_TOP ) + if(type & Toolkit::Alignment::VERTICAL_TOP) { mVertical = Toolkit::Alignment::VERTICAL_TOP; } - if( type & Toolkit::Alignment::VERTICAL_CENTER ) + if(type & Toolkit::Alignment::VERTICAL_CENTER) { mVertical = Toolkit::Alignment::VERTICAL_CENTER; } @@ -161,10 +156,10 @@ void Alignment::SetAlignmentType( Toolkit::Alignment::Type type ) Toolkit::Alignment::Type Alignment::GetAlignmentType() const { - return Toolkit::Alignment::Type( mHorizontal | mVertical ); + return Toolkit::Alignment::Type(mHorizontal | mVertical); } -void Alignment::SetScaling( Toolkit::Alignment::Scaling scaling ) +void Alignment::SetScaling(Toolkit::Alignment::Scaling scaling) { mScaling = scaling; @@ -176,9 +171,9 @@ Toolkit::Alignment::Scaling Alignment::GetScaling() const return mScaling; } -void Alignment::SetPadding( const Toolkit::Alignment::Padding& padding ) +void Alignment::SetPadding(const Toolkit::Alignment::Padding& padding) { - DALI_ASSERT_ALWAYS( ( padding.left >= 0.f ) && ( padding.top >= 0.f ) && ( padding.right >= 0.f ) && ( padding.bottom >= 0.f ) ); + DALI_ASSERT_ALWAYS((padding.left >= 0.f) && (padding.top >= 0.f) && (padding.right >= 0.f) && (padding.bottom >= 0.f)); mPadding = padding; @@ -192,60 +187,60 @@ const Toolkit::Alignment::Padding& Alignment::GetPadding() const void Alignment::OnInitialize() { - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } -void Alignment::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void Alignment::OnRelayout(const Vector2& size, RelayoutContainer& container) { // lay out the actors - Vector3 anchorPointAndParentOrigin = Vector3::ZERO; - anchorPointAndParentOrigin.z = 0.5f; + Vector3 anchorPointAndParentOrigin = Vector3::ZERO; + anchorPointAndParentOrigin.z = 0.5f; // anchorPoint.x is initialized to 0.0, which is HORIZONTAL_LEFT - if( Toolkit::Alignment::HORIZONTAL_CENTER == mHorizontal ) + if(Toolkit::Alignment::HORIZONTAL_CENTER == mHorizontal) { anchorPointAndParentOrigin.x = 0.5f; } - else if( Toolkit::Alignment::HORIZONTAL_RIGHT == mHorizontal ) + else if(Toolkit::Alignment::HORIZONTAL_RIGHT == mHorizontal) { anchorPointAndParentOrigin.x = 1.0f; } // anchorPoint.y is initialized to 0.0, which is VERTICAL_TOP - if( Toolkit::Alignment::VERTICAL_CENTER == mVertical ) + if(Toolkit::Alignment::VERTICAL_CENTER == mVertical) { anchorPointAndParentOrigin.y = 0.5f; } - else if( Toolkit::Alignment::VERTICAL_BOTTOM == mVertical ) + else if(Toolkit::Alignment::VERTICAL_BOTTOM == mVertical) { anchorPointAndParentOrigin.y = 1.0f; } - for( unsigned int i = 0, childCount = Self().GetChildCount(); i < childCount; ++i ) + for(unsigned int i = 0, childCount = Self().GetChildCount(); i < childCount; ++i) { Actor child = Self().GetChildAt(i); - child.SetProperty( Actor::Property::ANCHOR_POINT, anchorPointAndParentOrigin ); - child.SetProperty( Actor::Property::PARENT_ORIGIN, anchorPointAndParentOrigin ); + child.SetProperty(Actor::Property::ANCHOR_POINT, anchorPointAndParentOrigin); + child.SetProperty(Actor::Property::PARENT_ORIGIN, anchorPointAndParentOrigin); - Vector2 currentChildSize( child.GetTargetSize().GetVectorXY() ); - if( currentChildSize == Vector2::ZERO ) + Vector2 currentChildSize(child.GetTargetSize().GetVectorXY()); + if(currentChildSize == Vector2::ZERO) { currentChildSize = child.GetNaturalSize(); } - bool renegotiate = true; + bool renegotiate = true; Vector2 newChildSize; - newChildSize.width = size.width - ( mPadding.left + mPadding.right ); - newChildSize.height = size.height- ( mPadding.top + mPadding.bottom ); + newChildSize.width = size.width - (mPadding.left + mPadding.right); + newChildSize.height = size.height - (mPadding.top + mPadding.bottom); // prevent ridiculous sizes if parent is really small or if we don't have a proper size for the actor - if( ( newChildSize.width > Math::MACHINE_EPSILON_1000 ) && ( newChildSize.height > Math::MACHINE_EPSILON_1000 ) && - ( currentChildSize.width > Math::MACHINE_EPSILON_1000 ) && ( currentChildSize.height > Math::MACHINE_EPSILON_1000 ) ) + if((newChildSize.width > Math::MACHINE_EPSILON_1000) && (newChildSize.height > Math::MACHINE_EPSILON_1000) && + (currentChildSize.width > Math::MACHINE_EPSILON_1000) && (currentChildSize.height > Math::MACHINE_EPSILON_1000)) { // no point trying to squeeze actors into too small size - switch( mScaling ) + switch(mScaling) { case Toolkit::Alignment::SCALE_NONE: { @@ -260,28 +255,28 @@ void Alignment::OnRelayout( const Vector2& size, RelayoutContainer& container ) } case Toolkit::Alignment::SCALE_TO_FIT_KEEP_ASPECT: { - newChildSize = currentChildSize * std::min( ( newChildSize.width / currentChildSize.width ), ( newChildSize.height / currentChildSize.height ) ); + newChildSize = currentChildSize * std::min((newChildSize.width / currentChildSize.width), (newChildSize.height / currentChildSize.height)); break; } case Toolkit::Alignment::SCALE_TO_FILL_KEEP_ASPECT: { - newChildSize = currentChildSize * std::max( ( newChildSize.width / currentChildSize.width ), ( newChildSize.height / currentChildSize.height ) ); + newChildSize = currentChildSize * std::max((newChildSize.width / currentChildSize.width), (newChildSize.height / currentChildSize.height)); break; } case Toolkit::Alignment::SHRINK_TO_FIT: { - newChildSize = Vector2( std::min( newChildSize.width, currentChildSize.width ), std::min( newChildSize.height, currentChildSize.height ) ); + newChildSize = Vector2(std::min(newChildSize.width, currentChildSize.width), std::min(newChildSize.height, currentChildSize.height)); break; } case Toolkit::Alignment::SHRINK_TO_FIT_KEEP_ASPECT: { // check source size vs target size to see if we need to shrink - float widthScale = ( newChildSize.width < currentChildSize.width ) ? (newChildSize.width / currentChildSize.width) : 1.f; - float heightScale = ( newChildSize.height < currentChildSize.height ) ? (newChildSize.height / currentChildSize.height) : 1.0f; + float widthScale = (newChildSize.width < currentChildSize.width) ? (newChildSize.width / currentChildSize.width) : 1.f; + float heightScale = (newChildSize.height < currentChildSize.height) ? (newChildSize.height / currentChildSize.height) : 1.0f; // use smaller of the scales - float scale = std::min( widthScale, heightScale ); + float scale = std::min(widthScale, heightScale); // check if we need to scale - if( scale < 1.0f ) + if(scale < 1.0f) { // scale natural size to fit inside newChildSize *= scale; @@ -291,21 +286,21 @@ void Alignment::OnRelayout( const Vector2& size, RelayoutContainer& container ) } } - child.SetProperty( Actor::Property::POSITION, GetPosition( mPadding, mHorizontal, mVertical , newChildSize, currentChildSize ) ); + child.SetProperty(Actor::Property::POSITION, GetPosition(mPadding, mHorizontal, mVertical, newChildSize, currentChildSize)); - if( renegotiate ) + if(renegotiate) { - container.Add( child, newChildSize ); + container.Add(child, newChildSize); } } } -Alignment::Alignment( Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical ) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mHorizontal( horizontal ), - mVertical( vertical ), - mScaling( Toolkit::Alignment::SCALE_NONE ), - mPadding( 0.f, 0.f, 0.f, 0.f ) +Alignment::Alignment(Toolkit::Alignment::Type horizontal, Toolkit::Alignment::Type vertical) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mHorizontal(horizontal), + mVertical(vertical), + mScaling(Toolkit::Alignment::SCALE_NONE), + mPadding(0.f, 0.f, 0.f, 0.f) { } diff --git a/dali-toolkit/internal/controls/bloom-view/bloom-view-impl.cpp b/dali-toolkit/internal/controls/bloom-view/bloom-view-impl.cpp index d54dcd3..b685219 100644 --- a/dali-toolkit/internal/controls/bloom-view/bloom-view-impl.cpp +++ b/dali-toolkit/internal/controls/bloom-view/bloom-view-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,33 @@ #include "bloom-view-impl.h" // EXTERNAL INCLUDES -#include -#include +#include #include #include -#include #include -#include #include +#include #include #include +#include +#include // INTERNAL INCLUDES -#include #include -#include -#include -#include +#include #include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - using namespace Dali; BaseHandle Create() @@ -57,72 +53,69 @@ BaseHandle Create() return Toolkit::BloomView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::BloomView, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::BloomView, Toolkit::Control, Create) DALI_TYPE_REGISTRATION_END() // default parameters -const float BLOOM_THRESHOLD_DEFAULT = 0.25f; +const float BLOOM_THRESHOLD_DEFAULT = 0.25f; const float BLOOM_BLUR_STRENGTH_DEFAULT = 1.0f; -const float BLOOM_INTENSITY_DEFAULT = 1.0f; -const float IMAGE_INTENSITY_DEFAULT = 1.0f; -const float BLOOM_SATURATION_DEFAULT = 1.0f; -const float IMAGE_SATURATION_DEFAULT = 1.0f; +const float BLOOM_INTENSITY_DEFAULT = 1.0f; +const float IMAGE_INTENSITY_DEFAULT = 1.0f; +const float BLOOM_SATURATION_DEFAULT = 1.0f; +const float IMAGE_SATURATION_DEFAULT = 1.0f; // gaussian blur -const unsigned int BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5; -const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f; +const unsigned int BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5; +const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f; const Pixel::Format BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888; -const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_FADE_IN = 1.0f; // default, fully blurred -const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f; -const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f; +const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_FADE_IN = 1.0f; // default, fully blurred +const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f; +const float BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f; const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f; -const char* const BLOOM_BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty"; -const char* const BLOOM_THRESHOLD_PROPERTY_NAME = "uBloomThreshold"; +const char* const BLOOM_BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty"; +const char* const BLOOM_THRESHOLD_PROPERTY_NAME = "uBloomThreshold"; const char* const RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME = "uRecipOneMinusBloomThreshold"; -const char* const BLOOM_INTENSITY_PROPERTY_NAME = "uBloomIntensity"; -const char* const BLOOM_SATURATION_PROPERTY_NAME = "uBloomSaturation"; -const char* const IMAGE_INTENSITY_PROPERTY_NAME = "uImageIntensity"; -const char* const IMAGE_SATURATION_PROPERTY_NAME = "uImageSaturation"; +const char* const BLOOM_INTENSITY_PROPERTY_NAME = "uBloomIntensity"; +const char* const BLOOM_SATURATION_PROPERTY_NAME = "uBloomSaturation"; +const char* const IMAGE_INTENSITY_PROPERTY_NAME = "uImageIntensity"; +const char* const IMAGE_SATURATION_PROPERTY_NAME = "uImageSaturation"; } // namespace - - BloomView::BloomView() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mBlurNumSamples(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES), mBlurBellCurveWidth(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH), mPixelFormat(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT), mDownsampleWidthScale(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE), mDownsampleHeightScale(BLOOM_GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE), - mDownsampledWidth( 0.0f ), - mDownsampledHeight( 0.0f ), + mDownsampledWidth(0.0f), + mDownsampledHeight(0.0f), mTargetSize(Vector2::ZERO), mLastSize(Vector2::ZERO), mChildrenRoot(Actor::New()), - mInternalRoot(Actor::New() ), + mInternalRoot(Actor::New()), mBloomThresholdPropertyIndex(Property::INVALID_INDEX), mBlurStrengthPropertyIndex(Property::INVALID_INDEX), mBloomIntensityPropertyIndex(Property::INVALID_INDEX), mBloomSaturationPropertyIndex(Property::INVALID_INDEX), mImageIntensityPropertyIndex(Property::INVALID_INDEX), mImageSaturationPropertyIndex(Property::INVALID_INDEX), - mActivated( false ) + mActivated(false) { } -BloomView::BloomView( const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, - const float downsampleWidthScale, const float downsampleHeightScale) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +BloomView::BloomView(const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, const float downsampleWidthScale, const float downsampleHeightScale) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mBlurNumSamples(blurNumSamples), mBlurBellCurveWidth(blurBellCurveWidth), mPixelFormat(renderTargetPixelFormat), mDownsampleWidthScale(downsampleWidthScale), mDownsampleHeightScale(downsampleHeightScale), - mDownsampledWidth( 0.0f ), - mDownsampledHeight( 0.0f ), + mDownsampledWidth(0.0f), + mDownsampledHeight(0.0f), mTargetSize(Vector2::ZERO), mLastSize(Vector2::ZERO), mChildrenRoot(Actor::New()), @@ -133,7 +126,7 @@ BloomView::BloomView( const unsigned int blurNumSamples, const float blurBellCur mBloomSaturationPropertyIndex(Property::INVALID_INDEX), mImageIntensityPropertyIndex(Property::INVALID_INDEX), mImageSaturationPropertyIndex(Property::INVALID_INDEX), - mActivated( false ) + mActivated(false) { } @@ -145,7 +138,7 @@ Toolkit::BloomView BloomView::New() { BloomView* impl = new BloomView(); - Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView( *impl ); + Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -154,12 +147,11 @@ Toolkit::BloomView BloomView::New() return handle; } -Toolkit::BloomView BloomView::New(const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, - const float downsampleWidthScale, const float downsampleHeightScale) +Toolkit::BloomView BloomView::New(const unsigned int blurNumSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, const float downsampleWidthScale, const float downsampleHeightScale) { - BloomView* impl = new BloomView( blurNumSamples, blurBellCurveWidth, renderTargetPixelFormat, downsampleWidthScale, downsampleHeightScale); + BloomView* impl = new BloomView(blurNumSamples, blurBellCurveWidth, renderTargetPixelFormat, downsampleWidthScale, downsampleHeightScale); - Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView( *impl ); + Dali::Toolkit::BloomView handle = Dali::Toolkit::BloomView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -176,69 +168,67 @@ Toolkit::BloomView BloomView::New(const unsigned int blurNumSamples, const float void BloomView::OnInitialize() { // root actor to parent all user added actors, needed to allow us to set that subtree as exclusive for our child render task - mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mInternalRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mInternalRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); ////////////////////////////////////////////////////// // Create actors // Create an image view for rendering from the scene texture to the bloom texture mBloomExtractActor = Actor::New(); - mBloomExtractActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mBloomExtractActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // Create an image view for compositing the result (scene and bloom textures) to output mCompositeActor = Actor::New(); - mCompositeActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mCompositeActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // Create an image view for holding final result, i.e. the blurred image. This will get rendered to screen later, via default / user render task mTargetActor = Actor::New(); - mTargetActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mTargetActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // Create the Gaussian Blur object + render tasks // Note that we use mBloomExtractTarget as the source image and also re-use this as the gaussian blur final render target. This saves the gaussian blur code from creating it // render targets etc internally, so we make better use of resources // Note, this also internally creates the render tasks used by the Gaussian blur, this must occur after the bloom extraction and before the compositing mGaussianBlurView = Dali::Toolkit::GaussianBlurView::New(mBlurNumSamples, mBlurBellCurveWidth, mPixelFormat, mDownsampleWidthScale, mDownsampleHeightScale, true); - mGaussianBlurView.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - + mGaussianBlurView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); ////////////////////////////////////////////////////// // Create cameras for the renders corresponding to the (potentially downsampled) render targets' size mRenderDownsampledCamera = CameraActor::New(); - mRenderDownsampledCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mRenderDownsampledCamera.SetInvertYAxis( true ); + mRenderDownsampledCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mRenderDownsampledCamera.SetInvertYAxis(true); mRenderFullSizeCamera = CameraActor::New(); - mRenderFullSizeCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mRenderFullSizeCamera.SetInvertYAxis( true ); - + mRenderFullSizeCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mRenderFullSizeCamera.SetInvertYAxis(true); //////////////////////////////// // Connect to actor tree - Self().Add( mChildrenRoot ); - Self().Add( mInternalRoot ); - mInternalRoot.Add( mBloomExtractActor ); - mInternalRoot.Add( mGaussianBlurView ); - mInternalRoot.Add( mCompositeActor ); - mInternalRoot.Add( mTargetActor ); - mInternalRoot.Add( mRenderDownsampledCamera ); - mInternalRoot.Add( mRenderFullSizeCamera ); + Self().Add(mChildrenRoot); + Self().Add(mInternalRoot); + mInternalRoot.Add(mBloomExtractActor); + mInternalRoot.Add(mGaussianBlurView); + mInternalRoot.Add(mCompositeActor); + mInternalRoot.Add(mTargetActor); + mInternalRoot.Add(mRenderDownsampledCamera); + mInternalRoot.Add(mRenderFullSizeCamera); // bind properties for / set shader constants to defaults SetupProperties(); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::ANIMATION ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::ANIMATION)); + }); } void BloomView::OnSizeSet(const Vector3& targetSize) { mTargetSize = Vector2(targetSize); - mChildrenRoot.SetProperty( Actor::Property::SIZE, targetSize); - mCompositeActor.SetProperty( Actor::Property::SIZE, targetSize); - mTargetActor.SetProperty( Actor::Property::SIZE, targetSize); + mChildrenRoot.SetProperty(Actor::Property::SIZE, targetSize); + mCompositeActor.SetProperty(Actor::Property::SIZE, targetSize); + mTargetActor.SetProperty(Actor::Property::SIZE, targetSize); // Children render camera must move when GaussianBlurView object is // resized. This is since we cannot change render target size - so we need @@ -248,7 +238,7 @@ void BloomView::OnSizeSet(const Vector3& targetSize) // this is the trade off for not being able to modify render target size // Change camera z position based on GaussianBlurView actor height float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f); - mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale); + mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale); // if we have already activated the blur, need to update render target sizes now to reflect the new size of this actor if(mActivated) @@ -257,24 +247,24 @@ void BloomView::OnSizeSet(const Vector3& targetSize) Activate(); } - Control::OnSizeSet( targetSize ); + Control::OnSizeSet(targetSize); } -void BloomView::OnChildAdd( Actor& child ) +void BloomView::OnChildAdd(Actor& child) { - if( child != mChildrenRoot && child != mInternalRoot) + if(child != mChildrenRoot && child != mInternalRoot) { - mChildrenRoot.Add( child ); + mChildrenRoot.Add(child); } - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void BloomView::OnChildRemove( Actor& child ) +void BloomView::OnChildRemove(Actor& child) { - mChildrenRoot.Remove( child ); + mChildrenRoot.Remove(child); - Control::OnChildRemove( child ); + Control::OnChildRemove(child); } void BloomView::AllocateResources() @@ -285,10 +275,9 @@ void BloomView::AllocateResources() mLastSize = mTargetSize; // get size of downsampled render targets - mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale; + mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale; mDownsampledHeight = mTargetSize.height * mDownsampleHeightScale; - ////////////////////////////////////////////////////// // Create cameras @@ -298,7 +287,7 @@ void BloomView::AllocateResources() mRenderDownsampledCamera.SetAspectRatio(mDownsampledWidth / mDownsampledHeight); mRenderDownsampledCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor - mRenderDownsampledCamera.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, ( ( mDownsampledHeight * 0.5f ) / tanf( ARBITRARY_FIELD_OF_VIEW * 0.5f ) ) ) ); + mRenderDownsampledCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)))); // Create and place a camera for the children render, corresponding to its render target size mRenderFullSizeCamera.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW); @@ -307,58 +296,58 @@ void BloomView::AllocateResources() mRenderFullSizeCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f); - mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale ) ); + mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale)); ////////////////////////////////////////////////////// // Pass size change onto GaussianBlurView, so it matches - mGaussianBlurView.SetProperty( Actor::Property::SIZE, mTargetSize ); + mGaussianBlurView.SetProperty(Actor::Property::SIZE, mTargetSize); GetImpl(mGaussianBlurView).AllocateResources(); - mGaussianBlurView.SetProperty( Actor::Property::VISIBLE, true ); + mGaussianBlurView.SetProperty(Actor::Property::VISIBLE, true); ////////////////////////////////////////////////////// // Create render targets // create off screen buffer of new size to render our child actors to - mRenderTargetForRenderingChildren = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture textureForChildren = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mRenderTargetForRenderingChildren.AttachColorTexture( textureForChildren ); + mRenderTargetForRenderingChildren = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture textureForChildren = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mRenderTargetForRenderingChildren.AttachColorTexture(textureForChildren); - mBloomExtractTarget = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE ); - Texture texture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight) ); - mBloomExtractTarget.AttachColorTexture( texture ); + mBloomExtractTarget = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE); + Texture texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight)); + mBloomExtractTarget.AttachColorTexture(texture); - FrameBuffer blurExtractTarget = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE ); - texture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight) ); - blurExtractTarget.AttachColorTexture( texture ); + FrameBuffer blurExtractTarget = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE); + texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight)); + blurExtractTarget.AttachColorTexture(texture); - mOutputRenderTarget = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture outputTexture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mOutputRenderTarget.AttachColorTexture( outputTexture ); + mOutputRenderTarget = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture outputTexture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mOutputRenderTarget.AttachColorTexture(outputTexture); ////////////////////////////////////////////////////// // Point actors and render tasks at new render targets - Renderer bloomRenderer = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_EXTRACT_SHADER_FRAG ); - SetRendererTexture( bloomRenderer, mRenderTargetForRenderingChildren ); - mBloomExtractActor.AddRenderer( bloomRenderer ); - mBloomExtractActor.SetProperty( Actor::Property::SIZE, Vector2( mDownsampledWidth, mDownsampledHeight ) ); // size needs to match render target + Renderer bloomRenderer = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_EXTRACT_SHADER_FRAG); + SetRendererTexture(bloomRenderer, mRenderTargetForRenderingChildren); + mBloomExtractActor.AddRenderer(bloomRenderer); + mBloomExtractActor.SetProperty(Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight)); // size needs to match render target // set GaussianBlurView to blur our extracted bloom - mGaussianBlurView.SetUserImageAndOutputRenderTarget( mBloomExtractTarget.GetColorTexture(), blurExtractTarget ); + mGaussianBlurView.SetUserImageAndOutputRenderTarget(mBloomExtractTarget.GetColorTexture(), blurExtractTarget); // use the completed blur in the first buffer and composite with the original child actors render - Renderer compositeRenderer = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_COMPOSITE_SHADER_FRAG ); - SetRendererTexture( compositeRenderer, mRenderTargetForRenderingChildren ); + Renderer compositeRenderer = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_BLOOM_VIEW_COMPOSITE_SHADER_FRAG); + SetRendererTexture(compositeRenderer, mRenderTargetForRenderingChildren); TextureSet textureSet = compositeRenderer.GetTextures(); - textureSet.SetTexture( 0u, mRenderTargetForRenderingChildren.GetColorTexture() ); - textureSet.SetTexture( 1u, blurExtractTarget.GetColorTexture() ); - mCompositeActor.AddRenderer( compositeRenderer ); + textureSet.SetTexture(0u, mRenderTargetForRenderingChildren.GetColorTexture()); + textureSet.SetTexture(1u, blurExtractTarget.GetColorTexture()); + mCompositeActor.AddRenderer(compositeRenderer); // set up target actor for rendering result, i.e. the blurred image - Renderer targetRenderer = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE ); - SetRendererTexture( targetRenderer, mOutputRenderTarget ); - mTargetActor.AddRenderer( targetRenderer ); + Renderer targetRenderer = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE); + SetRendererTexture(targetRenderer, mOutputRenderTarget); + mTargetActor.AddRenderer(targetRenderer); } } @@ -368,33 +357,33 @@ void BloomView::CreateRenderTasks() // create render task to render our child actors to offscreen buffer mRenderChildrenTask = taskList.CreateTask(); - mRenderChildrenTask.SetSourceActor( mChildrenRoot ); + mRenderChildrenTask.SetSourceActor(mChildrenRoot); mRenderChildrenTask.SetExclusive(true); - mRenderChildrenTask.SetInputEnabled( false ); - mRenderChildrenTask.SetClearEnabled( true ); + mRenderChildrenTask.SetInputEnabled(false); + mRenderChildrenTask.SetClearEnabled(true); mRenderChildrenTask.SetCameraActor(mRenderFullSizeCamera); // use camera that covers render target exactly - mRenderChildrenTask.SetFrameBuffer( mRenderTargetForRenderingChildren ); + mRenderChildrenTask.SetFrameBuffer(mRenderTargetForRenderingChildren); // Extract the bright part of the image and render to a new buffer. Downsampling also occurs at this stage to save pixel fill, if it is set up. mBloomExtractTask = taskList.CreateTask(); - mBloomExtractTask.SetSourceActor( mBloomExtractActor ); + mBloomExtractTask.SetSourceActor(mBloomExtractActor); mBloomExtractTask.SetExclusive(true); - mBloomExtractTask.SetInputEnabled( false ); - mBloomExtractTask.SetClearEnabled( true ); + mBloomExtractTask.SetInputEnabled(false); + mBloomExtractTask.SetClearEnabled(true); mBloomExtractTask.SetCameraActor(mRenderDownsampledCamera); - mBloomExtractTask.SetFrameBuffer( mBloomExtractTarget ); + mBloomExtractTask.SetFrameBuffer(mBloomExtractTarget); // GaussianBlurView tasks must be created here, so they are executed in the correct order with respect to BloomView tasks GetImpl(mGaussianBlurView).CreateRenderTasks(); // Use an image view displaying the children render and composite it with the blurred bloom buffer, targeting the output mCompositeTask = taskList.CreateTask(); - mCompositeTask.SetSourceActor( mCompositeActor ); + mCompositeTask.SetSourceActor(mCompositeActor); mCompositeTask.SetExclusive(true); - mCompositeTask.SetInputEnabled( false ); - mCompositeTask.SetClearEnabled( true ); + mCompositeTask.SetInputEnabled(false); + mCompositeTask.SetClearEnabled(true); mCompositeTask.SetCameraActor(mRenderFullSizeCamera); - mCompositeTask.SetFrameBuffer( mOutputRenderTarget ); + mCompositeTask.SetFrameBuffer(mOutputRenderTarget); } void BloomView::RemoveRenderTasks() @@ -428,11 +417,11 @@ void BloomView::Deactivate() mOutputRenderTarget.Reset(); // Reset children - mBloomExtractActor.RemoveRenderer( 0u ); - mTargetActor.RemoveRenderer( 0u ); - mCompositeActor.RemoveRenderer( 0u ); + mBloomExtractActor.RemoveRenderer(0u); + mTargetActor.RemoveRenderer(0u); + mCompositeActor.RemoveRenderer(0u); - mGaussianBlurView.SetProperty( Actor::Property::VISIBLE, false ); + mGaussianBlurView.SetProperty(Actor::Property::VISIBLE, false); mActivated = false; } @@ -444,11 +433,13 @@ void BloomView::Deactivate() */ struct RecipOneMinusConstraint { - RecipOneMinusConstraint(){} + RecipOneMinusConstraint() + { + } - void operator()( float& current, const PropertyInputContainer& inputs ) + void operator()(float& current, const PropertyInputContainer& inputs) { - current = 1.0f / ( 1.0f - inputs[0]->GetFloat() ); + current = 1.0f / (1.0f - inputs[0]->GetFloat()); } }; @@ -458,83 +449,77 @@ void BloomView::SetupProperties() { CustomActor self = Self(); - /////////////////////////////////////////// // bloom threshold // set defaults, makes sure properties are registered with shader - mBloomExtractActor.RegisterProperty( BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT ); - mBloomExtractActor.RegisterProperty( RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME, 1.0f / (1.0f - BLOOM_THRESHOLD_DEFAULT) ); + mBloomExtractActor.RegisterProperty(BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT); + mBloomExtractActor.RegisterProperty(RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME, 1.0f / (1.0f - BLOOM_THRESHOLD_DEFAULT)); // Register a property that the user can control to change the bloom threshold - mBloomThresholdPropertyIndex = self.RegisterProperty(BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT); + mBloomThresholdPropertyIndex = self.RegisterProperty(BLOOM_THRESHOLD_PROPERTY_NAME, BLOOM_THRESHOLD_DEFAULT); Property::Index shaderBloomThresholdPropertyIndex = mBloomExtractActor.GetPropertyIndex(BLOOM_THRESHOLD_PROPERTY_NAME); - Constraint bloomThresholdConstraint = Constraint::New( mBloomExtractActor, shaderBloomThresholdPropertyIndex, EqualToConstraint()); - bloomThresholdConstraint.AddSource( Source(self, mBloomThresholdPropertyIndex) ); + Constraint bloomThresholdConstraint = Constraint::New(mBloomExtractActor, shaderBloomThresholdPropertyIndex, EqualToConstraint()); + bloomThresholdConstraint.AddSource(Source(self, mBloomThresholdPropertyIndex)); bloomThresholdConstraint.Apply(); // precalc 1.0 / (1.0 - threshold) on CPU to save shader insns, using constraint to tie to the normal threshold property Property::Index shaderRecipOneMinusBloomThresholdPropertyIndex = mBloomExtractActor.GetPropertyIndex(RECIP_ONE_MINUS_BLOOM_THRESHOLD_PROPERTY_NAME); - Constraint thresholdConstraint = Constraint::New( mBloomExtractActor, shaderRecipOneMinusBloomThresholdPropertyIndex, RecipOneMinusConstraint()); - thresholdConstraint.AddSource( LocalSource(shaderBloomThresholdPropertyIndex) ); + Constraint thresholdConstraint = Constraint::New(mBloomExtractActor, shaderRecipOneMinusBloomThresholdPropertyIndex, RecipOneMinusConstraint()); + thresholdConstraint.AddSource(LocalSource(shaderBloomThresholdPropertyIndex)); thresholdConstraint.Apply(); - //////////////////////////////////////////// // bloom strength // Register a property that the user can control to fade the blur in / out via internal GaussianBlurView object - mBlurStrengthPropertyIndex = self.RegisterProperty(BLOOM_BLUR_STRENGTH_PROPERTY_NAME, BLOOM_BLUR_STRENGTH_DEFAULT); - Constraint blurStrengthConstraint = Constraint::New( mGaussianBlurView, mGaussianBlurView.GetBlurStrengthPropertyIndex(), EqualToConstraint()); - blurStrengthConstraint.AddSource( Source(self, mBlurStrengthPropertyIndex) ); + mBlurStrengthPropertyIndex = self.RegisterProperty(BLOOM_BLUR_STRENGTH_PROPERTY_NAME, BLOOM_BLUR_STRENGTH_DEFAULT); + Constraint blurStrengthConstraint = Constraint::New(mGaussianBlurView, mGaussianBlurView.GetBlurStrengthPropertyIndex(), EqualToConstraint()); + blurStrengthConstraint.AddSource(Source(self, mBlurStrengthPropertyIndex)); blurStrengthConstraint.Apply(); - //////////////////////////////////////////// // bloom intensity // Register a property that the user can control to fade the bloom intensity via internally hidden shader mBloomIntensityPropertyIndex = self.RegisterProperty(BLOOM_INTENSITY_PROPERTY_NAME, BLOOM_INTENSITY_DEFAULT); - mCompositeActor.RegisterProperty( BLOOM_INTENSITY_PROPERTY_NAME, BLOOM_INTENSITY_DEFAULT ); + mCompositeActor.RegisterProperty(BLOOM_INTENSITY_PROPERTY_NAME, BLOOM_INTENSITY_DEFAULT); Property::Index shaderBloomIntensityPropertyIndex = mCompositeActor.GetPropertyIndex(BLOOM_INTENSITY_PROPERTY_NAME); - Constraint bloomIntensityConstraint = Constraint::New( mCompositeActor, shaderBloomIntensityPropertyIndex, EqualToConstraint()); - bloomIntensityConstraint.AddSource( Source(self, mBloomIntensityPropertyIndex) ); + Constraint bloomIntensityConstraint = Constraint::New(mCompositeActor, shaderBloomIntensityPropertyIndex, EqualToConstraint()); + bloomIntensityConstraint.AddSource(Source(self, mBloomIntensityPropertyIndex)); bloomIntensityConstraint.Apply(); - //////////////////////////////////////////// // bloom saturation // Register a property that the user can control to fade the bloom saturation via internally hidden shader mBloomSaturationPropertyIndex = self.RegisterProperty(BLOOM_SATURATION_PROPERTY_NAME, BLOOM_SATURATION_DEFAULT); - mCompositeActor.RegisterProperty( BLOOM_SATURATION_PROPERTY_NAME, BLOOM_SATURATION_DEFAULT ); + mCompositeActor.RegisterProperty(BLOOM_SATURATION_PROPERTY_NAME, BLOOM_SATURATION_DEFAULT); Property::Index shaderBloomSaturationPropertyIndex = mCompositeActor.GetPropertyIndex(BLOOM_SATURATION_PROPERTY_NAME); - Constraint bloomSaturationConstraint = Constraint::New( mCompositeActor, shaderBloomSaturationPropertyIndex, EqualToConstraint()); - bloomSaturationConstraint.AddSource( Source(self, mBloomSaturationPropertyIndex) ); + Constraint bloomSaturationConstraint = Constraint::New(mCompositeActor, shaderBloomSaturationPropertyIndex, EqualToConstraint()); + bloomSaturationConstraint.AddSource(Source(self, mBloomSaturationPropertyIndex)); bloomSaturationConstraint.Apply(); - //////////////////////////////////////////// // image intensity // Register a property that the user can control to fade the image intensity via internally hidden shader mImageIntensityPropertyIndex = self.RegisterProperty(IMAGE_INTENSITY_PROPERTY_NAME, IMAGE_INTENSITY_DEFAULT); - mCompositeActor.RegisterProperty( IMAGE_INTENSITY_PROPERTY_NAME, IMAGE_INTENSITY_DEFAULT ); + mCompositeActor.RegisterProperty(IMAGE_INTENSITY_PROPERTY_NAME, IMAGE_INTENSITY_DEFAULT); Property::Index shaderImageIntensityPropertyIndex = mCompositeActor.GetPropertyIndex(IMAGE_INTENSITY_PROPERTY_NAME); - Constraint imageIntensityConstraint = Constraint::New( mCompositeActor, shaderImageIntensityPropertyIndex, EqualToConstraint()); - imageIntensityConstraint.AddSource( Source(self, mImageIntensityPropertyIndex) ); + Constraint imageIntensityConstraint = Constraint::New(mCompositeActor, shaderImageIntensityPropertyIndex, EqualToConstraint()); + imageIntensityConstraint.AddSource(Source(self, mImageIntensityPropertyIndex)); imageIntensityConstraint.Apply(); - //////////////////////////////////////////// // image saturation // Register a property that the user can control to fade the image saturation via internally hidden shader mImageSaturationPropertyIndex = self.RegisterProperty(IMAGE_SATURATION_PROPERTY_NAME, IMAGE_SATURATION_DEFAULT); - mCompositeActor.RegisterProperty( IMAGE_SATURATION_PROPERTY_NAME, IMAGE_SATURATION_DEFAULT ); + mCompositeActor.RegisterProperty(IMAGE_SATURATION_PROPERTY_NAME, IMAGE_SATURATION_DEFAULT); Property::Index shaderImageSaturationPropertyIndex = mCompositeActor.GetPropertyIndex(IMAGE_SATURATION_PROPERTY_NAME); - Constraint imageSaturationConstraint = Constraint::New( mCompositeActor, shaderImageSaturationPropertyIndex, EqualToConstraint()); - imageSaturationConstraint.AddSource( Source(self, mImageSaturationPropertyIndex) ); + Constraint imageSaturationConstraint = Constraint::New(mCompositeActor, shaderImageSaturationPropertyIndex, EqualToConstraint()); + imageSaturationConstraint.AddSource(Source(self, mImageSaturationPropertyIndex)); imageSaturationConstraint.Apply(); } diff --git a/dali-toolkit/internal/controls/bubble-effect/bubble-emitter-impl.cpp b/dali-toolkit/internal/controls/bubble-effect/bubble-emitter-impl.cpp index b1e28e7..dde8253 100644 --- a/dali-toolkit/internal/controls/bubble-effect/bubble-emitter-impl.cpp +++ b/dali-toolkit/internal/controls/bubble-effect/bubble-emitter-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. @@ -21,8 +21,8 @@ // EXTERNAL INCLUDES #include #include -#include #include +#include // INTERNAL INCLUDES #include @@ -34,16 +34,20 @@ namespace struct Vertex { Vertex() - : index( 0.0f ), position(), textureCoord() + : index(0.0f), + position(), + textureCoord() { } - Vertex( float index, const Dali::Vector2& position, const Dali::Vector2& textureCoord ) - : index( index ), position( position ), textureCoord( textureCoord ) + Vertex(float index, const Dali::Vector2& position, const Dali::Vector2& textureCoord) + : index(index), + position(position), + textureCoord(textureCoord) { } - float index; + float index; Dali::Vector2 position; Dali::Vector2 textureCoord; }; @@ -57,7 +61,7 @@ struct Vertex */ float RandomRange(float f0, float f1, unsigned int& seed) { - return f0 + (rand_r( &seed ) & 0xfff) * (f1-f0) * (1.0f/4095.0f); + return f0 + (rand_r(&seed) & 0xfff) * (f1 - f0) * (1.0f / 4095.0f); } Dali::Geometry CreateTexturedQuad() @@ -68,85 +72,82 @@ Dali::Geometry CreateTexturedQuad() Dali::Vector2 texCoord; }; - static const Vertex data[] = {{ Dali::Vector2( -0.5f, -0.5f ), Dali::Vector2( 0.0f, 0.0f ) }, - { Dali::Vector2( 0.5f, -0.5f ), Dali::Vector2( 1.0f, 0.0f ) }, - { Dali::Vector2( -0.5f, 0.5f ), Dali::Vector2( 0.0f, 1.0f ) }, - { Dali::Vector2( 0.5f, 0.5f ), Dali::Vector2( 1.0f, 1.0f ) }}; + static const Vertex data[] = {{Dali::Vector2(-0.5f, -0.5f), Dali::Vector2(0.0f, 0.0f)}, + {Dali::Vector2(0.5f, -0.5f), Dali::Vector2(1.0f, 0.0f)}, + {Dali::Vector2(-0.5f, 0.5f), Dali::Vector2(0.0f, 1.0f)}, + {Dali::Vector2(0.5f, 0.5f), Dali::Vector2(1.0f, 1.0f)}}; // Create a vertex buffer for vertex positions and texture coordinates - Dali::VertexBuffer vertexBuffer = Dali::VertexBuffer::New( Dali::Property::Map() - .Add( "aPosition", Dali::Property::VECTOR2 ) - .Add( "aTexCoord", Dali::Property::VECTOR2 ) ); - vertexBuffer.SetData( data, 4u ); + Dali::VertexBuffer vertexBuffer = Dali::VertexBuffer::New(Dali::Property::Map() + .Add("aPosition", Dali::Property::VECTOR2) + .Add("aTexCoord", Dali::Property::VECTOR2)); + vertexBuffer.SetData(data, 4u); //Create the geometry Dali::Geometry geometry = Dali::Geometry::New(); - geometry.AddVertexBuffer( vertexBuffer ); - geometry.SetType(Dali::Geometry::TRIANGLE_STRIP ); + geometry.AddVertexBuffer(vertexBuffer); + geometry.SetType(Dali::Geometry::TRIANGLE_STRIP); return geometry; } -} +} // namespace namespace Dali { - namespace Toolkit { - namespace Internal { -BubbleEmitter::BubbleEmitter( const Vector2& movementArea, - Texture shapeTexture, - unsigned int maximumNumberOfBubble, - const Vector2& bubbleSizeRange ) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mShapeTexture( shapeTexture ), - mMovementArea( movementArea ), - mBubbleSizeRange( bubbleSizeRange ), - mDensity( 5 ), - mTotalNumOfBubble( maximumNumberOfBubble ), - mCurrentBubble( 0 ), - mRandomSeed( 0 ), +BubbleEmitter::BubbleEmitter(const Vector2& movementArea, + Texture shapeTexture, + unsigned int maximumNumberOfBubble, + const Vector2& bubbleSizeRange) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mShapeTexture(shapeTexture), + mMovementArea(movementArea), + mBubbleSizeRange(bubbleSizeRange), + mDensity(5), + mTotalNumOfBubble(maximumNumberOfBubble), + mCurrentBubble(0), + mRandomSeed(0), mRenderTaskRunning(false) { // Calculate how many shaders are required - if( mTotalNumOfBubble>100 ) + if(mTotalNumOfBubble > 100) { mNumBubblePerRenderer = 100; - mNumRenderer = mTotalNumOfBubble / 100; - if( mNumRenderer*mNumBubblePerRenderer < mTotalNumOfBubble ) + mNumRenderer = mTotalNumOfBubble / 100; + if(mNumRenderer * mNumBubblePerRenderer < mTotalNumOfBubble) { mNumRenderer++; - mNumBubblePerRenderer = mTotalNumOfBubble / mNumRenderer+1; - mTotalNumOfBubble = mNumRenderer * mNumBubblePerRenderer; + mNumBubblePerRenderer = mTotalNumOfBubble / mNumRenderer + 1; + mTotalNumOfBubble = mNumRenderer * mNumBubblePerRenderer; } } else { mNumBubblePerRenderer = mTotalNumOfBubble; - mNumRenderer = 1; + mNumRenderer = 1; } - mRandomSeed = time( NULL ); + mRandomSeed = time(NULL); } BubbleEmitter::~BubbleEmitter() { } -Toolkit::BubbleEmitter BubbleEmitter::New( const Vector2& winSize, - Texture shapeTexture, - unsigned int maximumNumberOfBubble, - const Vector2& bubbleSizeRange ) +Toolkit::BubbleEmitter BubbleEmitter::New(const Vector2& winSize, + Texture shapeTexture, + unsigned int maximumNumberOfBubble, + const Vector2& bubbleSizeRange) { // Create the implementation - IntrusivePtr internalBubbleEmitter ( new BubbleEmitter( winSize, shapeTexture, - maximumNumberOfBubble,bubbleSizeRange ) ); + IntrusivePtr internalBubbleEmitter(new BubbleEmitter(winSize, shapeTexture, maximumNumberOfBubble, bubbleSizeRange)); // Pass ownership to Toolkit::BubbleEmitter handle - Toolkit::BubbleEmitter bubbleEmitter( *internalBubbleEmitter ); + Toolkit::BubbleEmitter bubbleEmitter(*internalBubbleEmitter); //Second phase of implementeation : Initialization internalBubbleEmitter->OnInitialize(); @@ -158,34 +159,34 @@ void BubbleEmitter::OnInitialize() { // Create the root actor, all the meshActor should be its children mBubbleRoot = Actor::New(); - mBubbleRoot.SetProperty( Actor::Property::SIZE, mMovementArea ); + mBubbleRoot.SetProperty(Actor::Property::SIZE, mMovementArea); // Prepare the frame buffer to store the color adjusted background texture - Vector2 imageSize = Vector2( mMovementArea.width/4.f, mMovementArea.height/4.f ); - mFrameBuffer = FrameBuffer::New( imageSize.x, imageSize.y, FrameBuffer::Attachment::NONE ); - mEffectTexture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, imageSize.x, imageSize.y ); - mFrameBuffer.AttachColorTexture( mEffectTexture ); + Vector2 imageSize = Vector2(mMovementArea.width / 4.f, mMovementArea.height / 4.f); + mFrameBuffer = FrameBuffer::New(imageSize.x, imageSize.y, FrameBuffer::Attachment::NONE); + mEffectTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, imageSize.x, imageSize.y); + mFrameBuffer.AttachColorTexture(mEffectTexture); // Generate the geometry, which is used by all bubbleActors - mMeshGeometry = CreateGeometry( mNumBubblePerRenderer*mDensity ); + mMeshGeometry = CreateGeometry(mNumBubblePerRenderer * mDensity); - Shader bubbleShader = CreateBubbleShader( mNumBubblePerRenderer ); + Shader bubbleShader = CreateBubbleShader(mNumBubblePerRenderer); mTextureSet = TextureSet::New(); - mTextureSet.SetTexture( 0u, mEffectTexture ); - mTextureSet.SetTexture( 1u, mShapeTexture ); + mTextureSet.SetTexture(0u, mEffectTexture); + mTextureSet.SetTexture(1u, mShapeTexture); // Create the renderers to render the bubbles - mBubbleRenderers.resize( mNumRenderer ); - for(unsigned int i=0; i < mNumRenderer; i++ ) + mBubbleRenderers.resize(mNumRenderer); + for(unsigned int i = 0; i < mNumRenderer; i++) { - mBubbleRenderers[i].Initialize( mNumBubblePerRenderer, mMovementArea, mMeshGeometry, mTextureSet, bubbleShader ); - mBubbleRoot.AddRenderer( mBubbleRenderers[i].GetRenderer() ); + mBubbleRenderers[i].Initialize(mNumBubblePerRenderer, mMovementArea, mMeshGeometry, mTextureSet, bubbleShader); + mBubbleRoot.AddRenderer(mBubbleRenderers[i].GetRenderer()); } // Create a cameraActor for the off screen render task. mCameraActor = CameraActor::New(mMovementArea); - mCameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); Stage stage = Stage::GetCurrent(); @@ -198,67 +199,67 @@ Actor BubbleEmitter::GetRootActor() return mBubbleRoot; } -void BubbleEmitter::SetBackground( Texture bgTexture, const Vector3& hsvDelta ) +void BubbleEmitter::SetBackground(Texture bgTexture, const Vector3& hsvDelta) { mBackgroundTexture = bgTexture; - mHSVDelta = hsvDelta; + mHSVDelta = hsvDelta; //Create RenderTask source actor Actor sourceActor = Actor::New(); - sourceActor.SetProperty( Actor::Property::SIZE, mMovementArea ); - sourceActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - sourceActor.RegisterProperty( "uHSVDelta", hsvDelta ); - Stage::GetCurrent().Add( sourceActor ); + sourceActor.SetProperty(Actor::Property::SIZE, mMovementArea); + sourceActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + sourceActor.RegisterProperty("uHSVDelta", hsvDelta); + Stage::GetCurrent().Add(sourceActor); //Create renderer - Dali::Geometry geometry = CreateTexturedQuad(); - Shader shader = Shader::New( SHADER_BUBBLE_EMITTER_VERT, SHADER_BUBBLE_EMITTER_FRAG ); - Renderer renderer = Renderer::New( geometry, shader ); - TextureSet textureSet = TextureSet::New(); - textureSet.SetTexture(0u, bgTexture ); - renderer.SetTextures( textureSet ); - sourceActor.AddRenderer( renderer ); + Dali::Geometry geometry = CreateTexturedQuad(); + Shader shader = Shader::New(SHADER_BUBBLE_EMITTER_VERT, SHADER_BUBBLE_EMITTER_FRAG); + Renderer renderer = Renderer::New(geometry, shader); + TextureSet textureSet = TextureSet::New(); + textureSet.SetTexture(0u, bgTexture); + renderer.SetTextures(textureSet); + sourceActor.AddRenderer(renderer); RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); - RenderTask task = taskList.CreateTask(); - task.SetRefreshRate( RenderTask::REFRESH_ONCE ); - task.SetSourceActor( sourceActor ); + RenderTask task = taskList.CreateTask(); + task.SetRefreshRate(RenderTask::REFRESH_ONCE); + task.SetSourceActor(sourceActor); task.SetExclusive(true); task.SetCameraActor(mCameraActor); task.GetCameraActor().SetInvertYAxis(true); - task.SetFrameBuffer( mFrameBuffer ); + task.SetFrameBuffer(mFrameBuffer); task.FinishedSignal().Connect(this, &BubbleEmitter::OnRenderFinished); mRenderTaskRunning = true; } -void BubbleEmitter::SetBubbleShape( Texture shapeTexture ) +void BubbleEmitter::SetBubbleShape(Texture shapeTexture) { - mTextureSet.SetTexture( 1, shapeTexture ); + mTextureSet.SetTexture(1, shapeTexture); } -void BubbleEmitter::SetBubbleScale( float scale ) +void BubbleEmitter::SetBubbleScale(float scale) { - for(unsigned int i=0; i < mNumRenderer; i++ ) + for(unsigned int i = 0; i < mNumRenderer; i++) { - mBubbleRenderers[i].SetDynamicScale( scale ); + mBubbleRenderers[i].SetDynamicScale(scale); } } -void BubbleEmitter::SetBubbleDensity( unsigned int density ) +void BubbleEmitter::SetBubbleDensity(unsigned int density) { - DALI_ASSERT_ALWAYS( density>0 && density<=9 && " Only densities between 1 to 9 are valid " ); + DALI_ASSERT_ALWAYS(density > 0 && density <= 9 && " Only densities between 1 to 9 are valid "); - if( density == mDensity ) + if(density == mDensity) { return; } else { - mDensity = density; - mMeshGeometry = CreateGeometry( mNumBubblePerRenderer*mDensity ); - for(unsigned int i=0; i < mNumRenderer; i++ ) + mDensity = density; + mMeshGeometry = CreateGeometry(mNumBubblePerRenderer * mDensity); + for(unsigned int i = 0; i < mNumRenderer; i++) { - mBubbleRenderers[i].SetGeometry( mMeshGeometry ); + mBubbleRenderers[i].SetGeometry(mMeshGeometry); } } } @@ -267,8 +268,8 @@ void BubbleEmitter::SetBubbleDensity( unsigned int density ) void BubbleEmitter::OnRenderFinished(RenderTask& source) { mRenderTaskRunning = false; - Actor sourceActor = source.GetSourceActor(); - Stage stage = Stage::GetCurrent(); + Actor sourceActor = source.GetSourceActor(); + Stage stage = Stage::GetCurrent(); stage.Remove(sourceActor); stage.GetRenderTaskList().RemoveTask(source); } @@ -277,94 +278,94 @@ void BubbleEmitter::OnContextRegained() { // Context was lost, so the framebuffer has been destroyed. Re-create render task // and trigger re-draw if not already running - if( ! mRenderTaskRunning ) + if(!mRenderTaskRunning) { - SetBackground( mBackgroundTexture, mHSVDelta ); + SetBackground(mBackgroundTexture, mHSVDelta); } } -void BubbleEmitter::EmitBubble( Animation& animation, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement ) +void BubbleEmitter::EmitBubble(Animation& animation, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement) { - unsigned int curUniform = mCurrentBubble % mNumBubblePerRenderer; - unsigned int groupIdx = mCurrentBubble / mNumBubblePerRenderer; - SetBubbleParameter( mBubbleRenderers[groupIdx], curUniform, emitPosition - Vector2(mMovementArea.x*0.5f,mMovementArea.y*0.5f), direction, displacement); - animation.AnimateTo( mBubbleRenderers[groupIdx].GetPercentageProperty(curUniform), - 1.f, AlphaFunction::LINEAR ); + unsigned int curUniform = mCurrentBubble % mNumBubblePerRenderer; + unsigned int groupIdx = mCurrentBubble / mNumBubblePerRenderer; + SetBubbleParameter(mBubbleRenderers[groupIdx], curUniform, emitPosition - Vector2(mMovementArea.x * 0.5f, mMovementArea.y * 0.5f), direction, displacement); + animation.AnimateTo(mBubbleRenderers[groupIdx].GetPercentageProperty(curUniform), + 1.f, + AlphaFunction::LINEAR); mCurrentBubble = (mCurrentBubble + 1) % mTotalNumOfBubble; } void BubbleEmitter::Restore() { - for(unsigned int i=0; i < mNumRenderer; i++ ) + for(unsigned int i = 0; i < mNumRenderer; i++) { mBubbleRenderers[i].ResetProperties(); } } -Geometry BubbleEmitter::CreateGeometry( unsigned int numOfPatch ) +Geometry BubbleEmitter::CreateGeometry(unsigned int numOfPatch) { - unsigned int numVertex = numOfPatch*4u; + unsigned int numVertex = numOfPatch * 4u; Vector vertexData; - vertexData.Reserve( numVertex ); + vertexData.Reserve(numVertex); - unsigned int numIndex = numOfPatch*6u; + unsigned int numIndex = numOfPatch * 6u; Vector indexData; - indexData.Reserve( numIndex ); + indexData.Reserve(numIndex); for(unsigned int i = 0; i < numOfPatch; i++) { float halfSize = RandomRange(mBubbleSizeRange.x, mBubbleSizeRange.y, mRandomSeed) * 0.5f; - float index = static_cast( i ); - vertexData.PushBack( Vertex( index, Vector2(-halfSize,-halfSize),Vector2(0.f,0.f) ) ); - vertexData.PushBack( Vertex( index, Vector2(-halfSize, halfSize), Vector2(0.f,1.f) ) ); - vertexData.PushBack( Vertex( index, Vector2( halfSize, halfSize), Vector2(1.f,1.f) ) ); - vertexData.PushBack( Vertex( index, Vector2( halfSize,-halfSize), Vector2(1.f,0.f) ) ); + float index = static_cast(i); + vertexData.PushBack(Vertex(index, Vector2(-halfSize, -halfSize), Vector2(0.f, 0.f))); + vertexData.PushBack(Vertex(index, Vector2(-halfSize, halfSize), Vector2(0.f, 1.f))); + vertexData.PushBack(Vertex(index, Vector2(halfSize, halfSize), Vector2(1.f, 1.f))); + vertexData.PushBack(Vertex(index, Vector2(halfSize, -halfSize), Vector2(1.f, 0.f))); unsigned short idx = index * 4; - indexData.PushBack( idx ); - indexData.PushBack( idx+1 ); - indexData.PushBack( idx+2 ); - indexData.PushBack( idx ); - indexData.PushBack( idx+2 ); - indexData.PushBack( idx+3 ); + indexData.PushBack(idx); + indexData.PushBack(idx + 1); + indexData.PushBack(idx + 2); + indexData.PushBack(idx); + indexData.PushBack(idx + 2); + indexData.PushBack(idx + 3); } Property::Map vertexFormat; - vertexFormat["aIndex"] = Property::FLOAT; + vertexFormat["aIndex"] = Property::FLOAT; vertexFormat["aPosition"] = Property::VECTOR2; vertexFormat["aTexCoord"] = Property::VECTOR2; - VertexBuffer vertices = VertexBuffer::New( vertexFormat ); - vertices.SetData( &vertexData[0], numVertex ); + VertexBuffer vertices = VertexBuffer::New(vertexFormat); + vertices.SetData(&vertexData[0], numVertex); Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( vertices ); - geometry.SetIndexBuffer( &indexData[0], numIndex ); + geometry.AddVertexBuffer(vertices); + geometry.SetIndexBuffer(&indexData[0], numIndex); return geometry; } -void BubbleEmitter::SetBubbleParameter( BubbleRenderer& bubbleRenderer, unsigned int curUniform, - const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement ) +void BubbleEmitter::SetBubbleParameter(BubbleRenderer& bubbleRenderer, unsigned int curUniform, const Vector2& emitPosition, const Vector2& direction, const Vector2& displacement) { Vector2 dir(direction); int halfRange = displacement.x / 2; // for the y coordinate, always negative, so bubbles always go upwards - Vector2 randomVec( rand_r( &mRandomSeed ) % static_cast(displacement.x) - halfRange, -rand_r( &mRandomSeed ) % static_cast(displacement.y) ); + Vector2 randomVec(rand_r(&mRandomSeed) % static_cast(displacement.x) - halfRange, -rand_r(&mRandomSeed) % static_cast(displacement.y)); dir.Normalize(); - randomVec.x -= dir.x*halfRange; - randomVec.y *= 1.0f - fabsf(dir.x)*0.33f; + randomVec.x -= dir.x * halfRange; + randomVec.y *= 1.0f - fabsf(dir.x) * 0.33f; if(randomVec.y > 0.0f) { randomVec.y *= 0.33f; } - Vector4 startAndEndPos( emitPosition.x, emitPosition.y, emitPosition.x+randomVec.x, emitPosition.y+randomVec.y ); - bubbleRenderer.SetStartAndEndPosition( curUniform, startAndEndPos ); + Vector4 startAndEndPos(emitPosition.x, emitPosition.y, emitPosition.x + randomVec.x, emitPosition.y + randomVec.y); + bubbleRenderer.SetStartAndEndPosition(curUniform, startAndEndPos); - bubbleRenderer.SetPercentage( curUniform, 0.f); + bubbleRenderer.SetPercentage(curUniform, 0.f); } } // namespace Internal diff --git a/dali-toolkit/internal/controls/bubble-effect/bubble-renderer.cpp b/dali-toolkit/internal/controls/bubble-effect/bubble-renderer.cpp index 88b1a85..b3ef299 100644 --- a/dali-toolkit/internal/controls/bubble-effect/bubble-renderer.cpp +++ b/dali-toolkit/internal/controls/bubble-effect/bubble-renderer.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,68 +26,65 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - BubbleRenderer::BubbleRenderer() : mRenderer(), mIndicesOffset(), mIndiceStartEndPos(), mIndicesPercentage(), - mIndexGravity( Property::INVALID_INDEX ), - mIndexDynamicScale( Property::INVALID_INDEX ), - mIndexInvertedMovementArea( Property::INVALID_INDEX ) + mIndexGravity(Property::INVALID_INDEX), + mIndexDynamicScale(Property::INVALID_INDEX), + mIndexInvertedMovementArea(Property::INVALID_INDEX) { } -void BubbleRenderer::Initialize( unsigned int numberOfBubble, const Vector2& movementArea, Geometry geometry, TextureSet textureSet, Shader shader ) +void BubbleRenderer::Initialize(unsigned int numberOfBubble, const Vector2& movementArea, Geometry geometry, TextureSet textureSet, Shader shader) { - if( mRenderer ) + if(mRenderer) { // This function is supposed to be called once return; } - mRenderer = Renderer::New( geometry, shader ); - mRenderer.SetTextures( textureSet ); + mRenderer = Renderer::New(geometry, shader); + mRenderer.SetTextures(textureSet); // register uniforms - mIndexGravity = mRenderer.RegisterProperty( "uGravity", 50.f ); - mIndexDynamicScale = mRenderer.RegisterProperty( "uDynamicScale", 1.f ); + mIndexGravity = mRenderer.RegisterProperty("uGravity", 50.f); + mIndexDynamicScale = mRenderer.RegisterProperty("uDynamicScale", 1.f); - mIndexInvertedMovementArea = mRenderer.RegisterProperty( "uInvertedMovementArea", Vector2(1.f,1.f) / movementArea ); + mIndexInvertedMovementArea = mRenderer.RegisterProperty("uInvertedMovementArea", Vector2(1.f, 1.f) / movementArea); mIndicesOffset.resize(9); int offset = movementArea.Length() / 10.f; - unsigned int seed = time( NULL ); + unsigned int seed = time(NULL); - mIndicesOffset[0] = mRenderer.RegisterProperty( "uOffset[0]", Vector2( 0.f,0.f ) ); - mIndicesOffset[1] = mRenderer.RegisterProperty( "uOffset[1]", Vector2( rand_r( &seed ) % offset, rand_r( &seed ) % offset ) ); - mIndicesOffset[2] = mRenderer.RegisterProperty( "uOffset[2]", Vector2( rand_r( &seed ) % offset, -rand_r( &seed ) % offset ) ); - mIndicesOffset[3] = mRenderer.RegisterProperty( "uOffset[3]", Vector2(-rand_r( &seed ) % offset, rand_r( &seed ) % offset ) ); - mIndicesOffset[4] = mRenderer.RegisterProperty( "uOffset[4]", Vector2(-rand_r( &seed ) % offset, -rand_r( &seed ) % offset ) ); - mIndicesOffset[5] = mRenderer.RegisterProperty( "uOffset[5]", Vector2( rand_r( &seed ) % offset, 0.f ) ); - mIndicesOffset[6] = mRenderer.RegisterProperty( "uOffset[6]", Vector2(-rand_r( &seed ) % offset, 0.f ) ); - mIndicesOffset[7] = mRenderer.RegisterProperty( "uOffset[7]", Vector2( 0.f, rand_r( &seed ) % offset ) ); - mIndicesOffset[8] = mRenderer.RegisterProperty( "uOffset[8]", Vector2( 0.f, -rand_r( &seed ) % offset ) ); + mIndicesOffset[0] = mRenderer.RegisterProperty("uOffset[0]", Vector2(0.f, 0.f)); + mIndicesOffset[1] = mRenderer.RegisterProperty("uOffset[1]", Vector2(rand_r(&seed) % offset, rand_r(&seed) % offset)); + mIndicesOffset[2] = mRenderer.RegisterProperty("uOffset[2]", Vector2(rand_r(&seed) % offset, -rand_r(&seed) % offset)); + mIndicesOffset[3] = mRenderer.RegisterProperty("uOffset[3]", Vector2(-rand_r(&seed) % offset, rand_r(&seed) % offset)); + mIndicesOffset[4] = mRenderer.RegisterProperty("uOffset[4]", Vector2(-rand_r(&seed) % offset, -rand_r(&seed) % offset)); + mIndicesOffset[5] = mRenderer.RegisterProperty("uOffset[5]", Vector2(rand_r(&seed) % offset, 0.f)); + mIndicesOffset[6] = mRenderer.RegisterProperty("uOffset[6]", Vector2(-rand_r(&seed) % offset, 0.f)); + mIndicesOffset[7] = mRenderer.RegisterProperty("uOffset[7]", Vector2(0.f, rand_r(&seed) % offset)); + mIndicesOffset[8] = mRenderer.RegisterProperty("uOffset[8]", Vector2(0.f, -rand_r(&seed) % offset)); Vector4 zeroVector; - mIndiceStartEndPos.resize( numberOfBubble ); - mIndicesPercentage.resize( numberOfBubble ); - for( unsigned int i=0; i // for strcmp +#include #include +#include #include #include -#include #include +#include #include -#include -#include +#include // for strcmp // INTERNAL INCLUDES -#include -#include -#include -#include -#include +#include #include #include -#include #include #include +#include +#include +#include +#include +#include #include #include #if defined(DEBUG_ENABLED) - Debug::Filter* gLogButtonFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_BUTTON_CONTROL"); +Debug::Filter* gLogButtonFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_BUTTON_CONTROL"); #endif namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { // empty handle as we cannot create button (but type registered for clicked signal) @@ -66,75 +62,74 @@ BaseHandle Create() } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Button, Toolkit::Control, Create ) - -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabled", BOOLEAN, DISABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "autoRepeating", BOOLEAN, AUTO_REPEATING ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "initialAutoRepeatingDelay", FLOAT, INITIAL_AUTO_REPEATING_DELAY ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "nextAutoRepeatingDelay", FLOAT, NEXT_AUTO_REPEATING_DELAY ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "togglable", BOOLEAN, TOGGLABLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selected", BOOLEAN, SELECTED ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "unselectedVisual", MAP, UNSELECTED_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selectedVisual", MAP, SELECTED_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledSelectedVisual", MAP, DISABLED_SELECTED_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledUnselectedVisual", MAP, DISABLED_UNSELECTED_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "unselectedBackgroundVisual", MAP, UNSELECTED_BACKGROUND_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "label", MAP, LABEL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "selectedBackgroundVisual", MAP, SELECTED_BACKGROUND_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledUnselectedBackgroundVisual", MAP, DISABLED_UNSELECTED_BACKGROUND_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Button, "disabledSelectedBackgroundVisual", MAP, DISABLED_SELECTED_BACKGROUND_VISUAL ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "labelRelativeAlignment", STRING, LABEL_RELATIVE_ALIGNMENT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "labelPadding", VECTOR4, LABEL_PADDING ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, Button, "visualPadding", VECTOR4, VISUAL_PADDING ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Button, Toolkit::Control, Create) + +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabled", BOOLEAN, DISABLED) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "autoRepeating", BOOLEAN, AUTO_REPEATING) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "initialAutoRepeatingDelay", FLOAT, INITIAL_AUTO_REPEATING_DELAY) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "nextAutoRepeatingDelay", FLOAT, NEXT_AUTO_REPEATING_DELAY) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "togglable", BOOLEAN, TOGGLABLE) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "selected", BOOLEAN, SELECTED) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "unselectedVisual", MAP, UNSELECTED_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "selectedVisual", MAP, SELECTED_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledSelectedVisual", MAP, DISABLED_SELECTED_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledUnselectedVisual", MAP, DISABLED_UNSELECTED_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "unselectedBackgroundVisual", MAP, UNSELECTED_BACKGROUND_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "label", MAP, LABEL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "selectedBackgroundVisual", MAP, SELECTED_BACKGROUND_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledUnselectedBackgroundVisual", MAP, DISABLED_UNSELECTED_BACKGROUND_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Button, "disabledSelectedBackgroundVisual", MAP, DISABLED_SELECTED_BACKGROUND_VISUAL) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, Button, "labelRelativeAlignment", STRING, LABEL_RELATIVE_ALIGNMENT) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, Button, "labelPadding", VECTOR4, LABEL_PADDING) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, Button, "visualPadding", VECTOR4, VISUAL_PADDING) // Signals: -DALI_SIGNAL_REGISTRATION( Toolkit, Button, "pressed", SIGNAL_PRESSED ) -DALI_SIGNAL_REGISTRATION( Toolkit, Button, "released", SIGNAL_RELEASED ) -DALI_SIGNAL_REGISTRATION( Toolkit, Button, "clicked", SIGNAL_CLICKED ) -DALI_SIGNAL_REGISTRATION( Toolkit, Button, "stateChanged", SIGNAL_STATE_CHANGED ) +DALI_SIGNAL_REGISTRATION(Toolkit, Button, "pressed", SIGNAL_PRESSED) +DALI_SIGNAL_REGISTRATION(Toolkit, Button, "released", SIGNAL_RELEASED) +DALI_SIGNAL_REGISTRATION(Toolkit, Button, "clicked", SIGNAL_CLICKED) +DALI_SIGNAL_REGISTRATION(Toolkit, Button, "stateChanged", SIGNAL_STATE_CHANGED) // Actions: -DALI_ACTION_REGISTRATION( Toolkit, Button, "buttonClick", ACTION_BUTTON_CLICK ) +DALI_ACTION_REGISTRATION(Toolkit, Button, "buttonClick", ACTION_BUTTON_CLICK) DALI_TYPE_REGISTRATION_END() -DALI_ENUM_TO_STRING_TABLE_BEGIN( ALIGNMENT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, BEGIN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, END ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, TOP ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Internal::Button, BOTTOM ) -DALI_ENUM_TO_STRING_TABLE_END( ALIGNMENT ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(ALIGNMENT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, BEGIN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, END) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, TOP) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Internal::Button, BOTTOM) +DALI_ENUM_TO_STRING_TABLE_END(ALIGNMENT) const Scripting::StringEnum ALIGNMENT_STRING_TABLE[] = -{ - { "BEGIN", Button::BEGIN }, - { "END", Button::END }, - { "TOP", Button::TOP }, - { "BOTTOM", Button::BOTTOM }, + { + {"BEGIN", Button::BEGIN}, + {"END", Button::END}, + {"TOP", Button::TOP}, + {"BOTTOM", Button::BOTTOM}, }; -const unsigned int ALIGNMENT_STRING_TABLE_COUNT = sizeof( ALIGNMENT_STRING_TABLE ) / sizeof( ALIGNMENT_STRING_TABLE[0] ); +const unsigned int ALIGNMENT_STRING_TABLE_COUNT = sizeof(ALIGNMENT_STRING_TABLE) / sizeof(ALIGNMENT_STRING_TABLE[0]); const Property::Index VISUAL_INDEX_FOR_STATE[][Button::STATE_COUNT] = -{ - { Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::UNSELECTED_VISUAL }, - { Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::SELECTED_VISUAL }, - { Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL }, - { Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_SELECTED_VISUAL } -}; + { + {Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::UNSELECTED_VISUAL}, + {Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::SELECTED_VISUAL}, + {Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL}, + {Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL, Toolkit::Button::Property::DISABLED_SELECTED_VISUAL}}; /** * Checks if given map contains a text string */ -bool MapContainsTextString( Property::Map& map ) +bool MapContainsTextString(Property::Map& map) { - bool result = false; - Property::Value* value = map.Find( Toolkit::TextVisual::Property::TEXT ); - if ( value ) + bool result = false; + Property::Value* value = map.Find(Toolkit::TextVisual::Property::TEXT); + if(value) { std::string textString; - value->Get( textString ); - if ( !textString.empty() ) + value->Get(textString); + if(!textString.empty()) { result = true; } @@ -145,19 +140,19 @@ bool MapContainsTextString( Property::Map& map ) } // unnamed namespace Button::Button() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mAutoRepeatingTimer(), - mTextLabelAlignment( END ), - mAutoRepeating( false ), - mTogglableButton( false ), - mTextStringSetFlag( false ), - mInitialAutoRepeatingDelay( 0.0f ), - mNextAutoRepeatingDelay( 0.0f ), - mAnimationTime( 0.0f ), - mButtonPressedState( UNPRESSED ), - mButtonState( UNSELECTED_STATE ), - mPreviousButtonState( mButtonState ), - mClickActionPerforming( false ) + mTextLabelAlignment(END), + mAutoRepeating(false), + mTogglableButton(false), + mTextStringSetFlag(false), + mInitialAutoRepeatingDelay(0.0f), + mNextAutoRepeatingDelay(0.0f), + mAnimationTime(0.0f), + mButtonPressedState(UNPRESSED), + mButtonState(UNSELECTED_STATE), + mPreviousButtonState(mButtonState), + mClickActionPerforming(false) { } @@ -165,156 +160,154 @@ Button::~Button() { } -void Button::SetAutoRepeating( bool autoRepeating ) +void Button::SetAutoRepeating(bool autoRepeating) { mAutoRepeating = autoRepeating; // An autorepeating button can't be a toggle button. - if( autoRepeating ) + if(autoRepeating) { - if( IsSelected() ) + if(IsSelected()) { - SetSelected( false ); // UnSelect before switching off Toggle feature. + SetSelected(false); // UnSelect before switching off Toggle feature. } mTogglableButton = false; } } -void Button::SetInitialAutoRepeatingDelay( float initialAutoRepeatingDelay ) +void Button::SetInitialAutoRepeatingDelay(float initialAutoRepeatingDelay) { - DALI_ASSERT_DEBUG( initialAutoRepeatingDelay > 0.f ); + DALI_ASSERT_DEBUG(initialAutoRepeatingDelay > 0.f); mInitialAutoRepeatingDelay = initialAutoRepeatingDelay; } -void Button::SetNextAutoRepeatingDelay( float nextAutoRepeatingDelay ) +void Button::SetNextAutoRepeatingDelay(float nextAutoRepeatingDelay) { - DALI_ASSERT_DEBUG( nextAutoRepeatingDelay > 0.f ); + DALI_ASSERT_DEBUG(nextAutoRepeatingDelay > 0.f); mNextAutoRepeatingDelay = nextAutoRepeatingDelay; } -void Button::SetTogglableButton( bool togglable ) +void Button::SetTogglableButton(bool togglable) { mTogglableButton = togglable; // A toggle button can't be an autorepeating button. - if( togglable ) + if(togglable) { mAutoRepeating = false; } } -void Button::SetSelected( bool selected ) +void Button::SetSelected(bool selected) { - if( mTogglableButton ) + if(mTogglableButton) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetSelected (%s)\n", (selected?"true":"false") ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetSelected (%s)\n", (selected ? "true" : "false")); - if ( selected && ( mButtonState != SELECTED_STATE ) ) + if(selected && (mButtonState != SELECTED_STATE)) { - ChangeState( SELECTED_STATE ); + ChangeState(SELECTED_STATE); } - else if ( !selected && ( mButtonState != UNSELECTED_STATE ) ) + else if(!selected && (mButtonState != UNSELECTED_STATE)) { - ChangeState( UNSELECTED_STATE ); + ChangeState(UNSELECTED_STATE); } } } -void Button::SetDisabled( bool disabled ) +void Button::SetDisabled(bool disabled) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetDisabled(%s) state(%d)\n", (disabled)?"disabled":"active", mButtonState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetDisabled(%s) state(%d)\n", (disabled) ? "disabled" : "active", mButtonState); - if ( disabled ) + if(disabled) { - if ( mButtonState == SELECTED_STATE ) + if(mButtonState == SELECTED_STATE) { - ChangeState( DISABLED_SELECTED_STATE ); + ChangeState(DISABLED_SELECTED_STATE); } - else if ( mButtonState == UNSELECTED_STATE ) + else if(mButtonState == UNSELECTED_STATE) { - ChangeState( DISABLED_UNSELECTED_STATE ); + ChangeState(DISABLED_UNSELECTED_STATE); } } else { - if ( mButtonState == DISABLED_SELECTED_STATE ) + if(mButtonState == DISABLED_SELECTED_STATE) { - ChangeState( SELECTED_STATE ); + ChangeState(SELECTED_STATE); } - else if ( mButtonState == DISABLED_UNSELECTED_STATE ) + else if(mButtonState == DISABLED_UNSELECTED_STATE) { - ChangeState( UNSELECTED_STATE ); + ChangeState(UNSELECTED_STATE); } } } bool Button::IsDisabled() const { - return ( mButtonState == DISABLED_SELECTED_STATE || mButtonState == DISABLED_UNSELECTED_STATE ) ; + return (mButtonState == DISABLED_SELECTED_STATE || mButtonState == DISABLED_UNSELECTED_STATE); } -bool Button::ValidateState( State requestedState ) +bool Button::ValidateState(State requestedState) { /* Below tables shows allowed state transitions * Match rows in first column to following columns, if true then transition allowed. * eg UNSELECTED_STATE to DISABLED_UNSELECTED_STATE is true so state transition allowed. * to| UNSELECTED_STATE | SELECTED_STATE | DISABLED_UNSELECTED_STATE | DISABLED_SELECTED_STATE |*/ - /* from*/ - bool transitionTable[4][4] = { /* UNSELECTED_STATE*/ { false, true, true, false }, - /* SELECTED_STATE*/ { true, false, false, true }, - /* DISABLED_UNSELECTED_STATE*/{ true, true, false, false }, - /* DISABLED_SELECTED_STATE*/ { false, true, false, false } - }; + /* from*/ + bool transitionTable[4][4] = {/* UNSELECTED_STATE*/ {false, true, true, false}, + /* SELECTED_STATE*/ {true, false, false, true}, + /* DISABLED_UNSELECTED_STATE*/ {true, true, false, false}, + /* DISABLED_SELECTED_STATE*/ {false, true, false, false}}; - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ValidateState ReuestedState:%d, CurrentState:%d, result:%s\n", - requestedState, mButtonState, (transitionTable[mButtonState][requestedState])?"change-accepted":"change-denied"); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::ValidateState ReuestedState:%d, CurrentState:%d, result:%s\n", requestedState, mButtonState, (transitionTable[mButtonState][requestedState]) ? "change-accepted" : "change-denied"); return transitionTable[mButtonState][requestedState]; } -void Button::ChangeState( State requestedState ) +void Button::ChangeState(State requestedState) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d)\n", requestedState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d)\n", requestedState); // Validate State before changing - if ( !ValidateState( requestedState )) + if(!ValidateState(requestedState)) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d) not validated\n", requestedState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::ChangeState ReuestedState(%d) not validated\n", requestedState); return; } // If not on stage the button could have still been set to selected so update state - mPreviousButtonState = mButtonState; // Store previous state for visual removal (used when animations ended) - mButtonState = requestedState; // Update current state + mPreviousButtonState = mButtonState; // Store previous state for visual removal (used when animations ended) + mButtonState = requestedState; // Update current state - if ( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(Self().GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { - OnStateChange( mButtonState ); // Notify derived buttons - SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] ); - SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] ); + OnStateChange(mButtonState); // Notify derived buttons + SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]); + SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]); // If animation supported then visual removal should be performed after any transition animation has completed. // If Required Visual is not loaded before current visual is removed then a flickering will be evident. // Derived button can override OnButtonVisualRemoval - OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ BACKGROUND ] ); - OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ FOREGROUND ] ); + OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][BACKGROUND]); + OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][FOREGROUND]); RelayoutRequest(); } - Toolkit::Button handle( GetOwner() ); + Toolkit::Button handle(GetOwner()); // Emit signal. - mStateChangedSignal.Emit( handle ); + mStateChangedSignal.Emit(handle); } bool Button::IsSelected() const { - bool selected = ( mButtonState == SELECTED_STATE ) || ( mButtonState == DISABLED_SELECTED_STATE ); + bool selected = (mButtonState == SELECTED_STATE) || (mButtonState == DISABLED_SELECTED_STATE); return mTogglableButton && selected; } -void Button::MergeWithExistingLabelProperties( const Property::Map& inMap, Property::Map& outMap ) +void Button::MergeWithExistingLabelProperties(const Property::Map& inMap, Property::Map& outMap) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties with %d properties\n", inMap.Count() ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties with %d properties\n", inMap.Count()); /** * Properties for the Label visual could be from a style sheet but after being set the "TEXT" property could be set. @@ -325,24 +318,24 @@ void Button::MergeWithExistingLabelProperties( const Property::Map& inMap, Prope * 3) Merge with new properties ( settings ) * 4) Return new merged map */ - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); - if ( visual ) + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, Toolkit::Button::Property::LABEL); + if(visual) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties Visual already exists, retrieving existing map\n"); - visual.CreatePropertyMap( outMap ); - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties retrieved %d properties\n", outMap.Count() ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties Visual already exists, retrieving existing map\n"); + visual.CreatePropertyMap(outMap); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties retrieved %d properties\n", outMap.Count()); } - outMap.Merge( inMap ); + outMap.Merge(inMap); // Store if a text string has been supplied. - mTextStringSetFlag = MapContainsTextString( outMap ); + mTextStringSetFlag = MapContainsTextString(outMap); - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "MergeLabelProperties now has %d properties\n", outMap.Count() ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "MergeLabelProperties now has %d properties\n", outMap.Count()); } -void Button::SetLabelAlignment( Button::Align labelAlignment) +void Button::SetLabelAlignment(Button::Align labelAlignment) { mTextLabelAlignment = labelAlignment; RelayoutRequest(); @@ -360,92 +353,91 @@ Button::Align Button::GetLabelAlignment() * 3) Register visual with control with false for enable flag. Button will later enable visual when needed ( Button::SelectRequiredVisual ) * 4) Unregister visual if empty map was provided. This is the method to remove a visual */ -void Button::CreateVisualsForComponent( Property::Index index, const Property::Value& value, const int visualDepth ) +void Button::CreateVisualsForComponent(Property::Index index, const Property::Value& value, const int visualDepth) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent index(%d)\n", index ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent index(%d)\n", index); Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get(); - Toolkit::Visual::Base buttonVisual; + Toolkit::Visual::Base buttonVisual; std::string imageUrl; - if( value.Get( imageUrl ) ) + if(value.Get(imageUrl)) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using image URL(%d)\n", index ); - if ( !imageUrl.empty() ) + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using image URL(%d)\n", index); + if(!imageUrl.empty()) { - DALI_ASSERT_DEBUG( index != Toolkit::Button::Property::LABEL && "Creating a Image Visual instead of Text Visual " ); - buttonVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() ); + DALI_ASSERT_DEBUG(index != Toolkit::Button::Property::LABEL && "Creating a Image Visual instead of Text Visual "); + buttonVisual = visualFactory.CreateVisual(imageUrl, ImageDimensions()); } } else { // if its not a string then get a Property::Map from the property if possible. - const Property::Map *map = value.GetMap(); - if( map && !map->Empty() ) // Empty map results in current visual removal. + const Property::Map* map = value.GetMap(); + if(map && !map->Empty()) // Empty map results in current visual removal. { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using Map(%d)\n", index ); - buttonVisual = visualFactory.CreateVisual( *map ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent Using Map(%d)\n", index); + buttonVisual = visualFactory.CreateVisual(*map); } } - if ( buttonVisual ) + if(buttonVisual) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent RegisterVisual index(%d) enabled(%s)\n", - index, DevelControl::IsVisualEnabled( *this, index )?"true":"false" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "CreateVisualsForComponent RegisterVisual index(%d) enabled(%s)\n", index, DevelControl::IsVisualEnabled(*this, index) ? "true" : "false"); // enable the visual if needed for current state - const bool enabled = ( ( index == VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] )|| - ( index == VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] )|| - ( index == Toolkit::Button::Property::LABEL ) ); - DevelControl::RegisterVisual( *this, index, buttonVisual, enabled, visualDepth ); + const bool enabled = ((index == VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]) || + (index == VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]) || + (index == Toolkit::Button::Property::LABEL)); + DevelControl::RegisterVisual(*this, index, buttonVisual, enabled, visualDepth); } else { - DevelControl::UnregisterVisual( *this, index ); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "CreateVisualsForComponent Visual not created or empty map (clearing visual).(%d)\n", index); + DevelControl::UnregisterVisual(*this, index); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "CreateVisualsForComponent Visual not created or empty map (clearing visual).(%d)\n", index); } RelayoutRequest(); } -bool Button::GetPropertyMapForVisual( Property::Index visualIndex, Property::Map& retreivedMap ) const +bool Button::GetPropertyMapForVisual(Property::Index visualIndex, Property::Map& retreivedMap) const { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetPropertyMapForVisual visual(%d)\n", visualIndex); - bool success = false; - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex ); - if ( visual ) + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetPropertyMapForVisual visual(%d)\n", visualIndex); + bool success = false; + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, visualIndex); + if(visual) { - visual.CreatePropertyMap( retreivedMap ); + visual.CreatePropertyMap(retreivedMap); success = true; } - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetPropertyMapForVisual %s\n", success?"Success":"Failure"); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetPropertyMapForVisual %s\n", success ? "Success" : "Failure"); return success; } -bool Button::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes ) +bool Button::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes) { bool ret = false; - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - Toolkit::Button button = Toolkit::Button::DownCast( handle ); + Toolkit::Button button = Toolkit::Button::DownCast(handle); - DALI_ASSERT_DEBUG( button ); + DALI_ASSERT_DEBUG(button); - if( 0 == strcmp( actionName.c_str(), ACTION_BUTTON_CLICK ) ) + if(0 == strcmp(actionName.c_str(), ACTION_BUTTON_CLICK)) { - ret = GetImplementation( button ).DoClickAction( attributes ); + ret = GetImplementation(button).DoClickAction(attributes); } return ret; } -bool Button::DoClickAction( const Property::Map& attributes ) +bool Button::DoClickAction(const Property::Map& attributes) { // Prevents the button signals from doing a recursive loop by sending an action // and re-emitting the signals. - if( !mClickActionPerforming ) + if(!mClickActionPerforming) { mClickActionPerforming = true; ButtonDown(); - if ( !mTogglableButton ) + if(!mTogglableButton) { mButtonPressedState = DEPRESSED; } @@ -460,11 +452,11 @@ bool Button::DoClickAction( const Property::Map& attributes ) void Button::ButtonDown() { - if( mTogglableButton ) + if(mTogglableButton) { - if ( mButtonState != SELECTED_STATE ) + if(mButtonState != SELECTED_STATE) { - SetSelected( true ); + SetSelected(true); mButtonPressedState = TOGGLE_DEPRESSED; } else @@ -476,68 +468,67 @@ void Button::ButtonDown() { Pressed(); mButtonPressedState = DEPRESSED; - if( mAutoRepeating ) + if(mAutoRepeating) { - SetUpTimer( mInitialAutoRepeatingDelay ); + SetUpTimer(mInitialAutoRepeatingDelay); } } // The pressed signal should be emitted regardless of toggle mode. - Toolkit::Button handle( GetOwner() ); - mPressedSignal.Emit( handle ); + Toolkit::Button handle(GetOwner()); + mPressedSignal.Emit(handle); } void Button::ButtonUp() { bool emitSignalsForPressAndReleaseAction = false; - if( DEPRESSED == mButtonPressedState ) + if(DEPRESSED == mButtonPressedState) { - if( mTogglableButton ) // Button up will change state + if(mTogglableButton) // Button up will change state { emitSignalsForPressAndReleaseAction = OnToggleReleased(); // Derived toggle buttons can override this to provide custom behaviour } else { Released(); // Button up will result in unselected state - if( mAutoRepeating ) + if(mAutoRepeating) { mAutoRepeatingTimer.Reset(); } emitSignalsForPressAndReleaseAction = true; } } - else if ( TOGGLE_DEPRESSED == mButtonPressedState ) + else if(TOGGLE_DEPRESSED == mButtonPressedState) { emitSignalsForPressAndReleaseAction = true; // toggle released after being pressed, a click } - if ( emitSignalsForPressAndReleaseAction ) + if(emitSignalsForPressAndReleaseAction) { // The clicked and released signals should be emitted regardless of toggle mode. - Toolkit::Button handle( GetOwner() ); - mReleasedSignal.Emit( handle ); - mClickedSignal.Emit( handle ); + Toolkit::Button handle(GetOwner()); + mReleasedSignal.Emit(handle); + mClickedSignal.Emit(handle); } } bool Button::OnToggleReleased() { - SetSelected( !IsSelected() ); + SetSelected(!IsSelected()); mButtonPressedState = UNPRESSED; return true; } - void Button::OnTouchPointLeave() { - if( DEPRESSED == mButtonPressedState ) + if(DEPRESSED == mButtonPressedState) { - if( !mTogglableButton ) + if(!mTogglableButton) { Released(); - if( mAutoRepeating ) + if(mAutoRepeating) { mAutoRepeatingTimer.Reset(); } @@ -546,8 +537,8 @@ void Button::OnTouchPointLeave() mButtonPressedState = UNPRESSED; // The released signal should be emitted regardless of toggle mode. - Toolkit::Button handle( GetOwner() ); - mReleasedSignal.Emit( handle ); + Toolkit::Button handle(GetOwner()); + mReleasedSignal.Emit(handle); } } @@ -576,28 +567,28 @@ Toolkit::Button::ButtonSignalType& Button::StateChangedSignal() return mStateChangedSignal; } -bool Button::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool Button::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::Button button = Toolkit::Button::DownCast( handle ); + bool connected(true); + Toolkit::Button button = Toolkit::Button::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_PRESSED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_PRESSED)) { - button.PressedSignal().Connect( tracker, functor ); + button.PressedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_RELEASED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_RELEASED)) { - button.ReleasedSignal().Connect( tracker, functor ); + button.ReleasedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_CLICKED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_CLICKED)) { - button.ClickedSignal().Connect( tracker, functor ); + button.ClickedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_STATE_CHANGED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_STATE_CHANGED)) { - button.StateChangedSignal().Connect( tracker, functor ); + button.StateChangedSignal().Connect(tracker, functor); } else { @@ -610,18 +601,18 @@ bool Button::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tr void Button::OnInitialize() { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnInitialize\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::OnInitialize\n"); Actor self = Self(); mTapDetector = TapGestureDetector::New(); - mTapDetector.Attach( self ); + mTapDetector.Attach(self); mTapDetector.DetectedSignal().Connect(this, &Button::OnTap); - self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true ); - self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true); + self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); - self.TouchedSignal().Connect( this, &Button::OnTouch ); + self.TouchedSignal().Connect(this, &Button::OnTouch); } bool Button::OnAccessibilityActivated() @@ -629,13 +620,13 @@ bool Button::OnAccessibilityActivated() return OnKeyboardEnter(); } -bool Button::OnTouch( Actor actor, const TouchEvent& touch ) +bool Button::OnTouch(Actor actor, const TouchEvent& touch) { - if( !IsDisabled() && (actor == touch.GetHitActor(0)) ) + if(!IsDisabled() && (actor == touch.GetHitActor(0))) { - if ( 1 == touch.GetPointCount() ) + if(1 == touch.GetPointCount()) { - switch( touch.GetState( 0 ) ) + switch(touch.GetState(0)) { case PointState::DOWN: { @@ -665,7 +656,7 @@ bool Button::OnTouch( Actor actor, const TouchEvent& touch ) } } } - else if( 1 < touch.GetPointCount() ) + else if(1 < touch.GetPointCount()) { OnTouchPointLeave(); // Notification for derived classes. @@ -680,20 +671,20 @@ bool Button::OnKeyboardEnter() { // When the enter key is pressed, or button is activated, the click action is performed. Property::Map attributes; - bool ret = DoClickAction( attributes ); + bool ret = DoClickAction(attributes); return ret; } void Button::OnSceneDisconnection() { - if( DEPRESSED == mButtonPressedState ) + if(DEPRESSED == mButtonPressedState) { - if( !mTogglableButton ) + if(!mTogglableButton) { Released(); - if( mAutoRepeating ) + if(mAutoRepeating) { mAutoRepeatingTimer.Reset(); } @@ -705,15 +696,15 @@ void Button::OnSceneDisconnection() Control::OnSceneDisconnection(); // Visuals will be set off stage } -void Button::OnSceneConnection( int depth ) +void Button::OnSceneConnection(int depth) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnSceneConnection ptr(%p) \n", this ); - OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ BACKGROUND ] ); - OnButtonVisualRemoval( VISUAL_INDEX_FOR_STATE[ mPreviousButtonState ][ FOREGROUND ] ); - SelectRequiredVisual( Toolkit::Button::Property::LABEL ); - SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ BACKGROUND ] ); - SelectRequiredVisual( VISUAL_INDEX_FOR_STATE[ mButtonState ][ FOREGROUND ] ); - Control::OnSceneConnection( depth ); // Enabled visuals will be put on stage + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::OnSceneConnection ptr(%p) \n", this); + OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][BACKGROUND]); + OnButtonVisualRemoval(VISUAL_INDEX_FOR_STATE[mPreviousButtonState][FOREGROUND]); + SelectRequiredVisual(Toolkit::Button::Property::LABEL); + SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]); + SelectRequiredVisual(VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]); + Control::OnSceneConnection(depth); // Enabled visuals will be put on stage RelayoutRequest(); } @@ -729,92 +720,90 @@ Vector3 Button::GetNaturalSize() bool foreGroundVisualUsed = false; - for ( int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++ ) + for(int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[state][FOREGROUND] ); - Size visualSize; - if ( visual ) + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[state][FOREGROUND]); + Size visualSize; + if(visual) { - visual.GetNaturalSize( visualSize ); - largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width ); - largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height ); - foreGroundVisualUsed = true; + visual.GetNaturalSize(visualSize); + largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width); + largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height); + foreGroundVisualUsed = true; } } - if ( !foreGroundVisualUsed ) // If foreground visual not supplied then use the background visual to calculate Natural size + if(!foreGroundVisualUsed) // If foreground visual not supplied then use the background visual to calculate Natural size { - for ( int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++ ) + for(int state = Button::UNSELECTED_STATE; state < Button::STATE_COUNT; state++) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[state][BACKGROUND] ); - Size visualSize; - if ( visual ) + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[state][BACKGROUND]); + Size visualSize; + if(visual) { - visual.GetNaturalSize( visualSize ); - largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width ); - largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height ); + visual.GetNaturalSize(visualSize); + largestProvidedVisual.width = std::max(largestProvidedVisual.width, visualSize.width); + largestProvidedVisual.height = std::max(largestProvidedVisual.height, visualSize.height); } } } // Get horizontal padding total - if ( largestProvidedVisual.width > 0 ) // if visual exists + if(largestProvidedVisual.width > 0) // if visual exists { size.width += largestProvidedVisual.width + mForegroundPadding.left + mForegroundPadding.right; } // Get vertical padding total - if ( largestProvidedVisual.height > 0 ) + if(largestProvidedVisual.height > 0) { size.height += largestProvidedVisual.height + mForegroundPadding.top + mForegroundPadding.bottom; } - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize visual Size(%f,%f)\n", - largestProvidedVisual.width, largestProvidedVisual.height ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetNaturalSize visual Size(%f,%f)\n", largestProvidedVisual.width, largestProvidedVisual.height); // Get natural size of label if text has been set - if ( mTextStringSetFlag ) + if(mTextStringSetFlag) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, Toolkit::Button::Property::LABEL); - if ( visual ) + if(visual) { - visual.GetNaturalSize( labelSize ); + visual.GetNaturalSize(labelSize); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize labelSize(%f,%f) padding(%f,%f)\n", - labelSize.width, labelSize.height, mLabelPadding.left + mLabelPadding.right, mLabelPadding.top + mLabelPadding.bottom); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetNaturalSize labelSize(%f,%f) padding(%f,%f)\n", labelSize.width, labelSize.height, mLabelPadding.left + mLabelPadding.right, mLabelPadding.top + mLabelPadding.bottom); labelSize.width += mLabelPadding.left + mLabelPadding.right; labelSize.height += mLabelPadding.top + mLabelPadding.bottom; // Add label size to height or width depending on alignment position - if ( horizontalAlignment ) + if(horizontalAlignment) { size.width += labelSize.width; - size.height = std::max(size.height, labelSize.height ); + size.height = std::max(size.height, labelSize.height); } else { size.height += labelSize.height; - size.width = std::max(size.width, labelSize.width ); + size.width = std::max(size.width, labelSize.width); } } } - if( size.width < 1 && size.height < 1 ) + if(size.width < 1 && size.height < 1) { // if no image or label then use Control's natural size - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "GetNaturalSize Using control natural size\n"); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "GetNaturalSize Using control natural size\n"); size = Control::GetNaturalSize(); } - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "Button GetNaturalSize (%f,%f)\n", size.width, size.height ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "Button GetNaturalSize (%f,%f)\n", size.width, size.height); return size; } -void Button::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension ) +void Button::OnSetResizePolicy(ResizePolicy::Type policy, Dimension::Type dimension) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnSetResizePolicy\n"); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnSetResizePolicy\n"); RelayoutRequest(); } @@ -823,165 +812,164 @@ void Button::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimen * Whilst the control has it's size negotiated it has to size it's visuals explicitly here. */ -void Button::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void Button::OnRelayout(const Vector2& size, RelayoutContainer& container) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout targetSize(%f,%f) ptr(%p) state[%d]\n", size.width, size.height, this, mButtonState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout targetSize(%f,%f) ptr(%p) state[%d]\n", size.width, size.height, this, mButtonState); - Toolkit::Visual::Base currentVisual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND] ); - Toolkit::Visual::Base currentBackGroundVisual = DevelControl::GetVisual( *this, VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND] ); + Toolkit::Visual::Base currentVisual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[mButtonState][FOREGROUND]); + Toolkit::Visual::Base currentBackGroundVisual = DevelControl::GetVisual(*this, VISUAL_INDEX_FOR_STATE[mButtonState][BACKGROUND]); // Sizes and padding set to zero, if not present then values will no effect calculations. - Vector2 visualPosition = Vector2::ZERO; - Vector2 labelPosition = Vector2::ZERO; - Size visualSize = Size::ZERO; - Padding foregroundVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f ); - Padding labelVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f ); + Vector2 visualPosition = Vector2::ZERO; + Vector2 labelPosition = Vector2::ZERO; + Size visualSize = Size::ZERO; + Padding foregroundVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f); + Padding labelVisualPadding = Padding(0.0f, 0.0f, 0.0f, 0.0f); - if ( mTextStringSetFlag ) + if(mTextStringSetFlag) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Label padding setting padding:%f,%f,%f,%f\n", mLabelPadding.y, mLabelPadding.x, mLabelPadding.width,mLabelPadding.height ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Label padding setting padding:%f,%f,%f,%f\n", mLabelPadding.y, mLabelPadding.x, mLabelPadding.width, mLabelPadding.height); labelVisualPadding = mLabelPadding; } - if ( currentVisual ) + if(currentVisual) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Foreground Visual setting padding:%f,%f,%f,%f\n", mForegroundPadding.y, mForegroundPadding.x, mForegroundPadding.width,mForegroundPadding.height ); - currentVisual.GetNaturalSize( visualSize ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Foreground Visual setting padding:%f,%f,%f,%f\n", mForegroundPadding.y, mForegroundPadding.x, mForegroundPadding.width, mForegroundPadding.height); + currentVisual.GetNaturalSize(visualSize); foregroundVisualPadding = mForegroundPadding; } Toolkit::Align::Type visualAnchorPoint = Toolkit::Align::TOP_BEGIN; - Vector2 visualAndPaddingSize = Vector2( ( foregroundVisualPadding.x + visualSize.width + foregroundVisualPadding.y ), - ( foregroundVisualPadding.width + visualSize.height + foregroundVisualPadding.height )); + Vector2 visualAndPaddingSize = Vector2((foregroundVisualPadding.x + visualSize.width + foregroundVisualPadding.y), + (foregroundVisualPadding.width + visualSize.height + foregroundVisualPadding.height)); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout visualAndPaddingSize(%f,%f)\n", visualAndPaddingSize.width, visualAndPaddingSize.height); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout visualAndPaddingSize(%f,%f)\n", visualAndPaddingSize.width, visualAndPaddingSize.height); // Text Visual should take all space available after foreground visual size and all padding is considered. // Remaining Space priority, Foreground padding, foreground visual, Text padding then Text visual. Size remainingSpaceForText = Size::ZERO; - switch ( mTextLabelAlignment ) + switch(mTextLabelAlignment) { - case BEGIN : + case BEGIN: { visualAnchorPoint = Toolkit::Align::TOP_END; - visualPosition.x = foregroundVisualPadding.right; - visualPosition.y = foregroundVisualPadding.top; + visualPosition.x = foregroundVisualPadding.right; + visualPosition.y = foregroundVisualPadding.top; labelPosition.x = labelVisualPadding.x; labelPosition.y = labelVisualPadding.top; - remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y; + remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } - case END : + case END: { visualAnchorPoint = Toolkit::Align::TOP_BEGIN; - visualPosition.x = foregroundVisualPadding.left; - visualPosition.y = foregroundVisualPadding.top; + visualPosition.x = foregroundVisualPadding.left; + visualPosition.y = foregroundVisualPadding.top; labelPosition.x = visualAndPaddingSize.width + labelVisualPadding.x; labelPosition.y = labelVisualPadding.top; - remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y; + remainingSpaceForText.width = size.width - visualAndPaddingSize.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } - case TOP : + case TOP: { visualAnchorPoint = Toolkit::Align::BOTTOM_END; - visualPosition.x = foregroundVisualPadding.left; - visualPosition.y = foregroundVisualPadding.bottom; + visualPosition.x = foregroundVisualPadding.left; + visualPosition.y = foregroundVisualPadding.bottom; labelPosition.x = labelVisualPadding.left; labelPosition.y = labelVisualPadding.top; - remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y; + remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - visualAndPaddingSize.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } - case BOTTOM : + case BOTTOM: { visualAnchorPoint = Toolkit::Align::TOP_END; - visualPosition.x = foregroundVisualPadding.left; - visualPosition.y = foregroundVisualPadding.top; + visualPosition.x = foregroundVisualPadding.left; + visualPosition.y = foregroundVisualPadding.top; labelPosition.x = labelVisualPadding.left; labelPosition.y = visualAndPaddingSize.height + labelVisualPadding.top; - remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y; + remainingSpaceForText.width = size.width - labelVisualPadding.x - labelVisualPadding.y; remainingSpaceForText.height = size.height - visualAndPaddingSize.height - labelVisualPadding.top - labelVisualPadding.bottom; break; } } - if ( currentBackGroundVisual ) + if(currentBackGroundVisual) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Setting visual background size to(%f,%f)\n", size.width, size.height); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Setting visual background size to(%f,%f)\n", size.width, size.height); Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, size ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, size) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)); - currentBackGroundVisual.SetTransformAndSize( visualTransform, size ); + currentBackGroundVisual.SetTransformAndSize(visualTransform, size); } - if ( currentVisual ) + if(currentVisual) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height); Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, visualSize ) - .Add( Toolkit::Visual::Transform::Property::OFFSET, visualPosition ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, visualSize) + .Add(Toolkit::Visual::Transform::Property::OFFSET, visualPosition) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint); - currentVisual.SetTransformAndSize( visualTransform, size ); + currentVisual.SetTransformAndSize(visualTransform, size); } - if ( mTextStringSetFlag ) + if(mTextStringSetFlag) { - Toolkit::Visual::Base textVisual = DevelControl::GetVisual( *this, Toolkit::Button::Property::LABEL ); // No need to search for Label visual if no text set. + Toolkit::Visual::Base textVisual = DevelControl::GetVisual(*this, Toolkit::Button::Property::LABEL); // No need to search for Label visual if no text set. - if ( textVisual ) + if(textVisual) { - if ( !currentVisual ) + if(!currentVisual) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout Only Text\n"); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout Only Text\n"); labelPosition.x = labelVisualPadding.left; labelPosition.y = labelVisualPadding.height; } - Vector2 preSize = Vector2( static_cast< int >( remainingSpaceForText.x ), static_cast< int >( remainingSpaceForText.y )); - - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout text Size(%f,%f) text Position(%f,%f) \n", remainingSpaceForText.width, remainingSpaceForText.height, labelPosition.x, labelPosition.y); + Vector2 preSize = Vector2(static_cast(remainingSpaceForText.x), static_cast(remainingSpaceForText.y)); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout text Size -- (%f,%f) text Position(%f,%f) \n", preSize.width, preSize.height, labelPosition.x, labelPosition.y); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout text Size(%f,%f) text Position(%f,%f) \n", remainingSpaceForText.width, remainingSpaceForText.height, labelPosition.x, labelPosition.y); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout text Size -- (%f,%f) text Position(%f,%f) \n", preSize.width, preSize.height, labelPosition.x, labelPosition.y); Property::Map textVisualTransform; - textVisualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, preSize ) - .Add( Toolkit::Visual::Transform::Property::OFFSET, labelPosition ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint ); - - textVisual.SetTransformAndSize( textVisualTransform, size ); + textVisualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, preSize) + .Add(Toolkit::Visual::Transform::Property::OFFSET, labelPosition) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, visualAnchorPoint); + + textVisual.SetTransformAndSize(textVisualTransform, size); } } - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout selected (%s) \n", IsSelected()?"yes":"no" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout selected (%s) \n", IsSelected() ? "yes" : "no"); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "OnRelayout << \n"); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "OnRelayout << \n"); } void Button::OnTap(Actor actor, const TapGesture& tap) @@ -989,130 +977,130 @@ void Button::OnTap(Actor actor, const TapGesture& tap) // Prevents Parent getting a tap event } -void Button::SetUpTimer( float delay ) +void Button::SetUpTimer(float delay) { - mAutoRepeatingTimer = Dali::Timer::New( static_cast( 1000.f * delay ) ); - mAutoRepeatingTimer.TickSignal().Connect( this, &Button::AutoRepeatingSlot ); + mAutoRepeatingTimer = Dali::Timer::New(static_cast(1000.f * delay)); + mAutoRepeatingTimer.TickSignal().Connect(this, &Button::AutoRepeatingSlot); mAutoRepeatingTimer.Start(); } bool Button::AutoRepeatingSlot() { bool consumed = false; - if( !IsDisabled() ) + if(!IsDisabled()) { // Restart the autorepeat timer. - SetUpTimer( mNextAutoRepeatingDelay ); + SetUpTimer(mNextAutoRepeatingDelay); Pressed(); - Toolkit::Button handle( GetOwner() ); + Toolkit::Button handle(GetOwner()); //Emit signal. - consumed = mReleasedSignal.Emit( handle ); - consumed = mClickedSignal.Emit( handle ); - consumed |= mPressedSignal.Emit( handle ); - } + consumed = mReleasedSignal.Emit(handle); + consumed = mClickedSignal.Emit(handle); + consumed |= mPressedSignal.Emit(handle); + } return consumed; } void Button::Pressed() { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::Pressed\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::Pressed\n"); - if( mButtonState == UNSELECTED_STATE ) + if(mButtonState == UNSELECTED_STATE) { - ChangeState( SELECTED_STATE ); - OnPressed(); // Notifies the derived class the button has been pressed. + ChangeState(SELECTED_STATE); + OnPressed(); // Notifies the derived class the button has been pressed. } } void Button::Released() { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::Released\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::Released\n"); - if( mButtonState == SELECTED_STATE && !mTogglableButton ) + if(mButtonState == SELECTED_STATE && !mTogglableButton) { - ChangeState( UNSELECTED_STATE ); + ChangeState(UNSELECTED_STATE); OnReleased(); // // Notifies the derived class the button has been released. } mButtonPressedState = UNPRESSED; } -void Button::SelectRequiredVisual( Property::Index visualIndex ) +void Button::SelectRequiredVisual(Property::Index visualIndex) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SelectRequiredVisual index(%d) state(%d)\n", visualIndex, mButtonState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SelectRequiredVisual index(%d) state(%d)\n", visualIndex, mButtonState); // only enable visuals that exist - if( DevelControl::GetVisual( *this, visualIndex ) ) + if(DevelControl::GetVisual(*this, visualIndex)) { - DevelControl::EnableVisual( *this, visualIndex, true ); + DevelControl::EnableVisual(*this, visualIndex, true); } } -void Button::RemoveVisual( Property::Index visualIndex ) +void Button::RemoveVisual(Property::Index visualIndex) { // Use OnButtonVisualRemoval if want button developer to have the option to override removal. - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::RemoveVisual index(%d) state(%d)\n", visualIndex, mButtonState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::RemoveVisual index(%d) state(%d)\n", visualIndex, mButtonState); - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex ); + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, visualIndex); - if( visual ) + if(visual) { - DevelControl::EnableVisual( *this, visualIndex, false ); + DevelControl::EnableVisual(*this, visualIndex, false); } } -void Button::OnButtonVisualRemoval( Property::Index visualIndex ) +void Button::OnButtonVisualRemoval(Property::Index visualIndex) { // Derived Buttons can over ride this to prevent default removal. - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::OnButtonVisualRemoval index(%d)\n", visualIndex ); - RemoveVisual( visualIndex ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::OnButtonVisualRemoval index(%d)\n", visualIndex); + RemoveVisual(visualIndex); } -void Button::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void Button::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::Button button = Toolkit::Button::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Button button = Toolkit::Button::DownCast(Dali::BaseHandle(object)); - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetProperty index[%d]\n", index ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetProperty index[%d]\n", index); - if ( button ) + if(button) { - switch ( index ) + switch(index) { case Toolkit::Button::Property::DISABLED: { - GetImplementation( button ).SetDisabled( value.Get< bool >() ); + GetImplementation(button).SetDisabled(value.Get()); break; } case Toolkit::Button::Property::AUTO_REPEATING: { - GetImplementation( button ).SetAutoRepeating( value.Get< bool >() ); + GetImplementation(button).SetAutoRepeating(value.Get()); break; } case Toolkit::Button::Property::INITIAL_AUTO_REPEATING_DELAY: { - GetImplementation( button ).SetInitialAutoRepeatingDelay( value.Get< float >() ); + GetImplementation(button).SetInitialAutoRepeatingDelay(value.Get()); break; } case Toolkit::Button::Property::NEXT_AUTO_REPEATING_DELAY: { - GetImplementation( button ).SetNextAutoRepeatingDelay( value.Get< float >() ); + GetImplementation(button).SetNextAutoRepeatingDelay(value.Get()); break; } case Toolkit::Button::Property::TOGGLABLE: { - GetImplementation( button ).SetTogglableButton( value.Get< bool >() ); + GetImplementation(button).SetTogglableButton(value.Get()); break; } case Toolkit::Button::Property::SELECTED: { - GetImplementation( button ).SetSelected( value.Get< bool >() ); + GetImplementation(button).SetSelected(value.Get()); break; } @@ -1121,7 +1109,7 @@ void Button::SetProperty( BaseObject* object, Property::Index index, const Prope case Toolkit::Button::Property::DISABLED_SELECTED_VISUAL: case Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL: { - GetImplementation( button ).CreateVisualsForComponent( index, value, DepthIndex::CONTENT ); + GetImplementation(button).CreateVisualsForComponent(index, value, DepthIndex::CONTENT); break; } @@ -1130,39 +1118,39 @@ void Button::SetProperty( BaseObject* object, Property::Index index, const Prope case Toolkit::Button::Property::DISABLED_SELECTED_BACKGROUND_VISUAL: case Toolkit::Button::Property::DISABLED_UNSELECTED_BACKGROUND_VISUAL: { - GetImplementation( button ).CreateVisualsForComponent( index , value, DepthIndex::BACKGROUND); + GetImplementation(button).CreateVisualsForComponent(index, value, DepthIndex::BACKGROUND); break; } case Toolkit::Button::Property::LABEL: { Property::Map outTextVisualProperties; - std::string textString; + std::string textString; - if ( value.Get( textString ) ) + if(value.Get(textString)) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetProperty Setting TextVisual with string[%s]\n", textString.c_str() ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetProperty Setting TextVisual with string[%s]\n", textString.c_str()); Property::Map setPropertyMap; - setPropertyMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT ) - .Add( Toolkit::TextVisual::Property::TEXT, textString ); + setPropertyMap.Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT) + .Add(Toolkit::TextVisual::Property::TEXT, textString); - GetImplementation( button ).MergeWithExistingLabelProperties( setPropertyMap, outTextVisualProperties ); + GetImplementation(button).MergeWithExistingLabelProperties(setPropertyMap, outTextVisualProperties); } else { // Get a Property::Map from the property if possible. const Property::Map* setPropertyMap = value.GetMap(); - if( setPropertyMap ) + if(setPropertyMap) { - Property::Map indexKeys = TextVisual::ConvertStringKeysToIndexKeys( *setPropertyMap ); - GetImplementation( button ).MergeWithExistingLabelProperties( indexKeys, outTextVisualProperties ); + Property::Map indexKeys = TextVisual::ConvertStringKeysToIndexKeys(*setPropertyMap); + GetImplementation(button).MergeWithExistingLabelProperties(indexKeys, outTextVisualProperties); } } - if( !outTextVisualProperties.Empty() ) + if(!outTextVisualProperties.Empty()) { - GetImplementation( button ).CreateVisualsForComponent( index, outTextVisualProperties, DepthIndex::CONTENT ); + GetImplementation(button).CreateVisualsForComponent(index, outTextVisualProperties, DepthIndex::CONTENT); } break; } @@ -1170,74 +1158,75 @@ void Button::SetProperty( BaseObject* object, Property::Index index, const Prope case Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT: { Button::Align labelAlignment(END); - Scripting::GetEnumeration< Button::Align> ( value.Get< std::string >().c_str(), - ALIGNMENT_TABLE, ALIGNMENT_TABLE_COUNT, - labelAlignment ); + Scripting::GetEnumeration(value.Get().c_str(), + ALIGNMENT_TABLE, + ALIGNMENT_TABLE_COUNT, + labelAlignment); - GetImplementation( button ).SetLabelAlignment( labelAlignment ); + GetImplementation(button).SetLabelAlignment(labelAlignment); break; } case Toolkit::DevelButton::Property::LABEL_PADDING: { - Vector4 padding ( value.Get< Vector4 >() ); - GetImplementation( button ).SetLabelPadding( Padding( padding.x, padding.y, padding.z, padding.w ) ); + Vector4 padding(value.Get()); + GetImplementation(button).SetLabelPadding(Padding(padding.x, padding.y, padding.z, padding.w)); break; } case Toolkit::DevelButton::Property::VISUAL_PADDING: { - Vector4 padding ( value.Get< Vector4 >() ); - GetImplementation( button ).SetForegroundPadding( Padding( padding.x, padding.y, padding.z, padding.w ) ); + Vector4 padding(value.Get()); + GetImplementation(button).SetForegroundPadding(Padding(padding.x, padding.y, padding.z, padding.w)); break; } } } } -Property::Value Button::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value Button::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::Button button = Toolkit::Button::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Button button = Toolkit::Button::DownCast(Dali::BaseHandle(object)); - if ( button ) + if(button) { - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::Button::Property::DISABLED: { - value = GetImplementation( button ).IsDisabled(); + value = GetImplementation(button).IsDisabled(); break; } case Toolkit::Button::Property::AUTO_REPEATING: { - value = GetImplementation( button ).mAutoRepeating; + value = GetImplementation(button).mAutoRepeating; break; } case Toolkit::Button::Property::INITIAL_AUTO_REPEATING_DELAY: { - value = GetImplementation( button ).mInitialAutoRepeatingDelay; + value = GetImplementation(button).mInitialAutoRepeatingDelay; break; } case Toolkit::Button::Property::NEXT_AUTO_REPEATING_DELAY: { - value = GetImplementation( button ).mNextAutoRepeatingDelay; + value = GetImplementation(button).mNextAutoRepeatingDelay; break; } case Toolkit::Button::Property::TOGGLABLE: { - value = GetImplementation( button ).mTogglableButton; + value = GetImplementation(button).mTogglableButton; break; } case Toolkit::Button::Property::SELECTED: { - value = GetImplementation( button ).IsSelected(); + value = GetImplementation(button).IsSelected(); break; } @@ -1252,7 +1241,7 @@ Property::Value Button::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Button::Property::LABEL: { Property::Map visualProperty; - if ( GetImplementation( button ).GetPropertyMapForVisual( propertyIndex, visualProperty ) ) + if(GetImplementation(button).GetPropertyMapForVisual(propertyIndex, visualProperty)) { value = visualProperty; } @@ -1261,12 +1250,12 @@ Property::Value Button::GetProperty( BaseObject* object, Property::Index propert case Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT: { - const char* alignment = Scripting::GetEnumerationName< Button::Align >( GetImplementation( button ).GetLabelAlignment(), - ALIGNMENT_STRING_TABLE, - ALIGNMENT_STRING_TABLE_COUNT ); - if( alignment ) + const char* alignment = Scripting::GetEnumerationName(GetImplementation(button).GetLabelAlignment(), + ALIGNMENT_STRING_TABLE, + ALIGNMENT_STRING_TABLE_COUNT); + if(alignment) { - value = std::string( alignment ); + value = std::string(alignment); } break; @@ -1274,15 +1263,15 @@ Property::Value Button::GetProperty( BaseObject* object, Property::Index propert case Toolkit::DevelButton::Property::LABEL_PADDING: { - Padding padding = GetImplementation( button ).GetLabelPadding(); - value = Vector4( padding.x, padding.y, padding.top, padding.bottom); + Padding padding = GetImplementation(button).GetLabelPadding(); + value = Vector4(padding.x, padding.y, padding.top, padding.bottom); break; } case Toolkit::DevelButton::Property::VISUAL_PADDING: { - Padding padding = GetImplementation( button ).GetForegroundPadding(); - value = Vector4( padding.x, padding.y, padding.top, padding.bottom); + Padding padding = GetImplementation(button).GetForegroundPadding(); + value = Vector4(padding.x, padding.y, padding.top, padding.bottom); } } } @@ -1290,10 +1279,10 @@ Property::Value Button::GetProperty( BaseObject* object, Property::Index propert return value; } -void Button::SetLabelPadding( const Padding& padding) +void Button::SetLabelPadding(const Padding& padding) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetLabelPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top ); - mLabelPadding = Padding( padding.left, padding.right, padding.bottom, padding.top ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetLabelPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top); + mLabelPadding = Padding(padding.left, padding.right, padding.bottom, padding.top); RelayoutRequest(); } @@ -1302,10 +1291,10 @@ Padding Button::GetLabelPadding() return mLabelPadding; } -void Button::SetForegroundPadding( const Padding& padding) +void Button::SetForegroundPadding(const Padding& padding) { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "Button::SetForegroundPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top ); - mForegroundPadding = Padding( padding.left, padding.right, padding.bottom, padding.top ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "Button::SetForegroundPadding padding(%f,%f,%f,%f)\n", padding.left, padding.right, padding.bottom, padding.top); + mForegroundPadding = Padding(padding.left, padding.right, padding.bottom, padding.top); RelayoutRequest(); } @@ -1316,26 +1305,25 @@ Padding Button::GetForegroundPadding() std::string Button::AccessibleImpl::GetNameRaw() { - std::string labelText; - auto slf = Toolkit::Button::DownCast( self ); - Property::Map labelMap = slf.GetProperty( Toolkit::Button::Property::LABEL ); + std::string labelText; + auto slf = Toolkit::Button::DownCast(self); + Property::Map labelMap = slf.GetProperty(Toolkit::Button::Property::LABEL); - Property::Value* textPropertyPtr = labelMap.Find( Toolkit::TextVisual::Property::TEXT ); - if ( textPropertyPtr ) + Property::Value* textPropertyPtr = labelMap.Find(Toolkit::TextVisual::Property::TEXT); + if(textPropertyPtr) { - textPropertyPtr->Get( labelText ); + textPropertyPtr->Get(labelText); } return labelText; } - Property::Index Button::AccessibleImpl::GetNamePropertyIndex() { - Property::Index label = Toolkit::Button::Property::LABEL; - Property::Map labelMap = self.GetProperty(label); + Property::Index label = Toolkit::Button::Property::LABEL; + Property::Map labelMap = self.GetProperty(label); - if (MapContainsTextString(labelMap)) + if(MapContainsTextString(labelMap)) return label; else return Property::INVALID_INDEX; @@ -1343,11 +1331,11 @@ Property::Index Button::AccessibleImpl::GetNamePropertyIndex() Dali::Accessibility::States Button::AccessibleImpl::CalculateStates() { - auto tmp = Control::Impl::AccessibleImpl::CalculateStates(); + auto tmp = Control::Impl::AccessibleImpl::CalculateStates(); tmp[Dali::Accessibility::State::SELECTABLE] = true; - auto slf = Toolkit::Button::DownCast( self ); - tmp[Dali::Accessibility::State::ENABLED] = !slf.GetProperty( Toolkit::Button::Property::DISABLED ); - tmp[Dali::Accessibility::State::CHECKED] = slf.GetProperty( Toolkit::Button::Property::SELECTED ); + auto slf = Toolkit::Button::DownCast(self); + tmp[Dali::Accessibility::State::ENABLED] = !slf.GetProperty(Toolkit::Button::Property::DISABLED); + tmp[Dali::Accessibility::State::CHECKED] = slf.GetProperty(Toolkit::Button::Property::SELECTED); return tmp; } diff --git a/dali-toolkit/internal/controls/buttons/check-box-button-impl.cpp b/dali-toolkit/internal/controls/buttons/check-box-button-impl.cpp index 103992f..3f4188b 100644 --- a/dali-toolkit/internal/controls/buttons/check-box-button-impl.cpp +++ b/dali-toolkit/internal/controls/buttons/check-box-button-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,45 +23,38 @@ #include //INTERNAL INCLUDES -#include #include #include -#include +#include #if defined(DEBUG_ENABLED) - extern Debug::Filter* gLogButtonFilter; +extern Debug::Filter* gLogButtonFilter; #endif namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::CheckBoxButton::New(); } -TypeRegistration mType( typeid(Toolkit::CheckBoxButton), typeid(Toolkit::Button), Create ); - +TypeRegistration mType(typeid(Toolkit::CheckBoxButton), typeid(Toolkit::Button), Create); - -} +} // namespace Dali::Toolkit::CheckBoxButton CheckBoxButton::New() { // Create the implementation, temporarily owned on stack - IntrusivePtr< CheckBoxButton > internalCheckBoxButton = new CheckBoxButton(); + IntrusivePtr internalCheckBoxButton = new CheckBoxButton(); // Pass ownership to CustomActor - Dali::Toolkit::CheckBoxButton checkBoxButton( *internalCheckBoxButton ); + Dali::Toolkit::CheckBoxButton checkBoxButton(*internalCheckBoxButton); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -73,7 +66,7 @@ Dali::Toolkit::CheckBoxButton CheckBoxButton::New() CheckBoxButton::CheckBoxButton() : Button() { - SetTogglableButton( true ); + SetTogglableButton(true); } CheckBoxButton::~CheckBoxButton() @@ -84,29 +77,28 @@ void CheckBoxButton::OnInitialize() { Button::OnInitialize(); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::CHECK_BOX ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::CHECK_BOX)); + }); } Dali::Accessibility::States CheckBoxButton::AccessibleImpl::CalculateStates() { auto tmp = Button::AccessibleImpl::CalculateStates(); - auto slf = Toolkit::Button::DownCast( self ); - if( slf.GetProperty( Toolkit::Button::Property::SELECTED ) ) + auto slf = Toolkit::Button::DownCast(self); + if(slf.GetProperty(Toolkit::Button::Property::SELECTED)) tmp[Dali::Accessibility::State::CHECKED] = true; return tmp; } -void CheckBoxButton::OnStateChange( State newState ) +void CheckBoxButton::OnStateChange(State newState) { // TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used - if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) + if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) { Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged( - Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0 - ); + Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0); } } diff --git a/dali-toolkit/internal/controls/buttons/push-button-impl.cpp b/dali-toolkit/internal/controls/buttons/push-button-impl.cpp index 2fadac4..b5a4233 100644 --- a/dali-toolkit/internal/controls/buttons/push-button-impl.cpp +++ b/dali-toolkit/internal/controls/buttons/push-button-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,33 +19,29 @@ #include "push-button-impl.h" // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES -#include -#include #include #include +#include +#include #if defined(DEBUG_ENABLED) - extern Debug::Filter* gLogButtonFilter; +extern Debug::Filter* gLogButtonFilter; #endif namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::PushButton::New(); @@ -53,10 +49,10 @@ BaseHandle Create() // Properties -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PushButton, Toolkit::Button, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PushButton, Toolkit::Button, Create) -DALI_PROPERTY_REGISTRATION( Toolkit, PushButton, "labelPadding", STRING, LABEL_PADDING ) -DALI_PROPERTY_REGISTRATION( Toolkit, PushButton, "iconPadding", STRING, ICON_PADDING ) +DALI_PROPERTY_REGISTRATION(Toolkit, PushButton, "labelPadding", STRING, LABEL_PADDING) +DALI_PROPERTY_REGISTRATION(Toolkit, PushButton, "iconPadding", STRING, ICON_PADDING) DALI_TYPE_REGISTRATION_END() @@ -64,16 +60,15 @@ DALI_TYPE_REGISTRATION_END() namespace { - } // unnamed namespace Dali::Toolkit::PushButton PushButton::New() { // Create the implementation, temporarily owned on stack - IntrusivePtr< PushButton > internalPushButton = new PushButton(); + IntrusivePtr internalPushButton = new PushButton(); // Pass ownership to CustomActor - Dali::Toolkit::PushButton pushButton( *internalPushButton ); + Dali::Toolkit::PushButton pushButton(*internalPushButton); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -84,7 +79,7 @@ Dali::Toolkit::PushButton PushButton::New() PushButton::PushButton() : Button(), - mIconAlignment( RIGHT ) + mIconAlignment(RIGHT) { } @@ -98,42 +93,42 @@ void PushButton::OnInitialize() // Push button requires the Leave event. Actor self = Self(); - self.SetProperty( Actor::Property::LEAVE_REQUIRED, true ); + self.SetProperty(Actor::Property::LEAVE_REQUIRED, true); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::PUSH_BUTTON ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::PUSH_BUTTON)); + }); } -void PushButton::SetIconAlignment( const PushButton::IconAlignment iconAlignment ) +void PushButton::SetIconAlignment(const PushButton::IconAlignment iconAlignment) { mIconAlignment = iconAlignment; Button::Align labelAlignment; - switch ( iconAlignment ) + switch(iconAlignment) { - case RIGHT: - { - labelAlignment = Button::BEGIN; - break; - } - case TOP: - { - labelAlignment = Button::BOTTOM; - break; - } - case BOTTOM: - { - labelAlignment = Button::TOP; - break; - } - case LEFT: - default: - labelAlignment = Button::END; - break; + case RIGHT: + { + labelAlignment = Button::BEGIN; + break; + } + case TOP: + { + labelAlignment = Button::BOTTOM; + break; + } + case BOTTOM: + { + labelAlignment = Button::TOP; + break; + } + case LEFT: + default: + labelAlignment = Button::END; + break; } - Button::SetLabelAlignment( labelAlignment ); + Button::SetLabelAlignment(labelAlignment); } const PushButton::IconAlignment PushButton::GetIconAlignment() const @@ -141,56 +136,56 @@ const PushButton::IconAlignment PushButton::GetIconAlignment() const return mIconAlignment; } -void PushButton::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) +void PushButton::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value) { - Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast( Dali::BaseHandle( object ) ); + Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast(Dali::BaseHandle(object)); - if ( pushButton ) + if(pushButton) { - PushButton& pushButtonImpl( GetImplementation( pushButton ) ); + PushButton& pushButtonImpl(GetImplementation(pushButton)); // Properties remain here for Tizen 3.0 legacy requirements. Are now in Button base class - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::PushButton::Property::LABEL_PADDING: { - Vector4 padding ( value.Get< Vector4 >() ); - pushButtonImpl.Button::SetLabelPadding( Padding( padding.x, padding.y, padding.z, padding.w ) ); + Vector4 padding(value.Get()); + pushButtonImpl.Button::SetLabelPadding(Padding(padding.x, padding.y, padding.z, padding.w)); break; } case Toolkit::PushButton::Property::ICON_PADDING: { - Vector4 padding ( value.Get< Vector4 >() ); - pushButtonImpl.Button::SetForegroundPadding( Padding( padding.x, padding.y, padding.z, padding.w ) ); + Vector4 padding(value.Get()); + pushButtonImpl.Button::SetForegroundPadding(Padding(padding.x, padding.y, padding.z, padding.w)); break; } } } } -Property::Value PushButton::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value PushButton::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast( Dali::BaseHandle( object ) ); + Toolkit::PushButton pushButton = Toolkit::PushButton::DownCast(Dali::BaseHandle(object)); - if ( pushButton ) + if(pushButton) { - PushButton& pushButtonImpl( GetImplementation( pushButton ) ); + PushButton& pushButtonImpl(GetImplementation(pushButton)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::PushButton::Property::LABEL_PADDING: { Padding padding = pushButtonImpl.Button::GetLabelPadding(); - value = Vector4( padding.x, padding.y, padding.top, padding.bottom); + value = Vector4(padding.x, padding.y, padding.top, padding.bottom); break; } case Toolkit::PushButton::Property::ICON_PADDING: { Padding padding = pushButtonImpl.Button::GetForegroundPadding(); - value = Vector4( padding.x, padding.y, padding.top, padding.bottom); + value = Vector4(padding.x, padding.y, padding.top, padding.bottom); break; } } @@ -201,26 +196,24 @@ Property::Value PushButton::GetProperty( BaseObject* object, Property::Index pro Dali::Accessibility::States PushButton::AccessibleImpl::CalculateStates() { - auto tmp = Button::AccessibleImpl::CalculateStates(); - auto slf = Toolkit::Button::DownCast( self ); - tmp[Dali::Accessibility::State::PRESSED] = slf.GetProperty( Toolkit::Button::Property::SELECTED ); + auto tmp = Button::AccessibleImpl::CalculateStates(); + auto slf = Toolkit::Button::DownCast(self); + tmp[Dali::Accessibility::State::PRESSED] = slf.GetProperty(Toolkit::Button::Property::SELECTED); return tmp; } -void PushButton::OnStateChange( State newState ) +void PushButton::OnStateChange(State newState) { // TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used - if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) + if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) { Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged( - Dali::Accessibility::State::PRESSED, newState == SELECTED_STATE ? 1 : 0, 0 - ); + Dali::Accessibility::State::PRESSED, newState == SELECTED_STATE ? 1 : 0, 0); - if (Self().GetProperty(Toolkit::Button::Property::TOGGLABLE)) + if(Self().GetProperty(Toolkit::Button::Property::TOGGLABLE)) { Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged( - Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0 - ); + Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0); } } } diff --git a/dali-toolkit/internal/controls/buttons/radio-button-impl.cpp b/dali-toolkit/internal/controls/buttons/radio-button-impl.cpp index 3276076..ba3348a 100644 --- a/dali-toolkit/internal/controls/buttons/radio-button-impl.cpp +++ b/dali-toolkit/internal/controls/buttons/radio-button-impl.cpp @@ -15,7 +15,6 @@ * */ - // CLASS HEADER #include "radio-button-impl.h" @@ -24,34 +23,30 @@ #include #if defined(DEBUG_ENABLED) - extern Debug::Filter* gLogButtonFilter; +extern Debug::Filter* gLogButtonFilter; #endif namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::RadioButton::New(); } -TypeRegistration typeRegistration( typeid( Toolkit::RadioButton ), typeid( Toolkit::Button ), Create); +TypeRegistration typeRegistration(typeid(Toolkit::RadioButton), typeid(Toolkit::Button), Create); -} +} // namespace Dali::Toolkit::RadioButton RadioButton::New() { // Create the implementation, temporarily owned on stack - IntrusivePtr< RadioButton > internalRadioButton = new RadioButton(); + IntrusivePtr internalRadioButton = new RadioButton(); // Pass ownership to CustomActor Dali::Toolkit::RadioButton radioButton(*internalRadioButton); @@ -76,10 +71,10 @@ void RadioButton::OnInitialize() { Button::OnInitialize(); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::RADIO_BUTTON ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::RADIO_BUTTON)); + }); } bool RadioButton::OnToggleReleased() @@ -88,40 +83,39 @@ bool RadioButton::OnToggleReleased() return false; } -void RadioButton::OnStateChange( State newState ) +void RadioButton::OnStateChange(State newState) { // Radio button can be part of a group, if a button in the group is selected then all others should be unselected - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "RadioButton::OnStateChange state(%d)\n", newState ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "RadioButton::OnStateChange state(%d)\n", newState); - if ( SELECTED_STATE == newState ) + if(SELECTED_STATE == newState) { Actor parent = Self().GetParent(); - if( parent ) + if(parent) { - for( unsigned int i = 0; i < parent.GetChildCount(); ++i ) + for(unsigned int i = 0; i < parent.GetChildCount(); ++i) { - Dali::Toolkit::RadioButton radioButtonChild = Dali::Toolkit::RadioButton::DownCast( parent.GetChildAt( i ) ); - if( radioButtonChild && radioButtonChild != Self() ) + Dali::Toolkit::RadioButton radioButtonChild = Dali::Toolkit::RadioButton::DownCast(parent.GetChildAt(i)); + if(radioButtonChild && radioButtonChild != Self()) { - radioButtonChild.SetProperty( Toolkit::Button::Property::SELECTED, false ); + radioButtonChild.SetProperty(Toolkit::Button::Property::SELECTED, false); } } } } // TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used - if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) + if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) { Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged( - Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0 - ); + Dali::Accessibility::State::CHECKED, newState == SELECTED_STATE ? 1 : 0, 0); } } Dali::Accessibility::States RadioButton::AccessibleImpl::CalculateStates() { auto tmp = Button::AccessibleImpl::CalculateStates(); - auto slf = Toolkit::Button::DownCast( self ); - if( slf.GetProperty( Toolkit::Button::Property::SELECTED ) ) + auto slf = Toolkit::Button::DownCast(self); + if(slf.GetProperty(Toolkit::Button::Property::SELECTED)) tmp[Dali::Accessibility::State::CHECKED] = true; tmp[Dali::Accessibility::State::SELECTABLE] = true; return tmp; diff --git a/dali-toolkit/internal/controls/buttons/toggle-button-impl.cpp b/dali-toolkit/internal/controls/buttons/toggle-button-impl.cpp index a756a22..b141fbd 100644 --- a/dali-toolkit/internal/controls/buttons/toggle-button-impl.cpp +++ b/dali-toolkit/internal/controls/buttons/toggle-button-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,50 +19,45 @@ #include "toggle-button-impl.h" // EXTERNAL INCLUDES -#include -#include #include -#include #include +#include +#include +#include // INTERNAL INCLUDES -#include #include #include +#include #include -#include #include -#include +#include #include -#include +#include #if defined(DEBUG_ENABLED) - extern Debug::Filter* gLogButtonFilter; +extern Debug::Filter* gLogButtonFilter; #endif namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::ToggleButton::New(); } // Properties -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ToggleButton, Toolkit::Button, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ToggleButton, Toolkit::Button, Create) -DALI_PROPERTY_REGISTRATION( Toolkit, ToggleButton, "stateVisuals", ARRAY, STATE_VISUALS ) -DALI_PROPERTY_REGISTRATION( Toolkit, ToggleButton, "tooltips", ARRAY, TOOLTIPS ) -DALI_PROPERTY_REGISTRATION( Toolkit, ToggleButton, "currentStateIndex", INTEGER, CURRENT_STATE_INDEX ) +DALI_PROPERTY_REGISTRATION(Toolkit, ToggleButton, "stateVisuals", ARRAY, STATE_VISUALS) +DALI_PROPERTY_REGISTRATION(Toolkit, ToggleButton, "tooltips", ARRAY, TOOLTIPS) +DALI_PROPERTY_REGISTRATION(Toolkit, ToggleButton, "currentStateIndex", INTEGER, CURRENT_STATE_INDEX) DALI_TYPE_REGISTRATION_END() @@ -70,12 +65,12 @@ DALI_TYPE_REGISTRATION_END() Dali::Toolkit::ToggleButton ToggleButton::New() { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::New\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::New\n"); // Create the implementation, temporarily owned on stack - IntrusivePtr< ToggleButton > internalToggleButton = new ToggleButton(); + IntrusivePtr internalToggleButton = new ToggleButton(); // Pass ownership to CustomActor - Dali::Toolkit::ToggleButton toggleButton( *internalToggleButton ); + Dali::Toolkit::ToggleButton toggleButton(*internalToggleButton); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -94,8 +89,8 @@ ToggleButton::ToggleButton() mToggleTooltips(), mCurrentToggleIndex(0) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::Constructor\n" ); - SetTogglableButton( false ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::Constructor\n"); + SetTogglableButton(false); } ToggleButton::~ToggleButton() @@ -104,37 +99,37 @@ ToggleButton::~ToggleButton() void ToggleButton::OnInitialize() { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnInitialize\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnInitialize\n"); Button::OnInitialize(); // Toggle button requires the Leave event. Actor self = Self(); - self.SetProperty( Actor::Property::LEAVE_REQUIRED, true ); + self.SetProperty(Actor::Property::LEAVE_REQUIRED, true); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::TOGGLE_BUTTON ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::TOGGLE_BUTTON)); + }); } -void ToggleButton::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) +void ToggleButton::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value) { - Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast(Dali::BaseHandle(object)); - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::SetProperty index[%d]\n", propertyIndex ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::SetProperty index[%d]\n", propertyIndex); - if ( toggleButton ) + if(toggleButton) { - ToggleButton& toggleButtonImpl( GetImplementation( toggleButton ) ); + ToggleButton& toggleButtonImpl(GetImplementation(toggleButton)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::ToggleButton::Property::STATE_VISUALS: { Property::Array stateArray; - if( value.Get( stateArray ) ) + if(value.Get(stateArray)) { - toggleButtonImpl.SetToggleStates( stateArray ); + toggleButtonImpl.SetToggleStates(stateArray); } break; @@ -142,20 +137,20 @@ void ToggleButton::SetProperty( BaseObject* object, Property::Index propertyInde case Toolkit::ToggleButton::Property::TOOLTIPS: { const Property::Array* tipArray = value.GetArray(); - if( tipArray ) + if(tipArray) { std::vector tips; - size_t tipsCount = tipArray->Count(); - tips.resize( tipsCount ); - for( size_t i = 0; i != tipsCount; ++i ) + size_t tipsCount = tipArray->Count(); + tips.resize(tipsCount); + for(size_t i = 0; i != tipsCount; ++i) { - tipArray->GetElementAt( i ).Get( tips[i] ); + tipArray->GetElementAt(i).Get(tips[i]); } toggleButtonImpl.SetToggleTooltips(tips); } break; } - default : + default: { break; } @@ -163,38 +158,38 @@ void ToggleButton::SetProperty( BaseObject* object, Property::Index propertyInde } } -Property::Value ToggleButton::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value ToggleButton::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ToggleButton toggleButton = Toolkit::ToggleButton::DownCast(Dali::BaseHandle(object)); - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::GetProperty index[%d]\n", propertyIndex ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::GetProperty index[%d]\n", propertyIndex); - if ( toggleButton ) + if(toggleButton) { - ToggleButton& toggleButtonImpl( GetImplementation( toggleButton ) ); + ToggleButton& toggleButtonImpl(GetImplementation(toggleButton)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::ToggleButton::Property::STATE_VISUALS: { Property::Array array = toggleButtonImpl.GetToggleStates(); - value = Property::Value( array ); + value = Property::Value(array); break; } case Toolkit::ToggleButton::Property::TOOLTIPS: { - Property::Value value1( Property::ARRAY ); + Property::Value value1(Property::ARRAY); Property::Array* tipArray = value1.GetArray(); - if( tipArray ) + if(tipArray) { std::vector tips = toggleButtonImpl.GetToggleTooltips(); - size_t tipsCount( tips.size() ); - for( size_t i( 0 ); i != tipsCount; ++i ) + size_t tipsCount(tips.size()); + for(size_t i(0); i != tipsCount; ++i) { - tipArray->PushBack( tips[i] ); + tipArray->PushBack(tips[i]); } } value = value1; @@ -211,51 +206,51 @@ Property::Value ToggleButton::GetProperty( BaseObject* object, Property::Index p return value; } -void ToggleButton::CreateVisualsForAllStates( const Property::Array& states, std::vector& visuals ) +void ToggleButton::CreateVisualsForAllStates(const Property::Array& states, std::vector& visuals) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::CreateVisualsForAllStates\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::CreateVisualsForAllStates\n"); visuals.clear(); - for ( unsigned int i = 0; i < states.Count(); i++ ) + for(unsigned int i = 0; i < states.Count(); i++) { - Property::Value value( states[i] ); + Property::Value value(states[i]); Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get(); - Toolkit::Visual::Base stateVisual; + Toolkit::Visual::Base stateVisual; - if ( value.GetType() == Property::MAP ) + if(value.GetType() == Property::MAP) { - Property::Map *map = value.GetMap(); - if( map && !map->Empty() ) // Empty map results in current visual removal. + Property::Map* map = value.GetMap(); + if(map && !map->Empty()) // Empty map results in current visual removal. { - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using Map\n" ); - stateVisual = visualFactory.CreateVisual( *map ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using Map\n"); + stateVisual = visualFactory.CreateVisual(*map); } } - else if ( value.GetType() == Property::STRING ) + else if(value.GetType() == Property::STRING) { std::string imageUrl = value.Get(); - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using image URL\n" ); - if ( !imageUrl.empty() ) + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals Using image URL\n"); + if(!imageUrl.empty()) { - stateVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() ); + stateVisual = visualFactory.CreateVisual(imageUrl, ImageDimensions()); } } - if ( stateVisual ) + if(stateVisual) { - stateVisual.SetDepthIndex( DepthIndex::CONTENT ); - visuals.push_back( stateVisual ); + stateVisual.SetDepthIndex(DepthIndex::CONTENT); + visuals.push_back(stateVisual); } } // end of for - DALI_LOG_INFO( gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals mToggleVisuals:%d\n", mToggleVisuals.size() ); + DALI_LOG_INFO(gLogButtonFilter, Debug::Verbose, "ToggleButton::CreateVisuals mToggleVisuals:%d\n", mToggleVisuals.size()); } -void ToggleButton::SetToggleStates( const Property::Array& states ) +void ToggleButton::SetToggleStates(const Property::Array& states) { //this should really be generalized to be either string or maps so that any visual can be created. - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::SetToggleStates\n" ); - if ( !states.Empty() ) + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::SetToggleStates\n"); + if(!states.Empty()) { mToggleStates.Clear(); mToggleStates = states; @@ -263,17 +258,17 @@ void ToggleButton::SetToggleStates( const Property::Array& states ) mCurrentToggleIndex = 0; // Create all visuals, save to mToggleVisuals. - CreateVisualsForAllStates( states, mToggleVisuals ); - CreateVisualsForAllStates( states, mToggleSelectedVisuals ); - CreateVisualsForAllStates( states, mToggleDisabledVisuals ); - CreateVisualsForAllStates( states, mToggleDisabledSelectedVisuals ); + CreateVisualsForAllStates(states, mToggleVisuals); + CreateVisualsForAllStates(states, mToggleSelectedVisuals); + CreateVisualsForAllStates(states, mToggleDisabledVisuals); + CreateVisualsForAllStates(states, mToggleDisabledSelectedVisuals); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::Began to register visual.\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::Began to register visual.\n"); - PrepareVisual( Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex] ); - PrepareVisual( Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex] ); - PrepareVisual( Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex] ); - PrepareVisual( Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex] ); + PrepareVisual(Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex]); + PrepareVisual(Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex]); + PrepareVisual(Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex]); + PrepareVisual(Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex]); RelayoutRequest(); } @@ -284,18 +279,18 @@ Property::Array ToggleButton::GetToggleStates() const return mToggleStates; } -void ToggleButton::SetToggleTooltips( std::vector& tips ) +void ToggleButton::SetToggleTooltips(std::vector& tips) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::SetToggleTooltips\n" ); - if ( !tips.empty() ) + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::SetToggleTooltips\n"); + if(!tips.empty()) { mToggleTooltips.clear(); - mToggleTooltips.swap( tips ); + mToggleTooltips.swap(tips); } - if ( !mToggleTooltips.empty() && ( mCurrentToggleIndex < mToggleTooltips.size() ) ) + if(!mToggleTooltips.empty() && (mCurrentToggleIndex < mToggleTooltips.size())) { - Self().SetProperty( Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex] ); + Self().SetProperty(Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex]); } RelayoutRequest(); @@ -311,67 +306,67 @@ void ToggleButton::PrepareVisual(Property::Index index, Toolkit::Visual::Base& v bool enabled = false; // Disabled by default // Unregister the visual with the given index if registered previously - if( DevelControl::GetVisual( *this, index ) ) + if(DevelControl::GetVisual(*this, index)) { // Check whether it was enabled to ensure we do the same with the new visual we're registering - enabled = DevelControl::IsVisualEnabled( *this, index ); - DevelControl::UnregisterVisual( *this, index ); + enabled = DevelControl::IsVisualEnabled(*this, index); + DevelControl::UnregisterVisual(*this, index); } - DevelControl::RegisterVisual( *this, index, visual, enabled ); + DevelControl::RegisterVisual(*this, index, visual, enabled); } -void ToggleButton::RelayoutVisual( Property::Index index, const Vector2& size ) +void ToggleButton::RelayoutVisual(Property::Index index, const Vector2& size) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, index ); - if ( visual ) + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, index); + if(visual) { - Size visualSize = Size::ZERO; + Size visualSize = Size::ZERO; Vector2 visualPosition = Vector2::ZERO; - visual.GetNaturalSize( visualSize ); + visual.GetNaturalSize(visualSize); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height ); - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual position to(%f,%f)\n", visualPosition.x, visualPosition.y ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual size to(%f,%f)\n", visualSize.width, visualSize.height); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout Setting visual position to(%f,%f)\n", visualPosition.x, visualPosition.y); Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, visualSize ) - .Add( Toolkit::Visual::Transform::Property::OFFSET, visualPosition ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::CENTER ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::CENTER ); - - visual.SetTransformAndSize( visualTransform, size ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, visualSize) + .Add(Toolkit::Visual::Transform::Property::OFFSET, visualPosition) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::CENTER) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::CENTER); + + visual.SetTransformAndSize(visualTransform, size); } } -void ToggleButton::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void ToggleButton::OnRelayout(const Vector2& size, RelayoutContainer& container) { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout targetSize(%f,%f) ptr(%p)\n", size.width, size.height, this ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnRelayout targetSize(%f,%f) ptr(%p)\n", size.width, size.height, this); - RelayoutVisual( Toolkit::Button::Property::UNSELECTED_VISUAL, size ); - RelayoutVisual( Toolkit::Button::Property::SELECTED_VISUAL, size ); - RelayoutVisual( Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, size ); - RelayoutVisual( Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, size ); + RelayoutVisual(Toolkit::Button::Property::UNSELECTED_VISUAL, size); + RelayoutVisual(Toolkit::Button::Property::SELECTED_VISUAL, size); + RelayoutVisual(Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, size); + RelayoutVisual(Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, size); } void ToggleButton::OnPressed() { - DALI_LOG_INFO( gLogButtonFilter, Debug::General, "ToggleButton::OnPressed\n" ); + DALI_LOG_INFO(gLogButtonFilter, Debug::General, "ToggleButton::OnPressed\n"); // State index will add 1 only when button is pressed. - mCurrentToggleIndex = ( mCurrentToggleIndex + 1 ) % mToggleVisuals.size(); + mCurrentToggleIndex = (mCurrentToggleIndex + 1) % mToggleVisuals.size(); // Both create SelectedVisual and UnselectedVisual - PrepareVisual( Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex] ); - PrepareVisual( Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex] ); - PrepareVisual( Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex] ); - PrepareVisual( Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex] ); + PrepareVisual(Toolkit::Button::Property::UNSELECTED_VISUAL, mToggleVisuals[mCurrentToggleIndex]); + PrepareVisual(Toolkit::Button::Property::SELECTED_VISUAL, mToggleSelectedVisuals[mCurrentToggleIndex]); + PrepareVisual(Toolkit::Button::Property::DISABLED_UNSELECTED_VISUAL, mToggleDisabledVisuals[mCurrentToggleIndex]); + PrepareVisual(Toolkit::Button::Property::DISABLED_SELECTED_VISUAL, mToggleDisabledSelectedVisuals[mCurrentToggleIndex]); //Need to check mCurrentToggleIndex, it must less than the size of mToggleTooltips. - if ( !mToggleTooltips.empty() && ( mCurrentToggleIndex < mToggleTooltips.size() ) ) + if(!mToggleTooltips.empty() && (mCurrentToggleIndex < mToggleTooltips.size())) { - Self().SetProperty( Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex] ); + Self().SetProperty(Toolkit::DevelControl::Property::TOOLTIP, mToggleTooltips[mCurrentToggleIndex]); } RelayoutRequest(); @@ -380,17 +375,17 @@ void ToggleButton::OnPressed() Dali::Accessibility::States ToggleButton::AccessibleImpl::CalculateStates() { auto states = Button::AccessibleImpl::CalculateStates(); - auto button = Toolkit::ToggleButton::DownCast( self ); - if( button.GetProperty( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ) ) + auto button = Toolkit::ToggleButton::DownCast(self); + if(button.GetProperty(Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX)) states[Dali::Accessibility::State::CHECKED] = true; return states; } std::string ToggleButton::AccessibleImpl::GetDescriptionRaw() { - auto button = Toolkit::ToggleButton::DownCast( self ); - auto index = button.GetProperty( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ); - auto tooltips = button.GetProperty( Toolkit::ToggleButton::Property::TOOLTIPS ); + auto button = Toolkit::ToggleButton::DownCast(self); + auto index = button.GetProperty(Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX); + auto tooltips = button.GetProperty(Toolkit::ToggleButton::Property::TOOLTIPS); return tooltips[index].Get(); } @@ -400,14 +395,13 @@ Property::Index ToggleButton::AccessibleImpl::GetDescriptionPropertyIndex() return Toolkit::ToggleButton::Property::TOOLTIPS; } -void ToggleButton::OnStateChange( State newState ) +void ToggleButton::OnStateChange(State newState) { // TODO: replace it with OnPropertySet hook once Button::Property::SELECTED will be consistently used - if (Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) + if(Dali::Accessibility::IsUp() && (newState == SELECTED_STATE || newState == UNSELECTED_STATE)) { Dali::Accessibility::Accessible::Get(Self())->EmitStateChanged( - Dali::Accessibility::State::CHECKED, mCurrentToggleIndex ? 1 : 0, 0 - ); + Dali::Accessibility::State::CHECKED, mCurrentToggleIndex ? 1 : 0, 0); if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) { diff --git a/dali-toolkit/internal/controls/control/control-data-impl.cpp b/dali-toolkit/internal/controls/control/control-data-impl.cpp old mode 100755 new mode 100644 index b10842b..ff1ca1e --- a/dali-toolkit/internal/controls/control/control-data-impl.cpp +++ b/dali-toolkit/internal/controls/control/control-data-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,87 +19,78 @@ #include "control-data-impl.h" // EXTERNAL INCLUDES +#include +#include #include -#include +#include +#include +#include #include #include #include -#include -#include #include -#include -#include +#include #include -#include -#include -#include +#include #include #include // INTERNAL INCLUDES -#include -#include -#include +#include #include #include #include #include +#include #include -#include #include -#include +#include +#include +#include namespace { - const std::string READING_INFO_TYPE_NAME = "name"; - const std::string READING_INFO_TYPE_ROLE = "role"; - const std::string READING_INFO_TYPE_DESCRIPTION = "description"; - const std::string READING_INFO_TYPE_STATE = "state"; - const std::string READING_INFO_TYPE_ATTRIBUTE_NAME = "reading_info_type"; - const std::string READING_INFO_TYPE_SEPARATOR = "|"; -} +const std::string READING_INFO_TYPE_NAME = "name"; +const std::string READING_INFO_TYPE_ROLE = "role"; +const std::string READING_INFO_TYPE_DESCRIPTION = "description"; +const std::string READING_INFO_TYPE_STATE = "state"; +const std::string READING_INFO_TYPE_ATTRIBUTE_NAME = "reading_info_type"; +const std::string READING_INFO_TYPE_SEPARATOR = "|"; +} // namespace namespace Dali { - namespace Toolkit { - namespace Internal { - extern const Dali::Scripting::StringEnum ControlStateTable[]; -extern const unsigned int ControlStateTableCount; - +extern const unsigned int ControlStateTableCount; // Not static or anonymous - shared with other translation units const Scripting::StringEnum ControlStateTable[] = { - { "NORMAL", Toolkit::DevelControl::NORMAL }, - { "FOCUSED", Toolkit::DevelControl::FOCUSED }, - { "DISABLED", Toolkit::DevelControl::DISABLED }, + {"NORMAL", Toolkit::DevelControl::NORMAL}, + {"FOCUSED", Toolkit::DevelControl::FOCUSED}, + {"DISABLED", Toolkit::DevelControl::DISABLED}, }; -const unsigned int ControlStateTableCount = sizeof( ControlStateTable ) / sizeof( ControlStateTable[0] ); - - +const unsigned int ControlStateTableCount = sizeof(ControlStateTable) / sizeof(ControlStateTable[0]); namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_CONTROL_VISUALS"); #endif - template -void Remove( Dictionary& keyValues, const std::string& name ) +void Remove(Dictionary& keyValues, const std::string& name) { keyValues.Remove(name); } -void Remove( DictionaryKeys& keys, const std::string& name ) +void Remove(DictionaryKeys& keys, const std::string& name) { - DictionaryKeys::iterator iter = std::find( keys.begin(), keys.end(), name ); - if( iter != keys.end()) + DictionaryKeys::iterator iter = std::find(keys.begin(), keys.end(), name); + if(iter != keys.end()) { keys.erase(iter); } @@ -108,11 +99,11 @@ void Remove( DictionaryKeys& keys, const std::string& name ) /** * Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter */ -bool FindVisual( Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter ) +bool FindVisual(Property::Index targetIndex, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter) { - for ( iter = visuals.Begin(); iter != visuals.End(); iter++ ) + for(iter = visuals.Begin(); iter != visuals.End(); iter++) { - if ( (*iter)->index == targetIndex ) + if((*iter)->index == targetIndex) { return true; } @@ -123,12 +114,12 @@ bool FindVisual( Property::Index targetIndex, const RegisteredVisualContainer& v /** * Finds visual in given array, returning true if found along with the iterator for that visual as a out parameter */ -bool FindVisual( std::string visualName, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter ) +bool FindVisual(std::string visualName, const RegisteredVisualContainer& visuals, RegisteredVisualContainer::Iterator& iter) { - for ( iter = visuals.Begin(); iter != visuals.End(); iter++ ) + for(iter = visuals.Begin(); iter != visuals.End(); iter++) { Toolkit::Visual::Base visual = (*iter)->visual; - if( visual && visual.GetName() == visualName ) + if(visual && visual.GetName() == visualName) { return true; } @@ -136,37 +127,38 @@ bool FindVisual( std::string visualName, const RegisteredVisualContainer& visual return false; } -void FindChangableVisuals( Dictionary& stateVisualsToAdd, - Dictionary& stateVisualsToChange, - DictionaryKeys& stateVisualsToRemove) +void FindChangableVisuals(Dictionary& stateVisualsToAdd, + Dictionary& stateVisualsToChange, + DictionaryKeys& stateVisualsToRemove) { DictionaryKeys copyOfStateVisualsToRemove = stateVisualsToRemove; - for( DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin(); - iter != copyOfStateVisualsToRemove.end(); ++iter ) + for(DictionaryKeys::iterator iter = copyOfStateVisualsToRemove.begin(); + iter != copyOfStateVisualsToRemove.end(); + ++iter) { const std::string& visualName = (*iter); - Property::Map* toMap = stateVisualsToAdd.Find( visualName ); - if( toMap ) + Property::Map* toMap = stateVisualsToAdd.Find(visualName); + if(toMap) { - stateVisualsToChange.Add( visualName, *toMap ); - stateVisualsToAdd.Remove( visualName ); - Remove( stateVisualsToRemove, visualName ); + stateVisualsToChange.Add(visualName, *toMap); + stateVisualsToAdd.Remove(visualName); + Remove(stateVisualsToRemove, visualName); } } } Toolkit::Visual::Base GetVisualByName( const RegisteredVisualContainer& visuals, - const std::string& visualName ) + const std::string& visualName) { Toolkit::Visual::Base visualHandle; RegisteredVisualContainer::Iterator iter; - for ( iter = visuals.Begin(); iter != visuals.End(); iter++ ) + for(iter = visuals.Begin(); iter != visuals.End(); iter++) { Toolkit::Visual::Base visual = (*iter)->visual; - if( visual && visual.GetName() == visualName ) + if(visual && visual.GetName() == visualName) { visualHandle = visual; break; @@ -196,14 +188,14 @@ Toolkit::Visual::Base GetVisualByIndex( /** * Move visual from source to destination container */ -void MoveVisual( RegisteredVisualContainer::Iterator sourceIter, RegisteredVisualContainer& source, RegisteredVisualContainer& destination ) +void MoveVisual(RegisteredVisualContainer::Iterator sourceIter, RegisteredVisualContainer& source, RegisteredVisualContainer& destination) { - Toolkit::Visual::Base visual = (*sourceIter)->visual; - if( visual ) - { - RegisteredVisual* rv = source.Release( sourceIter ); - destination.PushBack( rv ); - } + Toolkit::Visual::Base visual = (*sourceIter)->visual; + if(visual) + { + RegisteredVisual* rv = source.Release(sourceIter); + destination.PushBack(rv); + } } /** @@ -220,54 +212,56 @@ const char* ACTION_ACCESSIBILITY_READING_RESUMED = "ReadingResumed"; const char* ACTION_ACCESSIBILITY_READING_SKIPPED = "ReadingSkipped"; const char* ACTION_ACCESSIBILITY_READING_STOPPED = "ReadingStopped"; -static bool DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes ) +static bool DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes) { bool ret = true; - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - Toolkit::Control control = Toolkit::Control::DownCast( handle ); + Toolkit::Control control = Toolkit::Control::DownCast(handle); - DALI_ASSERT_ALWAYS( control ); + DALI_ASSERT_ALWAYS(control); - if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED ) || - actionName == "activate" ) + if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_ACTIVATED) || + actionName == "activate") { // if cast succeeds there is an implementation so no need to check - if( !DevelControl::AccessibilityActivateSignal( control ).Empty() ) - DevelControl::AccessibilityActivateSignal( control ).Emit(); - else ret = Internal::GetImplementation( control ).OnAccessibilityActivated(); + if(!DevelControl::AccessibilityActivateSignal(control).Empty()) + DevelControl::AccessibilityActivateSignal(control).Emit(); + else + ret = Internal::GetImplementation(control).OnAccessibilityActivated(); } - else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_SKIPPED ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_SKIPPED)) { // if cast succeeds there is an implementation so no need to check - if( !DevelControl::AccessibilityReadingSkippedSignal( control ).Empty() ) - DevelControl::AccessibilityReadingSkippedSignal( control ).Emit(); + if(!DevelControl::AccessibilityReadingSkippedSignal(control).Empty()) + DevelControl::AccessibilityReadingSkippedSignal(control).Emit(); } - else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_PAUSED ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_PAUSED)) { // if cast succeeds there is an implementation so no need to check - if( !DevelControl::AccessibilityReadingPausedSignal( control ).Empty() ) - DevelControl::AccessibilityReadingPausedSignal( control ).Emit(); + if(!DevelControl::AccessibilityReadingPausedSignal(control).Empty()) + DevelControl::AccessibilityReadingPausedSignal(control).Emit(); } - else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_RESUMED ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_RESUMED)) { // if cast succeeds there is an implementation so no need to check - if( !DevelControl::AccessibilityReadingResumedSignal( control ).Empty() ) - DevelControl::AccessibilityReadingResumedSignal( control ).Emit(); + if(!DevelControl::AccessibilityReadingResumedSignal(control).Empty()) + DevelControl::AccessibilityReadingResumedSignal(control).Emit(); } - else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_CANCELLED ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_CANCELLED)) { // if cast succeeds there is an implementation so no need to check - if( !DevelControl::AccessibilityReadingCancelledSignal( control ).Empty() ) - DevelControl::AccessibilityReadingCancelledSignal( control ).Emit(); + if(!DevelControl::AccessibilityReadingCancelledSignal(control).Empty()) + DevelControl::AccessibilityReadingCancelledSignal(control).Emit(); } - else if( 0 == strcmp( actionName.c_str(), ACTION_ACCESSIBILITY_READING_STOPPED ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_ACCESSIBILITY_READING_STOPPED)) { // if cast succeeds there is an implementation so no need to check - if(!DevelControl::AccessibilityReadingStoppedSignal( control ).Empty()) - DevelControl::AccessibilityReadingStoppedSignal( control ).Emit(); - } else + if(!DevelControl::AccessibilityReadingStoppedSignal(control).Empty()) + DevelControl::AccessibilityReadingStoppedSignal(control).Emit(); + } + else { ret = false; } @@ -283,72 +277,71 @@ static bool DoAction( BaseObject* object, const std::string& actionName, const P * @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. */ -const char* SIGNAL_KEY_EVENT = "keyEvent"; +const char* SIGNAL_KEY_EVENT = "keyEvent"; const char* SIGNAL_KEY_INPUT_FOCUS_GAINED = "keyInputFocusGained"; -const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost"; -const char* SIGNAL_TAPPED = "tapped"; -const char* SIGNAL_PANNED = "panned"; -const char* SIGNAL_PINCHED = "pinched"; -const char* SIGNAL_LONG_PRESSED = "longPressed"; -const char* SIGNAL_GET_NAME = "getName"; -const char* SIGNAL_GET_DESCRIPTION = "getDescription"; -const char* SIGNAL_DO_GESTURE = "doGesture"; -static bool DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) -{ - Dali::BaseHandle handle( object ); - - bool connected( false ); - Toolkit::Control control = Toolkit::Control::DownCast( handle ); - if ( control ) - { - Internal::Control& controlImpl( Internal::GetImplementation( control ) ); +const char* SIGNAL_KEY_INPUT_FOCUS_LOST = "keyInputFocusLost"; +const char* SIGNAL_TAPPED = "tapped"; +const char* SIGNAL_PANNED = "panned"; +const char* SIGNAL_PINCHED = "pinched"; +const char* SIGNAL_LONG_PRESSED = "longPressed"; +const char* SIGNAL_GET_NAME = "getName"; +const char* SIGNAL_GET_DESCRIPTION = "getDescription"; +const char* SIGNAL_DO_GESTURE = "doGesture"; +static bool DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) +{ + Dali::BaseHandle handle(object); + + bool connected(false); + Toolkit::Control control = Toolkit::Control::DownCast(handle); + if(control) + { + Internal::Control& controlImpl(Internal::GetImplementation(control)); connected = true; - if ( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_EVENT ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_EVENT)) { - controlImpl.KeyEventSignal().Connect( tracker, functor ); + controlImpl.KeyEventSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_GAINED)) { - controlImpl.KeyInputFocusGainedSignal().Connect( tracker, functor ); + controlImpl.KeyInputFocusGainedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_LOST)) { - controlImpl.KeyInputFocusLostSignal().Connect( tracker, functor ); + controlImpl.KeyInputFocusLostSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_TAPPED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_TAPPED)) { - controlImpl.EnableGestureDetection( GestureType::TAP ); - controlImpl.GetTapGestureDetector().DetectedSignal().Connect( tracker, functor ); + controlImpl.EnableGestureDetection(GestureType::TAP); + controlImpl.GetTapGestureDetector().DetectedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_PANNED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_PANNED)) { - controlImpl.EnableGestureDetection( GestureType::PAN ); - controlImpl.GetPanGestureDetector().DetectedSignal().Connect( tracker, functor ); + controlImpl.EnableGestureDetection(GestureType::PAN); + controlImpl.GetPanGestureDetector().DetectedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_PINCHED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_PINCHED)) { - controlImpl.EnableGestureDetection( GestureType::PINCH ); - controlImpl.GetPinchGestureDetector().DetectedSignal().Connect( tracker, functor ); + controlImpl.EnableGestureDetection(GestureType::PINCH); + controlImpl.GetPinchGestureDetector().DetectedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_LONG_PRESSED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_LONG_PRESSED)) { - controlImpl.EnableGestureDetection( GestureType::LONG_PRESS ); - controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect( tracker, functor ); + controlImpl.EnableGestureDetection(GestureType::LONG_PRESS); + controlImpl.GetLongPressGestureDetector().DetectedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_GET_NAME ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_GET_NAME)) { - DevelControl::AccessibilityGetNameSignal( control ).Connect( tracker, functor ); + DevelControl::AccessibilityGetNameSignal(control).Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_GET_DESCRIPTION ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_GET_DESCRIPTION)) { - DevelControl::AccessibilityGetDescriptionSignal( control ).Connect( tracker, functor ); + DevelControl::AccessibilityGetDescriptionSignal(control).Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_DO_GESTURE ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_DO_GESTURE)) { - DevelControl::AccessibilityDoGestureSignal( control ).Connect( tracker, functor ); + DevelControl::AccessibilityDoGestureSignal(control).Connect(tracker, functor); } - } return connected; } @@ -361,28 +354,28 @@ BaseHandle Create() return Internal::Control::New(); } // Setup signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Control, CustomActor, Create ); +DALI_TYPE_REGISTRATION_BEGIN(Control, CustomActor, Create); // Note: Properties are registered separately below. -SignalConnectorType registerSignal1( typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal ); -SignalConnectorType registerSignal2( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal ); -SignalConnectorType registerSignal3( typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal ); -SignalConnectorType registerSignal4( typeRegistration, SIGNAL_TAPPED, &DoConnectSignal ); -SignalConnectorType registerSignal5( typeRegistration, SIGNAL_PANNED, &DoConnectSignal ); -SignalConnectorType registerSignal6( typeRegistration, SIGNAL_PINCHED, &DoConnectSignal ); -SignalConnectorType registerSignal7( typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal ); -SignalConnectorType registerSignal8( typeRegistration, SIGNAL_GET_NAME, &DoConnectSignal ); -SignalConnectorType registerSignal9( typeRegistration, SIGNAL_GET_DESCRIPTION, &DoConnectSignal ); -SignalConnectorType registerSignal10( typeRegistration, SIGNAL_DO_GESTURE, &DoConnectSignal ); - -TypeAction registerAction1( typeRegistration, "activate", &DoAction ); -TypeAction registerAction2( typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction ); -TypeAction registerAction3( typeRegistration, ACTION_ACCESSIBILITY_READING_SKIPPED, &DoAction ); -TypeAction registerAction4( typeRegistration, ACTION_ACCESSIBILITY_READING_CANCELLED, &DoAction ); -TypeAction registerAction5( typeRegistration, ACTION_ACCESSIBILITY_READING_STOPPED, &DoAction ); -TypeAction registerAction6( typeRegistration, ACTION_ACCESSIBILITY_READING_PAUSED, &DoAction ); -TypeAction registerAction7( typeRegistration, ACTION_ACCESSIBILITY_READING_RESUMED, &DoAction ); +SignalConnectorType registerSignal1(typeRegistration, SIGNAL_KEY_EVENT, &DoConnectSignal); +SignalConnectorType registerSignal2(typeRegistration, SIGNAL_KEY_INPUT_FOCUS_GAINED, &DoConnectSignal); +SignalConnectorType registerSignal3(typeRegistration, SIGNAL_KEY_INPUT_FOCUS_LOST, &DoConnectSignal); +SignalConnectorType registerSignal4(typeRegistration, SIGNAL_TAPPED, &DoConnectSignal); +SignalConnectorType registerSignal5(typeRegistration, SIGNAL_PANNED, &DoConnectSignal); +SignalConnectorType registerSignal6(typeRegistration, SIGNAL_PINCHED, &DoConnectSignal); +SignalConnectorType registerSignal7(typeRegistration, SIGNAL_LONG_PRESSED, &DoConnectSignal); +SignalConnectorType registerSignal8(typeRegistration, SIGNAL_GET_NAME, &DoConnectSignal); +SignalConnectorType registerSignal9(typeRegistration, SIGNAL_GET_DESCRIPTION, &DoConnectSignal); +SignalConnectorType registerSignal10(typeRegistration, SIGNAL_DO_GESTURE, &DoConnectSignal); + +TypeAction registerAction1(typeRegistration, "activate", &DoAction); +TypeAction registerAction2(typeRegistration, ACTION_ACCESSIBILITY_ACTIVATED, &DoAction); +TypeAction registerAction3(typeRegistration, ACTION_ACCESSIBILITY_READING_SKIPPED, &DoAction); +TypeAction registerAction4(typeRegistration, ACTION_ACCESSIBILITY_READING_CANCELLED, &DoAction); +TypeAction registerAction5(typeRegistration, ACTION_ACCESSIBILITY_READING_STOPPED, &DoAction); +TypeAction registerAction6(typeRegistration, ACTION_ACCESSIBILITY_READING_PAUSED, &DoAction); +TypeAction registerAction7(typeRegistration, ACTION_ACCESSIBILITY_READING_RESUMED, &DoAction); DALI_TYPE_REGISTRATION_END() @@ -392,56 +385,57 @@ DALI_TYPE_REGISTRATION_END() * @param[in] container Container of visuals * @param[in] parent Parent actor to remove visuals from */ -void SetVisualsOffScene( const RegisteredVisualContainer& container, Actor parent ) +void SetVisualsOffScene(const RegisteredVisualContainer& container, Actor parent) { - for( auto iter = container.Begin(), end = container.End() ; iter!= end; iter++) + for(auto iter = container.Begin(), end = container.End(); iter != end; iter++) { - if( (*iter)->visual ) + if((*iter)->visual) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::SetOffScene Setting visual(%d) off stage\n", (*iter)->index ); - Toolkit::GetImplementation((*iter)->visual).SetOffScene( parent ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::SetOffScene Setting visual(%d) off stage\n", (*iter)->index); + Toolkit::GetImplementation((*iter)->visual).SetOffScene(parent); } } } } // unnamed namespace - +// clang-format off // Properties registered without macro to use specific member variables. -const PropertyRegistration Control::Impl::PROPERTY_1( typeRegistration, "styleName", Toolkit::Control::Property::STYLE_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_4( typeRegistration, "keyInputFocus", Toolkit::Control::Property::KEY_INPUT_FOCUS, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_5( typeRegistration, "background", Toolkit::Control::Property::BACKGROUND, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_6( typeRegistration, "margin", Toolkit::Control::Property::MARGIN, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_7( typeRegistration, "padding", Toolkit::Control::Property::PADDING, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_8( typeRegistration, "tooltip", Toolkit::DevelControl::Property::TOOLTIP, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_9( typeRegistration, "state", Toolkit::DevelControl::Property::STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_10( typeRegistration, "subState", Toolkit::DevelControl::Property::SUB_STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_11( typeRegistration, "leftFocusableActorId", Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_12( typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID,Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_13( typeRegistration, "upFocusableActorId", Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_14( typeRegistration, "downFocusableActorId", Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_15( typeRegistration, "shadow", Toolkit::DevelControl::Property::SHADOW, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_16( typeRegistration, "accessibilityAttributes", Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_17( typeRegistration, "accessibilityName", Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_18( typeRegistration, "accessibilityDescription", Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_19( typeRegistration, "accessibilityTranslationDomain", Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_20( typeRegistration, "accessibilityRole", Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_21( typeRegistration, "accessibilityHighlightable", Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); -const PropertyRegistration Control::Impl::PROPERTY_22( typeRegistration, "accessibilityAnimated", Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty ); - -Control::Impl::Impl( Control& controlImpl ) -: mControlImpl( controlImpl ), - mState( Toolkit::DevelControl::NORMAL ), +const PropertyRegistration Control::Impl::PROPERTY_1(typeRegistration, "styleName", Toolkit::Control::Property::STYLE_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_4(typeRegistration, "keyInputFocus", Toolkit::Control::Property::KEY_INPUT_FOCUS, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_5(typeRegistration, "background", Toolkit::Control::Property::BACKGROUND, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_6(typeRegistration, "margin", Toolkit::Control::Property::MARGIN, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_7(typeRegistration, "padding", Toolkit::Control::Property::PADDING, Property::EXTENTS, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_8(typeRegistration, "tooltip", Toolkit::DevelControl::Property::TOOLTIP, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_9(typeRegistration, "state", Toolkit::DevelControl::Property::STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_10(typeRegistration, "subState", Toolkit::DevelControl::Property::SUB_STATE, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_11(typeRegistration, "leftFocusableActorId", Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_12(typeRegistration, "rightFocusableActorId", Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_13(typeRegistration, "upFocusableActorId", Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_14(typeRegistration, "downFocusableActorId", Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_15(typeRegistration, "shadow", Toolkit::DevelControl::Property::SHADOW, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_16(typeRegistration, "accessibilityAttributes", Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES, Property::MAP, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_17(typeRegistration, "accessibilityName", Toolkit::DevelControl::Property::ACCESSIBILITY_NAME, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_18(typeRegistration, "accessibilityDescription", Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_19(typeRegistration, "accessibilityTranslationDomain", Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN, Property::STRING, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_20(typeRegistration, "accessibilityRole", Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE, Property::INTEGER, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_21(typeRegistration, "accessibilityHighlightable", Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +const PropertyRegistration Control::Impl::PROPERTY_22(typeRegistration, "accessibilityAnimated", Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, Property::BOOLEAN, &Control::Impl::SetProperty, &Control::Impl::GetProperty); +// clang-format on + +Control::Impl::Impl(Control& controlImpl) +: mControlImpl(controlImpl), + mState(Toolkit::DevelControl::NORMAL), mSubStateName(""), - mLeftFocusableActorId( -1 ), - mRightFocusableActorId( -1 ), - mUpFocusableActorId( -1 ), - mDownFocusableActorId( -1 ), + mLeftFocusableActorId(-1), + mRightFocusableActorId(-1), + mUpFocusableActorId(-1), + mDownFocusableActorId(-1), mStyleName(""), mBackgroundColor(Color::TRANSPARENT), mStartingPinchScale(nullptr), - mMargin( 0, 0, 0, 0 ), - mPadding( 0, 0, 0, 0 ), + mMargin(0, 0, 0, 0), + mPadding(0, 0, 0, 0), mKeyEventSignal(), mKeyInputFocusGainedSignal(), mKeyInputFocusLostSignal(), @@ -454,28 +448,28 @@ Control::Impl::Impl( Control& controlImpl ) mPanGestureDetector(), mTapGestureDetector(), mLongPressGestureDetector(), - mTooltip( NULL ), + mTooltip(NULL), mInputMethodContext(), mIdleCallback(nullptr), - mFlags( Control::ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mIsKeyboardNavigationSupported( false ), - mIsKeyboardFocusGroup( false ), + mFlags(Control::ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mIsKeyboardNavigationSupported(false), + mIsKeyboardFocusGroup(false), mIsEmittingResourceReadySignal(false), mNeedToEmitResourceReady(false) { Dali::Accessibility::Accessible::RegisterControlAccessibilityGetter( - []( Dali::Actor actor ) -> Dali::Accessibility::Accessible* { - return Control::Impl::GetAccessibilityObject( actor ); - } ); + [](Dali::Actor actor) -> Dali::Accessibility::Accessible* { + return Control::Impl::GetAccessibilityObject(actor); + }); - accessibilityConstructor = []( Dali::Actor actor ) -> std::unique_ptr< Dali::Accessibility::Accessible > { - return std::unique_ptr< Dali::Accessibility::Accessible >( new AccessibleImpl( actor, - Dali::Accessibility::Role::UNKNOWN ) ); - }; + accessibilityConstructor = [](Dali::Actor actor) -> std::unique_ptr { + return std::unique_ptr(new AccessibleImpl(actor, + Dali::Accessibility::Role::UNKNOWN)); + }; size_t len = static_cast(Dali::Accessibility::RelationType::MAX_COUNT); mAccessibilityRelations.reserve(len); - for (auto i = 0u; i < len; ++i) + for(auto i = 0u; i < len; ++i) { mAccessibilityRelations.push_back({}); } @@ -483,14 +477,14 @@ Control::Impl::Impl( Control& controlImpl ) Control::Impl::~Impl() { - for( auto&& iter : mVisuals ) + for(auto&& iter : mVisuals) { - StopObservingVisual( iter->visual ); + StopObservingVisual(iter->visual); } - for( auto&& iter : mRemoveVisuals ) + for(auto&& iter : mRemoveVisuals) { - StopObservingVisual( iter->visual ); + StopObservingVisual(iter->visual); } AccessibilityDeregister(); @@ -504,12 +498,12 @@ Control::Impl::~Impl() } } -Control::Impl& Control::Impl::Get( Internal::Control& internalControl ) +Control::Impl& Control::Impl::Get(Internal::Control& internalControl) { return *internalControl.mImpl; } -const Control::Impl& Control::Impl::Get( const Internal::Control& internalControl ) +const Control::Impl& Control::Impl::Get(const Internal::Control& internalControl) { return *internalControl.mImpl; } @@ -535,86 +529,86 @@ void Control::Impl::LongPressDetected(Actor actor, const LongPressGesture& longP mControlImpl.OnLongPress(longPress); } -void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual ) +void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual) { - RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET ); + RegisterVisual(index, visual, VisualState::ENABLED, DepthIndexValue::NOT_SET); } -void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, int depthIndex ) +void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, int depthIndex) { - RegisterVisual( index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex ); + RegisterVisual(index, visual, VisualState::ENABLED, DepthIndexValue::SET, depthIndex); } -void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled ) +void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, bool enabled) { - RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::NOT_SET ); + RegisterVisual(index, visual, (enabled ? VisualState::ENABLED : VisualState::DISABLED), DepthIndexValue::NOT_SET); } -void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex ) +void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, bool enabled, int depthIndex) { - RegisterVisual( index, visual, ( enabled ? VisualState::ENABLED : VisualState::DISABLED ), DepthIndexValue::SET, depthIndex ); + RegisterVisual(index, visual, (enabled ? VisualState::ENABLED : VisualState::DISABLED), DepthIndexValue::SET, depthIndex); } -void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex ) +void Control::Impl::RegisterVisual(Property::Index index, Toolkit::Visual::Base& visual, VisualState::Type enabled, DepthIndexValue::Type depthIndexValueSet, int depthIndex) { - DALI_LOG_INFO( gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index ); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "RegisterVisual:%d \n", index); - bool visualReplaced ( false ); + bool visualReplaced(false); Actor self = mControlImpl.Self(); // Set the depth index, if not set by caller this will be either the current visual depth, max depth of all visuals // or zero. int requiredDepthIndex = visual.GetDepthIndex(); - if( depthIndexValueSet == DepthIndexValue::SET ) + if(depthIndexValueSet == DepthIndexValue::SET) { requiredDepthIndex = depthIndex; } // Visual replacement, existing visual should only be removed from stage when replacement ready. - if( !mVisuals.Empty() ) + if(!mVisuals.Empty()) { RegisteredVisualContainer::Iterator registeredVisualsiter; // Check if visual (index) is already registered, this is the current visual. - if( FindVisual( index, mVisuals, registeredVisualsiter ) ) + if(FindVisual(index, mVisuals, registeredVisualsiter)) { Toolkit::Visual::Base& currentRegisteredVisual = (*registeredVisualsiter)->visual; - if( currentRegisteredVisual ) + if(currentRegisteredVisual) { // Store current visual depth index as may need to set the replacement visual to same depth const int currentDepthIndex = (*registeredVisualsiter)->visual.GetDepthIndex(); // No longer required to know if the replaced visual's resources are ready - StopObservingVisual( currentRegisteredVisual ); + StopObservingVisual(currentRegisteredVisual); // If control staged and visual enabled then visuals will be swapped once ready - if( self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && enabled ) + if(self.GetProperty(Actor::Property::CONNECTED_TO_SCENE) && enabled) { // Check if visual is currently in the process of being replaced ( is in removal container ) RegisteredVisualContainer::Iterator visualQueuedForRemoval; - if ( FindVisual( index, mRemoveVisuals, visualQueuedForRemoval ) ) + if(FindVisual(index, mRemoveVisuals, visualQueuedForRemoval)) { // Visual with same index is already in removal container so current visual pending // Only the the last requested visual will be displayed so remove current visual which is staged but not ready. - Toolkit::GetImplementation( currentRegisteredVisual ).SetOffScene( self ); - mVisuals.Erase( registeredVisualsiter ); + Toolkit::GetImplementation(currentRegisteredVisual).SetOffScene(self); + mVisuals.Erase(registeredVisualsiter); } else { // current visual not already in removal container so add now. - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index ); - MoveVisual( registeredVisualsiter, mVisuals, mRemoveVisuals ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "RegisterVisual Move current registered visual to removal Queue: %d \n", index); + MoveVisual(registeredVisualsiter, mVisuals, mRemoveVisuals); } } else { // Control not staged or visual disabled so can just erase from registered visuals and new visual will be added later. - mVisuals.Erase( registeredVisualsiter ); + mVisuals.Erase(registeredVisualsiter); } // If we've not set the depth-index value and the new visual does not have a depth index applied to it, then use the previously set depth-index for this index - if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) && - ( visual.GetDepthIndex() == 0 ) ) + if((depthIndexValueSet == DepthIndexValue::NOT_SET) && + (visual.GetDepthIndex() == 0)) { requiredDepthIndex = currentDepthIndex; } @@ -626,100 +620,96 @@ void Control::Impl::RegisterVisual( Property::Index index, Toolkit::Visual::Base // If not set, set the name of the visual to the same name as the control's property. // ( If the control has been type registered ) - if( visual.GetName().empty() ) + if(visual.GetName().empty()) { // returns empty string if index is not found as long as index is not -1 - std::string visualName = self.GetPropertyName( index ); - if( !visualName.empty() ) + std::string visualName = self.GetPropertyName(index); + if(!visualName.empty()) { - DALI_LOG_INFO( gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n", - index, visualName.c_str() ); - visual.SetName( visualName ); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "Setting visual name for property %d to %s\n", index, visualName.c_str()); + visual.SetName(visualName); } } - if( !visualReplaced ) // New registration entry + if(!visualReplaced) // New registration entry { // If we've not set the depth-index value, we have more than one visual and the visual does not have a depth index, then set it to be the highest - if( ( depthIndexValueSet == DepthIndexValue::NOT_SET ) && - ( mVisuals.Size() > 0 ) && - ( visual.GetDepthIndex() == 0 ) ) + if((depthIndexValueSet == DepthIndexValue::NOT_SET) && + (mVisuals.Size() > 0) && + (visual.GetDepthIndex() == 0)) { - int maxDepthIndex = std::numeric_limits< int >::min(); + int maxDepthIndex = std::numeric_limits::min(); - RegisteredVisualContainer::ConstIterator iter; + RegisteredVisualContainer::ConstIterator iter; const RegisteredVisualContainer::ConstIterator endIter = mVisuals.End(); - for ( iter = mVisuals.Begin(); iter != endIter; iter++ ) + for(iter = mVisuals.Begin(); iter != endIter; iter++) { const int visualDepthIndex = (*iter)->visual.GetDepthIndex(); - if ( visualDepthIndex > maxDepthIndex ) + if(visualDepthIndex > maxDepthIndex) { maxDepthIndex = visualDepthIndex; } } - ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top - requiredDepthIndex = std::max( 0, maxDepthIndex ); // Start at zero if maxDepth index belongs to a background + ++maxDepthIndex; // Add one to the current maximum depth index so that our added visual appears on top + requiredDepthIndex = std::max(0, maxDepthIndex); // Start at zero if maxDepth index belongs to a background } } - if( visual ) + if(visual) { // Set determined depth index - visual.SetDepthIndex( requiredDepthIndex ); + visual.SetDepthIndex(requiredDepthIndex); // Monitor when the visual resources are ready - StartObservingVisual( visual ); + StartObservingVisual(visual); - DALI_LOG_INFO( gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex ); - RegisteredVisual* newRegisteredVisual = new RegisteredVisual( index, visual, - ( enabled == VisualState::ENABLED ? true : false ), - ( visualReplaced && enabled ) ) ; - mVisuals.PushBack( newRegisteredVisual ); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "New Visual registration index[%d] depth[%d]\n", index, requiredDepthIndex); + RegisteredVisual* newRegisteredVisual = new RegisteredVisual(index, visual, (enabled == VisualState::ENABLED ? true : false), (visualReplaced && enabled)); + mVisuals.PushBack(newRegisteredVisual); - Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); + Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); // Put on stage if enabled and the control is already on the stage - if( ( enabled == VisualState::ENABLED ) && self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if((enabled == VisualState::ENABLED) && self.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { - visualImpl.SetOnScene( self ); + visualImpl.SetOnScene(self); } - else if( visualImpl.IsResourceReady() ) // When not being staged, check if visual already 'ResourceReady' before it was Registered. ( Resource may have been loaded already ) + else if(visualImpl.IsResourceReady()) // When not being staged, check if visual already 'ResourceReady' before it was Registered. ( Resource may have been loaded already ) { - ResourceReady( visualImpl ); + ResourceReady(visualImpl); } - } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n", visual.GetName().c_str(), index, enabled?"true":"false" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::RegisterVisual() Registered %s(%d), enabled:%s\n", visual.GetName().c_str(), index, enabled ? "true" : "false"); } -void Control::Impl::UnregisterVisual( Property::Index index ) +void Control::Impl::UnregisterVisual(Property::Index index) { RegisteredVisualContainer::Iterator iter; - if ( FindVisual( index, mVisuals, iter ) ) + if(FindVisual(index, mVisuals, iter)) { // stop observing visual - StopObservingVisual( (*iter)->visual ); + StopObservingVisual((*iter)->visual); - Actor self( mControlImpl.Self() ); - Toolkit::GetImplementation((*iter)->visual).SetOffScene( self ); + Actor self(mControlImpl.Self()); + Toolkit::GetImplementation((*iter)->visual).SetOffScene(self); (*iter)->visual.Reset(); - mVisuals.Erase( iter ); + mVisuals.Erase(iter); } - if( FindVisual( index, mRemoveVisuals, iter ) ) + if(FindVisual(index, mRemoveVisuals, iter)) { - Actor self( mControlImpl.Self() ); - Toolkit::GetImplementation( (*iter)->visual ).SetOffScene( self ); + Actor self(mControlImpl.Self()); + Toolkit::GetImplementation((*iter)->visual).SetOffScene(self); (*iter)->pending = false; (*iter)->visual.Reset(); - mRemoveVisuals.Erase( iter ); + mRemoveVisuals.Erase(iter); } } -Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const +Toolkit::Visual::Base Control::Impl::GetVisual(Property::Index index) const { RegisteredVisualContainer::Iterator iter; - if ( FindVisual( index, mVisuals, iter ) ) + if(FindVisual(index, mVisuals, iter)) { return (*iter)->visual; } @@ -727,104 +717,104 @@ Toolkit::Visual::Base Control::Impl::GetVisual( Property::Index index ) const return Toolkit::Visual::Base(); } -void Control::Impl::EnableVisual( Property::Index index, bool enable ) +void Control::Impl::EnableVisual(Property::Index index, bool enable) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Control::EnableVisual(%d, %s)\n", index, enable?"T":"F"); + DALI_LOG_INFO(gLogFilter, Debug::General, "Control::EnableVisual(%d, %s)\n", index, enable ? "T" : "F"); RegisteredVisualContainer::Iterator iter; - if ( FindVisual( index, mVisuals, iter ) ) + if(FindVisual(index, mVisuals, iter)) { - if ( (*iter)->enabled == enable ) + if((*iter)->enabled == enable) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable?"enabled":"disabled"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::EnableVisual Visual %s(%d) already %s\n", (*iter)->visual.GetName().c_str(), index, enable ? "enabled" : "disabled"); return; } - (*iter)->enabled = enable; + (*iter)->enabled = enable; Actor parentActor = mControlImpl.Self(); - if ( mControlImpl.Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) // If control not on Scene then Visual will be added when SceneConnection is called. + if(mControlImpl.Self().GetProperty(Actor::Property::CONNECTED_TO_SCENE)) // If control not on Scene then Visual will be added when SceneConnection is called. { - if ( enable ) + if(enable) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index ); - Toolkit::GetImplementation((*iter)->visual).SetOnScene( parentActor ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) on stage \n", (*iter)->visual.GetName().c_str(), index); + Toolkit::GetImplementation((*iter)->visual).SetOnScene(parentActor); } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index ); - Toolkit::GetImplementation((*iter)->visual).SetOffScene( parentActor ); // No need to call if control not staged. + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::EnableVisual Setting %s(%d) off stage \n", (*iter)->visual.GetName().c_str(), index); + Toolkit::GetImplementation((*iter)->visual).SetOffScene(parentActor); // No need to call if control not staged. } } } else { - DALI_LOG_WARNING( "Control::EnableVisual(%d, %s) FAILED - NO SUCH VISUAL\n", index, enable?"T":"F" ); + DALI_LOG_WARNING("Control::EnableVisual(%d, %s) FAILED - NO SUCH VISUAL\n", index, enable ? "T" : "F"); } } -bool Control::Impl::IsVisualEnabled( Property::Index index ) const +bool Control::Impl::IsVisualEnabled(Property::Index index) const { RegisteredVisualContainer::Iterator iter; - if ( FindVisual( index, mVisuals, iter ) ) + if(FindVisual(index, mVisuals, iter)) { return (*iter)->enabled; } return false; } -void Control::Impl::StopObservingVisual( Toolkit::Visual::Base& visual ) +void Control::Impl::StopObservingVisual(Toolkit::Visual::Base& visual) { - Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); + Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); // Stop observing the visual - visualImpl.RemoveEventObserver( *this ); + visualImpl.RemoveEventObserver(*this); } -void Control::Impl::StartObservingVisual( Toolkit::Visual::Base& visual) +void Control::Impl::StartObservingVisual(Toolkit::Visual::Base& visual) { - Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); + Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); // start observing the visual for events - visualImpl.AddEventObserver( *this ); + visualImpl.AddEventObserver(*this); } // Called by a Visual when it's resource is ready -void Control::Impl::ResourceReady( Visual::Base& object) +void Control::Impl::ResourceReady(Visual::Base& object) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Control::Impl::ResourceReady() replacements pending[%d]\n", mRemoveVisuals.Count() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Control::Impl::ResourceReady() replacements pending[%d]\n", mRemoveVisuals.Count()); Actor self = mControlImpl.Self(); // A resource is ready, find resource in the registered visuals container and get its index - for( auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter ) + for(auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter) { - Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual ); + Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation((*registeredIter)->visual); - if( &object == ®isteredVisualImpl ) + if(&object == ®isteredVisualImpl) { RegisteredVisualContainer::Iterator visualToRemoveIter; // Find visual with the same index in the removal container // Set if off stage as it's replacement is now ready. // Remove if from removal list as now removed from stage. // Set Pending flag on the ready visual to false as now ready. - if( FindVisual( (*registeredIter)->index, mRemoveVisuals, visualToRemoveIter ) ) + if(FindVisual((*registeredIter)->index, mRemoveVisuals, visualToRemoveIter)) { (*registeredIter)->pending = false; - Toolkit::GetImplementation( (*visualToRemoveIter)->visual ).SetOffScene( self ); - mRemoveVisuals.Erase( visualToRemoveIter ); + Toolkit::GetImplementation((*visualToRemoveIter)->visual).SetOffScene(self); + mRemoveVisuals.Erase(visualToRemoveIter); } break; } } // A visual is ready so control may need relayouting if staged - if ( self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(self.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { mControlImpl.RelayoutRequest(); } // Emit signal if all enabled visuals registered by the control are ready. - if( IsResourceReady() ) + if(IsResourceReady()) { // Reset the flag mNeedToEmitResourceReady = false; @@ -833,15 +823,15 @@ void Control::Impl::ResourceReady( Visual::Base& object) } } -void Control::Impl::NotifyVisualEvent( Visual::Base& object, Property::Index signalId ) +void Control::Impl::NotifyVisualEvent(Visual::Base& object, Property::Index signalId) { - for( auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter ) + for(auto registeredIter = mVisuals.Begin(), end = mVisuals.End(); registeredIter != end; ++registeredIter) { - Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation( (*registeredIter)->visual ); - if( &object == ®isteredVisualImpl ) + Internal::Visual::Base& registeredVisualImpl = Toolkit::GetImplementation((*registeredIter)->visual); + if(&object == ®isteredVisualImpl) { - Dali::Toolkit::Control handle( mControlImpl.GetOwner() ); - mVisualEventSignal.Emit( handle, (*registeredIter)->index, signalId ); + Dali::Toolkit::Control handle(mControlImpl.GetOwner()); + mVisualEventSignal.Emit(handle, (*registeredIter)->index, signalId); break; } } @@ -850,14 +840,15 @@ void Control::Impl::NotifyVisualEvent( Visual::Base& object, Property::Index sig bool Control::Impl::IsResourceReady() const { // Iterate through and check all the enabled visuals are ready - for( auto visualIter = mVisuals.Begin(); - visualIter != mVisuals.End(); ++visualIter ) + for(auto visualIter = mVisuals.Begin(); + visualIter != mVisuals.End(); + ++visualIter) { - const Toolkit::Visual::Base visual = (*visualIter)->visual; - const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); + const Toolkit::Visual::Base visual = (*visualIter)->visual; + const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); // one of the enabled visuals is not ready - if( !visualImpl.IsResourceReady() && (*visualIter)->enabled ) + if(!visualImpl.IsResourceReady() && (*visualIter)->enabled) { return false; } @@ -865,85 +856,83 @@ bool Control::Impl::IsResourceReady() const return true; } -Toolkit::Visual::ResourceStatus Control::Impl::GetVisualResourceStatus( Property::Index index ) const +Toolkit::Visual::ResourceStatus Control::Impl::GetVisualResourceStatus(Property::Index index) const { RegisteredVisualContainer::Iterator iter; - if ( FindVisual( index, mVisuals, iter ) ) + if(FindVisual(index, mVisuals, iter)) { - const Toolkit::Visual::Base visual = (*iter)->visual; - const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); - return visualImpl.GetResourceStatus( ); + const Toolkit::Visual::Base visual = (*iter)->visual; + const Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); + return visualImpl.GetResourceStatus(); } return Toolkit::Visual::ResourceStatus::PREPARING; } - - -void Control::Impl::AddTransitions( Dali::Animation& animation, - const Toolkit::TransitionData& handle, - bool createAnimation ) +void Control::Impl::AddTransitions(Dali::Animation& animation, + const Toolkit::TransitionData& handle, + bool createAnimation) { // Setup a Transition from TransitionData. - const Internal::TransitionData& transitionData = Toolkit::GetImplementation( handle ); - TransitionData::Iterator end = transitionData.End(); - for( TransitionData::Iterator iter = transitionData.Begin() ; - iter != end; ++iter ) + const Internal::TransitionData& transitionData = Toolkit::GetImplementation(handle); + TransitionData::Iterator end = transitionData.End(); + for(TransitionData::Iterator iter = transitionData.Begin(); + iter != end; + ++iter) { TransitionData::Animator* animator = (*iter); - Toolkit::Visual::Base visual = GetVisualByName( mVisuals, animator->objectName ); + Toolkit::Visual::Base visual = GetVisualByName(mVisuals, animator->objectName); - if( visual ) + if(visual) { #if defined(DEBUG_ENABLED) - Dali::TypeInfo typeInfo; + Dali::TypeInfo typeInfo; ControlWrapper* controlWrapperImpl = dynamic_cast(&mControlImpl); - if( controlWrapperImpl ) + if(controlWrapperImpl) { typeInfo = controlWrapperImpl->GetTypeInfo(); } - DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n", - visual.GetName().c_str(), typeInfo?typeInfo.GetName().c_str():"Unknown" ); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "CreateTransition: Found %s visual for %s\n", visual.GetName().c_str(), typeInfo ? typeInfo.GetName().c_str() : "Unknown"); #endif - Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); - visualImpl.AnimateProperty( animation, *animator ); + Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); + visualImpl.AnimateProperty(animation, *animator); } else { - DALI_LOG_INFO( gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors"); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "CreateTransition: Could not find visual. Trying actors"); // Otherwise, try any actor children of control (Including the control) - Actor child = mControlImpl.Self().FindChildByName( animator->objectName ); - if( child ) + Actor child = mControlImpl.Self().FindChildByName(animator->objectName); + if(child) { - Property::Index propertyIndex = child.GetPropertyIndex( animator->propertyKey ); - if( propertyIndex != Property::INVALID_INDEX ) + Property::Index propertyIndex = child.GetPropertyIndex(animator->propertyKey); + if(propertyIndex != Property::INVALID_INDEX) { - if( animator->animate == false ) + if(animator->animate == false) { - if( animator->targetValue.GetType() != Property::NONE ) + if(animator->targetValue.GetType() != Property::NONE) { - child.SetProperty( propertyIndex, animator->targetValue ); + child.SetProperty(propertyIndex, animator->targetValue); } } else // animate the property { - if( animator->initialValue.GetType() != Property::NONE ) + if(animator->initialValue.GetType() != Property::NONE) { - child.SetProperty( propertyIndex, animator->initialValue ); + child.SetProperty(propertyIndex, animator->initialValue); } - if( createAnimation && !animation ) + if(createAnimation && !animation) { - animation = Dali::Animation::New( 0.1f ); + animation = Dali::Animation::New(0.1f); } - animation.AnimateTo( Property( child, propertyIndex ), - animator->targetValue, - animator->alphaFunction, - TimePeriod( animator->timePeriodDelay, - animator->timePeriodDuration ) ); + animation.AnimateTo(Property(child, propertyIndex), + animator->targetValue, + animator->alphaFunction, + TimePeriod(animator->timePeriodDelay, + animator->timePeriodDuration)); } } } @@ -951,67 +940,65 @@ void Control::Impl::AddTransitions( Dali::Animation& animation, } } -Dali::Animation Control::Impl::CreateTransition( const Toolkit::TransitionData& transitionData ) +Dali::Animation Control::Impl::CreateTransition(const Toolkit::TransitionData& transitionData) { Dali::Animation transition; - if( transitionData.Count() > 0 ) + if(transitionData.Count() > 0) { - AddTransitions( transition, transitionData, true ); + AddTransitions(transition, transitionData, true); } return transition; } - - -void Control::Impl::DoAction( Dali::Property::Index visualIndex, Dali::Property::Index actionId, const Dali::Property::Value attributes ) +void Control::Impl::DoAction(Dali::Property::Index visualIndex, Dali::Property::Index actionId, const Dali::Property::Value attributes) { RegisteredVisualContainer::Iterator iter; - if ( FindVisual( visualIndex, mVisuals, iter ) ) + if(FindVisual(visualIndex, mVisuals, iter)) { - Toolkit::GetImplementation((*iter)->visual).DoAction( actionId, attributes ); + Toolkit::GetImplementation((*iter)->visual).DoAction(actionId, attributes); } } -void Control::Impl::AppendAccessibilityAttribute( const std::string& key, - const std::string value ) +void Control::Impl::AppendAccessibilityAttribute(const std::string& key, + const std::string value) { - Property::Value* val = mAccessibilityAttributes.Find( key ); - if( val ) + Property::Value* val = mAccessibilityAttributes.Find(key); + if(val) { - mAccessibilityAttributes[key] = Property::Value( value ); + mAccessibilityAttributes[key] = Property::Value(value); } else { - mAccessibilityAttributes.Insert( key, value ); + mAccessibilityAttributes.Insert(key, value); } } -void Control::Impl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void Control::Impl::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) ); + Toolkit::Control control = Toolkit::Control::DownCast(BaseHandle(object)); - if ( control ) + if(control) { - Control& controlImpl( GetImplementation( control ) ); + Control& controlImpl(GetImplementation(control)); - switch ( index ) + switch(index) { case Toolkit::Control::Property::STYLE_NAME: { - controlImpl.SetStyleName( value.Get< std::string >() ); + controlImpl.SetStyleName(value.Get()); break; } case Toolkit::DevelControl::Property::STATE: { - bool withTransitions=true; - const Property::Value* valuePtr=&value; - const Property::Map* map = value.GetMap(); + bool withTransitions = true; + const Property::Value* valuePtr = &value; + const Property::Map* map = value.GetMap(); if(map) { Property::Value* value2 = map->Find("withTransitions"); - if( value2 ) + if(value2) { withTransitions = value2->Get(); } @@ -1019,12 +1006,12 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons valuePtr = map->Find("state"); } - if( valuePtr ) + if(valuePtr) { - Toolkit::DevelControl::State state( controlImpl.mImpl->mState ); - if( Scripting::GetEnumerationProperty< Toolkit::DevelControl::State >( *valuePtr, ControlStateTable, ControlStateTableCount, state ) ) + Toolkit::DevelControl::State state(controlImpl.mImpl->mState); + if(Scripting::GetEnumerationProperty(*valuePtr, ControlStateTable, ControlStateTableCount, state)) { - controlImpl.mImpl->SetState( state, withTransitions ); + controlImpl.mImpl->SetState(state, withTransitions); } } } @@ -1033,9 +1020,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::SUB_STATE: { std::string subState; - if( value.Get( subState ) ) + if(value.Get(subState)) { - controlImpl.mImpl->SetSubState( subState ); + controlImpl.mImpl->SetSubState(subState); } } break; @@ -1043,7 +1030,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::LEFT_FOCUSABLE_ACTOR_ID: { int focusId; - if( value.Get( focusId ) ) + if(value.Get(focusId)) { controlImpl.mImpl->mLeftFocusableActorId = focusId; } @@ -1053,7 +1040,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::RIGHT_FOCUSABLE_ACTOR_ID: { int focusId; - if( value.Get( focusId ) ) + if(value.Get(focusId)) { controlImpl.mImpl->mRightFocusableActorId = focusId; } @@ -1063,9 +1050,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_NAME: { std::string name; - if( value.Get( name ) ) + if(value.Get(name)) { - controlImpl.mImpl->mAccessibilityName = name; + controlImpl.mImpl->mAccessibilityName = name; controlImpl.mImpl->mAccessibilityNameSet = true; } else @@ -1078,9 +1065,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION: { std::string txt; - if( value.Get( txt ) ) + if(value.Get(txt)) { - controlImpl.mImpl->mAccessibilityDescription = txt; + controlImpl.mImpl->mAccessibilityDescription = txt; controlImpl.mImpl->mAccessibilityDescriptionSet = true; } else @@ -1093,9 +1080,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN: { std::string txt; - if( value.Get( txt ) ) + if(value.Get(txt)) { - controlImpl.mImpl->mAccessibilityTranslationDomain = txt; + controlImpl.mImpl->mAccessibilityTranslationDomain = txt; controlImpl.mImpl->mAccessibilityTranslationDomainSet = true; } else @@ -1108,9 +1095,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE: { bool highlightable; - if( value.Get( highlightable ) ) + if(value.Get(highlightable)) { - controlImpl.mImpl->mAccessibilityHighlightable = highlightable; + controlImpl.mImpl->mAccessibilityHighlightable = highlightable; controlImpl.mImpl->mAccessibilityHighlightableSet = true; } else @@ -1123,7 +1110,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE: { Dali::Accessibility::Role val; - if( value.Get( val ) ) + if(value.Get(val)) { controlImpl.mImpl->mAccessibilityRole = val; } @@ -1133,7 +1120,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::UP_FOCUSABLE_ACTOR_ID: { int focusId; - if( value.Get( focusId ) ) + if(value.Get(focusId)) { controlImpl.mImpl->mUpFocusableActorId = focusId; } @@ -1143,7 +1130,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::DOWN_FOCUSABLE_ACTOR_ID: { int focusId; - if( value.Get( focusId ) ) + if(value.Get(focusId)) { controlImpl.mImpl->mDownFocusableActorId = focusId; } @@ -1152,7 +1139,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::Control::Property::KEY_INPUT_FOCUS: { - if ( value.Get< bool >() ) + if(value.Get()) { controlImpl.SetKeyInputFocus(); } @@ -1165,23 +1152,23 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::Control::Property::BACKGROUND: { - std::string url; - Vector4 color; + std::string url; + Vector4 color; const Property::Map* map = value.GetMap(); - if( map && !map->Empty() ) + if(map && !map->Empty()) { - controlImpl.SetBackground( *map ); + controlImpl.SetBackground(*map); } - else if( value.Get( url ) ) + else if(value.Get(url)) { // don't know the size to load - Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, ImageDimensions() ); - if( visual ) + Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(url, ImageDimensions()); + if(visual) { - controlImpl.mImpl->RegisterVisual( Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND ); + controlImpl.mImpl->RegisterVisual(Toolkit::Control::Property::BACKGROUND, visual, DepthIndex::BACKGROUND); } } - else if( value.Get( color ) ) + else if(value.Get(color)) { controlImpl.SetBackgroundColor(color); } @@ -1196,9 +1183,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::Control::Property::MARGIN: { Extents margin; - if( value.Get( margin ) ) + if(value.Get(margin)) { - controlImpl.mImpl->SetMargin( margin ); + controlImpl.mImpl->SetMargin(margin); } break; } @@ -1206,9 +1193,9 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::Control::Property::PADDING: { Extents padding; - if( value.Get( padding ) ) + if(value.Get(padding)) { - controlImpl.mImpl->SetPadding( padding ); + controlImpl.mImpl->SetPadding(padding); } break; } @@ -1216,20 +1203,20 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::TOOLTIP: { TooltipPtr& tooltipPtr = controlImpl.mImpl->mTooltip; - if( ! tooltipPtr ) + if(!tooltipPtr) { - tooltipPtr = Tooltip::New( control ); + tooltipPtr = Tooltip::New(control); } - tooltipPtr->SetProperties( value ); + tooltipPtr->SetProperties(value); break; } case Toolkit::DevelControl::Property::SHADOW: { const Property::Map* map = value.GetMap(); - if( map && !map->Empty() ) + if(map && !map->Empty()) { - controlImpl.mImpl->SetShadow( *map ); + controlImpl.mImpl->SetShadow(*map); } else { @@ -1242,7 +1229,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES: { const Property::Map* map = value.GetMap(); - if( map && !map->Empty() ) + if(map && !map->Empty()) { controlImpl.mImpl->mAccessibilityAttributes = *map; } @@ -1252,7 +1239,7 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons case Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED: { bool animated; - if( value.Get( animated ) ) + if(value.Get(animated)) { controlImpl.mImpl->mAccessibilityAnimated = animated; } @@ -1262,17 +1249,17 @@ void Control::Impl::SetProperty( BaseObject* object, Property::Index index, cons } } -Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index index ) +Property::Value Control::Impl::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::Control control = Toolkit::Control::DownCast( BaseHandle( object ) ); + Toolkit::Control control = Toolkit::Control::DownCast(BaseHandle(object)); - if ( control ) + if(control) { - Control& controlImpl( GetImplementation( control ) ); + Control& controlImpl(GetImplementation(control)); - switch ( index ) + switch(index) { case Toolkit::Control::Property::STYLE_NAME: { @@ -1306,7 +1293,7 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::DevelControl::Property::ACCESSIBILITY_NAME: { - if (controlImpl.mImpl->mAccessibilityNameSet) + if(controlImpl.mImpl->mAccessibilityNameSet) { value = controlImpl.mImpl->mAccessibilityName; } @@ -1315,7 +1302,7 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::DevelControl::Property::ACCESSIBILITY_DESCRIPTION: { - if (controlImpl.mImpl->mAccessibilityDescriptionSet) + if(controlImpl.mImpl->mAccessibilityDescriptionSet) { value = controlImpl.mImpl->mAccessibilityDescription; } @@ -1324,7 +1311,7 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::DevelControl::Property::ACCESSIBILITY_TRANSLATION_DOMAIN: { - if (controlImpl.mImpl->mAccessibilityTranslationDomainSet) + if(controlImpl.mImpl->mAccessibilityTranslationDomainSet) { value = controlImpl.mImpl->mAccessibilityTranslationDomain; } @@ -1333,7 +1320,7 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE: { - if (controlImpl.mImpl->mAccessibilityHighlightableSet) + if(controlImpl.mImpl->mAccessibilityHighlightableSet) { value = controlImpl.mImpl->mAccessibilityHighlightable; } @@ -1366,11 +1353,11 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::Control::Property::BACKGROUND: { - Property::Map map; - Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::Control::Property::BACKGROUND ); - if( visual ) + Property::Map map; + Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual(Toolkit::Control::Property::BACKGROUND); + if(visual) { - visual.CreatePropertyMap( map ); + visual.CreatePropertyMap(map); } value = map; @@ -1392,9 +1379,9 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::DevelControl::Property::TOOLTIP: { Property::Map map; - if( controlImpl.mImpl->mTooltip ) + if(controlImpl.mImpl->mTooltip) { - controlImpl.mImpl->mTooltip->CreatePropertyMap( map ); + controlImpl.mImpl->mTooltip->CreatePropertyMap(map); } value = map; break; @@ -1402,11 +1389,11 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index case Toolkit::DevelControl::Property::SHADOW: { - Property::Map map; - Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual( Toolkit::DevelControl::Property::SHADOW ); - if( visual ) + Property::Map map; + Toolkit::Visual::Base visual = controlImpl.mImpl->GetVisual(Toolkit::DevelControl::Property::SHADOW); + if(visual) { - visual.CreatePropertyMap( map ); + visual.CreatePropertyMap(map); } value = map; @@ -1430,10 +1417,10 @@ Property::Value Control::Impl::GetProperty( BaseObject* object, Property::Index return value; } -void Control::Impl::RemoveAccessibilityAttribute( const std::string& key ) +void Control::Impl::RemoveAccessibilityAttribute(const std::string& key) { - Property::Value* val = mAccessibilityAttributes.Find( key ); - if( val ) + Property::Value* val = mAccessibilityAttributes.Find(key); + if(val) mAccessibilityAttributes[key] = Property::Value(); } @@ -1442,129 +1429,130 @@ void Control::Impl::ClearAccessibilityAttributes() mAccessibilityAttributes.Clear(); } -void Control::Impl::SetAccessibilityReadingInfoType( const Dali::Accessibility::ReadingInfoTypes types ) +void Control::Impl::SetAccessibilityReadingInfoType(const Dali::Accessibility::ReadingInfoTypes types) { std::string value; - if ( types[ Dali::Accessibility::ReadingInfoType::NAME ] ) + if(types[Dali::Accessibility::ReadingInfoType::NAME]) { value += READING_INFO_TYPE_NAME; } - if ( types[ Dali::Accessibility::ReadingInfoType::ROLE ] ) + if(types[Dali::Accessibility::ReadingInfoType::ROLE]) { - if( !value.empty() ) + if(!value.empty()) { value += READING_INFO_TYPE_SEPARATOR; } value += READING_INFO_TYPE_ROLE; } - if ( types[ Dali::Accessibility::ReadingInfoType::DESCRIPTION ] ) + if(types[Dali::Accessibility::ReadingInfoType::DESCRIPTION]) { - if( !value.empty() ) + if(!value.empty()) { value += READING_INFO_TYPE_SEPARATOR; } value += READING_INFO_TYPE_DESCRIPTION; } - if ( types[ Dali::Accessibility::ReadingInfoType::STATE ] ) + if(types[Dali::Accessibility::ReadingInfoType::STATE]) { - if( !value.empty() ) + if(!value.empty()) { value += READING_INFO_TYPE_SEPARATOR; } value += READING_INFO_TYPE_STATE; } - AppendAccessibilityAttribute( READING_INFO_TYPE_ATTRIBUTE_NAME, value ); + AppendAccessibilityAttribute(READING_INFO_TYPE_ATTRIBUTE_NAME, value); } Dali::Accessibility::ReadingInfoTypes Control::Impl::GetAccessibilityReadingInfoType() const { std::string value; - auto place = mAccessibilityAttributes.Find( READING_INFO_TYPE_ATTRIBUTE_NAME ); - if( place ) + auto place = mAccessibilityAttributes.Find(READING_INFO_TYPE_ATTRIBUTE_NAME); + if(place) { - place->Get( value ); + place->Get(value); } - if ( value.empty() ) + if(value.empty()) { return {}; } Dali::Accessibility::ReadingInfoTypes types; - if ( value.find( READING_INFO_TYPE_NAME ) != std::string::npos ) + if(value.find(READING_INFO_TYPE_NAME) != std::string::npos) { - types[ Dali::Accessibility::ReadingInfoType::NAME ] = true; + types[Dali::Accessibility::ReadingInfoType::NAME] = true; } - if ( value.find( READING_INFO_TYPE_ROLE ) != std::string::npos ) + if(value.find(READING_INFO_TYPE_ROLE) != std::string::npos) { - types[ Dali::Accessibility::ReadingInfoType::ROLE ] = true; + types[Dali::Accessibility::ReadingInfoType::ROLE] = true; } - if ( value.find( READING_INFO_TYPE_DESCRIPTION ) != std::string::npos ) + if(value.find(READING_INFO_TYPE_DESCRIPTION) != std::string::npos) { - types[ Dali::Accessibility::ReadingInfoType::DESCRIPTION ] = true; + types[Dali::Accessibility::ReadingInfoType::DESCRIPTION] = true; } - if ( value.find( READING_INFO_TYPE_STATE ) != std::string::npos ) + if(value.find(READING_INFO_TYPE_STATE) != std::string::npos) { - types[ Dali::Accessibility::ReadingInfoType::STATE ] = true; + types[Dali::Accessibility::ReadingInfoType::STATE] = true; } return types; } -void Control::Impl::CopyInstancedProperties( RegisteredVisualContainer& visuals, Dictionary& instancedProperties ) +void Control::Impl::CopyInstancedProperties(RegisteredVisualContainer& visuals, Dictionary& instancedProperties) { - for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter!= visuals.End(); iter++) + for(RegisteredVisualContainer::Iterator iter = visuals.Begin(); iter != visuals.End(); iter++) { - if( (*iter)->visual ) + if((*iter)->visual) { Property::Map instanceMap; Toolkit::GetImplementation((*iter)->visual).CreateInstancePropertyMap(instanceMap); - instancedProperties.Add( (*iter)->visual.GetName(), instanceMap ); + instancedProperties.Add((*iter)->visual.GetName(), instanceMap); } } } - -void Control::Impl::RemoveVisual( RegisteredVisualContainer& visuals, const std::string& visualName ) +void Control::Impl::RemoveVisual(RegisteredVisualContainer& visuals, const std::string& visualName) { - Actor self( mControlImpl.Self() ); + Actor self(mControlImpl.Self()); - for ( RegisteredVisualContainer::Iterator visualIter = visuals.Begin(); - visualIter != visuals.End(); ++visualIter ) + for(RegisteredVisualContainer::Iterator visualIter = visuals.Begin(); + visualIter != visuals.End(); + ++visualIter) { Toolkit::Visual::Base visual = (*visualIter)->visual; - if( visual && visual.GetName() == visualName ) + if(visual && visual.GetName() == visualName) { - Toolkit::GetImplementation(visual).SetOffScene( self ); + Toolkit::GetImplementation(visual).SetOffScene(self); (*visualIter)->visual.Reset(); - visuals.Erase( visualIter ); + visuals.Erase(visualIter); break; } } } -void Control::Impl::RemoveVisuals( RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals ) +void Control::Impl::RemoveVisuals(RegisteredVisualContainer& visuals, DictionaryKeys& removeVisuals) { - Actor self( mControlImpl.Self() ); - for( DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter ) + Actor self(mControlImpl.Self()); + for(DictionaryKeys::iterator iter = removeVisuals.begin(); iter != removeVisuals.end(); ++iter) { const std::string visualName = *iter; - RemoveVisual( visuals, visualName ); + RemoveVisual(visuals, visualName); } } -void Control::Impl::RecreateChangedVisuals( Dictionary& stateVisualsToChange, - Dictionary& instancedProperties ) +void Control::Impl::RecreateChangedVisuals(Dictionary& stateVisualsToChange, + Dictionary& instancedProperties) { - Dali::CustomActor handle( mControlImpl.GetOwner() ); - for( Dictionary::iterator iter = stateVisualsToChange.Begin(); - iter != stateVisualsToChange.End(); ++iter ) + Dali::CustomActor handle(mControlImpl.GetOwner()); + for(Dictionary::iterator iter = stateVisualsToChange.Begin(); + iter != stateVisualsToChange.End(); + ++iter) { - const std::string& visualName = (*iter).key; - const Property::Map& toMap = (*iter).entry; + const std::string& visualName = (*iter).key; + const Property::Map& toMap = (*iter).entry; - Actor self = mControlImpl.Self(); + Actor self = mControlImpl.Self(); RegisteredVisualContainer::Iterator registeredVisualsiter; // Check if visual (visualName) is already registered, this is the current visual. if(FindVisual(visualName, mVisuals, registeredVisualsiter)) @@ -1609,70 +1597,67 @@ void Control::Impl::RecreateChangedVisuals( Dictionary& stateVisu } } -void Control::Impl::ReplaceStateVisualsAndProperties( const StylePtr oldState, const StylePtr newState, const std::string& subState ) +void Control::Impl::ReplaceStateVisualsAndProperties(const StylePtr oldState, const StylePtr newState, const std::string& subState) { // Collect all old visual names DictionaryKeys stateVisualsToRemove; - if( oldState ) + if(oldState) { - oldState->visuals.GetKeys( stateVisualsToRemove ); - if( ! subState.empty() ) + oldState->visuals.GetKeys(stateVisualsToRemove); + if(!subState.empty()) { const StylePtr* oldSubState = oldState->subStates.FindConst(subState); - if( oldSubState ) + if(oldSubState) { DictionaryKeys subStateVisualsToRemove; - (*oldSubState)->visuals.GetKeys( subStateVisualsToRemove ); - Merge( stateVisualsToRemove, subStateVisualsToRemove ); + (*oldSubState)->visuals.GetKeys(subStateVisualsToRemove); + Merge(stateVisualsToRemove, subStateVisualsToRemove); } } } // Collect all new visual properties Dictionary stateVisualsToAdd; - if( newState ) + if(newState) { stateVisualsToAdd = newState->visuals; - if( ! subState.empty() ) + if(!subState.empty()) { const StylePtr* newSubState = newState->subStates.FindConst(subState); - if( newSubState ) + if(newSubState) { - stateVisualsToAdd.Merge( (*newSubState)->visuals ); + stateVisualsToAdd.Merge((*newSubState)->visuals); } } } // If a name is in both add/remove, move it to change list. Dictionary stateVisualsToChange; - FindChangableVisuals( stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove); + FindChangableVisuals(stateVisualsToAdd, stateVisualsToChange, stateVisualsToRemove); // Copy instanced properties (e.g. text label) of current visuals Dictionary instancedProperties; - CopyInstancedProperties( mVisuals, instancedProperties ); + CopyInstancedProperties(mVisuals, instancedProperties); // For each visual in remove list, remove from mVisuals - RemoveVisuals( mVisuals, stateVisualsToRemove ); + RemoveVisuals(mVisuals, stateVisualsToRemove); // For each visual in add list, create and add to mVisuals - Dali::CustomActor handle( mControlImpl.GetOwner() ); - Style::ApplyVisuals( handle, stateVisualsToAdd, instancedProperties ); + Dali::CustomActor handle(mControlImpl.GetOwner()); + Style::ApplyVisuals(handle, stateVisualsToAdd, instancedProperties); // For each visual in change list, if it requires a new visual, // remove old visual, create and add to mVisuals - RecreateChangedVisuals( stateVisualsToChange, instancedProperties ); + RecreateChangedVisuals(stateVisualsToChange, instancedProperties); } -void Control::Impl::SetState( DevelControl::State newState, bool withTransitions ) +void Control::Impl::SetState(DevelControl::State newState, bool withTransitions) { DevelControl::State oldState = mState; - Dali::CustomActor handle( mControlImpl.GetOwner() ); - DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n", - (mState == DevelControl::NORMAL ? "NORMAL" :( - mState == DevelControl::FOCUSED ?"FOCUSED" : ( - mState == DevelControl::DISABLED?"DISABLED":"NONE" )))); + Dali::CustomActor handle(mControlImpl.GetOwner()); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "Control::Impl::SetState: %s\n", (mState == DevelControl::NORMAL ? "NORMAL" : (mState == DevelControl::FOCUSED ? "FOCUSED" : (mState == DevelControl::DISABLED ? "DISABLED" : "NONE")))); - if( mState != newState ) + if(mState != newState) { // If mState was Disabled, and new state is Focused, should probably // store that fact, e.g. in another property that FocusManager can access. @@ -1681,54 +1666,54 @@ void Control::Impl::SetState( DevelControl::State newState, bool withTransitions // Trigger state change and transitions // Apply new style, if stylemanager is available Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get(); - if( styleManager ) + if(styleManager) { - const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) ); + const StylePtr stylePtr = GetImpl(styleManager).GetRecordedStyle(Toolkit::Control(mControlImpl.GetOwner())); - if( stylePtr ) + if(stylePtr) { - std::string oldStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( oldState, ControlStateTable, ControlStateTableCount ); - std::string newStateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( newState, ControlStateTable, ControlStateTableCount ); + std::string oldStateName = Scripting::GetEnumerationName(oldState, ControlStateTable, ControlStateTableCount); + std::string newStateName = Scripting::GetEnumerationName(newState, ControlStateTable, ControlStateTableCount); - const StylePtr* newStateStyle = stylePtr->subStates.Find( newStateName ); - const StylePtr* oldStateStyle = stylePtr->subStates.Find( oldStateName ); - if( oldStateStyle && newStateStyle ) + const StylePtr* newStateStyle = stylePtr->subStates.Find(newStateName); + const StylePtr* oldStateStyle = stylePtr->subStates.Find(oldStateName); + if(oldStateStyle && newStateStyle) { // Only change if both state styles exist - ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, mSubStateName ); + ReplaceStateVisualsAndProperties(*oldStateStyle, *newStateStyle, mSubStateName); } } } } } -void Control::Impl::SetSubState( const std::string& subStateName, bool withTransitions ) +void Control::Impl::SetSubState(const std::string& subStateName, bool withTransitions) { - if( mSubStateName != subStateName ) + if(mSubStateName != subStateName) { // Get existing sub-state visuals, and unregister them - Dali::CustomActor handle( mControlImpl.GetOwner() ); + Dali::CustomActor handle(mControlImpl.GetOwner()); Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get(); - if( styleManager ) + if(styleManager) { - const StylePtr stylePtr = GetImpl( styleManager ).GetRecordedStyle( Toolkit::Control( mControlImpl.GetOwner() ) ); - if( stylePtr ) + const StylePtr stylePtr = GetImpl(styleManager).GetRecordedStyle(Toolkit::Control(mControlImpl.GetOwner())); + if(stylePtr) { // Stringify state - std::string stateName = Scripting::GetEnumerationName< Toolkit::DevelControl::State >( mState, ControlStateTable, ControlStateTableCount ); + std::string stateName = Scripting::GetEnumerationName(mState, ControlStateTable, ControlStateTableCount); - const StylePtr* state = stylePtr->subStates.Find( stateName ); - if( state ) + const StylePtr* state = stylePtr->subStates.Find(stateName); + if(state) { StylePtr stateStyle(*state); - const StylePtr* newStateStyle = stateStyle->subStates.Find( subStateName ); - const StylePtr* oldStateStyle = stateStyle->subStates.Find( mSubStateName ); - if( oldStateStyle && newStateStyle ) + const StylePtr* newStateStyle = stateStyle->subStates.Find(subStateName); + const StylePtr* oldStateStyle = stateStyle->subStates.Find(mSubStateName); + if(oldStateStyle && newStateStyle) { std::string empty; - ReplaceStateVisualsAndProperties( *oldStateStyle, *newStateStyle, empty ); + ReplaceStateVisualsAndProperties(*oldStateStyle, *newStateStyle, empty); } } } @@ -1747,16 +1732,16 @@ void Control::Impl::OnSceneDisconnection() // then when this control appears back on stage it should use that new visual. // Iterate through all registered visuals and set off scene - SetVisualsOffScene( mVisuals, self ); + SetVisualsOffScene(mVisuals, self); // Visuals pending replacement can now be taken out of the removal list and set off scene // Iterate through all replacement visuals and add to a move queue then set off scene - for( auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++ ) + for(auto removalIter = mRemoveVisuals.Begin(), end = mRemoveVisuals.End(); removalIter != end; removalIter++) { - Toolkit::GetImplementation((*removalIter)->visual).SetOffScene( self ); + Toolkit::GetImplementation((*removalIter)->visual).SetOffScene(self); } - for( auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++ ) + for(auto replacedIter = mVisuals.Begin(), end = mVisuals.End(); replacedIter != end; replacedIter++) { (*replacedIter)->pending = false; } @@ -1764,7 +1749,7 @@ void Control::Impl::OnSceneDisconnection() mRemoveVisuals.Clear(); } -void Control::Impl::SetMargin( Extents margin ) +void Control::Impl::SetMargin(Extents margin) { mControlImpl.mImpl->mMargin = margin; @@ -1777,7 +1762,7 @@ Extents Control::Impl::GetMargin() const return mControlImpl.mImpl->mMargin; } -void Control::Impl::SetPadding( Extents padding ) +void Control::Impl::SetPadding(Extents padding) { mControlImpl.mImpl->mPadding = padding; @@ -1790,18 +1775,18 @@ Extents Control::Impl::GetPadding() const return mControlImpl.mImpl->mPadding; } -void Control::Impl::SetInputMethodContext( InputMethodContext& inputMethodContext ) +void Control::Impl::SetInputMethodContext(InputMethodContext& inputMethodContext) { mInputMethodContext = inputMethodContext; } -bool Control::Impl::FilterKeyEvent( const KeyEvent& event ) +bool Control::Impl::FilterKeyEvent(const KeyEvent& event) { - bool consumed ( false ); + bool consumed(false); - if ( mInputMethodContext ) + if(mInputMethodContext) { - consumed = mInputMethodContext.FilterEventKey( event ); + consumed = mInputMethodContext.FilterEventKey(event); } return consumed; } @@ -1811,14 +1796,14 @@ DevelControl::VisualEventSignalType& Control::Impl::VisualEventSignal() return mVisualEventSignal; } -void Control::Impl::SetShadow( const Property::Map& map ) +void Control::Impl::SetShadow(const Property::Map& map) { - Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( map ); + Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(map); visual.SetName("shadow"); - if( visual ) + if(visual) { - mControlImpl.mImpl->RegisterVisual( Toolkit::DevelControl::Property::SHADOW, visual, DepthIndex::BACKGROUND_EFFECT ); + mControlImpl.mImpl->RegisterVisual(Toolkit::DevelControl::Property::SHADOW, visual, DepthIndex::BACKGROUND_EFFECT); mControlImpl.RelayoutRequest(); } @@ -1826,10 +1811,10 @@ void Control::Impl::SetShadow( const Property::Map& map ) void Control::Impl::ClearShadow() { - mControlImpl.mImpl->UnregisterVisual( Toolkit::DevelControl::Property::SHADOW ); + mControlImpl.mImpl->UnregisterVisual(Toolkit::DevelControl::Property::SHADOW); - // Trigger a size negotiation request that may be needed when unregistering a visual. - mControlImpl.RelayoutRequest(); + // Trigger a size negotiation request that may be needed when unregistering a visual. + mControlImpl.RelayoutRequest(); } Dali::Property Control::Impl::GetVisualProperty(Dali::Property::Index index, Dali::Property::Key visualPropertyKey) @@ -1864,7 +1849,7 @@ void Control::Impl::EmitResourceReadySignal() if(!mIdleCallback) { // The callback manager takes the ownership of the callback object. - mIdleCallback = MakeCallback( this, &Control::Impl::OnIdleCallback); + mIdleCallback = MakeCallback(this, &Control::Impl::OnIdleCallback); Adaptor::Get().AddIdle(mIdleCallback, false); } } @@ -1897,21 +1882,21 @@ void Control::Impl::OnIdleCallback() mIdleCallback = nullptr; } -Dali::Accessibility::Accessible *Control::Impl::GetAccessibilityObject() +Dali::Accessibility::Accessible* Control::Impl::GetAccessibilityObject() { - if( !accessibilityObject ) - accessibilityObject = accessibilityConstructor( mControlImpl.Self() ); + if(!accessibilityObject) + accessibilityObject = accessibilityConstructor(mControlImpl.Self()); return accessibilityObject.get(); } -Dali::Accessibility::Accessible *Control::Impl::GetAccessibilityObject(Dali::Actor actor) +Dali::Accessibility::Accessible* Control::Impl::GetAccessibilityObject(Dali::Actor actor) { - if( actor ) + if(actor) { - auto q = Dali::Toolkit::Control::DownCast( actor ); - if( q ) + auto q = Dali::Toolkit::Control::DownCast(actor); + if(q) { - auto q2 = static_cast< Internal::Control* >( &q.GetImplementation() ); + auto q2 = static_cast(&q.GetImplementation()); return q2->mImpl->GetAccessibilityObject(); } } @@ -1919,35 +1904,33 @@ Dali::Accessibility::Accessible *Control::Impl::GetAccessibilityObject(Dali::Act } Control::Impl::AccessibleImpl::AccessibleImpl(Dali::Actor self, Dali::Accessibility::Role role, bool modal) - : self(self), modal(modal) +: self(self), + modal(modal) { auto control = Dali::Toolkit::Control::DownCast(self); - Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control ); - Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl ); - if( controlImpl.mAccessibilityRole == Dali::Accessibility::Role::UNKNOWN ) + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); + if(controlImpl.mAccessibilityRole == Dali::Accessibility::Role::UNKNOWN) controlImpl.mAccessibilityRole = role; - self.PropertySetSignal().Connect(&controlImpl, [this, &controlImpl](Dali::Handle &handle, Dali::Property::Index index, Dali::Property::Value value) - { - if (this->self != Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) + self.PropertySetSignal().Connect(&controlImpl, [this, &controlImpl](Dali::Handle& handle, Dali::Property::Index index, Dali::Property::Value value) { + if(this->self != Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) { return; } - if (index == DevelControl::Property::ACCESSIBILITY_NAME - || (index == GetNamePropertyIndex() && !controlImpl.mAccessibilityNameSet)) + if(index == DevelControl::Property::ACCESSIBILITY_NAME || (index == GetNamePropertyIndex() && !controlImpl.mAccessibilityNameSet)) { - if (controlImpl.mAccessibilityGetNameSignal.Empty()) + if(controlImpl.mAccessibilityGetNameSignal.Empty()) { Emit(Dali::Accessibility::ObjectPropertyChangeEvent::NAME); } } - if (index == DevelControl::Property::ACCESSIBILITY_DESCRIPTION - || (index == GetDescriptionPropertyIndex() && !controlImpl.mAccessibilityDescriptionSet)) + if(index == DevelControl::Property::ACCESSIBILITY_DESCRIPTION || (index == GetDescriptionPropertyIndex() && !controlImpl.mAccessibilityDescriptionSet)) { - if (controlImpl.mAccessibilityGetDescriptionSignal.Empty()) + if(controlImpl.mAccessibilityGetDescriptionSignal.Empty()) { Emit(Dali::Accessibility::ObjectPropertyChangeEvent::DESCRIPTION); } @@ -1959,22 +1942,23 @@ std::string Control::Impl::AccessibleImpl::GetName() { auto control = Dali::Toolkit::Control::DownCast(self); - Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control ); - Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl ); + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); - if (!controlImpl.mAccessibilityGetNameSignal.Empty()) { - std::string ret; - controlImpl.mAccessibilityGetNameSignal.Emit(ret); - return ret; + if(!controlImpl.mAccessibilityGetNameSignal.Empty()) + { + std::string ret; + controlImpl.mAccessibilityGetNameSignal.Emit(ret); + return ret; } - if (controlImpl.mAccessibilityNameSet) + if(controlImpl.mAccessibilityNameSet) return controlImpl.mAccessibilityName; - if (auto raw = GetNameRaw(); !raw.empty()) + if(auto raw = GetNameRaw(); !raw.empty()) return raw; - return self.GetProperty< std::string >( Actor::Property::NAME ); + return self.GetProperty(Actor::Property::NAME); } std::string Control::Impl::AccessibleImpl::GetNameRaw() @@ -1986,16 +1970,17 @@ std::string Control::Impl::AccessibleImpl::GetDescription() { auto control = Dali::Toolkit::Control::DownCast(self); - Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control ); - Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl ); + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); - if (!controlImpl.mAccessibilityGetDescriptionSignal.Empty()) { - std::string ret; - controlImpl.mAccessibilityGetDescriptionSignal.Emit(ret); - return ret; + if(!controlImpl.mAccessibilityGetDescriptionSignal.Empty()) + { + std::string ret; + controlImpl.mAccessibilityGetDescriptionSignal.Emit(ret); + return ret; } - if (controlImpl.mAccessibilityDescriptionSet) + if(controlImpl.mAccessibilityDescriptionSet) return controlImpl.mAccessibilityDescription; return GetDescriptionRaw(); @@ -2008,7 +1993,7 @@ std::string Control::Impl::AccessibleImpl::GetDescriptionRaw() Dali::Accessibility::Accessible* Control::Impl::AccessibleImpl::GetParent() { - return Dali::Accessibility::Accessible::Get( self.GetParent() ); + return Dali::Accessibility::Accessible::Get(self.GetParent()); } size_t Control::Impl::AccessibleImpl::GetChildCount() @@ -2016,54 +2001,53 @@ size_t Control::Impl::AccessibleImpl::GetChildCount() return self.GetChildCount(); } -Dali::Accessibility::Accessible* Control::Impl::AccessibleImpl::GetChildAtIndex( size_t index ) +Dali::Accessibility::Accessible* Control::Impl::AccessibleImpl::GetChildAtIndex(size_t index) { - return Dali::Accessibility::Accessible::Get( self.GetChildAt( static_cast< unsigned int >( index ) ) ); + return Dali::Accessibility::Accessible::Get(self.GetChildAt(static_cast(index))); } size_t Control::Impl::AccessibleImpl::GetIndexInParent() { - auto s = self; + auto s = self; auto parent = s.GetParent(); - DALI_ASSERT_ALWAYS( parent && "can't call GetIndexInParent on object without parent" ); + DALI_ASSERT_ALWAYS(parent && "can't call GetIndexInParent on object without parent"); auto count = parent.GetChildCount(); - for( auto i = 0u; i < count; ++i ) + for(auto i = 0u; i < count; ++i) { - auto c = parent.GetChildAt( i ); - if( c == s ) + auto c = parent.GetChildAt(i); + if(c == s) return i; } - DALI_ASSERT_ALWAYS( false && "object isn't child of it's parent" ); + DALI_ASSERT_ALWAYS(false && "object isn't child of it's parent"); return static_cast(-1); } Dali::Accessibility::Role Control::Impl::AccessibleImpl::GetRole() { - return self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE ); + return self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE); } Dali::Accessibility::States Control::Impl::AccessibleImpl::CalculateStates() { Dali::Accessibility::States s; - s[Dali::Accessibility::State::FOCUSABLE] = self.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ); - s[Dali::Accessibility::State::FOCUSED] = Toolkit::KeyboardFocusManager::Get().GetCurrentFocusActor() == self; - if(self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE ).GetType() == Property::NONE ) + s[Dali::Accessibility::State::FOCUSABLE] = self.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE); + s[Dali::Accessibility::State::FOCUSED] = Toolkit::KeyboardFocusManager::Get().GetCurrentFocusActor() == self; + if(self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).GetType() == Property::NONE) s[Dali::Accessibility::State::HIGHLIGHTABLE] = false; else - s[Dali::Accessibility::State::HIGHLIGHTABLE] = self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE ).Get< bool >(); + s[Dali::Accessibility::State::HIGHLIGHTABLE] = self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).Get(); s[Dali::Accessibility::State::HIGHLIGHTED] = GetCurrentlyHighlightedActor() == self; - s[Dali::Accessibility::State::ENABLED] = true; - s[Dali::Accessibility::State::SENSITIVE] = true; - s[Dali::Accessibility::State::ANIMATED] = self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED ).Get< bool >(); - s[Dali::Accessibility::State::VISIBLE] = true; - if( modal ) + s[Dali::Accessibility::State::ENABLED] = true; + s[Dali::Accessibility::State::SENSITIVE] = true; + s[Dali::Accessibility::State::ANIMATED] = self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED).Get(); + s[Dali::Accessibility::State::VISIBLE] = true; + if(modal) { s[Dali::Accessibility::State::MODAL] = true; } - s[Dali::Accessibility::State::SHOWING] = !self.GetProperty( Dali::DevelActor::Property::CULLED ).Get< bool >() - && self.GetCurrentProperty< bool >( Actor::Property::VISIBLE ); + s[Dali::Accessibility::State::SHOWING] = !self.GetProperty(Dali::DevelActor::Property::CULLED).Get() && self.GetCurrentProperty(Actor::Property::VISIBLE); - s[Dali::Accessibility::State::DEFUNCT] = !self.GetProperty( Dali::DevelActor::Property::CONNECTED_TO_SCENE ).Get< bool >(); + s[Dali::Accessibility::State::DEFUNCT] = !self.GetProperty(Dali::DevelActor::Property::CONNECTED_TO_SCENE).Get(); return s; } @@ -2074,26 +2058,26 @@ Dali::Accessibility::States Control::Impl::AccessibleImpl::GetStates() Dali::Accessibility::Attributes Control::Impl::AccessibleImpl::GetAttributes() { - std::unordered_map< std::string, std::string > attribute_map; - auto q = Dali::Toolkit::Control::DownCast( self ); - auto w = - q.GetProperty( Dali::Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES ); + std::unordered_map attribute_map; + auto q = Dali::Toolkit::Control::DownCast(self); + auto w = + q.GetProperty(Dali::Toolkit::DevelControl::Property::ACCESSIBILITY_ATTRIBUTES); auto z = w.GetMap(); - if( z ) + if(z) { auto map_size = z->Count(); - for( unsigned int i = 0; i < map_size; i++ ) + for(unsigned int i = 0; i < map_size; i++) { - auto map_key = z->GetKeyAt( i ); - if( map_key.type == Property::Key::STRING ) + auto map_key = z->GetKeyAt(i); + if(map_key.type == Property::Key::STRING) { std::string map_value; - if( z->GetValue( i ).Get( map_value ) ) + if(z->GetValue(i).Get(map_value)) { - attribute_map.emplace( std::move( map_key.stringKey ), - std::move( map_value ) ); + attribute_map.emplace(std::move(map_key.stringKey), + std::move(map_value)); } } } @@ -2107,30 +2091,36 @@ Dali::Accessibility::ComponentLayer Control::Impl::AccessibleImpl::GetLayer() return Dali::Accessibility::ComponentLayer::WINDOW; } -Dali::Rect<> Control::Impl::AccessibleImpl::GetExtents( Dali::Accessibility::CoordType ctype ) +Dali::Rect<> Control::Impl::AccessibleImpl::GetExtents(Dali::Accessibility::CoordType ctype) { Vector2 screenPosition = - self.GetProperty( Dali::DevelActor::Property::SCREEN_POSITION ) - .Get< Vector2 >(); - auto size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * self.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_SCALE ); + self.GetProperty(Dali::DevelActor::Property::SCREEN_POSITION) + .Get(); + auto size = self.GetCurrentProperty(Actor::Property::SIZE) * self.GetCurrentProperty(Actor::Property::WORLD_SCALE); bool positionUsesAnchorPoint = - self.GetProperty( Dali::DevelActor::Property::POSITION_USES_ANCHOR_POINT ) - .Get< bool >(); + self.GetProperty(Dali::DevelActor::Property::POSITION_USES_ANCHOR_POINT) + .Get(); Vector3 anchorPointOffSet = - size * ( positionUsesAnchorPoint ? self.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) - : AnchorPoint::TOP_LEFT ); - Vector2 position = Vector2( screenPosition.x - anchorPointOffSet.x, - screenPosition.y - anchorPointOffSet.y ); + size * (positionUsesAnchorPoint ? self.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}; } -int16_t Control::Impl::AccessibleImpl::GetMdiZOrder() { return 0; } -double Control::Impl::AccessibleImpl::GetAlpha() { return 0; } +int16_t Control::Impl::AccessibleImpl::GetMdiZOrder() +{ + return 0; +} +double Control::Impl::AccessibleImpl::GetAlpha() +{ + return 0; +} bool Control::Impl::AccessibleImpl::GrabFocus() { - return Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor( self ); + return Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor(self); } static Dali::Actor CreateHighlightIndicatorActor() @@ -2139,11 +2129,11 @@ static Dali::Actor CreateHighlightIndicatorActor() focusBorderImagePath += "/keyboard_focus.9.png"; // Create the default if it hasn't been set and one that's shared by all the // keyboard focusable actors - auto actor = Toolkit::ImageView::New( focusBorderImagePath ); - actor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); - DevelControl::AppendAccessibilityAttribute( actor, "highlight", "" ); - actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, true); - actor.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false ); + auto actor = Toolkit::ImageView::New(focusBorderImagePath); + actor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); + DevelControl::AppendAccessibilityAttribute(actor, "highlight", ""); + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED, true); + actor.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false); return actor; } @@ -2152,100 +2142,99 @@ bool Control::Impl::AccessibleImpl::GrabHighlight() { auto old = GetCurrentlyHighlightedActor(); - if( !Dali::Accessibility::IsUp() ) - return false; - if( self == old ) + if(!Dali::Accessibility::IsUp()) + return false; + if(self == old) return true; - if( old ) + if(old) { - auto c = dynamic_cast< Dali::Accessibility::Component* >( GetAccessibilityObject( old ) ); - if( c ) + auto c = dynamic_cast(GetAccessibilityObject(old)); + if(c) c->ClearHighlight(); } auto highlight = GetHighlightActor(); - if ( !highlight ) + if(!highlight) { highlight = CreateHighlightIndicatorActor(); - SetHighlightActor( highlight ); + SetHighlightActor(highlight); } - highlight.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - highlight.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - highlight.SetProperty( Actor::Property::POSITION_Z, 1.0f ); - highlight.SetProperty( Actor::Property::POSITION, Vector2( 0.0f, 0.0f )); + highlight.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + highlight.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + highlight.SetProperty(Actor::Property::POSITION_Z, 1.0f); + highlight.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f)); EnsureSelfVisible(); - self.Add( highlight ); - SetCurrentlyHighlightedActor( self ); - EmitHighlighted( true ); + self.Add(highlight); + SetCurrentlyHighlightedActor(self); + EmitHighlighted(true); return true; } - - bool Control::Impl::AccessibleImpl::ClearHighlight() { - if( !Dali::Accessibility::IsUp() ) + if(!Dali::Accessibility::IsUp()) return false; - if( GetCurrentlyHighlightedActor() == self ) + if(GetCurrentlyHighlightedActor() == self) { - self.Remove( GetHighlightActor() ); - SetCurrentlyHighlightedActor( {} ); - EmitHighlighted( false ); + self.Remove(GetHighlightActor()); + SetCurrentlyHighlightedActor({}); + EmitHighlighted(false); return true; } return false; } -std::string Control::Impl::AccessibleImpl::GetActionName( size_t index ) +std::string Control::Impl::AccessibleImpl::GetActionName(size_t index) { - if ( index >= GetActionCount() ) return ""; + if(index >= GetActionCount()) return ""; Dali::TypeInfo type; - self.GetTypeInfo( type ); - DALI_ASSERT_ALWAYS( type && "no TypeInfo object" ); - return type.GetActionName( index ); + self.GetTypeInfo(type); + DALI_ASSERT_ALWAYS(type && "no TypeInfo object"); + return type.GetActionName(index); } -std::string Control::Impl::AccessibleImpl::GetLocalizedActionName( size_t index ) +std::string Control::Impl::AccessibleImpl::GetLocalizedActionName(size_t index) { // TODO: add localization - return GetActionName( index ); + return GetActionName(index); } -std::string Control::Impl::AccessibleImpl::GetActionDescription( size_t index ) +std::string Control::Impl::AccessibleImpl::GetActionDescription(size_t index) { return ""; } size_t Control::Impl::AccessibleImpl::GetActionCount() { Dali::TypeInfo type; - self.GetTypeInfo( type ); - DALI_ASSERT_ALWAYS( type && "no TypeInfo object" ); + self.GetTypeInfo(type); + DALI_ASSERT_ALWAYS(type && "no TypeInfo object"); return type.GetActionCount(); } -std::string Control::Impl::AccessibleImpl::GetActionKeyBinding( size_t index ) +std::string Control::Impl::AccessibleImpl::GetActionKeyBinding(size_t index) { return ""; } -bool Control::Impl::AccessibleImpl::DoAction( size_t index ) +bool Control::Impl::AccessibleImpl::DoAction(size_t index) { - std::string actionName = GetActionName( index ); - return self.DoAction( actionName, {} ); + std::string actionName = GetActionName(index); + return self.DoAction(actionName, {}); } bool Control::Impl::AccessibleImpl::DoAction(const std::string& name) { - return self.DoAction( name, {} ); + return self.DoAction(name, {}); } -bool Control::Impl::AccessibleImpl::DoGesture(const Dali::Accessibility::GestureInfo &gestureInfo) +bool Control::Impl::AccessibleImpl::DoGesture(const Dali::Accessibility::GestureInfo& gestureInfo) { auto control = Dali::Toolkit::Control::DownCast(self); - Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control ); - Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl ); + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); - if (!controlImpl.mAccessibilityDoGestureSignal.Empty()) { - auto ret = std::make_pair(gestureInfo, false); - controlImpl.mAccessibilityDoGestureSignal.Emit(ret); - return ret.second; + if(!controlImpl.mAccessibilityDoGestureSignal.Empty()) + { + auto ret = std::make_pair(gestureInfo, false); + controlImpl.mAccessibilityDoGestureSignal.Emit(ret); + return ret.second; } return false; @@ -2255,18 +2244,18 @@ std::vector Control::Impl::AccessibleImpl::GetRel { auto control = Dali::Toolkit::Control::DownCast(self); - Internal::Control& internalControl = Toolkit::Internal::GetImplementation( control ); - Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get( internalControl ); + Internal::Control& internalControl = Toolkit::Internal::GetImplementation(control); + Internal::Control::Impl& controlImpl = Internal::Control::Impl::Get(internalControl); std::vector ret; - auto &v = controlImpl.mAccessibilityRelations; - for (auto i = 0u; i < v.size(); ++i) + auto& v = controlImpl.mAccessibilityRelations; + for(auto i = 0u; i < v.size(); ++i) { - if ( v[i].empty() ) + if(v[i].empty()) continue; - ret.emplace_back( Accessibility::Relation{ static_cast(i), v[i] } ); + ret.emplace_back(Accessibility::Relation{static_cast(i), v[i]}); } return ret; @@ -2279,7 +2268,7 @@ void Control::Impl::AccessibleImpl::EnsureChildVisible(Actor child) void Control::Impl::AccessibleImpl::EnsureSelfVisible() { auto parent = dynamic_cast(GetParent()); - if (parent) + if(parent) { parent->EnsureChildVisible(self); } @@ -2295,40 +2284,40 @@ Property::Index Control::Impl::AccessibleImpl::GetDescriptionPropertyIndex() return Property::INVALID_INDEX; } -void Control::Impl::PositionOrSizeChangedCallback( PropertyNotification &p ) +void Control::Impl::PositionOrSizeChangedCallback(PropertyNotification& p) { auto self = Dali::Actor::DownCast(p.GetTarget()); - if (Dali::Accessibility::IsUp() && !self.GetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED ).Get< bool >()) + if(Dali::Accessibility::IsUp() && !self.GetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ANIMATED).Get()) { - auto extents = DevelActor::CalculateScreenExtents( self ); - Dali::Accessibility::Accessible::Get( self )->EmitBoundsChanged( extents ); + auto extents = DevelActor::CalculateScreenExtents(self); + Dali::Accessibility::Accessible::Get(self)->EmitBoundsChanged(extents); } } -void Control::Impl::CulledChangedCallback( PropertyNotification &p) +void Control::Impl::CulledChangedCallback(PropertyNotification& p) { - if (Dali::Accessibility::IsUp()) + if(Dali::Accessibility::IsUp()) { auto self = Dali::Actor::DownCast(p.GetTarget()); - Dali::Accessibility::Accessible::Get(self)->EmitShowing( !self.GetProperty( DevelActor::Property::CULLED ).Get() ); + Dali::Accessibility::Accessible::Get(self)->EmitShowing(!self.GetProperty(DevelActor::Property::CULLED).Get()); } } void Control::Impl::AccessibilityRegister() { - if (!accessibilityNotificationSet) + if(!accessibilityNotificationSet) { - accessibilityNotificationPosition = mControlImpl.Self().AddPropertyNotification( Actor::Property::POSITION, StepCondition( 0.01f ) ); - accessibilityNotificationPosition.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); - accessibilityNotificationPosition.NotifySignal().Connect( &Control::Impl::PositionOrSizeChangedCallback ); + accessibilityNotificationPosition = mControlImpl.Self().AddPropertyNotification(Actor::Property::POSITION, StepCondition(0.01f)); + accessibilityNotificationPosition.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); + accessibilityNotificationPosition.NotifySignal().Connect(&Control::Impl::PositionOrSizeChangedCallback); - accessibilityNotificationSize = mControlImpl.Self().AddPropertyNotification( Actor::Property::SIZE, StepCondition( 0.01f ) ); - accessibilityNotificationSize.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); - accessibilityNotificationSize.NotifySignal().Connect( &Control::Impl::PositionOrSizeChangedCallback ); + accessibilityNotificationSize = mControlImpl.Self().AddPropertyNotification(Actor::Property::SIZE, StepCondition(0.01f)); + accessibilityNotificationSize.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); + accessibilityNotificationSize.NotifySignal().Connect(&Control::Impl::PositionOrSizeChangedCallback); - accessibilityNotificationCulled = mControlImpl.Self().AddPropertyNotification( DevelActor::Property::CULLED, LessThanCondition( 0.5f ) ); - accessibilityNotificationCulled.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); - accessibilityNotificationCulled.NotifySignal().Connect( &Control::Impl::CulledChangedCallback ); + accessibilityNotificationCulled = mControlImpl.Self().AddPropertyNotification(DevelActor::Property::CULLED, LessThanCondition(0.5f)); + accessibilityNotificationCulled.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); + accessibilityNotificationCulled.NotifySignal().Connect(&Control::Impl::CulledChangedCallback); accessibilityNotificationSet = true; } @@ -2336,12 +2325,12 @@ void Control::Impl::AccessibilityRegister() void Control::Impl::AccessibilityDeregister() { - if (accessibilityNotificationSet) + if(accessibilityNotificationSet) { accessibilityNotificationPosition = {}; - accessibilityNotificationSize = {}; - accessibilityNotificationCulled = {}; - accessibilityNotificationSet = false; + accessibilityNotificationSize = {}; + accessibilityNotificationCulled = {}; + accessibilityNotificationSet = false; } } diff --git a/dali-toolkit/internal/controls/control/control-debug.cpp b/dali-toolkit/internal/controls/control/control-debug.cpp index bcb69ac..9a9c08f 100644 --- a/dali-toolkit/internal/controls/control/control-debug.cpp +++ b/dali-toolkit/internal/controls/control/control-debug.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. @@ -14,16 +14,16 @@ * limitations under the License. */ -#include -#include -#include -#include #include #include #include -#include +#include +#include +#include +#include #include #include +#include #if defined(DEBUG_ENABLED) @@ -33,11 +33,10 @@ namespace Toolkit { namespace Internal { - class JsonWriter { public: - JsonWriter( Property::Value& value ) + JsonWriter(Property::Value& value) : mValue(value) { } @@ -45,18 +44,18 @@ public: std::string ToString() { std::ostringstream stream; - ToStream( stream ); + ToStream(stream); return stream.str(); } - void ToStream( std::ostream& stream ) + void ToStream(std::ostream& stream) { - switch( mValue.GetType() ) + switch(mValue.GetType()) { case Dali::Property::BOOLEAN: { auto value = mValue.Get(); - stream << ((value)?"true":"false"); + stream << ((value) ? "true" : "false"); break; } case Dali::Property::FLOAT: @@ -91,9 +90,9 @@ public: { auto matrix = mValue.Get(); stream << "["; - for( int i=0; i<9; ++i ) + for(int i = 0; i < 9; ++i) { - if( i>0) + if(i > 0) stream << ","; stream << matrix.AsFloat()[i]; } @@ -104,9 +103,9 @@ public: { auto matrix = mValue.Get(); stream << "["; - for( int i=0; i<16; ++i ) + for(int i = 0; i < 16; ++i) { - if( i>0) + if(i > 0) stream << ","; stream << matrix.AsFloat()[i]; } @@ -135,13 +134,13 @@ public: { auto array = mValue.GetArray(); stream << "[ "; - if( array ) + if(array) { - for( Property::Array::SizeType i=0; iSize(); ++i) + for(Property::Array::SizeType i = 0; i < array->Size(); ++i) { - if( i>0) + if(i > 0) stream << ", "; - auto outValue = JsonWriter( array->GetElementAt(i) ); + auto outValue = JsonWriter(array->GetElementAt(i)); stream << outValue.ToString(); } } @@ -152,14 +151,14 @@ public: { auto map = mValue.GetMap(); stream << "{ "; - if( map ) + if(map) { - for( Property::Map::SizeType i=0; iCount(); ++i) + for(Property::Map::SizeType i = 0; i < map->Count(); ++i) { - if( i>0) + if(i > 0) stream << ", "; - auto key = map->GetKeyAt( i ); - auto outValue = JsonWriter( map->GetValue(i) ); + auto key = map->GetKeyAt(i); + auto outValue = JsonWriter(map->GetValue(i)); stream << '\"' << key << "\":"; stream << outValue.ToString(); } @@ -183,32 +182,33 @@ public: Property::Value& mValue; }; -static std::ostream& operator<<( std::ostream& o, JsonWriter& value ) +static std::ostream& operator<<(std::ostream& o, JsonWriter& value) { value.ToStream(o); return o; } - -std::ostream& operator<<( std::ostream& o, const RegisteredVisual& registeredVisual ) +std::ostream& operator<<(std::ostream& o, const RegisteredVisual& registeredVisual) { - o << "{\n" << "\"index\":" << registeredVisual.index << ",\n"; - o << "\"enabled\":" << (registeredVisual.enabled?"true":"false") << ",\n"; - o << "\"pending\":" << (registeredVisual.pending?"true":"false") << ",\n"; + o << "{\n" + << "\"index\":" << registeredVisual.index << ",\n"; + o << "\"enabled\":" << (registeredVisual.enabled ? "true" : "false") << ",\n"; + o << "\"pending\":" << (registeredVisual.pending ? "true" : "false") << ",\n"; Property::Map map; - registeredVisual.visual.CreatePropertyMap( map ); + registeredVisual.visual.CreatePropertyMap(map); o << "\"visual\": {\n\"name\":\"" << registeredVisual.visual.GetName() << "\",\n"; - o << map << "}\n" << "\n}\n"; + o << map << "}\n" + << "\n}\n"; return o; } -std::ostream& operator<<( std::ostream& o, const RegisteredVisualContainer& visualContainer ) +std::ostream& operator<<(std::ostream& o, const RegisteredVisualContainer& visualContainer) { - o<<"[\n"; + o << "[\n"; - bool first=true; - for( auto&& elem : visualContainer ) + bool first = true; + for(auto&& elem : visualContainer) { if(!first) { @@ -216,132 +216,132 @@ std::ostream& operator<<( std::ostream& o, const RegisteredVisualContainer& visu } first = false; - o<<*elem<<"\n"; + o << *elem << "\n"; } - o<<"]\n"; + o << "]\n"; return o; } -std::ostream& DumpProperty( std::ostream& o, Property::Index index, Handle handle ) +std::ostream& DumpProperty(std::ostream& o, Property::Index index, Handle handle) { - auto propertyValue = handle.GetProperty( index ); + auto propertyValue = handle.GetProperty(index); auto jsonPropertyValue = JsonWriter(propertyValue); o << "{\n"; o << "\"index\":" << index << ",\n"; - o << "\"name\":\"" << handle.GetPropertyName( index ) << "\",\n"; + o << "\"name\":\"" << handle.GetPropertyName(index) << "\",\n"; o << "\"value\":" << jsonPropertyValue << "\n"; o << "}"; return o; } - -std::ostream& DumpPropertiesWithPredicate( std::ostream& o, Dali::Handle handle, - Property::IndexContainer& indices, std::function predicate) +std::ostream& DumpPropertiesWithPredicate(std::ostream& o, Dali::Handle handle, Property::IndexContainer& indices, std::function predicate) { bool first = true; - for( auto index : indices ) + for(auto index : indices) { - if( predicate( index ) ) + if(predicate(index)) { - if( !first ) + if(!first) { o << ","; } o << std::endl; first = false; - DumpProperty( o, index, handle ); + DumpProperty(o, index, handle); } } return o; } -std::ostream& DumpProperties( std::ostream& o, Handle handle ) +std::ostream& DumpProperties(std::ostream& o, Handle handle) { Property::IndexContainer indices; - handle.GetPropertyIndices( indices ); + handle.GetPropertyIndices(indices); - auto childPropertiesP = [](int index) -> bool - { - return CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX; - }; - auto propertiesP = [](int index) -> bool - { - return !(CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX); - }; + auto childPropertiesP = [](int index) -> bool { + return CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX; + }; + auto propertiesP = [](int index) -> bool { + return !(CHILD_PROPERTY_REGISTRATION_START_INDEX <= index && index <= CHILD_PROPERTY_REGISTRATION_MAX_INDEX); + }; - o << "\"childProperties\":[\n" ; - DumpPropertiesWithPredicate( o, handle, indices, childPropertiesP ); - o << std::endl << "]," << std::endl; + o << "\"childProperties\":[\n"; + DumpPropertiesWithPredicate(o, handle, indices, childPropertiesP); + o << std::endl + << "]," << std::endl; - o << "\"Properties\":[\n" ; - DumpPropertiesWithPredicate( o, handle, indices, propertiesP ); - o << std::endl << "]" << std::endl; + o << "\"Properties\":[\n"; + DumpPropertiesWithPredicate(o, handle, indices, propertiesP); + o << std::endl + << "]" << std::endl; return o; } -std::string DumpControl( const Internal::Control& control ) +std::string DumpControl(const Internal::Control& control) { - auto& controlData = Internal::Control::Impl::Get( control ); + auto& controlData = Internal::Control::Impl::Get(control); std::ostringstream oss; oss << "{\n "; - const std::string& name = control.Self().GetProperty< std::string >( Dali::Actor::Property::NAME ); - if( ! name.empty() ) + const std::string& name = control.Self().GetProperty(Dali::Actor::Property::NAME); + if(!name.empty()) { oss << "\"name\":\"" << name << "\",\n"; } - oss << "\"id\":\"" << control.Self().GetProperty< int >( Actor::Property::ID ) << "\",\n"; - oss << "\"registeredVisuals\":\n" << controlData.mVisuals << ",\n"; - oss << "\"removeVisuals\":\n" << controlData.mRemoveVisuals << ",\n"; + oss << "\"id\":\"" << control.Self().GetProperty(Actor::Property::ID) << "\",\n"; + oss << "\"registeredVisuals\":\n" + << controlData.mVisuals << ",\n"; + oss << "\"removeVisuals\":\n" + << controlData.mRemoveVisuals << ",\n"; oss << "\"rendererCount\":" << control.Self().GetRendererCount() << ",\n"; oss << "\"properties\":\n{\n"; - DumpProperties( oss, control.Self() ) << "}\n"; + DumpProperties(oss, control.Self()) << "}\n"; oss << "}\n"; return oss.str(); } -std::string DumpActor( Actor actor ) +std::string DumpActor(Actor actor) { std::ostringstream oss; oss << "{\n "; - const std::string& name = actor.GetProperty< std::string >( Dali::Actor::Property::NAME ); - if( ! name.empty() ) + const std::string& name = actor.GetProperty(Dali::Actor::Property::NAME); + if(!name.empty()) { oss << "\"name\":\"" << name << "\",\n"; } - oss << "\"id\":\"" << actor.GetProperty< int >( Actor::Property::ID ) << "\",\n"; + oss << "\"id\":\"" << actor.GetProperty(Actor::Property::ID) << "\",\n"; oss << "\"rendererCount\":" << actor.GetRendererCount() << ",\n"; oss << "\"properties\":\n{\n"; - Toolkit::Internal::DumpProperties( oss, actor ) << "}\n"; + Toolkit::Internal::DumpProperties(oss, actor) << "}\n"; oss << "}\n"; return oss.str(); } -void DumpControlHierarchy( std::ostream& o, Actor actor ) +void DumpControlHierarchy(std::ostream& o, Actor actor) { - auto control = Toolkit::Control::DownCast( actor ); + auto control = Toolkit::Control::DownCast(actor); o << "{\n"; - if( control ) + if(control) { - o << "\"Control\":" << DumpControl( Toolkit::Internal::GetImplementation( control ) ); + o << "\"Control\":" << DumpControl(Toolkit::Internal::GetImplementation(control)); } else { - o << "\"Actor\":" << DumpActor( actor ); + o << "\"Actor\":" << DumpActor(actor); } o << ",\n\"children\":[\n"; - bool first=true; - for( auto count=actor.GetChildCount(), i=0u; i vertices; - vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) ); + Vector vertices; + vertices.Reserve((gridWidth + 1) * (gridHeight + 1)); - for( int y = 0; y < gridHeight + 1; ++y ) + for(int y = 0; y < gridHeight + 1; ++y) { - for( int x = 0; x < gridWidth + 1; ++x ) + for(int x = 0; x < gridWidth + 1; ++x) { - vertices.PushBack( Vector2( (float)x/gridWidth - 0.5f, (float)y/gridHeight - 0.5f) ); + vertices.PushBack(Vector2((float)x / gridWidth - 0.5f, (float)y / gridHeight - 0.5f)); } } // Create indices - Vector< unsigned short > indices; - indices.Reserve( (gridWidth+2)*gridHeight*2 - 2); + Vector indices; + indices.Reserve((gridWidth + 2) * gridHeight * 2 - 2); - for( unsigned int row = 0u; row < gridHeight; ++row ) + for(unsigned int row = 0u; row < gridHeight; ++row) { - unsigned int rowStartIndex = row*(gridWidth+1u); - unsigned int nextRowStartIndex = rowStartIndex + gridWidth +1u; + unsigned int rowStartIndex = row * (gridWidth + 1u); + unsigned int nextRowStartIndex = rowStartIndex + gridWidth + 1u; - if( row != 0u ) // degenerate index on non-first row + if(row != 0u) // degenerate index on non-first row { - indices.PushBack( rowStartIndex ); + indices.PushBack(rowStartIndex); } - for( unsigned int column = 0u; column < gridWidth+1u; column++) // main strip + for(unsigned int column = 0u; column < gridWidth + 1u; column++) // main strip { - indices.PushBack( rowStartIndex + column); - indices.PushBack( nextRowStartIndex + column); + indices.PushBack(rowStartIndex + column); + indices.PushBack(nextRowStartIndex + column); } - if( row != gridHeight-1u ) // degenerate index on non-last row + if(row != gridHeight - 1u) // degenerate index on non-last row { - indices.PushBack( nextRowStartIndex + gridWidth ); + indices.PushBack(nextRowStartIndex + gridWidth); } } Property::Map vertexFormat; - vertexFormat[ "aPosition" ] = Property::VECTOR2; - VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat ); - if( vertices.Size() > 0 ) + vertexFormat["aPosition"] = Property::VECTOR2; + VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat); + if(vertices.Size() > 0) { - vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() ); + vertexBuffer.SetData(&vertices[0], vertices.Size()); } // Create the geometry object Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( vertexBuffer ); - if( indices.Size() > 0 ) + geometry.AddVertexBuffer(vertexBuffer); + if(indices.Size() > 0) { - geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() ); + geometry.SetIndexBuffer(&indices[0], indices.Size()); } - geometry.SetType( Geometry::TRIANGLE_STRIP ); + geometry.SetType(Geometry::TRIANGLE_STRIP); return geometry; } -Dali::Renderer CreateRenderer( std::string_view vertexSrc, std::string_view fragmentSrc ) +Dali::Renderer CreateRenderer(std::string_view vertexSrc, std::string_view fragmentSrc) { - Dali::Shader shader = Dali::Shader::New( vertexSrc, fragmentSrc ); + Dali::Shader shader = Dali::Shader::New(vertexSrc, fragmentSrc); Dali::Geometry texturedQuadGeometry = Dali::Geometry::New(); - struct VertexPosition { Dali::Vector2 position; }; - struct VertexTexture { Dali::Vector2 texture; }; - - VertexPosition positionArray[] = + struct VertexPosition + { + Dali::Vector2 position; + }; + struct VertexTexture { - { Dali::Vector2( -0.5f, -0.5f ) }, - { Dali::Vector2( 0.5f, -0.5f ) }, - { Dali::Vector2( -0.5f, 0.5f ) }, - { Dali::Vector2( 0.5f, 0.5f ) } + Dali::Vector2 texture; }; - uint32_t numberOfVertices = sizeof(positionArray)/sizeof(VertexPosition); + + VertexPosition positionArray[] = + { + {Dali::Vector2(-0.5f, -0.5f)}, + {Dali::Vector2(0.5f, -0.5f)}, + {Dali::Vector2(-0.5f, 0.5f)}, + {Dali::Vector2(0.5f, 0.5f)}}; + uint32_t numberOfVertices = sizeof(positionArray) / sizeof(VertexPosition); Dali::Property::Map positionVertexFormat; - positionVertexFormat["aPosition"] = Dali::Property::VECTOR2; - Dali::VertexBuffer positionVertices = Dali::VertexBuffer::New( positionVertexFormat ); - positionVertices.SetData( positionArray, numberOfVertices ); - texturedQuadGeometry.AddVertexBuffer( positionVertices ); + positionVertexFormat["aPosition"] = Dali::Property::VECTOR2; + Dali::VertexBuffer positionVertices = Dali::VertexBuffer::New(positionVertexFormat); + positionVertices.SetData(positionArray, numberOfVertices); + texturedQuadGeometry.AddVertexBuffer(positionVertices); - const uint16_t indices[] = { 0, 3, 1, 0, 2, 3 }; - texturedQuadGeometry.SetIndexBuffer ( &indices[0], sizeof( indices )/ sizeof( indices[0] ) ); + const uint16_t indices[] = {0, 3, 1, 0, 2, 3}; + texturedQuadGeometry.SetIndexBuffer(&indices[0], sizeof(indices) / sizeof(indices[0])); - Dali::Renderer renderer = Dali::Renderer::New( texturedQuadGeometry, shader ); + Dali::Renderer renderer = Dali::Renderer::New(texturedQuadGeometry, shader); Dali::TextureSet textureSet = Dali::TextureSet::New(); - renderer.SetTextures( textureSet ); + renderer.SetTextures(textureSet); return renderer; } -Dali::Renderer CreateRenderer( std::string_view vertexSrc, std::string_view fragmentSrc, Dali::Shader::Hint::Value hints, Uint16Pair gridSize ) +Dali::Renderer CreateRenderer(std::string_view vertexSrc, std::string_view fragmentSrc, Dali::Shader::Hint::Value hints, Uint16Pair gridSize) { - Dali::Shader shader = Dali::Shader::New( vertexSrc, fragmentSrc, hints ); + Dali::Shader shader = Dali::Shader::New(vertexSrc, fragmentSrc, hints); - Dali::Geometry gridGeometry = CreateGridGeometry( gridSize ); + Dali::Geometry gridGeometry = CreateGridGeometry(gridSize); - Dali::Renderer renderer = Dali::Renderer::New( gridGeometry, shader ); + Dali::Renderer renderer = Dali::Renderer::New(gridGeometry, shader); Dali::TextureSet textureSet = Dali::TextureSet::New(); - renderer.SetTextures( textureSet ); + renderer.SetTextures(textureSet); return renderer; } -void SetRendererTexture( Dali::Renderer renderer, Dali::Texture texture ) +void SetRendererTexture(Dali::Renderer renderer, Dali::Texture texture) { - if( renderer ) + if(renderer) { Dali::TextureSet textureSet = renderer.GetTextures(); - textureSet.SetTexture( 0u, texture ); + textureSet.SetTexture(0u, texture); } } -void SetRendererTexture( Dali::Renderer renderer, Dali::FrameBuffer frameBuffer ) +void SetRendererTexture(Dali::Renderer renderer, Dali::FrameBuffer frameBuffer) { - if( frameBuffer ) + if(frameBuffer) { Dali::Texture texture = frameBuffer.GetColorTexture(); - SetRendererTexture( renderer, texture ); + SetRendererTexture(renderer, texture); } } diff --git a/dali-toolkit/internal/controls/effects-view/effects-view-impl.cpp b/dali-toolkit/internal/controls/effects-view/effects-view-impl.cpp index bd12e33..2bc36e0 100644 --- a/dali-toolkit/internal/controls/effects-view/effects-view-impl.cpp +++ b/dali-toolkit/internal/controls/effects-view/effects-view-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,83 +19,80 @@ #include "effects-view-impl.h" // EXTERNAL INCLUDES +#include #include #include -#include -#include #include -#include +#include #include +#include #include #include // INTERNAL INCLUDES #include #include -#include +#include +#include #include #include #include -#include -#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - Dali::BaseHandle Create() { return EffectsView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::EffectsView, Toolkit::Control, Create ) -DALI_PROPERTY_REGISTRATION( Toolkit, EffectsView, "effectSize", INTEGER, EFFECT_SIZE ) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, EffectsView, "effectOffset", VECTOR3, EFFECT_OFFSET ) -DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, EffectsView, "effectColor", Color::WHITE, EFFECT_COLOR ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::EffectsView, Toolkit::Control, Create) +DALI_PROPERTY_REGISTRATION(Toolkit, EffectsView, "effectSize", INTEGER, EFFECT_SIZE) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, EffectsView, "effectOffset", VECTOR3, EFFECT_OFFSET) +DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT(Toolkit, EffectsView, "effectColor", Color::WHITE, EFFECT_COLOR) DALI_TYPE_REGISTRATION_END() const Pixel::Format EFFECTS_VIEW_DEFAULT_PIXEL_FORMAT = Pixel::RGBA8888; -const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f; -const Vector4 EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR( 0.0f, 0.0f, 0.0f, 0.0 ); +const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f; +const Vector4 EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR(0.0f, 0.0f, 0.0f, 0.0); const bool EFFECTS_VIEW_REFRESH_ON_DEMAND(false); -const float BLUR_KERNEL0[] = { 12.0f/16.0f, - 2.0f/16.0f, 2.0f/16.0f }; - -const float BLUR_KERNEL1[] = { 8.0f/16.0f, - 4.0f/16.0f, 4.0f/16.0f }; - -const float BLUR_KERNEL2[] = { 6.0f/16.0f, - 2.5f/16.0f, 2.5f/16.0f, - 1.5f/16.0f, 1.5f/16.0f, - 1.0f/16.0f, 1.0f/16.0f }; - -const float BLUR_KERNEL3[] = { 4.0f/16.0f, - 3.0f/16.0f, 2.0f/16.0f, - 2.0f/16.0f, 2.0f/16.0f, - 1.0f/16.0f, 1.0f/16.0f }; - -const float BLUR_KERNEL4[] = { 3.0f/16.0f, - 2.5f/16.0f, 2.5f/16.0f, - 1.75f/16.0f, 1.75f/16.0f, - 1.25f/16.0f, 1.25f/16.0f, - 1.0f/16.0f, 1.0f/16.0f }; - +// clang-format off +const float BLUR_KERNEL0[] = {12.0f/16.0f, + 2.0f/16.0f, 2.0f/16.0f}; + +const float BLUR_KERNEL1[] = {8.0f/16.0f, + 4.0f/16.0f, 4.0f/16.0f }; + +const float BLUR_KERNEL2[] = {6.0f/16.0f, + 2.5f/16.0f, 2.5f/16.0f, + 1.5f/16.0f, 1.5f/16.0f, + 1.0f/16.0f, 1.0f/16.0f}; + +const float BLUR_KERNEL3[] = {4.0f/16.0f, + 3.0f/16.0f, 2.0f/16.0f, + 2.0f/16.0f, 2.0f/16.0f, + 1.0f/16.0f, 1.0f/16.0f}; + +const float BLUR_KERNEL4[] = {3.0f/16.0f, + 2.5f/16.0f, 2.5f/16.0f, + 1.75f/16.0f, 1.75f/16.0f, + 1.25f/16.0f, 1.25f/16.0f, + 1.0f/16.0f, 1.0f/16.0f}; +// clang-format on } // namespace Toolkit::EffectsView EffectsView::New() { EffectsView* effectsView = new EffectsView; - Toolkit::EffectsView handle = Toolkit::EffectsView( *effectsView ); + Toolkit::EffectsView handle = Toolkit::EffectsView(*effectsView); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -105,16 +102,16 @@ Toolkit::EffectsView EffectsView::New() } EffectsView::EffectsView() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mChildrenRoot(Actor::New()), - mBackgroundColor( EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR ), - mTargetSize( Vector2::ZERO ), - mLastSize( Vector2::ZERO ), + mBackgroundColor(EFFECTS_VIEW_DEFAULT_BACKGROUND_COLOR), + mTargetSize(Vector2::ZERO), + mLastSize(Vector2::ZERO), mEffectSize(0), - mEffectType( Toolkit::EffectsView::INVALID_TYPE ), - mPixelFormat( EFFECTS_VIEW_DEFAULT_PIXEL_FORMAT ), - mEnabled( false ), - mRefreshOnDemand( EFFECTS_VIEW_REFRESH_ON_DEMAND ) + mEffectType(Toolkit::EffectsView::INVALID_TYPE), + mPixelFormat(EFFECTS_VIEW_DEFAULT_PIXEL_FORMAT), + mEnabled(false), + mRefreshOnDemand(EFFECTS_VIEW_REFRESH_ON_DEMAND) { } @@ -123,27 +120,27 @@ EffectsView::~EffectsView() RemoveFilters(); } -void EffectsView::SetType( Toolkit::EffectsView::EffectType type ) +void EffectsView::SetType(Toolkit::EffectsView::EffectType type) { - if( mEffectType != type ) + if(mEffectType != type) { RemoveFilters(); Actor self = Self(); - switch( type ) + switch(type) { case Toolkit::EffectsView::DROP_SHADOW: { - mFilters.PushBack( new SpreadFilter ); - mFilters.PushBack( new BlurTwoPassFilter ); + mFilters.PushBack(new SpreadFilter); + mFilters.PushBack(new BlurTwoPassFilter); break; } case Toolkit::EffectsView::EMBOSS: { - mFilters.PushBack( new SpreadFilter ); - mFilters.PushBack( new EmbossFilter ); - mFilters.PushBack( new BlurTwoPassFilter ); + mFilters.PushBack(new SpreadFilter); + mFilters.PushBack(new EmbossFilter); + mFilters.PushBack(new BlurTwoPassFilter); break; } default: @@ -174,7 +171,7 @@ void EffectsView::Disable() // stop render tasks processing RemoveRenderTasks(); mLastSize = Vector2::ZERO; // Ensure resources are reallocated on subsequent enable - mEnabled = false; + mEnabled = false; } void EffectsView::Refresh() @@ -182,19 +179,19 @@ void EffectsView::Refresh() RefreshRenderTasks(); } -void EffectsView::SetRefreshOnDemand( bool onDemand ) +void EffectsView::SetRefreshOnDemand(bool onDemand) { mRefreshOnDemand = onDemand; RefreshRenderTasks(); } -void EffectsView::SetPixelFormat( Pixel::Format pixelFormat ) +void EffectsView::SetPixelFormat(Pixel::Format pixelFormat) { mPixelFormat = pixelFormat; } -void EffectsView::SetBackgroundColor( const Vector4& color ) +void EffectsView::SetBackgroundColor(const Vector4& color) { mBackgroundColor = color; } @@ -204,21 +201,21 @@ Vector4 EffectsView::GetBackgroundColor() const return mBackgroundColor; } -void EffectsView::SetEffectSize( int effectSize ) +void EffectsView::SetEffectSize(int effectSize) { mEffectSize = effectSize; - if( mEnabled ) + if(mEnabled) { - const size_t numFilters( mFilters.Size() ); - for( size_t i = 0; i < numFilters; ++i ) + const size_t numFilters(mFilters.Size()); + for(size_t i = 0; i < numFilters; ++i) { mFilters[i]->Disable(); } SetupFilters(); - for( size_t i = 0; i < numFilters; ++i ) + for(size_t i = 0; i < numFilters; ++i) { mFilters[i]->Enable(); } @@ -234,13 +231,13 @@ int EffectsView::GetEffectSize() void EffectsView::OnInitialize() { CustomActor self = Self(); - mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - self.Add( mChildrenRoot ); + mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + self.Add(mChildrenRoot); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } void EffectsView::OnSizeSet(const Vector3& targetSize) @@ -250,140 +247,165 @@ void EffectsView::OnSizeSet(const Vector3& targetSize) // if we are already on stage, need to update render target sizes now to reflect the new size of this actor if(mEnabled) { - if( mLastSize != Vector2::ZERO ) + if(mLastSize != Vector2::ZERO) { Disable(); } Enable(); } - mChildrenRoot.SetProperty( Actor::Property::SIZE, targetSize ); + mChildrenRoot.SetProperty(Actor::Property::SIZE, targetSize); - Control::OnSizeSet( targetSize ); + Control::OnSizeSet(targetSize); } -void EffectsView::OnSceneConnection( int depth ) +void EffectsView::OnSceneConnection(int depth) { - Actor self( Self() ); + Actor self(Self()); // Create renderers - mRendererPostFilter = CreateRenderer( SHADER_EFFECTS_VIEW_VERT, - SHADER_EFFECTS_VIEW_FRAG ); - mRendererPostFilter.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT ); - self.AddRenderer( mRendererPostFilter ); + mRendererPostFilter = CreateRenderer(SHADER_EFFECTS_VIEW_VERT, + SHADER_EFFECTS_VIEW_FRAG); + mRendererPostFilter.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT); + self.AddRenderer(mRendererPostFilter); - mRendererForChildren = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE ); - mRendererForChildren.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + 1 ); - self.AddRenderer( mRendererForChildren ); + mRendererForChildren = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE); + mRendererForChildren.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + 1); + self.AddRenderer(mRendererForChildren); Enable(); - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } void EffectsView::OnSceneDisconnection() { - Actor self( Self() ); + Actor self(Self()); Disable(); - const size_t numFilters( mFilters.Size() ); - for( size_t i = 0; i < numFilters; ++i ) + const size_t numFilters(mFilters.Size()); + for(size_t i = 0; i < numFilters; ++i) { mFilters[i]->Disable(); } // Remove renderers - self.RemoveRenderer( mRendererForChildren ); + self.RemoveRenderer(mRendererForChildren); mRendererForChildren.Reset(); - self.RemoveRenderer( mRendererPostFilter ); + self.RemoveRenderer(mRendererPostFilter); mRendererPostFilter.Reset(); Control::OnSceneDisconnection(); } -void EffectsView::OnChildAdd( Actor& child ) +void EffectsView::OnChildAdd(Actor& child) { - if( child != mChildrenRoot && child != mCameraForChildren ) + if(child != mChildrenRoot && child != mCameraForChildren) { - mChildrenRoot.Add( child ); + mChildrenRoot.Add(child); } - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void EffectsView::OnChildRemove( Actor& child ) +void EffectsView::OnChildRemove(Actor& child) { - mChildrenRoot.Remove( child ); + mChildrenRoot.Remove(child); - Control::OnChildRemove( child ); + Control::OnChildRemove(child); } void EffectsView::SetupFilters() { - switch( mEffectType ) + switch(mEffectType) { case Toolkit::EffectsView::DROP_SHADOW: { - SpreadFilter* spreadFilter = static_cast< SpreadFilter* >( mFilters[0] ); - spreadFilter->SetInputTexture( mFrameBufferForChildren.GetColorTexture() ); - spreadFilter->SetOutputFrameBuffer( mFrameBufferPostFilter ); - spreadFilter->SetRootActor( mChildrenRoot ); - spreadFilter->SetBackgroundColor( mBackgroundColor ); - spreadFilter->SetPixelFormat( mPixelFormat ); - spreadFilter->SetSize( mTargetSize ); - spreadFilter->SetSpread( mEffectSize ); - - BlurTwoPassFilter* blurFilter = static_cast< BlurTwoPassFilter* >( mFilters[1] ); - blurFilter->SetInputTexture( mFrameBufferPostFilter.GetColorTexture() ); - blurFilter->SetOutputFrameBuffer( mFrameBufferPostFilter ); - blurFilter->SetRootActor( mChildrenRoot ); - blurFilter->SetBackgroundColor( mBackgroundColor ); - blurFilter->SetPixelFormat( mPixelFormat ); - blurFilter->SetSize( mTargetSize ); + SpreadFilter* spreadFilter = static_cast(mFilters[0]); + spreadFilter->SetInputTexture(mFrameBufferForChildren.GetColorTexture()); + spreadFilter->SetOutputFrameBuffer(mFrameBufferPostFilter); + spreadFilter->SetRootActor(mChildrenRoot); + spreadFilter->SetBackgroundColor(mBackgroundColor); + spreadFilter->SetPixelFormat(mPixelFormat); + spreadFilter->SetSize(mTargetSize); + spreadFilter->SetSpread(mEffectSize); + + BlurTwoPassFilter* blurFilter = static_cast(mFilters[1]); + blurFilter->SetInputTexture(mFrameBufferPostFilter.GetColorTexture()); + blurFilter->SetOutputFrameBuffer(mFrameBufferPostFilter); + blurFilter->SetRootActor(mChildrenRoot); + blurFilter->SetBackgroundColor(mBackgroundColor); + blurFilter->SetPixelFormat(mPixelFormat); + blurFilter->SetSize(mTargetSize); const float* kernel(NULL); - size_t kernelSize(0); - switch( mEffectSize ) + size_t kernelSize(0); + switch(mEffectSize) { - case 4: { kernel = BLUR_KERNEL4; kernelSize = sizeof(BLUR_KERNEL4)/sizeof(BLUR_KERNEL4[0]); break; } - case 3: { kernel = BLUR_KERNEL3; kernelSize = sizeof(BLUR_KERNEL3)/sizeof(BLUR_KERNEL3[0]); break; } - case 2: { kernel = BLUR_KERNEL2; kernelSize = sizeof(BLUR_KERNEL2)/sizeof(BLUR_KERNEL2[0]); break; } - case 1: { kernel = BLUR_KERNEL1; kernelSize = sizeof(BLUR_KERNEL1)/sizeof(BLUR_KERNEL1[0]); break; } + case 4: + { + kernel = BLUR_KERNEL4; + kernelSize = sizeof(BLUR_KERNEL4) / sizeof(BLUR_KERNEL4[0]); + break; + } + case 3: + { + kernel = BLUR_KERNEL3; + kernelSize = sizeof(BLUR_KERNEL3) / sizeof(BLUR_KERNEL3[0]); + break; + } + case 2: + { + kernel = BLUR_KERNEL2; + kernelSize = sizeof(BLUR_KERNEL2) / sizeof(BLUR_KERNEL2[0]); + break; + } + case 1: + { + kernel = BLUR_KERNEL1; + kernelSize = sizeof(BLUR_KERNEL1) / sizeof(BLUR_KERNEL1[0]); + break; + } case 0: - default: { kernel = BLUR_KERNEL0; kernelSize = sizeof(BLUR_KERNEL0)/sizeof(BLUR_KERNEL0[0]); break; } + default: + { + kernel = BLUR_KERNEL0; + kernelSize = sizeof(BLUR_KERNEL0) / sizeof(BLUR_KERNEL0[0]); + break; + } } - blurFilter->CreateKernel( kernel, kernelSize ); + blurFilter->CreateKernel(kernel, kernelSize); break; } case Toolkit::EffectsView::EMBOSS: { - SpreadFilter* spreadFilter = static_cast< SpreadFilter* >( mFilters[0] ); - spreadFilter->SetInputTexture( mFrameBufferForChildren.GetColorTexture() ); - spreadFilter->SetOutputFrameBuffer( mFrameBufferPostFilter ); - spreadFilter->SetRootActor( mChildrenRoot ); - spreadFilter->SetBackgroundColor( mBackgroundColor ); - spreadFilter->SetPixelFormat( Pixel::RGBA8888 ); - spreadFilter->SetSize( mTargetSize ); - spreadFilter->SetSpread( mEffectSize ); - - EmbossFilter* embossFilter = static_cast< EmbossFilter* >( mFilters[1] ); - embossFilter->SetInputTexture( mFrameBufferPostFilter.GetColorTexture() ); - embossFilter->SetOutputFrameBuffer( mFrameBufferPostFilter ); - embossFilter->SetRootActor( mChildrenRoot ); - embossFilter->SetBackgroundColor( mBackgroundColor ); - embossFilter->SetPixelFormat( Pixel::RGBA8888 ); - embossFilter->SetSize( mTargetSize ); - - BlurTwoPassFilter* blurFilter = static_cast< BlurTwoPassFilter* >( mFilters[2] ); - blurFilter->SetInputTexture( mFrameBufferPostFilter.GetColorTexture() ); - blurFilter->SetOutputFrameBuffer( mFrameBufferPostFilter ); - blurFilter->SetRootActor( mChildrenRoot ); - blurFilter->SetBackgroundColor( Vector4( 0.5f, 0.5f, 0.5f, 0.0 ) ); - blurFilter->SetPixelFormat( Pixel::RGBA8888 ); - blurFilter->SetSize( mTargetSize ); - blurFilter->CreateKernel( BLUR_KERNEL0, sizeof(BLUR_KERNEL0)/sizeof(BLUR_KERNEL0[0]) ); + SpreadFilter* spreadFilter = static_cast(mFilters[0]); + spreadFilter->SetInputTexture(mFrameBufferForChildren.GetColorTexture()); + spreadFilter->SetOutputFrameBuffer(mFrameBufferPostFilter); + spreadFilter->SetRootActor(mChildrenRoot); + spreadFilter->SetBackgroundColor(mBackgroundColor); + spreadFilter->SetPixelFormat(Pixel::RGBA8888); + spreadFilter->SetSize(mTargetSize); + spreadFilter->SetSpread(mEffectSize); + + EmbossFilter* embossFilter = static_cast(mFilters[1]); + embossFilter->SetInputTexture(mFrameBufferPostFilter.GetColorTexture()); + embossFilter->SetOutputFrameBuffer(mFrameBufferPostFilter); + embossFilter->SetRootActor(mChildrenRoot); + embossFilter->SetBackgroundColor(mBackgroundColor); + embossFilter->SetPixelFormat(Pixel::RGBA8888); + embossFilter->SetSize(mTargetSize); + + BlurTwoPassFilter* blurFilter = static_cast(mFilters[2]); + blurFilter->SetInputTexture(mFrameBufferPostFilter.GetColorTexture()); + blurFilter->SetOutputFrameBuffer(mFrameBufferPostFilter); + blurFilter->SetRootActor(mChildrenRoot); + blurFilter->SetBackgroundColor(Vector4(0.5f, 0.5f, 0.5f, 0.0)); + blurFilter->SetPixelFormat(Pixel::RGBA8888); + blurFilter->SetSize(mTargetSize); + blurFilter->CreateKernel(BLUR_KERNEL0, sizeof(BLUR_KERNEL0) / sizeof(BLUR_KERNEL0[0])); break; } @@ -401,19 +423,19 @@ void EffectsView::AllocateResources() mLastSize = mTargetSize; SetupCameras(); - Actor self( Self() ); + Actor self(Self()); - mFrameBufferForChildren = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture textureForChildren = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mFrameBufferForChildren.AttachColorTexture( textureForChildren ); + mFrameBufferForChildren = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture textureForChildren = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mFrameBufferForChildren.AttachColorTexture(textureForChildren); - SetRendererTexture( mRendererForChildren, textureForChildren ); + SetRendererTexture(mRendererForChildren, textureForChildren); - mFrameBufferPostFilter = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture texturePostFilter = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mFrameBufferPostFilter.AttachColorTexture( texturePostFilter ); + mFrameBufferPostFilter = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture texturePostFilter = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mFrameBufferPostFilter.AttachColorTexture(texturePostFilter); - SetRendererTexture( mRendererPostFilter, texturePostFilter ); + SetRendererTexture(mRendererPostFilter, texturePostFilter); SetupFilters(); } @@ -421,30 +443,30 @@ void EffectsView::AllocateResources() void EffectsView::SetupCameras() { - if( !mCameraForChildren ) + if(!mCameraForChildren) { // Create a camera for the children render, corresponding to its render target size mCameraForChildren = CameraActor::New(mTargetSize); - mCameraForChildren.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mCameraForChildren.SetInvertYAxis( true ); - Self().Add( mCameraForChildren ); + mCameraForChildren.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mCameraForChildren.SetInvertYAxis(true); + Self().Add(mCameraForChildren); } else { // place the camera for the children render, corresponding to its render target size - const float cameraPosScale( 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f) ); + const float cameraPosScale(0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)); mCameraForChildren.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW); mCameraForChildren.SetNearClippingPlane(1.0f); mCameraForChildren.SetAspectRatio(mTargetSize.width / mTargetSize.height); mCameraForChildren.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor - mCameraForChildren.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, mTargetSize.height * cameraPosScale ) ); - mCameraForChildren.SetProperty( Actor::Property::POSITION_Z, mTargetSize.height * cameraPosScale ); + mCameraForChildren.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosScale)); + mCameraForChildren.SetProperty(Actor::Property::POSITION_Z, mTargetSize.height * cameraPosScale); } } void EffectsView::CreateRenderTasks() { - if( mTargetSize == Vector2::ZERO ) + if(mTargetSize == Vector2::ZERO) { return; } @@ -452,18 +474,18 @@ void EffectsView::CreateRenderTasks() // create render task to render our child actors to offscreen buffer mRenderTaskForChildren = taskList.CreateTask(); - mRenderTaskForChildren.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForChildren.SetSourceActor( mChildrenRoot ); + mRenderTaskForChildren.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForChildren.SetSourceActor(mChildrenRoot); mRenderTaskForChildren.SetExclusive(true); - mRenderTaskForChildren.SetInputEnabled( false ); - mRenderTaskForChildren.SetClearColor( mBackgroundColor ); - mRenderTaskForChildren.SetClearEnabled( true ); - mRenderTaskForChildren.SetFrameBuffer( mFrameBufferForChildren ); + mRenderTaskForChildren.SetInputEnabled(false); + mRenderTaskForChildren.SetClearColor(mBackgroundColor); + mRenderTaskForChildren.SetClearEnabled(true); + mRenderTaskForChildren.SetFrameBuffer(mFrameBufferForChildren); mRenderTaskForChildren.SetCameraActor(mCameraForChildren); // use camera that covers render target exactly // Enable image filters - const size_t numFilters( mFilters.Size() ); - for( size_t i = 0; i < numFilters; ++i ) + const size_t numFilters(mFilters.Size()); + for(size_t i = 0; i < numFilters; ++i) { mFilters[i]->Enable(); } @@ -471,7 +493,7 @@ void EffectsView::CreateRenderTasks() void EffectsView::RemoveRenderTasks() { - if( mTargetSize == Vector2::ZERO ) + if(mTargetSize == Vector2::ZERO) { return; } @@ -480,8 +502,8 @@ void EffectsView::RemoveRenderTasks() taskList.RemoveTask(mRenderTaskForChildren); - const size_t numFilters( mFilters.Size() ); - for( size_t i = 0; i < numFilters; ++i ) + const size_t numFilters(mFilters.Size()); + for(size_t i = 0; i < numFilters; ++i) { mFilters[i]->Disable(); } @@ -491,13 +513,13 @@ void EffectsView::RefreshRenderTasks() { RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); - if( mRenderTaskForChildren ) + if(mRenderTaskForChildren) { - mRenderTaskForChildren.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForChildren.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } - const size_t numFilters( mFilters.Size() ); - for( size_t i = 0; i < numFilters; ++i ) + const size_t numFilters(mFilters.Size()); + for(size_t i = 0; i < numFilters; ++i) { mFilters[i]->Refresh(); } @@ -505,28 +527,28 @@ void EffectsView::RefreshRenderTasks() void EffectsView::RemoveFilters() { - const size_t numFilters( mFilters.Size() ); - for( size_t i = 0; i < numFilters; ++i ) + const size_t numFilters(mFilters.Size()); + for(size_t i = 0; i < numFilters; ++i) { delete mFilters[i]; } mFilters.Release(); } -void EffectsView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void EffectsView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::EffectsView effectsView = Toolkit::EffectsView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::EffectsView effectsView = Toolkit::EffectsView::DownCast(Dali::BaseHandle(object)); - if ( effectsView ) + if(effectsView) { - switch ( index ) + switch(index) { case Toolkit::EffectsView::Property::EFFECT_SIZE: { int effectSize; - if( value.Get( effectSize ) ) + if(value.Get(effectSize)) { - GetImpl( effectsView ).SetEffectSize( effectSize ); + GetImpl(effectsView).SetEffectSize(effectSize); } break; } @@ -538,20 +560,20 @@ void EffectsView::SetProperty( BaseObject* object, Property::Index index, const } } -Property::Value EffectsView::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value EffectsView::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::EffectsView imageview = Toolkit::EffectsView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::EffectsView imageview = Toolkit::EffectsView::DownCast(Dali::BaseHandle(object)); - if ( imageview ) + if(imageview) { - EffectsView& impl = GetImpl( imageview ); - switch ( propertyIndex ) + EffectsView& impl = GetImpl(imageview); + switch(propertyIndex) { case Toolkit::EffectsView::Property::EFFECT_SIZE: { - value = impl.GetEffectSize(); + value = impl.GetEffectSize(); break; } default: diff --git a/dali-toolkit/internal/controls/flex-container/flex-container-impl.cpp b/dali-toolkit/internal/controls/flex-container/flex-container-impl.cpp old mode 100755 new mode 100644 index 5dc8719..263d0c9 --- a/dali-toolkit/internal/controls/flex-container/flex-container-impl.cpp +++ b/dali-toolkit/internal/controls/flex-container/flex-container-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. @@ -19,14 +19,14 @@ #include // EXTERNAL INCLUDES -#include -#include -#include -#include #include #include -#include #include +#include +#include +#include +#include +#include // INTERNAL INCLUDES #include @@ -35,48 +35,42 @@ using namespace Dali; namespace { - #if defined(DEBUG_ENABLED) // debugging support, very useful when new features are added or bugs are hunted down // currently not called from code so compiler will optimize these away, kept here for future debugging #define FLEX_CONTAINER_TAG "DALI Toolkit::FlexContainer " -#define FC_LOG(fmt, args,...) Debug::LogMessage(Debug::DebugInfo, FLEX_CONTAINER_TAG fmt, ## args) +#define FC_LOG(fmt, args, ...) Debug::LogMessage(Debug::DebugInfo, FLEX_CONTAINER_TAG fmt, ##args) // #define FLEX_CONTAINER_DEBUG 1 #if defined(FLEX_CONTAINER_DEBUG) -void PrintNodes( Toolkit::Internal::FlexContainer::FlexItemNodeContainer itemNodes ) +void PrintNodes(Toolkit::Internal::FlexContainer::FlexItemNodeContainer itemNodes) { // Print the style property and layout of all the children - for( unsigned int i = 0; i < itemNodes.size(); ++i ) + for(unsigned int i = 0; i < itemNodes.size(); ++i) { - FC_LOG( "Item %d style: \n", i ); - YGNodePrint( itemNodes[i].node, (YGPrintOptions)( YGPrintOptionsStyle | YGPrintOptionsChildren ) ); - FC_LOG( "\n" ); - FC_LOG( "Item %d layout: \n", i ); - YGNodePrint( itemNodes[i].node, (YGPrintOptions)( YGPrintOptionsLayout | YGPrintOptionsChildren ) ); - FC_LOG( "\n" ); + FC_LOG("Item %d style: \n", i); + YGNodePrint(itemNodes[i].node, (YGPrintOptions)(YGPrintOptionsStyle | YGPrintOptionsChildren)); + FC_LOG("\n"); + FC_LOG("Item %d layout: \n", i); + YGNodePrint(itemNodes[i].node, (YGPrintOptions)(YGPrintOptionsLayout | YGPrintOptionsChildren)); + FC_LOG("\n"); } } #endif // defined(FLEX_CONTAINER_DEBUG) #endif // defined(DEBUG_ENABLED) - } // namespace namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // Type registration BaseHandle Create() { @@ -84,91 +78,84 @@ BaseHandle Create() } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::FlexContainer, Toolkit::Control, Create ); - -DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "contentDirection", INTEGER, CONTENT_DIRECTION ) -DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flexDirection", INTEGER, FLEX_DIRECTION ) -DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flexWrap", INTEGER, FLEX_WRAP ) -DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "justifyContent", INTEGER, JUSTIFY_CONTENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "alignItems", INTEGER, ALIGN_ITEMS ) -DALI_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "alignContent", INTEGER, ALIGN_CONTENT ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flex", FLOAT, FLEX ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "alignSelf", INTEGER, ALIGN_SELF ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, FlexContainer, "flexMargin", VECTOR4, FLEX_MARGIN ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::FlexContainer, Toolkit::Control, Create); + +DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "contentDirection", INTEGER, CONTENT_DIRECTION) +DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flexDirection", INTEGER, FLEX_DIRECTION) +DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flexWrap", INTEGER, FLEX_WRAP) +DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "justifyContent", INTEGER, JUSTIFY_CONTENT) +DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "alignItems", INTEGER, ALIGN_ITEMS) +DALI_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "alignContent", INTEGER, ALIGN_CONTENT) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flex", FLOAT, FLEX) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "alignSelf", INTEGER, ALIGN_SELF) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, FlexContainer, "flexMargin", VECTOR4, FLEX_MARGIN) DALI_TYPE_REGISTRATION_END() const Scripting::StringEnum ALIGN_SELF_STRING_TABLE[] = -{ - { "auto", Toolkit::FlexContainer::ALIGN_AUTO }, - { "flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START }, - { "center", Toolkit::FlexContainer::ALIGN_CENTER }, - { "flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END }, - { "stretch", Toolkit::FlexContainer::ALIGN_STRETCH } -}; -const unsigned int ALIGN_SELF_STRING_TABLE_COUNT = sizeof( ALIGN_SELF_STRING_TABLE ) / sizeof( ALIGN_SELF_STRING_TABLE[0] ); + { + {"auto", Toolkit::FlexContainer::ALIGN_AUTO}, + {"flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START}, + {"center", Toolkit::FlexContainer::ALIGN_CENTER}, + {"flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END}, + {"stretch", Toolkit::FlexContainer::ALIGN_STRETCH}}; +const unsigned int ALIGN_SELF_STRING_TABLE_COUNT = sizeof(ALIGN_SELF_STRING_TABLE) / sizeof(ALIGN_SELF_STRING_TABLE[0]); const Scripting::StringEnum CONTENT_DIRECTION_STRING_TABLE[] = -{ - { "inherit", Toolkit::FlexContainer::INHERIT }, - { "LTR", Toolkit::FlexContainer::LTR }, - { "RTL", Toolkit::FlexContainer::RTL } -}; -const unsigned int CONTENT_DIRECTION_STRING_TABLE_COUNT = sizeof( CONTENT_DIRECTION_STRING_TABLE ) / sizeof( CONTENT_DIRECTION_STRING_TABLE[0] ); + { + {"inherit", Toolkit::FlexContainer::INHERIT}, + {"LTR", Toolkit::FlexContainer::LTR}, + {"RTL", Toolkit::FlexContainer::RTL}}; +const unsigned int CONTENT_DIRECTION_STRING_TABLE_COUNT = sizeof(CONTENT_DIRECTION_STRING_TABLE) / sizeof(CONTENT_DIRECTION_STRING_TABLE[0]); const Scripting::StringEnum FLEX_DIRECTION_STRING_TABLE[] = -{ - { "column", Toolkit::FlexContainer::COLUMN }, - { "columnReverse", Toolkit::FlexContainer::COLUMN_REVERSE }, - { "row", Toolkit::FlexContainer::ROW }, - { "rowReverse", Toolkit::FlexContainer::ROW_REVERSE } -}; -const unsigned int FLEX_DIRECTION_STRING_TABLE_COUNT = sizeof( FLEX_DIRECTION_STRING_TABLE ) / sizeof( FLEX_DIRECTION_STRING_TABLE[0] ); + { + {"column", Toolkit::FlexContainer::COLUMN}, + {"columnReverse", Toolkit::FlexContainer::COLUMN_REVERSE}, + {"row", Toolkit::FlexContainer::ROW}, + {"rowReverse", Toolkit::FlexContainer::ROW_REVERSE}}; +const unsigned int FLEX_DIRECTION_STRING_TABLE_COUNT = sizeof(FLEX_DIRECTION_STRING_TABLE) / sizeof(FLEX_DIRECTION_STRING_TABLE[0]); const Scripting::StringEnum FLEX_WRAP_STRING_TABLE[] = -{ - { "noWrap", Toolkit::FlexContainer::NO_WRAP }, - { "wrap", Toolkit::FlexContainer::WRAP } -}; -const unsigned int FLEX_WRAP_STRING_TABLE_COUNT = sizeof( FLEX_WRAP_STRING_TABLE ) / sizeof( FLEX_WRAP_STRING_TABLE[0] ); + { + {"noWrap", Toolkit::FlexContainer::NO_WRAP}, + {"wrap", Toolkit::FlexContainer::WRAP}}; +const unsigned int FLEX_WRAP_STRING_TABLE_COUNT = sizeof(FLEX_WRAP_STRING_TABLE) / sizeof(FLEX_WRAP_STRING_TABLE[0]); const Scripting::StringEnum JUSTIFY_CONTENT_STRING_TABLE[] = -{ - { "flexStart", Toolkit::FlexContainer::JUSTIFY_FLEX_START }, - { "center", Toolkit::FlexContainer::JUSTIFY_CENTER }, - { "flexEnd", Toolkit::FlexContainer::JUSTIFY_FLEX_END }, - { "spaceBetween", Toolkit::FlexContainer::JUSTIFY_SPACE_BETWEEN }, - { "spaceAround", Toolkit::FlexContainer::JUSTIFY_SPACE_AROUND } -}; -const unsigned int JUSTIFY_CONTENT_STRING_TABLE_COUNT = sizeof( JUSTIFY_CONTENT_STRING_TABLE ) / sizeof( JUSTIFY_CONTENT_STRING_TABLE[0] ); + { + {"flexStart", Toolkit::FlexContainer::JUSTIFY_FLEX_START}, + {"center", Toolkit::FlexContainer::JUSTIFY_CENTER}, + {"flexEnd", Toolkit::FlexContainer::JUSTIFY_FLEX_END}, + {"spaceBetween", Toolkit::FlexContainer::JUSTIFY_SPACE_BETWEEN}, + {"spaceAround", Toolkit::FlexContainer::JUSTIFY_SPACE_AROUND}}; +const unsigned int JUSTIFY_CONTENT_STRING_TABLE_COUNT = sizeof(JUSTIFY_CONTENT_STRING_TABLE) / sizeof(JUSTIFY_CONTENT_STRING_TABLE[0]); const Scripting::StringEnum ALIGN_ITEMS_STRING_TABLE[] = -{ - { "flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START }, - { "center", Toolkit::FlexContainer::ALIGN_CENTER }, - { "flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END }, - { "stretch", Toolkit::FlexContainer::ALIGN_STRETCH } -}; -const unsigned int ALIGN_ITEMS_STRING_TABLE_COUNT = sizeof( ALIGN_ITEMS_STRING_TABLE ) / sizeof( ALIGN_ITEMS_STRING_TABLE[0] ); + { + {"flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START}, + {"center", Toolkit::FlexContainer::ALIGN_CENTER}, + {"flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END}, + {"stretch", Toolkit::FlexContainer::ALIGN_STRETCH}}; +const unsigned int ALIGN_ITEMS_STRING_TABLE_COUNT = sizeof(ALIGN_ITEMS_STRING_TABLE) / sizeof(ALIGN_ITEMS_STRING_TABLE[0]); const Scripting::StringEnum ALIGN_CONTENT_STRING_TABLE[] = -{ - { "flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START }, - { "center", Toolkit::FlexContainer::ALIGN_CENTER }, - { "flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END }, - { "stretch", Toolkit::FlexContainer::ALIGN_STRETCH } -}; -const unsigned int ALIGN_CONTENT_STRING_TABLE_COUNT = sizeof( ALIGN_CONTENT_STRING_TABLE ) / sizeof( ALIGN_CONTENT_STRING_TABLE[0] ); + { + {"flexStart", Toolkit::FlexContainer::ALIGN_FLEX_START}, + {"center", Toolkit::FlexContainer::ALIGN_CENTER}, + {"flexEnd", Toolkit::FlexContainer::ALIGN_FLEX_END}, + {"stretch", Toolkit::FlexContainer::ALIGN_STRETCH}}; +const unsigned int ALIGN_CONTENT_STRING_TABLE_COUNT = sizeof(ALIGN_CONTENT_STRING_TABLE) / sizeof(ALIGN_CONTENT_STRING_TABLE[0]); } // Unnamed namespace Toolkit::FlexContainer FlexContainer::New() { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< FlexContainer > impl = new FlexContainer(); + IntrusivePtr impl = new FlexContainer(); // Pass ownership to CustomActor handle - Toolkit::FlexContainer handle( *impl ); + Toolkit::FlexContainer handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -179,29 +166,29 @@ Toolkit::FlexContainer FlexContainer::New() FlexContainer::~FlexContainer() { - YGNodeFree( mRootNode.node ); + YGNodeFree(mRootNode.node); - for( unsigned int i = 0; i < mChildrenNodes.size(); i++ ) + for(unsigned int i = 0; i < mChildrenNodes.size(); i++) { - YGNodeFree( mChildrenNodes[i].node ); + YGNodeFree(mChildrenNodes[i].node); } mChildrenNodes.clear(); } -void FlexContainer::SetContentDirection( Toolkit::FlexContainer::ContentDirection contentDirection) +void FlexContainer::SetContentDirection(Toolkit::FlexContainer::ContentDirection contentDirection) { - if( mContentDirection != contentDirection ) + if(mContentDirection != contentDirection) { Dali::CustomActor ownerActor(GetOwner()); - if( Toolkit::FlexContainer::INHERIT != contentDirection ) + if(Toolkit::FlexContainer::INHERIT != contentDirection) { mContentDirection = contentDirection; - ownerActor.SetProperty( Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, false ); + ownerActor.SetProperty(Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, false); - if( Toolkit::FlexContainer::LTR == contentDirection ) + if(Toolkit::FlexContainer::LTR == contentDirection) { ownerActor.SetProperty(Dali::Actor::Property::LAYOUT_DIRECTION, Dali::LayoutDirection::LEFT_TO_RIGHT); } @@ -212,11 +199,11 @@ void FlexContainer::SetContentDirection( Toolkit::FlexContainer::ContentDirectio } else { - ownerActor.SetProperty( Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, true ); + ownerActor.SetProperty(Dali::Actor::Property::INHERIT_LAYOUT_DIRECTION, true); - Dali::LayoutDirection::Type layoutDirection = static_cast( ownerActor.GetParent().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + Dali::LayoutDirection::Type layoutDirection = static_cast(ownerActor.GetParent().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { mContentDirection = Toolkit::FlexContainer::RTL; } @@ -235,12 +222,12 @@ Toolkit::FlexContainer::ContentDirection FlexContainer::GetContentDirection() return mContentDirection; } -void FlexContainer::SetFlexDirection( Toolkit::FlexContainer::FlexDirection flexDirection ) +void FlexContainer::SetFlexDirection(Toolkit::FlexContainer::FlexDirection flexDirection) { - if( mFlexDirection != flexDirection ) + if(mFlexDirection != flexDirection) { mFlexDirection = flexDirection; - YGNodeStyleSetFlexDirection( mRootNode.node, static_cast( flexDirection ) ); + YGNodeStyleSetFlexDirection(mRootNode.node, static_cast(flexDirection)); RelayoutRequest(); } @@ -251,12 +238,12 @@ Toolkit::FlexContainer::FlexDirection FlexContainer::GetFlexDirection() return mFlexDirection; } -void FlexContainer::SetFlexWrap( Toolkit::FlexContainer::WrapType flexWrap ) +void FlexContainer::SetFlexWrap(Toolkit::FlexContainer::WrapType flexWrap) { - if( mFlexWrap != flexWrap ) + if(mFlexWrap != flexWrap) { mFlexWrap = flexWrap; - YGNodeStyleSetFlexWrap( mRootNode.node, static_cast( flexWrap ) ); + YGNodeStyleSetFlexWrap(mRootNode.node, static_cast(flexWrap)); RelayoutRequest(); } @@ -267,12 +254,12 @@ Toolkit::FlexContainer::WrapType FlexContainer::GetFlexWrap() return mFlexWrap; } -void FlexContainer::SetJustifyContent( Toolkit::FlexContainer::Justification justifyContent ) +void FlexContainer::SetJustifyContent(Toolkit::FlexContainer::Justification justifyContent) { - if( mJustifyContent != justifyContent ) + if(mJustifyContent != justifyContent) { mJustifyContent = justifyContent; - YGNodeStyleSetJustifyContent( mRootNode.node, static_cast( justifyContent ) ); + YGNodeStyleSetJustifyContent(mRootNode.node, static_cast(justifyContent)); RelayoutRequest(); } @@ -283,12 +270,12 @@ Toolkit::FlexContainer::Justification FlexContainer::GetJustifyContent() return mJustifyContent; } -void FlexContainer::SetAlignItems( Toolkit::FlexContainer::Alignment alignItems ) +void FlexContainer::SetAlignItems(Toolkit::FlexContainer::Alignment alignItems) { - if( mAlignItems != alignItems ) + if(mAlignItems != alignItems) { mAlignItems = alignItems; - YGNodeStyleSetAlignItems( mRootNode.node, static_cast( alignItems ) ); + YGNodeStyleSetAlignItems(mRootNode.node, static_cast(alignItems)); RelayoutRequest(); } @@ -299,12 +286,12 @@ Toolkit::FlexContainer::Alignment FlexContainer::GetAlignItems() return mAlignItems; } -void FlexContainer::SetAlignContent( Toolkit::FlexContainer::Alignment alignContent ) +void FlexContainer::SetAlignContent(Toolkit::FlexContainer::Alignment alignContent) { - if( mAlignContent != alignContent ) + if(mAlignContent != alignContent) { mAlignContent = alignContent; - YGNodeStyleSetAlignContent( mRootNode.node, static_cast( alignContent ) ); + YGNodeStyleSetAlignContent(mRootNode.node, static_cast(alignContent)); RelayoutRequest(); } @@ -315,27 +302,27 @@ Toolkit::FlexContainer::Alignment FlexContainer::GetAlignContent() return mAlignContent; } -void FlexContainer::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void FlexContainer::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast( Dali::BaseHandle( object ) ); + Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(Dali::BaseHandle(object)); - if( flexContainer ) + if(flexContainer) { - FlexContainer& flexContainerImpl( GetImpl( flexContainer ) ); - switch( index ) + FlexContainer& flexContainerImpl(GetImpl(flexContainer)); + switch(index) { case Toolkit::FlexContainer::Property::CONTENT_DIRECTION: { - Toolkit::FlexContainer::ContentDirection contentDirection( Toolkit::FlexContainer::INHERIT ); + Toolkit::FlexContainer::ContentDirection contentDirection(Toolkit::FlexContainer::INHERIT); - if( value.GetType() == Property::INTEGER ) + if(value.GetType() == Property::INTEGER) { - flexContainerImpl.SetContentDirection( static_cast( value.Get< int >() ) ); + flexContainerImpl.SetContentDirection(static_cast(value.Get())); } - else if( Scripting::GetEnumeration< Toolkit::FlexContainer::ContentDirection >( value.Get< std::string >().c_str(), - CONTENT_DIRECTION_STRING_TABLE, - CONTENT_DIRECTION_STRING_TABLE_COUNT, - contentDirection ) ) + else if(Scripting::GetEnumeration(value.Get().c_str(), + CONTENT_DIRECTION_STRING_TABLE, + CONTENT_DIRECTION_STRING_TABLE_COUNT, + contentDirection)) { flexContainerImpl.SetContentDirection(contentDirection); } @@ -343,16 +330,16 @@ void FlexContainer::SetProperty( BaseObject* object, Property::Index index, cons } case Toolkit::FlexContainer::Property::FLEX_DIRECTION: { - Toolkit::FlexContainer::FlexDirection flexDirection( Toolkit::FlexContainer::COLUMN ); + Toolkit::FlexContainer::FlexDirection flexDirection(Toolkit::FlexContainer::COLUMN); - if( value.GetType() == Property::INTEGER ) + if(value.GetType() == Property::INTEGER) { - flexContainerImpl.SetFlexDirection( static_cast( value.Get< int >() ) ); + flexContainerImpl.SetFlexDirection(static_cast(value.Get())); } - else if( Scripting::GetEnumeration< Toolkit::FlexContainer::FlexDirection >( value.Get< std::string >().c_str(), - FLEX_DIRECTION_STRING_TABLE, - FLEX_DIRECTION_STRING_TABLE_COUNT, - flexDirection ) ) + else if(Scripting::GetEnumeration(value.Get().c_str(), + FLEX_DIRECTION_STRING_TABLE, + FLEX_DIRECTION_STRING_TABLE_COUNT, + flexDirection)) { flexContainerImpl.SetFlexDirection(flexDirection); } @@ -360,16 +347,16 @@ void FlexContainer::SetProperty( BaseObject* object, Property::Index index, cons } case Toolkit::FlexContainer::Property::FLEX_WRAP: { - Toolkit::FlexContainer::WrapType flexWrap( Toolkit::FlexContainer::NO_WRAP ); + Toolkit::FlexContainer::WrapType flexWrap(Toolkit::FlexContainer::NO_WRAP); - if( value.GetType() == Property::INTEGER ) + if(value.GetType() == Property::INTEGER) { - flexContainerImpl.SetFlexWrap( static_cast( value.Get< int >() ) ); + flexContainerImpl.SetFlexWrap(static_cast(value.Get())); } - else if( Scripting::GetEnumeration< Toolkit::FlexContainer::WrapType >( value.Get< std::string >().c_str(), - FLEX_WRAP_STRING_TABLE, - FLEX_WRAP_STRING_TABLE_COUNT, - flexWrap ) ) + else if(Scripting::GetEnumeration(value.Get().c_str(), + FLEX_WRAP_STRING_TABLE, + FLEX_WRAP_STRING_TABLE_COUNT, + flexWrap)) { flexContainerImpl.SetFlexWrap(flexWrap); } @@ -377,16 +364,16 @@ void FlexContainer::SetProperty( BaseObject* object, Property::Index index, cons } case Toolkit::FlexContainer::Property::JUSTIFY_CONTENT: { - Toolkit::FlexContainer::Justification justifyContent( Toolkit::FlexContainer::JUSTIFY_FLEX_START ); + Toolkit::FlexContainer::Justification justifyContent(Toolkit::FlexContainer::JUSTIFY_FLEX_START); - if( value.GetType() == Property::INTEGER ) + if(value.GetType() == Property::INTEGER) { - flexContainerImpl.SetJustifyContent( static_cast( value.Get< int >() ) ); + flexContainerImpl.SetJustifyContent(static_cast(value.Get())); } - else if( Scripting::GetEnumeration< Toolkit::FlexContainer::Justification >( value.Get< std::string >().c_str(), - JUSTIFY_CONTENT_STRING_TABLE, - JUSTIFY_CONTENT_STRING_TABLE_COUNT, - justifyContent ) ) + else if(Scripting::GetEnumeration(value.Get().c_str(), + JUSTIFY_CONTENT_STRING_TABLE, + JUSTIFY_CONTENT_STRING_TABLE_COUNT, + justifyContent)) { flexContainerImpl.SetJustifyContent(justifyContent); } @@ -394,16 +381,16 @@ void FlexContainer::SetProperty( BaseObject* object, Property::Index index, cons } case Toolkit::FlexContainer::Property::ALIGN_ITEMS: { - Toolkit::FlexContainer::Alignment alignItems( Toolkit::FlexContainer::ALIGN_STRETCH ); + Toolkit::FlexContainer::Alignment alignItems(Toolkit::FlexContainer::ALIGN_STRETCH); - if( value.GetType() == Property::INTEGER ) + if(value.GetType() == Property::INTEGER) { - flexContainerImpl.SetAlignItems( static_cast( value.Get< int >() ) ); + flexContainerImpl.SetAlignItems(static_cast(value.Get())); } - else if( Scripting::GetEnumeration< Toolkit::FlexContainer::Alignment >( value.Get< std::string >().c_str(), - ALIGN_ITEMS_STRING_TABLE, - ALIGN_ITEMS_STRING_TABLE_COUNT, - alignItems ) ) + else if(Scripting::GetEnumeration(value.Get().c_str(), + ALIGN_ITEMS_STRING_TABLE, + ALIGN_ITEMS_STRING_TABLE_COUNT, + alignItems)) { flexContainerImpl.SetAlignItems(alignItems); } @@ -411,16 +398,16 @@ void FlexContainer::SetProperty( BaseObject* object, Property::Index index, cons } case Toolkit::FlexContainer::Property::ALIGN_CONTENT: { - Toolkit::FlexContainer::Alignment alignContent( Toolkit::FlexContainer::ALIGN_FLEX_START ); + Toolkit::FlexContainer::Alignment alignContent(Toolkit::FlexContainer::ALIGN_FLEX_START); - if( value.GetType() == Property::INTEGER ) + if(value.GetType() == Property::INTEGER) { - flexContainerImpl.SetAlignContent( static_cast( value.Get< int >() ) ); + flexContainerImpl.SetAlignContent(static_cast(value.Get())); } - else if( Scripting::GetEnumeration< Toolkit::FlexContainer::Alignment >( value.Get< std::string >().c_str(), - ALIGN_CONTENT_STRING_TABLE, - ALIGN_CONTENT_STRING_TABLE_COUNT, - alignContent ) ) + else if(Scripting::GetEnumeration(value.Get().c_str(), + ALIGN_CONTENT_STRING_TABLE, + ALIGN_CONTENT_STRING_TABLE_COUNT, + alignContent)) { flexContainerImpl.SetAlignContent(alignContent); } @@ -430,16 +417,16 @@ void FlexContainer::SetProperty( BaseObject* object, Property::Index index, cons } } -Property::Value FlexContainer::GetProperty( BaseObject* object, Property::Index index ) +Property::Value FlexContainer::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast( Dali::BaseHandle( object ) ); + Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(Dali::BaseHandle(object)); - if( flexContainer ) + if(flexContainer) { - FlexContainer& flexContainerImpl( GetImpl( flexContainer ) ); - switch( index ) + FlexContainer& flexContainerImpl(GetImpl(flexContainer)); + switch(index) { case Toolkit::FlexContainer::Property::CONTENT_DIRECTION: { @@ -477,29 +464,29 @@ Property::Value FlexContainer::GetProperty( BaseObject* object, Property::Index return value; } -void FlexContainer::OnChildAdd( Actor& child ) +void FlexContainer::OnChildAdd(Actor& child) { // Create a new node for the child. FlexItemNode childNode; childNode.actor = child; - childNode.node = YGNodeNew(); + childNode.node = YGNodeNew(); - mChildrenNodes.push_back( childNode ); - YGNodeInsertChild( mRootNode.node, childNode.node, mChildrenNodes.size() - 1 ); + mChildrenNodes.push_back(childNode); + YGNodeInsertChild(mRootNode.node, childNode.node, mChildrenNodes.size() - 1); - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void FlexContainer::OnChildRemove( Actor& child ) +void FlexContainer::OnChildRemove(Actor& child) { - for( unsigned int i = 0; i < mChildrenNodes.size(); i++ ) + for(unsigned int i = 0; i < mChildrenNodes.size(); i++) { - if( mChildrenNodes[i].actor.GetHandle() == child ) + if(mChildrenNodes[i].actor.GetHandle() == child) { - YGNodeRemoveChild( mRootNode.node, mChildrenNodes[i].node ); - YGNodeFree( mChildrenNodes[i].node ); + YGNodeRemoveChild(mRootNode.node, mChildrenNodes[i].node); + YGNodeFree(mChildrenNodes[i].node); - mChildrenNodes.erase( mChildrenNodes.begin() + i ); + mChildrenNodes.erase(mChildrenNodes.begin() + i); // Relayout the container only if instances were found RelayoutRequest(); @@ -507,33 +494,33 @@ void FlexContainer::OnChildRemove( Actor& child ) } } - Control::OnChildRemove( child ); + Control::OnChildRemove(child); } -void FlexContainer::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void FlexContainer::OnRelayout(const Vector2& size, RelayoutContainer& container) { - for( unsigned int i = 0; i < mChildrenNodes.size(); i++ ) + for(unsigned int i = 0; i < mChildrenNodes.size(); i++) { Actor child = mChildrenNodes[i].actor.GetHandle(); - if( child ) + if(child) { // Anchor actor to top left of the container - if( child.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >() ) + if(child.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get()) { - child.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); + child.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); } - child.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); + child.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); - float negotiatedWidth = child.GetRelayoutSize(Dimension::WIDTH); + float negotiatedWidth = child.GetRelayoutSize(Dimension::WIDTH); float negotiatedHeight = child.GetRelayoutSize(Dimension::HEIGHT); - if( negotiatedWidth > 0 ) + if(negotiatedWidth > 0) { - YGNodeStyleSetWidth( mChildrenNodes[i].node, negotiatedWidth ); + YGNodeStyleSetWidth(mChildrenNodes[i].node, negotiatedWidth); } - if( negotiatedHeight > 0 ) + if(negotiatedHeight > 0) { - YGNodeStyleSetHeight( mChildrenNodes[i].node, negotiatedHeight ); + YGNodeStyleSetHeight(mChildrenNodes[i].node, negotiatedHeight); } } } @@ -541,57 +528,57 @@ void FlexContainer::OnRelayout( const Vector2& size, RelayoutContainer& containe // Relayout the container RelayoutChildren(); #if defined(FLEX_CONTAINER_DEBUG) - PrintNodes( mChildrenNodes ); + PrintNodes(mChildrenNodes); #endif - for( unsigned int i = 0; i < mChildrenNodes.size(); i++ ) + for(unsigned int i = 0; i < mChildrenNodes.size(); i++) { Actor child = mChildrenNodes[i].actor.GetHandle(); - if( child ) + if(child) { - if( child.GetPropertyType( Toolkit::FlexContainer::ChildProperty::FLEX ) != Property::NONE ) + if(child.GetPropertyType(Toolkit::FlexContainer::ChildProperty::FLEX) != Property::NONE) { // Only Set to USE_ASSIGNED_SIZE if the child actor is flexible. - if( child.GetResizePolicy( Dimension::WIDTH ) != ResizePolicy::USE_ASSIGNED_SIZE ) + if(child.GetResizePolicy(Dimension::WIDTH) != ResizePolicy::USE_ASSIGNED_SIZE) { - child.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH ); + child.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH); } - if( child.GetResizePolicy( Dimension::HEIGHT ) != ResizePolicy::USE_ASSIGNED_SIZE ) + if(child.GetResizePolicy(Dimension::HEIGHT) != ResizePolicy::USE_ASSIGNED_SIZE) { - child.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT ); + child.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT); } } - container.Add( child, Vector2(YGNodeLayoutGetWidth(mChildrenNodes[i].node), YGNodeLayoutGetHeight(mChildrenNodes[i].node) ) ); + container.Add(child, Vector2(YGNodeLayoutGetWidth(mChildrenNodes[i].node), YGNodeLayoutGetHeight(mChildrenNodes[i].node))); } } } -bool FlexContainer::RelayoutDependentOnChildren( Dimension::Type dimension ) +bool FlexContainer::RelayoutDependentOnChildren(Dimension::Type dimension) { return true; } -void FlexContainer::OnSizeSet( const Vector3& size ) +void FlexContainer::OnSizeSet(const Vector3& size) { - if( mRootNode.node ) + if(mRootNode.node) { Actor self = Self(); - YGNodeStyleSetWidth( mRootNode.node, size.x ); - YGNodeStyleSetHeight( mRootNode.node, size.y ); + YGNodeStyleSetWidth(mRootNode.node, size.x); + YGNodeStyleSetHeight(mRootNode.node, size.y); RelayoutRequest(); } - Control::OnSizeSet( size ); + Control::OnSizeSet(size); } -void FlexContainer::OnLayoutDirectionChanged( Dali::Actor actor, Dali::LayoutDirection::Type type ) +void FlexContainer::OnLayoutDirectionChanged(Dali::Actor actor, Dali::LayoutDirection::Type type) { - Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(actor); + Toolkit::FlexContainer flexContainer = Toolkit::FlexContainer::DownCast(actor); Toolkit::FlexContainer::ContentDirection direction; - if( type == Dali::LayoutDirection::RIGHT_TO_LEFT ) + if(type == Dali::LayoutDirection::RIGHT_TO_LEFT) { direction = Toolkit::FlexContainer::RTL; } @@ -600,9 +587,9 @@ void FlexContainer::OnLayoutDirectionChanged( Dali::Actor actor, Dali::LayoutDir direction = Toolkit::FlexContainer::LTR; } - Toolkit::Internal::FlexContainer &flexContainerImpl = GetImpl( flexContainer ); + Toolkit::Internal::FlexContainer& flexContainerImpl = GetImpl(flexContainer); - if( flexContainerImpl.mContentDirection != direction ) + if(flexContainerImpl.mContentDirection != direction) { Dali::CustomActor ownerActor(flexContainerImpl.GetOwner()); flexContainerImpl.mContentDirection = direction; @@ -613,86 +600,86 @@ void FlexContainer::OnLayoutDirectionChanged( Dali::Actor actor, Dali::LayoutDir void FlexContainer::ComputeLayout() { - if( mRootNode.node ) + if(mRootNode.node) { - for( unsigned int i = 0; i < mChildrenNodes.size(); i++ ) + for(unsigned int i = 0; i < mChildrenNodes.size(); i++) { - YGNodeRef childNode = mChildrenNodes[i].node; - Actor childActor = mChildrenNodes[i].actor.GetHandle(); + YGNodeRef childNode = mChildrenNodes[i].node; + Actor childActor = mChildrenNodes[i].actor.GetHandle(); // Intialize the style of the child. - YGNodeStyleSetMinWidth( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MINIMUM_SIZE ).x ); - YGNodeStyleSetMinHeight( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MINIMUM_SIZE ).y ); - YGNodeStyleSetMaxWidth( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).x ); - YGNodeStyleSetMaxHeight( childNode, childActor.GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).y ); + YGNodeStyleSetMinWidth(childNode, childActor.GetProperty(Actor::Property::MINIMUM_SIZE).x); + YGNodeStyleSetMinHeight(childNode, childActor.GetProperty(Actor::Property::MINIMUM_SIZE).y); + YGNodeStyleSetMaxWidth(childNode, childActor.GetProperty(Actor::Property::MAXIMUM_SIZE).x); + YGNodeStyleSetMaxHeight(childNode, childActor.GetProperty(Actor::Property::MAXIMUM_SIZE).y); // Check child properties on the child for how to layout it. // These properties should be dynamically registered to the child which // would be added to FlexContainer. - if( childActor.GetPropertyType( Toolkit::FlexContainer::ChildProperty::FLEX ) != Property::NONE ) + if(childActor.GetPropertyType(Toolkit::FlexContainer::ChildProperty::FLEX) != Property::NONE) { - YGNodeStyleSetFlex( childNode, childActor.GetProperty( Toolkit::FlexContainer::ChildProperty::FLEX ).Get() ); + YGNodeStyleSetFlex(childNode, childActor.GetProperty(Toolkit::FlexContainer::ChildProperty::FLEX).Get()); } - Toolkit::FlexContainer::Alignment alignSelf( Toolkit::FlexContainer::ALIGN_AUTO ); - if( childActor.GetPropertyType( Toolkit::FlexContainer::ChildProperty::ALIGN_SELF ) != Property::NONE ) + Toolkit::FlexContainer::Alignment alignSelf(Toolkit::FlexContainer::ALIGN_AUTO); + if(childActor.GetPropertyType(Toolkit::FlexContainer::ChildProperty::ALIGN_SELF) != Property::NONE) { - Property::Value alignSelfPropertyValue = childActor.GetProperty( Toolkit::FlexContainer::ChildProperty::ALIGN_SELF ); - if( alignSelfPropertyValue.GetType() == Property::INTEGER ) + Property::Value alignSelfPropertyValue = childActor.GetProperty(Toolkit::FlexContainer::ChildProperty::ALIGN_SELF); + if(alignSelfPropertyValue.GetType() == Property::INTEGER) { - alignSelf = static_cast( alignSelfPropertyValue.Get< int >() ); + alignSelf = static_cast(alignSelfPropertyValue.Get()); } - else if( alignSelfPropertyValue.GetType() == Property::STRING ) + else if(alignSelfPropertyValue.GetType() == Property::STRING) { std::string value = alignSelfPropertyValue.Get(); - Scripting::GetEnumeration< Toolkit::FlexContainer::Alignment >( value.c_str(), - ALIGN_SELF_STRING_TABLE, - ALIGN_SELF_STRING_TABLE_COUNT, - alignSelf ); + Scripting::GetEnumeration(value.c_str(), + ALIGN_SELF_STRING_TABLE, + ALIGN_SELF_STRING_TABLE_COUNT, + alignSelf); } - YGNodeStyleSetAlignSelf( childNode, static_cast(alignSelf) ); + YGNodeStyleSetAlignSelf(childNode, static_cast(alignSelf)); } - if( childActor.GetPropertyType( Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN ) != Property::NONE ) + if(childActor.GetPropertyType(Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN) != Property::NONE) { - Vector4 flexMargin = childActor.GetProperty( Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN ).Get(); - YGNodeStyleSetMargin( childNode, YGEdgeLeft, flexMargin.x ); - YGNodeStyleSetMargin( childNode, YGEdgeTop, flexMargin.y ); - YGNodeStyleSetMargin( childNode, YGEdgeRight, flexMargin.z ); - YGNodeStyleSetMargin( childNode, YGEdgeBottom, flexMargin.w ); + Vector4 flexMargin = childActor.GetProperty(Toolkit::FlexContainer::ChildProperty::FLEX_MARGIN).Get(); + YGNodeStyleSetMargin(childNode, YGEdgeLeft, flexMargin.x); + YGNodeStyleSetMargin(childNode, YGEdgeTop, flexMargin.y); + YGNodeStyleSetMargin(childNode, YGEdgeRight, flexMargin.z); + YGNodeStyleSetMargin(childNode, YGEdgeBottom, flexMargin.w); } } // Calculate the layout YGDirection nodeLayoutDirection = YGDirectionInherit; - switch( mContentDirection ) + switch(mContentDirection) { - case Dali::Toolkit::FlexContainer::LTR: - { - nodeLayoutDirection = YGDirectionLTR; - break; - } + case Dali::Toolkit::FlexContainer::LTR: + { + nodeLayoutDirection = YGDirectionLTR; + break; + } - case Dali::Toolkit::FlexContainer::RTL: - { - nodeLayoutDirection = YGDirectionRTL; - break; - } + case Dali::Toolkit::FlexContainer::RTL: + { + nodeLayoutDirection = YGDirectionRTL; + break; + } - case Dali::Toolkit::FlexContainer::INHERIT: - { - nodeLayoutDirection = YGDirectionInherit; - break; - } + case Dali::Toolkit::FlexContainer::INHERIT: + { + nodeLayoutDirection = YGDirectionInherit; + break; + } } #if defined(FLEX_CONTAINER_DEBUG) - YGNodePrint( mRootNode.node, (YGPrintOptions)( YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren ) ); + YGNodePrint(mRootNode.node, (YGPrintOptions)(YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren)); #endif - YGNodeCalculateLayout( mRootNode.node, Self().GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).x, Self().GetProperty< Vector2 >( Actor::Property::MAXIMUM_SIZE ).y, nodeLayoutDirection ); + YGNodeCalculateLayout(mRootNode.node, Self().GetProperty(Actor::Property::MAXIMUM_SIZE).x, Self().GetProperty(Actor::Property::MAXIMUM_SIZE).y, nodeLayoutDirection); #if defined(FLEX_CONTAINER_DEBUG) - YGNodePrint( mRootNode.node, (YGPrintOptions)( YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren ) ); + YGNodePrint(mRootNode.node, (YGPrintOptions)(YGPrintOptionsLayout | YGPrintOptionsStyle | YGPrintOptionsChildren)); #endif } } @@ -702,13 +689,13 @@ void FlexContainer::RelayoutChildren() ComputeLayout(); // Set size and position of children according to the layout calculation - for( unsigned int i = 0; i < mChildrenNodes.size(); i++ ) + for(unsigned int i = 0; i < mChildrenNodes.size(); i++) { Dali::Actor child = mChildrenNodes[i].actor.GetHandle(); - if( child ) + if(child) { - child.SetProperty( Actor::Property::POSITION_X, YGNodeLayoutGetLeft( mChildrenNodes[i].node ) ); - child.SetProperty( Actor::Property::POSITION_Y, YGNodeLayoutGetTop( mChildrenNodes[i].node ) ); + child.SetProperty(Actor::Property::POSITION_X, YGNodeLayoutGetLeft(mChildrenNodes[i].node)); + child.SetProperty(Actor::Property::POSITION_Y, YGNodeLayoutGetTop(mChildrenNodes[i].node)); } } } @@ -718,9 +705,9 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To Actor nextFocusableActor; // First check whether there is any items in the container - if( mChildrenNodes.size() > 0 ) + if(mChildrenNodes.size() > 0) { - if ( !currentFocusedActor || currentFocusedActor == Self() ) + if(!currentFocusedActor || currentFocusedActor == Self()) { // Nothing is currently focused, so the first child in the container should be focused. nextFocusableActor = mChildrenNodes[0].actor.GetHandle(); @@ -729,20 +716,20 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To { // Check whether the current focused actor is within flex container int currentFocusedActorIndex = -1; - for( unsigned int index = 0; index < mChildrenNodes.size(); index++ ) + for(unsigned int index = 0; index < mChildrenNodes.size(); index++) { - if( currentFocusedActor == mChildrenNodes[index].actor.GetHandle() ) + if(currentFocusedActor == mChildrenNodes[index].actor.GetHandle()) { currentFocusedActorIndex = index; break; } } - if( currentFocusedActorIndex > -1 ) + if(currentFocusedActorIndex > -1) { int previousCheckedActorIndex = -1; - int nextFocusedActorIndex = currentFocusedActorIndex; - switch ( direction ) + int nextFocusedActorIndex = currentFocusedActorIndex; + switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: case Toolkit::Control::KeyboardFocus::UP: @@ -751,11 +738,11 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To do { nextFocusedActorIndex--; - if( nextFocusedActorIndex < 0 ) + if(nextFocusedActorIndex < 0) { nextFocusedActorIndex = loopEnabled ? mChildrenNodes.size() - 1 : 0; } - if( nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex ) + if(nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex) { previousCheckedActorIndex = nextFocusedActorIndex; } @@ -763,7 +750,7 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To { break; } - } while ( !mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ); + } while(!mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)); break; } case Toolkit::Control::KeyboardFocus::RIGHT: @@ -773,11 +760,11 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To do { nextFocusedActorIndex++; - if( nextFocusedActorIndex > static_cast(mChildrenNodes.size() - 1) ) + if(nextFocusedActorIndex > static_cast(mChildrenNodes.size() - 1)) { nextFocusedActorIndex = loopEnabled ? 0 : mChildrenNodes.size() - 1; } - if( nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex ) + if(nextFocusedActorIndex != previousCheckedActorIndex && nextFocusedActorIndex != currentFocusedActorIndex) { previousCheckedActorIndex = nextFocusedActorIndex; } @@ -785,7 +772,7 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To { break; } - } while ( !mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ); + } while(!mChildrenNodes[nextFocusedActorIndex].actor.GetHandle().GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)); break; } default: @@ -794,7 +781,7 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To } } - if( nextFocusedActorIndex != currentFocusedActorIndex ) + if(nextFocusedActorIndex != currentFocusedActorIndex) { nextFocusableActor = mChildrenNodes[nextFocusedActorIndex].actor.GetHandle(); } @@ -816,42 +803,42 @@ Actor FlexContainer::GetNextKeyboardFocusableActor(Actor currentFocusedActor, To } FlexContainer::FlexContainer() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mContentDirection( Toolkit::FlexContainer::INHERIT ), - mFlexDirection( Toolkit::FlexContainer::COLUMN ), - mFlexWrap( Toolkit::FlexContainer::NO_WRAP ), - mJustifyContent( Toolkit::FlexContainer::JUSTIFY_FLEX_START ), - mAlignItems( Toolkit::FlexContainer::ALIGN_STRETCH ), - mAlignContent( Toolkit::FlexContainer::ALIGN_FLEX_START ) -{ - SetKeyboardNavigationSupport( true ); +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mContentDirection(Toolkit::FlexContainer::INHERIT), + mFlexDirection(Toolkit::FlexContainer::COLUMN), + mFlexWrap(Toolkit::FlexContainer::NO_WRAP), + mJustifyContent(Toolkit::FlexContainer::JUSTIFY_FLEX_START), + mAlignItems(Toolkit::FlexContainer::ALIGN_STRETCH), + mAlignContent(Toolkit::FlexContainer::ALIGN_FLEX_START) +{ + SetKeyboardNavigationSupport(true); } void FlexContainer::OnInitialize() { // Initialize the node for the flex container itself Dali::Actor self = Self(); - self.LayoutDirectionChangedSignal().Connect( this, &FlexContainer::OnLayoutDirectionChanged ); + self.LayoutDirectionChangedSignal().Connect(this, &FlexContainer::OnLayoutDirectionChanged); mRootNode.actor = self; - mRootNode.node = YGNodeNew(); - YGNodeSetContext( mRootNode.node, &mChildrenNodes ); + mRootNode.node = YGNodeNew(); + YGNodeSetContext(mRootNode.node, &mChildrenNodes); // Set default style - YGNodeStyleSetFlexDirection( mRootNode.node, static_cast( mFlexDirection ) ); - YGNodeStyleSetFlexWrap( mRootNode.node, static_cast( mFlexWrap ) ); - YGNodeStyleSetJustifyContent( mRootNode.node, static_cast( mJustifyContent ) ); - YGNodeStyleSetAlignItems( mRootNode.node, static_cast( mAlignItems ) ); - YGNodeStyleSetAlignContent( mRootNode.node, static_cast( mAlignContent ) ); + YGNodeStyleSetFlexDirection(mRootNode.node, static_cast(mFlexDirection)); + YGNodeStyleSetFlexWrap(mRootNode.node, static_cast(mFlexWrap)); + YGNodeStyleSetJustifyContent(mRootNode.node, static_cast(mJustifyContent)); + YGNodeStyleSetAlignItems(mRootNode.node, static_cast(mAlignItems)); + YGNodeStyleSetAlignContent(mRootNode.node, static_cast(mAlignContent)); // Make self as keyboard focusable and focus group - self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true ); - SetAsKeyboardFocusGroup( true ); + self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true); + SetAsKeyboardFocusGroup(true); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } } // namespace Internal diff --git a/dali-toolkit/internal/controls/gaussian-blur-view/gaussian-blur-view-impl.cpp b/dali-toolkit/internal/controls/gaussian-blur-view/gaussian-blur-view-impl.cpp index 304c799..961ff9f 100644 --- a/dali-toolkit/internal/controls/gaussian-blur-view/gaussian-blur-view-impl.cpp +++ b/dali-toolkit/internal/controls/gaussian-blur-view/gaussian-blur-view-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,25 +19,25 @@ #include "gaussian-blur-view-impl.h" // EXTERNAL INCLUDES -#include -#include +#include +#include +#include #include #include -#include -#include #include +#include +#include #include #include #include -#include -#include -#include +#include +#include // INTERNAL INCLUDES -#include -#include #include +#include #include +#include // TODO: // pixel format / size - set from JSON @@ -45,7 +45,6 @@ // default near clip value // Manager object - re-use render targets if there are multiple GaussianBlurViews created - ///////////////////////////////////////////////////////// // IMPLEMENTATION NOTES @@ -57,7 +56,6 @@ // to take account of the changed GaussianBlurView object size, projecting to the unchanged render target sizes. This is done relative to the fixed render target / actor sizes // by using constraints relative to the GaussianBlurView actor size. - // 2 modes: // 1st mode, this control has a tree of actors (use Add() to add children) that are rendered and blurred. // mRenderChildrenTask renders children to FB mRenderTargetForRenderingChildren @@ -73,16 +71,12 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - using namespace Dali; BaseHandle Create() @@ -90,67 +84,66 @@ BaseHandle Create() return Toolkit::GaussianBlurView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::GaussianBlurView, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::GaussianBlurView, Toolkit::Control, Create) DALI_TYPE_REGISTRATION_END() -const unsigned int GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5; -const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f; +const unsigned int GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5; +const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f; const Pixel::Format GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888; -const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH = 1.0f; // default, fully blurred -const char* const GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME = "GaussianBlurStrengthPropertyName"; -const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f; -const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f; +const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH = 1.0f; // default, fully blurred +const char* const GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME = "GaussianBlurStrengthPropertyName"; +const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f; +const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f; const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f; } // namespace - GaussianBlurView::GaussianBlurView() -: Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ), +: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)), mNumSamples(GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES), - mBlurBellCurveWidth( 0.001f ), + mBlurBellCurveWidth(0.001f), mPixelFormat(GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT), mDownsampleWidthScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE), mDownsampleHeightScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE), - mDownsampledWidth( 0.0f ), - mDownsampledHeight( 0.0f ), - mBlurUserImage( false ), - mRenderOnce( false ), - mBackgroundColor( Color::BLACK ), + mDownsampledWidth(0.0f), + mDownsampledHeight(0.0f), + mBlurUserImage(false), + mRenderOnce(false), + mBackgroundColor(Color::BLACK), mTargetSize(Vector2::ZERO), mLastSize(Vector2::ZERO), mChildrenRoot(Actor::New()), mInternalRoot(Actor::New()), mBlurStrengthPropertyIndex(Property::INVALID_INDEX), - mActivated( false ) + mActivated(false) { SetBlurBellCurveWidth(GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH); } -GaussianBlurView::GaussianBlurView( const unsigned int numSamples, - const float blurBellCurveWidth, - const Pixel::Format renderTargetPixelFormat, - const float downsampleWidthScale, - const float downsampleHeightScale, - bool blurUserImage) -: Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ), +GaussianBlurView::GaussianBlurView(const unsigned int numSamples, + const float blurBellCurveWidth, + const Pixel::Format renderTargetPixelFormat, + const float downsampleWidthScale, + const float downsampleHeightScale, + bool blurUserImage) +: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)), mNumSamples(numSamples), - mBlurBellCurveWidth( 0.001f ), + mBlurBellCurveWidth(0.001f), mPixelFormat(renderTargetPixelFormat), mDownsampleWidthScale(downsampleWidthScale), mDownsampleHeightScale(downsampleHeightScale), - mDownsampledWidth( 0.0f ), - mDownsampledHeight( 0.0f ), - mBlurUserImage( blurUserImage ), - mRenderOnce( false ), - mBackgroundColor( Color::BLACK ), + mDownsampledWidth(0.0f), + mDownsampledHeight(0.0f), + mBlurUserImage(blurUserImage), + mRenderOnce(false), + mBackgroundColor(Color::BLACK), mTargetSize(Vector2::ZERO), mLastSize(Vector2::ZERO), mChildrenRoot(Actor::New()), mInternalRoot(Actor::New()), mBlurStrengthPropertyIndex(Property::INVALID_INDEX), - mActivated( false ) + mActivated(false) { SetBlurBellCurveWidth(blurBellCurveWidth); } @@ -159,12 +152,11 @@ GaussianBlurView::~GaussianBlurView() { } - Toolkit::GaussianBlurView GaussianBlurView::New() { GaussianBlurView* impl = new GaussianBlurView(); - Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl ); + Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -173,15 +165,11 @@ Toolkit::GaussianBlurView GaussianBlurView::New() return handle; } -Toolkit::GaussianBlurView GaussianBlurView::New(const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, - const float downsampleWidthScale, const float downsampleHeightScale, - bool blurUserImage) +Toolkit::GaussianBlurView GaussianBlurView::New(const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat, const float downsampleWidthScale, const float downsampleHeightScale, bool blurUserImage) { - GaussianBlurView* impl = new GaussianBlurView( numSamples, blurBellCurveWidth, renderTargetPixelFormat, - downsampleWidthScale, downsampleHeightScale, - blurUserImage); + GaussianBlurView* impl = new GaussianBlurView(numSamples, blurBellCurveWidth, renderTargetPixelFormat, downsampleWidthScale, downsampleHeightScale, blurUserImage); - Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl ); + Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -197,7 +185,7 @@ void GaussianBlurView::SetUserImageAndOutputRenderTarget(Texture inputImage, Fra mUserInputImage = inputImage; - SetRendererTexture( mHorizBlurActor.GetRendererAt(0), inputImage ); + SetRendererTexture(mHorizBlurActor.GetRendererAt(0), inputImage); mUserOutputRenderTarget = outputRenderTarget; } @@ -212,7 +200,7 @@ FrameBuffer GaussianBlurView::GetBlurredRenderTarget() const return mUserOutputRenderTarget; } -void GaussianBlurView::SetBackgroundColor( const Vector4& color ) +void GaussianBlurView::SetBackgroundColor(const Vector4& color) { mBackgroundColor = color; } @@ -230,8 +218,8 @@ Vector4 GaussianBlurView::GetBackgroundColor() const void GaussianBlurView::OnInitialize() { // root actor to parent all user added actors, needed to allow us to set that subtree as exclusive for our child render task - mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mInternalRoot.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); + mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mInternalRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); ////////////////////////////////////////////////////// // Create shaders @@ -246,93 +234,91 @@ void GaussianBlurView::OnInitialize() // Create an actor for performing a horizontal blur on the texture mHorizBlurActor = Actor::New(); - mHorizBlurActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); + mHorizBlurActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); - Renderer renderer = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() ); - mHorizBlurActor.AddRenderer( renderer ); + Renderer renderer = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str()); + mHorizBlurActor.AddRenderer(renderer); // Create an actor for performing a vertical blur on the texture mVertBlurActor = Actor::New(); - mVertBlurActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - renderer = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() ); - mVertBlurActor.AddRenderer( renderer ); + mVertBlurActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + renderer = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str()); + mVertBlurActor.AddRenderer(renderer); // Register a property that the user can control to fade the blur in / out via the GaussianBlurView object - Actor self = Self(); + Actor self = Self(); mBlurStrengthPropertyIndex = self.RegisterProperty(GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME, GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // Create an image view for compositing the blur and the original child actors render if(!mBlurUserImage) { mCompositingActor = Actor::New(); - mCompositingActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mCompositingActor.SetProperty( Actor::Property::OPACITY,GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // ensure alpha is enabled for this object and set default value - renderer = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE ); - mCompositingActor.AddRenderer( renderer ); + mCompositingActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mCompositingActor.SetProperty(Actor::Property::OPACITY, GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // ensure alpha is enabled for this object and set default value + renderer = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE); + mCompositingActor.AddRenderer(renderer); - Constraint blurStrengthConstraint = Constraint::New( mCompositingActor, Actor::Property::COLOR_ALPHA, EqualToConstraint()); - blurStrengthConstraint.AddSource( Source( self, mBlurStrengthPropertyIndex) ); + Constraint blurStrengthConstraint = Constraint::New(mCompositingActor, Actor::Property::COLOR_ALPHA, EqualToConstraint()); + blurStrengthConstraint.AddSource(Source(self, mBlurStrengthPropertyIndex)); blurStrengthConstraint.Apply(); // Create an image view for holding final result, i.e. the blurred image. This will get rendered to screen later, via default / user render task mTargetActor = Actor::New(); - mTargetActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - renderer = CreateRenderer( BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE ); - mTargetActor.AddRenderer( renderer ); + mTargetActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + renderer = CreateRenderer(BASIC_VERTEX_SOURCE, BASIC_FRAGMENT_SOURCE); + mTargetActor.AddRenderer(renderer); ////////////////////////////////////////////////////// // Create cameras for the renders corresponding to the view size mRenderFullSizeCamera = CameraActor::New(); - mRenderFullSizeCamera.SetInvertYAxis( true ); - mRenderFullSizeCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); + mRenderFullSizeCamera.SetInvertYAxis(true); + mRenderFullSizeCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); ////////////////////////////////////////////////////// // Connect to actor tree - mInternalRoot.Add( mCompositingActor ); - mInternalRoot.Add( mTargetActor ); - mInternalRoot.Add( mRenderFullSizeCamera ); + mInternalRoot.Add(mCompositingActor); + mInternalRoot.Add(mTargetActor); + mInternalRoot.Add(mRenderFullSizeCamera); } ////////////////////////////////////////////////////// // Create camera for the renders corresponding to the (potentially downsampled) render targets' size mRenderDownsampledCamera = CameraActor::New(); - mRenderDownsampledCamera.SetInvertYAxis( true ); - mRenderDownsampledCamera.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); + mRenderDownsampledCamera.SetInvertYAxis(true); + mRenderDownsampledCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); ////////////////////////////////////////////////////// // Connect to actor tree - Self().Add( mChildrenRoot ); - mInternalRoot.Add( mHorizBlurActor ); - mInternalRoot.Add( mVertBlurActor ); - mInternalRoot.Add( mRenderDownsampledCamera ); - - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + Self().Add(mChildrenRoot); + mInternalRoot.Add(mHorizBlurActor); + mInternalRoot.Add(mVertBlurActor); + mInternalRoot.Add(mRenderDownsampledCamera); + + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } - void GaussianBlurView::OnSizeSet(const Vector3& targetSize) { mTargetSize = Vector2(targetSize); - mChildrenRoot.SetProperty( Actor::Property::SIZE, targetSize); + mChildrenRoot.SetProperty(Actor::Property::SIZE, targetSize); - if( !mBlurUserImage ) + if(!mBlurUserImage) { - mCompositingActor.SetProperty( Actor::Property::SIZE, targetSize); - mTargetActor.SetProperty( Actor::Property::SIZE, targetSize); + mCompositingActor.SetProperty(Actor::Property::SIZE, targetSize); + mTargetActor.SetProperty(Actor::Property::SIZE, targetSize); // Children render camera must move when GaussianBlurView object is resized. This is since we cannot change render target size - so we need to remap the child actors' rendering // accordingly so they still exactly fill the render target. Note that this means the effective resolution of the child render changes as the GaussianBlurView object changes // size, this is the trade off for not being able to modify render target size // Change camera z position based on GaussianBlurView actor height float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f); - mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale); + mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION_Z, mTargetSize.height * cameraPosConstraintScale); } - // if we have already activated the blur, need to update render target sizes now to reflect the new size of this actor if(mActivated) { @@ -340,24 +326,24 @@ void GaussianBlurView::OnSizeSet(const Vector3& targetSize) Activate(); } - Control::OnSizeSet( targetSize ); + Control::OnSizeSet(targetSize); } -void GaussianBlurView::OnChildAdd( Actor& child ) +void GaussianBlurView::OnChildAdd(Actor& child) { - if( child != mChildrenRoot && child != mInternalRoot) + if(child != mChildrenRoot && child != mInternalRoot) { - mChildrenRoot.Add( child ); + mChildrenRoot.Add(child); } - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void GaussianBlurView::OnChildRemove( Actor& child ) +void GaussianBlurView::OnChildRemove(Actor& child) { - mChildrenRoot.Remove( child ); + mChildrenRoot.Remove(child); - Control::OnChildRemove( child ); + Control::OnChildRemove(child); } void GaussianBlurView::AllocateResources() @@ -365,7 +351,7 @@ void GaussianBlurView::AllocateResources() mLastSize = mTargetSize; // get size of downsampled render targets - mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale; + mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale; mDownsampledHeight = mTargetSize.height * mDownsampleHeightScale; // Create and place a camera for the renders corresponding to the (potentially downsampled) render targets' size @@ -375,7 +361,7 @@ void GaussianBlurView::AllocateResources() mRenderDownsampledCamera.SetAspectRatio(mDownsampledWidth / mDownsampledHeight); mRenderDownsampledCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor - mRenderDownsampledCamera.SetProperty( Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)))); + mRenderDownsampledCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)))); // setup for normal operation if(!mBlurUserImage) @@ -388,39 +374,39 @@ void GaussianBlurView::AllocateResources() mRenderFullSizeCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f); - mRenderFullSizeCamera.SetProperty( Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale)); + mRenderFullSizeCamera.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale)); // create offscreen buffer of new size to render our child actors to - mRenderTargetForRenderingChildren = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture texture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mRenderTargetForRenderingChildren.AttachColorTexture( texture ); + mRenderTargetForRenderingChildren = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mRenderTargetForRenderingChildren.AttachColorTexture(texture); // Set actor for performing a horizontal blur - SetRendererTexture( mHorizBlurActor.GetRendererAt(0), mRenderTargetForRenderingChildren ); + SetRendererTexture(mHorizBlurActor.GetRendererAt(0), mRenderTargetForRenderingChildren); // Create offscreen buffer for vert blur pass - mRenderTarget1 = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE ); - texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight)); - mRenderTarget1.AttachColorTexture( texture ); + mRenderTarget1 = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE); + texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight)); + mRenderTarget1.AttachColorTexture(texture); // use the completed blur in the first buffer and composite with the original child actors render - SetRendererTexture( mCompositingActor.GetRendererAt(0), mRenderTarget1 ); + SetRendererTexture(mCompositingActor.GetRendererAt(0), mRenderTarget1); // set up target actor for rendering result, i.e. the blurred image - SetRendererTexture( mTargetActor.GetRendererAt(0), mRenderTargetForRenderingChildren ); + SetRendererTexture(mTargetActor.GetRendererAt(0), mRenderTargetForRenderingChildren); } // Create offscreen buffer for horiz blur pass - mRenderTarget2 = FrameBuffer::New( mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE ); + mRenderTarget2 = FrameBuffer::New(mDownsampledWidth, mDownsampledHeight, FrameBuffer::Attachment::NONE); Texture texture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mDownsampledWidth), unsigned(mDownsampledHeight)); - mRenderTarget2.AttachColorTexture( texture ); + mRenderTarget2.AttachColorTexture(texture); // size needs to match render target - mHorizBlurActor.SetProperty( Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight) ); + mHorizBlurActor.SetProperty(Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight)); // size needs to match render target - mVertBlurActor.SetProperty( Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight) ); - SetRendererTexture( mVertBlurActor.GetRendererAt(0), mRenderTarget2 ); + mVertBlurActor.SetProperty(Actor::Property::SIZE, Vector2(mDownsampledWidth, mDownsampledHeight)); + SetRendererTexture(mVertBlurActor.GetRendererAt(0), mRenderTarget2); // set gaussian blur up for new sized render targets SetShaderConstants(); @@ -434,16 +420,16 @@ void GaussianBlurView::CreateRenderTasks() { // create render task to render our child actors to offscreen buffer mRenderChildrenTask = taskList.CreateTask(); - mRenderChildrenTask.SetSourceActor( mChildrenRoot ); + mRenderChildrenTask.SetSourceActor(mChildrenRoot); mRenderChildrenTask.SetExclusive(true); - mRenderChildrenTask.SetInputEnabled( false ); - mRenderChildrenTask.SetClearEnabled( true ); - mRenderChildrenTask.SetClearColor( mBackgroundColor ); + mRenderChildrenTask.SetInputEnabled(false); + mRenderChildrenTask.SetClearEnabled(true); + mRenderChildrenTask.SetClearColor(mBackgroundColor); mRenderChildrenTask.SetCameraActor(mRenderFullSizeCamera); - mRenderChildrenTask.SetFrameBuffer( mRenderTargetForRenderingChildren ); + mRenderChildrenTask.SetFrameBuffer(mRenderTargetForRenderingChildren); - if( mRenderOnce ) + if(mRenderOnce) { mRenderChildrenTask.SetRefreshRate(RenderTask::REFRESH_ONCE); } @@ -451,52 +437,52 @@ void GaussianBlurView::CreateRenderTasks() // perform a horizontal blur targeting the second buffer mHorizBlurTask = taskList.CreateTask(); - mHorizBlurTask.SetSourceActor( mHorizBlurActor ); + mHorizBlurTask.SetSourceActor(mHorizBlurActor); mHorizBlurTask.SetExclusive(true); - mHorizBlurTask.SetInputEnabled( false ); - mHorizBlurTask.SetClearEnabled( true ); - mHorizBlurTask.SetClearColor( mBackgroundColor ); + mHorizBlurTask.SetInputEnabled(false); + mHorizBlurTask.SetClearEnabled(true); + mHorizBlurTask.SetClearColor(mBackgroundColor); mHorizBlurTask.SetCameraActor(mRenderDownsampledCamera); - mHorizBlurTask.SetFrameBuffer( mRenderTarget2 ); - if( mRenderOnce || ( mRenderOnce && mBlurUserImage ) ) + mHorizBlurTask.SetFrameBuffer(mRenderTarget2); + if(mRenderOnce || (mRenderOnce && mBlurUserImage)) { mHorizBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE); } // use the second buffer and perform a horizontal blur targeting the first buffer mVertBlurTask = taskList.CreateTask(); - mVertBlurTask.SetSourceActor( mVertBlurActor ); + mVertBlurTask.SetSourceActor(mVertBlurActor); mVertBlurTask.SetExclusive(true); - mVertBlurTask.SetInputEnabled( false ); - mVertBlurTask.SetClearEnabled( true ); - mVertBlurTask.SetClearColor( mBackgroundColor ); + mVertBlurTask.SetInputEnabled(false); + mVertBlurTask.SetClearEnabled(true); + mVertBlurTask.SetClearColor(mBackgroundColor); mVertBlurTask.SetCameraActor(mRenderDownsampledCamera); if(mUserOutputRenderTarget) { - mVertBlurTask.SetFrameBuffer( mUserOutputRenderTarget ); + mVertBlurTask.SetFrameBuffer(mUserOutputRenderTarget); } else { - mVertBlurTask.SetFrameBuffer( mRenderTarget1 ); + mVertBlurTask.SetFrameBuffer(mRenderTarget1); } - if( mRenderOnce || ( mRenderOnce && mBlurUserImage ) ) + if(mRenderOnce || (mRenderOnce && mBlurUserImage)) { mVertBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE); - mVertBlurTask.FinishedSignal().Connect( this, &GaussianBlurView::OnRenderTaskFinished ); + mVertBlurTask.FinishedSignal().Connect(this, &GaussianBlurView::OnRenderTaskFinished); } // use the completed blur in the first buffer and composite with the original child actors render if(!mBlurUserImage) { mCompositeTask = taskList.CreateTask(); - mCompositeTask.SetSourceActor( mCompositingActor ); + mCompositeTask.SetSourceActor(mCompositingActor); mCompositeTask.SetExclusive(true); - mCompositeTask.SetInputEnabled( false ); + mCompositeTask.SetInputEnabled(false); mCompositeTask.SetCameraActor(mRenderFullSizeCamera); - mCompositeTask.SetFrameBuffer( mRenderTargetForRenderingChildren ); + mCompositeTask.SetFrameBuffer(mRenderTargetForRenderingChildren); - if( mRenderOnce ) + if(mRenderOnce) { mCompositeTask.SetRefreshRate(RenderTask::REFRESH_ONCE); } @@ -515,10 +501,10 @@ void GaussianBlurView::RemoveRenderTasks() void GaussianBlurView::Activate() { - if( !mActivated ) + if(!mActivated) { // make sure resources are allocated and start the render tasks processing - Self().Add( mInternalRoot ); + Self().Add(mInternalRoot); AllocateResources(); CreateRenderTasks(); mActivated = true; @@ -534,7 +520,7 @@ void GaussianBlurView::ActivateOnce() void GaussianBlurView::Deactivate() { - if( mActivated ) + if(mActivated) { // stop render tasks processing // Note: render target resources are automatically freed since we set the Image::Unused flag @@ -544,14 +530,14 @@ void GaussianBlurView::Deactivate() mRenderTarget2.Reset(); RemoveRenderTasks(); mRenderOnce = false; - mActivated = false; + mActivated = false; } } void GaussianBlurView::SetBlurBellCurveWidth(float blurBellCurveWidth) { // a value of zero leads to undefined Gaussian weights, do not allow user to do this - mBlurBellCurveWidth = std::max( blurBellCurveWidth, 0.001f ); + mBlurBellCurveWidth = std::max(blurBellCurveWidth, 0.001f); } float GaussianBlurView::CalcGaussianWeight(float x) @@ -561,22 +547,22 @@ float GaussianBlurView::CalcGaussianWeight(float x) void GaussianBlurView::SetShaderConstants() { - Vector2 *uvOffsets; - float ofs; - float *weights; - float w, totalWeights; + Vector2* uvOffsets; + float ofs; + float* weights; + float w, totalWeights; unsigned int i; uvOffsets = new Vector2[mNumSamples + 1]; - weights = new float[mNumSamples + 1]; + weights = new float[mNumSamples + 1]; totalWeights = weights[0] = CalcGaussianWeight(0); - uvOffsets[0].x = 0.0f; - uvOffsets[0].y = 0.0f; + uvOffsets[0].x = 0.0f; + uvOffsets[0].y = 0.0f; - for(i=0; i> 1; i++) + for(i = 0; i < mNumSamples >> 1; i++) { - w = CalcGaussianWeight((float)(i + 1)); + w = CalcGaussianWeight((float)(i + 1)); weights[(i << 1) + 1] = w; weights[(i << 1) + 2] = w; totalWeights += w * 2.0f; @@ -585,8 +571,8 @@ void GaussianBlurView::SetShaderConstants() ofs = ((float)(i << 1)) + 1.5f; // get offsets from units of pixels into uv coordinates in [0..1] - float ofsX = ofs / mDownsampledWidth; - float ofsY = ofs / mDownsampledHeight; + float ofsX = ofs / mDownsampledWidth; + float ofsY = ofs / mDownsampledHeight; uvOffsets[(i << 1) + 1].x = ofsX; uvOffsets[(i << 1) + 1].y = ofsY; @@ -594,7 +580,7 @@ void GaussianBlurView::SetShaderConstants() uvOffsets[(i << 1) + 2].y = -ofsY; } - for(i=0; i -#include #include +#include +#include // INTERNAL INCLUDES -#include #include -#include #include -#include -#include -#include #include +#include +#include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); BaseHandle Create() @@ -53,11 +49,11 @@ BaseHandle Create() } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ImageView, Toolkit::Control, Create ); -DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "image", MAP, IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, ImageView, "preMultipliedAlpha", BOOLEAN, PRE_MULTIPLIED_ALPHA ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ImageView, Toolkit::Control, Create); +DALI_PROPERTY_REGISTRATION(Toolkit, ImageView, "image", MAP, IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, ImageView, "preMultipliedAlpha", BOOLEAN, PRE_MULTIPLIED_ALPHA) -DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, ImageView, "pixelArea", Vector4(0.f, 0.f, 1.f, 1.f), PIXEL_AREA ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT(Toolkit, ImageView, "pixelArea", Vector4(0.f, 0.f, 1.f, 1.f), PIXEL_AREA) DALI_TYPE_REGISTRATION_END() } // anonymous namespace @@ -65,10 +61,10 @@ DALI_TYPE_REGISTRATION_END() using namespace Dali; ImageView::ImageView() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mImageSize(), - mImageVisualPaddingSetByTransform( false ), - mImageViewPixelAreaSetByFittingMode( false ) + mImageVisualPaddingSetByTransform(false), + mImageViewPixelAreaSetByFittingMode(false) { } @@ -80,7 +76,7 @@ Toolkit::ImageView ImageView::New() { ImageView* impl = new ImageView(); - Toolkit::ImageView handle = Toolkit::ImageView( *impl ); + Toolkit::ImageView handle = Toolkit::ImageView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -94,46 +90,45 @@ Toolkit::ImageView ImageView::New() void ImageView::OnInitialize() { // ImageView can relayout in the OnImageReady, alternative to a signal would be to have a upcall from the Control to ImageView - Dali::Toolkit::Control handle( GetOwner() ); - handle.ResourceReadySignal().Connect( this, &ImageView::OnResourceReady ); + Dali::Toolkit::Control handle(GetOwner()); + handle.ResourceReadySignal().Connect(this, &ImageView::OnResourceReady); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::IMAGE ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::IMAGE)); + }); //Enable highightability - Self().SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); - + Self().SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); } -void ImageView::SetImage( const Property::Map& map ) +void ImageView::SetImage(const Property::Map& map) { // Comparing a property map is too expensive so just creating a new visual mPropertyMap = map; mUrl.clear(); - Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( mPropertyMap ); - if( visual ) + Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(mPropertyMap); + if(visual) { // Don't set mVisual until it is ready and shown. Getters will still use current visual. - if( !mVisual ) + if(!mVisual) { mVisual = visual; } - if( !mShaderMap.Empty() ) + if(!mShaderMap.Empty()) { - Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); - visualImpl.SetCustomShader( mShaderMap ); + Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); + visualImpl.SetCustomShader(mShaderMap); } - DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual ); + DevelControl::RegisterVisual(*this, Toolkit::ImageView::Property::IMAGE, visual); } else { // Unregister the exsiting visual - DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE ); + DevelControl::UnregisterVisual(*this, Toolkit::ImageView::Property::IMAGE); // Trigger a size negotiation request that may be needed when unregistering a visual. RelayoutRequest(); @@ -142,34 +137,34 @@ void ImageView::SetImage( const Property::Map& map ) // Signal that a Relayout may be needed } -void ImageView::SetImage( const std::string& url, ImageDimensions size ) +void ImageView::SetImage(const std::string& url, ImageDimensions size) { // Don't bother comparing if we had a visual previously, just drop old visual and create new one - mUrl = url; + mUrl = url; mImageSize = size; mPropertyMap.Clear(); // Don't set mVisual until it is ready and shown. Getters will still use current visual. - Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( url, size ); - if( visual ) + Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(url, size); + if(visual) { - if( !mVisual ) + if(!mVisual) { mVisual = visual; } - if( !mShaderMap.Empty() ) + if(!mShaderMap.Empty()) { - Internal::Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); - visualImpl.SetCustomShader( mShaderMap ); + Internal::Visual::Base& visualImpl = Toolkit::GetImplementation(visual); + visualImpl.SetCustomShader(mShaderMap); } - DevelControl::RegisterVisual( *this, Toolkit::ImageView::Property::IMAGE, visual ); + DevelControl::RegisterVisual(*this, Toolkit::ImageView::Property::IMAGE, visual); } else { // Unregister the exsiting visual - DevelControl::UnregisterVisual( *this, Toolkit::ImageView::Property::IMAGE ); + DevelControl::UnregisterVisual(*this, Toolkit::ImageView::Property::IMAGE); // Trigger a size negotiation request that may be needed when unregistering a visual. RelayoutRequest(); @@ -178,128 +173,128 @@ void ImageView::SetImage( const std::string& url, ImageDimensions size ) // Signal that a Relayout may be needed } -void ImageView::EnablePreMultipliedAlpha( bool preMultipled ) +void ImageView::EnablePreMultipliedAlpha(bool preMultipled) { - if( mVisual ) + if(mVisual) { - Toolkit::GetImplementation( mVisual ).EnablePreMultipliedAlpha( preMultipled ); + Toolkit::GetImplementation(mVisual).EnablePreMultipliedAlpha(preMultipled); } } bool ImageView::IsPreMultipliedAlphaEnabled() const { - if( mVisual ) + if(mVisual) { - return Toolkit::GetImplementation( mVisual ).IsPreMultipliedAlphaEnabled(); + return Toolkit::GetImplementation(mVisual).IsPreMultipliedAlphaEnabled(); } return false; } -void ImageView::SetDepthIndex( int depthIndex ) +void ImageView::SetDepthIndex(int depthIndex) { - if( mVisual ) + if(mVisual) { - mVisual.SetDepthIndex( depthIndex ); + mVisual.SetDepthIndex(depthIndex); } } Vector3 ImageView::GetNaturalSize() { - if( mVisual ) + if(mVisual) { Vector2 rendererNaturalSize; - mVisual.GetNaturalSize( rendererNaturalSize ); + mVisual.GetNaturalSize(rendererNaturalSize); Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); - rendererNaturalSize.width += ( padding.start + padding.end ); - rendererNaturalSize.height += ( padding.top + padding.bottom ); - return Vector3( rendererNaturalSize ); + rendererNaturalSize.width += (padding.start + padding.end); + rendererNaturalSize.height += (padding.top + padding.bottom); + return Vector3(rendererNaturalSize); } // if no visual then use Control's natural size return Control::GetNaturalSize(); } -float ImageView::GetHeightForWidth( float width ) +float ImageView::GetHeightForWidth(float width) { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); - if( mVisual ) + if(mVisual) { - return mVisual.GetHeightForWidth( width ) + padding.top + padding.bottom; + return mVisual.GetHeightForWidth(width) + padding.top + padding.bottom; } else { - return Control::GetHeightForWidth( width ) + padding.top + padding.bottom; + return Control::GetHeightForWidth(width) + padding.top + padding.bottom; } } -float ImageView::GetWidthForHeight( float height ) +float ImageView::GetWidthForHeight(float height) { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); - if( mVisual ) + if(mVisual) { - return mVisual.GetWidthForHeight( height ) + padding.start + padding.end; + return mVisual.GetWidthForHeight(height) + padding.start + padding.end; } else { - return Control::GetWidthForHeight( height ) + padding.start + padding.end; + return Control::GetWidthForHeight(height) + padding.start + padding.end; } } -void ImageView::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void ImageView::OnRelayout(const Vector2& size, RelayoutContainer& container) { - Control::OnRelayout( size, container ); - if( mVisual ) + Control::OnRelayout(size, container); + if(mVisual) { Property::Map transformMap = Property::Map(); - Extents padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + Extents padding = Self().GetProperty(Toolkit::Control::Property::PADDING); - bool zeroPadding = ( padding == Extents() ); + bool zeroPadding = (padding == Extents()); Vector2 naturalSize; - mVisual.GetNaturalSize( naturalSize ); + mVisual.GetNaturalSize(naturalSize); Dali::LayoutDirection::Type layoutDirection = static_cast( - Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { - std::swap( padding.start, padding.end ); + std::swap(padding.start, padding.end); } // remove padding from the size to know how much is left for the visual - Vector2 finalSize = size - Vector2( padding.start + padding.end, padding.top + padding.bottom ); - Vector2 finalOffset = Vector2( padding.start, padding.top ); + Vector2 finalSize = size - Vector2(padding.start + padding.end, padding.top + padding.bottom); + Vector2 finalOffset = Vector2(padding.start, padding.top); - ApplyFittingMode( finalSize, naturalSize, finalOffset, zeroPadding , transformMap ); + ApplyFittingMode(finalSize, naturalSize, finalOffset, zeroPadding, transformMap); - mVisual.SetTransformAndSize( transformMap, size ); + mVisual.SetTransformAndSize(transformMap, size); // mVisual is not updated util the resource is ready in the case of visual replacement. // in this case, the Property Map must be initialized so that the previous value is not reused. // after mVisual is updated, the correct value will be reset. - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE ); - if( visual && visual != mVisual ) + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, Toolkit::ImageView::Property::IMAGE); + if(visual && visual != mVisual) { - visual.SetTransformAndSize( Property::Map(), size ); + visual.SetTransformAndSize(Property::Map(), size); } } } -void ImageView::OnResourceReady( Toolkit::Control control ) +void ImageView::OnResourceReady(Toolkit::Control control) { // Visual ready so update visual attached to this ImageView, following call to RelayoutRequest will use this visual. - mVisual = DevelControl::GetVisual( *this, Toolkit::ImageView::Property::IMAGE ); + mVisual = DevelControl::GetVisual(*this, Toolkit::ImageView::Property::IMAGE); // Signal that a Relayout may be needed } -void ImageView::SetTransformMapForFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, Visual::FittingMode fittingMode, Property::Map& transformMap ) +void ImageView::SetTransformMapForFittingMode(Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, Visual::FittingMode fittingMode, Property::Map& transformMap) { switch(fittingMode) { @@ -308,63 +303,63 @@ void ImageView::SetTransformMapForFittingMode( Vector2 finalSize, Vector2 natura auto availableVisualSize = finalSize; // scale to fit the padded area - finalSize = naturalSize * std::min( ( naturalSize.width ? ( availableVisualSize.width / naturalSize.width ) : 0 ), - ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) ); + finalSize = naturalSize * std::min((naturalSize.width ? (availableVisualSize.width / naturalSize.width) : 0), + (naturalSize.height ? (availableVisualSize.height / naturalSize.height) : 0)); // calculate final offset within the padded area - finalOffset += ( availableVisualSize - finalSize ) * .5f; + finalOffset += (availableVisualSize - finalSize) * .5f; // populate the transform map - transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset ) - .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize ); + transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, finalOffset) + .Add(Toolkit::Visual::Transform::Property::SIZE, finalSize); break; } case Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO: { mImageViewPixelAreaSetByFittingMode = true; - auto availableVisualSize = finalSize; - finalSize = naturalSize * std::max( ( naturalSize.width ? ( availableVisualSize.width / naturalSize.width ) : 0 ), - ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) ); + auto availableVisualSize = finalSize; + finalSize = naturalSize * std::max((naturalSize.width ? (availableVisualSize.width / naturalSize.width) : 0), + (naturalSize.height ? (availableVisualSize.height / naturalSize.height) : 0)); auto originalOffset = finalOffset; - finalOffset += ( availableVisualSize - finalSize ) * .5f; + finalOffset += (availableVisualSize - finalSize) * .5f; - float x = abs( (availableVisualSize.width - finalSize.width ) / finalSize.width )* .5f; - float y = abs( (availableVisualSize.height - finalSize.height ) / finalSize.height ) * .5f; - float widthRatio = 1.f - abs( (availableVisualSize.width - finalSize.width ) / finalSize.width ); - float heightRatio = 1.f - abs( (availableVisualSize.height - finalSize.height ) / finalSize.height ); - Vector4 pixelArea = Vector4( x, y, widthRatio, heightRatio); - Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, pixelArea ); + float x = abs((availableVisualSize.width - finalSize.width) / finalSize.width) * .5f; + float y = abs((availableVisualSize.height - finalSize.height) / finalSize.height) * .5f; + float widthRatio = 1.f - abs((availableVisualSize.width - finalSize.width) / finalSize.width); + float heightRatio = 1.f - abs((availableVisualSize.height - finalSize.height) / finalSize.height); + Vector4 pixelArea = Vector4(x, y, widthRatio, heightRatio); + Self().SetProperty(Toolkit::ImageView::Property::PIXEL_AREA, pixelArea); // populate the transform map - transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, originalOffset ) - .Add( Toolkit::Visual::Transform::Property::SIZE, availableVisualSize ); + transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, originalOffset) + .Add(Toolkit::Visual::Transform::Property::SIZE, availableVisualSize); break; } case Visual::FittingMode::CENTER: { auto availableVisualSize = finalSize; - if( availableVisualSize.width > naturalSize.width && availableVisualSize.height > naturalSize.height ) + if(availableVisualSize.width > naturalSize.width && availableVisualSize.height > naturalSize.height) { finalSize = naturalSize; } else { - finalSize = naturalSize * std::min( ( naturalSize.width ? ( availableVisualSize.width / naturalSize.width ) : 0 ), - ( naturalSize.height ? ( availableVisualSize.height / naturalSize.height ) : 0 ) ); + finalSize = naturalSize * std::min((naturalSize.width ? (availableVisualSize.width / naturalSize.width) : 0), + (naturalSize.height ? (availableVisualSize.height / naturalSize.height) : 0)); } - finalOffset += ( availableVisualSize - finalSize ) * .5f; + finalOffset += (availableVisualSize - finalSize) * .5f; // populate the transform map - transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset ) - .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize ); + transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, finalOffset) + .Add(Toolkit::Visual::Transform::Property::SIZE, finalSize); break; } case Visual::FittingMode::FILL: { - transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, finalOffset ) - .Add( Toolkit::Visual::Transform::Property::SIZE, finalSize ); + transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, finalOffset) + .Add(Toolkit::Visual::Transform::Property::SIZE, finalSize); break; } case Visual::FittingMode::FIT_WIDTH: @@ -376,53 +371,53 @@ void ImageView::SetTransformMapForFittingMode( Vector2 finalSize, Vector2 natura } } -void ImageView::ApplyFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, bool zeroPadding , Property::Map& transformMap ) +void ImageView::ApplyFittingMode(Vector2 finalSize, Vector2 naturalSize, Vector2 finalOffset, bool zeroPadding, Property::Map& transformMap) { - Visual::FittingMode fittingMode = Toolkit::GetImplementation(mVisual).GetFittingMode(); - - // Reset PIXEL_AREA after using OVER_FIT_KEEP_ASPECT_RATIO - if( mImageViewPixelAreaSetByFittingMode ) - { - Self().SetProperty( Toolkit::ImageView::Property::PIXEL_AREA, FULL_TEXTURE_RECT ); - mImageViewPixelAreaSetByFittingMode = false; - } - - if( ( !zeroPadding ) || // If padding is not zero - ( fittingMode != Visual::FittingMode::FILL ) ) - { - mImageVisualPaddingSetByTransform = true; + Visual::FittingMode fittingMode = Toolkit::GetImplementation(mVisual).GetFittingMode(); - // If FittingMode use FIT_WIDTH or FIT_HEIGTH, it need to change proper fittingMode - if( fittingMode == Visual::FittingMode::FIT_WIDTH ) - { - fittingMode = ( finalSize.height / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::FIT_KEEP_ASPECT_RATIO; - } - else if( fittingMode == Visual::FittingMode::FIT_HEIGHT ) - { - fittingMode = ( finalSize.height / naturalSize.height ) < ( finalSize.width / naturalSize.width ) ? Visual::FittingMode::FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO; - } + // Reset PIXEL_AREA after using OVER_FIT_KEEP_ASPECT_RATIO + if(mImageViewPixelAreaSetByFittingMode) + { + Self().SetProperty(Toolkit::ImageView::Property::PIXEL_AREA, FULL_TEXTURE_RECT); + mImageViewPixelAreaSetByFittingMode = false; + } - SetTransformMapForFittingMode( finalSize, naturalSize, finalOffset, fittingMode, transformMap ); + if((!zeroPadding) || // If padding is not zero + (fittingMode != Visual::FittingMode::FILL)) + { + mImageVisualPaddingSetByTransform = true; - // Set extra value for applying transformMap - transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, - Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, - Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ); + // If FittingMode use FIT_WIDTH or FIT_HEIGTH, it need to change proper fittingMode + if(fittingMode == Visual::FittingMode::FIT_WIDTH) + { + fittingMode = (finalSize.height / naturalSize.height) < (finalSize.width / naturalSize.width) ? Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::FIT_KEEP_ASPECT_RATIO; } - else if ( mImageVisualPaddingSetByTransform && zeroPadding ) // Reset offset to zero only if padding applied previously + else if(fittingMode == Visual::FittingMode::FIT_HEIGHT) { - mImageVisualPaddingSetByTransform = false; - // Reset the transform map - transformMap.Add( Toolkit::Visual::Transform::Property::OFFSET, Vector2::ZERO ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, - Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE, Vector2::ONE ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, - Vector2( Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE ) ); + fittingMode = (finalSize.height / naturalSize.height) < (finalSize.width / naturalSize.width) ? Visual::FittingMode::FIT_KEEP_ASPECT_RATIO : Visual::FittingMode::OVER_FIT_KEEP_ASPECT_RATIO; } + + SetTransformMapForFittingMode(finalSize, naturalSize, finalOffset, fittingMode, transformMap); + + // Set extra value for applying transformMap + transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, + Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, + Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)); + } + else if(mImageVisualPaddingSetByTransform && zeroPadding) // Reset offset to zero only if padding applied previously + { + mImageVisualPaddingSetByTransform = false; + // Reset the transform map + transformMap.Add(Toolkit::Visual::Transform::Property::OFFSET, Vector2::ZERO) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, + Vector2(Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE)) + .Add(Toolkit::Visual::Transform::Property::SIZE, Vector2::ONE) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, + Vector2(Toolkit::Visual::Transform::Policy::RELATIVE, Toolkit::Visual::Transform::Policy::RELATIVE)); + } } /////////////////////////////////////////////////////////// @@ -430,50 +425,50 @@ void ImageView::ApplyFittingMode( Vector2 finalSize, Vector2 naturalSize, Vector // Properties // -void ImageView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void ImageView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::ImageView imageView = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ImageView imageView = Toolkit::ImageView::DownCast(Dali::BaseHandle(object)); - if ( imageView ) + if(imageView) { - ImageView& impl = GetImpl( imageView ); - switch ( index ) + ImageView& impl = GetImpl(imageView); + switch(index) { case Toolkit::ImageView::Property::IMAGE: { - std::string imageUrl; + std::string imageUrl; const Property::Map* map; - if( value.Get( imageUrl ) ) + if(value.Get(imageUrl)) { - impl.SetImage( imageUrl, ImageDimensions() ); + impl.SetImage(imageUrl, ImageDimensions()); } // if its not a string then get a Property::Map from the property if possible. else { map = value.GetMap(); - if( map ) + if(map) { - Property::Value* shaderValue = map->Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER ); + Property::Value* shaderValue = map->Find(Toolkit::Visual::Property::SHADER, CUSTOM_SHADER); // set image only if property map contains image information other than custom shader - if( map->Count() > 1u || !shaderValue ) + if(map->Count() > 1u || !shaderValue) { - impl.SetImage( *map ); + impl.SetImage(*map); } // the property map contains only the custom shader - else if( ( map->Count() == 1u )&&( shaderValue ) ) + else if((map->Count() == 1u) && (shaderValue)) { Property::Map* shaderMap = shaderValue->GetMap(); - if( shaderMap ) + if(shaderMap) { impl.mShaderMap = *shaderMap; - if( !impl.mUrl.empty() ) + if(!impl.mUrl.empty()) { - impl.SetImage( impl.mUrl, impl.mImageSize ); + impl.SetImage(impl.mUrl, impl.mImageSize); } - else if( !impl.mPropertyMap.Empty() ) + else if(!impl.mPropertyMap.Empty()) { - impl.SetImage( impl.mPropertyMap ); + impl.SetImage(impl.mPropertyMap); } } } @@ -485,9 +480,9 @@ void ImageView::SetProperty( BaseObject* object, Property::Index index, const Pr case Toolkit::ImageView::Property::PRE_MULTIPLIED_ALPHA: { bool isPre; - if( value.Get( isPre ) ) + if(value.Get(isPre)) { - impl.EnablePreMultipliedAlpha( isPre ); + impl.EnablePreMultipliedAlpha(isPre); } break; } @@ -495,30 +490,30 @@ void ImageView::SetProperty( BaseObject* object, Property::Index index, const Pr } } -Property::Value ImageView::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value ImageView::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::ImageView imageview = Toolkit::ImageView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ImageView imageview = Toolkit::ImageView::DownCast(Dali::BaseHandle(object)); - if ( imageview ) + if(imageview) { - ImageView& impl = GetImpl( imageview ); - switch ( propertyIndex ) + ImageView& impl = GetImpl(imageview); + switch(propertyIndex) { case Toolkit::ImageView::Property::IMAGE: { - if ( !impl.mUrl.empty() ) + if(!impl.mUrl.empty()) { value = impl.mUrl; } else { - Property::Map map; - Toolkit::Visual::Base visual = DevelControl::GetVisual( impl, Toolkit::ImageView::Property::IMAGE ); - if( visual ) + Property::Map map; + Toolkit::Visual::Base visual = DevelControl::GetVisual(impl, Toolkit::ImageView::Property::IMAGE); + if(visual) { - visual.CreatePropertyMap( map ); + visual.CreatePropertyMap(map); } value = map; } diff --git a/dali-toolkit/internal/controls/magnifier/magnifier-impl.cpp b/dali-toolkit/internal/controls/magnifier/magnifier-impl.cpp index 0be5d46..11fa7a7 100644 --- a/dali-toolkit/internal/controls/magnifier/magnifier-impl.cpp +++ b/dali-toolkit/internal/controls/magnifier/magnifier-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,49 +19,46 @@ #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 Toolkit { - namespace Internal { - namespace // unnamed namespace { - - Dali::BaseHandle Create() { return Toolkit::Magnifier::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Magnifier, Toolkit::Control, Create ) +// clang-format off +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Magnifier, Toolkit::Control, Create) -DALI_PROPERTY_REGISTRATION( Toolkit, Magnifier, "frameVisibility", BOOLEAN, FRAME_VISIBILITY ) -DALI_PROPERTY_REGISTRATION( Toolkit, Magnifier, "magnificationFactor", FLOAT, MAGNIFICATION_FACTOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, Magnifier, "frameVisibility", BOOLEAN, FRAME_VISIBILITY ) +DALI_PROPERTY_REGISTRATION(Toolkit, Magnifier, "magnificationFactor", FLOAT, MAGNIFICATION_FACTOR) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Magnifier, "sourcePosition", VECTOR3, SOURCE_POSITION ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Magnifier, "sourcePosition", VECTOR3, SOURCE_POSITION) DALI_TYPE_REGISTRATION_END() +// clang-format on -const float IMAGE_BORDER_INDENT = 5.0f; ///< Indent of border in pixels. +const float IMAGE_BORDER_INDENT = 5.0f; ///< Indent of border in pixels. struct CameraActorPositionConstraint { @@ -71,7 +68,7 @@ struct CameraActorPositionConstraint { } - void operator()( Vector3& current, const PropertyInputContainer& inputs ) + void operator()(Vector3& current, const PropertyInputContainer& inputs) { const Vector3& sourcePosition = inputs[0]->GetVector3(); @@ -81,8 +78,7 @@ struct CameraActorPositionConstraint } Vector2 mStageSize; - float mDefaultCameraDistance; - + float mDefaultCameraDistance; }; struct RenderTaskViewportPositionConstraint @@ -92,7 +88,7 @@ struct RenderTaskViewportPositionConstraint { } - void operator()( Vector2& current, const PropertyInputContainer& inputs ) + void operator()(Vector2& current, const PropertyInputContainer& inputs) { current = inputs[0]->GetVector3(); // World position? @@ -102,8 +98,8 @@ struct RenderTaskViewportPositionConstraint Vector3 size = inputs[1]->GetVector3() * inputs[2]->GetVector3(); /* magnifier-size * magnifier-scale */ // Reposition, and resize viewport to reflect the world bounds of this Magnifier actor. - current.x += ( mStageSize.width - size.width ) * 0.5f; - current.y += ( mStageSize.height - size.height ) * 0.5f; + current.x += (mStageSize.width - size.width) * 0.5f; + current.y += (mStageSize.height - size.height) * 0.5f; } Vector2 mStageSize; @@ -115,7 +111,7 @@ struct RenderTaskViewportSizeConstraint { } - void operator()( Vector2& current, const PropertyInputContainer& inputs ) + void operator()(Vector2& current, const PropertyInputContainer& inputs) { current = inputs[0]->GetVector3() * inputs[1]->GetVector3(); /* magnifier-size * magnifier-scale */ } @@ -143,7 +139,7 @@ Dali::Toolkit::Magnifier Magnifier::New() } Magnifier::Magnifier() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mDefaultCameraDistance(1000.f), mActorSize(Vector3::ZERO), mMagnificationFactor(1.0f) @@ -152,12 +148,12 @@ Magnifier::Magnifier() void Magnifier::SetSourceActor(Actor actor) { - mTask.SetSourceActor( actor ); + mTask.SetSourceActor(actor); } void Magnifier::Initialize() { - Actor self = Self(); + Actor self = Self(); Vector2 stageSize(Stage::GetCurrent().GetSize()); // NOTE: @@ -172,9 +168,9 @@ void Magnifier::Initialize() // and what is not. mSourceActor = Actor::New(); Stage().GetCurrent().Add(mSourceActor); - mSourceActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - Constraint constraint = Constraint::New( mSourceActor, Actor::Property::POSITION, EqualToConstraint() ); - constraint.AddSource( Source( self, Toolkit::Magnifier::Property::SOURCE_POSITION ) ); + mSourceActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + Constraint constraint = Constraint::New(mSourceActor, Actor::Property::POSITION, EqualToConstraint()); + constraint.AddSource(Source(self, Toolkit::Magnifier::Property::SOURCE_POSITION)); constraint.Apply(); // create the render task this will render content on top of everything @@ -194,42 +190,41 @@ void Magnifier::Initialize() // But we can determine the initial position using the same formula: // distance = stage.height * 0.5 / tan(FOV * 0.5) - RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); - RenderTask renderTask = taskList.GetTask(0u); - float fov = renderTask.GetCameraActor().GetFieldOfView(); - mDefaultCameraDistance = (stageSize.height * 0.5f) / tanf(fov * 0.5f); + RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); + RenderTask renderTask = taskList.GetTask(0u); + float fov = renderTask.GetCameraActor().GetFieldOfView(); + mDefaultCameraDistance = (stageSize.height * 0.5f) / tanf(fov * 0.5f); // Use a 1 frame delayed source position to determine the camera actor's position. // This is necessary as the viewport is determined by the Magnifier's Actor's World position (which is computed // at the end of the update cycle i.e. after constraints have been applied.) //Property::Index propertySourcePositionDelayed = mCameraActor.RegisterProperty("delayedSourcePosition", Vector3::ZERO); - constraint = Constraint::New( mCameraActor, Actor::Property::POSITION, CameraActorPositionConstraint(stageSize, mDefaultCameraDistance) ); - constraint.AddSource( Source( mSourceActor, Actor::Property::WORLD_POSITION ) ); + constraint = Constraint::New(mCameraActor, Actor::Property::POSITION, CameraActorPositionConstraint(stageSize, mDefaultCameraDistance)); + constraint.AddSource(Source(mSourceActor, Actor::Property::WORLD_POSITION)); constraint.Apply(); // Apply constraint to render-task viewport position - constraint = Constraint::New( mTask, RenderTask::Property::VIEWPORT_POSITION, RenderTaskViewportPositionConstraint(stageSize) ); - constraint.AddSource( Source( self, Actor::Property::WORLD_POSITION ) ); - constraint.AddSource( Source( self, Actor::Property::SIZE ) ); - constraint.AddSource( Source( self, Actor::Property::WORLD_SCALE ) ); + constraint = Constraint::New(mTask, RenderTask::Property::VIEWPORT_POSITION, RenderTaskViewportPositionConstraint(stageSize)); + constraint.AddSource(Source(self, Actor::Property::WORLD_POSITION)); + constraint.AddSource(Source(self, Actor::Property::SIZE)); + constraint.AddSource(Source(self, Actor::Property::WORLD_SCALE)); constraint.Apply(); // Apply constraint to render-task viewport position - constraint = Constraint::New( mTask, RenderTask::Property::VIEWPORT_SIZE, RenderTaskViewportSizeConstraint() ); - constraint.AddSource( Source( self, Actor::Property::SIZE ) ); - constraint.AddSource( Source( self, Actor::Property::WORLD_SCALE ) ); + constraint = Constraint::New(mTask, RenderTask::Property::VIEWPORT_SIZE, RenderTaskViewportSizeConstraint()); + constraint.AddSource(Source(self, Actor::Property::SIZE)); + constraint.AddSource(Source(self, Actor::Property::WORLD_SCALE)); constraint.Apply(); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } Magnifier::~Magnifier() { - } void Magnifier::InitializeRenderTask() @@ -247,7 +242,7 @@ void Magnifier::InitializeRenderTask() mCameraActor.SetType(Camera::FREE_LOOK); stage.Add(mCameraActor); - mTask.SetCameraActor( mCameraActor ); + mTask.SetCameraActor(mCameraActor); SetFrameVisibility(true); } @@ -263,24 +258,24 @@ void Magnifier::SetFrameVisibility(bool visible) { Actor self(Self()); - mFrame = Actor::New( ); - mFrame.SetProperty( Actor::Property::INHERIT_POSITION, false ); - mFrame.SetProperty( Actor::Property::INHERIT_SCALE, true ); - mFrame.SetResizePolicy( ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS ); - Vector3 sizeOffset(IMAGE_BORDER_INDENT*2.f - 2.f, IMAGE_BORDER_INDENT*2.f - 2.f, 0.0f); - mFrame.SetProperty( Actor::Property::SIZE_MODE_FACTOR, sizeOffset ); + mFrame = Actor::New(); + mFrame.SetProperty(Actor::Property::INHERIT_POSITION, false); + mFrame.SetProperty(Actor::Property::INHERIT_SCALE, true); + mFrame.SetResizePolicy(ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS); + Vector3 sizeOffset(IMAGE_BORDER_INDENT * 2.f - 2.f, IMAGE_BORDER_INDENT * 2.f - 2.f, 0.0f); + mFrame.SetProperty(Actor::Property::SIZE_MODE_FACTOR, sizeOffset); Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get(); Property::Map map; - map[ Toolkit::Visual::Property::TYPE ] = Toolkit::Visual::BORDER; - map[ Toolkit::BorderVisual::Property::COLOR ] = Color::WHITE; - map[ Toolkit::BorderVisual::Property::SIZE ] = IMAGE_BORDER_INDENT; - Toolkit::Visual::Base borderVisual = visualFactory.CreateVisual( map ); - Toolkit::GetImplementation(borderVisual).SetOnScene( mFrame ); - - Constraint constraint = Constraint::New( mFrame, Actor::Property::POSITION, EqualToConstraint() ); - constraint.AddSource( ParentSource( Actor::Property::WORLD_POSITION ) ); + map[Toolkit::Visual::Property::TYPE] = Toolkit::Visual::BORDER; + map[Toolkit::BorderVisual::Property::COLOR] = Color::WHITE; + map[Toolkit::BorderVisual::Property::SIZE] = IMAGE_BORDER_INDENT; + Toolkit::Visual::Base borderVisual = visualFactory.CreateVisual(map); + Toolkit::GetImplementation(borderVisual).SetOnScene(mFrame); + + Constraint constraint = Constraint::New(mFrame, Actor::Property::POSITION, EqualToConstraint()); + constraint.AddSource(ParentSource(Actor::Property::WORLD_POSITION)); constraint.Apply(); self.Add(mFrame); @@ -301,7 +296,7 @@ void Magnifier::OnSizeSet(const Vector3& targetSize) mActorSize = targetSize; Update(); - Control::OnSizeSet( targetSize ); + Control::OnSizeSet(targetSize); } float Magnifier::GetMagnificationFactor() const @@ -321,8 +316,8 @@ void Magnifier::Update() // should be updated when: // Magnifier's world size/scale changes. - Actor self(Self()); - Vector3 worldSize = mActorSize * self.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_SCALE ); + Actor self(Self()); + Vector3 worldSize = mActorSize * self.GetCurrentProperty(Actor::Property::WORLD_SCALE); // Adjust field of view to scale content @@ -335,46 +330,46 @@ void Magnifier::Update() // |./ // |/ <--- fov/2 radians. // - const float fov = atanf( 0.5f * worldSize.height / mDefaultCameraDistance / mMagnificationFactor) * 2.0f; - mCameraActor.SetFieldOfView( fov ); + const float fov = atanf(0.5f * worldSize.height / mDefaultCameraDistance / mMagnificationFactor) * 2.0f; + mCameraActor.SetFieldOfView(fov); // Adjust aspect ratio to compensate for rectangular viewports. - mCameraActor.SetAspectRatio( worldSize.width / worldSize.height ); + mCameraActor.SetAspectRatio(worldSize.width / worldSize.height); } -void Magnifier::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void Magnifier::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast(Dali::BaseHandle(object)); - if( magnifier ) + if(magnifier) { - Magnifier& magnifierImpl( GetImpl( magnifier ) ); - switch( index ) + Magnifier& magnifierImpl(GetImpl(magnifier)); + switch(index) { case Toolkit::Magnifier::Property::FRAME_VISIBILITY: { - magnifierImpl.SetFrameVisibility( value.Get< bool >() ); + magnifierImpl.SetFrameVisibility(value.Get()); break; } case Toolkit::Magnifier::Property::MAGNIFICATION_FACTOR: { - magnifierImpl.SetMagnificationFactor( value.Get< float >() ); + magnifierImpl.SetMagnificationFactor(value.Get()); break; } } } } -Property::Value Magnifier::GetProperty( BaseObject* object, Property::Index index ) +Property::Value Magnifier::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Magnifier magnifier = Toolkit::Magnifier::DownCast(Dali::BaseHandle(object)); - if( magnifier ) + if(magnifier) { - Magnifier& magnifierImpl( GetImpl( magnifier ) ); - switch( index ) + Magnifier& magnifierImpl(GetImpl(magnifier)); + switch(index) { case Toolkit::Magnifier::Property::FRAME_VISIBILITY: { diff --git a/dali-toolkit/internal/controls/model3d-view/model3d-view-impl.cpp b/dali-toolkit/internal/controls/model3d-view/model3d-view-impl.cpp index 1665905..492f529 100644 --- a/dali-toolkit/internal/controls/model3d-view/model3d-view-impl.cpp +++ b/dali-toolkit/internal/controls/model3d-view/model3d-view-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,32 +19,28 @@ #include "model3d-view-impl.h" // EXTERNAL INCLUDES -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // Texture indices are constants. enum TextureIndex { @@ -58,15 +54,15 @@ enum TextureIndex * @param[in] imageUrl The URL of the file * @return A texture if loading succeeds, an empty handle otherwise */ -Texture LoadTexture( const char* imageUrl ) +Texture LoadTexture(const char* imageUrl) { - Texture texture; - Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl ); - if( pixelBuffer ) + Texture texture; + Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl); + if(pixelBuffer) { - texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() ); - PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer ); - texture.Upload( pixelData ); + texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight()); + PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); + texture.Upload(pixelData); texture.GenerateMipmaps(); } @@ -80,17 +76,17 @@ BaseHandle Create() } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Model3dView, Toolkit::Control, Create ); +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Model3dView, Toolkit::Control, Create); -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "geometryUrl", STRING, GEOMETRY_URL) -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "materialUrl", STRING, MATERIAL_URL) -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "imagesUrl", STRING, IMAGES_URL) -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "illuminationType", INTEGER, ILLUMINATION_TYPE) -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "texture0Url", STRING, TEXTURE0_URL) -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "texture1Url", STRING, TEXTURE1_URL) -DALI_PROPERTY_REGISTRATION( Toolkit, Model3dView, "texture2Url", STRING, TEXTURE2_URL) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "geometryUrl", STRING, GEOMETRY_URL) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "materialUrl", STRING, MATERIAL_URL) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "imagesUrl", STRING, IMAGES_URL) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "illuminationType", INTEGER, ILLUMINATION_TYPE) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "texture0Url", STRING, TEXTURE0_URL) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "texture1Url", STRING, TEXTURE1_URL) +DALI_PROPERTY_REGISTRATION(Toolkit, Model3dView, "texture2Url", STRING, TEXTURE2_URL) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Model3dView, "lightPosition", VECTOR3, LIGHT_POSITION) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Model3dView, "lightPosition", VECTOR3, LIGHT_POSITION) DALI_TYPE_REGISTRATION_END() @@ -99,13 +95,13 @@ DALI_TYPE_REGISTRATION_END() using namespace Dali; Model3dView::Model3dView() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)) { mIlluminationType = Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP; mCameraFOV = Math::PI_OVER_180 * 45.f; - mControlSize = Vector2(100.,100.); + mControlSize = Vector2(100., 100.); } Model3dView::~Model3dView() @@ -116,7 +112,7 @@ Toolkit::Model3dView Model3dView::New() { Model3dView* impl = new Model3dView(); - Dali::Toolkit::Model3dView handle = Dali::Toolkit::Model3dView( *impl ); + Dali::Toolkit::Model3dView handle = Dali::Toolkit::Model3dView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -125,18 +121,18 @@ Toolkit::Model3dView Model3dView::New() return handle; } -void Model3dView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void Model3dView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast(Dali::BaseHandle(object)); - if( model3dView ) + if(model3dView) { - Model3dView& impl( GetImpl( model3dView ) ); - switch( index ) + Model3dView& impl(GetImpl(model3dView)); + switch(index) { case Toolkit::Model3dView::Property::GEOMETRY_URL: { - if( value.Get(impl.mObjUrl) ) + if(value.Get(impl.mObjUrl)) { impl.LoadGeometry(); impl.CreateGeometry(); @@ -145,7 +141,7 @@ void Model3dView::SetProperty( BaseObject* object, Property::Index index, const } case Toolkit::Model3dView::Property::MATERIAL_URL: { - if( value.Get(impl.mTextureSetUrl) ) + if(value.Get(impl.mTextureSetUrl)) { impl.LoadMaterial(); impl.CreateMaterial(); @@ -155,7 +151,7 @@ void Model3dView::SetProperty( BaseObject* object, Property::Index index, const } case Toolkit::Model3dView::Property::IMAGES_URL: { - if( value.Get(impl.mImagesUrl) ) + if(value.Get(impl.mImagesUrl)) { impl.LoadTextures(); } @@ -164,7 +160,7 @@ void Model3dView::SetProperty( BaseObject* object, Property::Index index, const case Toolkit::Model3dView::Property::ILLUMINATION_TYPE: { int illuminationType; - if( value.Get(illuminationType) ) + if(value.Get(illuminationType)) { impl.mIlluminationType = Toolkit::Model3dView::IlluminationType(illuminationType); impl.CreateGeometry(); @@ -192,16 +188,16 @@ void Model3dView::SetProperty( BaseObject* object, Property::Index index, const } } -Property::Value Model3dView::GetProperty( BaseObject* object, Property::Index index ) +Property::Value Model3dView::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Model3dView model3dView = Toolkit::Model3dView::DownCast(Dali::BaseHandle(object)); - if( model3dView ) + if(model3dView) { - Model3dView& impl( GetImpl( model3dView ) ); - switch( index ) + Model3dView& impl(GetImpl(model3dView)); + switch(index) { case Toolkit::Model3dView::Property::GEOMETRY_URL: { @@ -246,30 +242,29 @@ Property::Value Model3dView::GetProperty( BaseObject* object, Property::Index in ///////////////////////////////////////////////////////////// - -void Model3dView::OnSceneConnection( int depth ) +void Model3dView::OnSceneConnection(int depth) { CustomActor self = Self(); - self.AddRenderer( mRenderer ); + self.AddRenderer(mRenderer); - if( mObjLoader.IsSceneLoaded() ) + if(mObjLoader.IsSceneLoaded()) { - mMesh = mObjLoader.CreateGeometry( GetShaderProperties( mIlluminationType ), true ); + mMesh = mObjLoader.CreateGeometry(GetShaderProperties(mIlluminationType), true); CreateMaterial(); LoadTextures(); - mRenderer.SetGeometry( mMesh ); + mRenderer.SetGeometry(mMesh); //create constraint for lightPosition Property with uLightPosition in the shader - Vector3 lightPosition( 0, 0, 0 ); - Dali::Property::Index lightProperty = mShader.RegisterProperty( "uLightPosition", lightPosition ); - Constraint constraint = Constraint::New( mShader, lightProperty, EqualToConstraint() ); - constraint.AddSource( Source( self, Toolkit::Model3dView::Property::LIGHT_POSITION ) ); + Vector3 lightPosition(0, 0, 0); + Dali::Property::Index lightProperty = mShader.RegisterProperty("uLightPosition", lightPosition); + Constraint constraint = Constraint::New(mShader, lightProperty, EqualToConstraint()); + constraint.AddSource(Source(self, Toolkit::Model3dView::Property::LIGHT_POSITION)); constraint.Apply(); } - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } /////////////////////////////////////////////////////////// @@ -280,30 +275,30 @@ void Model3dView::OnSceneConnection( int depth ) void Model3dView::OnInitialize() { //Create empty versions of the geometry and material so we always have a Renderer - Geometry mesh = Geometry::New(); - Shader shader = Shader::New( SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG ); - mRenderer = Renderer::New( mesh, shader ); - - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::IMAGE ) ); - } ); + Geometry mesh = Geometry::New(); + Shader shader = Shader::New(SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG); + mRenderer = Renderer::New(mesh, shader); + + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::IMAGE)); + }); } void Model3dView::LoadGeometry() { //Load file in adaptor - std::streampos fileSize; + std::streampos fileSize; Dali::Vector fileContent; - if (FileLoader::ReadFile(mObjUrl,fileSize,fileContent,FileLoader::TEXT)) + if(FileLoader::ReadFile(mObjUrl, fileSize, fileContent, FileLoader::TEXT)) { mObjLoader.ClearArrays(); mObjLoader.LoadObject(fileContent.Begin(), fileSize); //Get size information from the obj loaded mSceneCenter = mObjLoader.GetCenter(); - mSceneSize = mObjLoader.GetSize(); + mSceneSize = mObjLoader.GetSize(); } else { @@ -314,10 +309,10 @@ void Model3dView::LoadGeometry() void Model3dView::LoadMaterial() { //Load file in adaptor - std::streampos fileSize; + std::streampos fileSize; Dali::Vector fileContent; - if( FileLoader::ReadFile(mTextureSetUrl, fileSize, fileContent, FileLoader::TEXT) ) + if(FileLoader::ReadFile(mTextureSetUrl, fileSize, fileContent, FileLoader::TEXT)) { mObjLoader.LoadMaterial(fileContent.Begin(), fileSize, mTexture0Url, mTexture1Url, mTexture2Url); } @@ -333,56 +328,56 @@ void Model3dView::Load() LoadMaterial(); } -void Model3dView::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void Model3dView::OnRelayout(const Vector2& size, RelayoutContainer& container) { UpdateView(); } void Model3dView::UpdateView() { - if( mObjLoader.IsSceneLoaded() ) + if(mObjLoader.IsSceneLoaded()) { //The object will always be centred Matrix scaleMatrix; scaleMatrix.SetIdentityAndScale(Vector3(1.0, -1.0, 1.0)); - mShader.RegisterProperty( "uObjectMatrix", scaleMatrix ); + mShader.RegisterProperty("uObjectMatrix", scaleMatrix); } } void Model3dView::CreateGeometry() { - if( mObjLoader.IsSceneLoaded() ) + if(mObjLoader.IsSceneLoaded()) { - mMesh = mObjLoader.CreateGeometry( GetShaderProperties( mIlluminationType ), true ); + mMesh = mObjLoader.CreateGeometry(GetShaderProperties(mIlluminationType), true); - if( mRenderer ) + if(mRenderer) { - mRenderer.SetGeometry( mMesh ); - mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON ); - mRenderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON ); + mRenderer.SetGeometry(mMesh); + mRenderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON); + mRenderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON); } } } void Model3dView::UpdateShaderUniforms() { - if( mShader ) + if(mShader) { //Update shader related info, uniforms, etc. for the new shader UpdateView(); - Vector3 lightPosition( 0, 0, 0 ); - Dali::Property::Index lightProperty = mShader.RegisterProperty( "uLightPosition", lightPosition ); + Vector3 lightPosition(0, 0, 0); + Dali::Property::Index lightProperty = mShader.RegisterProperty("uLightPosition", lightPosition); CustomActor self = Self(); //create constraint for lightPosition Property with uLightPosition in the shader - if( lightProperty ) + if(lightProperty) { - Constraint constraint = Constraint::New( mShader, lightProperty, EqualToConstraint() ); - constraint.AddSource( Source( self, Toolkit::Model3dView::Property::LIGHT_POSITION ) ); + Constraint constraint = Constraint::New(mShader, lightProperty, EqualToConstraint()); + constraint.AddSource(Source(self, Toolkit::Model3dView::Property::LIGHT_POSITION)); constraint.Apply(); } } @@ -390,34 +385,34 @@ void Model3dView::UpdateShaderUniforms() void Model3dView::CreateMaterial() { - if( mObjLoader.IsMaterialLoaded() && (mTexture0Url != "") && mObjLoader.IsTexturePresent() ) + if(mObjLoader.IsMaterialLoaded() && (mTexture0Url != "") && mObjLoader.IsTexturePresent()) { - if( (mTexture2Url != "") && (mTexture1Url != "") && (mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP) ) + if((mTexture2Url != "") && (mTexture1Url != "") && (mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP)) { - mShader = Shader::New( SHADER_MODEL3D_VIEW_NRMMAP_SHADER_VERT, SHADER_MODEL3D_VIEW_NRMMAP_SHADER_FRAG ); + mShader = Shader::New(SHADER_MODEL3D_VIEW_NRMMAP_SHADER_VERT, SHADER_MODEL3D_VIEW_NRMMAP_SHADER_FRAG); } - else if( mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE || - mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP ) + else if(mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE || + mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP) { - mShader = Shader::New( SHADER_MODEL3D_VIEW_SHADER_VERT, SHADER_MODEL3D_VIEW_SHADER_FRAG ); + mShader = Shader::New(SHADER_MODEL3D_VIEW_SHADER_VERT, SHADER_MODEL3D_VIEW_SHADER_FRAG); } else { - mShader = Shader::New( SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG ); + mShader = Shader::New(SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG); } } else { - mShader = Shader::New( SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG ); + mShader = Shader::New(SHADER_MODEL3D_VIEW_SIMPLE_SHADER_VERT, SHADER_MODEL3D_VIEW_SIMPLE_SHADER_FRAG); } mTextureSet = TextureSet::New(); - if( mRenderer ) + if(mRenderer) { - mRenderer.SetTextures( mTextureSet ); - mRenderer.SetShader( mShader ); - mRenderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK ); + mRenderer.SetTextures(mTextureSet); + mRenderer.SetShader(mShader); + mRenderer.SetProperty(Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK); } UpdateShaderUniforms(); @@ -425,70 +420,70 @@ void Model3dView::CreateMaterial() void Model3dView::LoadTextures() { - if( !mTextureSet ) + if(!mTextureSet) { return; } Sampler sampler = Sampler::New(); - sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR ); + sampler.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR); // Setup diffuse texture. - if( !mTexture0Url.empty() && ( mIlluminationType != Toolkit::Model3dView::DIFFUSE ) ) + if(!mTexture0Url.empty() && (mIlluminationType != Toolkit::Model3dView::DIFFUSE)) { std::string imageUrl = mImagesUrl + mTexture0Url; //Load textures - Texture diffuseTexture = LoadTexture( imageUrl.c_str() ); - if( diffuseTexture ) + Texture diffuseTexture = LoadTexture(imageUrl.c_str()); + if(diffuseTexture) { - mTextureSet.SetTexture( DIFFUSE_TEXTURE_INDEX, diffuseTexture ); - mTextureSet.SetSampler( DIFFUSE_TEXTURE_INDEX, sampler ); + mTextureSet.SetTexture(DIFFUSE_TEXTURE_INDEX, diffuseTexture); + mTextureSet.SetSampler(DIFFUSE_TEXTURE_INDEX, sampler); } } - if( mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP ) + if(mIlluminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP) { // Setup normal map texture. - if( !mTexture1Url.empty() ) + if(!mTexture1Url.empty()) { std::string imageUrl = mImagesUrl + mTexture1Url; //Load textures - Texture normalTexture = LoadTexture( imageUrl.c_str() ); - if( normalTexture ) + Texture normalTexture = LoadTexture(imageUrl.c_str()); + if(normalTexture) { - mTextureSet.SetTexture( NORMAL_TEXTURE_INDEX, normalTexture ); - mTextureSet.SetSampler( NORMAL_TEXTURE_INDEX, sampler ); + mTextureSet.SetTexture(NORMAL_TEXTURE_INDEX, normalTexture); + mTextureSet.SetSampler(NORMAL_TEXTURE_INDEX, sampler); } } - if( !mTexture2Url.empty() ) + if(!mTexture2Url.empty()) { // Setup gloss map texture. std::string imageUrl = mImagesUrl + mTexture2Url; //Load textures - Texture glossTexture = LoadTexture( imageUrl.c_str() ); - if( glossTexture ) + Texture glossTexture = LoadTexture(imageUrl.c_str()); + if(glossTexture) { - mTextureSet.SetTexture( GLOSS_TEXTURE_INDEX, glossTexture ); - mTextureSet.SetSampler( GLOSS_TEXTURE_INDEX, sampler ); + mTextureSet.SetTexture(GLOSS_TEXTURE_INDEX, glossTexture); + mTextureSet.SetSampler(GLOSS_TEXTURE_INDEX, sampler); } } } } -int Model3dView::GetShaderProperties( Toolkit::Model3dView::IlluminationType illuminationType ) +int Model3dView::GetShaderProperties(Toolkit::Model3dView::IlluminationType illuminationType) { int objectProperties = 0; - if( illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE || - illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP ) + if(illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_TEXTURE || + illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP) { objectProperties |= ObjLoader::TEXTURE_COORDINATES; } - if( illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP ) + if(illuminationType == Toolkit::Model3dView::DIFFUSE_WITH_NORMAL_MAP) { objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS; } diff --git a/dali-toolkit/internal/controls/model3d-view/obj-loader.cpp b/dali-toolkit/internal/controls/model3d-view/obj-loader.cpp index 273c8ca..fe03a54 100644 --- a/dali-toolkit/internal/controls/model3d-view/obj-loader.cpp +++ b/dali-toolkit/internal/controls/model3d-view/obj-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. @@ -20,33 +20,30 @@ // EXTERNAL INCLUDES #include -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const int MAX_POINT_INDICES = 4; +const int MAX_POINT_INDICES = 4; } using namespace Dali; ObjLoader::ObjLoader() { - mSceneLoaded = false; - mMaterialLoaded = false; + mSceneLoaded = false; + mMaterialLoaded = false; mHasTexturePoints = false; - mHasDiffuseMap = false; - mHasNormalMap = false; - mHasSpecularMap = false; + mHasDiffuseMap = false; + mHasNormalMap = false; + mHasSpecularMap = false; mSceneAABB.Init(); } @@ -65,17 +62,16 @@ bool ObjLoader::IsMaterialLoaded() return mMaterialLoaded; } -void ObjLoader::CalculateHardFaceNormals( const Dali::Vector& vertices, Dali::Vector& triangles, - Dali::Vector& normals ) +void ObjLoader::CalculateHardFaceNormals(const Dali::Vector& vertices, Dali::Vector& triangles, Dali::Vector& normals) { - int numFaceVertices = 3 * triangles.Size(); //Vertex per face, as each point has different normals for each face. - int normalIndex = 0; //Tracks progress through the array of normals. + int numFaceVertices = 3 * triangles.Size(); //Vertex per face, as each point has different normals for each face. + int normalIndex = 0; //Tracks progress through the array of normals. normals.Clear(); - normals.Resize( numFaceVertices ); + normals.Resize(numFaceVertices); //For each triangle, calculate the normal by crossing two vectors on the triangle's plane. - for( unsigned long i = 0; i < triangles.Size(); i++ ) + for(unsigned long i = 0; i < triangles.Size(); i++) { //Triangle vertices. const Vector3& v0 = vertices[triangles[i].pointIndex[0]]; @@ -91,25 +87,24 @@ void ObjLoader::CalculateHardFaceNormals( const Dali::Vector& vertices, normalVector.Normalize(); //Assign normals to points. - for( unsigned long j = 0; j < 3; j++, normalIndex++ ) + for(unsigned long j = 0; j < 3; j++, normalIndex++) { triangles[i].normalIndex[j] = normalIndex; - normals[normalIndex] = normalVector; + normals[normalIndex] = normalVector; } } } -void ObjLoader::CalculateSoftFaceNormals( const Dali::Vector& vertices, Dali::Vector& triangles, - Dali::Vector& normals ) +void ObjLoader::CalculateSoftFaceNormals(const Dali::Vector& vertices, Dali::Vector& triangles, Dali::Vector& normals) { - int normalIndex = 0; //Tracks progress through the array of normals. + int normalIndex = 0; //Tracks progress through the array of normals. normals.Clear(); - normals.Resize( vertices.Size() ); //One (averaged) normal per point. + normals.Resize(vertices.Size()); //One (averaged) normal per point. //For each triangle, calculate the normal by crossing two vectors on the triangle's plane //We then add the triangle's normal to the cumulative normals at each point of it - for( unsigned long i = 0; i < triangles.Size(); i++ ) + for(unsigned long i = 0; i < triangles.Size(); i++) { //Triangle vertices. const Vector3& v0 = vertices[triangles[i].pointIndex[0]]; @@ -124,7 +119,7 @@ void ObjLoader::CalculateSoftFaceNormals( const Dali::Vector& vertices, Vector3 normalVector = edge1.Cross(edge2); //Add this triangle's normal to the cumulative normal of each constituent point and set the index of the normal accordingly. - for( unsigned long j = 0; j < 3; j++, normalIndex++ ) + for(unsigned long j = 0; j < 3; j++, normalIndex++) { triangles[i].normalIndex[j] = triangles[i].pointIndex[j]; //Normal index matches up to vertex index, as one normal per vertex. normals[triangles[i].normalIndex[j]] += normalVector; @@ -132,7 +127,7 @@ void ObjLoader::CalculateSoftFaceNormals( const Dali::Vector& vertices, } //Normalise the normals. - for( unsigned long i = 0; i < normals.Size(); i++ ) + for(unsigned long i = 0; i < normals.Size(); i++) { normals[i].Normalize(); } @@ -144,11 +139,11 @@ void ObjLoader::CalculateTangentFrame() //Reset tangent and bitangent vectors to hold new values. mTangents.Clear(); mBiTangents.Clear(); - mTangents.Resize( mPoints.Size() ); - mBiTangents.Resize( mPoints.Size() ); + mTangents.Resize(mPoints.Size()); + mBiTangents.Resize(mPoints.Size()); //For each triangle, calculate the tangent vector and then add it to the total tangent vector of each point. - for ( unsigned long a = 0; a < mTriangles.Size(); a++ ) + for(unsigned long a = 0; a < mTriangles.Size(); a++) { Vector3 tangentVector; @@ -170,9 +165,9 @@ void ObjLoader::CalculateTangentFrame() float f = 1.0f / (deltaU1 * deltaV2 - deltaU2 * deltaV1); - tangentVector.x = f * ( deltaV2 * edge1.x - deltaV1 * edge2.x ); - tangentVector.y = f * ( deltaV2 * edge1.y - deltaV1 * edge2.y ); - tangentVector.z = f * ( deltaV2 * edge1.z - deltaV1 * edge2.z ); + tangentVector.x = f * (deltaV2 * edge1.x - deltaV1 * edge2.x); + tangentVector.y = f * (deltaV2 * edge1.y - deltaV1 * edge2.y); + tangentVector.z = f * (deltaV2 * edge1.z - deltaV1 * edge2.z); mTangents[mTriangles[a].pointIndex[0]] += tangentVector; mTangents[mTriangles[a].pointIndex[1]] += tangentVector; @@ -180,7 +175,7 @@ void ObjLoader::CalculateTangentFrame() } //Orthogonalize tangents and set binormals. - for ( unsigned long a = 0; a < mTangents.Size(); a++ ) + for(unsigned long a = 0; a < mTangents.Size(); a++) { const Vector3& n = mNormals[a]; const Vector3& t = mTangents[a]; @@ -189,28 +184,28 @@ void ObjLoader::CalculateTangentFrame() mTangents[a] = t - n * n.Dot(t); mTangents[a].Normalize(); - mBiTangents[a] = mNormals[a].Cross( mTangents[a] ); + mBiTangents[a] = mNormals[a].Cross(mTangents[a]); } } -void ObjLoader::CenterAndScale( bool center, Dali::Vector& points ) +void ObjLoader::CenterAndScale(bool center, Dali::Vector& points) { BoundingVolume newAABB; Vector3 sceneSize = GetSize(); float biggestDimension = sceneSize.x; - if( sceneSize.y > biggestDimension ) + if(sceneSize.y > biggestDimension) { biggestDimension = sceneSize.y; } - if( sceneSize.z > biggestDimension ) + if(sceneSize.z > biggestDimension) { biggestDimension = sceneSize.z; } newAABB.Init(); - for( unsigned int ui = 0; ui < points.Size(); ++ui ) + for(unsigned int ui = 0; ui < points.Size(); ++ui) { points[ui] = points[ui] - GetCenter(); points[ui] = points[ui] / biggestDimension; @@ -220,11 +215,11 @@ void ObjLoader::CenterAndScale( bool center, Dali::Vector& points ) mSceneAABB = newAABB; } -void ObjLoader::CreateGeometryArray( Dali::Vector & vertices, - Dali::Vector & textures, - Dali::Vector & verticesExt, - Dali::Vector & indices, - bool useSoftNormals ) +void ObjLoader::CreateGeometryArray(Dali::Vector& vertices, + Dali::Vector& textures, + Dali::Vector& verticesExt, + Dali::Vector& indices, + bool useSoftNormals) { //We must calculate the tangents and bitangents if they weren't supplied, or if they don't match up. bool mustCalculateTangents = mTangents.Size() == 0 || mBiTangents.Size() == 0 || @@ -237,55 +232,55 @@ void ObjLoader::CreateGeometryArray( Dali::Vector & vertices, //We also have to recalculate the normals if we need to calculate tangents, // as we need just one normal, tangent and bitangent per vertex, rather than the supplied per-face vertices. //Alternatively, we need to calculate the normals if there weren't any to begin with. - if( mNormals.Size() == 0 || mustCalculateTangents ) + if(mNormals.Size() == 0 || mustCalculateTangents) { - if( useSoftNormals || mustCalculateTangents ) + if(useSoftNormals || mustCalculateTangents) { - CalculateSoftFaceNormals( mPoints, mTriangles, mNormals ); + CalculateSoftFaceNormals(mPoints, mTriangles, mNormals); } else { - CalculateHardFaceNormals( mPoints, mTriangles, mNormals ); + CalculateHardFaceNormals(mPoints, mTriangles, mNormals); } } //TODO: Use a better function to calculate tangents - if( mHasTexturePoints && mustCalculateTangents ) + if(mHasTexturePoints && mustCalculateTangents) { CalculateTangentFrame(); } bool mapsCorrespond; //True if the sizes of the arrays necessary for the object agree. - if ( mHasTexturePoints ) + if(mHasTexturePoints) { - mapsCorrespond = ( mPoints.Size() == mTextures.Size() ) && ( mTextures.Size() == mNormals.Size() ); + mapsCorrespond = (mPoints.Size() == mTextures.Size()) && (mTextures.Size() == mNormals.Size()); } else { - mapsCorrespond = ( mPoints.Size() == mNormals.Size() ); + mapsCorrespond = (mPoints.Size() == mNormals.Size()); } //Check the number of points textures and normals - if ( mapsCorrespond ) + if(mapsCorrespond) { - int numPoints = mPoints.Size(); + int numPoints = mPoints.Size(); int numIndices = 3 * mTriangles.Size(); - vertices.Resize( numPoints ); - textures.Resize( numPoints ); - verticesExt.Resize( numPoints ); - indices.Resize( numIndices ); + vertices.Resize(numPoints); + textures.Resize(numPoints); + verticesExt.Resize(numPoints); + indices.Resize(numIndices); //We create the vertices array. For now we just copy points info - for (unsigned int ui = 0 ; ui < mPoints.Size() ; ++ui ) + for(unsigned int ui = 0; ui < mPoints.Size(); ++ui) { Vertex vertex; vertex.position = mPoints[ui]; - vertices[ui] = vertex; + vertices[ui] = vertex; - if ( mHasTexturePoints ) + if(mHasTexturePoints) { - textures[ui] = Vector2(); + textures[ui] = Vector2(); verticesExt[ui] = VertexExt(); } } @@ -293,19 +288,19 @@ void ObjLoader::CreateGeometryArray( Dali::Vector & vertices, int indiceIndex = 0; //We copy the indices - for ( unsigned int ui = 0 ; ui < mTriangles.Size() ; ++ui ) + for(unsigned int ui = 0; ui < mTriangles.Size(); ++ui) { - for ( int j = 0 ; j < 3 ; ++j ) + for(int j = 0; j < 3; ++j) { indices[indiceIndex] = mTriangles[ui].pointIndex[j]; indiceIndex++; vertices[mTriangles[ui].pointIndex[j]].normal = mNormals[mTriangles[ui].normalIndex[j]]; - if ( mHasTexturePoints ) + if(mHasTexturePoints) { - textures[mTriangles[ui].pointIndex[j]] = mTextures[mTriangles[ui].textureIndex[j]]; - verticesExt[mTriangles[ui].pointIndex[j]].tangent = mTangents[mTriangles[ui].normalIndex[j]]; + textures[mTriangles[ui].pointIndex[j]] = mTextures[mTriangles[ui].textureIndex[j]]; + verticesExt[mTriangles[ui].pointIndex[j]].tangent = mTangents[mTriangles[ui].normalIndex[j]]; verticesExt[mTriangles[ui].pointIndex[j]].bitangent = mBiTangents[mTriangles[ui].normalIndex[j]]; } } @@ -314,29 +309,29 @@ void ObjLoader::CreateGeometryArray( Dali::Vector & vertices, else { int numVertices = 3 * mTriangles.Size(); - vertices.Resize( numVertices ); - textures.Resize( numVertices ); - verticesExt.Resize( numVertices ); + vertices.Resize(numVertices); + textures.Resize(numVertices); + verticesExt.Resize(numVertices); int index = 0; //We have to normalize the arrays so we can draw we just one index array - for ( unsigned int ui = 0 ; ui < mTriangles.Size() ; ++ui ) + for(unsigned int ui = 0; ui < mTriangles.Size(); ++ui) { - for ( int j = 0 ; j < 3 ; ++j ) + for(int j = 0; j < 3; ++j) { Vertex vertex; vertex.position = mPoints[mTriangles[ui].pointIndex[j]]; - vertex.normal = mNormals[mTriangles[ui].normalIndex[j]]; + vertex.normal = mNormals[mTriangles[ui].normalIndex[j]]; vertices[index] = vertex; - if ( mHasTexturePoints ) + if(mHasTexturePoints) { textures[index] = mTextures[mTriangles[ui].textureIndex[j]]; VertexExt vertexExt; - vertexExt.tangent = mTangents[mTriangles[ui].normalIndex[j]]; + vertexExt.tangent = mTangents[mTriangles[ui].normalIndex[j]]; vertexExt.bitangent = mBiTangents[mTriangles[ui].normalIndex[j]]; - verticesExt[index] = vertexExt; + verticesExt[index] = vertexExt; } index++; @@ -345,96 +340,95 @@ void ObjLoader::CreateGeometryArray( Dali::Vector & vertices, } } -bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) +bool ObjLoader::LoadObject(char* objBuffer, std::streampos fileSize) { - Vector3 point; - Vector2 texture; + Vector3 point; + Vector2 texture; std::string vet[MAX_POINT_INDICES], name; - int ptIdx[MAX_POINT_INDICES]; - int nrmIdx[MAX_POINT_INDICES]; - int texIdx[MAX_POINT_INDICES]; - TriIndex triangle,triangle2; - int pntAcum = 0, texAcum = 0, nrmAcum = 0; - bool iniObj = false; - bool hasTexture = false; - int face = 0; + int ptIdx[MAX_POINT_INDICES]; + int nrmIdx[MAX_POINT_INDICES]; + int texIdx[MAX_POINT_INDICES]; + TriIndex triangle, triangle2; + int pntAcum = 0, texAcum = 0, nrmAcum = 0; + bool iniObj = false; + bool hasTexture = false; + int face = 0; //Init AABB for the file mSceneAABB.Init(); std::string strMatActual; - std::string input( objBuffer, fileSize ); + std::string input(objBuffer, fileSize); std::istringstream ss(input); - ss.imbue( std::locale( "C" ) ); - + ss.imbue(std::locale("C")); std::string line; - std::getline( ss, line ); + std::getline(ss, line); - while ( std::getline( ss, line ) ) + while(std::getline(ss, line)) { - std::istringstream isline( line, std::istringstream::in ); - std::string tag; + std::istringstream isline(line, std::istringstream::in); + std::string tag; isline >> tag; - if ( tag == "v" ) + if(tag == "v") { //Two different objects in the same file isline >> point.x; isline >> point.y; isline >> point.z; - mPoints.PushBack( point ); + mPoints.PushBack(point); - mSceneAABB.ConsiderNewPointInVolume( point ); + mSceneAABB.ConsiderNewPointInVolume(point); } - else if ( tag == "vn" ) + else if(tag == "vn") { isline >> point.x; isline >> point.y; isline >> point.z; - mNormals.PushBack( point ); + mNormals.PushBack(point); } - else if ( tag == "#_#tangent" ) + else if(tag == "#_#tangent") { isline >> point.x; isline >> point.y; isline >> point.z; - mTangents.PushBack( point ); + mTangents.PushBack(point); } - else if ( tag == "#_#binormal" ) + else if(tag == "#_#binormal") { isline >> point.x; isline >> point.y; isline >> point.z; - mBiTangents.PushBack( point ); + mBiTangents.PushBack(point); } - else if ( tag == "vt" ) + else if(tag == "vt") { isline >> texture.x; isline >> texture.y; - texture.y = 1.0-texture.y; - mTextures.PushBack( texture ); + texture.y = 1.0 - texture.y; + mTextures.PushBack(texture); } - else if ( tag == "#_#vt1" ) + else if(tag == "#_#vt1") { isline >> texture.x; isline >> texture.y; - texture.y = 1.0-texture.y; - mTextures2.PushBack( texture ); + texture.y = 1.0 - texture.y; + mTextures2.PushBack(texture); } - else if ( tag == "s" ) + else if(tag == "s") { } - else if ( tag == "f" ) + else if(tag == "f") { - if ( !iniObj ) + if(!iniObj) { //name assign @@ -442,7 +436,7 @@ bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) } int numIndices = 0; - while( ( numIndices < MAX_POINT_INDICES ) && ( isline >> vet[numIndices] ) ) + while((numIndices < MAX_POINT_INDICES) && (isline >> vet[numIndices])) { numIndices++; } @@ -451,26 +445,26 @@ bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) char separator; char separator2; - const char * subString; //A pointer to the position in the string as we move through it. + const char* subString; //A pointer to the position in the string as we move through it. - subString = strstr( vet[0].c_str(),"/" ); //Search for the first '/' + subString = strstr(vet[0].c_str(), "/"); //Search for the first '/' - if( subString ) + if(subString) { - if( subString[1] == '/' ) // Of the form A//C, so has points and normals but no texture coordinates. + if(subString[1] == '/') // Of the form A//C, so has points and normals but no texture coordinates. { - for( int i = 0 ; i < numIndices; i++) + for(int i = 0; i < numIndices; i++) { - std::istringstream isindex( vet[i] ); + std::istringstream isindex(vet[i]); isindex >> ptIdx[i] >> separator >> separator2 >> nrmIdx[i]; texIdx[i] = 0; } } - else if( strstr( subString, "/" ) ) // Of the form A/B/C, so has points, textures and normals. + else if(strstr(subString, "/")) // Of the form A/B/C, so has points, textures and normals. { - for( int i = 0 ; i < numIndices; i++ ) + for(int i = 0; i < numIndices; i++) { - std::istringstream isindex( vet[i] ); + std::istringstream isindex(vet[i]); isindex >> ptIdx[i] >> separator >> texIdx[i] >> separator2 >> nrmIdx[i]; } @@ -478,9 +472,9 @@ bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) } else // Of the form A/B, so has points and textures but no normals. { - for( int i = 0 ; i < numIndices; i++ ) + for(int i = 0; i < numIndices; i++) { - std::istringstream isindex( vet[i] ); + std::istringstream isindex(vet[i]); isindex >> ptIdx[i] >> separator >> texIdx[i]; nrmIdx[i] = 0; } @@ -490,9 +484,9 @@ bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) } else // Simply of the form A, as in, point indices only. { - for( int i = 0 ; i < numIndices; i++ ) + for(int i = 0; i < numIndices; i++) { - std::istringstream isindex( vet[i] ); + std::istringstream isindex(vet[i]); isindex >> ptIdx[i]; texIdx[i] = 0; nrmIdx[i] = 0; @@ -500,58 +494,58 @@ bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) } //If it is a triangle - if( numIndices == 3 ) + if(numIndices == 3) { - for( int i = 0 ; i < 3; i++ ) + for(int i = 0; i < 3; i++) { - triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum; - triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum; + triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum; + triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum; triangle.textureIndex[i] = texIdx[i] - 1 - texAcum; } - mTriangles.PushBack( triangle ); + mTriangles.PushBack(triangle); face++; } //If on the other hand it is a quad, we will create two triangles - else if( numIndices == 4 ) + else if(numIndices == 4) { - for( int i = 0 ; i < 3; i++ ) + for(int i = 0; i < 3; i++) { - triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum; - triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum; + triangle.pointIndex[i] = ptIdx[i] - 1 - pntAcum; + triangle.normalIndex[i] = nrmIdx[i] - 1 - nrmAcum; triangle.textureIndex[i] = texIdx[i] - 1 - texAcum; } - mTriangles.PushBack( triangle ); + mTriangles.PushBack(triangle); face++; - for( int i = 0 ; i < 3; i++ ) + for(int i = 0; i < 3; i++) { - int idx = ( i + 2 ) % numIndices; - triangle2.pointIndex[i] = ptIdx[idx] - 1 - pntAcum; - triangle2.normalIndex[i] = nrmIdx[idx] - 1 - nrmAcum; + int idx = (i + 2) % numIndices; + triangle2.pointIndex[i] = ptIdx[idx] - 1 - pntAcum; + triangle2.normalIndex[i] = nrmIdx[idx] - 1 - nrmAcum; triangle2.textureIndex[i] = texIdx[idx] - 1 - texAcum; } - mTriangles.PushBack( triangle2 ); + mTriangles.PushBack(triangle2); face++; } } - else if ( tag == "usemtl" ) + else if(tag == "usemtl") { isline >> strMatActual; } - else if ( tag == "mtllib" ) + else if(tag == "mtllib") { isline >> strMatActual; } - else if ( tag == "g" ) + else if(tag == "g") { isline >> name; } } - if ( iniObj ) + if(iniObj) { - CenterAndScale( true, mPoints ); - mSceneLoaded = true; + CenterAndScale(true, mPoints); + mSceneLoaded = true; mHasTexturePoints = hasTexture; return true; } @@ -559,62 +553,61 @@ bool ObjLoader::LoadObject( char* objBuffer, std::streampos fileSize ) return false; } -void ObjLoader::LoadMaterial( char* objBuffer, std::streampos fileSize, std::string& diffuseTextureUrl, - std::string& normalTextureUrl, std::string& glossTextureUrl ) +void ObjLoader::LoadMaterial(char* objBuffer, std::streampos fileSize, std::string& diffuseTextureUrl, std::string& normalTextureUrl, std::string& glossTextureUrl) { - float fR,fG,fB; + float fR, fG, fB; std::string info; - std::string input( objBuffer, fileSize ); + std::string input(objBuffer, fileSize); std::istringstream ss(input); ss.imbue(std::locale("C")); std::string line; - std::getline( ss, line ); + std::getline(ss, line); - while ( std::getline( ss, line ) ) + while(std::getline(ss, line)) { - std::istringstream isline( line, std::istringstream::in ); - std::string tag; + std::istringstream isline(line, std::istringstream::in); + std::string tag; isline >> tag; - if ( tag == "newmtl" ) //name of the material + if(tag == "newmtl") //name of the material { isline >> info; } - else if ( tag == "Ka" ) //ambient color + else if(tag == "Ka") //ambient color { isline >> fR >> fG >> fB; } - else if ( tag == "Kd" ) //diffuse color + else if(tag == "Kd") //diffuse color { isline >> fR >> fG >> fB; } - else if ( tag == "Ks" ) //specular color + else if(tag == "Ks") //specular color { isline >> fR >> fG >> fB; } - else if ( tag == "Tf" ) //color + else if(tag == "Tf") //color { } - else if ( tag == "Ni" ) + else if(tag == "Ni") { } - else if ( tag == "map_Kd" ) + else if(tag == "map_Kd") { isline >> info; diffuseTextureUrl = info; - mHasDiffuseMap = true; + mHasDiffuseMap = true; } - else if ( tag == "bump" ) + else if(tag == "bump") { isline >> info; normalTextureUrl = info; - mHasNormalMap = true; + mHasNormalMap = true; } - else if ( tag == "map_Ks" ) + else if(tag == "map_Ks") { isline >> info; glossTextureUrl = info; @@ -625,52 +618,52 @@ void ObjLoader::LoadMaterial( char* objBuffer, std::streampos fileSize, std::str mMaterialLoaded = true; } -Geometry ObjLoader::CreateGeometry( int objectProperties, bool useSoftNormals ) +Geometry ObjLoader::CreateGeometry(int objectProperties, bool useSoftNormals) { Geometry surface = Geometry::New(); - Dali::Vector vertices; - Dali::Vector textures; - Dali::Vector verticesExt; + Dali::Vector vertices; + Dali::Vector textures; + Dali::Vector verticesExt; Dali::Vector indices; - CreateGeometryArray( vertices, textures, verticesExt, indices, useSoftNormals ); + CreateGeometryArray(vertices, textures, verticesExt, indices, useSoftNormals); //All vertices need at least Position and Normal Property::Map vertexFormat; - vertexFormat["aPosition"] = Property::VECTOR3; - vertexFormat["aNormal"] = Property::VECTOR3; - VertexBuffer surfaceVertices = VertexBuffer::New( vertexFormat ); - surfaceVertices.SetData( &vertices[0], vertices.Size() ); - surface.AddVertexBuffer( surfaceVertices ); + vertexFormat["aPosition"] = Property::VECTOR3; + vertexFormat["aNormal"] = Property::VECTOR3; + VertexBuffer surfaceVertices = VertexBuffer::New(vertexFormat); + surfaceVertices.SetData(&vertices[0], vertices.Size()); + surface.AddVertexBuffer(surfaceVertices); //Some need texture coordinates - if( ( objectProperties & TEXTURE_COORDINATES ) && mHasTexturePoints && mHasDiffuseMap ) + if((objectProperties & TEXTURE_COORDINATES) && mHasTexturePoints && mHasDiffuseMap) { Property::Map textureFormat; textureFormat["aTexCoord"] = Property::VECTOR2; - VertexBuffer extraVertices = VertexBuffer::New( textureFormat ); - extraVertices.SetData( &textures[0], textures.Size() ); + VertexBuffer extraVertices = VertexBuffer::New(textureFormat); + extraVertices.SetData(&textures[0], textures.Size()); - surface.AddVertexBuffer( extraVertices ); + surface.AddVertexBuffer(extraVertices); } //Some need tangent and bitangent - if( ( objectProperties & TANGENTS ) && ( objectProperties & BINORMALS ) && mHasTexturePoints ) + if((objectProperties & TANGENTS) && (objectProperties & BINORMALS) && mHasTexturePoints) { Property::Map vertexExtFormat; - vertexExtFormat["aTangent"] = Property::VECTOR3; + vertexExtFormat["aTangent"] = Property::VECTOR3; vertexExtFormat["aBiNormal"] = Property::VECTOR3; - VertexBuffer extraVertices = VertexBuffer::New( vertexExtFormat ); - extraVertices.SetData( &verticesExt[0], verticesExt.Size() ); + VertexBuffer extraVertices = VertexBuffer::New(vertexExtFormat); + extraVertices.SetData(&verticesExt[0], verticesExt.Size()); - surface.AddVertexBuffer( extraVertices ); + surface.AddVertexBuffer(extraVertices); } //If indices are required, we set them. - if ( indices.Size() ) + if(indices.Size()) { - surface.SetIndexBuffer ( &indices[0], indices.Size() ); + surface.SetIndexBuffer(&indices[0], indices.Size()); } return surface; diff --git a/dali-toolkit/internal/controls/navigation-view/navigation-view-impl.cpp b/dali-toolkit/internal/controls/navigation-view/navigation-view-impl.cpp index 4573b4c..47906cd 100644 --- a/dali-toolkit/internal/controls/navigation-view/navigation-view-impl.cpp +++ b/dali-toolkit/internal/controls/navigation-view/navigation-view-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. @@ -26,28 +26,24 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // to register type { - BaseHandle Create() { return Toolkit::NavigationView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::NavigationView, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::NavigationView, Toolkit::Control, Create) DALI_TYPE_REGISTRATION_END() } // namespace NavigationView::NavigationView() -: Control(ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)) { } @@ -60,10 +56,10 @@ NavigationView::~NavigationView() Toolkit::NavigationView NavigationView::New() { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< NavigationView > internalNavigationView = new NavigationView(); + IntrusivePtr internalNavigationView = new NavigationView(); // Pass ownership to CustomActor handle - Toolkit::NavigationView navigationView( *internalNavigationView ); + Toolkit::NavigationView navigationView(*internalNavigationView); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -74,31 +70,31 @@ Toolkit::NavigationView NavigationView::New() void NavigationView::OnInitialize() { - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } -void NavigationView::OnSceneConnection( int depth ) +void NavigationView::OnSceneConnection(int depth) { - Self().SetProperty( Actor::Property::SENSITIVE,true); + Self().SetProperty(Actor::Property::SENSITIVE, true); - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } -void NavigationView::Push( Actor& actor ) +void NavigationView::Push(Actor& actor) { // check the uninitialized item // check the duplicated push for the top item - if(!actor ) + if(!actor) { return; } - if( mContentStack.size() > 0 ) + if(mContentStack.size() > 0) { - Self().Remove( mContentStack.back() ); + Self().Remove(mContentStack.back()); } //push the new item into the stack and show it @@ -110,7 +106,7 @@ Actor NavigationView::Pop() { // cannot pop out the bottom-most item Actor poppedItem; - if( mContentStack.size() > 1 ) + if(mContentStack.size() > 1) { // pop out the top item of the stack and show the new item right under the old one. Self().Remove(mContentStack.back()); diff --git a/dali-toolkit/internal/controls/page-turn-view/page-turn-effect.cpp b/dali-toolkit/internal/controls/page-turn-view/page-turn-effect.cpp index 175d6d2..1de017d 100644 --- a/dali-toolkit/internal/controls/page-turn-view/page-turn-effect.cpp +++ b/dali-toolkit/internal/controls/page-turn-view/page-turn-effect.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,25 +16,25 @@ */ // EXTERNAL INCLUDES -#include -#include #include +#include #include +#include // INTERNAL INCLUDES -#include #include #include +#include using namespace Dali; using namespace Dali::Toolkit; namespace { -const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" ); -const char * const PROPERTY_ORIGINAL_CENTER( "originalCenter" ); -const char * const PROPERTY_CURRENT_CENTER( "currentCenter" ); -} +const char* const PROPERTY_COMMON_PARAMETERS("uCommonParameters"); +const char* const PROPERTY_ORIGINAL_CENTER("originalCenter"); +const char* const PROPERTY_CURRENT_CENTER("currentCenter"); +} // namespace /** * This constraint updates the common parameter values used by every vertex. @@ -42,83 +42,84 @@ const char * const PROPERTY_CURRENT_CENTER( "currentCenter" ); */ struct CommonParametersConstraint { - CommonParametersConstraint( float pageHeight ) - : mPageHeight( pageHeight ) - {} + CommonParametersConstraint(float pageHeight) + : mPageHeight(pageHeight) + { + } - void operator()( Dali::Matrix& current, const PropertyInputContainer& inputs ) + void operator()(Dali::Matrix& current, const PropertyInputContainer& inputs) { const Vector2& originalCenter = inputs[0]->GetVector2(); - Vector2 currentCenter = inputs[1]->GetVector2(); + Vector2 currentCenter = inputs[1]->GetVector2(); // calculate the curve direction and the vanishing point // here, the vanishing point is the intersection of spine with the line passing through original center and vertical to curve direction - Vector2 curveDirection( currentCenter - originalCenter ); + Vector2 curveDirection(currentCenter - originalCenter); curveDirection.Normalize(); - if( fabs(curveDirection.y) < 0.01f) // eliminate the possibility of division by zero in the next step + if(fabs(curveDirection.y) < 0.01f) // eliminate the possibility of division by zero in the next step { curveDirection.y = 0.01f; } float vanishingPointY = originalCenter.y + curveDirection.x * originalCenter.x / curveDirection.y; - float curveEndY, cosTheta ,sinTheta ,translateX, translateY; + float curveEndY, cosTheta, sinTheta, translateX, translateY; // when the vanishing point is very far away, make it infinitely, in this case, the page bent horizontally const float THRESHOLD(20.0); - if( fabs(vanishingPointY-mPageHeight*0.5f) >= mPageHeight*THRESHOLD ) + if(fabs(vanishingPointY - mPageHeight * 0.5f) >= mPageHeight * THRESHOLD) { - curveDirection = Vector2(-1.f,0.f); + curveDirection = Vector2(-1.f, 0.f); currentCenter.y = originalCenter.y; - curveEndY = originalCenter.y; - cosTheta = 1.f; - sinTheta = 0.f; + curveEndY = originalCenter.y; + cosTheta = 1.f; + sinTheta = 0.f; translateX = currentCenter.x - originalCenter.x; translateY = vanishingPointY; } else { - curveEndY = currentCenter.y - curveDirection.y * (currentCenter.x/curveDirection.x) ; - Vector2 v1( currentCenter.x, currentCenter.y - vanishingPointY ); + curveEndY = currentCenter.y - curveDirection.y * (currentCenter.x / curveDirection.x); + Vector2 v1(currentCenter.x, currentCenter.y - vanishingPointY); v1.Normalize(); - Vector2 v2( originalCenter.x, originalCenter.y - vanishingPointY ); + Vector2 v2(originalCenter.x, originalCenter.y - vanishingPointY); v2.Normalize(); - cosTheta = v1.x*v2.x + v1.y*v2.y; - sinTheta = ( vanishingPointY > mPageHeight*0.5f ) ? sqrt(1.0-cosTheta*cosTheta) : -sqrt(1.0-cosTheta*cosTheta); - translateX = currentCenter.x - cosTheta*originalCenter.x - sinTheta*( originalCenter.y-vanishingPointY ); - translateY = currentCenter.y + sinTheta*originalCenter.x - cosTheta*( originalCenter.y-vanishingPointY ); + cosTheta = v1.x * v2.x + v1.y * v2.y; + sinTheta = (vanishingPointY > mPageHeight * 0.5f) ? sqrt(1.0 - cosTheta * cosTheta) : -sqrt(1.0 - cosTheta * cosTheta); + translateX = currentCenter.x - cosTheta * originalCenter.x - sinTheta * (originalCenter.y - vanishingPointY); + translateY = currentCenter.y + sinTheta * originalCenter.x - cosTheta * (originalCenter.y - vanishingPointY); } - float originalLength = fabs(originalCenter.x/curveDirection.x); - float currentLength = fabs(currentCenter.x/curveDirection.x); - float curveHeight = 0.45f*sqrt(originalLength*originalLength - currentLength*currentLength); + float originalLength = fabs(originalCenter.x / curveDirection.x); + float currentLength = fabs(currentCenter.x / curveDirection.x); + float curveHeight = 0.45f * sqrt(originalLength * originalLength - currentLength * currentLength); float* parameterArray = current.AsFloat(); - parameterArray[0] = cosTheta; - parameterArray[1] = -sinTheta; - parameterArray[2] = originalCenter.x; - parameterArray[3] = originalCenter.y; - parameterArray[4] = sinTheta; - parameterArray[5] = cosTheta; - parameterArray[6] = currentCenter.x; - parameterArray[7] = currentCenter.y; - parameterArray[8] = translateX; - parameterArray[9] = translateY; - parameterArray[10] = vanishingPointY; - parameterArray[11] = curveEndY; - parameterArray[12] = curveDirection.x; - parameterArray[13] = curveDirection.y; - parameterArray[14] = curveHeight; - parameterArray[15] = currentLength; + parameterArray[0] = cosTheta; + parameterArray[1] = -sinTheta; + parameterArray[2] = originalCenter.x; + parameterArray[3] = originalCenter.y; + parameterArray[4] = sinTheta; + parameterArray[5] = cosTheta; + parameterArray[6] = currentCenter.x; + parameterArray[7] = currentCenter.y; + parameterArray[8] = translateX; + parameterArray[9] = translateY; + parameterArray[10] = vanishingPointY; + parameterArray[11] = curveEndY; + parameterArray[12] = curveDirection.x; + parameterArray[13] = curveDirection.y; + parameterArray[14] = curveHeight; + parameterArray[15] = currentLength; } float mPageHeight; }; -void Dali::Toolkit::Internal::PageTurnApplyInternalConstraint( Actor& actor, float pageHeight ) +void Dali::Toolkit::Internal::PageTurnApplyInternalConstraint(Actor& actor, float pageHeight) { - Constraint constraint = Constraint::New( actor, actor.GetPropertyIndex( PROPERTY_COMMON_PARAMETERS ) , CommonParametersConstraint( pageHeight ) ); - constraint.AddSource( LocalSource( actor.GetPropertyIndex( PROPERTY_ORIGINAL_CENTER ) ) ); - constraint.AddSource( LocalSource( actor.GetPropertyIndex( PROPERTY_CURRENT_CENTER ) ) ); + Constraint constraint = Constraint::New(actor, actor.GetPropertyIndex(PROPERTY_COMMON_PARAMETERS), CommonParametersConstraint(pageHeight)); + constraint.AddSource(LocalSource(actor.GetPropertyIndex(PROPERTY_ORIGINAL_CENTER))); + constraint.AddSource(LocalSource(actor.GetPropertyIndex(PROPERTY_CURRENT_CENTER))); constraint.Apply(); } @@ -128,12 +129,11 @@ Property::Map Dali::Toolkit::Internal::CreatePageTurnEffect() Property::Map customShader; - customShader[ Toolkit::Visual::Shader::Property::VERTEX_SHADER ] = SHADER_PAGE_TURN_EFFECT_VERT.data(); - customShader[ Toolkit::Visual::Shader::Property::FRAGMENT_SHADER ] = SHADER_PAGE_TURN_EFFECT_FRAG.data(); - customShader[ Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X ] = 20; - customShader[ Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y ] = 20; + customShader[Toolkit::Visual::Shader::Property::VERTEX_SHADER] = SHADER_PAGE_TURN_EFFECT_VERT.data(); + customShader[Toolkit::Visual::Shader::Property::FRAGMENT_SHADER] = SHADER_PAGE_TURN_EFFECT_FRAG.data(); + customShader[Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X] = 20; + customShader[Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y] = 20; - map[ Toolkit::Visual::Property::SHADER ] = customShader; + map[Toolkit::Visual::Property::SHADER] = customShader; return map; - } diff --git a/dali-toolkit/internal/controls/page-turn-view/page-turn-landscape-view-impl.cpp b/dali-toolkit/internal/controls/page-turn-view/page-turn-landscape-view-impl.cpp index fbbc650..daa4852 100644 --- a/dali-toolkit/internal/controls/page-turn-view/page-turn-landscape-view-impl.cpp +++ b/dali-toolkit/internal/controls/page-turn-view/page-turn-landscape-view-impl.cpp @@ -19,41 +19,38 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnLandscapeView, Toolkit::PageTurnView, NULL ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PageTurnLandscapeView, Toolkit::PageTurnView, NULL) DALI_TYPE_REGISTRATION_END() -} +} // namespace -PageTurnLandscapeView::PageTurnLandscapeView( PageFactory& pageFactory, const Vector2& viewPageSize ) -: PageTurnView( pageFactory, viewPageSize ) +PageTurnLandscapeView::PageTurnLandscapeView(PageFactory& pageFactory, const Vector2& viewPageSize) +: PageTurnView(pageFactory, viewPageSize) { } PageTurnLandscapeView::~PageTurnLandscapeView() -{} +{ +} -Toolkit::PageTurnLandscapeView PageTurnLandscapeView::New( PageFactory& pageFactory, const Vector2& viewPageSize ) +Toolkit::PageTurnLandscapeView PageTurnLandscapeView::New(PageFactory& pageFactory, const Vector2& viewPageSize) { // Create the implementation, temporarily owned on stack - IntrusivePtr< PageTurnLandscapeView > internalPageTurnView = new PageTurnLandscapeView( pageFactory, viewPageSize ); + IntrusivePtr internalPageTurnView = new PageTurnLandscapeView(pageFactory, viewPageSize); // Pass ownership to CustomActor - Dali::Toolkit::PageTurnLandscapeView pageTurnView( *internalPageTurnView ); + Dali::Toolkit::PageTurnLandscapeView pageTurnView(*internalPageTurnView); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -64,38 +61,38 @@ Toolkit::PageTurnLandscapeView PageTurnLandscapeView::New( PageFactory& pageFact void PageTurnLandscapeView::OnPageTurnViewInitialize() { - mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f ); - mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f ); + mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f); + mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 2.f); - mControlSize = Vector2( mPageSize.width * 2.f, mPageSize.height ); - Self().SetProperty( Actor::Property::SIZE, mControlSize ); - mTurningPageLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mControlSize = Vector2(mPageSize.width * 2.f, mPageSize.height); + Self().SetProperty(Actor::Property::SIZE, mControlSize); + mTurningPageLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); } -void PageTurnLandscapeView::OnAddPage( Actor newPage, bool isLeftSide ) +void PageTurnLandscapeView::OnAddPage(Actor newPage, bool isLeftSide) { - newPage.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + newPage.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); } -Vector2 PageTurnLandscapeView::SetPanPosition( const Vector2& gesturePosition ) +Vector2 PageTurnLandscapeView::SetPanPosition(const Vector2& gesturePosition) { - if( mPages[mIndex].isTurnBack ) + if(mPages[mIndex].isTurnBack) { - return Vector2( mPageSize.width - gesturePosition.x, gesturePosition.y ); + return Vector2(mPageSize.width - gesturePosition.x, gesturePosition.y); } else { - return Vector2( gesturePosition.x - mPageSize.width, gesturePosition.y ); + return Vector2(gesturePosition.x - mPageSize.width, gesturePosition.y); } } -void PageTurnLandscapeView::SetPanActor( const Vector2& panPosition ) +void PageTurnLandscapeView::SetPanActor(const Vector2& panPosition) { - if( panPosition.x > mPageSize.width && mCurrentPageIndex < mTotalPageCount ) + if(panPosition.x > mPageSize.width && mCurrentPageIndex < mTotalPageCount) { mTurningPageIndex = mCurrentPageIndex; } - else if( panPosition.x <= mPageSize.width && mCurrentPageIndex > 0 ) + else if(panPosition.x <= mPageSize.width && mCurrentPageIndex > 0) { mTurningPageIndex = mCurrentPageIndex - 1; } diff --git a/dali-toolkit/internal/controls/page-turn-view/page-turn-portrait-view-impl.cpp b/dali-toolkit/internal/controls/page-turn-view/page-turn-portrait-view-impl.cpp index d4566bf..094de09 100644 --- a/dali-toolkit/internal/controls/page-turn-view/page-turn-portrait-view-impl.cpp +++ b/dali-toolkit/internal/controls/page-turn-view/page-turn-portrait-view-impl.cpp @@ -20,24 +20,21 @@ // EXTERNAL INCLUDES #include -#include #include +#include //INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnPortraitView, Toolkit::PageTurnView, NULL ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PageTurnPortraitView, Toolkit::PageTurnView, NULL) DALI_TYPE_REGISTRATION_END() // the panning speed threshold, no matter how far is the pan displacement, pan fast to left/right quickly (speed > 0.3) will turn over/back the page @@ -46,10 +43,10 @@ const float GESTURE_SPEED_THRESHOLD(0.3f); // the animation duration of turning the previous page back when an outwards flick is detected const float PAGE_TURN_OVER_ANIMATION_DURATION(0.5f); -} +} // namespace -PageTurnPortraitView::PageTurnPortraitView( PageFactory& pageFactory, const Vector2& viewPageSize ) -: PageTurnView( pageFactory, viewPageSize ) +PageTurnPortraitView::PageTurnPortraitView(PageFactory& pageFactory, const Vector2& viewPageSize) +: PageTurnView(pageFactory, viewPageSize) { } @@ -57,13 +54,13 @@ PageTurnPortraitView::~PageTurnPortraitView() { } -Toolkit::PageTurnPortraitView PageTurnPortraitView::New( PageFactory& pageFactory, const Vector2& viewPageSize ) +Toolkit::PageTurnPortraitView PageTurnPortraitView::New(PageFactory& pageFactory, const Vector2& viewPageSize) { // Create the implementation, temporarily owned on stack - IntrusivePtr< PageTurnPortraitView > internalPageTurnView = new PageTurnPortraitView( pageFactory, viewPageSize ); + IntrusivePtr internalPageTurnView = new PageTurnPortraitView(pageFactory, viewPageSize); // Pass ownership to CustomActor - Dali::Toolkit::PageTurnPortraitView pageTurnView( *internalPageTurnView ); + Dali::Toolkit::PageTurnPortraitView pageTurnView(*internalPageTurnView); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -74,22 +71,22 @@ Toolkit::PageTurnPortraitView PageTurnPortraitView::New( PageFactory& pageFactor void PageTurnPortraitView::OnPageTurnViewInitialize() { - mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f ); - mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f ); + mTurnEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f); + mSpineEffectShader.RegisterProperty(PROPERTY_TEXTURE_WIDTH, 1.f); mControlSize = mPageSize; - Self().SetProperty( Actor::Property::SIZE, mPageSize ); - mTurningPageLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); + Self().SetProperty(Actor::Property::SIZE, mPageSize); + mTurningPageLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT); } -Vector2 PageTurnPortraitView::SetPanPosition( const Vector2& gesturePosition ) +Vector2 PageTurnPortraitView::SetPanPosition(const Vector2& gesturePosition) { return gesturePosition; } -void PageTurnPortraitView::SetPanActor( const Vector2& panPosition ) +void PageTurnPortraitView::SetPanActor(const Vector2& panPosition) { - if( mCurrentPageIndex < mTotalPageCount ) + if(mCurrentPageIndex < mTotalPageCount) { mTurningPageIndex = mCurrentPageIndex; } @@ -99,14 +96,14 @@ void PageTurnPortraitView::SetPanActor( const Vector2& panPosition ) } } -void PageTurnPortraitView::OnPossibleOutwardsFlick( const Vector2& panPosition, float gestureSpeed ) +void PageTurnPortraitView::OnPossibleOutwardsFlick(const Vector2& panPosition, float gestureSpeed) { Vector2 offset = panPosition - mPressDownPosition; // There is previous page and an outwards flick is detected - if( mCurrentPageIndex > 0 && gestureSpeed > GESTURE_SPEED_THRESHOLD && offset.x > fabs( offset.y )) + if(mCurrentPageIndex > 0 && gestureSpeed > GESTURE_SPEED_THRESHOLD && offset.x > fabs(offset.y)) { - int actorIndex = (mCurrentPageIndex-1) % NUMBER_OF_CACHED_PAGES; - Actor actor = mPages[ actorIndex ].actor; + int actorIndex = (mCurrentPageIndex - 1) % NUMBER_OF_CACHED_PAGES; + Actor actor = mPages[actorIndex].actor; if(actor.GetParent() != Self()) { return; @@ -114,53 +111,54 @@ void PageTurnPortraitView::OnPossibleOutwardsFlick( const Vector2& panPosition, // Guard against destruction during signal emission //Emit signal, to notify that page[mCurrentPageIndex-1] is turning backwards - Toolkit::PageTurnView handle( GetOwner() ); - mTurningPageIndex = mCurrentPageIndex-1; - mPageTurnStartedSignal.Emit( handle, static_cast(mTurningPageIndex), false ); + Toolkit::PageTurnView handle(GetOwner()); + mTurningPageIndex = mCurrentPageIndex - 1; + mPageTurnStartedSignal.Emit(handle, static_cast(mTurningPageIndex), false); //update pages mCurrentPageIndex--; - RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE ); - AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE ); + RemovePage(mCurrentPageIndex + NUMBER_OF_CACHED_PAGES_EACH_SIDE); + AddPage(mCurrentPageIndex - NUMBER_OF_CACHED_PAGES_EACH_SIDE); OrganizePageDepth(); mPageUpdated = true; - actor.SetProperty( Actor::Property::VISIBLE,true); + actor.SetProperty(Actor::Property::VISIBLE, true); // Add the page to tuning page layer and set up PageTurnEffect - mShadowView.Add( actor ); - mPages[actorIndex].UseEffect( mTurnEffectShader ); + mShadowView.Add(actor); + mPages[actorIndex].UseEffect(mTurnEffectShader); mAnimatingCount++; - Vector2 originalCenter( mPageSize.width*1.5f, 0.5f*mPageSize.height ); - mPages[actorIndex].SetOriginalCenter( originalCenter ); - mPages[actorIndex].SetCurrentCenter( Vector2( mPageSize.width*0.5f, mPageSize.height*0.5f ) ); + Vector2 originalCenter(mPageSize.width * 1.5f, 0.5f * mPageSize.height); + mPages[actorIndex].SetOriginalCenter(originalCenter); + mPages[actorIndex].SetCurrentCenter(Vector2(mPageSize.width * 0.5f, mPageSize.height * 0.5f)); PageTurnApplyInternalConstraint(actor, mPageSize.height); // Start an animation to turn the previous page back - Animation animation = Animation::New( PAGE_TURN_OVER_ANIMATION_DURATION ); + Animation animation = Animation::New(PAGE_TURN_OVER_ANIMATION_DURATION); mAnimationPageIdPair[animation] = mCurrentPageIndex; - animation.AnimateTo( Property( actor, mPages[actorIndex].propertyCurrentCenter ), - originalCenter, - AlphaFunction::EASE_OUT, TimePeriod(PAGE_TURN_OVER_ANIMATION_DURATION*0.75f) ); - animation.AnimateBy( Property( actor, Actor::Property::ORIENTATION ), AngleAxis( Degree( 180.0f ), Vector3::YAXIS ) ,AlphaFunction::EASE_OUT ); + animation.AnimateTo(Property(actor, mPages[actorIndex].propertyCurrentCenter), + originalCenter, + AlphaFunction::EASE_OUT, + TimePeriod(PAGE_TURN_OVER_ANIMATION_DURATION * 0.75f)); + animation.AnimateBy(Property(actor, Actor::Property::ORIENTATION), AngleAxis(Degree(180.0f), Vector3::YAXIS), AlphaFunction::EASE_OUT); animation.Play(); - animation.FinishedSignal().Connect( this, &PageTurnPortraitView::TurnedOverBackwards ); + animation.FinishedSignal().Connect(this, &PageTurnPortraitView::TurnedOverBackwards); } } -void PageTurnPortraitView::OnTurnedOver( Actor actor, bool isLeftSide ) +void PageTurnPortraitView::OnTurnedOver(Actor actor, bool isLeftSide) { - if( isLeftSide ) + if(isLeftSide) { - actor.SetProperty( Actor::Property::VISIBLE, false ); + actor.SetProperty(Actor::Property::VISIBLE, false); } } -void PageTurnPortraitView::TurnedOverBackwards( Animation& animation ) +void PageTurnPortraitView::TurnedOverBackwards(Animation& animation) { - TurnedOver( animation ); + TurnedOver(animation); } } // namespace Internal diff --git a/dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.cpp b/dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.cpp index df3bf6f..974dbcf 100644 --- a/dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.cpp +++ b/dali-toolkit/internal/controls/page-turn-view/page-turn-view-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,35 +19,35 @@ #include // EXTERNAL INCLUDES -#include // for strcmp +#include #include #include -#include #include -#include +#include +#include // for strcmp // INTERNAL INCLUDES -#include -#include +#include #include +#include #include #include -#include +#include using namespace Dali; namespace //Unnamed namespace { // properties set on shader, these properties have the constant value in regardless of the page status -const char * const PROPERTY_SPINE_SHADOW ( "uSpineShadowParameter" ); // uniform for both spine and turn effect +const char* const PROPERTY_SPINE_SHADOW("uSpineShadowParameter"); // uniform for both spine and turn effect // properties set on actor, the value of these properties varies depending on the page status // properties used in turn effect -const char * const PROPERTY_TURN_DIRECTION( "uIsTurningBack" ); // uniform -const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" ); //uniform +const char* const PROPERTY_TURN_DIRECTION("uIsTurningBack"); // uniform +const char* const PROPERTY_COMMON_PARAMETERS("uCommonParameters"); //uniform -const char * const PROPERTY_PAN_DISPLACEMENT( "panDisplacement" );// property used to constrain the uniforms -const char * const PROPERTY_PAN_CENTER( "panCenter" );// property used to constrain the uniforms +const char* const PROPERTY_PAN_DISPLACEMENT("panDisplacement"); // property used to constrain the uniforms +const char* const PROPERTY_PAN_CENTER("panCenter"); // property used to constrain the uniforms // default grid density for page turn effect, 20 pixels by 20 pixels const float DEFAULT_GRID_DENSITY(20.0f); @@ -70,7 +70,7 @@ const float PAGE_TURN_OVER_ANIMATION_DURATION(1.2f); const Vector2 DEFAULT_SPINE_SHADOW_PARAMETER(50.0f, 20.0f); // constants for shadow casting -const float POINT_LIGHT_HEIGHT_RATIO(2.f); +const float POINT_LIGHT_HEIGHT_RATIO(2.f); const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.5f); // constraints //////////////////////////////////////////////////////////////// @@ -83,30 +83,30 @@ const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.5f); struct OriginalCenterConstraint { OriginalCenterConstraint(const Vector2& originalCenter, const Vector2& offset) - : mOldCenter( originalCenter ) + : mOldCenter(originalCenter) { mNewCenter = originalCenter + offset; - mDistance = offset.Length() * 0.5f; - mDirection = offset / mDistance; + mDistance = offset.Length() * 0.5f; + mDirection = offset / mDistance; } - void operator()( Vector2& current, const PropertyInputContainer& inputs ) + void operator()(Vector2& current, const PropertyInputContainer& inputs) { float displacement = inputs[0]->GetFloat(); - if( displacement < mDistance ) + if(displacement < mDistance) { current = mOldCenter + mDirection * displacement; } else { - current = mNewCenter + Vector2(0.25f*(displacement-mDistance), 0.f); + current = mNewCenter + Vector2(0.25f * (displacement - mDistance), 0.f); } } Vector2 mOldCenter; Vector2 mNewCenter; - float mDistance; + float mDistance; Vector2 mDirection; }; @@ -118,34 +118,34 @@ struct OriginalCenterConstraint */ struct RotationConstraint { - RotationConstraint( float distance, float pageWidth, bool isTurnBack ) - : mDistance( distance*0.5f ) + RotationConstraint(float distance, float pageWidth, bool isTurnBack) + : mDistance(distance * 0.5f) { - mStep = 1.f / pageWidth; - mSign = isTurnBack ? -1.0f : 1.0f; - mConst = isTurnBack ? -1.0f : 0.f; - mRotation = isTurnBack ? Quaternion( Radian( -Math::PI ), Vector3::YAXIS ) : Quaternion( Radian(0.f), Vector3::YAXIS ); + mStep = 1.f / pageWidth; + mSign = isTurnBack ? -1.0f : 1.0f; + mConst = isTurnBack ? -1.0f : 0.f; + mRotation = isTurnBack ? Quaternion(Radian(-Math::PI), Vector3::YAXIS) : Quaternion(Radian(0.f), Vector3::YAXIS); } - void operator()( Quaternion& current, const PropertyInputContainer& inputs ) + void operator()(Quaternion& current, const PropertyInputContainer& inputs) { float displacement = inputs[0]->GetFloat(); - if( displacement < mDistance) + if(displacement < mDistance) { current = mRotation; } else { - float coef = std::max(-1.0f, mStep*(mDistance-displacement)); - float angle = Math::PI * ( mConst + mSign * coef ); - current = Quaternion( Radian( angle ), Vector3::YAXIS ); + float coef = std::max(-1.0f, mStep * (mDistance - displacement)); + float angle = Math::PI * (mConst + mSign * coef); + current = Quaternion(Radian(angle), Vector3::YAXIS); } } - float mDistance; - float mStep; - float mConst; - float mSign; + float mDistance; + float mStep; + float mConst; + float mSign; Quaternion mRotation; }; @@ -157,29 +157,29 @@ struct RotationConstraint */ struct CurrentCenterConstraint { - CurrentCenterConstraint( float pageWidth ) - : mPageWidth( pageWidth ) + CurrentCenterConstraint(float pageWidth) + : mPageWidth(pageWidth) { mThres = pageWidth * PAGE_TURN_OVER_THRESHOLD_RATIO * 0.5f; } - void operator()( Vector2& current, const PropertyInputContainer& inputs ) + void operator()(Vector2& current, const PropertyInputContainer& inputs) { const Vector2& centerPosition = inputs[0]->GetVector2(); - if( centerPosition.x > 0.f ) + if(centerPosition.x > 0.f) { - current.x = mThres+centerPosition.x * 0.5f; + current.x = mThres + centerPosition.x * 0.5f; current.y = centerPosition.y; } else { const Vector2& centerOrigin = inputs[1]->GetVector2(); - Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y); - float coef = 1.f+(centerPosition.x*2.f / mPageWidth); + Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y); + float coef = 1.f + (centerPosition.x * 2.f / mPageWidth); // when coef <= 0, the page is flat, slow down the last moment of the page stretch by 10 times to avoid a small bounce if(coef < 0.025f) { - coef = (coef+0.225f)/10.0f; + coef = (coef + 0.225f) / 10.0f; } current = centerOrigin - direction * coef; } @@ -191,25 +191,26 @@ struct CurrentCenterConstraint struct ShadowBlurStrengthConstraint { - ShadowBlurStrengthConstraint( float thres ) - : mThres( thres ) - {} + ShadowBlurStrengthConstraint(float thres) + : mThres(thres) + { + } - void operator()( float& blurStrength, const PropertyInputContainer& inputs ) + void operator()(float& blurStrength, const PropertyInputContainer& inputs) { float displacement = inputs[2]->GetFloat(); - if( EqualsZero(displacement)) + if(EqualsZero(displacement)) { const Vector2& cur = inputs[0]->GetVector2(); const Vector2& ori = inputs[1]->GetVector2(); - blurStrength = 5.f*(ori-cur).Length() / mThres; + blurStrength = 5.f * (ori - cur).Length() / mThres; } else { - blurStrength = 1.f - (displacement-2.f*mThres)/mThres; + blurStrength = 1.f - (displacement - 2.f * mThres) / mThres; } - blurStrength = blurStrength > 1.f ? 1.f : ( blurStrength < 0.f ? 0.f : blurStrength ); + blurStrength = blurStrength > 1.f ? 1.f : (blurStrength < 0.f ? 0.f : blurStrength); } float mThres; @@ -219,16 +220,12 @@ struct ShadowBlurStrengthConstraint namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { // empty handle as we cannot create PageTurnView(but type registered for page turn signal) @@ -236,128 +233,128 @@ BaseHandle Create() } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnView, Toolkit::Control, Create ); +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::PageTurnView, Toolkit::Control, Create); -DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "viewPageSize", VECTOR2, VIEW_PAGE_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "currentPageId", INTEGER, CURRENT_PAGE_ID ) -DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "spineShadow", VECTOR2, SPINE_SHADOW ) +DALI_PROPERTY_REGISTRATION(Toolkit, PageTurnView, "viewPageSize", VECTOR2, VIEW_PAGE_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, PageTurnView, "currentPageId", INTEGER, CURRENT_PAGE_ID) +DALI_PROPERTY_REGISTRATION(Toolkit, PageTurnView, "spineShadow", VECTOR2, SPINE_SHADOW) -DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnStarted", SIGNAL_PAGE_TURN_STARTED ) -DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnFinished", SIGNAL_PAGE_TURN_FINISHED ) -DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanStarted", SIGNAL_PAGE_PAN_STARTED ) -DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanFinished", SIGNAL_PAGE_PAN_FINISHED ) +DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pageTurnStarted", SIGNAL_PAGE_TURN_STARTED) +DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pageTurnFinished", SIGNAL_PAGE_TURN_FINISHED) +DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pagePanStarted", SIGNAL_PAGE_PAN_STARTED) +DALI_SIGNAL_REGISTRATION(Toolkit, PageTurnView, "pagePanFinished", SIGNAL_PAGE_PAN_FINISHED) DALI_TYPE_REGISTRATION_END() -} +} // namespace // these several constants are also used in the derived classes -const char * const PageTurnView::PROPERTY_TEXTURE_WIDTH( "uTextureWidth" ); // uniform name -const char * const PageTurnView::PROPERTY_ORIGINAL_CENTER( "originalCenter" ); // property used to constrain the uniform -const char * const PageTurnView::PROPERTY_CURRENT_CENTER( "currentCenter" );// property used to constrain the uniform -const int PageTurnView::MAXIMUM_TURNING_NUM = 4; -const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1; -const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE*2; -const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f; +const char* const PageTurnView::PROPERTY_TEXTURE_WIDTH("uTextureWidth"); // uniform name +const char* const PageTurnView::PROPERTY_ORIGINAL_CENTER("originalCenter"); // property used to constrain the uniform +const char* const PageTurnView::PROPERTY_CURRENT_CENTER("currentCenter"); // property used to constrain the uniform +const int PageTurnView::MAXIMUM_TURNING_NUM = 4; +const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1; +const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE * 2; +const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f; PageTurnView::Page::Page() -: isTurnBack( false ) +: isTurnBack(false) { actor = Actor::New(); - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT ); - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); - actor.SetProperty( Actor::Property::VISIBLE, false ); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT); + actor.SetProperty(Actor::Property::VISIBLE, false); - propertyPanDisplacement = actor.RegisterProperty( PROPERTY_PAN_DISPLACEMENT, 0.f ); - propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO); + propertyPanDisplacement = actor.RegisterProperty(PROPERTY_PAN_DISPLACEMENT, 0.f); + propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO); propertyOriginalCenter = actor.RegisterProperty(PROPERTY_ORIGINAL_CENTER, Vector2::ZERO); - propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO); + propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO); Matrix zeroMatrix(true); actor.RegisterProperty(PROPERTY_COMMON_PARAMETERS, zeroMatrix); propertyTurnDirection = actor.RegisterProperty(PROPERTY_TURN_DIRECTION, -1.f); } -void PageTurnView::Page::SetTexture( Texture texture ) +void PageTurnView::Page::SetTexture(Texture texture) { - if( !textureSet ) + if(!textureSet) { textureSet = TextureSet::New(); } - textureSet.SetTexture( 0u, texture ); + textureSet.SetTexture(0u, texture); } void PageTurnView::Page::UseEffect(Shader newShader) { shader = newShader; - if( renderer ) + if(renderer) { - renderer.SetShader( shader ); + renderer.SetShader(shader); } } void PageTurnView::Page::UseEffect(Shader newShader, Geometry geometry) { - UseEffect( newShader ); + UseEffect(newShader); - if( !renderer ) + if(!renderer) { - renderer = Renderer::New( geometry, shader ); + renderer = Renderer::New(geometry, shader); - if( !textureSet ) + if(!textureSet) { textureSet = TextureSet::New(); } - renderer.SetTextures( textureSet ); - renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON ); - actor.AddRenderer( renderer ); + renderer.SetTextures(textureSet); + renderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON); + actor.AddRenderer(renderer); } } void PageTurnView::Page::ChangeTurnDirection() { isTurnBack = !isTurnBack; - actor.SetProperty( propertyTurnDirection, isTurnBack ? 1.f : -1.f ); + actor.SetProperty(propertyTurnDirection, isTurnBack ? 1.f : -1.f); } void PageTurnView::Page::SetPanDisplacement(float value) { - actor.SetProperty( propertyPanDisplacement, value ); + actor.SetProperty(propertyPanDisplacement, value); } -void PageTurnView::Page::SetPanCenter( const Vector2& value ) +void PageTurnView::Page::SetPanCenter(const Vector2& value) { - actor.SetProperty( propertyPanCenter, value ); + actor.SetProperty(propertyPanCenter, value); } -void PageTurnView::Page::SetOriginalCenter( const Vector2& value ) +void PageTurnView::Page::SetOriginalCenter(const Vector2& value) { - actor.SetProperty( propertyOriginalCenter, value ); + actor.SetProperty(propertyOriginalCenter, value); } -void PageTurnView::Page::SetCurrentCenter( const Vector2& value ) +void PageTurnView::Page::SetCurrentCenter(const Vector2& value) { - actor.SetProperty( propertyCurrentCenter, value ); + actor.SetProperty(propertyCurrentCenter, value); } -PageTurnView::PageTurnView( PageFactory& pageFactory, const Vector2& viewPageSize ) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mPageFactory( &pageFactory ), - mPageSize( viewPageSize ), - mSpineShadowParameter( DEFAULT_SPINE_SHADOW_PARAMETER ), - mDistanceUpCorner( 0.f ), - mDistanceBottomCorner( 0.f ), - mPanDisplacement( 0.f ), - mTotalPageCount( 0 ), - mCurrentPageIndex( 0 ), - mTurningPageIndex( 0 ), - mIndex( 0 ), - mSlidingCount( 0 ), - mAnimatingCount( 0 ), - mConstraints( false ), - mPress( false ), - mPageUpdated( true ), +PageTurnView::PageTurnView(PageFactory& pageFactory, const Vector2& viewPageSize) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mPageFactory(&pageFactory), + mPageSize(viewPageSize), + mSpineShadowParameter(DEFAULT_SPINE_SHADOW_PARAMETER), + mDistanceUpCorner(0.f), + mDistanceBottomCorner(0.f), + mPanDisplacement(0.f), + mTotalPageCount(0), + mCurrentPageIndex(0), + mTurningPageIndex(0), + mIndex(0), + mSlidingCount(0), + mAnimatingCount(0), + mConstraints(false), + mPress(false), + mPageUpdated(true), mPageTurnStartedSignal(), mPageTurnFinishedSignal(), mPagePanStartedSignal(), @@ -371,32 +368,32 @@ PageTurnView::~PageTurnView() void PageTurnView::OnInitialize() { - // create the book spine effect for static pages + // create the book spine effect for static pages Property::Map spineEffectMap = CreatePageTurnBookSpineEffect(); - mSpineEffectShader = CreateShader( spineEffectMap ); - mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter ); + mSpineEffectShader = CreateShader(spineEffectMap); + mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter); // create the turn effect for turning pages Property::Map turnEffectMap = CreatePageTurnEffect(); - mTurnEffectShader = CreateShader( turnEffectMap ); - mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter ); + mTurnEffectShader = CreateShader(turnEffectMap); + mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter); // create the grid geometry for pages - uint16_t width = static_cast(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f); + uint16_t width = static_cast(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f); uint16_t height = static_cast(mPageSize.height / DEFAULT_GRID_DENSITY + 0.5f); - mGeometry = VisualFactoryCache::CreateGridGeometry( Uint16Pair( width, height ) ); + mGeometry = VisualFactoryCache::CreateGridGeometry(Uint16Pair(width, height)); - mPages.reserve( NUMBER_OF_CACHED_PAGES ); - for( int i = 0; i < NUMBER_OF_CACHED_PAGES; i++ ) + mPages.reserve(NUMBER_OF_CACHED_PAGES); + for(int i = 0; i < NUMBER_OF_CACHED_PAGES; i++) { - mPages.push_back( Page() ); - mPages[i].actor.SetProperty( Actor::Property::SIZE, mPageSize ); - Self().Add( mPages[i].actor ); + mPages.push_back(Page()); + mPages[i].actor.SetProperty(Actor::Property::SIZE, mPageSize); + Self().Add(mPages[i].actor); } // create the layer for turning pages mTurningPageLayer = Layer::New(); - mTurningPageLayer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT ); - mTurningPageLayer.SetProperty( Layer::Property::BEHAVIOR, Layer::LAYER_3D ); + mTurningPageLayer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT); + mTurningPageLayer.SetProperty(Layer::Property::BEHAVIOR, Layer::LAYER_3D); mTurningPageLayer.Raise(); // Set control size and the parent origin of page layers @@ -404,44 +401,44 @@ void PageTurnView::OnInitialize() Self().Add(mTurningPageLayer); - mTotalPageCount = static_cast( mPageFactory->GetNumberOfPages() ); + mTotalPageCount = static_cast(mPageFactory->GetNumberOfPages()); // add pages to the scene, and set depth for the stacked pages - for( int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ ) + for(int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++) { - AddPage( i ); - mPages[i].actor.SetProperty( Actor::Property::POSITION_Z, -static_cast( i )*STATIC_PAGE_INTERVAL_DISTANCE ); + AddPage(i); + mPages[i].actor.SetProperty(Actor::Property::POSITION_Z, -static_cast(i) * STATIC_PAGE_INTERVAL_DISTANCE); } - mPages[0].actor.SetProperty( Actor::Property::VISIBLE,true); + mPages[0].actor.SetProperty(Actor::Property::VISIBLE, true); // enable the pan gesture which is attached to the control EnableGestureDetection(GestureType::Value(GestureType::PAN)); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::PAGE_TAB_LIST ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::PAGE_TAB_LIST)); + }); } -Shader PageTurnView::CreateShader( const Property::Map& shaderMap ) +Shader PageTurnView::CreateShader(const Property::Map& shaderMap) { - Shader shader; - Property::Value* shaderValue = shaderMap.Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER ); - Property::Map shaderSource; - if( shaderValue && shaderValue->Get( shaderSource ) ) + Shader shader; + Property::Value* shaderValue = shaderMap.Find(Toolkit::Visual::Property::SHADER, CUSTOM_SHADER); + Property::Map shaderSource; + if(shaderValue && shaderValue->Get(shaderSource)) { - std::string vertexShader; - Property::Value* vertexShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER ); - if( !vertexShaderValue || !vertexShaderValue->Get( vertexShader ) ) + std::string vertexShader; + Property::Value* vertexShaderValue = shaderSource.Find(Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER); + if(!vertexShaderValue || !vertexShaderValue->Get(vertexShader)) { DALI_LOG_ERROR("PageTurnView::CreateShader failed: vertex shader source is not available.\n"); } - std::string fragmentShader; - Property::Value* fragmentShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER ); - if( !fragmentShaderValue || !fragmentShaderValue->Get( fragmentShader ) ) + std::string fragmentShader; + Property::Value* fragmentShaderValue = shaderSource.Find(Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER); + if(!fragmentShaderValue || !fragmentShaderValue->Get(fragmentShader)) { DALI_LOG_ERROR("PageTurnView::CreateShader failed: fragment shader source is not available.\n"); } - shader = Shader::New( vertexShader, fragmentShader ); + shader = Shader::New(vertexShader, fragmentShader); } else { @@ -453,35 +450,35 @@ Shader PageTurnView::CreateShader( const Property::Map& shaderMap ) void PageTurnView::SetupShadowView() { - mShadowView = Toolkit::ShadowView::New( 0.25f, 0.25f ); - Vector3 origin = mTurningPageLayer.GetCurrentProperty< Vector3 >( Actor::Property::PARENT_ORIGIN ); - mShadowView.SetProperty( Actor::Property::PARENT_ORIGIN, origin ); - mShadowView.SetProperty( Actor::Property::ANCHOR_POINT, origin ); - mShadowView.SetPointLightFieldOfView( Math::PI / 2.0f); + mShadowView = Toolkit::ShadowView::New(0.25f, 0.25f); + Vector3 origin = mTurningPageLayer.GetCurrentProperty(Actor::Property::PARENT_ORIGIN); + mShadowView.SetProperty(Actor::Property::PARENT_ORIGIN, origin); + mShadowView.SetProperty(Actor::Property::ANCHOR_POINT, origin); + mShadowView.SetPointLightFieldOfView(Math::PI / 2.0f); mShadowView.SetShadowColor(DEFAULT_SHADOW_COLOR); mShadowPlaneBackground = Actor::New(); - mShadowPlaneBackground.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mShadowPlaneBackground.SetProperty( Actor::Property::SIZE, mControlSize ); - Self().Add( mShadowPlaneBackground ); - mShadowView.SetShadowPlaneBackground( mShadowPlaneBackground ); + mShadowPlaneBackground.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mShadowPlaneBackground.SetProperty(Actor::Property::SIZE, mControlSize); + Self().Add(mShadowPlaneBackground); + mShadowView.SetShadowPlaneBackground(mShadowPlaneBackground); mPointLight = Actor::New(); - mPointLight.SetProperty( Actor::Property::ANCHOR_POINT, origin ); - mPointLight.SetProperty( Actor::Property::PARENT_ORIGIN, origin ); - mPointLight.SetProperty( Actor::Property::POSITION, Vector3( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO )); - Self().Add( mPointLight ); - mShadowView.SetPointLight( mPointLight ); + mPointLight.SetProperty(Actor::Property::ANCHOR_POINT, origin); + mPointLight.SetProperty(Actor::Property::PARENT_ORIGIN, origin); + mPointLight.SetProperty(Actor::Property::POSITION, Vector3(0.f, 0.f, mPageSize.width * POINT_LIGHT_HEIGHT_RATIO)); + Self().Add(mPointLight); + mShadowView.SetPointLight(mPointLight); - mTurningPageLayer.Add( mShadowView ); + mTurningPageLayer.Add(mShadowView); mShadowView.Activate(); } -void PageTurnView::OnSceneConnection( int depth ) +void PageTurnView::OnSceneConnection(int depth) { SetupShadowView(); - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } void PageTurnView::OnSceneDisconnection() @@ -500,25 +497,25 @@ void PageTurnView::OnSceneDisconnection() Control::OnSceneDisconnection(); } -void PageTurnView::SetPageSize( const Vector2& viewPageSize ) +void PageTurnView::SetPageSize(const Vector2& viewPageSize) { mPageSize = viewPageSize; - if( mPointLight ) + if(mPointLight) { - mPointLight.SetProperty( Actor::Property::POSITION, Vector3( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO )); + mPointLight.SetProperty(Actor::Property::POSITION, Vector3(0.f, 0.f, mPageSize.width * POINT_LIGHT_HEIGHT_RATIO)); } - for( size_t i=0; i(pageId), 0, mTotalPageCount-1); + int pageIdx = Clamp(static_cast(pageId), 0, mTotalPageCount - 1); - if( mCurrentPageIndex == pageIdx ) + if(mCurrentPageIndex == pageIdx) { return; } @@ -556,17 +553,16 @@ void PageTurnView::GoToPage( unsigned int pageId ) // record the new current page index mCurrentPageIndex = pageIdx; - // add the current page and the pages right before and after it - for( int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ ) + for(int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++) { - AddPage( i ); + AddPage(i); } - mPages[pageId%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,true); - if( pageId > 0 ) + mPages[pageId % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, true); + if(pageId > 0) { - mPages[(pageId-1)%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,true); + mPages[(pageId - 1) % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, true); } // set ordered depth to the stacked pages OrganizePageDepth(); @@ -574,64 +570,64 @@ void PageTurnView::GoToPage( unsigned int pageId ) unsigned int PageTurnView::GetCurrentPage() { - DALI_ASSERT_ALWAYS( mCurrentPageIndex >= 0 ); - return static_cast< unsigned int >( mCurrentPageIndex ); + DALI_ASSERT_ALWAYS(mCurrentPageIndex >= 0); + return static_cast(mCurrentPageIndex); } -void PageTurnView::AddPage( int pageIndex ) +void PageTurnView::AddPage(int pageIndex) { - if(pageIndex > -1 && pageIndex < mTotalPageCount) // whether the page is available from the page factory + if(pageIndex > -1 && pageIndex < mTotalPageCount) // whether the page is available from the page factory { int index = pageIndex % NUMBER_OF_CACHED_PAGES; Texture newPage; - newPage = mPageFactory->NewPage( pageIndex ); - DALI_ASSERT_ALWAYS( newPage && "must pass in valid texture" ); + newPage = mPageFactory->NewPage(pageIndex); + DALI_ASSERT_ALWAYS(newPage && "must pass in valid texture"); - bool isLeftSide = ( pageIndex < mCurrentPageIndex ); - if( mPages[index].isTurnBack != isLeftSide ) + bool isLeftSide = (pageIndex < mCurrentPageIndex); + if(mPages[index].isTurnBack != isLeftSide) { mPages[index].ChangeTurnDirection(); } - float degree = isLeftSide ? 180.f :0.f; - mPages[index].actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( degree ), Vector3::YAXIS ) ); - mPages[index].actor.SetProperty( Actor::Property::VISIBLE, false ); - mPages[index].UseEffect( mSpineEffectShader, mGeometry ); - mPages[index].SetTexture( newPage ); + float degree = isLeftSide ? 180.f : 0.f; + mPages[index].actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(degree), Vector3::YAXIS)); + mPages[index].actor.SetProperty(Actor::Property::VISIBLE, false); + mPages[index].UseEffect(mSpineEffectShader, mGeometry); + mPages[index].SetTexture(newPage); // For Portrait, nothing to do // For Landscape, set the parent origin to CENTER - OnAddPage( mPages[index].actor, isLeftSide ); + OnAddPage(mPages[index].actor, isLeftSide); } } -void PageTurnView::RemovePage( int pageIndex ) +void PageTurnView::RemovePage(int pageIndex) { - if( pageIndex > -1 && pageIndex < mTotalPageCount) + if(pageIndex > -1 && pageIndex < mTotalPageCount) { int index = pageIndex % NUMBER_OF_CACHED_PAGES; - mPages[index].actor.SetProperty( Actor::Property::VISIBLE,false); + mPages[index].actor.SetProperty(Actor::Property::VISIBLE, false); } } -void PageTurnView::OnPan( const PanGesture& gesture ) +void PageTurnView::OnPan(const PanGesture& gesture) { // the pan gesture is attached to control itself instead of each page - switch( gesture.GetState() ) + switch(gesture.GetState()) { case GestureState::STARTED: { // check whether the undergoing turning page number already reaches the maximum allowed - if( mPageUpdated && mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1 ) + if(mPageUpdated && mAnimatingCount < MAXIMUM_TURNING_NUM && mSlidingCount < 1) { const Vector2& position = gesture.GetPosition(); - SetPanActor( position ); // determine which page actor is panned - if( mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently + SetPanActor(position); // determine which page actor is panned + if(mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently { mTurningPageIndex = -1; } - PanStarted( SetPanPosition( position ) ); // pass in the pan position in the local page coordinate + PanStarted(SetPanPosition(position)); // pass in the pan position in the local page coordinate } else { @@ -641,13 +637,13 @@ void PageTurnView::OnPan( const PanGesture& gesture ) } case GestureState::CONTINUING: { - PanContinuing( SetPanPosition( gesture.GetPosition() ) ); // pass in the pan position in the local page coordinate + PanContinuing(SetPanPosition(gesture.GetPosition())); // pass in the pan position in the local page coordinate break; } case GestureState::FINISHED: case GestureState::CANCELLED: { - PanFinished( SetPanPosition( gesture.GetPosition() ), gesture.GetSpeed() ); + PanFinished(SetPanPosition(gesture.GetPosition()), gesture.GetSpeed()); break; } case GestureState::CLEAR: @@ -659,11 +655,11 @@ void PageTurnView::OnPan( const PanGesture& gesture ) } } -void PageTurnView::PanStarted( const Vector2& gesturePosition ) +void PageTurnView::PanStarted(const Vector2& gesturePosition) { mPressDownPosition = gesturePosition; - if( mTurningPageIndex == -1 ) + if(mTurningPageIndex == -1) { return; } @@ -671,65 +667,62 @@ void PageTurnView::PanStarted( const Vector2& gesturePosition ) mIndex = mTurningPageIndex % NUMBER_OF_CACHED_PAGES; mOriginalCenter = gesturePosition; - mPress = false; - mPageUpdated = false; + mPress = false; + mPageUpdated = false; // Guard against destruction during signal emission - Toolkit::PageTurnView handle( GetOwner() ); - mPagePanStartedSignal.Emit( handle ); + Toolkit::PageTurnView handle(GetOwner()); + mPagePanStartedSignal.Emit(handle); } -void PageTurnView::PanContinuing( const Vector2& gesturePosition ) +void PageTurnView::PanContinuing(const Vector2& gesturePosition) { - if( mTurningPageIndex == -1 ) + if(mTurningPageIndex == -1) { return; } // Guard against destruction during signal emission - Toolkit::PageTurnView handle( GetOwner() ); + Toolkit::PageTurnView handle(GetOwner()); if(!mPress) { // when the touch down position is near the spine // or when the panning goes outwards or some other position which would tear the paper in real situation // we change the start position into the current panning position and update the shader parameters - if( mOriginalCenter.x < mPageSize.width*MINIMUM_START_POSITION_RATIO - || gesturePosition.x > mOriginalCenter.x-1.0f - || ( ( gesturePosition.x/mOriginalCenter.x > gesturePosition.y/mOriginalCenter.y ) && - ( gesturePosition.x/mOriginalCenter.x > (gesturePosition.y-mPageSize.height )/(mOriginalCenter.y-mPageSize.height ) ) ) ) + if(mOriginalCenter.x < mPageSize.width * MINIMUM_START_POSITION_RATIO || gesturePosition.x > mOriginalCenter.x - 1.0f || ((gesturePosition.x / mOriginalCenter.x > gesturePosition.y / mOriginalCenter.y) && (gesturePosition.x / mOriginalCenter.x > (gesturePosition.y - mPageSize.height) / (mOriginalCenter.y - mPageSize.height)))) { mOriginalCenter = gesturePosition; } else { - mDistanceUpCorner = mOriginalCenter.Length(); - mDistanceBottomCorner = ( mOriginalCenter - Vector2( 0.0f, mPageSize.height ) ).Length(); - mShadowView.Add( mPages[mIndex].actor ); - mPages[mIndex].UseEffect( mTurnEffectShader ); - mPages[mIndex].SetOriginalCenter( mOriginalCenter ); + mDistanceUpCorner = mOriginalCenter.Length(); + mDistanceBottomCorner = (mOriginalCenter - Vector2(0.0f, mPageSize.height)).Length(); + mShadowView.Add(mPages[mIndex].actor); + mPages[mIndex].UseEffect(mTurnEffectShader); + mPages[mIndex].SetOriginalCenter(mOriginalCenter); mCurrentCenter = mOriginalCenter; - mPages[mIndex].SetCurrentCenter( mCurrentCenter ); + mPages[mIndex].SetCurrentCenter(mCurrentCenter); mPanDisplacement = 0.f; - mConstraints = false; - mPress = true; + mConstraints = false; + mPress = true; mAnimatingCount++; - mPageTurnStartedSignal.Emit( handle, static_cast(mTurningPageIndex), !mPages[mIndex].isTurnBack ); + mPageTurnStartedSignal.Emit(handle, static_cast(mTurningPageIndex), !mPages[mIndex].isTurnBack); int id = mTurningPageIndex + (mPages[mIndex].isTurnBack ? -1 : 1); - if( id >=0 && id < mTotalPageCount ) + if(id >= 0 && id < mTotalPageCount) { - mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,true); + mPages[id % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, true); } mShadowView.RemoveConstraints(); Actor self = Self(); - mPages[mIndex].SetPanDisplacement( 0.f ); + mPages[mIndex].SetPanDisplacement(0.f); - Constraint shadowBlurStrengthConstraint = Constraint::New( mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint( mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO ) ); - shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter) ); - shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter) ); - shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement) ); + Constraint shadowBlurStrengthConstraint = Constraint::New(mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint(mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO)); + shadowBlurStrengthConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter)); + shadowBlurStrengthConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter)); + shadowBlurStrengthConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement)); shadowBlurStrengthConstraint.Apply(); } } @@ -740,73 +733,72 @@ void PageTurnView::PanContinuing( const Vector2& gesturePosition ) // Test whether the new current center would tear the paper from the top pine in real situation // we do not forbid this totally, which would restrict the panning gesture too much // instead, set it to the nearest allowable position - float distanceUpCorner = currentCenter.Length(); - float distanceBottomCorner = ( currentCenter-Vector2( 0.0f, mPageSize.height ) ).Length(); - if( distanceUpCorner > mDistanceUpCorner ) + float distanceUpCorner = currentCenter.Length(); + float distanceBottomCorner = (currentCenter - Vector2(0.0f, mPageSize.height)).Length(); + if(distanceUpCorner > mDistanceUpCorner) { - currentCenter = currentCenter*mDistanceUpCorner/distanceUpCorner; + currentCenter = currentCenter * mDistanceUpCorner / distanceUpCorner; } // would tear the paper from the bottom spine in real situation - if( distanceBottomCorner > mDistanceBottomCorner ) + if(distanceBottomCorner > mDistanceBottomCorner) { - currentCenter = ( ( currentCenter - Vector2( 0.0f, mPageSize.height ) )*mDistanceBottomCorner/distanceBottomCorner + Vector2(0.0f,mPageSize.height ) ); + currentCenter = ((currentCenter - Vector2(0.0f, mPageSize.height)) * mDistanceBottomCorner / distanceBottomCorner + Vector2(0.0f, mPageSize.height)); } // If direction has a very high y component, reduce it. Vector2 curveDirection = currentCenter - mOriginalCenter; - if( fabs( curveDirection.y ) > fabs( curveDirection.x ) ) + if(fabs(curveDirection.y) > fabs(curveDirection.x)) { - currentCenter.y = mOriginalCenter.y + ( currentCenter.y - mOriginalCenter.y ) * fabs( curveDirection.x/curveDirection.y ); + currentCenter.y = mOriginalCenter.y + (currentCenter.y - mOriginalCenter.y) * fabs(curveDirection.x / curveDirection.y); } // If the vertical distance is high, reduce it float yShift = currentCenter.y - mOriginalCenter.y; - if( fabs( yShift ) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO ) + if(fabs(yShift) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO) { - currentCenter.y = mOriginalCenter.y + yShift*mPageSize.height*MAXIMUM_VERTICAL_MOVEMENT_RATIO/fabs(yShift ); + currentCenter.y = mOriginalCenter.y + yShift * mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO / fabs(yShift); } // use contraints to control the page shape and rotation when the pan position is near the spine - if( currentCenter.x <= mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO ) + if(currentCenter.x <= mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO) { // set the property values used by the constraints - mPanDisplacement = mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x; - mPages[mIndex].SetPanDisplacement( mPanDisplacement ); - mPages[mIndex].SetPanCenter( currentCenter ); + mPanDisplacement = mPageSize.width * PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x; + mPages[mIndex].SetPanDisplacement(mPanDisplacement); + mPages[mIndex].SetPanCenter(currentCenter); // set up the OriginalCenterConstraint and CurrentCebterConstraint to the PageTurnEdffect // also set up the RotationConstraint to the page actor - if( !mConstraints ) + if(!mConstraints) { Vector2 corner; // the corner position need to be a little far away from the page edge to ensure the whole page is lift up - if( currentCenter.y >= mOriginalCenter.y ) + if(currentCenter.y >= mOriginalCenter.y) { - corner = Vector2( 1.1f*mPageSize.width, 0.f ); + corner = Vector2(1.1f * mPageSize.width, 0.f); } else { - corner = mPageSize*1.1f; + corner = mPageSize * 1.1f; } - Vector2 offset( currentCenter-mOriginalCenter ); - float k = - ( (mOriginalCenter.x-corner.x)*offset.x + (mOriginalCenter.y-corner.y)*offset.y ) - /( offset.x*offset.x + offset.y*offset.y ); + Vector2 offset(currentCenter - mOriginalCenter); + float k = -((mOriginalCenter.x - corner.x) * offset.x + (mOriginalCenter.y - corner.y) * offset.y) / (offset.x * offset.x + offset.y * offset.y); offset *= k; Actor self = Self(); - Constraint originalCenterConstraint = Constraint::New( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint( mOriginalCenter, offset )); - originalCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) ); + Constraint originalCenterConstraint = Constraint::New(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint(mOriginalCenter, offset)); + originalCenterConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement)); originalCenterConstraint.Apply(); - Constraint currentCenterConstraint = Constraint::New( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width)); - currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanCenter ) ); - currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter ) ); + Constraint currentCenterConstraint = Constraint::New(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width)); + currentCenterConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter)); + currentCenterConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter)); currentCenterConstraint.Apply(); - PageTurnApplyInternalConstraint( mPages[mIndex].actor, mPageSize.height ); + PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height); - float distance = offset.Length(); - Constraint rotationConstraint = Constraint::New( mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack)); - rotationConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) ); + float distance = offset.Length(); + Constraint rotationConstraint = Constraint::New(mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack)); + rotationConstraint.AddSource(Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement)); rotationConstraint.Apply(); mConstraints = true; @@ -817,34 +809,34 @@ void PageTurnView::PanContinuing( const Vector2& gesturePosition ) if(mConstraints) // remove the constraint is the pan position move back to far away from the spine { mPages[mIndex].actor.RemoveConstraints(); - mPages[mIndex].SetOriginalCenter(mOriginalCenter ); - mConstraints = false; + mPages[mIndex].SetOriginalCenter(mOriginalCenter); + mConstraints = false; mPanDisplacement = 0.f; } - mPages[mIndex].SetCurrentCenter( currentCenter ); + mPages[mIndex].SetCurrentCenter(currentCenter); mCurrentCenter = currentCenter; - PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height ); + PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height); } } } -void PageTurnView::PanFinished( const Vector2& gesturePosition, float gestureSpeed ) +void PageTurnView::PanFinished(const Vector2& gesturePosition, float gestureSpeed) { // Guard against destruction during signal emission - Toolkit::PageTurnView handle( GetOwner() ); + Toolkit::PageTurnView handle(GetOwner()); - if( mTurningPageIndex == -1 ) + if(mTurningPageIndex == -1) { - if( mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1) + if(mAnimatingCount < MAXIMUM_TURNING_NUM && mSlidingCount < 1) { - OnPossibleOutwardsFlick( gesturePosition, gestureSpeed ); + OnPossibleOutwardsFlick(gesturePosition, gestureSpeed); } return; } - mPagePanFinishedSignal.Emit( handle ); + mPagePanFinishedSignal.Emit(handle); if(mPress) { @@ -855,111 +847,114 @@ void PageTurnView::PanFinished( const Vector2& gesturePosition, float gestureSpe if(mPages[mIndex].isTurnBack) { mCurrentPageIndex--; - RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE ); - AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE ); + RemovePage(mCurrentPageIndex + NUMBER_OF_CACHED_PAGES_EACH_SIDE); + AddPage(mCurrentPageIndex - NUMBER_OF_CACHED_PAGES_EACH_SIDE); } else { mCurrentPageIndex++; - RemovePage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 ); - AddPage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 ); + RemovePage(mCurrentPageIndex - NUMBER_OF_CACHED_PAGES_EACH_SIDE - 1); + AddPage(mCurrentPageIndex + NUMBER_OF_CACHED_PAGES_EACH_SIDE - 1); } OrganizePageDepth(); // set up an animation to turn the page over - float width = mPageSize.width*(1.f+PAGE_TURN_OVER_THRESHOLD_RATIO); - Animation animation = Animation::New( std::max(0.1f,PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width)) ); - animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement), - width,AlphaFunction::EASE_OUT_SINE); - animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter), - Vector2(-mPageSize.width*1.1f, 0.5f*mPageSize.height), AlphaFunction::EASE_OUT_SINE); + float width = mPageSize.width * (1.f + PAGE_TURN_OVER_THRESHOLD_RATIO); + Animation animation = Animation::New(std::max(0.1f, PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width))); + animation.AnimateTo(Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement), + width, + AlphaFunction::EASE_OUT_SINE); + animation.AnimateTo(Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter), + Vector2(-mPageSize.width * 1.1f, 0.5f * mPageSize.height), + AlphaFunction::EASE_OUT_SINE); mAnimationPageIdPair[animation] = mTurningPageIndex; animation.Play(); - animation.FinishedSignal().Connect( this, &PageTurnView::TurnedOver ); + animation.FinishedSignal().Connect(this, &PageTurnView::TurnedOver); } else // the pan finished position is far away from the spine, set up an animation to slide the page back instead of turning over { - Animation animation= Animation::New( PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO ); - animation.AnimateTo( Property( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter ), - mOriginalCenter, AlphaFunction::LINEAR ); + Animation animation = Animation::New(PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO); + animation.AnimateTo(Property(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter), + mOriginalCenter, + AlphaFunction::LINEAR); mAnimationPageIdPair[animation] = mTurningPageIndex; animation.Play(); mSlidingCount++; - animation.FinishedSignal().Connect( this, &PageTurnView::SliddenBack ); + animation.FinishedSignal().Connect(this, &PageTurnView::SliddenBack); - mPageTurnStartedSignal.Emit( handle, static_cast(mTurningPageIndex), mPages[mIndex].isTurnBack ); + mPageTurnStartedSignal.Emit(handle, static_cast(mTurningPageIndex), mPages[mIndex].isTurnBack); } } else { // In portrait view, an outwards flick should turn the previous page back // In landscape view, nothing to do - OnPossibleOutwardsFlick( gesturePosition, gestureSpeed ); + OnPossibleOutwardsFlick(gesturePosition, gestureSpeed); } mPageUpdated = true; } -void PageTurnView::TurnedOver( Animation& animation ) +void PageTurnView::TurnedOver(Animation& animation) { int pageId = mAnimationPageIdPair[animation]; - int index = pageId%NUMBER_OF_CACHED_PAGES; + int index = pageId % NUMBER_OF_CACHED_PAGES; mPages[index].ChangeTurnDirection(); mPages[index].actor.RemoveConstraints(); Self().Add(mPages[index].actor); mAnimatingCount--; - mAnimationPageIdPair.erase( animation ); + mAnimationPageIdPair.erase(animation); float degree = mPages[index].isTurnBack ? 180.f : 0.f; - mPages[index].actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree(degree), Vector3::YAXIS ) ); - mPages[index].UseEffect( mSpineEffectShader ); + mPages[index].actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(degree), Vector3::YAXIS)); + mPages[index].UseEffect(mSpineEffectShader); int id = pageId + (mPages[index].isTurnBack ? -1 : 1); - if( id >=0 && id < mTotalPageCount ) + if(id >= 0 && id < mTotalPageCount) { - mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,false); + mPages[id % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, false); } - OnTurnedOver( mPages[index].actor, mPages[index].isTurnBack ); + OnTurnedOver(mPages[index].actor, mPages[index].isTurnBack); // Guard against destruction during signal emission - Toolkit::PageTurnView handle( GetOwner() ); - mPageTurnFinishedSignal.Emit( handle, static_cast(pageId), mPages[index].isTurnBack ); + Toolkit::PageTurnView handle(GetOwner()); + mPageTurnFinishedSignal.Emit(handle, static_cast(pageId), mPages[index].isTurnBack); } -void PageTurnView::SliddenBack( Animation& animation ) +void PageTurnView::SliddenBack(Animation& animation) { int pageId = mAnimationPageIdPair[animation]; - int index = pageId%NUMBER_OF_CACHED_PAGES; + int index = pageId % NUMBER_OF_CACHED_PAGES; Self().Add(mPages[index].actor); mSlidingCount--; mAnimatingCount--; - mAnimationPageIdPair.erase( animation ); + mAnimationPageIdPair.erase(animation); - mPages[index].UseEffect( mSpineEffectShader ); + mPages[index].UseEffect(mSpineEffectShader); int id = pageId + (mPages[index].isTurnBack ? -1 : 1); - if( id >=0 && id < mTotalPageCount ) + if(id >= 0 && id < mTotalPageCount) { - mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::VISIBLE,false); + mPages[id % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::VISIBLE, false); } // Guard against destruction during signal emission - Toolkit::PageTurnView handle( GetOwner() ); - mPageTurnFinishedSignal.Emit( handle, static_cast(pageId), mPages[index].isTurnBack ); + Toolkit::PageTurnView handle(GetOwner()); + mPageTurnFinishedSignal.Emit(handle, static_cast(pageId), mPages[index].isTurnBack); } void PageTurnView::OrganizePageDepth() { - for( int i=0; i( i )*STATIC_PAGE_INTERVAL_DISTANCE ); + mPages[(mCurrentPageIndex + i) % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::POSITION_Z, -static_cast(i) * STATIC_PAGE_INTERVAL_DISTANCE); } - if( mCurrentPageIndex >= i + 1 ) + if(mCurrentPageIndex >= i + 1) { - mPages[( mCurrentPageIndex-i-1 )%NUMBER_OF_CACHED_PAGES].actor.SetProperty( Actor::Property::POSITION_Z, -static_cast( i )*STATIC_PAGE_INTERVAL_DISTANCE ); + mPages[(mCurrentPageIndex - i - 1) % NUMBER_OF_CACHED_PAGES].actor.SetProperty(Actor::Property::POSITION_Z, -static_cast(i) * STATIC_PAGE_INTERVAL_DISTANCE); } } } @@ -967,24 +962,24 @@ void PageTurnView::OrganizePageDepth() void PageTurnView::StopTurning() { mAnimatingCount = 0; - mSlidingCount = 0; + mSlidingCount = 0; - if( !mPageUpdated ) + if(!mPageUpdated) { int index = mTurningPageIndex % NUMBER_OF_CACHED_PAGES; - Self().Add( mPages[ index ].actor ); - mPages[ index ].actor.RemoveConstraints(); - mPages[ index ].UseEffect( mSpineEffectShader ); - float degree = mTurningPageIndex==mCurrentPageIndex ? 0.f :180.f; - mPages[index].actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree(degree), Vector3::YAXIS ) ); + Self().Add(mPages[index].actor); + mPages[index].actor.RemoveConstraints(); + mPages[index].UseEffect(mSpineEffectShader); + float degree = mTurningPageIndex == mCurrentPageIndex ? 0.f : 180.f; + mPages[index].actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(degree), Vector3::YAXIS)); mPageUpdated = true; } - if( !mAnimationPageIdPair.empty() ) + if(!mAnimationPageIdPair.empty()) { - for (std::map::iterator it=mAnimationPageIdPair.begin(); it!=mAnimationPageIdPair.end(); ++it) + for(std::map::iterator it = mAnimationPageIdPair.begin(); it != mAnimationPageIdPair.end(); ++it) { - static_cast(it->first).SetCurrentProgress( 1.f ); + static_cast(it->first).SetCurrentProgress(1.f); } } } @@ -1009,28 +1004,28 @@ Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanFinishedSignal() return mPagePanFinishedSignal; } -bool PageTurnView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool PageTurnView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( handle ); + bool connected(true); + Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_STARTED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_TURN_STARTED)) { - pageTurnView.PageTurnStartedSignal().Connect( tracker, functor ); + pageTurnView.PageTurnStartedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED)) { - pageTurnView.PageTurnFinishedSignal().Connect( tracker, functor ); + pageTurnView.PageTurnFinishedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_STARTED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_PAN_STARTED)) { - pageTurnView.PagePanStartedSignal().Connect( tracker, functor ); + pageTurnView.PagePanStartedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED)) { - pageTurnView.PagePanFinishedSignal().Connect( tracker, functor ); + pageTurnView.PagePanFinishedSignal().Connect(tracker, functor); } else { @@ -1041,46 +1036,46 @@ bool PageTurnView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterfa return connected; } -void PageTurnView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void PageTurnView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast(Dali::BaseHandle(object)); - if( pageTurnView ) + if(pageTurnView) { - PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) ); + PageTurnView& pageTurnViewImpl(GetImplementation(pageTurnView)); - switch( index ) + switch(index) { case Toolkit::PageTurnView::Property::VIEW_PAGE_SIZE: { - pageTurnViewImpl.SetPageSize( value.Get() ); + pageTurnViewImpl.SetPageSize(value.Get()); break; } case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID: { - pageTurnViewImpl.GoToPage( value.Get() ); + pageTurnViewImpl.GoToPage(value.Get()); break; } case Toolkit::PageTurnView::Property::SPINE_SHADOW: { - pageTurnViewImpl.SetSpineShadowParameter( value.Get() ); + pageTurnViewImpl.SetSpineShadowParameter(value.Get()); break; } } } } -Property::Value PageTurnView::GetProperty( BaseObject* object, Property::Index index ) +Property::Value PageTurnView::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast(Dali::BaseHandle(object)); - if( pageTurnView ) + if(pageTurnView) { - PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) ); + PageTurnView& pageTurnViewImpl(GetImplementation(pageTurnView)); - switch( index ) + switch(index) { case Toolkit::PageTurnView::Property::VIEW_PAGE_SIZE: { @@ -1089,7 +1084,7 @@ Property::Value PageTurnView::GetProperty( BaseObject* object, Property::Index i } case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID: { - value = static_cast( pageTurnViewImpl.GetCurrentPage() ); + value = static_cast(pageTurnViewImpl.GetCurrentPage()); break; } case Toolkit::PageTurnView::Property::SPINE_SHADOW: diff --git a/dali-toolkit/internal/controls/popup/confirmation-popup-impl.cpp b/dali-toolkit/internal/controls/popup/confirmation-popup-impl.cpp index 0f1a585..1d8f605 100644 --- a/dali-toolkit/internal/controls/popup/confirmation-popup-impl.cpp +++ b/dali-toolkit/internal/controls/popup/confirmation-popup-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,8 +19,8 @@ #include "confirmation-popup-impl.h" // EXTERNAL INCLUDES -#include #include +#include #include // INTERNAL INCLUDES @@ -28,16 +28,12 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - /* * This struct is used to define all details required about a dynamically created signal. */ @@ -48,15 +44,17 @@ struct ControlDetailType const char* connectSignalPropertyName; }; +// clang-format off /* A table of all control details. These details are kept in one place for maintainability. * Name of the signal | Name of the control | Name of the property which lets the * the app-developer | which will provide | app developer choose which signal * can connect to. | the signal. | within the control to connect to. */ const ControlDetailType ControlDetails[] = { - { "controlSignalOk", "controlOk", "connectSignalOkSelected" }, - { "controlSignalCancel", "controlCancel", "connectSignalCancelSelected" }, + {"controlSignalOk", "controlOk", "connectSignalOkSelected" }, + {"controlSignalCancel", "controlCancel", "connectSignalCancelSelected"}, }; -const unsigned int ControlDetailsCount = sizeof( ControlDetails ) / sizeof( ControlDetails[0] ); +// clang-format on +const unsigned int ControlDetailsCount = sizeof(ControlDetails) / sizeof(ControlDetails[0]); // To give sensible default behaviour to save the connect signal properties being set. const char* const DEFAULT_CONNECT_SIGNAL_NAME = "clicked"; @@ -66,15 +64,15 @@ BaseHandle Create() return Toolkit::ConfirmationPopup::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ConfirmationPopup, Toolkit::Popup, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ConfirmationPopup, Toolkit::Popup, Create) -DALI_PROPERTY_REGISTRATION( Toolkit, ConfirmationPopup, ControlDetails[0].connectSignalPropertyName, STRING, CONNECT_SIGNAL_OK_SELECTED ) -DALI_PROPERTY_REGISTRATION( Toolkit, ConfirmationPopup, ControlDetails[1].connectSignalPropertyName, STRING, CONNECT_SIGNAL_CANCEL_SELECTED ) +DALI_PROPERTY_REGISTRATION(Toolkit, ConfirmationPopup, ControlDetails[0].connectSignalPropertyName, STRING, CONNECT_SIGNAL_OK_SELECTED) +DALI_PROPERTY_REGISTRATION(Toolkit, ConfirmationPopup, ControlDetails[1].connectSignalPropertyName, STRING, CONNECT_SIGNAL_CANCEL_SELECTED) // Note: We do not use the macros for signal registration as we do not want to redefine the signal name strings. // We have predefined them for optimal signal name to control name lookup. -SignalConnectorType signalConnector1( typeRegistration, ControlDetails[0].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal ); -SignalConnectorType signalConnector2( typeRegistration, ControlDetails[1].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal ); +SignalConnectorType signalConnector1(typeRegistration, ControlDetails[0].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal); +SignalConnectorType signalConnector2(typeRegistration, ControlDetails[1].signalName, &Toolkit::Internal::ConfirmationPopup::DoConnectSignal); DALI_TYPE_REGISTRATION_END() @@ -83,10 +81,10 @@ DALI_TYPE_REGISTRATION_END() Dali::Toolkit::ConfirmationPopup ConfirmationPopup::New() { // Create the implementation, temporarily owned on stack. - IntrusivePtr< ConfirmationPopup > internalConfirmationPopup = new ConfirmationPopup(); + IntrusivePtr internalConfirmationPopup = new ConfirmationPopup(); // Pass ownership to CustomActor - Dali::Toolkit::ConfirmationPopup confirmationPopup( *internalConfirmationPopup ); + Dali::Toolkit::ConfirmationPopup confirmationPopup(*internalConfirmationPopup); // Second-phase initialisation of the implementation. // This can only be done after the CustomActor connection has been made... @@ -98,64 +96,64 @@ Dali::Toolkit::ConfirmationPopup ConfirmationPopup::New() ConfirmationPopup::ConfirmationPopup() : Toolkit::Internal::Popup() { - mControlSignals.reserve( MAXIMUM_NUMBER_OF_CONTROLS ); - mControlSignalNames[ Toolkit::ConfirmationPopup::CONTROL_OK ] = DEFAULT_CONNECT_SIGNAL_NAME; - mControlSignalNames[ Toolkit::ConfirmationPopup::CONTROL_CANCEL ] = DEFAULT_CONNECT_SIGNAL_NAME; + mControlSignals.reserve(MAXIMUM_NUMBER_OF_CONTROLS); + mControlSignalNames[Toolkit::ConfirmationPopup::CONTROL_OK] = DEFAULT_CONNECT_SIGNAL_NAME; + mControlSignalNames[Toolkit::ConfirmationPopup::CONTROL_CANCEL] = DEFAULT_CONNECT_SIGNAL_NAME; } ConfirmationPopup::~ConfirmationPopup() { - for( SignalContainerType::iterator i = mControlSignals.begin(); i != mControlSignals.end(); ++i ) + for(SignalContainerType::iterator i = mControlSignals.begin(); i != mControlSignals.end(); ++i) { - delete ( i->second ); + delete(i->second); } mControlSignals.clear(); } -void ConfirmationPopup::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) +void ConfirmationPopup::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value) { - Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast(Dali::BaseHandle(object)); - if ( popup ) + if(popup) { - ConfirmationPopup& popupImpl( GetDerivedImplementation( popup ) ); + ConfirmationPopup& popupImpl(GetDerivedImplementation(popup)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_OK_SELECTED: { - popupImpl.SetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_OK, value.Get< std::string >() ); + popupImpl.SetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_OK, value.Get()); break; } case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_CANCEL_SELECTED: { - popupImpl.SetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_CANCEL, value.Get< std::string >() ); + popupImpl.SetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_CANCEL, value.Get()); break; } } } } -Property::Value ConfirmationPopup::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value ConfirmationPopup::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast(Dali::BaseHandle(object)); - if ( popup ) + if(popup) { - ConfirmationPopup& popupImpl( GetDerivedImplementation( popup ) ); + ConfirmationPopup& popupImpl(GetDerivedImplementation(popup)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_OK_SELECTED: { - value = popupImpl.GetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_OK ); + value = popupImpl.GetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_OK); break; } case Toolkit::ConfirmationPopup::Property::CONNECT_SIGNAL_CANCEL_SELECTED: { - value = popupImpl.GetControlSignalName( Toolkit::ConfirmationPopup::CONTROL_CANCEL ); + value = popupImpl.GetControlSignalName(Toolkit::ConfirmationPopup::CONTROL_CANCEL); break; } } @@ -164,38 +162,38 @@ Property::Value ConfirmationPopup::GetProperty( BaseObject* object, Property::In return value; } -void ConfirmationPopup::SetControlSignalName( const unsigned int controlNumber, const std::string& signalName ) +void ConfirmationPopup::SetControlSignalName(const unsigned int controlNumber, const std::string& signalName) { - if( controlNumber < ControlDetailsCount ) + if(controlNumber < ControlDetailsCount) { - mControlSignalNames[ controlNumber ] = signalName; + mControlSignalNames[controlNumber] = signalName; } } -std::string ConfirmationPopup::GetControlSignalName( unsigned int controlNumber ) const +std::string ConfirmationPopup::GetControlSignalName(unsigned int controlNumber) const { - if( controlNumber < ControlDetailsCount ) + if(controlNumber < ControlDetailsCount) { - return mControlSignalNames[ controlNumber ]; + return mControlSignalNames[controlNumber]; } return ""; } -bool ConfirmationPopup::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool ConfirmationPopup::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); - Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast( handle ); + Dali::BaseHandle handle(object); + Toolkit::ConfirmationPopup popup = Toolkit::ConfirmationPopup::DownCast(handle); // Look up the requested signal, attempting to create it dynamically if it doesn't exist. - SignalDelegate* signalDelegate = Dali::Toolkit::GetDerivedImplementation( popup ).GetControlSignal( signalName ); - if( signalDelegate ) + SignalDelegate* signalDelegate = Dali::Toolkit::GetDerivedImplementation(popup).GetControlSignal(signalName); + if(signalDelegate) { // The signal delegate was created successfully, attempt to connect it to a callback if specified. // If none is specified, the creation is still successful as the signal delegate can connect at a later time. - if( functor ) + if(functor) { - signalDelegate->Connect( tracker, functor ); + signalDelegate->Connect(tracker, functor); } return true; } @@ -204,14 +202,14 @@ bool ConfirmationPopup::DoConnectSignal( BaseObject* object, ConnectionTrackerIn return false; } -SignalDelegate* ConfirmationPopup::GetControlSignal( const std::string& signalName ) +SignalDelegate* ConfirmationPopup::GetControlSignal(const std::string& signalName) { // Check if the specified signal name already exists. SignalContainerType::iterator end = mControlSignals.end(); - for( SignalContainerType::iterator iter = mControlSignals.begin(); iter != end; ++iter ) + for(SignalContainerType::iterator iter = mControlSignals.begin(); iter != end; ++iter) { // Find the first non-connected signal by matching signal name. - if( ( signalName == iter->first ) && ( !iter->second->IsConnected() ) ) + if((signalName == iter->first) && (!iter->second->IsConnected())) { // The requested signal (delegate) already exists, just return it. return iter->second; @@ -222,21 +220,21 @@ SignalDelegate* ConfirmationPopup::GetControlSignal( const std::string& signalNa // To make a new connection to an existing signal, we need a new delegate, // as delegates house a signal connection functor each. // Check the signal name is valid and if so create the signal dynamically. - for( unsigned int i = 0; i < ControlDetailsCount; ++i ) + for(unsigned int i = 0; i < ControlDetailsCount; ++i) { - if( 0 == strcmp( signalName.c_str(), ControlDetails[ i ].signalName ) ) + if(0 == strcmp(signalName.c_str(), ControlDetails[i].signalName)) { // The signal name is valid, check the respective actor to connect to exists. - Actor connectActor = Self().FindChildByName( ControlDetails[ i ].controlName ); - if( connectActor ) + Actor connectActor = Self().FindChildByName(ControlDetails[i].controlName); + if(connectActor) { // The actor exists, set up a signal delegate that will allow the application developer // to connect the actor signal directly to their callback. // Note: We don't use the GetControlSignalName() here for speedup, as we know the array bound is capped. - SignalDelegate* signalDelegate = new SignalDelegate( connectActor, mControlSignalNames[ i ] ); + SignalDelegate* signalDelegate = new SignalDelegate(connectActor, mControlSignalNames[i]); // Store the delegate with the signal name so we know what signals have been dynamically created so far. - mControlSignals.push_back( std::make_pair( signalName, signalDelegate ) ); + mControlSignals.push_back(std::make_pair(signalName, signalDelegate)); // Return the delegate to allow connection to the newly created signal. return signalDelegate; @@ -251,7 +249,6 @@ SignalDelegate* ConfirmationPopup::GetControlSignal( const std::string& signalNa return NULL; } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/controls/popup/popup-impl.cpp b/dali-toolkit/internal/controls/popup/popup-impl.cpp index 092569c..768a978 100644 --- a/dali-toolkit/internal/controls/popup/popup-impl.cpp +++ b/dali-toolkit/internal/controls/popup/popup-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,46 +19,40 @@ #include // EXTERNAL INCLUDES -#include // for strcmp -#include #include -#include +#include +#include +#include #include #include #include -#include #include #include +#include #include -#include -#include #include +#include // for strcmp // INTERNAL INCLUDES +#include #include +#include #include #include #include #include #include -#include -#include -#include using namespace Dali; namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - /** * Creation function for main Popup type. * @return Handle to the new popup object. @@ -69,10 +63,10 @@ BaseHandle Create() } // Toast style defaults. -const int DEFAULT_TOAST_AUTO_HIDE_DELAY = 3000; ///< Toast will auto-hide after 3000ms (3 seconds) -const float DEFAULT_TOAST_TRANSITION_TIME = 0.65f; ///< Default time the toast Popup will take to show and hide. -const Vector3 DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN( 0.5f, 0.94f, 0.5f ); ///< This is similar to BOTTOM_CENTER, but vertically higher up, as a ratio of parent height. -const Vector3 DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO( 0.75f, 0.75f, 0.75f ); ///< Amount of the stage's width that the toast popup will take up. +const int DEFAULT_TOAST_AUTO_HIDE_DELAY = 3000; ///< Toast will auto-hide after 3000ms (3 seconds) +const float DEFAULT_TOAST_TRANSITION_TIME = 0.65f; ///< Default time the toast Popup will take to show and hide. +const Vector3 DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN(0.5f, 0.94f, 0.5f); ///< This is similar to BOTTOM_CENTER, but vertically higher up, as a ratio of parent height. +const Vector3 DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO(0.75f, 0.75f, 0.75f); ///< Amount of the stage's width that the toast popup will take up. /** * Creation function for named type "popupToast". @@ -83,126 +77,134 @@ BaseHandle CreateToast() Toolkit::Popup popup = Toolkit::Popup::New(); // Setup for Toast Popup type. - popup.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO ); - popup.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH ); - popup.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT ); - popup.SetProperty( Toolkit::Popup::Property::CONTEXTUAL_MODE, Toolkit::Popup::NON_CONTEXTUAL ); - popup.SetProperty( Toolkit::Popup::Property::ANIMATION_DURATION, DEFAULT_TOAST_TRANSITION_TIME ); - popup.SetProperty( Toolkit::Popup::Property::TAIL_VISIBILITY, false ); + popup.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_TOAST_WIDTH_OF_STAGE_RATIO); + popup.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH); + popup.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT); + popup.SetProperty(Toolkit::Popup::Property::CONTEXTUAL_MODE, Toolkit::Popup::NON_CONTEXTUAL); + popup.SetProperty(Toolkit::Popup::Property::ANIMATION_DURATION, DEFAULT_TOAST_TRANSITION_TIME); + popup.SetProperty(Toolkit::Popup::Property::TAIL_VISIBILITY, false); // Disable the dimmed backing. - popup.SetProperty( Toolkit::Popup::Property::BACKING_ENABLED, false ); + popup.SetProperty(Toolkit::Popup::Property::BACKING_ENABLED, false); // The toast popup should fade in (not zoom). - popup.SetProperty( Toolkit::Popup::Property::ANIMATION_MODE, Toolkit::Popup::FADE ); + popup.SetProperty(Toolkit::Popup::Property::ANIMATION_MODE, Toolkit::Popup::FADE); // The toast popup should auto-hide. - popup.SetProperty( Toolkit::Popup::Property::AUTO_HIDE_DELAY, DEFAULT_TOAST_AUTO_HIDE_DELAY ); + popup.SetProperty(Toolkit::Popup::Property::AUTO_HIDE_DELAY, DEFAULT_TOAST_AUTO_HIDE_DELAY); // Align to the bottom of the screen. - popup.SetProperty( Actor::Property::PARENT_ORIGIN, DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN ); - popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); + popup.SetProperty(Actor::Property::PARENT_ORIGIN, DEFAULT_TOAST_BOTTOM_PARENT_ORIGIN); + popup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER); // Let events pass through the toast popup. - popup.SetProperty( Toolkit::Popup::Property::TOUCH_TRANSPARENT, true ); + popup.SetProperty(Toolkit::Popup::Property::TOUCH_TRANSPARENT, true); return popup; } +// clang-format off // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Popup, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Popup, Toolkit::Control, Create ) // Main content related properties. -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "title", MAP, TITLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "content", MAP, CONTENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "footer", MAP, FOOTER ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "displayState", STRING, DISPLAY_STATE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "touchTransparent", BOOLEAN, TOUCH_TRANSPARENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "title", MAP, TITLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "content", MAP, CONTENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "footer", MAP, FOOTER ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "displayState", STRING, DISPLAY_STATE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "touchTransparent", BOOLEAN, TOUCH_TRANSPARENT ) // Contextual related properties. -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailVisibility", BOOLEAN, TAIL_VISIBILITY ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailPosition", VECTOR3, TAIL_POSITION ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "contextualMode", STRING, CONTEXTUAL_MODE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailVisibility", BOOLEAN, TAIL_VISIBILITY ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailPosition", VECTOR3, TAIL_POSITION ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "contextualMode", STRING, CONTEXTUAL_MODE ) // Animation related properties. -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "animationDuration", FLOAT, ANIMATION_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "animationMode", STRING, ANIMATION_MODE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "entryAnimation", MAP, ENTRY_ANIMATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "exitAnimation", MAP, EXIT_ANIMATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "autoHideDelay", INTEGER, AUTO_HIDE_DELAY ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "animationDuration", FLOAT, ANIMATION_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "animationMode", STRING, ANIMATION_MODE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "entryAnimation", MAP, ENTRY_ANIMATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "exitAnimation", MAP, EXIT_ANIMATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "autoHideDelay", INTEGER, AUTO_HIDE_DELAY ) // Style related properties. -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "backingEnabled", BOOLEAN, BACKING_ENABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "backingColor", VECTOR4, BACKING_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "popupBackgroundImage", STRING, POPUP_BACKGROUND_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "popupBackgroundBorder", RECTANGLE, POPUP_BACKGROUND_BORDER ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailUpImage", STRING, TAIL_UP_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailDownImage", STRING, TAIL_DOWN_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailLeftImage", STRING, TAIL_LEFT_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Popup, "tailRightImage", STRING, TAIL_RIGHT_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "backingEnabled", BOOLEAN, BACKING_ENABLED ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "backingColor", VECTOR4, BACKING_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "popupBackgroundImage", STRING, POPUP_BACKGROUND_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "popupBackgroundBorder", RECTANGLE, POPUP_BACKGROUND_BORDER) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailUpImage", STRING, TAIL_UP_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailDownImage", STRING, TAIL_DOWN_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailLeftImage", STRING, TAIL_LEFT_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Popup, "tailRightImage", STRING, TAIL_RIGHT_IMAGE ) // Signals. -DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "touchedOutside", SIGNAL_TOUCHED_OUTSIDE ) -DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "showing", SIGNAL_SHOWING ) -DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "shown", SIGNAL_SHOWN ) -DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "hiding", SIGNAL_HIDING ) -DALI_SIGNAL_REGISTRATION( Toolkit, Popup, "hidden", SIGNAL_HIDDEN ) +DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "touchedOutside", SIGNAL_TOUCHED_OUTSIDE) +DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "showing", SIGNAL_SHOWING ) +DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "shown", SIGNAL_SHOWN ) +DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "hiding", SIGNAL_HIDING ) +DALI_SIGNAL_REGISTRATION(Toolkit, Popup, "hidden", SIGNAL_HIDDEN ) DALI_TYPE_REGISTRATION_END() // Named type registration. // Toast Popup: Non-modal popup that displays information at the bottom of the screen. -TypeRegistration typeRegistrationToast( "PopupToast", typeid( Toolkit::Popup ), CreateToast ); +TypeRegistration typeRegistrationToast("PopupToast", typeid( Toolkit::Popup ), CreateToast); // Enumeration to / from string conversion tables -const Scripting::StringEnum DisplayStateTable[] = { - { "SHOWING", Toolkit::Popup::SHOWING }, - { "SHOWN", Toolkit::Popup::SHOWN }, - { "HIDING", Toolkit::Popup::HIDING }, - { "HIDDEN", Toolkit::Popup::HIDDEN }, -}; const unsigned int DisplayStateTableCount = sizeof( DisplayStateTable ) / sizeof( DisplayStateTable[0] ); - -const Scripting::StringEnum AnimationModeTable[] = { - { "NONE", Toolkit::Popup::NONE }, - { "ZOOM", Toolkit::Popup::ZOOM }, - { "FADE", Toolkit::Popup::FADE }, - { "CUSTOM", Toolkit::Popup::CUSTOM }, -}; const unsigned int AnimationModeTableCount = sizeof( AnimationModeTable ) / sizeof( AnimationModeTable[0] ); - -const Scripting::StringEnum ContextualModeTable[] = { - { "NON_CONTEXTUAL", Toolkit::Popup::NON_CONTEXTUAL }, - { "ABOVE", Toolkit::Popup::ABOVE }, - { "RIGHT", Toolkit::Popup::RIGHT }, - { "BELOW", Toolkit::Popup::BELOW }, - { "LEFT", Toolkit::Popup::LEFT }, -}; const unsigned int ContextualModeTableCount = sizeof( ContextualModeTable ) / sizeof( ContextualModeTable[0] ); +const Scripting::StringEnum DisplayStateTable[] = +{ + {"SHOWING", Toolkit::Popup::SHOWING}, + {"SHOWN", Toolkit::Popup::SHOWN }, + {"HIDING", Toolkit::Popup::HIDING }, + {"HIDDEN", Toolkit::Popup::HIDDEN }, +}; +const unsigned int DisplayStateTableCount = sizeof(DisplayStateTable) / sizeof(DisplayStateTable[0]); + +const Scripting::StringEnum AnimationModeTable[] = +{ + {"NONE", Toolkit::Popup::NONE }, + {"ZOOM", Toolkit::Popup::ZOOM }, + {"FADE", Toolkit::Popup::FADE }, + {"CUSTOM", Toolkit::Popup::CUSTOM}, +}; +const unsigned int AnimationModeTableCount = sizeof(AnimationModeTable) / sizeof(AnimationModeTable[0]); + +const Scripting::StringEnum ContextualModeTable[] = +{ + {"NON_CONTEXTUAL", Toolkit::Popup::NON_CONTEXTUAL}, + {"ABOVE", Toolkit::Popup::ABOVE }, + {"RIGHT", Toolkit::Popup::RIGHT }, + {"BELOW", Toolkit::Popup::BELOW }, + {"LEFT", Toolkit::Popup::LEFT }, +}; +const unsigned int ContextualModeTableCount = sizeof(ContextualModeTable) / sizeof(ContextualModeTable[0]); +// clang-format on // Popup defaults. -const Vector3 DEFAULT_POPUP_PARENT_RELATIVE_SIZE( 0.75f, 1.0f, 1.0f ); ///< Default size percentage of parent. -const float DEFAULT_POPUP_ANIMATION_DURATION = 0.6f; ///< Duration of hide/show animations. -const float POPUP_OUT_MARGIN_WIDTH = 16.f; ///< Space between the screen edge and the popup edge in the horizontal dimension. -const float POPUP_OUT_MARGIN_HEIGHT = 36.f; ///< Space between the screen edge and the popup edge in the vertical dimension. -const Vector3 DEFAULT_TAIL_POSITION( 0.5f, 1.0f, 0.0f ); ///< Position the tail will be displayed when enabled without setting the position. +const Vector3 DEFAULT_POPUP_PARENT_RELATIVE_SIZE(0.75f, 1.0f, 1.0f); ///< Default size percentage of parent. +const float DEFAULT_POPUP_ANIMATION_DURATION = 0.6f; ///< Duration of hide/show animations. +const float POPUP_OUT_MARGIN_WIDTH = 16.f; ///< Space between the screen edge and the popup edge in the horizontal dimension. +const float POPUP_OUT_MARGIN_HEIGHT = 36.f; ///< Space between the screen edge and the popup edge in the vertical dimension. +const Vector3 DEFAULT_TAIL_POSITION(0.5f, 1.0f, 0.0f); ///< Position the tail will be displayed when enabled without setting the position. // Contextual defaults. -const Vector2 DEFAULT_CONTEXTUAL_ADJACENCY_MARGIN( 10.0f, 10.0f ); ///< How close the Popup will be to it's contextual parent. -const Vector2 DEFAULT_CONTEXTUAL_STAGE_BORDER( 15.0f, 15.0f ); ///< How close the Popup can be to the stage edges. +const Vector2 DEFAULT_CONTEXTUAL_ADJACENCY_MARGIN(10.0f, 10.0f); ///< How close the Popup will be to it's contextual parent. +const Vector2 DEFAULT_CONTEXTUAL_STAGE_BORDER(15.0f, 15.0f); ///< How close the Popup can be to the stage edges. // Popup style defaults. -const char* DEFAULT_BACKGROUND_IMAGE_FILE_NAME = "00_popup_bg.9.png"; ///< Background image. -const char* DEFAULT_TAIL_UP_IMAGE_FILE_NAME = "popup_tail_up.png"; ///< Tail up image. -const char* DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME = "popup_tail_down.png"; ///< Tail down image. -const char* DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME = "popup_tail_left.png"; ///< Tail left image. -const char* DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME = "popup_tail_right.png"; ///< Tail right image. - -const Vector4 DEFAULT_BACKING_COLOR( 0.0f, 0.0f, 0.0f, 0.5f ); ///< Color of the dimmed backing. -const Rect DEFAULT_BACKGROUND_BORDER( 17, 17, 13, 13 ); ///< Default border of the background. -const Rect DEFAULT_TITLE_PADDING( 20.0f, 20.0f, 20.0f, 20.0f ); ///< Title padding used on popups with content and/or controls (from Tizen GUI UX). -const Rect DEFAULT_TITLE_ONLY_PADDING( 8.0f, 8.0f, 8.0f, 8.0f ); ///< Title padding used on popups with a title only (like toast popups). -const Vector3 FOOTER_SIZE( 620.0f, 96.0f,0.0f ); ///< Default size of the bottom control area. -const float DEFAULT_RELATIVE_PARENT_WIDTH = 0.75f; ///< If width is not fixed, relative size to parent is used by default. +const char* DEFAULT_BACKGROUND_IMAGE_FILE_NAME = "00_popup_bg.9.png"; ///< Background image. +const char* DEFAULT_TAIL_UP_IMAGE_FILE_NAME = "popup_tail_up.png"; ///< Tail up image. +const char* DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME = "popup_tail_down.png"; ///< Tail down image. +const char* DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME = "popup_tail_left.png"; ///< Tail left image. +const char* DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME = "popup_tail_right.png"; ///< Tail right image. + +const Vector4 DEFAULT_BACKING_COLOR(0.0f, 0.0f, 0.0f, 0.5f); ///< Color of the dimmed backing. +const Rect DEFAULT_BACKGROUND_BORDER(17, 17, 13, 13); ///< Default border of the background. +const Rect DEFAULT_TITLE_PADDING(20.0f, 20.0f, 20.0f, 20.0f); ///< Title padding used on popups with content and/or controls (from Tizen GUI UX). +const Rect DEFAULT_TITLE_ONLY_PADDING(8.0f, 8.0f, 8.0f, 8.0f); ///< Title padding used on popups with a title only (like toast popups). +const Vector3 FOOTER_SIZE(620.0f, 96.0f, 0.0f); ///< Default size of the bottom control area. +const float DEFAULT_RELATIVE_PARENT_WIDTH = 0.75f; ///< If width is not fixed, relative size to parent is used by default. } // Unnamed namespace @@ -213,10 +215,10 @@ const float DEFAULT_RELATIVE_PARENT_WIDTH = 0.75f; Dali::Toolkit::Popup Popup::New() { // Create the implementation - PopupPtr popup( new Popup() ); + PopupPtr popup(new Popup()); // Pass ownership to CustomActor via derived handle. - Dali::Toolkit::Popup handle( *popup ); + Dali::Toolkit::Popup handle(*popup); // Second-phase initialisation of the implementation. // This can only be done after the CustomActor connection has been made. @@ -226,7 +228,7 @@ Dali::Toolkit::Popup Popup::New() } Popup::Popup() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mTouchedOutsideSignal(), mShowingSignal(), mShownSignal(), @@ -239,111 +241,110 @@ Popup::Popup() mTailImage(), mPopupContainer(), mAnimation(), - mAlterAddedChild( false ), - mLayoutDirty( true ), + mAlterAddedChild(false), + mLayoutDirty(true), mAutoHideTimer(), - mTouchTransparent( false ), + mTouchTransparent(false), mTitle(), mContent(), mFooter(), - mDisplayState( Toolkit::Popup::HIDDEN ), // Hidden until shown with SetDisplayState() - mTailVisible( false ), - mTailPosition( DEFAULT_TAIL_POSITION ), - mContextualMode( Toolkit::Popup::NON_CONTEXTUAL ), - mAnimationDuration( DEFAULT_POPUP_ANIMATION_DURATION ), - mAnimationMode( Toolkit::Popup::FADE ), + mDisplayState(Toolkit::Popup::HIDDEN), // Hidden until shown with SetDisplayState() + mTailVisible(false), + mTailPosition(DEFAULT_TAIL_POSITION), + mContextualMode(Toolkit::Popup::NON_CONTEXTUAL), + mAnimationDuration(DEFAULT_POPUP_ANIMATION_DURATION), + mAnimationMode(Toolkit::Popup::FADE), mEntryAnimationData(), mExitAnimationData(), - mAutoHideDelay( 0 ), - mBackingEnabled( true ), - mBackingColor( DEFAULT_BACKING_COLOR ), + mAutoHideDelay(0), + mBackingEnabled(true), + mBackingColor(DEFAULT_BACKING_COLOR), mPopupBackgroundImage(), - mBackgroundBorder( DEFAULT_BACKGROUND_BORDER ), + mBackgroundBorder(DEFAULT_BACKGROUND_BORDER), mMargin(), mTailUpImage(), mTailDownImage(), mTailLeftImage(), mTailRightImage() { - SetKeyboardNavigationSupport( true ); + SetKeyboardNavigationSupport(true); const std::string imageDirPath = AssetManager::GetDaliImagePath(); - mTailUpImage = imageDirPath + DEFAULT_TAIL_UP_IMAGE_FILE_NAME; - mTailDownImage = imageDirPath + DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME; - mTailLeftImage = imageDirPath + DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME; - mTailRightImage = imageDirPath + DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME; + mTailUpImage = imageDirPath + DEFAULT_TAIL_UP_IMAGE_FILE_NAME; + mTailDownImage = imageDirPath + DEFAULT_TAIL_DOWN_IMAGE_FILE_NAME; + mTailLeftImage = imageDirPath + DEFAULT_TAIL_LEFT_IMAGE_FILE_NAME; + mTailRightImage = imageDirPath + DEFAULT_TAIL_RIGHT_IMAGE_FILE_NAME; } void Popup::OnInitialize() { Actor self = Self(); - self.SetProperty( Dali::Actor::Property::NAME, "popup" ); + self.SetProperty(Dali::Actor::Property::NAME, "popup"); // Apply some default resizing rules. - self.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - self.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + self.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + self.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); - self.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_POPUP_PARENT_RELATIVE_SIZE ); - self.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH ); - self.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT ); + self.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_POPUP_PARENT_RELATIVE_SIZE); + self.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::WIDTH); + self.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT); // Create a new layer so all Popup components can appear above all other actors. mLayer = Layer::New(); - mLayer.SetProperty( Dali::Actor::Property::NAME, "popupLayer" ); + mLayer.SetProperty(Dali::Actor::Property::NAME, "popupLayer"); - mLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mLayer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mLayer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mLayer.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); // Important to set as invisible as otherwise, if the popup is parented, // but not shown yet it will appear statically on the screen. - mLayer.SetProperty( Actor::Property::VISIBLE, false ); + mLayer.SetProperty(Actor::Property::VISIBLE, false); // Add the layer to the hierarchy. - self.Add( mLayer ); + self.Add(mLayer); // Add Backing (Dimmed effect). mBacking = CreateBacking(); - mLayer.Add( mBacking ); + mLayer.Add(mBacking); mPopupContainer = Actor::New(); - mPopupContainer.SetProperty( Dali::Actor::Property::NAME, "popupContainer" ); - mPopupContainer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mPopupContainer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mPopupContainer.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS ); - mLayer.Add( mPopupContainer ); + mPopupContainer.SetProperty(Dali::Actor::Property::NAME, "popupContainer"); + mPopupContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mPopupContainer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mPopupContainer.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS); + mLayer.Add(mPopupContainer); // Create the Popup layout to contain all main content. - mPopupLayout = Toolkit::TableView::New( 3, 1 ); + mPopupLayout = Toolkit::TableView::New(3, 1); // Adds the default background image. const std::string imageDirPath = AssetManager::GetDaliImagePath(); - SetPopupBackgroundImage( Toolkit::ImageView::New( imageDirPath + DEFAULT_BACKGROUND_IMAGE_FILE_NAME ) ); + SetPopupBackgroundImage(Toolkit::ImageView::New(imageDirPath + DEFAULT_BACKGROUND_IMAGE_FILE_NAME)); - mPopupLayout.SetProperty( Dali::Actor::Property::NAME, "popupLayoutTable" ); - mPopupLayout.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mPopupLayout.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + mPopupLayout.SetProperty(Dali::Actor::Property::NAME, "popupLayoutTable"); + mPopupLayout.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mPopupLayout.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); - mPopupLayout.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH ); - mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT ); - mPopupLayout.SetProperty( Actor::Property::SIZE, Vector2( Stage::GetCurrent().GetSize().x * DEFAULT_RELATIVE_PARENT_WIDTH, 0.0f ) ); + mPopupLayout.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH); + mPopupLayout.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT); + mPopupLayout.SetProperty(Actor::Property::SIZE, Vector2(Stage::GetCurrent().GetSize().x * DEFAULT_RELATIVE_PARENT_WIDTH, 0.0f)); - mPopupLayout.SetFitHeight( 0 ); // Set row to fit. - mPopupLayout.SetFitHeight( 1 ); // Set row to fit. + mPopupLayout.SetFitHeight(0); // Set row to fit. + mPopupLayout.SetFitHeight(1); // Set row to fit. - mPopupContainer.Add( mPopupLayout ); + mPopupContainer.Add(mPopupLayout); // Any content after this point which is added to Self() will be re-parented to mContent. mAlterAddedChild = true; - SetAsKeyboardFocusGroup( true ); + SetAsKeyboardFocusGroup(true); SetupTouch(); DevelControl::AppendAccessibilityAttribute(self, "sub-role", "Alert"); - DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) - { + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { return std::unique_ptr(new AccessibleImpl(actor, Dali::Accessibility::Role::DIALOG, true)); }); } @@ -357,19 +358,19 @@ Popup::~Popup() void Popup::LayoutAnimation() { // Perform setup based on the currently selected animation. - switch( mAnimationMode ) + switch(mAnimationMode) { case Toolkit::Popup::ZOOM: { // Zoom animations start fully zoomed out. - mPopupContainer.SetProperty( Actor::Property::SCALE, Vector3::ZERO ); + mPopupContainer.SetProperty(Actor::Property::SCALE, Vector3::ZERO); break; } case Toolkit::Popup::FADE: { // Fade animations start transparent. - mPopupContainer.SetProperty( Actor::Property::OPACITY, 0.0f ); + mPopupContainer.SetProperty(Actor::Property::OPACITY, 0.0f); break; } @@ -377,7 +378,7 @@ void Popup::LayoutAnimation() { // Initialise the custom animation by playing to the end of it's exit animation instantly. // EG. If it was zooming in, then we zoom out fully instantly so the zoom in works. - StartTransitionAnimation( false, true ); + StartTransitionAnimation(false, true); break; } @@ -388,10 +389,10 @@ void Popup::LayoutAnimation() } } -void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* false */ ) +void Popup::StartTransitionAnimation(bool transitionIn, bool instantaneous /* false */) { // Stop and recreate animation. - if ( mAnimation ) + if(mAnimation) { mAnimation.Stop(); mAnimation.Clear(); @@ -401,9 +402,9 @@ void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* f // Setup variables ready to start the animations. // If we are performing the animation instantaneously, we do not want to emit a signal. - if( !instantaneous ) + if(!instantaneous) { - if( transitionIn ) + if(transitionIn) { // Setup variables and signal that we are starting the transition. // Note: We signal even if the transition is instant so signal order is consistent. @@ -416,55 +417,55 @@ void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* f } // Perform chosen animation for the Popup. - switch( mAnimationMode ) + switch(mAnimationMode) { case Toolkit::Popup::NONE: { - mAnimation = Animation::New( 0.0f ); + mAnimation = Animation::New(0.0f); break; } case Toolkit::Popup::ZOOM: { - mAnimation = Animation::New( duration ); - if( duration > Math::MACHINE_EPSILON_0 ) + mAnimation = Animation::New(duration); + if(duration > Math::MACHINE_EPSILON_0) { - if( transitionIn ) + if(transitionIn) { - mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::SCALE ), Vector3::ONE, AlphaFunction::EASE_IN_OUT, TimePeriod( duration * 0.25f, duration * 0.75f ) ); + mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::SCALE), Vector3::ONE, AlphaFunction::EASE_IN_OUT, TimePeriod(duration * 0.25f, duration * 0.75f)); } else { // Zoom out animation is twice the speed. Modify the duration variable so the backing animation speed is modified also. duration /= 2.0f; - mAnimation.SetDuration( duration ); - mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::SCALE ), Vector3::ZERO, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.0f, duration ) ); + mAnimation.SetDuration(duration); + mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::SCALE), Vector3::ZERO, AlphaFunction::EASE_IN_OUT, TimePeriod(0.0f, duration)); } } else { - mPopupContainer.SetProperty( Actor::Property::SCALE, transitionIn ? Vector3::ONE : Vector3::ZERO ); + mPopupContainer.SetProperty(Actor::Property::SCALE, transitionIn ? Vector3::ONE : Vector3::ZERO); } break; } case Toolkit::Popup::FADE: { - mAnimation = Animation::New( duration ); - if( duration > Math::MACHINE_EPSILON_0 ) + mAnimation = Animation::New(duration); + if(duration > Math::MACHINE_EPSILON_0) { - if( transitionIn ) + if(transitionIn) { - mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::COLOR_ALPHA ), 1.0f, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.30f, duration * 0.70f ) ); + mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::COLOR_ALPHA), 1.0f, AlphaFunction::EASE_IN_OUT, TimePeriod(0.30f, duration * 0.70f)); } else { - mAnimation.AnimateTo( Property( mPopupContainer, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.0f, duration * 0.70f ) ); + mAnimation.AnimateTo(Property(mPopupContainer, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod(0.0f, duration * 0.70f)); } } else { - mPopupContainer.SetProperty( Actor::Property::OPACITY, transitionIn ? 1.0f : 0.0f ); + mPopupContainer.SetProperty(Actor::Property::OPACITY, transitionIn ? 1.0f : 0.0f); } break; } @@ -478,13 +479,13 @@ void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* f // Create a new animation from the pre-defined data in the AnimationData class. // If there is no data, mAnimation is invalidated. - mAnimation = animationData->CreateAnimation( mPopupContainer, duration ); + mAnimation = animationData->CreateAnimation(mPopupContainer, duration); // If we don't have a valid animation, provide a blank one so play() can still function generically. - if( !mAnimation ) + if(!mAnimation) { // No animation was configured (even though custom mode was specified). Create a dummy animation to avoid an exception. - mAnimation = Animation::New( 0.0f ); + mAnimation = Animation::New(0.0f); } break; @@ -493,37 +494,37 @@ void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* f // Animate the backing, if enabled. // This is set up last so that different animation modes can have an effect on the backing animation speed. - if( mBackingEnabled ) + if(mBackingEnabled) { // Use the alpha from the user-specified color. float targetAlpha = mBackingColor.a; - if( duration > Math::MACHINE_EPSILON_0 ) + if(duration > Math::MACHINE_EPSILON_0) { - if( transitionIn ) + if(transitionIn) { - mAnimation.AnimateTo( Property( mBacking, Actor::Property::COLOR_ALPHA ), targetAlpha, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.0f, duration * 0.70f ) ); + mAnimation.AnimateTo(Property(mBacking, Actor::Property::COLOR_ALPHA), targetAlpha, AlphaFunction::EASE_IN_OUT, TimePeriod(0.0f, duration * 0.70f)); } else { - mAnimation.AnimateTo( Property( mBacking, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod( 0.30f, duration * 0.70f ) ); + mAnimation.AnimateTo(Property(mBacking, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN_OUT, TimePeriod(0.30f, duration * 0.70f)); } } else { - mBacking.SetProperty( Actor::Property::COLOR_ALPHA, transitionIn ? targetAlpha : 0.0f ); + mBacking.SetProperty(Actor::Property::COLOR_ALPHA, transitionIn ? targetAlpha : 0.0f); } } // If we are performing the animation instantaneously, jump to the position directly and do not signal. - if( instantaneous ) + if(instantaneous) { - mAnimation.SetCurrentProgress( 1.0f ); + mAnimation.SetCurrentProgress(1.0f); mAnimation.Play(); } - else if( duration > Math::MACHINE_EPSILON_0 ) + else if(duration > Math::MACHINE_EPSILON_0) { // Run the animation. - mAnimation.FinishedSignal().Connect( this, &Popup::OnDisplayChangeAnimationFinished ); + mAnimation.FinishedSignal().Connect(this, &Popup::OnDisplayChangeAnimationFinished); mAnimation.Play(); } else @@ -534,7 +535,7 @@ void Popup::StartTransitionAnimation( bool transitionIn, bool instantaneous /* f } } -void Popup::OnDisplayChangeAnimationFinished( Animation& source ) +void Popup::OnDisplayChangeAnimationFinished(Animation& source) { DisplayStateChangeComplete(); } @@ -542,28 +543,28 @@ void Popup::OnDisplayChangeAnimationFinished( Animation& source ) void Popup::DisplayStateChangeComplete() { // Remove contents from stage if completely hidden. - if( mDisplayState == Toolkit::Popup::HIDING ) + if(mDisplayState == Toolkit::Popup::HIDING) { mDisplayState = Toolkit::Popup::HIDDEN; - mLayer.SetProperty( Actor::Property::VISIBLE, false ); - mPopupLayout.SetProperty( Actor::Property::SENSITIVE, false ); + mLayer.SetProperty(Actor::Property::VISIBLE, false); + mPopupLayout.SetProperty(Actor::Property::SENSITIVE, false); // Guard against destruction during signal emission. - Toolkit::Popup handle( GetOwner() ); + Toolkit::Popup handle(GetOwner()); mHiddenSignal.Emit(); } - else if( mDisplayState == Toolkit::Popup::SHOWING ) + else if(mDisplayState == Toolkit::Popup::SHOWING) { mDisplayState = Toolkit::Popup::SHOWN; - Toolkit::Popup handle( GetOwner() ); + Toolkit::Popup handle(GetOwner()); mShownSignal.Emit(); // Start a timer to auto-hide if enabled. - if( mAutoHideDelay > 0u ) + if(mAutoHideDelay > 0u) { - mAutoHideTimer = Timer::New( mAutoHideDelay ); - mAutoHideTimer.TickSignal().Connect( this, &Popup::OnAutoHideTimeReached ); + mAutoHideTimer = Timer::New(mAutoHideDelay); + mAutoHideTimer.TickSignal().Connect(this, &Popup::OnAutoHideTimeReached); mAutoHideTimer.Start(); } } @@ -571,28 +572,28 @@ void Popup::DisplayStateChangeComplete() bool Popup::OnAutoHideTimeReached() { - if (!Dali::Accessibility::IsUp() || true) // TODO: remove 'true' in sync with EFL (UX change) + if(!Dali::Accessibility::IsUp() || true) // TODO: remove 'true' in sync with EFL (UX change) { // Display timer has expired, auto hide the popup exactly as if the user had clicked outside. - SetDisplayState( Toolkit::Popup::HIDDEN ); + SetDisplayState(Toolkit::Popup::HIDDEN); } - if( mAutoHideTimer ) + if(mAutoHideTimer) { mAutoHideTimer.Stop(); - mAutoHideTimer.TickSignal().Disconnect( this, &Popup::OnAutoHideTimeReached ); + mAutoHideTimer.TickSignal().Disconnect(this, &Popup::OnAutoHideTimeReached); mAutoHideTimer.Reset(); } return true; } -void Popup::SetPopupBackgroundImage( Actor image ) +void Popup::SetPopupBackgroundImage(Actor image) { // Removes any previous background. - if( mPopupBackgroundImage ) + if(mPopupBackgroundImage) { mPopupBackgroundImage.Unparent(); - if( mTailImage ) + if(mTailImage) { mTailImage.Unparent(); } @@ -600,22 +601,22 @@ void Popup::SetPopupBackgroundImage( Actor image ) // Adds new background to the dialog. mPopupBackgroundImage = image; - mPopupBackgroundImage.SetProperty( Dali::Actor::Property::NAME, "popupBackgroundImage" ); - mPopupBackgroundImage.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mPopupBackgroundImage.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mPopupBackgroundImage.SetProperty(Dali::Actor::Property::NAME, "popupBackgroundImage"); + mPopupBackgroundImage.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mPopupBackgroundImage.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // Set the popup border to be slightly larger than the layout contents. UpdateBackgroundPositionAndSize(); const bool prevAlter = mAlterAddedChild; - mAlterAddedChild = false; - mPopupContainer.Add( mPopupBackgroundImage ); + mAlterAddedChild = false; + mPopupContainer.Add(mPopupBackgroundImage); mPopupBackgroundImage.LowerToBottom(); mAlterAddedChild = prevAlter; - if( mTailImage ) + if(mTailImage) { - mPopupBackgroundImage.Add( mTailImage ); + mPopupBackgroundImage.Add(mTailImage); } mLayoutDirty = true; @@ -626,27 +627,27 @@ Actor Popup::GetPopupBackgroundImage() const return mPopupBackgroundImage; } -void Popup::SetTitle( Actor titleActor ) +void Popup::SetTitle(Actor titleActor) { // Replaces the current title actor. - if( !mPopupLayout ) + if(!mPopupLayout) { return; } - if( mTitle ) + if(mTitle) { - mPopupLayout.RemoveChildAt( Toolkit::TableView::CellPosition( 0, 0) ); + mPopupLayout.RemoveChildAt(Toolkit::TableView::CellPosition(0, 0)); } mTitle = titleActor; - if( mTitle ) + if(mTitle) { // Set up padding to give sensible default behaviour // (an application developer can later override this if they wish). - mTitle.SetProperty( Actor::Property::PADDING, DEFAULT_TITLE_PADDING ); + mTitle.SetProperty(Actor::Property::PADDING, DEFAULT_TITLE_PADDING); - mPopupLayout.AddChild( mTitle, Toolkit::TableView::CellPosition( 0, 0 ) ); + mPopupLayout.AddChild(mTitle, Toolkit::TableView::CellPosition(0, 0)); } mLayoutDirty = true; @@ -658,21 +659,21 @@ Actor Popup::GetTitle() const return mTitle; } -void Popup::SetContent( Actor content ) +void Popup::SetContent(Actor content) { // Remove previous content actor. - if( mPopupLayout ) + if(mPopupLayout) { - mPopupLayout.RemoveChildAt( Toolkit::TableView::CellPosition( 1, 0 ) ); + mPopupLayout.RemoveChildAt(Toolkit::TableView::CellPosition(1, 0)); } - // Keep a handle to the new content. + // Keep a handle to the new content. mContent = content; - if( mContent ) + if(mContent) { - mContent.SetProperty( Dali::Actor::Property::NAME, "popupContent" ); + mContent.SetProperty(Dali::Actor::Property::NAME, "popupContent"); - mPopupLayout.AddChild( mContent, Toolkit::TableView::CellPosition( 1, 0 ) ); + mPopupLayout.AddChild(mContent, Toolkit::TableView::CellPosition(1, 0)); } mLayoutDirty = true; @@ -684,24 +685,24 @@ Actor Popup::GetContent() const return mContent; } -void Popup::SetFooter( Actor footer ) +void Popup::SetFooter(Actor footer) { // Remove previous content actor. - if( mPopupLayout ) + if(mPopupLayout) { - mPopupLayout.RemoveChildAt( Toolkit::TableView::CellPosition( 2, 0 ) ); + mPopupLayout.RemoveChildAt(Toolkit::TableView::CellPosition(2, 0)); } // Keep a handle to the new content. mFooter = footer; - if( mFooter ) + if(mFooter) { - mFooter.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); + mFooter.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH); // The control container has a fixed height. - mPopupLayout.SetFitHeight( 2u ); - mPopupLayout.AddChild( footer, Toolkit::TableView::CellPosition( 2, 0 ) ); + mPopupLayout.SetFitHeight(2u); + mPopupLayout.AddChild(footer, Toolkit::TableView::CellPosition(2, 0)); } mLayoutDirty = true; @@ -713,19 +714,19 @@ Actor Popup::GetFooter() const return mFooter; } -void Popup::SetDisplayState( Toolkit::Popup::DisplayState displayState ) +void Popup::SetDisplayState(Toolkit::Popup::DisplayState displayState) { // Convert the 4-way state to a bool, true for show, false for hide. - bool display = ( displayState == Toolkit::Popup::SHOWING ) || ( displayState == Toolkit::Popup::SHOWN ); + bool display = (displayState == Toolkit::Popup::SHOWING) || (displayState == Toolkit::Popup::SHOWN); // Ignore if we are already at the target display state. - if( display == ( ( mDisplayState == Toolkit::Popup::SHOWING ) || ( mDisplayState == Toolkit::Popup::SHOWN ) ) ) + if(display == ((mDisplayState == Toolkit::Popup::SHOWING) || (mDisplayState == Toolkit::Popup::SHOWN))) { return; } - auto *accessible = Dali::Accessibility::Accessible::Get(Self()); - if (display) + auto* accessible = Dali::Accessibility::Accessible::Get(Self()); + if(display) { Dali::Accessibility::Bridge::GetCurrentBridge()->AddPopup(accessible); accessible->EmitStateChanged(Dali::Accessibility::State::SHOWING, 1, 0); @@ -739,7 +740,7 @@ void Popup::SetDisplayState( Toolkit::Popup::DisplayState displayState ) // Convert the bool state to the actual display state to use. mDisplayState = display ? Toolkit::Popup::SHOWING : Toolkit::Popup::HIDING; - if ( display ) + if(display) { // Update the state to indicate the current intent. mDisplayState = Toolkit::Popup::SHOWING; @@ -749,46 +750,46 @@ void Popup::SetDisplayState( Toolkit::Popup::DisplayState displayState ) // We are displaying so bring the popup layer to the front, and set it visible so it is rendered. mLayer.RaiseToTop(); - mLayer.SetProperty( Actor::Property::VISIBLE, true ); + mLayer.SetProperty(Actor::Property::VISIBLE, true); // Set up the layout if this is the first display or the layout has become dirty. - if( mLayoutDirty ) + if(mLayoutDirty) { // Bake-in any style and layout options to create the Popup layout. LayoutPopup(); } // Allow the popup to catch events. - mPopupLayout.SetProperty( Actor::Property::SENSITIVE, true ); + mPopupLayout.SetProperty(Actor::Property::SENSITIVE, true); // Handle the keyboard focus when popup is shown. Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get(); - if( keyboardFocusManager ) + if(keyboardFocusManager) { mPreviousFocusedActor = keyboardFocusManager.GetCurrentFocusActor(); - if( Self().GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + if(Self().GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // Setup the actgor to start focus from. Actor focusActor; - if( mContent && mContent.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + if(mContent && mContent.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // If the content is focusable, move the focus to the content. focusActor = mContent; } - else if( mFooter && mFooter.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + else if(mFooter && mFooter.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // If the footer is focusable, move the focus to the footer. focusActor = mFooter; } else { - DALI_LOG_WARNING( "There is no focusable in popup\n" ); + DALI_LOG_WARNING("There is no focusable in popup\n"); } - if( focusActor ) + if(focusActor) { - keyboardFocusManager.SetCurrentFocusActor( focusActor ); + keyboardFocusManager.SetCurrentFocusActor(focusActor); } } } @@ -799,18 +800,18 @@ void Popup::SetDisplayState( Toolkit::Popup::DisplayState displayState ) ClearKeyInputFocus(); // Restore the keyboard focus when popup is hidden. - if( mPreviousFocusedActor && mPreviousFocusedActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + if(mPreviousFocusedActor && mPreviousFocusedActor.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { Dali::Toolkit::KeyboardFocusManager keyboardFocusManager = Dali::Toolkit::KeyboardFocusManager::Get(); - if( keyboardFocusManager ) + if(keyboardFocusManager) { - keyboardFocusManager.SetCurrentFocusActor( mPreviousFocusedActor ); + keyboardFocusManager.SetCurrentFocusActor(mPreviousFocusedActor); } } } // Perform animation. - StartTransitionAnimation( display ); + StartTransitionAnimation(display); } Toolkit::Popup::DisplayState Popup::GetDisplayState() const @@ -835,19 +836,19 @@ void Popup::LayoutPopup() * | |```` * | | */ - mPopupContainer.SetProperty( Actor::Property::PARENT_ORIGIN, Self().GetCurrentProperty< Vector3 >( Actor::Property::PARENT_ORIGIN ) ); - mPopupContainer.SetProperty( Actor::Property::ANCHOR_POINT, Self().GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) ); + mPopupContainer.SetProperty(Actor::Property::PARENT_ORIGIN, Self().GetCurrentProperty(Actor::Property::PARENT_ORIGIN)); + mPopupContainer.SetProperty(Actor::Property::ANCHOR_POINT, Self().GetCurrentProperty(Actor::Property::ANCHOR_POINT)); // If there is only a title, use less padding. - if( mTitle ) + if(mTitle) { - if( !mContent && !mFooter ) + if(!mContent && !mFooter) { - mTitle.SetProperty( Actor::Property::PADDING, DEFAULT_TITLE_ONLY_PADDING ); + mTitle.SetProperty(Actor::Property::PADDING, DEFAULT_TITLE_ONLY_PADDING); } else { - mTitle.SetProperty( Actor::Property::PADDING, DEFAULT_TITLE_PADDING ); + mTitle.SetProperty(Actor::Property::PADDING, DEFAULT_TITLE_PADDING); } } @@ -855,7 +856,7 @@ void Popup::LayoutPopup() OnLayoutSetup(); // Update background visibility. - mPopupContainer.SetProperty( Actor::Property::VISIBLE, !( !mFooter && mPopupLayout.GetChildCount() == 0 ) ); + mPopupContainer.SetProperty(Actor::Property::VISIBLE, !(!mFooter && mPopupLayout.GetChildCount() == 0)); // Create / destroy / position the tail as needed. LayoutTail(); @@ -869,68 +870,68 @@ void Popup::LayoutPopup() void Popup::LayoutTail() { // Removes the tail actor. - if( mTailImage && mTailImage.GetParent() ) + if(mTailImage && mTailImage.GetParent()) { - mTailImage.GetParent().Remove( mTailImage ); + mTailImage.GetParent().Remove(mTailImage); mTailImage.Reset(); } - if( !mTailVisible ) + if(!mTailVisible) { return; } const Vector3& parentOrigin = GetTailPosition(); - Vector3 position; - std::string image; - Vector3 anchorPoint; + Vector3 position; + std::string image; + Vector3 anchorPoint; // depending on position of tail around ParentOrigin, a different tail image is used... - if( parentOrigin.y < Math::MACHINE_EPSILON_1 ) + if(parentOrigin.y < Math::MACHINE_EPSILON_1) { - image = mTailUpImage; + image = mTailUpImage; anchorPoint = AnchorPoint::BOTTOM_CENTER; - position.y = mBackgroundBorder.top; + position.y = mBackgroundBorder.top; } - else if( parentOrigin.y > ( 1.0f - Math::MACHINE_EPSILON_1 ) ) + else if(parentOrigin.y > (1.0f - Math::MACHINE_EPSILON_1)) { - image = mTailDownImage; + image = mTailDownImage; anchorPoint = AnchorPoint::TOP_CENTER; - position.y = - mBackgroundBorder.bottom; + position.y = -mBackgroundBorder.bottom; } - else if( parentOrigin.x < Math::MACHINE_EPSILON_1 ) + else if(parentOrigin.x < Math::MACHINE_EPSILON_1) { - image = mTailLeftImage; + image = mTailLeftImage; anchorPoint = AnchorPoint::CENTER_RIGHT; - position.x = mBackgroundBorder.left; + position.x = mBackgroundBorder.left; } - else if( parentOrigin.x > ( 1.0f - Math::MACHINE_EPSILON_1 ) ) + else if(parentOrigin.x > (1.0f - Math::MACHINE_EPSILON_1)) { - image = mTailRightImage; + image = mTailRightImage; anchorPoint = AnchorPoint::CENTER_LEFT; - position.x = - mBackgroundBorder.right; + position.x = -mBackgroundBorder.right; } - if( !image.empty() ) + if(!image.empty()) { // Adds the tail actor. - mTailImage = Toolkit::ImageView::New( image ); - mTailImage.SetProperty( Dali::Actor::Property::NAME, "tailImage" ); - mTailImage.SetProperty( Actor::Property::PARENT_ORIGIN, parentOrigin ); - mTailImage.SetProperty( Actor::Property::ANCHOR_POINT, anchorPoint ); - mTailImage.SetProperty( Actor::Property::POSITION, position ); + mTailImage = Toolkit::ImageView::New(image); + mTailImage.SetProperty(Dali::Actor::Property::NAME, "tailImage"); + mTailImage.SetProperty(Actor::Property::PARENT_ORIGIN, parentOrigin); + mTailImage.SetProperty(Actor::Property::ANCHOR_POINT, anchorPoint); + mTailImage.SetProperty(Actor::Property::POSITION, position); - if( mPopupBackgroundImage ) + if(mPopupBackgroundImage) { - mPopupBackgroundImage.Add( mTailImage ); + mPopupBackgroundImage.Add(mTailImage); } } } -void Popup::SetContextualMode( Toolkit::Popup::ContextualMode mode ) +void Popup::SetContextualMode(Toolkit::Popup::ContextualMode mode) { mContextualMode = mode; - mLayoutDirty = true; + mLayoutDirty = true; } Toolkit::Popup::ContextualMode Popup::GetContextualMode() const @@ -941,24 +942,23 @@ Toolkit::Popup::ContextualMode Popup::GetContextualMode() const Toolkit::Control Popup::CreateBacking() { Toolkit::Control backing = Control::New(); - backing.SetProperty( Toolkit::Control::Property::BACKGROUND, - Property::Map().Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR ) - .Add( Toolkit::ColorVisual::Property::MIX_COLOR, Vector4( mBackingColor.r, mBackingColor.g, mBackingColor.b, 1.0f ) ) ); - backing.SetProperty( Dali::Actor::Property::NAME, "popupBacking" ); + backing.SetProperty(Toolkit::Control::Property::BACKGROUND, + Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(Toolkit::ColorVisual::Property::MIX_COLOR, Vector4(mBackingColor.r, mBackingColor.g, mBackingColor.b, 1.0f))); + backing.SetProperty(Dali::Actor::Property::NAME, "popupBacking"); // Must always be positioned top-left of stage, regardless of parent. - backing.SetProperty( Actor::Property::INHERIT_POSITION, false ); + backing.SetProperty(Actor::Property::INHERIT_POSITION, false); // Always the full size of the stage. - backing.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); - backing.SetProperty( Actor::Property::SIZE, Stage::GetCurrent().GetSize() ); + backing.SetResizePolicy(ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS); + backing.SetProperty(Actor::Property::SIZE, Stage::GetCurrent().GetSize()); // Catch events. - backing.SetProperty( Actor::Property::SENSITIVE, true ); + backing.SetProperty(Actor::Property::SENSITIVE, true); // Default to being transparent. - backing.SetProperty( Actor::Property::COLOR_ALPHA, 0.0f ); - backing.WheelEventSignal().Connect( this, &Popup::OnBackingWheelEvent ); + backing.SetProperty(Actor::Property::COLOR_ALPHA, 0.0f); + backing.WheelEventSignal().Connect(this, &Popup::OnBackingWheelEvent); return backing; } @@ -987,7 +987,7 @@ Toolkit::Popup::DisplayStateChangeSignalType& Popup::HiddenSignal() return mHiddenSignal; } -void Popup::SetTailVisibility( bool visible ) +void Popup::SetTailVisibility(bool visible) { mTailVisible = visible; mLayoutDirty = true; @@ -998,10 +998,10 @@ const bool Popup::IsTailVisible() const return mTailVisible; } -void Popup::SetTailPosition( Vector3 position ) +void Popup::SetTailPosition(Vector3 position) { mTailPosition = position; - mLayoutDirty = true; + mLayoutDirty = true; } const Vector3& Popup::GetTailPosition() const @@ -1009,10 +1009,10 @@ const Vector3& Popup::GetTailPosition() const return mTailPosition; } -void Popup::SetAnimationDuration( float duration ) +void Popup::SetAnimationDuration(float duration) { mAnimationDuration = duration; - mLayoutDirty = true; + mLayoutDirty = true; } float Popup::GetAnimationDuration() const @@ -1020,10 +1020,10 @@ float Popup::GetAnimationDuration() const return mAnimationDuration; } -void Popup::SetAnimationMode( Toolkit::Popup::AnimationMode animationMode ) +void Popup::SetAnimationMode(Toolkit::Popup::AnimationMode animationMode) { mAnimationMode = animationMode; - mLayoutDirty = true; + mLayoutDirty = true; } Toolkit::Popup::AnimationMode Popup::GetAnimationMode() const @@ -1031,31 +1031,31 @@ Toolkit::Popup::AnimationMode Popup::GetAnimationMode() const return mAnimationMode; } -void Popup::SetEntryAnimationData( const Property::Map& map ) +void Popup::SetEntryAnimationData(const Property::Map& map) { mEntryAnimationData.Clear(); - Scripting::NewAnimation( map, mEntryAnimationData ); + Scripting::NewAnimation(map, mEntryAnimationData); } -void Popup::SetExitAnimationData( const Property::Map& map ) +void Popup::SetExitAnimationData(const Property::Map& map) { mExitAnimationData.Clear(); - Scripting::NewAnimation( map, mExitAnimationData ); + Scripting::NewAnimation(map, mExitAnimationData); } void Popup::UpdateBackgroundPositionAndSize() { - if( mPopupBackgroundImage ) + if(mPopupBackgroundImage) { - mPopupBackgroundImage.SetResizePolicy( ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS ); - mPopupBackgroundImage.SetProperty( Actor::Property::SIZE_MODE_FACTOR, Vector3( mBackgroundBorder.left + mBackgroundBorder.right, mBackgroundBorder.top + mBackgroundBorder.bottom, 0.0f ) ); + mPopupBackgroundImage.SetResizePolicy(ResizePolicy::SIZE_FIXED_OFFSET_FROM_PARENT, Dimension::ALL_DIMENSIONS); + mPopupBackgroundImage.SetProperty(Actor::Property::SIZE_MODE_FACTOR, Vector3(mBackgroundBorder.left + mBackgroundBorder.right, mBackgroundBorder.top + mBackgroundBorder.bottom, 0.0f)); // Adjust the position of the background so the transparent areas are set appropriately - mPopupBackgroundImage.SetProperty( Actor::Property::POSITION, Vector2( ( mBackgroundBorder.right - mBackgroundBorder.left ) * 0.5f, ( mBackgroundBorder.bottom - mBackgroundBorder.top ) * 0.5f )); + mPopupBackgroundImage.SetProperty(Actor::Property::POSITION, Vector2((mBackgroundBorder.right - mBackgroundBorder.left) * 0.5f, (mBackgroundBorder.bottom - mBackgroundBorder.top) * 0.5f)); } } -void Popup::SetAutoHideDelay( int delay ) +void Popup::SetAutoHideDelay(int delay) { mAutoHideDelay = delay; } @@ -1065,10 +1065,10 @@ int Popup::GetAutoHideDelay() const return mAutoHideDelay; } -void Popup::SetBackingEnabled( bool enabled ) +void Popup::SetBackingEnabled(bool enabled) { mBackingEnabled = enabled; - mLayoutDirty = true; + mLayoutDirty = true; } const bool Popup::IsBackingEnabled() const @@ -1076,10 +1076,10 @@ const bool Popup::IsBackingEnabled() const return mBackingEnabled; } -void Popup::SetBackingColor( Vector4 color ) +void Popup::SetBackingColor(Vector4 color) { mBackingColor = color; - mBacking.SetBackgroundColor( Vector4( color.r, color.g, color.b, 1.0f ) ); + mBacking.SetBackgroundColor(Vector4(color.r, color.g, color.b, 1.0f)); mLayoutDirty = true; } @@ -1088,7 +1088,7 @@ const Vector4& Popup::GetBackingColor() const return mBackingColor; } -void Popup::SetTailUpImage( std::string image ) +void Popup::SetTailUpImage(std::string image) { mTailUpImage = image; mLayoutDirty = true; @@ -1100,10 +1100,10 @@ const std::string& Popup::GetTailUpImage() const return mTailUpImage; } -void Popup::SetTailDownImage( std::string image ) +void Popup::SetTailDownImage(std::string image) { mTailDownImage = image; - mLayoutDirty = true; + mLayoutDirty = true; LayoutTail(); } @@ -1112,10 +1112,10 @@ const std::string& Popup::GetTailDownImage() const return mTailDownImage; } -void Popup::SetTailLeftImage( std::string image ) +void Popup::SetTailLeftImage(std::string image) { mTailLeftImage = image; - mLayoutDirty = true; + mLayoutDirty = true; LayoutTail(); } @@ -1124,10 +1124,10 @@ const std::string& Popup::GetTailLeftImage() const return mTailLeftImage; } -void Popup::SetTailRightImage( std::string image ) +void Popup::SetTailRightImage(std::string image) { mTailRightImage = image; - mLayoutDirty = true; + mLayoutDirty = true; LayoutTail(); } @@ -1136,9 +1136,9 @@ const std::string& Popup::GetTailRightImage() const return mTailRightImage; } -void Popup::SetTouchTransparent( bool enabled ) +void Popup::SetTouchTransparent(bool enabled) { - if( mTouchTransparent != enabled ) + if(mTouchTransparent != enabled) { mTouchTransparent = enabled; SetupTouch(); @@ -1150,52 +1150,52 @@ const bool Popup::IsTouchTransparent() const return mTouchTransparent; } -void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) +void Popup::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value) { - Toolkit::Popup popup = Toolkit::Popup::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Popup popup = Toolkit::Popup::DownCast(Dali::BaseHandle(object)); - if ( popup ) + if(popup) { - Popup& popupImpl( GetImpl( popup ) ); + Popup& popupImpl(GetImpl(popup)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::Popup::Property::TITLE: { Property::Map valueMap; - if( value.Get( valueMap ) ) + if(value.Get(valueMap)) { - popupImpl.SetTitle( Scripting::NewActor( valueMap ) ); + popupImpl.SetTitle(Scripting::NewActor(valueMap)); } break; } case Toolkit::Popup::Property::CONTENT: { Property::Map valueMap; - if( value.Get( valueMap ) ) + if(value.Get(valueMap)) { - popupImpl.SetContent( Scripting::NewActor( valueMap ) ); + popupImpl.SetContent(Scripting::NewActor(valueMap)); } break; } case Toolkit::Popup::Property::FOOTER: { Property::Map valueMap; - if( value.Get( valueMap ) ) + if(value.Get(valueMap)) { - popupImpl.SetFooter( Scripting::NewActor( valueMap ) ); + popupImpl.SetFooter(Scripting::NewActor(valueMap)); } break; } case Toolkit::Popup::Property::DISPLAY_STATE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - Toolkit::Popup::DisplayState displayState( Toolkit::Popup::HIDDEN ); - if( Scripting::GetEnumeration< Toolkit::Popup::DisplayState >( valueString.c_str(), DisplayStateTable, DisplayStateTableCount, displayState ) ) + Toolkit::Popup::DisplayState displayState(Toolkit::Popup::HIDDEN); + if(Scripting::GetEnumeration(valueString.c_str(), DisplayStateTable, DisplayStateTableCount, displayState)) { - popupImpl.SetDisplayState( displayState ); + popupImpl.SetDisplayState(displayState); } } break; @@ -1203,39 +1203,39 @@ void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, cons case Toolkit::Popup::Property::TOUCH_TRANSPARENT: { bool valueBool; - if( value.Get( valueBool ) ) + if(value.Get(valueBool)) { - popupImpl.SetTouchTransparent( valueBool ); + popupImpl.SetTouchTransparent(valueBool); } break; } case Toolkit::Popup::Property::TAIL_VISIBILITY: { bool valueBool; - if( value.Get( valueBool ) ) + if(value.Get(valueBool)) { - popupImpl.SetTailVisibility( valueBool ); + popupImpl.SetTailVisibility(valueBool); } break; } case Toolkit::Popup::Property::TAIL_POSITION: { Vector3 valueVector3; - if( value.Get( valueVector3 ) ) + if(value.Get(valueVector3)) { - popupImpl.SetTailPosition( valueVector3 ); + popupImpl.SetTailPosition(valueVector3); } break; } case Toolkit::Popup::Property::CONTEXTUAL_MODE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - Toolkit::Popup::ContextualMode contextualMode( Toolkit::Popup::BELOW ); - if( Scripting::GetEnumeration< Toolkit::Popup::ContextualMode >( valueString.c_str(), ContextualModeTable, ContextualModeTableCount, contextualMode ) ) + Toolkit::Popup::ContextualMode contextualMode(Toolkit::Popup::BELOW); + if(Scripting::GetEnumeration(valueString.c_str(), ContextualModeTable, ContextualModeTableCount, contextualMode)) { - popupImpl.SetContextualMode( contextualMode ); + popupImpl.SetContextualMode(contextualMode); } } break; @@ -1243,21 +1243,21 @@ void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, cons case Toolkit::Popup::Property::ANIMATION_DURATION: { float valueFloat; - if( value.Get( valueFloat ) ) + if(value.Get(valueFloat)) { - popupImpl.SetAnimationDuration( valueFloat ); + popupImpl.SetAnimationDuration(valueFloat); } break; } case Toolkit::Popup::Property::ANIMATION_MODE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - Toolkit::Popup::AnimationMode animationMode( Toolkit::Popup::FADE ); - if( Scripting::GetEnumeration< Toolkit::Popup::AnimationMode >( valueString.c_str(), AnimationModeTable, AnimationModeTableCount, animationMode ) ) + Toolkit::Popup::AnimationMode animationMode(Toolkit::Popup::FADE); + if(Scripting::GetEnumeration(valueString.c_str(), AnimationModeTable, AnimationModeTableCount, animationMode)) { - popupImpl.SetAnimationMode( animationMode ); + popupImpl.SetAnimationMode(animationMode); } } break; @@ -1265,55 +1265,55 @@ void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, cons case Toolkit::Popup::Property::ENTRY_ANIMATION: { Property::Map valueMap; - if( value.Get( valueMap ) ) + if(value.Get(valueMap)) { - popupImpl.SetEntryAnimationData( valueMap ); + popupImpl.SetEntryAnimationData(valueMap); } break; } case Toolkit::Popup::Property::EXIT_ANIMATION: { Property::Map valueMap; - if( value.Get( valueMap ) ) + if(value.Get(valueMap)) { - popupImpl.SetExitAnimationData( valueMap ); + popupImpl.SetExitAnimationData(valueMap); } break; } case Toolkit::Popup::Property::AUTO_HIDE_DELAY: { int valueInt; - if( value.Get( valueInt ) ) + if(value.Get(valueInt)) { - popupImpl.SetAutoHideDelay( valueInt ); + popupImpl.SetAutoHideDelay(valueInt); } break; } case Toolkit::Popup::Property::BACKING_ENABLED: { bool valueBool; - if( value.Get( valueBool ) ) + if(value.Get(valueBool)) { - popupImpl.SetBackingEnabled( valueBool ); + popupImpl.SetBackingEnabled(valueBool); } break; } case Toolkit::Popup::Property::BACKING_COLOR: { Vector4 valueVector4; - if( value.Get( valueVector4 ) ) + if(value.Get(valueVector4)) { - popupImpl.SetBackingColor( valueVector4 ); + popupImpl.SetBackingColor(valueVector4); } break; } case Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - Toolkit::ImageView actor = Toolkit::ImageView::New( valueString ); - popupImpl.SetPopupBackgroundImage( actor ); + Toolkit::ImageView actor = Toolkit::ImageView::New(valueString); + popupImpl.SetPopupBackgroundImage(actor); } break; } @@ -1322,22 +1322,22 @@ void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, cons bool valueUpdated = false; Vector4 valueVector4; - if( value.Get( popupImpl.mBackgroundBorder ) ) + if(value.Get(popupImpl.mBackgroundBorder)) { valueUpdated = true; } - else if( value.Get( valueVector4 ) ) + else if(value.Get(valueVector4)) { popupImpl.mBackgroundBorder.left = valueVector4.x; popupImpl.mBackgroundBorder.right = valueVector4.y; popupImpl.mBackgroundBorder.bottom = valueVector4.z; popupImpl.mBackgroundBorder.top = valueVector4.w; - valueUpdated = true; + valueUpdated = true; } - if( valueUpdated ) + if(valueUpdated) { - popupImpl.LayoutTail(); // Update the tail if required + popupImpl.LayoutTail(); // Update the tail if required popupImpl.UpdateBackgroundPositionAndSize(); // Update the background's size and position } break; @@ -1345,36 +1345,36 @@ void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, cons case Toolkit::Popup::Property::TAIL_UP_IMAGE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - popupImpl.SetTailUpImage( valueString ); + popupImpl.SetTailUpImage(valueString); } break; } case Toolkit::Popup::Property::TAIL_DOWN_IMAGE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - popupImpl.SetTailDownImage( valueString ); + popupImpl.SetTailDownImage(valueString); } break; } case Toolkit::Popup::Property::TAIL_LEFT_IMAGE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - popupImpl.SetTailLeftImage( valueString ); + popupImpl.SetTailLeftImage(valueString); } break; } case Toolkit::Popup::Property::TAIL_RIGHT_IMAGE: { std::string valueString; - if( value.Get( valueString ) ) + if(value.Get(valueString)) { - popupImpl.SetTailRightImage( valueString ); + popupImpl.SetTailRightImage(valueString); } break; } @@ -1382,42 +1382,42 @@ void Popup::SetProperty( BaseObject* object, Property::Index propertyIndex, cons } } -Property::Value Popup::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value Popup::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::Popup popup = Toolkit::Popup::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Popup popup = Toolkit::Popup::DownCast(Dali::BaseHandle(object)); - if ( popup ) + if(popup) { - Popup& popupImpl( GetImpl( popup ) ); + Popup& popupImpl(GetImpl(popup)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::Popup::Property::TITLE: { Property::Map map; - Scripting::CreatePropertyMap( popupImpl.GetTitle(), map ); + Scripting::CreatePropertyMap(popupImpl.GetTitle(), map); value = map; break; } case Toolkit::Popup::Property::CONTENT: { Property::Map map; - Scripting::CreatePropertyMap( popupImpl.GetContent(), map ); + Scripting::CreatePropertyMap(popupImpl.GetContent(), map); value = map; break; } case Toolkit::Popup::Property::FOOTER: { Property::Map map; - Scripting::CreatePropertyMap( popupImpl.GetFooter(), map ); + Scripting::CreatePropertyMap(popupImpl.GetFooter(), map); value = map; break; } case Toolkit::Popup::Property::DISPLAY_STATE: { - value = Scripting::GetLinearEnumerationName< Toolkit::Popup::DisplayState >( popupImpl.GetDisplayState(), DisplayStateTable, DisplayStateTableCount ); + value = Scripting::GetLinearEnumerationName(popupImpl.GetDisplayState(), DisplayStateTable, DisplayStateTableCount); break; } case Toolkit::Popup::Property::TOUCH_TRANSPARENT: @@ -1437,7 +1437,7 @@ Property::Value Popup::GetProperty( BaseObject* object, Property::Index property } case Toolkit::Popup::Property::CONTEXTUAL_MODE: { - value = Scripting::GetLinearEnumerationName< Toolkit::Popup::ContextualMode >( popupImpl.GetContextualMode(), ContextualModeTable, ContextualModeTableCount ); + value = Scripting::GetLinearEnumerationName(popupImpl.GetContextualMode(), ContextualModeTable, ContextualModeTableCount); break; } case Toolkit::Popup::Property::ANIMATION_DURATION: @@ -1447,7 +1447,7 @@ Property::Value Popup::GetProperty( BaseObject* object, Property::Index property } case Toolkit::Popup::Property::ANIMATION_MODE: { - value = Scripting::GetLinearEnumerationName< Toolkit::Popup::AnimationMode >( popupImpl.GetAnimationMode(), AnimationModeTable, AnimationModeTableCount ); + value = Scripting::GetLinearEnumerationName(popupImpl.GetAnimationMode(), AnimationModeTable, AnimationModeTableCount); break; } case Toolkit::Popup::Property::ENTRY_ANIMATION: @@ -1481,10 +1481,10 @@ Property::Value Popup::GetProperty( BaseObject* object, Property::Index property } case Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE: { - Toolkit::ImageView imageView = Toolkit::ImageView::DownCast( popupImpl.GetPopupBackgroundImage() ); - if( imageView ) + Toolkit::ImageView imageView = Toolkit::ImageView::DownCast(popupImpl.GetPopupBackgroundImage()); + if(imageView) { - value = imageView.GetProperty( Toolkit::ImageView::Property::IMAGE ); + value = imageView.GetProperty(Toolkit::ImageView::Property::IMAGE); } break; } @@ -1519,32 +1519,32 @@ Property::Value Popup::GetProperty( BaseObject* object, Property::Index property return value; } -bool Popup::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool Popup::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::Popup popup = Toolkit::Popup::DownCast( handle ); + bool connected(true); + Toolkit::Popup popup = Toolkit::Popup::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_TOUCHED_OUTSIDE ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_TOUCHED_OUTSIDE)) { - popup.OutsideTouchedSignal().Connect( tracker, functor ); + popup.OutsideTouchedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_SHOWING ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_SHOWING)) { - popup.ShowingSignal().Connect( tracker, functor ); + popup.ShowingSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_SHOWN ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_SHOWN)) { - popup.ShownSignal().Connect( tracker, functor ); + popup.ShownSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_HIDING ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_HIDING)) { - popup.HidingSignal().Connect( tracker, functor ); + popup.HidingSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_HIDDEN ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_HIDDEN)) { - popup.HiddenSignal().Connect( tracker, functor ); + popup.HiddenSignal().Connect(tracker, functor); } else { @@ -1555,15 +1555,15 @@ bool Popup::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tra return connected; } -bool Popup::OnBackingTouched( Actor actor, const TouchEvent& touch ) +bool Popup::OnBackingTouched(Actor actor, const TouchEvent& touch) { // Allow events to pass through if the backing isn't the hit-actor - if( (touch.GetHitActor(0) == actor) && - (touch.GetPointCount() > 0) && - (touch.GetState( 0 ) == PointState::DOWN)) + if((touch.GetHitActor(0) == actor) && + (touch.GetPointCount() > 0) && + (touch.GetState(0) == PointState::DOWN)) { // Guard against destruction during signal emission. - Toolkit::Popup handle( GetOwner() ); + Toolkit::Popup handle(GetOwner()); mTouchedOutsideSignal.Emit(); } @@ -1571,10 +1571,10 @@ bool Popup::OnBackingTouched( Actor actor, const TouchEvent& touch ) return false; } -bool Popup::OnBackingWheelEvent( Actor actor, const WheelEvent& event ) +bool Popup::OnBackingWheelEvent(Actor actor, const WheelEvent& event) { // Allow events to pass through if touch transparency is enabled. - if( mTouchTransparent ) + if(mTouchTransparent) { return false; } @@ -1582,26 +1582,26 @@ bool Popup::OnBackingWheelEvent( Actor actor, const WheelEvent& event ) return true; } -bool Popup::OnDialogTouched( Actor actor, const TouchEvent& touch ) +bool Popup::OnDialogTouched(Actor actor, const TouchEvent& touch) { // Only connecting this so the backing does not become the default hit-actor and inadvertently closes the popup return false; } -void Popup::OnSceneConnection( int depth ) +void Popup::OnSceneConnection(int depth) { mLayoutDirty = true; RelayoutRequest(); - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } -void Popup::OnChildAdd( Actor& child ) +void Popup::OnChildAdd(Actor& child) { // Re-parent any children added by user to the body layer. - if( mAlterAddedChild ) + if(mAlterAddedChild) { - SetContent( child ); + SetContent(child); } else { @@ -1609,33 +1609,33 @@ void Popup::OnChildAdd( Actor& child ) RelayoutRequest(); } - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void Popup::LayoutContext( const Vector2& size ) +void Popup::LayoutContext(const Vector2& size) { // Do nothing if not in a contextual mode (or there is no parent context). - Actor self = Self(); + Actor self = Self(); Actor parent = self.GetParent(); - if( ( mContextualMode == Toolkit::Popup::NON_CONTEXTUAL ) || !parent ) + if((mContextualMode == Toolkit::Popup::NON_CONTEXTUAL) || !parent) { return; } - mPopupContainer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mPopupContainer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // We always anchor to the CENTER, rather than a different anchor point for each contextual // mode to allow code-reuse of the bound checking code (for maintainability). - mPopupContainer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + mPopupContainer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); // Setup with some pre-calculations for speed. - Vector3 halfStageSize( Stage().GetCurrent().GetSize() / 2.0f ); - Vector3 parentPosition( parent.GetCurrentProperty< Vector3 >( Actor::Property::POSITION ) ); - Vector2 halfSize( size / 2.0f ); - Vector2 halfParentSize( parent.GetRelayoutSize( Dimension::WIDTH ) / 2.0f, parent.GetRelayoutSize( Dimension::HEIGHT ) / 2.0f ); - Vector3 newPosition( Vector3::ZERO ); + Vector3 halfStageSize(Stage().GetCurrent().GetSize() / 2.0f); + Vector3 parentPosition(parent.GetCurrentProperty(Actor::Property::POSITION)); + Vector2 halfSize(size / 2.0f); + Vector2 halfParentSize(parent.GetRelayoutSize(Dimension::WIDTH) / 2.0f, parent.GetRelayoutSize(Dimension::HEIGHT) / 2.0f); + Vector3 newPosition(Vector3::ZERO); // Perform different positioning based on the specified contextual layout mode. - switch( mContextualMode ) + switch(mContextualMode) { case Toolkit::Popup::BELOW: { @@ -1672,121 +1672,121 @@ void Popup::LayoutContext( const Vector2& size ) // Check new position is not too far right. If so, correct it. // Note: Check for right rather than left first, so if popup is too wide, the left check overrides // the right check and we at least see the left portion of the popup (as this is more useful). - if( newPosition.x >= ( halfStageSize.x - parentPosition.x - halfSize.x - DEFAULT_CONTEXTUAL_STAGE_BORDER.x ) ) + if(newPosition.x >= (halfStageSize.x - parentPosition.x - halfSize.x - DEFAULT_CONTEXTUAL_STAGE_BORDER.x)) { newPosition.x = halfStageSize.x - parentPosition.x - halfSize.x - DEFAULT_CONTEXTUAL_STAGE_BORDER.x; } // Check new position is not too far left. If so, correct it. - if( newPosition.x < halfSize.x - ( parentPosition.x + halfStageSize.x ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x ) + if(newPosition.x < halfSize.x - (parentPosition.x + halfStageSize.x) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x) { - newPosition.x = halfSize.x - ( parentPosition.x + halfStageSize.x ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x;// - parentSize.x; + newPosition.x = halfSize.x - (parentPosition.x + halfStageSize.x) + DEFAULT_CONTEXTUAL_STAGE_BORDER.x; // - parentSize.x; } // Check new position is not too far down. If so, correct it. - if( newPosition.y >= ( halfStageSize.y - parentPosition.y - halfSize.y - DEFAULT_CONTEXTUAL_STAGE_BORDER.y ) ) + if(newPosition.y >= (halfStageSize.y - parentPosition.y - halfSize.y - DEFAULT_CONTEXTUAL_STAGE_BORDER.y)) { newPosition.y = halfStageSize.y - parentPosition.y - halfSize.y - DEFAULT_CONTEXTUAL_STAGE_BORDER.y; } // Check new position is not too far up. If so, correct it. - if( newPosition.y < halfSize.y - ( parentPosition.y + halfStageSize.y ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y ) + if(newPosition.y < halfSize.y - (parentPosition.y + halfStageSize.y) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y) { - newPosition.y = halfSize.y - ( parentPosition.y + halfStageSize.y ) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y; + newPosition.y = halfSize.y - (parentPosition.y + halfStageSize.y) + DEFAULT_CONTEXTUAL_STAGE_BORDER.y; } // Set the final position. - mPopupContainer.SetProperty( Actor::Property::POSITION, newPosition ); + mPopupContainer.SetProperty(Actor::Property::POSITION, newPosition); } -void Popup::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void Popup::OnRelayout(const Vector2& size, RelayoutContainer& container) { - Vector2 useSize( size ); + Vector2 useSize(size); // Use the Popup layouts size, unless requested to use a fixed size. // In which case take the size set for the Popup itself. - ResizePolicy::Type widthPolicy = Self().GetResizePolicy( Dimension::WIDTH ); - ResizePolicy::Type heightPolicy = Self().GetResizePolicy( Dimension::HEIGHT ); + ResizePolicy::Type widthPolicy = Self().GetResizePolicy(Dimension::WIDTH); + ResizePolicy::Type heightPolicy = Self().GetResizePolicy(Dimension::HEIGHT); // Width calculations: - if( widthPolicy == ResizePolicy::USE_NATURAL_SIZE || widthPolicy == ResizePolicy::FIT_TO_CHILDREN ) + if(widthPolicy == ResizePolicy::USE_NATURAL_SIZE || widthPolicy == ResizePolicy::FIT_TO_CHILDREN) { // If we using a child-based policy, take the size from the popup layout. - mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::WIDTH ); - useSize.width = mPopupLayout.GetRelayoutSize( Dimension::WIDTH ); + mPopupLayout.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::WIDTH); + useSize.width = mPopupLayout.GetRelayoutSize(Dimension::WIDTH); - mPopupLayout.SetFitWidth( 0u ); + mPopupLayout.SetFitWidth(0u); } else { // If we using a parent-based policy, take the size from the popup object itself (self). - mPopupLayout.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH ); + mPopupLayout.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::WIDTH); - mPopupLayout.SetFixedWidth( 0u, useSize.width ); + mPopupLayout.SetFixedWidth(0u, useSize.width); } // Height calculations: // Title: Let the title be as high as it needs to be. - mPopupLayout.SetFitHeight( 0u ); + mPopupLayout.SetFitHeight(0u); // Footer: Convert the footer's resize policy to a TableView row policy. - if( mFooter ) + if(mFooter) { - ResizePolicy::Type footerHeightPolicy = mFooter.GetResizePolicy( Dimension::HEIGHT ); - if( ( footerHeightPolicy == ResizePolicy::USE_NATURAL_SIZE ) || - ( footerHeightPolicy == ResizePolicy::FIT_TO_CHILDREN ) ) + ResizePolicy::Type footerHeightPolicy = mFooter.GetResizePolicy(Dimension::HEIGHT); + if((footerHeightPolicy == ResizePolicy::USE_NATURAL_SIZE) || + (footerHeightPolicy == ResizePolicy::FIT_TO_CHILDREN)) { - mPopupLayout.SetFitHeight( 2u ); + mPopupLayout.SetFitHeight(2u); } - else if( footerHeightPolicy == ResizePolicy::FIXED ) + else if(footerHeightPolicy == ResizePolicy::FIXED) { - mPopupLayout.SetFixedHeight( 2u, mFooter.GetRelayoutSize( Dimension::HEIGHT) ); + mPopupLayout.SetFixedHeight(2u, mFooter.GetRelayoutSize(Dimension::HEIGHT)); } else { - mPopupLayout.SetRelativeHeight( 2u, 1.0f ); + mPopupLayout.SetRelativeHeight(2u, 1.0f); } } else { - mPopupLayout.SetFixedHeight( 2u, 0.0f ); + mPopupLayout.SetFixedHeight(2u, 0.0f); } // Popup contents: Adjust the tableview's policies based on the popup's policies. - if( heightPolicy == ResizePolicy::USE_NATURAL_SIZE || heightPolicy == ResizePolicy::FIT_TO_CHILDREN ) + if(heightPolicy == ResizePolicy::USE_NATURAL_SIZE || heightPolicy == ResizePolicy::FIT_TO_CHILDREN) { - mPopupLayout.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT ); + mPopupLayout.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT); // Let both the contents expand as necessary. - mPopupLayout.SetFitHeight( 1u ); - useSize.height = mPopupLayout.GetRelayoutSize( Dimension::HEIGHT ); + mPopupLayout.SetFitHeight(1u); + useSize.height = mPopupLayout.GetRelayoutSize(Dimension::HEIGHT); } else { - mPopupLayout.SetResizePolicy( heightPolicy, Dimension::HEIGHT ); + mPopupLayout.SetResizePolicy(heightPolicy, Dimension::HEIGHT); // Let the content expand to fill the remaining space. - mPopupLayout.SetRelativeHeight( 1u, 1.0f ); - mPopupLayout.SetResizePolicy( ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT ); + mPopupLayout.SetRelativeHeight(1u, 1.0f); + mPopupLayout.SetResizePolicy(ResizePolicy::USE_ASSIGNED_SIZE, Dimension::HEIGHT); } // Relayout the popup-layout to give it it's new size this frame. - container.Add( mPopupLayout, useSize ); + container.Add(mPopupLayout, useSize); - if( mContent ) + if(mContent) { - container.Add( mContent, Vector2( mContent.GetRelayoutSize( Dimension::WIDTH ), mContent.GetRelayoutSize( Dimension::HEIGHT ) ) ); + container.Add(mContent, Vector2(mContent.GetRelayoutSize(Dimension::WIDTH), mContent.GetRelayoutSize(Dimension::HEIGHT))); } // Perform contextual layout setup if required. // This is done each time in case the parent moves. // This will have no effect if no contextual mode is selected. - LayoutContext( useSize ); + LayoutContext(useSize); } -void Popup::OnSetResizePolicy( ResizePolicy::Type policy, Dimension::Type dimension ) +void Popup::OnSetResizePolicy(ResizePolicy::Type policy, Dimension::Type dimension) { // To get the popup to emulate fit-to-children, we need to actually set use-natural-size. - if( ( dimension & Dimension::HEIGHT ) && ( policy == ResizePolicy::FIT_TO_CHILDREN ) ) + if((dimension & Dimension::HEIGHT) && (policy == ResizePolicy::FIT_TO_CHILDREN)) { - Self().SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT ); + Self().SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::HEIGHT); } mLayoutDirty = true; @@ -1798,31 +1798,31 @@ Vector3 Popup::GetNaturalSize() return mPopupLayout.GetNaturalSize(); } -float Popup::GetHeightForWidth( float width ) +float Popup::GetHeightForWidth(float width) { - return mPopupLayout.GetHeightForWidth( width ); + return mPopupLayout.GetHeightForWidth(width); } -float Popup::GetWidthForHeight( float height ) +float Popup::GetWidthForHeight(float height) { - return mPopupLayout.GetWidthForHeight( height ); + return mPopupLayout.GetWidthForHeight(height); } -bool Popup::OnKeyEvent( const KeyEvent& event ) +bool Popup::OnKeyEvent(const KeyEvent& event) { // Allow events to pass through if touch transparency is enabled. - if( mTouchTransparent ) + if(mTouchTransparent) { return false; } bool consumed = false; - if( event.GetState() == KeyEvent::DOWN ) + if(event.GetState() == KeyEvent::DOWN) { - if (event.GetKeyCode() == Dali::DALI_KEY_ESCAPE || event.GetKeyCode() == Dali::DALI_KEY_BACK) + if(event.GetKeyCode() == Dali::DALI_KEY_ESCAPE || event.GetKeyCode() == Dali::DALI_KEY_BACK) { - SetDisplayState( Toolkit::Popup::HIDDEN ); + SetDisplayState(Toolkit::Popup::HIDDEN); consumed = true; } } @@ -1830,77 +1830,77 @@ bool Popup::OnKeyEvent( const KeyEvent& event ) return consumed; } -void Popup::AddFocusableChildrenRecursive( Actor parent, std::vector< Actor >& focusableActors ) +void Popup::AddFocusableChildrenRecursive(Actor parent, std::vector& focusableActors) { - if( parent ) + if(parent) { - Toolkit::Control control = Toolkit::Control::DownCast( parent ); - bool layoutControl = control && GetImplementation( control ).IsKeyboardNavigationSupported(); + Toolkit::Control control = Toolkit::Control::DownCast(parent); + bool layoutControl = control && GetImplementation(control).IsKeyboardNavigationSupported(); - if( parent.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) || layoutControl ) + if(parent.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE) || layoutControl) { - focusableActors.push_back( parent ); + focusableActors.push_back(parent); - if( !layoutControl ) + if(!layoutControl) { - for( unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i ) + for(unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i) { - Actor child( parent.GetChildAt( i ) ); - AddFocusableChildrenRecursive( child, focusableActors ); + Actor child(parent.GetChildAt(i)); + AddFocusableChildrenRecursive(child, focusableActors); } } } } } -void Popup::AddFocusableChildren( Actor parent, std::vector< Actor >& focusableActors ) +void Popup::AddFocusableChildren(Actor parent, std::vector& focusableActors) { - if( parent ) + if(parent) { - Toolkit::Control control = Toolkit::Control::DownCast( parent ); - if( !GetImplementation( control ).IsKeyboardNavigationSupported() ) + Toolkit::Control control = Toolkit::Control::DownCast(parent); + if(!GetImplementation(control).IsKeyboardNavigationSupported()) { - for( unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i ) + for(unsigned int i = 0, numberChildren = parent.GetChildCount(); i < numberChildren; ++i) { - Actor child( parent.GetChildAt( i ) ); - AddFocusableChildrenRecursive( child, focusableActors ); + Actor child(parent.GetChildAt(i)); + AddFocusableChildrenRecursive(child, focusableActors); } } else { - focusableActors.push_back( parent ); + focusableActors.push_back(parent); } } } -Actor Popup::GetNextKeyboardFocusableActor( Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled ) +Actor Popup::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled) { std::string currentStr; - if( currentFocusedActor ) + if(currentFocusedActor) { - currentStr = currentFocusedActor.GetProperty< std::string >( Dali::Actor::Property::NAME ); + currentStr = currentFocusedActor.GetProperty(Dali::Actor::Property::NAME); } - Actor nextFocusableActor( currentFocusedActor ); + Actor nextFocusableActor(currentFocusedActor); Actor currentFocusGroup; - if( currentFocusedActor ) + if(currentFocusedActor) { - currentFocusGroup = KeyboardFocusManager::Get().GetFocusGroup( currentFocusedActor ); + currentFocusGroup = KeyboardFocusManager::Get().GetFocusGroup(currentFocusedActor); } // TODO: Needs to be optimised // The following statement checks that if we have a current focused actor, then the current focus group is not the popup content or footer. // This is to detect if the focus is currently outside the popup, and if so, move it inside. - if( !currentFocusedActor || - ( currentFocusedActor && ( ( !mContent || ( currentFocusGroup != mContent ) ) && ( !mFooter || ( currentFocusGroup != mFooter ) ) ) ) ) + if(!currentFocusedActor || + (currentFocusedActor && ((!mContent || (currentFocusGroup != mContent)) && (!mFooter || (currentFocusGroup != mFooter))))) { // The current focused actor is not within popup. - if( mContent && mContent.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + if(mContent && mContent.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // If the content is focusable, move the focus to the content. nextFocusableActor = mContent; } - else if( mFooter && mFooter.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + else if(mFooter && mFooter.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // If the footer is focusable, move the focus to the footer. nextFocusableActor = mFooter; @@ -1909,59 +1909,59 @@ Actor Popup::GetNextKeyboardFocusableActor( Actor currentFocusedActor, Toolkit:: else { // Rebuild the focus chain because controls or content can be added or removed dynamically - std::vector< Actor > focusableActors; + std::vector focusableActors; - AddFocusableChildren( mContent, focusableActors ); - AddFocusableChildren( mFooter, focusableActors ); + AddFocusableChildren(mContent, focusableActors); + AddFocusableChildren(mFooter, focusableActors); - std::vector< Actor >::iterator endIterator = focusableActors.end(); - std::vector< Actor >::iterator currentIterator = focusableActors.begin(); - for( std::vector< Actor >::iterator iterator = focusableActors.begin(); iterator != endIterator; ++iterator ) + std::vector::iterator endIterator = focusableActors.end(); + std::vector::iterator currentIterator = focusableActors.begin(); + for(std::vector::iterator iterator = focusableActors.begin(); iterator != endIterator; ++iterator) { - if( currentFocusedActor == *iterator ) + if(currentFocusedActor == *iterator) { currentIterator = iterator; } } - if( currentIterator != endIterator ) + if(currentIterator != endIterator) { - switch( direction ) + switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { - if( currentIterator == focusableActors.begin() ) + if(currentIterator == focusableActors.begin()) { - nextFocusableActor = *( endIterator - 1 ); + nextFocusableActor = *(endIterator - 1); } else { - nextFocusableActor = *( currentIterator - 1 ); + nextFocusableActor = *(currentIterator - 1); } break; } case Toolkit::Control::KeyboardFocus::RIGHT: { - if( currentIterator == endIterator - 1 ) + if(currentIterator == endIterator - 1) { - nextFocusableActor = *( focusableActors.begin() ); + nextFocusableActor = *(focusableActors.begin()); } else { - nextFocusableActor = *( currentIterator + 1 ); + nextFocusableActor = *(currentIterator + 1); } break; } case Toolkit::Control::KeyboardFocus::UP: { - nextFocusableActor = *( focusableActors.begin() ); + nextFocusableActor = *(focusableActors.begin()); break; } case Toolkit::Control::KeyboardFocus::DOWN: { - nextFocusableActor = *( endIterator - 1 ); + nextFocusableActor = *(endIterator - 1); break; } @@ -1971,9 +1971,9 @@ Actor Popup::GetNextKeyboardFocusableActor( Actor currentFocusedActor, Toolkit:: } } - if( !nextFocusableActor ) + if(!nextFocusableActor) { - DALI_LOG_WARNING( "Can not decide next focusable actor\n" ); + DALI_LOG_WARNING("Can not decide next focusable actor\n"); } } } @@ -1983,41 +1983,41 @@ Actor Popup::GetNextKeyboardFocusableActor( Actor currentFocusedActor, Toolkit:: void Popup::SetupTouch() { - if( ! mTouchTransparent ) + if(!mTouchTransparent) { // Connect all the signals and set us up to consume all touch events - mBacking.TouchedSignal().Connect( this, &Popup::OnBackingTouched ); - mPopupBackgroundImage.TouchedSignal().Connect( this, &Popup::OnDialogTouched ); - mPopupLayout.TouchedSignal().Connect( this, &Popup::OnDialogTouched ); - mLayer.SetProperty( Layer::Property::CONSUMES_TOUCH, true ); + mBacking.TouchedSignal().Connect(this, &Popup::OnBackingTouched); + mPopupBackgroundImage.TouchedSignal().Connect(this, &Popup::OnDialogTouched); + mPopupLayout.TouchedSignal().Connect(this, &Popup::OnDialogTouched); + mLayer.SetProperty(Layer::Property::CONSUMES_TOUCH, true); } else { // We are touch transparent so disconnect all signals and ensure our layer does not consumed all touch events - mBacking.TouchedSignal().Disconnect( this, &Popup::OnBackingTouched ); - mPopupBackgroundImage.TouchedSignal().Disconnect( this, &Popup::OnDialogTouched ); - mPopupLayout.TouchedSignal().Disconnect( this, &Popup::OnDialogTouched ); - mLayer.SetProperty( Layer::Property::CONSUMES_TOUCH, false ); + mBacking.TouchedSignal().Disconnect(this, &Popup::OnBackingTouched); + mPopupBackgroundImage.TouchedSignal().Disconnect(this, &Popup::OnDialogTouched); + mPopupLayout.TouchedSignal().Disconnect(this, &Popup::OnDialogTouched); + mLayer.SetProperty(Layer::Property::CONSUMES_TOUCH, false); } } std::string Popup::AccessibleImpl::GetNameRaw() { - auto popup = Toolkit::Popup::DownCast( self ); + auto popup = Toolkit::Popup::DownCast(self); std::string title; - Actor popupTitle = popup.GetTitle(); - if (popupTitle) + Actor popupTitle = popup.GetTitle(); + if(popupTitle) { std::string titleText = popupTitle.GetProperty(Toolkit::TextLabel::Property::TEXT); - title = titleText; + title = titleText; } else { Actor popupContent = popup.GetContent(); - if (popupContent) + if(popupContent) { std::string contentText = popupContent.GetProperty(Toolkit::TextLabel::Property::TEXT); - title = contentText; + title = contentText; } } return title; @@ -2025,8 +2025,8 @@ std::string Popup::AccessibleImpl::GetNameRaw() Dali::Accessibility::States Popup::AccessibleImpl::CalculateStates() { - auto states = Control::Impl::AccessibleImpl::CalculateStates(); - auto popup = Toolkit::Popup::DownCast(self); + auto states = Control::Impl::AccessibleImpl::CalculateStates(); + auto popup = Toolkit::Popup::DownCast(self); auto displayState = popup.GetProperty(Toolkit::Popup::Property::DISPLAY_STATE); states[Dali::Accessibility::State::SHOWING] = (displayState == "SHOWN" || displayState == "SHOWING"); diff --git a/dali-toolkit/internal/controls/progress-bar/progress-bar-impl.cpp b/dali-toolkit/internal/controls/progress-bar/progress-bar-impl.cpp index 7251b48..12ccab6 100644 --- a/dali-toolkit/internal/controls/progress-bar/progress-bar-impl.cpp +++ b/dali-toolkit/internal/controls/progress-bar/progress-bar-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,58 +19,57 @@ #include // EXTERNAL INCLUDES -#include // for strcmp -#include -#include -#include -#include -#include -#include #include #include +#include +#include #include #include -#include +#include #include #include #include #include -#include +#include +#include +#include +#include +#include // for strcmp +#include #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // Unnamed namespace { - BaseHandle Create() { return Dali::Toolkit::ProgressBar::New(); } +// clang-format off // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ProgressBar, Toolkit::Control, Create ) - -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "progressValue", FLOAT, PROGRESS_VALUE ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "secondaryProgressValue", FLOAT, SECONDARY_PROGRESS_VALUE ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "indeterminate", BOOLEAN, INDETERMINATE ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "trackVisual", MAP, TRACK_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "progressVisual", MAP, PROGRESS_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "secondaryProgressVisual", MAP, SECONDARY_PROGRESS_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "indeterminateVisual", MAP, INDETERMINATE_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "indeterminateVisualAnimation", ARRAY, INDETERMINATE_VISUAL_ANIMATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, ProgressBar, "labelVisual", MAP, LABEL_VISUAL ) -DALI_SIGNAL_REGISTRATION( Toolkit, ProgressBar, "valueChanged", SIGNAL_VALUE_CHANGED ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ProgressBar, Toolkit::Control, Create) + +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "progressValue", FLOAT, PROGRESS_VALUE ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "secondaryProgressValue", FLOAT, SECONDARY_PROGRESS_VALUE ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "indeterminate", BOOLEAN, INDETERMINATE ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "trackVisual", MAP, TRACK_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "progressVisual", MAP, PROGRESS_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "secondaryProgressVisual", MAP, SECONDARY_PROGRESS_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "indeterminateVisual", MAP, INDETERMINATE_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "indeterminateVisualAnimation", ARRAY, INDETERMINATE_VISUAL_ANIMATION) +DALI_PROPERTY_REGISTRATION(Toolkit, ProgressBar, "labelVisual", MAP, LABEL_VISUAL ) + +DALI_SIGNAL_REGISTRATION(Toolkit, ProgressBar, "valueChanged", SIGNAL_VALUE_CHANGED) DALI_TYPE_REGISTRATION_END() +// clang-format on struct ProgressDepthIndex { @@ -85,37 +84,36 @@ struct ProgressDepthIndex }; }; -float DEFAULT_VALUE = 0.0f; -float DEFAULT_LOWER_BOUND = 0.0f; -float DEFAULT_UPPER_BOUND = 1.0f; -float DEFAULT_FONT_SIZE = 12.0f; +float DEFAULT_VALUE = 0.0f; +float DEFAULT_LOWER_BOUND = 0.0f; +float DEFAULT_UPPER_BOUND = 1.0f; +float DEFAULT_FONT_SIZE = 12.0f; const char* CIRCULAR_PROGRESS_BAR_STYLE_NAME = "CircularProgressBar"; - -void BackupVisualProperties( const Control* control, Property::Index index, Property::Map& map ) +void BackupVisualProperties(const Control* control, Property::Index index, Property::Map& map) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *control, index ); + Toolkit::Visual::Base visual = DevelControl::GetVisual(*control, index); - if( visual ) + if(visual) { map.Clear(); - visual.CreatePropertyMap( map ); + visual.CreatePropertyMap(map); } } -void RestoreVisualProperties( Control* control, Property::Index index, Property::Map& map, int depth ) +void RestoreVisualProperties(Control* control, Property::Index index, Property::Map& map, int depth) { - if( !map.Empty() ) + if(!map.Empty()) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *control, index ); + Toolkit::Visual::Base visual = DevelControl::GetVisual(*control, index); - Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); + Visual::Base& visualImpl = Toolkit::GetImplementation(visual); - visualImpl.SetProperties( map ); + visualImpl.SetProperties(map); - DevelControl::UnregisterVisual( *control, index ); + DevelControl::UnregisterVisual(*control, index); - DevelControl::RegisterVisual( *control, index, visual, true, depth ); + DevelControl::RegisterVisual(*control, index, visual, true, depth); } } @@ -125,18 +123,18 @@ void RestoreVisualProperties( Control* control, Property::Index index, Property: // ProgressBar /////////////////////////////////////////////////////////////////////////////////////////////////// -Dali::Toolkit::ProgressBar ProgressBar::New( DevelProgressBar::Style progressBarStyle ) +Dali::Toolkit::ProgressBar ProgressBar::New(DevelProgressBar::Style progressBarStyle) { // Create the implementation - ProgressBarPtr progressBar( new ProgressBar() ); + ProgressBarPtr progressBar(new ProgressBar()); - Dali::Toolkit::ProgressBar handle( *progressBar ); + Dali::Toolkit::ProgressBar handle(*progressBar); - switch( progressBarStyle ) + switch(progressBarStyle) { case DevelProgressBar::Style::CIRCULAR: { - progressBar->SetStyleName( CIRCULAR_PROGRESS_BAR_STYLE_NAME ); + progressBar->SetStyleName(CIRCULAR_PROGRESS_BAR_STYLE_NAME); break; } default: @@ -153,10 +151,10 @@ Dali::Toolkit::ProgressBar ProgressBar::New( DevelProgressBar::Style progressBar } ProgressBar::ProgressBar() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mProgressValue( DEFAULT_VALUE ), - mSecondaryProgressValue( DEFAULT_VALUE ), - mIndeterminate( false ) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mProgressValue(DEFAULT_VALUE), + mSecondaryProgressValue(DEFAULT_VALUE), + mIndeterminate(false) { } @@ -166,91 +164,89 @@ ProgressBar::~ProgressBar() void ProgressBar::OnInitialize() { - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::PROGRESS_BAR ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::PROGRESS_BAR)); + }); //Enable highightability - Self().SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + Self().SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); } -void ProgressBar::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void ProgressBar::OnRelayout(const Vector2& size, RelayoutContainer& container) { + Vector2 trackSize(size); + mDomain = CalcDomain(size); - Vector2 trackSize( size ); - mDomain = CalcDomain( size ); - - trackSize.width = std::max( 0.0f, size.width ); // Ensure we don't go negative + trackSize.width = std::max(0.0f, size.width); // Ensure we don't go negative - Toolkit::Visual::Base trackVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::TRACK_VISUAL ); - Toolkit::Visual::Base labelVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::LABEL_VISUAL ); - Toolkit::Visual::Base indeterminateVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL ); + Toolkit::Visual::Base trackVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::TRACK_VISUAL); + Toolkit::Visual::Base labelVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::LABEL_VISUAL); + Toolkit::Visual::Base indeterminateVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL); - if( trackVisual ) + if(trackVisual) { Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, trackSize ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, trackSize) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)); - trackVisual.SetTransformAndSize( visualTransform, trackSize ); + trackVisual.SetTransformAndSize(visualTransform, trackSize); } - ApplyProgressToVisualTransform( mSecondaryProgressValue, trackSize, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL ); + ApplyProgressToVisualTransform(mSecondaryProgressValue, trackSize, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL); - ApplyProgressToVisualTransform( mProgressValue, trackSize, Toolkit::ProgressBar::Property::PROGRESS_VISUAL ); + ApplyProgressToVisualTransform(mProgressValue, trackSize, Toolkit::ProgressBar::Property::PROGRESS_VISUAL); - if( labelVisual ) + if(labelVisual) { Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, trackSize ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ); - labelVisual.SetTransformAndSize( visualTransform, trackSize ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, trackSize) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)); + labelVisual.SetTransformAndSize(visualTransform, trackSize); } - if( indeterminateVisual ) + if(indeterminateVisual) { Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, trackSize ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ); - indeterminateVisual.SetTransformAndSize( visualTransform, trackSize ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, trackSize) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)); + indeterminateVisual.SetTransformAndSize(visualTransform, trackSize); } - } Vector3 ProgressBar::GetNaturalSize() { // Return the bigger size after comparing trackVisual naturalSize and labelVisual naturalSize - Toolkit::Visual::Base trackVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::TRACK_VISUAL ); - Toolkit::Visual::Base labelVisual = DevelControl::GetVisual( *this, Toolkit::ProgressBar::Property::LABEL_VISUAL ); + Toolkit::Visual::Base trackVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::TRACK_VISUAL); + Toolkit::Visual::Base labelVisual = DevelControl::GetVisual(*this, Toolkit::ProgressBar::Property::LABEL_VISUAL); Size trackSize; Size labelSize; - if ( trackVisual ) + if(trackVisual) { - trackVisual.GetNaturalSize( trackSize ); + trackVisual.GetNaturalSize(trackSize); } - if ( labelVisual ) + if(labelVisual) { - labelVisual.GetNaturalSize( labelSize ); + labelVisual.GetNaturalSize(labelSize); } Vector3 naturalSize; - naturalSize.width = ( trackSize.width > labelSize.width ) ? trackSize.width: labelSize.width; - naturalSize.height = ( trackSize.height > labelSize.height ) ? trackSize.height: labelSize.height; + naturalSize.width = (trackSize.width > labelSize.width) ? trackSize.width : labelSize.width; + naturalSize.height = (trackSize.height > labelSize.height) ? trackSize.height : labelSize.height; return naturalSize; } -ProgressBar::Domain ProgressBar::CalcDomain( const Vector2& currentSize ) +ProgressBar::Domain ProgressBar::CalcDomain(const Vector2& currentSize) { - return Domain( Vector2( 0.0f, 0.0f ), currentSize ); + return Domain(Vector2(0.0f, 0.0f), currentSize); } Toolkit::ProgressBar::ValueChangedSignalType& ProgressBar::ValueChangedSignal() @@ -258,21 +254,21 @@ Toolkit::ProgressBar::ValueChangedSignalType& ProgressBar::ValueChangedSignal() return mValueChangedSignal; } -void ProgressBar::SetProgressValue( float value ) +void ProgressBar::SetProgressValue(float value) { // update the progress bar value (taking float precision errors into account) // TODO : it seems 0.0f cannot into this statement. - if( ( mProgressValue != value ) && - ( ( value >= DEFAULT_LOWER_BOUND ) || ( Equals( value, DEFAULT_LOWER_BOUND ) ) ) && - ( ( value <= DEFAULT_UPPER_BOUND ) || ( Equals( value, DEFAULT_UPPER_BOUND ) ) ) ) + if((mProgressValue != value) && + ((value >= DEFAULT_LOWER_BOUND) || (Equals(value, DEFAULT_LOWER_BOUND))) && + ((value <= DEFAULT_UPPER_BOUND) || (Equals(value, DEFAULT_UPPER_BOUND)))) { - mProgressValue = Clamp( value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND ); + mProgressValue = Clamp(value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); - ApplyProgressToVisual( mProgressValue, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, ProgressDepthIndex::PROGRESS_VISUAL ); + ApplyProgressToVisual(mProgressValue, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, ProgressDepthIndex::PROGRESS_VISUAL); - Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast( Self() ); - mValueChangedSignal.Emit( self, mProgressValue, mSecondaryProgressValue ); - if (Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) + Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast(Self()); + mValueChangedSignal.Emit(self, mProgressValue, mSecondaryProgressValue); + if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) { Control::Impl::GetAccessibilityObject(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::VALUE); } @@ -285,20 +281,20 @@ float ProgressBar::GetProgressValue() const return mProgressValue; } -void ProgressBar::SetSecondaryProgressValue( float value ) +void ProgressBar::SetSecondaryProgressValue(float value) { // update the progress bar value (taking float precision errors into account) // TODO : it seems 0.0f cannot into this statement. - if( ( mSecondaryProgressValue != value ) && - ( ( value >= DEFAULT_LOWER_BOUND ) || ( Equals( value, DEFAULT_LOWER_BOUND ) ) ) && - ( ( value <= DEFAULT_UPPER_BOUND ) || ( Equals( value, DEFAULT_UPPER_BOUND ) ) ) ) + if((mSecondaryProgressValue != value) && + ((value >= DEFAULT_LOWER_BOUND) || (Equals(value, DEFAULT_LOWER_BOUND))) && + ((value <= DEFAULT_UPPER_BOUND) || (Equals(value, DEFAULT_UPPER_BOUND)))) { - mSecondaryProgressValue = Clamp( value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND ); + mSecondaryProgressValue = Clamp(value, DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); - ApplyProgressToVisual( mSecondaryProgressValue, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL ); + ApplyProgressToVisual(mSecondaryProgressValue, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL); - Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast( Self() ); - mValueChangedSignal.Emit( self, mProgressValue, mSecondaryProgressValue ); + Toolkit::ProgressBar self = Toolkit::ProgressBar::DownCast(Self()); + mValueChangedSignal.Emit(self, mProgressValue, mSecondaryProgressValue); RelayoutRequest(); } @@ -309,30 +305,30 @@ float ProgressBar::GetSecondaryProgressValue() const return mSecondaryProgressValue; } -void ProgressBar::SetIndeterminate( bool value ) +void ProgressBar::SetIndeterminate(bool value) { mIndeterminate = value; - DevelControl::EnableVisual( *this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL, mIndeterminate ); + DevelControl::EnableVisual(*this, Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL, mIndeterminate); - if( mIndeterminate ) + if(mIndeterminate) { RelayoutRequest(); - if( mIndeterminateVisualTransition ) + if(mIndeterminateVisualTransition) { PlayIndeterminateVisualTransition(); } } else { - if( mIndeterminateVisualAni ) + if(mIndeterminateVisualAni) { mIndeterminateVisualAni.Stop(); } // Restore previous visual data after animation finished. - RestoreVisualProperties( this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap, ProgressDepthIndex::TRACK_VISUAL ); - RestoreVisualProperties( this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL ); - RestoreVisualProperties( this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap, ProgressDepthIndex::PROGRESS_VISUAL ); + RestoreVisualProperties(this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap, ProgressDepthIndex::TRACK_VISUAL); + RestoreVisualProperties(this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL); + RestoreVisualProperties(this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap, ProgressDepthIndex::PROGRESS_VISUAL); RelayoutRequest(); } @@ -343,10 +339,10 @@ bool ProgressBar::GetIndeterminate() const return mIndeterminate; } -void ProgressBar::SetIndeterminateVisualTransition( Toolkit::TransitionData transition ) +void ProgressBar::SetIndeterminateVisualTransition(Toolkit::TransitionData transition) { mIndeterminateVisualTransition = transition; - if( mIndeterminate ) + if(mIndeterminate) { PlayIndeterminateVisualTransition(); } @@ -355,36 +351,36 @@ void ProgressBar::SetIndeterminateVisualTransition( Toolkit::TransitionData tran void ProgressBar::PlayIndeterminateVisualTransition() { // Store current visual data before animation changes it. - BackupVisualProperties( this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap ); - BackupVisualProperties( this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap ); - BackupVisualProperties( this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap ); + BackupVisualProperties(this, Toolkit::ProgressBar::Property::TRACK_VISUAL, mTrackVisualMap); + BackupVisualProperties(this, Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL, mSecondaryProgressVisualMap); + BackupVisualProperties(this, Toolkit::ProgressBar::Property::PROGRESS_VISUAL, mProgressVisualMap); - if( mIndeterminateVisualAni ) + if(mIndeterminateVisualAni) { mIndeterminateVisualAni.Stop(); mIndeterminateVisualAni.Clear(); } - mIndeterminateVisualAni = DevelControl::CreateTransition( *this, mIndeterminateVisualTransition ); + mIndeterminateVisualAni = DevelControl::CreateTransition(*this, mIndeterminateVisualTransition); - if( mIndeterminate && mIndeterminateVisualAni ) + if(mIndeterminate && mIndeterminateVisualAni) { mIndeterminateVisualAni.SetLooping(true); mIndeterminateVisualAni.Play(); } } -Toolkit::TransitionData ProgressBar::ConvertPropertyToTransition( const Property::Value& value ) +Toolkit::TransitionData ProgressBar::ConvertPropertyToTransition(const Property::Value& value) { Toolkit::TransitionData transitionData; - if( value.GetType() == Property::ARRAY ) + if(value.GetType() == Property::ARRAY) { - transitionData = Toolkit::TransitionData::New( *value.GetArray() ); + transitionData = Toolkit::TransitionData::New(*value.GetArray()); } - else if( value.GetType() == Property::MAP ) + else if(value.GetType() == Property::MAP) { - transitionData = Toolkit::TransitionData::New( *value.GetMap() ); + transitionData = Toolkit::TransitionData::New(*value.GetMap()); } return transitionData; @@ -398,112 +394,111 @@ Toolkit::TransitionData ProgressBar::ConvertPropertyToTransition( const Property * 4) Unregister visual if empty map was provided. This is the method to remove a visual */ -void ProgressBar::CreateVisualsForComponent( Property::Index index, const Property::Value& value, const int visualDepth ) +void ProgressBar::CreateVisualsForComponent(Property::Index index, const Property::Value& value, const int visualDepth) { Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get(); - Toolkit::Visual::Base progressVisual; + Toolkit::Visual::Base progressVisual; std::string imageUrl; - if( value.Get( imageUrl ) ) + if(value.Get(imageUrl)) { - if ( !imageUrl.empty() ) + if(!imageUrl.empty()) { - progressVisual = visualFactory.CreateVisual( imageUrl, ImageDimensions() ); + progressVisual = visualFactory.CreateVisual(imageUrl, ImageDimensions()); } } else // Does this code make text-visual can be accepted as visual? { // if its not a string then get a Property::Map from the property if possible. - const Property::Map *map = value.GetMap(); - if( map && !map->Empty() ) // Empty map results in current visual removal. + const Property::Map* map = value.GetMap(); + if(map && !map->Empty()) // Empty map results in current visual removal. { - progressVisual = visualFactory.CreateVisual( *map ); + progressVisual = visualFactory.CreateVisual(*map); } } - if ( progressVisual ) + if(progressVisual) { - if( index == Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL ) + if(index == Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL) { - DevelControl::RegisterVisual( *this, index, progressVisual, mIndeterminate, visualDepth ); + DevelControl::RegisterVisual(*this, index, progressVisual, mIndeterminate, visualDepth); } else { - DevelControl::RegisterVisual( *this, index, progressVisual, true, visualDepth ); + DevelControl::RegisterVisual(*this, index, progressVisual, true, visualDepth); } } else { - DevelControl::UnregisterVisual( *this, index ); + DevelControl::UnregisterVisual(*this, index); } } -bool ProgressBar::GetPropertyMapForVisual( Property::Index visualIndex, Property::Map& retreivedMap ) const +bool ProgressBar::GetPropertyMapForVisual(Property::Index visualIndex, Property::Map& retreivedMap) const { - bool success = false; - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, visualIndex ); + bool success = false; + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, visualIndex); - if ( visual ) + if(visual) { - visual.CreatePropertyMap( retreivedMap ); + visual.CreatePropertyMap(retreivedMap); success = true; } return success; } - -void ProgressBar::ApplyProgressToVisual( float progress, Property::Index index, int depth ) +void ProgressBar::ApplyProgressToVisual(float progress, Property::Index index, int depth) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, index ); + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, index); - if( visual && static_cast( visual.GetType() ) == DevelVisual::ARC && !mIndeterminate ) + if(visual && static_cast(visual.GetType()) == DevelVisual::ARC && !mIndeterminate) { - Visual::Base& visualImpl = Toolkit::GetImplementation( visual ); + Visual::Base& visualImpl = Toolkit::GetImplementation(visual); Property::Map map; - map[ Toolkit::DevelArcVisual::Property::SWEEP_ANGLE ] = Property::Value( 360.0f * progress ); + map[Toolkit::DevelArcVisual::Property::SWEEP_ANGLE] = Property::Value(360.0f * progress); - visualImpl.SetProperties( map ); + visualImpl.SetProperties(map); - DevelControl::UnregisterVisual( *this, index ); - DevelControl::RegisterVisual( *this, index, visual, true, depth ); + DevelControl::UnregisterVisual(*this, index); + DevelControl::RegisterVisual(*this, index, visual, true, depth); } } -void ProgressBar::ApplyProgressToVisualTransform( float progress, Vector2 trackSize, Property::Index index ) +void ProgressBar::ApplyProgressToVisualTransform(float progress, Vector2 trackSize, Property::Index index) { - Toolkit::Visual::Base visual = DevelControl::GetVisual( *this, index ); + Toolkit::Visual::Base visual = DevelControl::GetVisual(*this, index); - if( visual ) + if(visual) { Property::Map visualTransform; - if( static_cast( visual.GetType() ) != DevelVisual::ARC ) + if(static_cast(visual.GetType()) != DevelVisual::ARC) { - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, Vector2( mDomain.from.x + progress * ( mDomain.to.x - mDomain.from.x ), trackSize.height ) ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN ); + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, Vector2(mDomain.from.x + progress * (mDomain.to.x - mDomain.from.x), trackSize.height)) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN); } - visual.SetTransformAndSize( visualTransform, trackSize ); + visual.SetTransformAndSize(visualTransform, trackSize); } } // Static class method to support script connecting signals -bool ProgressBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool ProgressBar::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected = true; - Toolkit::ProgressBar ProgressBar = Toolkit::ProgressBar::DownCast( handle ); + bool connected = true; + Toolkit::ProgressBar ProgressBar = Toolkit::ProgressBar::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_VALUE_CHANGED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_VALUE_CHANGED)) { - ProgressBar.ValueChangedSignal().Connect( tracker, functor ); + ProgressBar.ValueChangedSignal().Connect(tracker, functor); } else { @@ -514,118 +509,118 @@ bool ProgressBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterfac return connected; } -void ProgressBar::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) +void ProgressBar::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value) { - Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast(Dali::BaseHandle(object)); - if ( progressBar ) + if(progressBar) { - ProgressBar& progressBarImpl( GetImpl( progressBar ) ); + ProgressBar& progressBarImpl(GetImpl(progressBar)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::ProgressBar::Property::TRACK_VISUAL: { - progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::TRACK_VISUAL ); + progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::TRACK_VISUAL); break; } case Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VISUAL: { - progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL ); - progressBarImpl.ApplyProgressToVisual( progressBarImpl.mSecondaryProgressValue, propertyIndex, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL ); + progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL); + progressBarImpl.ApplyProgressToVisual(progressBarImpl.mSecondaryProgressValue, propertyIndex, ProgressDepthIndex::SECONDARY_PROGRESS_VISUAL); break; } case Toolkit::ProgressBar::Property::PROGRESS_VISUAL: { - progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::PROGRESS_VISUAL ); - progressBarImpl.ApplyProgressToVisual( progressBarImpl.mProgressValue, propertyIndex, ProgressDepthIndex::PROGRESS_VISUAL ); + progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::PROGRESS_VISUAL); + progressBarImpl.ApplyProgressToVisual(progressBarImpl.mProgressValue, propertyIndex, ProgressDepthIndex::PROGRESS_VISUAL); break; } case Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL: { - progressBarImpl.CreateVisualsForComponent( propertyIndex, value, ProgressDepthIndex::INDETERMINATE_VISUAL ); + progressBarImpl.CreateVisualsForComponent(propertyIndex, value, ProgressDepthIndex::INDETERMINATE_VISUAL); break; } case Toolkit::ProgressBar::Property::LABEL_VISUAL: { Property::Map map; - std::string textString; + std::string textString; - if ( value.Get( textString ) ) + if(value.Get(textString)) { // set new text string as TEXT property - Property::Map newTextMap; - Toolkit::Visual::Base label = DevelControl::GetVisual( progressBarImpl, Toolkit::ProgressBar::Property::LABEL_VISUAL ); + Property::Map newTextMap; + Toolkit::Visual::Base label = DevelControl::GetVisual(progressBarImpl, Toolkit::ProgressBar::Property::LABEL_VISUAL); - if( label ) + if(label) { - label.CreatePropertyMap( map ); + label.CreatePropertyMap(map); } // if LABEL_VISUAL doesn't set before, add Visual property "TYPE" to create new text Visual - if( map.Empty() ) + if(map.Empty()) { - newTextMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT ); - newTextMap.Add( Toolkit::TextVisual::Property::POINT_SIZE, DEFAULT_FONT_SIZE ); + newTextMap.Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT); + newTextMap.Add(Toolkit::TextVisual::Property::POINT_SIZE, DEFAULT_FONT_SIZE); } - newTextMap.Add( Toolkit::TextVisual::Property::TEXT, textString ); + newTextMap.Add(Toolkit::TextVisual::Property::TEXT, textString); - map.Merge( newTextMap ); + map.Merge(newTextMap); } else { - value.Get( map ); + value.Get(map); } - if( !map.Empty() ) + if(!map.Empty()) { - progressBarImpl.CreateVisualsForComponent( propertyIndex, map, ProgressDepthIndex::LABEL_VISUAL ); + progressBarImpl.CreateVisualsForComponent(propertyIndex, map, ProgressDepthIndex::LABEL_VISUAL); } break; } case Toolkit::ProgressBar::Property::PROGRESS_VALUE: { - progressBarImpl.SetProgressValue( value.Get< float >() ); + progressBarImpl.SetProgressValue(value.Get()); break; } case Toolkit::ProgressBar::Property::SECONDARY_PROGRESS_VALUE: { - progressBarImpl.SetSecondaryProgressValue( value.Get< float >() ); + progressBarImpl.SetSecondaryProgressValue(value.Get()); break; } case Toolkit::ProgressBar::Property::INDETERMINATE: { - progressBarImpl.SetIndeterminate( value.Get< bool >() ); + progressBarImpl.SetIndeterminate(value.Get()); break; } case Toolkit::ProgressBar::Property::INDETERMINATE_VISUAL_ANIMATION: { - progressBarImpl.SetIndeterminateVisualTransition( progressBarImpl.ConvertPropertyToTransition( value ) ); + progressBarImpl.SetIndeterminateVisualTransition(progressBarImpl.ConvertPropertyToTransition(value)); break; } } } } -Property::Value ProgressBar::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value ProgressBar::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ProgressBar progressBar = Toolkit::ProgressBar::DownCast(Dali::BaseHandle(object)); - if ( progressBar ) + if(progressBar) { - ProgressBar& progressBarImpl( GetImpl( progressBar ) ); + ProgressBar& progressBarImpl(GetImpl(progressBar)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::ProgressBar::Property::TRACK_VISUAL: case Toolkit::ProgressBar::Property::PROGRESS_VISUAL: @@ -634,7 +629,7 @@ Property::Value ProgressBar::GetProperty( BaseObject* object, Property::Index pr case Toolkit::ProgressBar::Property::LABEL_VISUAL: { Property::Map visualProperty; - if ( progressBarImpl.GetPropertyMapForVisual( propertyIndex, visualProperty ) ) + if(progressBarImpl.GetPropertyMapForVisual(propertyIndex, visualProperty)) { value = visualProperty; } @@ -669,39 +664,48 @@ Property::Value ProgressBar::GetProperty( BaseObject* object, Property::Index pr return value; } -void ProgressBar::OnSceneConnection( int depth ) +void ProgressBar::OnSceneConnection(int depth) { // Chain up first (ensures visuals are ready to draw) - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); - if( mIndeterminate ) + if(mIndeterminate) { PlayIndeterminateVisualTransition(); } } -double ProgressBar::AccessibleImpl::GetMinimum() { return DEFAULT_LOWER_BOUND; } +double ProgressBar::AccessibleImpl::GetMinimum() +{ + return DEFAULT_LOWER_BOUND; +} double ProgressBar::AccessibleImpl::GetCurrent() { - auto p = Toolkit::ProgressBar::DownCast( self ); - return p.GetProperty( Toolkit::ProgressBar::Property::PROGRESS_VALUE ) - .Get< float >(); + auto p = Toolkit::ProgressBar::DownCast(self); + return p.GetProperty(Toolkit::ProgressBar::Property::PROGRESS_VALUE) + .Get(); } -double ProgressBar::AccessibleImpl::GetMaximum() { return DEFAULT_UPPER_BOUND; } +double ProgressBar::AccessibleImpl::GetMaximum() +{ + return DEFAULT_UPPER_BOUND; +} -bool ProgressBar::AccessibleImpl::SetCurrent( double current ) +bool ProgressBar::AccessibleImpl::SetCurrent(double current) { - if( current < GetMinimum() || current > GetMaximum() ) + if(current < GetMinimum() || current > GetMaximum()) return false; - auto p = Toolkit::ProgressBar::DownCast( self ); - p.SetProperty( Toolkit::ProgressBar::Property::PROGRESS_VALUE, - static_cast< float >( current ) ); + auto p = Toolkit::ProgressBar::DownCast(self); + p.SetProperty(Toolkit::ProgressBar::Property::PROGRESS_VALUE, + static_cast(current)); return true; } -double ProgressBar::AccessibleImpl::GetMinimumIncrement() { return 0.0; } +double ProgressBar::AccessibleImpl::GetMinimumIncrement() +{ + return 0.0; +} } // namespace Internal diff --git a/dali-toolkit/internal/controls/scene3d-view/gltf-loader.cpp b/dali-toolkit/internal/controls/scene3d-view/gltf-loader.cpp index 959a39f..95f54f1 100644 --- a/dali-toolkit/internal/controls/scene3d-view/gltf-loader.cpp +++ b/dali-toolkit/internal/controls/scene3d-view/gltf-loader.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,117 +19,112 @@ #include // EXTERNAL INCLUDES -#include -#include -#include #include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace Gltf { - namespace { - // Utility functions -const TreeNode* Tidx( const TreeNode *node, uint32_t index ) +const TreeNode* Tidx(const TreeNode* node, uint32_t index) { uint32_t i = 0; - for( auto it = node->CBegin(), end = node->CEnd(); it != end; ++it, ++i ) + for(auto it = node->CBegin(), end = node->CEnd(); it != end; ++it, ++i) { - if( i == index ) + if(i == index) { - return &( ( *it ).second ); + return &((*it).second); } } return NULL; } -bool ReadBool( const TreeNode* node, bool& num ) +bool ReadBool(const TreeNode* node, bool& num) { - if( !node ) + if(!node) { return false; } bool returnValue = false; - if( node->GetType() == TreeNode::BOOLEAN ) + if(node->GetType() == TreeNode::BOOLEAN) { - num = node->GetBoolean(); + num = node->GetBoolean(); returnValue = true; } return returnValue; } -bool ReadInt( const TreeNode* node, int32_t& num ) +bool ReadInt(const TreeNode* node, int32_t& num) { - if( !node ) + if(!node) { return false; } bool returnValue = false; - if( node->GetType() == TreeNode::INTEGER ) + if(node->GetType() == TreeNode::INTEGER) { - num = node->GetInteger(); + num = node->GetInteger(); returnValue = true; } - else if( node->GetType() == TreeNode::FLOAT ) + else if(node->GetType() == TreeNode::FLOAT) { - num = node->GetFloat(); + num = node->GetFloat(); returnValue = true; } return returnValue; } -bool ReadFloat( const TreeNode* node, float& num ) +bool ReadFloat(const TreeNode* node, float& num) { - if( !node ) + if(!node) { return false; } bool returnValue = false; - if( node->GetType() == TreeNode::FLOAT ) + if(node->GetType() == TreeNode::FLOAT) { - num = node->GetFloat(); + num = node->GetFloat(); returnValue = true; } - else if( node->GetType() == TreeNode::INTEGER ) + else if(node->GetType() == TreeNode::INTEGER) { int32_t tempNum = 0; - ReadInt( node, tempNum ); - num = static_cast( tempNum ); + ReadInt(node, tempNum); + num = static_cast(tempNum); returnValue = true; } return returnValue; } -bool ReadVector( const TreeNode* node, float* num, uint32_t size ) +bool ReadVector(const TreeNode* node, float* num, uint32_t size) { - if( !node ) + if(!node) { return false; } bool returnValue = false; - if( ( node->Size() >= size ) && ( node->GetType() == TreeNode::ARRAY ) ) + if((node->Size() >= size) && (node->GetType() == TreeNode::ARRAY)) { uint32_t offset = 0u; - for( auto it = node->CBegin(); offset < size; ++it, ++offset ) + for(auto it = node->CBegin(); offset < size; ++it, ++offset) { - const TreeNode& coord = ( *it ).second; - if( !ReadFloat( &coord, *( num + offset ) ) ) + const TreeNode& coord = (*it).second; + if(!ReadFloat(&coord, *(num + offset))) { return false; } @@ -140,147 +135,146 @@ bool ReadVector( const TreeNode* node, float* num, uint32_t size ) return returnValue; } -bool ReadString( const TreeNode* node, std::string& strValue ) +bool ReadString(const TreeNode* node, std::string& strValue) { - if( !node ) + if(!node) { return false; } bool returnValue = false; - if( node->GetType() == TreeNode::STRING ) + if(node->GetType() == TreeNode::STRING) { - strValue = node->GetString(); + strValue = node->GetString(); returnValue = true; } return returnValue; } -template -float IntToFloat( T element, bool normalize ) +template +float IntToFloat(T element, bool normalize) { - if( !normalize ) + if(!normalize) { - return static_cast( element ); + return static_cast(element); } - if( std::is_same::value ) + if(std::is_same::value) { - return std::max( static_cast( element ) / 127.0, -1.0 ); + return std::max(static_cast(element) / 127.0, -1.0); } - if( std::is_same::value ) + if(std::is_same::value) { - return static_cast( element ) / 255.0; + return static_cast(element) / 255.0; } - if( std::is_same::value ) + if(std::is_same::value) { - return std::max( static_cast( element ) / 32767.0, -1.0 ); + return std::max(static_cast(element) / 32767.0, -1.0); } - if( std::is_same::value ) + if(std::is_same::value) { - return static_cast( element ) / 65535.0; + return static_cast(element) / 65535.0; } return -1.0; } -template -void FitBuffer( Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize ) +template +void FitBuffer(Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize) { - bufferDestination.Resize( bufferSize ); + bufferDestination.Resize(bufferSize); int32_t count = bufferSource.Size() / elementNumOfByteStride; - for( int32_t i = 0; i( bufferSource[i * elementNumOfByteStride] ); + bufferDestination[i] = static_cast(bufferSource[i * elementNumOfByteStride]); } } -template -void FitBuffer( Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize ) +template +void FitBuffer(Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize) { - bufferDestination.Resize( bufferSize ); + bufferDestination.Resize(bufferSize); int32_t count = bufferSource.Size() / elementNumOfByteStride; - for( int32_t i = 0; i -void FitBuffer( Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize ) +template +void FitBuffer(Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize) { - bufferDestination.Resize( bufferSize ); + bufferDestination.Resize(bufferSize); int32_t count = bufferSource.Size() / elementNumOfByteStride; - for( int32_t i = 0; i -void FitBuffer( Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize ) +template +void FitBuffer(Dali::Vector& bufferDestination, Dali::Vector& bufferSource, int32_t bufferSize, int32_t elementNumOfByteStride, bool normalize) { - bufferDestination.Resize( bufferSize ); + bufferDestination.Resize(bufferSize); int32_t count = bufferSource.Size() / elementNumOfByteStride; - for( int32_t i = 0; i -bool ReadBinFile( Vector &dataBuffer, std::string url, int32_t offset, int32_t count ) +template +bool ReadBinFile(Vector& dataBuffer, std::string url, int32_t offset, int32_t count) { - Dali::FileStream fileStream( url, FileStream::READ | FileStream::BINARY ); - FILE* fp = fileStream.GetFile(); - if( !fp ) + Dali::FileStream fileStream(url, FileStream::READ | FileStream::BINARY); + FILE* fp = fileStream.GetFile(); + if(!fp) { return false; } - dataBuffer.Resize( count ); + dataBuffer.Resize(count); ssize_t result = -1; - if( !fseek( fp, offset, SEEK_SET ) ) + if(!fseek(fp, offset, SEEK_SET)) { - result = fread( &dataBuffer[0], sizeof( T ), count, fp ); + result = fread(&dataBuffer[0], sizeof(T), count, fp); } - return ( result >= 0 ); + return (result >= 0); } -template -void LoadDataFromAccessor( int32_t accessorIdx, Dali::Vector& bufferData, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray ) +template +void LoadDataFromAccessor(int32_t accessorIdx, Dali::Vector& bufferData, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray) { - AccessorInfo accessor = accessorArray[accessorIdx]; + AccessorInfo accessor = accessorArray[accessorIdx]; BufferViewInfo bufferView = bufferViewArray[accessor.bufferView]; - std::string load_uri = bufferArray[bufferView.buffer].uri; + std::string load_uri = bufferArray[bufferView.buffer].uri; // In the glTF 2.0 Specification, 5121 is UNSIGNED BYTE, 5123 is UNSIGNED SHORT - int32_t elementByteSize = ( accessor.componentType <= 5121 ) ? 1 : - ( ( accessor.componentType <= 5123 ) ? 2 : 4 ); - int32_t elementNum = 1; - if( accessor.type == "VEC2" ) + int32_t elementByteSize = (accessor.componentType <= 5121) ? 1 : ((accessor.componentType <= 5123) ? 2 : 4); + int32_t elementNum = 1; + if(accessor.type == "VEC2") { elementNum = 2; } - else if( accessor.type == "VEC3" ) + else if(accessor.type == "VEC3") { elementNum = 3; } - else if( accessor.type == "VEC4" || accessor.type == "MAT2" ) + else if(accessor.type == "VEC4" || accessor.type == "MAT2") { elementNum = 4; } - else if( accessor.type == "MAT3" ) + else if(accessor.type == "MAT3") { elementNum = 9; } - else if( accessor.type == "MAT4" ) + else if(accessor.type == "MAT4") { elementNum = 16; } @@ -289,7 +283,7 @@ void LoadDataFromAccessor( int32_t accessorIdx, Dali::Vector& bufferData, std elementNum = 1; } int32_t elementNumOfByteStride = elementNum; - if( bufferView.byteStride > 0 ) + if(bufferView.byteStride > 0) { elementNumOfByteStride = bufferView.byteStride / elementByteSize; } @@ -304,65 +298,65 @@ void LoadDataFromAccessor( int32_t accessorIdx, Dali::Vector& bufferData, std * 5125 : UNSIGNED_INT * 5126 : FLOAT */ - if( accessor.componentType == 5120 ) + if(accessor.componentType == 5120) { Dali::Vector inputBufferData; - ReadBinFile( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count ); - FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized ); + ReadBinFile(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count); + FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized); } - else if( accessor.componentType == 5121 ) + else if(accessor.componentType == 5121) { Dali::Vector inputBufferData; - ReadBinFile( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count ); - FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized ); + ReadBinFile(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count); + FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized); } - else if( accessor.componentType == 5122 ) + else if(accessor.componentType == 5122) { Dali::Vector inputBufferData; - ReadBinFile( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count ); - FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized ); + ReadBinFile(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count); + FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized); } - else if( accessor.componentType == 5123 ) + else if(accessor.componentType == 5123) { Dali::Vector inputBufferData; - ReadBinFile( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count ); - FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized ); + ReadBinFile(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count); + FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized); } - else if( accessor.componentType == 5125 ) + else if(accessor.componentType == 5125) { Dali::Vector inputBufferData; - ReadBinFile( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count ); - FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized ); + ReadBinFile(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count); + FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized); } - else if( accessor.componentType == 5126 ) + else if(accessor.componentType == 5126) { Dali::Vector inputBufferData; - ReadBinFile( inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count ); - FitBuffer( bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized ); + ReadBinFile(inputBufferData, path + load_uri, bufferView.byteOffset + accessor.byteOffset, elementNumOfByteStride * accessor.count); + FitBuffer(bufferData, inputBufferData, accessor.count, elementNumOfByteStride, accessor.normalized); } } -void SetMeshInfoAndCanonize( MeshInfo& meshInfo, Dali::Vector &vertexBufferData ) +void SetMeshInfoAndCanonize(MeshInfo& meshInfo, Dali::Vector& vertexBufferData) { - Vector3 pointMin( std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max() ); - Vector3 pointMax( std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min() ); - for( auto&& data : vertexBufferData ) + Vector3 pointMin(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()); + Vector3 pointMax(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()); + for(auto&& data : vertexBufferData) { - pointMin.x = std::min( data.x, pointMin.x ); - pointMin.y = std::min( data.y, pointMin.y ); - pointMin.z = std::min( data.z, pointMin.z ); + pointMin.x = std::min(data.x, pointMin.x); + pointMin.y = std::min(data.y, pointMin.y); + pointMin.z = std::min(data.z, pointMin.z); - pointMax.x = std::max( data.x, pointMax.x ); - pointMax.y = std::max( data.y, pointMax.y ); - pointMax.z = std::max( data.z, pointMax.z ); + pointMax.x = std::max(data.x, pointMax.x); + pointMax.y = std::max(data.y, pointMax.y); + pointMax.z = std::max(data.z, pointMax.z); } - meshInfo.size = pointMax - pointMin; - meshInfo.pivot.x = ( -pointMin.x ) / ( pointMax.x - pointMin.x ); - meshInfo.pivot.y = ( -pointMin.y ) / ( pointMax.y - pointMin.y ); - meshInfo.pivot.z = ( -pointMin.z ) / ( pointMax.z - pointMin.z ); + meshInfo.size = pointMax - pointMin; + meshInfo.pivot.x = (-pointMin.x) / (pointMax.x - pointMin.x); + meshInfo.pivot.y = (-pointMin.y) / (pointMax.y - pointMin.y); + meshInfo.pivot.z = (-pointMin.z) / (pointMax.z - pointMin.z); Vector3 center = meshInfo.size * 0.5 + pointMin; - for( auto&& data : vertexBufferData ) + for(auto&& data : vertexBufferData) { data = data - center; data.x = data.x / meshInfo.size.x; @@ -371,278 +365,278 @@ void SetMeshInfoAndCanonize( MeshInfo& meshInfo, Dali::Vector &ve } } -template -VertexBuffer CreateVertexBuffer( Vector bufferData, std::string map, int32_t type ) +template +VertexBuffer CreateVertexBuffer(Vector bufferData, std::string map, int32_t type) { Property::Map positionMap; positionMap[map] = type; - VertexBuffer vertexBuffer = VertexBuffer::New( positionMap ); - vertexBuffer.SetData( bufferData.Begin(), bufferData.Count() ); + VertexBuffer vertexBuffer = VertexBuffer::New(positionMap); + vertexBuffer.SetData(bufferData.Begin(), bufferData.Count()); return vertexBuffer; } -void SetVertexBufferData( MeshInfo& meshInfo, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray, int32_t accessorIdx, std::string map, int32_t type ) +void SetVertexBufferData(MeshInfo& meshInfo, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray, int32_t accessorIdx, std::string map, int32_t type) { - if( accessorIdx >= 0 ) + if(accessorIdx >= 0) { Dali::Vector bufferData; - LoadDataFromAccessor( accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray ); - SetMeshInfoAndCanonize( meshInfo, bufferData ); + LoadDataFromAccessor(accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray); + SetMeshInfoAndCanonize(meshInfo, bufferData); - VertexBuffer vertexBuffer = CreateVertexBuffer( bufferData, map, type ); - meshInfo.geometry.AddVertexBuffer( vertexBuffer ); + VertexBuffer vertexBuffer = CreateVertexBuffer(bufferData, map, type); + meshInfo.geometry.AddVertexBuffer(vertexBuffer); } } -template -void SetAttributeBufferData( MeshInfo& meshInfo, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray, int32_t accessorIdx, std::string map, int32_t type ) +template +void SetAttributeBufferData(MeshInfo& meshInfo, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray, int32_t accessorIdx, std::string map, int32_t type) { - if( accessorIdx >= 0 ) + if(accessorIdx >= 0) { Dali::Vector bufferData; - LoadDataFromAccessor( accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray ); + LoadDataFromAccessor(accessorIdx, bufferData, path, accessorArray, bufferViewArray, bufferArray); - VertexBuffer vertexBuffer = CreateVertexBuffer( bufferData, map, type ); - meshInfo.geometry.AddVertexBuffer( vertexBuffer ); + VertexBuffer vertexBuffer = CreateVertexBuffer(bufferData, map, type); + meshInfo.geometry.AddVertexBuffer(vertexBuffer); } } -void SetIndexBuffersData( MeshInfo& meshInfo, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray, int32_t indexIdx ) +void SetIndexBuffersData(MeshInfo& meshInfo, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray, int32_t indexIdx) { Dali::Vector indexBufferData; - LoadDataFromAccessor( indexIdx, indexBufferData, path, accessorArray, bufferViewArray, bufferArray ); - meshInfo.geometry.SetIndexBuffer( &indexBufferData[0], indexBufferData.Size() ); + LoadDataFromAccessor(indexIdx, indexBufferData, path, accessorArray, bufferViewArray, bufferArray); + meshInfo.geometry.SetIndexBuffer(&indexBufferData[0], indexBufferData.Size()); } template -float LoadKeyFrames( const AnimationSamplerInfo& currentSampler, const Property::Index propIndex, KeyFrames& keyframes, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray ) +float LoadKeyFrames(const AnimationSamplerInfo& currentSampler, const Property::Index propIndex, KeyFrames& keyframes, std::string path, std::vector& accessorArray, std::vector& bufferViewArray, std::vector& bufferArray) { Dali::Vector inputBufferData; - Dali::Vector outputBufferData; + Dali::Vector outputBufferData; - LoadDataFromAccessor( currentSampler.input, inputBufferData, path, accessorArray, bufferViewArray, bufferArray ); - LoadDataFromAccessor( currentSampler.output, outputBufferData, path, accessorArray, bufferViewArray, bufferArray ); + LoadDataFromAccessor(currentSampler.input, inputBufferData, path, accessorArray, bufferViewArray, bufferArray); + LoadDataFromAccessor(currentSampler.output, outputBufferData, path, accessorArray, bufferViewArray, bufferArray); - uint32_t keyframeNum = inputBufferData.Size(); - float lengthAnimation = inputBufferData[inputBufferData.Size() - 1]; - for( uint32_t i = 0; i < keyframeNum; i++ ) + uint32_t keyframeNum = inputBufferData.Size(); + float lengthAnimation = inputBufferData[inputBufferData.Size() - 1]; + for(uint32_t i = 0; i < keyframeNum; i++) { - if( propIndex == Dali::Actor::Property::ORIENTATION ) + if(propIndex == Dali::Actor::Property::ORIENTATION) { - Vector4 vectorOrientation( outputBufferData[i] ); - float vW = vectorOrientation.w; - vW = ( vW < 0.0f ) ? std::max( vW, -1.0f ) : std::min( vW, 1.0f ); + Vector4 vectorOrientation(outputBufferData[i]); + float vW = vectorOrientation.w; + vW = (vW < 0.0f) ? std::max(vW, -1.0f) : std::min(vW, 1.0f); vectorOrientation.w = vW; - keyframes.Add( inputBufferData[i] / lengthAnimation, Quaternion( Vector4( vectorOrientation ) ) ); + keyframes.Add(inputBufferData[i] / lengthAnimation, Quaternion(Vector4(vectorOrientation))); } - else if( propIndex == Dali::Actor::Property::POSITION ) + else if(propIndex == Dali::Actor::Property::POSITION) { - keyframes.Add( inputBufferData[i] / lengthAnimation, Vector3( outputBufferData[i] ) ); + keyframes.Add(inputBufferData[i] / lengthAnimation, Vector3(outputBufferData[i])); } - else if( propIndex == Dali::Actor::Property::SCALE ) + else if(propIndex == Dali::Actor::Property::SCALE) { - keyframes.Add( inputBufferData[i] / lengthAnimation, Vector3( outputBufferData[i] ) ); + keyframes.Add(inputBufferData[i] / lengthAnimation, Vector3(outputBufferData[i])); } } return lengthAnimation; } -bool LoadBuffer( const TreeNode& buffer, std::vector& bufferArray ) +bool LoadBuffer(const TreeNode& buffer, std::vector& bufferArray) { BufferInfo bufferInfo; - const TreeNode* uriNode = buffer.GetChild( "uri" ); - if( uriNode ) + const TreeNode* uriNode = buffer.GetChild("uri"); + if(uriNode) { - ReadString( uriNode, bufferInfo.uri ); + ReadString(uriNode, bufferInfo.uri); } - const TreeNode* byteLengthNode = buffer.GetChild( "byteLength" ); - if( byteLengthNode ) + const TreeNode* byteLengthNode = buffer.GetChild("byteLength"); + if(byteLengthNode) { - ReadInt( byteLengthNode, bufferInfo.byteLength ); - if( bufferInfo.byteLength < 0 ) + ReadInt(byteLengthNode, bufferInfo.byteLength); + if(bufferInfo.byteLength < 0) { return false; } } - const TreeNode* nameNode = buffer.GetChild( "name" ); - if( nameNode ) + const TreeNode* nameNode = buffer.GetChild("name"); + if(nameNode) { - ReadString( nameNode, bufferInfo.name ); + ReadString(nameNode, bufferInfo.name); } - bufferArray.push_back( bufferInfo ); + bufferArray.push_back(bufferInfo); return true; } -bool LoadBufferView( const TreeNode& buffer, std::vector& bufferViewArray ) +bool LoadBufferView(const TreeNode& buffer, std::vector& bufferViewArray) { BufferViewInfo bufferViewInfo; - const TreeNode* bufferNode = buffer.GetChild( "buffer" ); - if( bufferNode ) + const TreeNode* bufferNode = buffer.GetChild("buffer"); + if(bufferNode) { - ReadInt( bufferNode, bufferViewInfo.buffer ); - if( bufferViewInfo.buffer < 0 ) + ReadInt(bufferNode, bufferViewInfo.buffer); + if(bufferViewInfo.buffer < 0) { return false; } } - const TreeNode* byteOffsetNode = buffer.GetChild( "byteOffset" ); - if( byteOffsetNode ) + const TreeNode* byteOffsetNode = buffer.GetChild("byteOffset"); + if(byteOffsetNode) { - ReadInt( byteOffsetNode, bufferViewInfo.byteOffset ); + ReadInt(byteOffsetNode, bufferViewInfo.byteOffset); } - const TreeNode* byteLengthNode = buffer.GetChild( "byteLength" ); - if( byteLengthNode ) + const TreeNode* byteLengthNode = buffer.GetChild("byteLength"); + if(byteLengthNode) { - ReadInt( byteLengthNode, bufferViewInfo.byteLength ); - if( bufferViewInfo.byteLength < 0 ) + ReadInt(byteLengthNode, bufferViewInfo.byteLength); + if(bufferViewInfo.byteLength < 0) { return false; } } - const TreeNode* byteStrideNode = buffer.GetChild( "byteStride" ); - if( byteStrideNode ) + const TreeNode* byteStrideNode = buffer.GetChild("byteStride"); + if(byteStrideNode) { - ReadInt( byteStrideNode, bufferViewInfo.byteStride ); + ReadInt(byteStrideNode, bufferViewInfo.byteStride); } - const TreeNode* targetNode = buffer.GetChild( "target" ); - if( targetNode ) + const TreeNode* targetNode = buffer.GetChild("target"); + if(targetNode) { - ReadInt( targetNode, bufferViewInfo.target ); + ReadInt(targetNode, bufferViewInfo.target); } - const TreeNode* nameNode = buffer.GetChild( "name" ); - if( nameNode ) + const TreeNode* nameNode = buffer.GetChild("name"); + if(nameNode) { - ReadString( nameNode, bufferViewInfo.name ); + ReadString(nameNode, bufferViewInfo.name); } - bufferViewArray.push_back( bufferViewInfo ); + bufferViewArray.push_back(bufferViewInfo); return true; } -bool LoadAccessor( const TreeNode& buffer, std::vector& accessorArray ) +bool LoadAccessor(const TreeNode& buffer, std::vector& accessorArray) { AccessorInfo accessorInfo; - const TreeNode* bufferViewNode = buffer.GetChild( "bufferView" ); - if( bufferViewNode ) + const TreeNode* bufferViewNode = buffer.GetChild("bufferView"); + if(bufferViewNode) { - ReadInt( bufferViewNode, accessorInfo.bufferView ); + ReadInt(bufferViewNode, accessorInfo.bufferView); } - const TreeNode* byteOffsetNode = buffer.GetChild( "byteOffset" ); - if( byteOffsetNode ) + const TreeNode* byteOffsetNode = buffer.GetChild("byteOffset"); + if(byteOffsetNode) { - ReadInt( byteOffsetNode, accessorInfo.byteOffset ); + ReadInt(byteOffsetNode, accessorInfo.byteOffset); } - const TreeNode* componentTypeNode = buffer.GetChild( "componentType" ); - if( componentTypeNode ) + const TreeNode* componentTypeNode = buffer.GetChild("componentType"); + if(componentTypeNode) { - ReadInt( componentTypeNode, accessorInfo.componentType ); - if( accessorInfo.componentType < 0 ) + ReadInt(componentTypeNode, accessorInfo.componentType); + if(accessorInfo.componentType < 0) { return false; } } - const TreeNode* normalizedNode = buffer.GetChild( "normalized" ); - if( normalizedNode ) + const TreeNode* normalizedNode = buffer.GetChild("normalized"); + if(normalizedNode) { - ReadBool( normalizedNode, accessorInfo.normalized ); + ReadBool(normalizedNode, accessorInfo.normalized); } - const TreeNode* countNode = buffer.GetChild( "count" ); - if( countNode ) + const TreeNode* countNode = buffer.GetChild("count"); + if(countNode) { - ReadInt( countNode, accessorInfo.count ); - if( accessorInfo.count < 0 ) + ReadInt(countNode, accessorInfo.count); + if(accessorInfo.count < 0) { return false; } } - const TreeNode* typeNode = buffer.GetChild( "type" ); - if( typeNode ) + const TreeNode* typeNode = buffer.GetChild("type"); + if(typeNode) { - ReadString( typeNode, accessorInfo.type ); - if( accessorInfo.type == "" ) + ReadString(typeNode, accessorInfo.type); + if(accessorInfo.type == "") { return false; } } - const TreeNode* maxNode = buffer.GetChild( "max" ); - if( maxNode ) + const TreeNode* maxNode = buffer.GetChild("max"); + if(maxNode) { - ReadInt( maxNode, accessorInfo.max ); + ReadInt(maxNode, accessorInfo.max); } - const TreeNode* minNode = buffer.GetChild( "min" ); - if( minNode ) + const TreeNode* minNode = buffer.GetChild("min"); + if(minNode) { - ReadInt( minNode, accessorInfo.min ); + ReadInt(minNode, accessorInfo.min); } - const TreeNode* nameNode = buffer.GetChild( "name" ); - if( nameNode ) + const TreeNode* nameNode = buffer.GetChild("name"); + if(nameNode) { - ReadString( nameNode, accessorInfo.name ); + ReadString(nameNode, accessorInfo.name); } - accessorArray.push_back( accessorInfo ); + accessorArray.push_back(accessorInfo); return true; } -bool LoadBinaryData( const TreeNode& root, std::vector& bufferArray, std::vector& bufferViewArray, std::vector& accessorArray ) +bool LoadBinaryData(const TreeNode& root, std::vector& bufferArray, std::vector& bufferViewArray, std::vector& accessorArray) { - const TreeNode* buffersNode = root.GetChild( "buffers" ); - if( !buffersNode ) + const TreeNode* buffersNode = root.GetChild("buffers"); + if(!buffersNode) { return false; } - for( auto bufferIter = buffersNode->CBegin(), end = buffersNode->CEnd(); bufferIter != end; ++bufferIter ) + for(auto bufferIter = buffersNode->CBegin(), end = buffersNode->CEnd(); bufferIter != end; ++bufferIter) { - LoadBuffer( ( *bufferIter ).second, bufferArray ); + LoadBuffer((*bufferIter).second, bufferArray); } - const TreeNode* bufferViewsNode = root.GetChild( "bufferViews" ); - if( !bufferViewsNode ) + const TreeNode* bufferViewsNode = root.GetChild("bufferViews"); + if(!bufferViewsNode) { return false; } - for( auto bufferViewIter = bufferViewsNode->CBegin(), end = bufferViewsNode->CEnd(); bufferViewIter != end; ++bufferViewIter ) + for(auto bufferViewIter = bufferViewsNode->CBegin(), end = bufferViewsNode->CEnd(); bufferViewIter != end; ++bufferViewIter) { - LoadBufferView( ( *bufferViewIter ).second, bufferViewArray ); + LoadBufferView((*bufferViewIter).second, bufferViewArray); } - const TreeNode* accessorsNode = root.GetChild( "accessors" ); - if( !accessorsNode ) + const TreeNode* accessorsNode = root.GetChild("accessors"); + if(!accessorsNode) { return false; } - for( auto accesorIter = accessorsNode->CBegin(), end = accessorsNode->CEnd(); accesorIter != end; ++accesorIter ) + for(auto accesorIter = accessorsNode->CBegin(), end = accessorsNode->CEnd(); accesorIter != end; ++accesorIter) { - LoadAccessor( ( *accesorIter ).second, accessorArray ); + LoadAccessor((*accesorIter).second, accessorArray); } return true; } -FilterMode::Type GetFilterMode( uint32_t mode ) +FilterMode::Type GetFilterMode(uint32_t mode) { FilterMode::Type retValue = FilterMode::DEFAULT; /** @@ -655,7 +649,7 @@ FilterMode::Type GetFilterMode( uint32_t mode ) * 9986 : NEAREST_MIPMAP_LINEAR * 9987 : LINEAR_MIPMAP_LINEAR */ - switch( mode ) + switch(mode) { case 9728: { @@ -692,7 +686,7 @@ FilterMode::Type GetFilterMode( uint32_t mode ) return retValue; } -WrapMode::Type GetWrapMode( uint32_t mode ) +WrapMode::Type GetWrapMode(uint32_t mode) { WrapMode::Type retValue = WrapMode::REPEAT; /** @@ -702,7 +696,7 @@ WrapMode::Type GetWrapMode( uint32_t mode ) * 33648 : MIRRORED_REPEAT * 10497 : REPEAT */ - switch( mode ) + switch(mode) { case 33071: { @@ -724,17 +718,17 @@ WrapMode::Type GetWrapMode( uint32_t mode ) return retValue; } -Texture LoadTexture( const char* imageUrl, bool generateMipmaps ) +Texture LoadTexture(const char* imageUrl, bool generateMipmaps) { - Texture texture; - Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl ); - if( pixelBuffer ) + Texture texture; + Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl); + if(pixelBuffer) { - texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() ); - PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer ); - texture.Upload( pixelData ); + texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight()); + PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); + texture.Upload(pixelData); - if( generateMipmaps ) + if(generateMipmaps) { texture.GenerateMipmaps(); } @@ -743,159 +737,159 @@ Texture LoadTexture( const char* imageUrl, bool generateMipmaps ) return texture; } -Sampler LoadSampler( const TreeNode& samplerNode ) +Sampler LoadSampler(const TreeNode& samplerNode) { Sampler sampler = Sampler::New(); - FilterMode::Type minFilter = FilterMode::DEFAULT; - FilterMode::Type magFilter = FilterMode::DEFAULT; - const TreeNode* magFilterNode = samplerNode.GetChild( "magFilter" ); - if( magFilterNode ) + FilterMode::Type minFilter = FilterMode::DEFAULT; + FilterMode::Type magFilter = FilterMode::DEFAULT; + const TreeNode* magFilterNode = samplerNode.GetChild("magFilter"); + if(magFilterNode) { int32_t magFilter_integer = 0; - ReadInt( magFilterNode, magFilter_integer ); - magFilter = GetFilterMode( magFilter_integer ); + ReadInt(magFilterNode, magFilter_integer); + magFilter = GetFilterMode(magFilter_integer); } - const TreeNode* minFilterNode = samplerNode.GetChild( "minFilter" ); - if( minFilterNode ) + const TreeNode* minFilterNode = samplerNode.GetChild("minFilter"); + if(minFilterNode) { int32_t minFilter_integer = 0; - ReadInt( minFilterNode, minFilter_integer ); - minFilter = GetFilterMode( minFilter_integer ); + ReadInt(minFilterNode, minFilter_integer); + minFilter = GetFilterMode(minFilter_integer); } - WrapMode::Type wrapR = WrapMode::REPEAT; - WrapMode::Type wrapS = WrapMode::REPEAT; - WrapMode::Type wrapT = WrapMode::REPEAT; - const TreeNode* wrapNode = samplerNode.GetChild( "wrapS" ); - if( wrapNode ) + WrapMode::Type wrapR = WrapMode::REPEAT; + WrapMode::Type wrapS = WrapMode::REPEAT; + WrapMode::Type wrapT = WrapMode::REPEAT; + const TreeNode* wrapNode = samplerNode.GetChild("wrapS"); + if(wrapNode) { - wrapS = GetWrapMode( wrapNode->GetInteger() ); + wrapS = GetWrapMode(wrapNode->GetInteger()); } - wrapNode = samplerNode.GetChild( "wrapT" ); - if( wrapNode ) + wrapNode = samplerNode.GetChild("wrapT"); + if(wrapNode) { - wrapT = GetWrapMode( wrapNode->GetInteger() ); + wrapT = GetWrapMode(wrapNode->GetInteger()); } - sampler.SetFilterMode( minFilter, magFilter ); - sampler.SetWrapMode( wrapR, wrapS, wrapT ); + sampler.SetFilterMode(minFilter, magFilter); + sampler.SetWrapMode(wrapR, wrapS, wrapT); return sampler; } -bool LoadTextureArray( const TreeNode& root, std::string path, std::vector& sourceArray, std::vector& samplerArray, std::vector& textureArray ) +bool LoadTextureArray(const TreeNode& root, std::string path, std::vector& sourceArray, std::vector& samplerArray, std::vector& textureArray) { - const TreeNode* imagesNode = root.GetChild( "images" ); - if( imagesNode ) + const TreeNode* imagesNode = root.GetChild("images"); + if(imagesNode) { - for( auto imageIter = imagesNode->CBegin(), end = imagesNode->CEnd(); imageIter != end; ++imageIter ) + for(auto imageIter = imagesNode->CBegin(), end = imagesNode->CEnd(); imageIter != end; ++imageIter) { - std::string imageUrl; - const TreeNode* uriNode = ( &( ( *imageIter ).second ) )->GetChild( "uri" ); - if( uriNode ) + std::string imageUrl; + const TreeNode* uriNode = (&((*imageIter).second))->GetChild("uri"); + if(uriNode) { std::string uri; - ReadString( uriNode, uri ); + ReadString(uriNode, uri); imageUrl = path + uri; } - sourceArray.push_back( LoadTexture( imageUrl.c_str(), true ) ); + sourceArray.push_back(LoadTexture(imageUrl.c_str(), true)); } } - const TreeNode* samplersNode = root.GetChild( "samplers" ); - if( samplersNode ) + const TreeNode* samplersNode = root.GetChild("samplers"); + if(samplersNode) { - for( auto samplerIter = samplersNode->CBegin(), end = samplersNode->CEnd(); samplerIter != end; ++samplerIter ) + for(auto samplerIter = samplersNode->CBegin(), end = samplersNode->CEnd(); samplerIter != end; ++samplerIter) { - samplerArray.push_back( LoadSampler( ( ( *samplerIter ).second ) ) ); + samplerArray.push_back(LoadSampler(((*samplerIter).second))); } } - const TreeNode* texturesNode = root.GetChild( "textures" ); - if( texturesNode ) + const TreeNode* texturesNode = root.GetChild("textures"); + if(texturesNode) { - for( auto textureIter = texturesNode->CBegin(), end = texturesNode->CEnd(); textureIter != end; ++textureIter ) + for(auto textureIter = texturesNode->CBegin(), end = texturesNode->CEnd(); textureIter != end; ++textureIter) { - const TreeNode* TextureNode = &( ( *textureIter ).second ); + const TreeNode* TextureNode = &((*textureIter).second); - TextureInfo texture; - const TreeNode* sourceNode = TextureNode->GetChild( "source" ); - if( sourceNode ) + TextureInfo texture; + const TreeNode* sourceNode = TextureNode->GetChild("source"); + if(sourceNode) { - ReadInt( sourceNode, texture.sourceIdx ); + ReadInt(sourceNode, texture.sourceIdx); } - const TreeNode* samplerNode = TextureNode->GetChild( "sampler" ); - if( samplerNode ) + const TreeNode* samplerNode = TextureNode->GetChild("sampler"); + if(samplerNode) { - ReadInt( samplerNode, texture.samplerIdx ); + ReadInt(samplerNode, texture.samplerIdx); } - textureArray.push_back( texture ); + textureArray.push_back(texture); } } return true; } -bool LoadPbrMetallicRoughness( const TreeNode& material, MaterialInfo& materialInfo ) +bool LoadPbrMetallicRoughness(const TreeNode& material, MaterialInfo& materialInfo) { - float floatVec[4]; - const TreeNode* pbrMetallicRoughnessNode = material.GetChild( "pbrMetallicRoughness" ); - if( !pbrMetallicRoughnessNode ) + float floatVec[4]; + const TreeNode* pbrMetallicRoughnessNode = material.GetChild("pbrMetallicRoughness"); + if(!pbrMetallicRoughnessNode) { return true; } const TreeNode* tempNode; - tempNode = pbrMetallicRoughnessNode->GetChild( "metallicFactor" ); - if( tempNode ) + tempNode = pbrMetallicRoughnessNode->GetChild("metallicFactor"); + if(tempNode) { - ReadFloat( tempNode, materialInfo.metallicFactor ); + ReadFloat(tempNode, materialInfo.metallicFactor); } - tempNode = pbrMetallicRoughnessNode->GetChild( "roughnessFactor" ); - if( tempNode ) + tempNode = pbrMetallicRoughnessNode->GetChild("roughnessFactor"); + if(tempNode) { - ReadFloat( tempNode, materialInfo.roughnessFactor ); + ReadFloat(tempNode, materialInfo.roughnessFactor); } - tempNode = pbrMetallicRoughnessNode->GetChild( "baseColorFactor" ); - if( tempNode && ReadVector( tempNode, floatVec, 4 ) ) + tempNode = pbrMetallicRoughnessNode->GetChild("baseColorFactor"); + if(tempNode && ReadVector(tempNode, floatVec, 4)) { - materialInfo.baseColorFactor = Vector4( floatVec[0], floatVec[1], floatVec[2], floatVec[3] ); + materialInfo.baseColorFactor = Vector4(floatVec[0], floatVec[1], floatVec[2], floatVec[3]); } - const TreeNode* baseColorTextureNode = pbrMetallicRoughnessNode->GetChild( "baseColorTexture" ); - if( baseColorTextureNode ) + const TreeNode* baseColorTextureNode = pbrMetallicRoughnessNode->GetChild("baseColorTexture"); + if(baseColorTextureNode) { - tempNode = baseColorTextureNode->GetChild( "index" ); - if( tempNode ) + tempNode = baseColorTextureNode->GetChild("index"); + if(tempNode) { materialInfo.baseColorTexture.index = tempNode->GetInteger(); } - tempNode = baseColorTextureNode->GetChild( "texCoord" ); - if( tempNode ) + tempNode = baseColorTextureNode->GetChild("texCoord"); + if(tempNode) { materialInfo.baseColorTexture.texCoord = tempNode->GetInteger(); } } - const TreeNode* metallicRoughnessTextureNode = pbrMetallicRoughnessNode->GetChild( "metallicRoughnessTexture" ); - if( metallicRoughnessTextureNode ) + const TreeNode* metallicRoughnessTextureNode = pbrMetallicRoughnessNode->GetChild("metallicRoughnessTexture"); + if(metallicRoughnessTextureNode) { - tempNode = metallicRoughnessTextureNode->GetChild( "index" ); - if( tempNode ) + tempNode = metallicRoughnessTextureNode->GetChild("index"); + if(tempNode) { materialInfo.metallicRoughnessTexture.index = tempNode->GetInteger(); } - tempNode = metallicRoughnessTextureNode->GetChild( "texCoord" ); - if( tempNode ) + tempNode = metallicRoughnessTextureNode->GetChild("texCoord"); + if(tempNode) { materialInfo.metallicRoughnessTexture.texCoord = tempNode->GetInteger(); } @@ -904,287 +898,286 @@ bool LoadPbrMetallicRoughness( const TreeNode& material, MaterialInfo& materialI return true; } -bool LoadMaterialSetArray( const TreeNode& root, std::vector& materialArray ) +bool LoadMaterialSetArray(const TreeNode& root, std::vector& materialArray) { - const TreeNode* materialsNode = root.GetChild( "materials" ); - if( !materialsNode ) + const TreeNode* materialsNode = root.GetChild("materials"); + if(!materialsNode) { return false; } - for( auto materialIter = materialsNode->CBegin(), end = materialsNode->CEnd(); materialIter != end; ++materialIter ) + for(auto materialIter = materialsNode->CBegin(), end = materialsNode->CEnd(); materialIter != end; ++materialIter) { MaterialInfo materialInfo; - LoadPbrMetallicRoughness( ( ( *materialIter ).second ), materialInfo ); + LoadPbrMetallicRoughness(((*materialIter).second), materialInfo); - const TreeNode* materialNode = &( ( *materialIter ).second ); - const TreeNode* tempNode = materialNode->GetChild( "name" ); - if( tempNode ) + const TreeNode* materialNode = &((*materialIter).second); + const TreeNode* tempNode = materialNode->GetChild("name"); + if(tempNode) { - ReadString( tempNode, materialInfo.name ); + ReadString(tempNode, materialInfo.name); } materialInfo.alphaMode = "OPAQUE"; - tempNode = materialNode->GetChild( "alphaMode" ); - if( tempNode ) + tempNode = materialNode->GetChild("alphaMode"); + if(tempNode) { - ReadString( tempNode, materialInfo.alphaMode ); + ReadString(tempNode, materialInfo.alphaMode); } materialInfo.alphaCutoff = 1.0; - tempNode = materialNode->GetChild( "alphaCutoff" ); - if( tempNode ) + tempNode = materialNode->GetChild("alphaCutoff"); + if(tempNode) { - ReadFloat( tempNode, materialInfo.alphaCutoff ); + ReadFloat(tempNode, materialInfo.alphaCutoff); } materialInfo.doubleSided = false; - tempNode = materialNode->GetChild( "doubleSided" ); - if( tempNode ) + tempNode = materialNode->GetChild("doubleSided"); + if(tempNode) { - ReadBool( tempNode, materialInfo.doubleSided ); + ReadBool(tempNode, materialInfo.doubleSided); } float floatVec[3]; - tempNode = materialNode->GetChild( "emissiveFactor" ); - if( tempNode && ReadVector( tempNode, floatVec, 3 ) ) + tempNode = materialNode->GetChild("emissiveFactor"); + if(tempNode && ReadVector(tempNode, floatVec, 3)) { - materialInfo.emissiveFactor = Vector3( floatVec[0], floatVec[1], floatVec[2] ); + materialInfo.emissiveFactor = Vector3(floatVec[0], floatVec[1], floatVec[2]); } - const TreeNode* texture = materialNode->GetChild( "normalTexture" ); - if( texture ) + const TreeNode* texture = materialNode->GetChild("normalTexture"); + if(texture) { - tempNode = texture->GetChild( "index" ); - if( tempNode ) + tempNode = texture->GetChild("index"); + if(tempNode) { materialInfo.normalTexture.index = tempNode->GetInteger(); } - tempNode = texture->GetChild( "texCoord" ); - if( tempNode ) + tempNode = texture->GetChild("texCoord"); + if(tempNode) { materialInfo.normalTexture.texCoord = tempNode->GetInteger(); } materialInfo.normalTexture.value = 1.0; - tempNode = texture->GetChild( "scale" ); - if( tempNode ) + tempNode = texture->GetChild("scale"); + if(tempNode) { - ReadFloat( tempNode, materialInfo.normalTexture.value ); + ReadFloat(tempNode, materialInfo.normalTexture.value); } } - texture = materialNode->GetChild( "occlusionTexture" ); - if( texture ) + texture = materialNode->GetChild("occlusionTexture"); + if(texture) { - tempNode = texture->GetChild( "index" ); - if( tempNode ) + tempNode = texture->GetChild("index"); + if(tempNode) { materialInfo.occlusionTexture.index = tempNode->GetInteger(); } - tempNode = texture->GetChild( "texCoord" ); - if( tempNode ) + tempNode = texture->GetChild("texCoord"); + if(tempNode) { materialInfo.occlusionTexture.texCoord = tempNode->GetInteger(); } - - tempNode = texture->GetChild( "strength" ); - if( tempNode ) + tempNode = texture->GetChild("strength"); + if(tempNode) { - ReadFloat( tempNode, materialInfo.occlusionTexture.value ); + ReadFloat(tempNode, materialInfo.occlusionTexture.value); } } - texture = materialNode->GetChild( "emissiveTexture" ); - if( texture ) + texture = materialNode->GetChild("emissiveTexture"); + if(texture) { - tempNode = texture->GetChild( "index" ); - if( tempNode ) + tempNode = texture->GetChild("index"); + if(tempNode) { materialInfo.emissiveTexture.index = tempNode->GetInteger(); } - tempNode = texture->GetChild( "texCoord" ); - if( tempNode ) + tempNode = texture->GetChild("texCoord"); + if(tempNode) { materialInfo.emissiveTexture.texCoord = tempNode->GetInteger(); } } - materialArray.push_back( materialInfo ); + materialArray.push_back(materialInfo); } return true; } -bool LoadAttribute( const TreeNode* primitive, MeshInfo& meshInfo ) +bool LoadAttribute(const TreeNode* primitive, MeshInfo& meshInfo) { - const TreeNode* attrbuteNode = primitive->GetChild( "attributes" ); - if( !attrbuteNode ) + const TreeNode* attrbuteNode = primitive->GetChild("attributes"); + if(!attrbuteNode) { return false; } const TreeNode* tempNode; - tempNode = attrbuteNode->GetChild( "POSITION" ); - if( tempNode ) + tempNode = attrbuteNode->GetChild("POSITION"); + if(tempNode) { meshInfo.attribute.POSITION = tempNode->GetInteger(); } - tempNode = attrbuteNode->GetChild( "NORMAL" ); - if( tempNode ) + tempNode = attrbuteNode->GetChild("NORMAL"); + if(tempNode) { meshInfo.attribute.NORMAL = tempNode->GetInteger(); } - tempNode = attrbuteNode->GetChild( "TANGENT" ); - if( tempNode ) + tempNode = attrbuteNode->GetChild("TANGENT"); + if(tempNode) { meshInfo.attribute.TANGENT = tempNode->GetInteger(); } uint32_t index = 0; meshInfo.attribute.TEXCOORD.clear(); - tempNode = attrbuteNode->GetChild( "TEXCOORD_" + std::to_string( index ) ); - while( tempNode ) + tempNode = attrbuteNode->GetChild("TEXCOORD_" + std::to_string(index)); + while(tempNode) { uint32_t value = tempNode->GetInteger(); - meshInfo.attribute.TEXCOORD.push_back( value ); - tempNode = attrbuteNode->GetChild( "TEXCOORD_" + std::to_string( ++index ) ); + meshInfo.attribute.TEXCOORD.push_back(value); + tempNode = attrbuteNode->GetChild("TEXCOORD_" + std::to_string(++index)); } index = 0; meshInfo.attribute.COLOR.clear(); - tempNode = attrbuteNode->GetChild( "COLOR_" + std::to_string( index ) ); - while( tempNode ) + tempNode = attrbuteNode->GetChild("COLOR_" + std::to_string(index)); + while(tempNode) { uint32_t value = tempNode->GetInteger(); - meshInfo.attribute.COLOR.push_back( value ); - tempNode = attrbuteNode->GetChild( "COLOR" + std::to_string( ++index ) ); + meshInfo.attribute.COLOR.push_back(value); + tempNode = attrbuteNode->GetChild("COLOR" + std::to_string(++index)); } return true; } -bool LoadPrimitive( const TreeNode& mesh, MeshInfo& meshInfo ) +bool LoadPrimitive(const TreeNode& mesh, MeshInfo& meshInfo) { - const TreeNode* primitivesNode = mesh.GetChild( "primitives" ); - if( !primitivesNode ) + const TreeNode* primitivesNode = mesh.GetChild("primitives"); + if(!primitivesNode) { return false; } - for( auto primitiveIter = primitivesNode->CBegin(), end = primitivesNode->CEnd(); primitiveIter != end; ++primitiveIter ) + for(auto primitiveIter = primitivesNode->CBegin(), end = primitivesNode->CEnd(); primitiveIter != end; ++primitiveIter) { - const TreeNode* primitiveNode = ( &( *primitiveIter ).second ); + const TreeNode* primitiveNode = (&(*primitiveIter).second); const TreeNode* tempNode; - tempNode = primitiveNode->GetChild( "indices" ); - if( tempNode ) + tempNode = primitiveNode->GetChild("indices"); + if(tempNode) { meshInfo.indicesIdx = tempNode->GetInteger(); } - tempNode = primitiveNode->GetChild( "material" ); - if( tempNode ) + tempNode = primitiveNode->GetChild("material"); + if(tempNode) { meshInfo.materialsIdx = tempNode->GetInteger(); } - tempNode = primitiveNode->GetChild( "mode" ); - if( tempNode ) + tempNode = primitiveNode->GetChild("mode"); + if(tempNode) { meshInfo.mode = tempNode->GetInteger(); } - LoadAttribute( primitiveNode, meshInfo ); + LoadAttribute(primitiveNode, meshInfo); } return true; } -bool SetGeometry( MeshInfo& meshInfo, std::string path, std::vector& bufferArray, std::vector& bufferViewArray, std::vector& accessorArray ) +bool SetGeometry(MeshInfo& meshInfo, std::string path, std::vector& bufferArray, std::vector& bufferViewArray, std::vector& accessorArray) { int32_t indicesIdx = meshInfo.indicesIdx; - if( meshInfo.mode != 0 ) + if(meshInfo.mode != 0) { - meshInfo.geometry.SetType( ( Dali::Geometry::Type )meshInfo.mode ); + meshInfo.geometry.SetType((Dali::Geometry::Type)meshInfo.mode); } - if( indicesIdx >= 0 ) + if(indicesIdx >= 0) { - SetIndexBuffersData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, indicesIdx ); + SetIndexBuffersData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, indicesIdx); } - SetVertexBufferData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.POSITION, "aPosition", Property::VECTOR3 ); - SetAttributeBufferData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.NORMAL, "aNormal", Property::VECTOR3 ); - SetAttributeBufferData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.TANGENT, "aTangent", Property::VECTOR4 ); + SetVertexBufferData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.POSITION, "aPosition", Property::VECTOR3); + SetAttributeBufferData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.NORMAL, "aNormal", Property::VECTOR3); + SetAttributeBufferData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, meshInfo.attribute.TANGENT, "aTangent", Property::VECTOR4); - for( uint32_t i = 0; i < meshInfo.attribute.TEXCOORD.size(); ++i ) + for(uint32_t i = 0; i < meshInfo.attribute.TEXCOORD.size(); ++i) { - int32_t accessorIdx = meshInfo.attribute.TEXCOORD[i]; + int32_t accessorIdx = meshInfo.attribute.TEXCOORD[i]; std::ostringstream texCoordString; texCoordString << "aTexCoord" << i; - SetAttributeBufferData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, texCoordString.str(), Property::VECTOR2 ); + SetAttributeBufferData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, texCoordString.str(), Property::VECTOR2); } - for( auto&& accessorIdx : meshInfo.attribute.COLOR ) + for(auto&& accessorIdx : meshInfo.attribute.COLOR) { - if( accessorIdx < 0 ) + if(accessorIdx < 0) { break; } - if( accessorArray[accessorIdx].type == "VEC3" ) + if(accessorArray[accessorIdx].type == "VEC3") { Dali::Vector inputBufferData; - LoadDataFromAccessor( accessorIdx, inputBufferData, path, accessorArray, bufferViewArray, bufferArray ); + LoadDataFromAccessor(accessorIdx, inputBufferData, path, accessorArray, bufferViewArray, bufferArray); Dali::Vector bufferData; - bufferData.Resize( inputBufferData.Size() ); - for( uint32_t i = 0; i( bufferData, "aVertexColor", Property::VECTOR4 ); - meshInfo.geometry.AddVertexBuffer( vertexBuffer ); + VertexBuffer vertexBuffer = CreateVertexBuffer(bufferData, "aVertexColor", Property::VECTOR4); + meshInfo.geometry.AddVertexBuffer(vertexBuffer); } - else if( accessorArray[accessorIdx].type == "VEC4" ) + else if(accessorArray[accessorIdx].type == "VEC4") { - SetAttributeBufferData( meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, "aVertexColor", Property::VECTOR4 ); + SetAttributeBufferData(meshInfo, path, accessorArray, bufferViewArray, bufferArray, accessorIdx, "aVertexColor", Property::VECTOR4); } } return true; } -bool LoadMeshArray( const TreeNode& root, std::string path, std::vector& meshArray, std::vector& bufferArray, std::vector& bufferViewArray, std::vector& accessorArray ) +bool LoadMeshArray(const TreeNode& root, std::string path, std::vector& meshArray, std::vector& bufferArray, std::vector& bufferViewArray, std::vector& accessorArray) { - const TreeNode* meshesNode = root.GetChild( "meshes" ); - if( !meshesNode ) + const TreeNode* meshesNode = root.GetChild("meshes"); + if(!meshesNode) { return false; } - for( auto meshIter = meshesNode->CBegin(), end = meshesNode->CEnd(); meshIter != end; ++meshIter ) + for(auto meshIter = meshesNode->CBegin(), end = meshesNode->CEnd(); meshIter != end; ++meshIter) { - MeshInfo meshInfo; - const TreeNode* nameNode = ( &( *meshIter ).second )->GetChild( "name" ); - if( nameNode ) + MeshInfo meshInfo; + const TreeNode* nameNode = (&(*meshIter).second)->GetChild("name"); + if(nameNode) { - ReadString( nameNode, meshInfo.name ); + ReadString(nameNode, meshInfo.name); } meshInfo.geometry = Geometry::New(); //Need to add weights for Morph targets. - LoadPrimitive( ( *meshIter ).second, meshInfo ); - SetGeometry( meshInfo, path, bufferArray, bufferViewArray, accessorArray ); - meshArray.push_back( meshInfo ); + LoadPrimitive((*meshIter).second, meshInfo); + SetGeometry(meshInfo, path, bufferArray, bufferViewArray, accessorArray); + meshArray.push_back(meshInfo); } return true; @@ -1193,8 +1186,8 @@ bool LoadMeshArray( const TreeNode& root, std::string path, std::vector buffer; - std::string fileBuffer; - if( !Dali::FileLoader::ReadFile( filePath, bufferSize, buffer, FileLoader::FileType::BINARY ) ) + std::string fileBuffer; + if(!Dali::FileLoader::ReadFile(filePath, bufferSize, buffer, FileLoader::FileType::BINARY)) { return false; } - fileBuffer.assign( &buffer[0], bufferSize ); + fileBuffer.assign(&buffer[0], bufferSize); mParser = Dali::Toolkit::JsonParser::New(); - return mParser.Parse( fileBuffer ); + return mParser.Parse(fileBuffer); } bool Loader::LoadAssets() { - if( LoadBinaryData( *mRoot, mBufferArray, mBufferViewArray, mAccessorArray ) && - LoadTextureArray( *mRoot, mPath, mSourceArray, mSamplerArray, mTextureArray ) && - LoadMaterialSetArray( *mRoot, mMaterialArray ) && - LoadMeshArray( *mRoot, mPath, mMeshArray, mBufferArray, mBufferViewArray, mAccessorArray ) - ) + if(LoadBinaryData(*mRoot, mBufferArray, mBufferViewArray, mAccessorArray) && + LoadTextureArray(*mRoot, mPath, mSourceArray, mSamplerArray, mTextureArray) && + LoadMaterialSetArray(*mRoot, mMaterialArray) && + LoadMeshArray(*mRoot, mPath, mMeshArray, mBufferArray, mBufferViewArray, mAccessorArray)) { return true; } return false; } -bool Loader::CreateScene( Internal::Scene3dView& scene3dView ) +bool Loader::CreateScene(Internal::Scene3dView& scene3dView) { - scene3dView.SetDefaultCamera( Dali::Camera::LOOK_AT_TARGET, 0.01, Vector3::ZERO ); - LoadCamera( scene3dView ); + scene3dView.SetDefaultCamera(Dali::Camera::LOOK_AT_TARGET, 0.01, Vector3::ZERO); + LoadCamera(scene3dView); - if( LoadSceneNodes( scene3dView ) && - LoadAnimation( scene3dView ) ) + if(LoadSceneNodes(scene3dView) && + LoadAnimation(scene3dView)) { return true; } return false; } -void Loader::LoadCamera( Scene3dView& scene3dView ) +void Loader::LoadCamera(Scene3dView& scene3dView) { - const TreeNode* camerasNode = mRoot->GetChild( "cameras" ); - if( !camerasNode ) + const TreeNode* camerasNode = mRoot->GetChild("cameras"); + if(!camerasNode) { return; } - for( auto cameraIter = camerasNode->CBegin(), end = camerasNode->CEnd(); cameraIter != end; ++cameraIter ) + for(auto cameraIter = camerasNode->CBegin(), end = camerasNode->CEnd(); cameraIter != end; ++cameraIter) { - const TreeNode* tempNode = ( &( *cameraIter ).second )->GetChild( "name" ); - CameraInfo cameraInfo; - if( tempNode ) + const TreeNode* tempNode = (&(*cameraIter).second)->GetChild("name"); + CameraInfo cameraInfo; + if(tempNode) { - ReadString( tempNode, cameraInfo.name ); + ReadString(tempNode, cameraInfo.name); } - tempNode = ( &( *cameraIter ).second )->GetChild( "type" ); - if( tempNode ) + tempNode = (&(*cameraIter).second)->GetChild("type"); + if(tempNode) { - ReadString( tempNode, cameraInfo.type ); + ReadString(tempNode, cameraInfo.type); } CameraActor cameraActor = CameraActor::New(); - cameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - cameraActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + cameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + cameraActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); - if( cameraInfo.type == "orthographic" ) + if(cameraInfo.type == "orthographic") { - LoadOrthoGraphic( ( *cameraIter ).second, cameraInfo ); + LoadOrthoGraphic((*cameraIter).second, cameraInfo); float xMag_2 = cameraInfo.orthographic.xmag / 2.0; float yMag_2 = cameraInfo.orthographic.ymag / 2.0; - cameraActor.SetOrthographicProjection( -xMag_2, xMag_2, yMag_2, -yMag_2, - cameraInfo.orthographic.znear, cameraInfo.orthographic.zfar ); + cameraActor.SetOrthographicProjection(-xMag_2, xMag_2, yMag_2, -yMag_2, cameraInfo.orthographic.znear, cameraInfo.orthographic.zfar); } - else if( cameraInfo.type == "perspective" ) + else if(cameraInfo.type == "perspective") { - if( !LoadPerspective( ( *cameraIter ).second, cameraInfo ) ) + if(!LoadPerspective((*cameraIter).second, cameraInfo)) { return; } - cameraActor.SetProjectionMode( Dali::Camera::PERSPECTIVE_PROJECTION ); - cameraActor.SetFieldOfView( cameraInfo.perspective.yfov ); - cameraActor.SetNearClippingPlane( cameraInfo.perspective.znear ); + cameraActor.SetProjectionMode(Dali::Camera::PERSPECTIVE_PROJECTION); + cameraActor.SetFieldOfView(cameraInfo.perspective.yfov); + cameraActor.SetNearClippingPlane(cameraInfo.perspective.znear); - if( cameraInfo.perspective.zfar > 0.0 ) + if(cameraInfo.perspective.zfar > 0.0) { - cameraActor.SetFarClippingPlane( cameraInfo.perspective.zfar ); + cameraActor.SetFarClippingPlane(cameraInfo.perspective.zfar); } - if( cameraInfo.perspective.aspectRatio > 0.0 ) + if(cameraInfo.perspective.aspectRatio > 0.0) { - cameraActor.SetAspectRatio( cameraInfo.perspective.aspectRatio ); + cameraActor.SetAspectRatio(cameraInfo.perspective.aspectRatio); } } - scene3dView.AddCamera( cameraActor ); + scene3dView.AddCamera(cameraActor); } } -bool Loader::LoadOrthoGraphic( const TreeNode& camera, CameraInfo& cameraInfo ) +bool Loader::LoadOrthoGraphic(const TreeNode& camera, CameraInfo& cameraInfo) { - const TreeNode* orthographicNode = camera.GetChild( "orthographic" ); - if( !orthographicNode ) + const TreeNode* orthographicNode = camera.GetChild("orthographic"); + if(!orthographicNode) { return false; } const TreeNode* tempNode; - tempNode = orthographicNode->GetChild( "xmag" ); - if( tempNode ) + tempNode = orthographicNode->GetChild("xmag"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.orthographic.xmag ); + ReadFloat(tempNode, cameraInfo.orthographic.xmag); } - tempNode = orthographicNode->GetChild( "ymag" ); - if( tempNode ) + tempNode = orthographicNode->GetChild("ymag"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.orthographic.ymag ); + ReadFloat(tempNode, cameraInfo.orthographic.ymag); } - tempNode = orthographicNode->GetChild( "zfar" ); - if( tempNode ) + tempNode = orthographicNode->GetChild("zfar"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.orthographic.zfar ); + ReadFloat(tempNode, cameraInfo.orthographic.zfar); } - tempNode = orthographicNode->GetChild( "znear" ); - if( tempNode ) + tempNode = orthographicNode->GetChild("znear"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.orthographic.znear ); + ReadFloat(tempNode, cameraInfo.orthographic.znear); } return true; } -bool Loader::LoadPerspective( const TreeNode& camera, CameraInfo& cameraInfo ) +bool Loader::LoadPerspective(const TreeNode& camera, CameraInfo& cameraInfo) { - const TreeNode* perspectiveNode = camera.GetChild( "perspective" ); - if( !perspectiveNode ) + const TreeNode* perspectiveNode = camera.GetChild("perspective"); + if(!perspectiveNode) { return false; } const TreeNode* tempNode; - tempNode = perspectiveNode->GetChild( "aspectRatio" ); - if( tempNode ) + tempNode = perspectiveNode->GetChild("aspectRatio"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.perspective.aspectRatio ); + ReadFloat(tempNode, cameraInfo.perspective.aspectRatio); } - tempNode = perspectiveNode->GetChild( "yfov" ); - if( tempNode ) + tempNode = perspectiveNode->GetChild("yfov"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.perspective.yfov ); + ReadFloat(tempNode, cameraInfo.perspective.yfov); } - tempNode = perspectiveNode->GetChild( "zfar" ); - if( tempNode ) + tempNode = perspectiveNode->GetChild("zfar"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.perspective.zfar ); + ReadFloat(tempNode, cameraInfo.perspective.zfar); } - tempNode = perspectiveNode->GetChild( "znear" ); - if( tempNode ) + tempNode = perspectiveNode->GetChild("znear"); + if(tempNode) { - ReadFloat( tempNode, cameraInfo.perspective.znear ); + ReadFloat(tempNode, cameraInfo.perspective.znear); } return true; } -bool Loader::LoadSceneNodes( Scene3dView& scene3dView ) +bool Loader::LoadSceneNodes(Scene3dView& scene3dView) { - const TreeNode* sceneNode = mRoot->GetChild( "scene" ); - uint32_t sceneNum = 0; - if( sceneNode ) + const TreeNode* sceneNode = mRoot->GetChild("scene"); + uint32_t sceneNum = 0; + if(sceneNode) { sceneNum = sceneNode->GetInteger(); } - const TreeNode* scenesNode = mRoot->GetChild( "scenes" ); - if( !( scenesNode && ( mNodes = mRoot->GetChild( "nodes" ) ) ) ) + const TreeNode* scenesNode = mRoot->GetChild("scenes"); + if(!(scenesNode && (mNodes = mRoot->GetChild("nodes")))) { return false; } - const TreeNode* tempNode = Tidx( scenesNode, sceneNum ); - if( !tempNode ) + const TreeNode* tempNode = Tidx(scenesNode, sceneNum); + if(!tempNode) { return false; } - tempNode = tempNode->GetChild( "nodes" ); - if( !tempNode ) + tempNode = tempNode->GetChild("nodes"); + if(!tempNode) { return false; } - for( auto nodeIter = tempNode->CBegin(), end = tempNode->CEnd(); nodeIter != end; ++nodeIter ) + for(auto nodeIter = tempNode->CBegin(), end = tempNode->CEnd(); nodeIter != end; ++nodeIter) { - Actor actor = AddNode( scene3dView, ( ( *nodeIter ).second ).GetInteger() ); - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - scene3dView.GetRoot().Add( actor ); + Actor actor = AddNode(scene3dView, ((*nodeIter).second).GetInteger()); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + scene3dView.GetRoot().Add(actor); } return true; } -Actor Loader::AddNode( Scene3dView& scene3dView, uint32_t index ) +Actor Loader::AddNode(Scene3dView& scene3dView, uint32_t index) { - const TreeNode* node = Tidx( mNodes, index ); - Actor actor = Actor::New(); - Vector3 actorSize( Vector3::ONE ); + const TreeNode* node = Tidx(mNodes, index); + Actor actor = Actor::New(); + Vector3 actorSize(Vector3::ONE); - Vector3 translation = Vector3( 0.0, 0.0, 0.0 ); - Vector3 scale = Vector3( 1.0, 1.0, 1.0 ); - Quaternion orientation( Vector4( 0.0, 0.0, 0.0, 1.0 ) ); + Vector3 translation = Vector3(0.0, 0.0, 0.0); + Vector3 scale = Vector3(1.0, 1.0, 1.0); + Quaternion orientation(Vector4(0.0, 0.0, 0.0, 1.0)); Vector3 anchorPoint = AnchorPoint::CENTER; const TreeNode* tempNode = NULL; - if( ( tempNode = node->GetChild( "translation" ) ) ) + if((tempNode = node->GetChild("translation"))) { - float floatVec[3] = { 0.0, 0.0, 0.0 }; - if( tempNode && ReadVector( tempNode, floatVec, 3 ) ) + float floatVec[3] = {0.0, 0.0, 0.0}; + if(tempNode && ReadVector(tempNode, floatVec, 3)) { - translation = Vector3( floatVec[0], floatVec[1], floatVec[2] ); + translation = Vector3(floatVec[0], floatVec[1], floatVec[2]); } } - if( ( tempNode = node->GetChild( "scale" ) ) ) + if((tempNode = node->GetChild("scale"))) { - float floatVec[3] = { 1.0, 1.0, 1.0 }; - if( tempNode && ReadVector( tempNode, floatVec, 3 ) ) + float floatVec[3] = {1.0, 1.0, 1.0}; + if(tempNode && ReadVector(tempNode, floatVec, 3)) { - scale = Vector3( floatVec[0], floatVec[1], floatVec[2] ); + scale = Vector3(floatVec[0], floatVec[1], floatVec[2]); } } - if( ( tempNode = node->GetChild( "rotation" ) ) ) + if((tempNode = node->GetChild("rotation"))) { - float floatVec[4] = { 0.0, 0.0, 0.0, 1.0 }; - if( tempNode && ReadVector( tempNode, floatVec, 4 ) ) + float floatVec[4] = {0.0, 0.0, 0.0, 1.0}; + if(tempNode && ReadVector(tempNode, floatVec, 4)) { - orientation = Quaternion( Vector4( floatVec[0], floatVec[1], floatVec[2], floatVec[3] ) ); + orientation = Quaternion(Vector4(floatVec[0], floatVec[1], floatVec[2], floatVec[3])); } } - if( ( tempNode = node->GetChild( "matrix" ) ) ) + if((tempNode = node->GetChild("matrix"))) { - float floatVec[16] = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; - if( tempNode && ReadVector( tempNode, floatVec, 16 ) ) + float floatVec[16] = {1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}; + if(tempNode && ReadVector(tempNode, floatVec, 16)) { - Matrix nodeMatrix = Matrix( floatVec ); - nodeMatrix.GetTransformComponents( translation, orientation, scale ); + Matrix nodeMatrix = Matrix(floatVec); + nodeMatrix.GetTransformComponents(translation, orientation, scale); } } - if( ( tempNode = node->GetChild( "mesh" ) ) ) + if((tempNode = node->GetChild("mesh"))) { - MeshInfo meshInfo = mMeshArray[tempNode->GetInteger()]; - bool isMaterial = ( meshInfo.materialsIdx >= 0 ); + MeshInfo meshInfo = mMeshArray[tempNode->GetInteger()]; + bool isMaterial = (meshInfo.materialsIdx >= 0); TextureSet textureSet; textureSet = TextureSet::New(); - int32_t addIdx = 0; - int32_t shaderTypeIndex = 0; - int32_t maxMipmapLevel = 0; - bool isBaseColorTexture = false; - bool isMetallicRoughnessTexture = false; - bool isNormalTexture = false; - bool isOcclusionTexture = false; - bool isEmissiveTexture = false; + int32_t addIdx = 0; + int32_t shaderTypeIndex = 0; + int32_t maxMipmapLevel = 0; + bool isBaseColorTexture = false; + bool isMetallicRoughnessTexture = false; + bool isNormalTexture = false; + bool isOcclusionTexture = false; + bool isEmissiveTexture = false; std::string VERTEX_SHADER, FRAGMENT_SHADER; VERTEX_SHADER = SHADER_GLTF_GLES_VERSION_300_DEF.data(); VERTEX_SHADER += SHADER_GLTF_PHYSICALLY_BASED_SHADER_VERT.data(); FRAGMENT_SHADER = SHADER_GLTF_GLES_VERSION_300_DEF.data(); - bool useIBL = ( scene3dView.GetLightType() >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ); - if( isMaterial ) + bool useIBL = (scene3dView.GetLightType() >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT); + if(isMaterial) { MaterialInfo materialInfo = mMaterialArray[meshInfo.materialsIdx]; - if( SetTextureAndSampler( textureSet, materialInfo.baseColorTexture.index, FRAGMENT_SHADER, SHADER_GLTF_BASECOLOR_TEXTURE_DEF.data(), addIdx ) ) + if(SetTextureAndSampler(textureSet, materialInfo.baseColorTexture.index, FRAGMENT_SHADER, SHADER_GLTF_BASECOLOR_TEXTURE_DEF.data(), addIdx)) { - shaderTypeIndex += static_cast( ShaderType::BASECOLOR_SHADER ); + shaderTypeIndex += static_cast(ShaderType::BASECOLOR_SHADER); isBaseColorTexture = true; } - if( SetTextureAndSampler( textureSet, materialInfo.metallicRoughnessTexture.index, FRAGMENT_SHADER, SHADER_GLTF_METALLICROUGHNESS_TEXTURE_DEF.data(), addIdx ) ) + if(SetTextureAndSampler(textureSet, materialInfo.metallicRoughnessTexture.index, FRAGMENT_SHADER, SHADER_GLTF_METALLICROUGHNESS_TEXTURE_DEF.data(), addIdx)) { - shaderTypeIndex += static_cast( ShaderType::METALLICROUGHNESS_SHADER ); + shaderTypeIndex += static_cast(ShaderType::METALLICROUGHNESS_SHADER); isMetallicRoughnessTexture = true; } - if( SetTextureAndSampler( textureSet, materialInfo.normalTexture.index, FRAGMENT_SHADER, SHADER_GLTF_NORMAL_TEXTURE_DEF.data(), addIdx ) ) + if(SetTextureAndSampler(textureSet, materialInfo.normalTexture.index, FRAGMENT_SHADER, SHADER_GLTF_NORMAL_TEXTURE_DEF.data(), addIdx)) { - shaderTypeIndex += static_cast( ShaderType::NORMAL_SHADER ); + shaderTypeIndex += static_cast(ShaderType::NORMAL_SHADER); isNormalTexture = true; } - if( SetTextureAndSampler( textureSet, materialInfo.occlusionTexture.index, FRAGMENT_SHADER, SHADER_GLTF_OCCULUSION_TEXTURE_DEF.data(), addIdx ) ) + if(SetTextureAndSampler(textureSet, materialInfo.occlusionTexture.index, FRAGMENT_SHADER, SHADER_GLTF_OCCULUSION_TEXTURE_DEF.data(), addIdx)) { - shaderTypeIndex += static_cast( ShaderType::OCCLUSION_SHADER ); + shaderTypeIndex += static_cast(ShaderType::OCCLUSION_SHADER); isOcclusionTexture = true; } - if( SetTextureAndSampler( textureSet, materialInfo.emissiveTexture.index, FRAGMENT_SHADER, SHADER_GLTF_EMIT_TEXTURE_DEF.data(), addIdx ) ) + if(SetTextureAndSampler(textureSet, materialInfo.emissiveTexture.index, FRAGMENT_SHADER, SHADER_GLTF_EMIT_TEXTURE_DEF.data(), addIdx)) { - shaderTypeIndex += static_cast( ShaderType::EMIT_SHADER ); + shaderTypeIndex += static_cast(ShaderType::EMIT_SHADER); isEmissiveTexture = true; } - if( useIBL ) + if(useIBL) { - shaderTypeIndex += static_cast( ShaderType::IBL_SHADER ); + shaderTypeIndex += static_cast(ShaderType::IBL_SHADER); FRAGMENT_SHADER += SHADER_GLTF_IBL_TEXTURE_DEF.data(); Sampler sampler = Sampler::New(); - sampler.SetFilterMode( FilterMode::DEFAULT, FilterMode::DEFAULT ); - sampler.SetWrapMode( WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT ); + sampler.SetFilterMode(FilterMode::DEFAULT, FilterMode::DEFAULT); + sampler.SetWrapMode(WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT); - textureSet.SetTexture( addIdx, scene3dView.GetBRDFTexture() ); - textureSet.SetSampler( addIdx++, sampler ); + textureSet.SetTexture(addIdx, scene3dView.GetBRDFTexture()); + textureSet.SetSampler(addIdx++, sampler); Sampler samplerIBL = Sampler::New(); - samplerIBL.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR ); - samplerIBL.SetWrapMode( WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE ); - textureSet.SetTexture( addIdx, scene3dView.GetDiffuseTexture() ); - textureSet.SetSampler( addIdx++, samplerIBL ); + samplerIBL.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR); + samplerIBL.SetWrapMode(WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE, WrapMode::CLAMP_TO_EDGE); + textureSet.SetTexture(addIdx, scene3dView.GetDiffuseTexture()); + textureSet.SetSampler(addIdx++, samplerIBL); Texture specularTexture = scene3dView.GetSpecularTexture(); - textureSet.SetTexture( addIdx, specularTexture ); - textureSet.SetSampler( addIdx++, samplerIBL ); + textureSet.SetTexture(addIdx, specularTexture); + textureSet.SetSampler(addIdx++, samplerIBL); - int32_t textureSize = std::min( specularTexture.GetWidth(), specularTexture.GetHeight() ); - maxMipmapLevel = 0; - while( textureSize >= 1 ) + int32_t textureSize = std::min(specularTexture.GetWidth(), specularTexture.GetHeight()); + maxMipmapLevel = 0; + while(textureSize >= 1) { maxMipmapLevel++; textureSize /= 2; @@ -1568,154 +1559,154 @@ Actor Loader::AddNode( Scene3dView& scene3dView, uint32_t index ) } FRAGMENT_SHADER += SHADER_GLTF_PHYSICALLY_BASED_SHADER_FRAG.data(); - if( !mShaderCache[shaderTypeIndex] ) + if(!mShaderCache[shaderTypeIndex]) { - mShaderCache[shaderTypeIndex] = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER ); - scene3dView.AddShader( mShaderCache[shaderTypeIndex] ); + mShaderCache[shaderTypeIndex] = Shader::New(VERTEX_SHADER, FRAGMENT_SHADER); + scene3dView.AddShader(mShaderCache[shaderTypeIndex]); } Shader shader = mShaderCache[shaderTypeIndex]; - Renderer renderer = Renderer::New( meshInfo.geometry, shader ); - renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON ); - renderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON ); - renderer.SetTextures( textureSet ); + Renderer renderer = Renderer::New(meshInfo.geometry, shader); + renderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON); + renderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON); + renderer.SetTextures(textureSet); anchorPoint = meshInfo.pivot; - actor.SetProperty( Actor::Property::ANCHOR_POINT, anchorPoint ); + actor.SetProperty(Actor::Property::ANCHOR_POINT, anchorPoint); - actor.SetProperty( Actor::Property::SIZE, Vector3( meshInfo.size.x, meshInfo.size.y, meshInfo.size.z ) ); - actor.AddRenderer( renderer ); + actor.SetProperty(Actor::Property::SIZE, Vector3(meshInfo.size.x, meshInfo.size.y, meshInfo.size.z)); + actor.AddRenderer(renderer); - actor.SetProperty( Actor::Property::SCALE, scale ); - actor.RotateBy( orientation ); - actor.SetProperty( Actor::Property::POSITION, translation ); + actor.SetProperty(Actor::Property::SCALE, scale); + actor.RotateBy(orientation); + actor.SetProperty(Actor::Property::POSITION, translation); - shader.RegisterProperty( "uLightType", ( scene3dView.GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ) ); - shader.RegisterProperty( "uLightVector", scene3dView.GetLightVector() ); - shader.RegisterProperty( "uLightColor", scene3dView.GetLightColor() ); + shader.RegisterProperty("uLightType", (scene3dView.GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT)); + shader.RegisterProperty("uLightVector", scene3dView.GetLightVector()); + shader.RegisterProperty("uLightColor", scene3dView.GetLightColor()); - actor.RegisterProperty( "uIsColor", meshInfo.attribute.COLOR.size() > 0 ); - if( isMaterial ) + actor.RegisterProperty("uIsColor", meshInfo.attribute.COLOR.size() > 0); + if(isMaterial) { MaterialInfo materialInfo = mMaterialArray[meshInfo.materialsIdx]; - actor.RegisterProperty( "uBaseColorFactor", materialInfo.baseColorFactor ); - actor.RegisterProperty( "uMetallicRoughnessFactors", Vector2( materialInfo.metallicFactor, materialInfo.roughnessFactor ) ); + actor.RegisterProperty("uBaseColorFactor", materialInfo.baseColorFactor); + actor.RegisterProperty("uMetallicRoughnessFactors", Vector2(materialInfo.metallicFactor, materialInfo.roughnessFactor)); - if( materialInfo.alphaMode == "OPAQUE" ) + if(materialInfo.alphaMode == "OPAQUE") { - actor.RegisterProperty( "alphaMode", 0 ); + actor.RegisterProperty("alphaMode", 0); } - else if( materialInfo.alphaMode == "MASK" ) + else if(materialInfo.alphaMode == "MASK") { - actor.RegisterProperty( "alphaMode", 1 ); + actor.RegisterProperty("alphaMode", 1); } else { - actor.RegisterProperty( "alphaMode", 2 ); + actor.RegisterProperty("alphaMode", 2); } - actor.RegisterProperty( "alphaCutoff", materialInfo.alphaCutoff ); + actor.RegisterProperty("alphaCutoff", materialInfo.alphaCutoff); - if( isBaseColorTexture ) + if(isBaseColorTexture) { - actor.RegisterProperty( "uBaseColorTexCoordIndex", materialInfo.baseColorTexture.texCoord ); + actor.RegisterProperty("uBaseColorTexCoordIndex", materialInfo.baseColorTexture.texCoord); } - if( isMetallicRoughnessTexture ) + if(isMetallicRoughnessTexture) { - actor.RegisterProperty( "uMetallicRoughnessTexCoordIndex", materialInfo.metallicRoughnessTexture.texCoord ); + actor.RegisterProperty("uMetallicRoughnessTexCoordIndex", materialInfo.metallicRoughnessTexture.texCoord); } - if( isNormalTexture ) + if(isNormalTexture) { - actor.RegisterProperty( "uNormalScale", materialInfo.normalTexture.value ); - actor.RegisterProperty( "uNormalTexCoordIndex", materialInfo.normalTexture.texCoord ); + actor.RegisterProperty("uNormalScale", materialInfo.normalTexture.value); + actor.RegisterProperty("uNormalTexCoordIndex", materialInfo.normalTexture.texCoord); } - if( isOcclusionTexture ) + if(isOcclusionTexture) { - actor.RegisterProperty( "uOcclusionTexCoordIndex", materialInfo.occlusionTexture.texCoord ); - actor.RegisterProperty( "uOcclusionStrength", materialInfo.occlusionTexture.value ); + actor.RegisterProperty("uOcclusionTexCoordIndex", materialInfo.occlusionTexture.texCoord); + actor.RegisterProperty("uOcclusionStrength", materialInfo.occlusionTexture.value); } - if( isEmissiveTexture ) + if(isEmissiveTexture) { - actor.RegisterProperty( "uEmissiveTexCoordIndex", materialInfo.emissiveTexture.texCoord ); - actor.RegisterProperty( "uEmissiveFactor", materialInfo.emissiveFactor ); + actor.RegisterProperty("uEmissiveTexCoordIndex", materialInfo.emissiveTexture.texCoord); + actor.RegisterProperty("uEmissiveFactor", materialInfo.emissiveFactor); } } - if( isMaterial && useIBL ) + if(isMaterial && useIBL) { - actor.RegisterProperty( "uScaleIBLAmbient", scene3dView.GetIBLScaleFactor() ); - actor.RegisterProperty( "uMipmapLevel", static_cast( maxMipmapLevel ) ); + actor.RegisterProperty("uScaleIBLAmbient", scene3dView.GetIBLScaleFactor()); + actor.RegisterProperty("uMipmapLevel", static_cast(maxMipmapLevel)); } } else { - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - actor.SetProperty( Actor::Property::POSITION, translation ); - actor.RotateBy( orientation ); - actor.SetProperty( Actor::Property::SIZE, actorSize ); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + actor.SetProperty(Actor::Property::POSITION, translation); + actor.RotateBy(orientation); + actor.SetProperty(Actor::Property::SIZE, actorSize); } - tempNode = node->GetChild( "camera" ); - if( tempNode ) + tempNode = node->GetChild("camera"); + if(tempNode) { - int32_t cameraNum = tempNode->GetInteger(); - CameraActor cameraActor = scene3dView.GetCamera( cameraNum ); - if( cameraActor ) + int32_t cameraNum = tempNode->GetInteger(); + CameraActor cameraActor = scene3dView.GetCamera(cameraNum); + if(cameraActor) { - actor.Add( cameraActor ); + actor.Add(cameraActor); } } - tempNode = node->GetChild( "name" ); - if( tempNode ) + tempNode = node->GetChild("name"); + if(tempNode) { std::string nameString; - ReadString( tempNode, nameString ); - actor.SetProperty( Dali::Actor::Property::NAME, nameString ); + ReadString(tempNode, nameString); + actor.SetProperty(Dali::Actor::Property::NAME, nameString); } - SetActorCache( actor, index ); - if( ( tempNode = node->GetChild( "children" ) ) ) + SetActorCache(actor, index); + if((tempNode = node->GetChild("children"))) { - for( auto childIter = tempNode->CBegin(), end = tempNode->CEnd(); childIter != end; ++childIter ) + for(auto childIter = tempNode->CBegin(), end = tempNode->CEnd(); childIter != end; ++childIter) { - Actor childActor = AddNode( scene3dView, ( ( *childIter ).second ).GetInteger() ); - childActor.SetProperty( Actor::Property::PARENT_ORIGIN, anchorPoint ); - actor.Add( childActor ); + Actor childActor = AddNode(scene3dView, ((*childIter).second).GetInteger()); + childActor.SetProperty(Actor::Property::PARENT_ORIGIN, anchorPoint); + actor.Add(childActor); } } return actor; } -void Loader::SetActorCache( Actor& actor, uint32_t index ) +void Loader::SetActorCache(Actor& actor, uint32_t index) { - if( mActorCache.size() < index + 1 ) + if(mActorCache.size() < index + 1) { - mActorCache.resize( index + 1 ); + mActorCache.resize(index + 1); } mActorCache[index] = actor; } -bool Loader::SetTextureAndSampler( TextureSet& textureSet, int32_t textureIdx, std::string& toShader, std::string shader, int32_t& addIdx ) +bool Loader::SetTextureAndSampler(TextureSet& textureSet, int32_t textureIdx, std::string& toShader, std::string shader, int32_t& addIdx) { - if( textureIdx >= 0 ) + if(textureIdx >= 0) { toShader += shader; TextureInfo textureInfo = mTextureArray[textureIdx]; - if( textureInfo.sourceIdx >= 0 ) + if(textureInfo.sourceIdx >= 0) { - textureSet.SetTexture( addIdx, mSourceArray[textureInfo.sourceIdx] ); + textureSet.SetTexture(addIdx, mSourceArray[textureInfo.sourceIdx]); } - if( textureInfo.samplerIdx >= 0 ) + if(textureInfo.samplerIdx >= 0) { - textureSet.SetSampler( addIdx, mSamplerArray[textureInfo.samplerIdx] ); + textureSet.SetSampler(addIdx, mSamplerArray[textureInfo.samplerIdx]); } else { Sampler sampler = Sampler::New(); - sampler.SetFilterMode( FilterMode::DEFAULT, FilterMode::DEFAULT ); - sampler.SetWrapMode( WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT ); - textureSet.SetSampler( addIdx, sampler ); + sampler.SetFilterMode(FilterMode::DEFAULT, FilterMode::DEFAULT); + sampler.SetWrapMode(WrapMode::REPEAT, WrapMode::REPEAT, WrapMode::REPEAT); + textureSet.SetSampler(addIdx, sampler); } addIdx++; return true; @@ -1723,101 +1714,101 @@ bool Loader::SetTextureAndSampler( TextureSet& textureSet, int32_t textureIdx, s return false; } -bool Loader::LoadAnimation( Scene3dView& scene3dView ) +bool Loader::LoadAnimation(Scene3dView& scene3dView) { - const TreeNode* animationsNode = mRoot->GetChild( "animations" ); - if( !animationsNode ) + const TreeNode* animationsNode = mRoot->GetChild("animations"); + if(!animationsNode) { return true; } - for( auto animationIter = animationsNode->CBegin(), end = animationsNode->CEnd(); animationIter != end; ++animationIter ) + for(auto animationIter = animationsNode->CBegin(), end = animationsNode->CEnd(); animationIter != end; ++animationIter) { - const TreeNode* nameNode = ( &( *animationIter ).second )->GetChild( "name" ); - AnimationInfo animationInfo; - if( nameNode ) + const TreeNode* nameNode = (&(*animationIter).second)->GetChild("name"); + AnimationInfo animationInfo; + if(nameNode) { - ReadString( nameNode, animationInfo.name ); + ReadString(nameNode, animationInfo.name); } Property::Index propIndex = Property::INVALID_INDEX; - LoadAnimationChannels( ( *animationIter ).second, animationInfo ); - if( animationInfo.channelArray.size() == 0 ) + LoadAnimationChannels((*animationIter).second, animationInfo); + if(animationInfo.channelArray.size() == 0) { continue; } - LoadAnimationSamplers( ( *animationIter ).second, animationInfo ); + LoadAnimationSamplers((*animationIter).second, animationInfo); - for( auto&& currentChannel : animationInfo.channelArray ) + for(auto&& currentChannel : animationInfo.channelArray) { - if( currentChannel.path == "rotation" ) + if(currentChannel.path == "rotation") { propIndex = Dali::Actor::Property::ORIENTATION; } - else if( currentChannel.path == "translation" ) + else if(currentChannel.path == "translation") { propIndex = Dali::Actor::Property::POSITION; } - else if( currentChannel.path == "scale" ) + else if(currentChannel.path == "scale") { propIndex = Dali::Actor::Property::SCALE; } - float duration = 0.0f; + float duration = 0.0f; KeyFrames keyframes = KeyFrames::New(); - if( propIndex == Dali::Actor::Property::ORIENTATION ) + if(propIndex == Dali::Actor::Property::ORIENTATION) { - duration = LoadKeyFrames( animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray ); + duration = LoadKeyFrames(animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray); } else { - duration = LoadKeyFrames( animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray ); + duration = LoadKeyFrames(animationInfo.samplerArray[currentChannel.sampler], propIndex, keyframes, mPath, mAccessorArray, mBufferViewArray, mBufferArray); } - Animation animation = Animation::New( duration ); + Animation animation = Animation::New(duration); Animation::Interpolation interpolation = Animation::Interpolation::LINEAR; - if( animationInfo.samplerArray[currentChannel.sampler].interpolation == "CUBICSPLINE" ) + if(animationInfo.samplerArray[currentChannel.sampler].interpolation == "CUBICSPLINE") { interpolation = Animation::Interpolation::CUBIC; } - if( animationInfo.samplerArray[currentChannel.sampler].interpolation == "STEP" ) + if(animationInfo.samplerArray[currentChannel.sampler].interpolation == "STEP") { } - animation.AnimateBetween( Property( mActorCache[currentChannel.targetNode], propIndex ), keyframes, interpolation ); + animation.AnimateBetween(Property(mActorCache[currentChannel.targetNode], propIndex), keyframes, interpolation); - animation.SetLooping( false ); - scene3dView.AddAnimation( animation ); + animation.SetLooping(false); + scene3dView.AddAnimation(animation); } } return true; } -bool Loader::LoadAnimationChannels( const TreeNode& animation, AnimationInfo& animationInfo ) +bool Loader::LoadAnimationChannels(const TreeNode& animation, AnimationInfo& animationInfo) { - const TreeNode* channelsNode = animation.GetChild( "channels" ); - if( !channelsNode ) + const TreeNode* channelsNode = animation.GetChild("channels"); + if(!channelsNode) { return false; } - for( auto channelIter = channelsNode->CBegin(), end = channelsNode->CEnd(); channelIter != end; ++channelIter ) + for(auto channelIter = channelsNode->CBegin(), end = channelsNode->CEnd(); channelIter != end; ++channelIter) { AnimationChannelInfo animationChannelInfo; - const TreeNode* channelNode = ( &( *channelIter ).second ); - const TreeNode* samplerNode = channelNode->GetChild( "sampler" ); - if( samplerNode ) + const TreeNode* channelNode = (&(*channelIter).second); + const TreeNode* samplerNode = channelNode->GetChild("sampler"); + if(samplerNode) { animationChannelInfo.sampler = samplerNode->GetInteger(); } - const TreeNode* targetNode = channelNode->GetChild( "target" ); - if( targetNode ) + const TreeNode* targetNode = channelNode->GetChild("target"); + if(targetNode) { - const TreeNode* tempNode = targetNode->GetChild( "node" ); - if( tempNode ) + const TreeNode* tempNode = targetNode->GetChild("node"); + if(tempNode) { animationChannelInfo.targetNode = tempNode->GetInteger(); } @@ -1826,58 +1817,58 @@ bool Loader::LoadAnimationChannels( const TreeNode& animation, AnimationInfo& an continue; } - tempNode = targetNode->GetChild( "path" ); - if( tempNode ) + tempNode = targetNode->GetChild("path"); + if(tempNode) { - ReadString( tempNode, animationChannelInfo.path ); + ReadString(tempNode, animationChannelInfo.path); } } - animationInfo.channelArray.push_back( animationChannelInfo ); + animationInfo.channelArray.push_back(animationChannelInfo); } return true; } -bool Loader::LoadAnimationSamplers( const TreeNode& animation, AnimationInfo& animationInfo ) +bool Loader::LoadAnimationSamplers(const TreeNode& animation, AnimationInfo& animationInfo) { - const TreeNode* samplersNode = animation.GetChild( "samplers" ); - if( !samplersNode ) + const TreeNode* samplersNode = animation.GetChild("samplers"); + if(!samplersNode) { return false; } - for( auto sampler = samplersNode->CBegin(), end = samplersNode->CEnd(); sampler != end; ++sampler ) + for(auto sampler = samplersNode->CBegin(), end = samplersNode->CEnd(); sampler != end; ++sampler) { AnimationSamplerInfo animationSamplerInfo; - const TreeNode* samplerNode = ( &( *sampler ).second ); - const TreeNode* tempNode = samplerNode->GetChild( "input" ); - if( tempNode ) + const TreeNode* samplerNode = (&(*sampler).second); + const TreeNode* tempNode = samplerNode->GetChild("input"); + if(tempNode) { animationSamplerInfo.input = tempNode->GetInteger(); } - tempNode = samplerNode->GetChild( "output" ); - if( tempNode ) + tempNode = samplerNode->GetChild("output"); + if(tempNode) { animationSamplerInfo.output = tempNode->GetInteger(); } - tempNode = samplerNode->GetChild( "interpolation" ); - if( tempNode ) + tempNode = samplerNode->GetChild("interpolation"); + if(tempNode) { - ReadString( tempNode, animationSamplerInfo.interpolation ); + ReadString(tempNode, animationSamplerInfo.interpolation); } - animationInfo.samplerArray.push_back( animationSamplerInfo ); + animationInfo.samplerArray.push_back(animationSamplerInfo); } return true; } -}//namespace Gltf +} //namespace Gltf -}//namespace Internal +} //namespace Internal -}//namespace Toolkit +} //namespace Toolkit -}//namespace Dali +} //namespace Dali diff --git a/dali-toolkit/internal/controls/scene3d-view/scene3d-view-impl.cpp b/dali-toolkit/internal/controls/scene3d-view/scene3d-view-impl.cpp index 1521ae9..aa8438a 100644 --- a/dali-toolkit/internal/controls/scene3d-view/scene3d-view-impl.cpp +++ b/dali-toolkit/internal/controls/scene3d-view/scene3d-view-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. @@ -26,39 +26,35 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const char* const IMAGE_BRDF_FILE_NAME = "brdfLUT.png"; // glTF file extension -const std::string GLTF_EXT( ".gltf" ); +const std::string GLTF_EXT(".gltf"); /** * cube map face index */ -const uint32_t CUBEMAP_INDEX_X[2][6] = { { 2, 0, 1, 1, 1, 3 }, { 0, 1, 2, 3, 4, 5 } }; -const uint32_t CUBEMAP_INDEX_Y[2][6] = { { 1, 1, 0, 2, 1, 1 }, { 0, 0, 0, 0, 0, 0 } }; +const uint32_t CUBEMAP_INDEX_X[2][6] = {{2, 0, 1, 1, 1, 3}, {0, 1, 2, 3, 4, 5}}; +const uint32_t CUBEMAP_INDEX_Y[2][6] = {{1, 1, 0, 2, 1, 1}, {0, 0, 0, 0, 0, 0}}; -}//namespace +} //namespace Scene3dView::Scene3dView() - : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mRoot( Actor::New() ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mRoot(Actor::New()), mShaderArray(), mCameraActorArray(), - mDefaultCamera( CameraActor::New() ), + mDefaultCamera(CameraActor::New()), mAnimationArray(), - mLightType( Toolkit::Scene3dView::LightType::NONE ), - mLightVector( Vector3::ONE ), - mLightColor( Vector3::ONE ) + mLightType(Toolkit::Scene3dView::LightType::NONE), + mLightVector(Vector3::ONE), + mLightColor(Vector3::ONE) { } @@ -66,11 +62,11 @@ Scene3dView::~Scene3dView() { } -Toolkit::Scene3dView Scene3dView::New( const std::string& filePath ) +Toolkit::Scene3dView Scene3dView::New(const std::string& filePath) { Scene3dView* impl = new Scene3dView(); - Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView( *impl ); + Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -80,16 +76,16 @@ Toolkit::Scene3dView Scene3dView::New( const std::string& filePath ) return handle; } -Toolkit::Scene3dView Scene3dView::New( const std::string& filePath, const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor ) +Toolkit::Scene3dView Scene3dView::New(const std::string& filePath, const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor) { Scene3dView* impl = new Scene3dView(); - Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView( *impl ); + Dali::Toolkit::Scene3dView handle = Dali::Toolkit::Scene3dView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... impl->mFilePath = filePath; - impl->SetCubeMap( diffuseTexturePath, specularTexturePath, scaleFactor ); + impl->SetCubeMap(diffuseTexturePath, specularTexturePath, scaleFactor); impl->Initialize(); return handle; @@ -97,10 +93,10 @@ Toolkit::Scene3dView Scene3dView::New( const std::string& filePath, const std::s bool Scene3dView::CreateScene() { - if( std::string::npos != mFilePath.rfind( GLTF_EXT ) ) + if(std::string::npos != mFilePath.rfind(GLTF_EXT)) { Internal::Gltf::Loader gltfloader; - return( gltfloader.LoadScene( mFilePath, *this ) ); + return (gltfloader.LoadScene(mFilePath, *this)); } return false; @@ -111,9 +107,9 @@ uint32_t Scene3dView::GetAnimationCount() return mAnimationArray.size(); } -bool Scene3dView::PlayAnimation( uint32_t index ) +bool Scene3dView::PlayAnimation(uint32_t index) { - if( GetAnimationCount() <= index ) + if(GetAnimationCount() <= index) { return false; } @@ -124,7 +120,7 @@ bool Scene3dView::PlayAnimation( uint32_t index ) bool Scene3dView::PlayAnimations() { - for( auto&& animation : mAnimationArray ) + for(auto&& animation : mAnimationArray) { animation.Play(); } @@ -132,43 +128,41 @@ bool Scene3dView::PlayAnimations() return true; } -bool Scene3dView::SetLight( Toolkit::Scene3dView::LightType type, Vector3 lightVector, Vector3 lightColor ) +bool Scene3dView::SetLight(Toolkit::Scene3dView::LightType type, Vector3 lightVector, Vector3 lightColor) { - if( type > Toolkit::Scene3dView::LightType::DIRECTIONAL_LIGHT ) + if(type > Toolkit::Scene3dView::LightType::DIRECTIONAL_LIGHT) { return false; } mLightType = static_cast( - ( mLightType >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ) ? - Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT + type : - type ); + (mLightType >= Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT) ? Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT + type : type); mLightVector = lightVector; - mLightColor = lightColor; + mLightColor = lightColor; - for( auto&& shader : mShaderArray ) + for(auto&& shader : mShaderArray) { - shader.RegisterProperty( "uLightType", ( GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT ) ); - shader.RegisterProperty( "uLightVector", lightVector ); - shader.RegisterProperty( "uLightColor", lightColor ); + shader.RegisterProperty("uLightType", (GetLightType() & ~Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT)); + shader.RegisterProperty("uLightVector", lightVector); + shader.RegisterProperty("uLightColor", lightColor); } return true; } -uint8_t* Scene3dView::GetCroppedBuffer( uint8_t* sourceBuffer, uint32_t bytesPerPixel, uint32_t width, uint32_t height, uint32_t xOffset, uint32_t yOffset, uint32_t xFaceSize, uint32_t yFaceSize ) +uint8_t* Scene3dView::GetCroppedBuffer(uint8_t* sourceBuffer, uint32_t bytesPerPixel, uint32_t width, uint32_t height, uint32_t xOffset, uint32_t yOffset, uint32_t xFaceSize, uint32_t yFaceSize) { - uint32_t byteSize = bytesPerPixel * xFaceSize * yFaceSize; - uint8_t* destBuffer = reinterpret_cast( malloc( byteSize + 4u ) ); + uint32_t byteSize = bytesPerPixel * xFaceSize * yFaceSize; + uint8_t* destBuffer = reinterpret_cast(malloc(byteSize + 4u)); - int32_t srcStride = width * bytesPerPixel; + int32_t srcStride = width * bytesPerPixel; int32_t destStride = xFaceSize * bytesPerPixel; - int32_t srcOffset = xOffset * bytesPerPixel + yOffset * srcStride; + int32_t srcOffset = xOffset * bytesPerPixel + yOffset * srcStride; int32_t destOffset = 0; - for( uint16_t row = yOffset; row < yOffset + yFaceSize; ++row ) + for(uint16_t row = yOffset; row < yOffset + yFaceSize; ++row) { - memcpy( destBuffer + destOffset, sourceBuffer + srcOffset, destStride ); + memcpy(destBuffer + destOffset, sourceBuffer + srcOffset, destStride); srcOffset += srcStride; destOffset += destStride; } @@ -176,22 +170,21 @@ uint8_t* Scene3dView::GetCroppedBuffer( uint8_t* sourceBuffer, uint32_t bytesPer return destBuffer; } -void Scene3dView::UploadTextureFace( Texture& texture, Devel::PixelBuffer pixelBuffer, uint32_t faceIndex ) +void Scene3dView::UploadTextureFace(Texture& texture, Devel::PixelBuffer pixelBuffer, uint32_t faceIndex) { - uint8_t* imageBuffer = pixelBuffer.GetBuffer(); - uint32_t bytesPerPixel = Pixel::GetBytesPerPixel( pixelBuffer.GetPixelFormat() ); - uint32_t imageWidth = pixelBuffer.GetWidth(); - uint32_t imageHeight = pixelBuffer.GetHeight(); + uint8_t* imageBuffer = pixelBuffer.GetBuffer(); + uint32_t bytesPerPixel = Pixel::GetBytesPerPixel(pixelBuffer.GetPixelFormat()); + uint32_t imageWidth = pixelBuffer.GetWidth(); + uint32_t imageHeight = pixelBuffer.GetHeight(); - CubeType cubeType = ( imageWidth / 4 == imageHeight / 3 ) ? CROSS_HORIZONTAL : - ( ( imageWidth / 6 == imageHeight ) ? ARRAY_HORIZONTAL : NONE ); + CubeType cubeType = (imageWidth / 4 == imageHeight / 3) ? CROSS_HORIZONTAL : ((imageWidth / 6 == imageHeight) ? ARRAY_HORIZONTAL : NONE); uint32_t faceSize = 0; - if( cubeType == CROSS_HORIZONTAL ) + if(cubeType == CROSS_HORIZONTAL) { faceSize = imageWidth / 4; } - else if( cubeType == ARRAY_HORIZONTAL ) + else if(cubeType == ARRAY_HORIZONTAL) { faceSize = imageWidth / 6; } @@ -203,70 +196,70 @@ void Scene3dView::UploadTextureFace( Texture& texture, Devel::PixelBuffer pixelB uint32_t xOffset = CUBEMAP_INDEX_X[cubeType][faceIndex] * faceSize; uint32_t yOffset = CUBEMAP_INDEX_Y[cubeType][faceIndex] * faceSize; - uint8_t* tempImageBuffer = GetCroppedBuffer( imageBuffer, bytesPerPixel, imageWidth, imageHeight, xOffset, yOffset, faceSize, faceSize ); - PixelData pixelData = PixelData::New( tempImageBuffer, faceSize * faceSize * bytesPerPixel, faceSize, faceSize, pixelBuffer.GetPixelFormat(), PixelData::FREE ); - texture.Upload( pixelData, CubeMapLayer::POSITIVE_X + faceIndex, 0, 0, 0, faceSize, faceSize ); + uint8_t* tempImageBuffer = GetCroppedBuffer(imageBuffer, bytesPerPixel, imageWidth, imageHeight, xOffset, yOffset, faceSize, faceSize); + PixelData pixelData = PixelData::New(tempImageBuffer, faceSize * faceSize * bytesPerPixel, faceSize, faceSize, pixelBuffer.GetPixelFormat(), PixelData::FREE); + texture.Upload(pixelData, CubeMapLayer::POSITIVE_X + faceIndex, 0, 0, 0, faceSize, faceSize); } -void Scene3dView::SetCubeMap( const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor ) +void Scene3dView::SetCubeMap(const std::string& diffuseTexturePath, const std::string& specularTexturePath, Vector4 scaleFactor) { mLightType = Toolkit::Scene3dView::LightType::IMAGE_BASED_LIGHT; // BRDF texture const std::string imageDirPath = AssetManager::GetDaliImagePath(); const std::string imageBrdfUrl = imageDirPath + IMAGE_BRDF_FILE_NAME; - mBRDFTexture = LoadTexture( imageBrdfUrl.c_str(), true ); - if( !mBRDFTexture ) + mBRDFTexture = LoadTexture(imageBrdfUrl.c_str(), true); + if(!mBRDFTexture) { return; } // Diffuse Cube Map - Devel::PixelBuffer diffusePixelBuffer = LoadImageFromFile( diffuseTexturePath ); - uint32_t diffuseFaceSize = diffusePixelBuffer.GetWidth() / 4; - mDiffuseTexture = Texture::New( TextureType::TEXTURE_CUBE, diffusePixelBuffer.GetPixelFormat(), diffuseFaceSize, diffuseFaceSize ); - for( uint32_t i = 0; i < 6; ++i ) + Devel::PixelBuffer diffusePixelBuffer = LoadImageFromFile(diffuseTexturePath); + uint32_t diffuseFaceSize = diffusePixelBuffer.GetWidth() / 4; + mDiffuseTexture = Texture::New(TextureType::TEXTURE_CUBE, diffusePixelBuffer.GetPixelFormat(), diffuseFaceSize, diffuseFaceSize); + for(uint32_t i = 0; i < 6; ++i) { - UploadTextureFace( mDiffuseTexture, diffusePixelBuffer, i ); + UploadTextureFace(mDiffuseTexture, diffusePixelBuffer, i); } mDiffuseTexture.GenerateMipmaps(); // Specular Cube Map - Devel::PixelBuffer specularPixelBuffer = LoadImageFromFile( specularTexturePath ); - uint32_t specularFaceSize = specularPixelBuffer.GetWidth() / 4; - mSpecularTexture = Texture::New( TextureType::TEXTURE_CUBE, specularPixelBuffer.GetPixelFormat(), specularFaceSize, specularFaceSize ); - for( uint32_t i = 0; i < 6; ++i ) + Devel::PixelBuffer specularPixelBuffer = LoadImageFromFile(specularTexturePath); + uint32_t specularFaceSize = specularPixelBuffer.GetWidth() / 4; + mSpecularTexture = Texture::New(TextureType::TEXTURE_CUBE, specularPixelBuffer.GetPixelFormat(), specularFaceSize, specularFaceSize); + for(uint32_t i = 0; i < 6; ++i) { - UploadTextureFace( mSpecularTexture, specularPixelBuffer, i ); + UploadTextureFace(mSpecularTexture, specularPixelBuffer, i); } mSpecularTexture.GenerateMipmaps(); mIBLScaleFactor = scaleFactor; } -bool Scene3dView::SetDefaultCamera( const Dali::Camera::Type type, const float nearPlane, const Vector3 cameraPosition ) +bool Scene3dView::SetDefaultCamera(const Dali::Camera::Type type, const float nearPlane, const Vector3 cameraPosition) { - mDefaultCamera.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mDefaultCamera.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mDefaultCamera.SetType( type ); - mDefaultCamera.SetNearClippingPlane( nearPlane ); - mDefaultCamera.SetProperty( Actor::Property::POSITION, cameraPosition ); + mDefaultCamera.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mDefaultCamera.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mDefaultCamera.SetType(type); + mDefaultCamera.SetNearClippingPlane(nearPlane); + mDefaultCamera.SetProperty(Actor::Property::POSITION, cameraPosition); return true; } -void Scene3dView::AddCamera( CameraActor cameraActor ) +void Scene3dView::AddCamera(CameraActor cameraActor) { - mCameraActorArray.push_back( cameraActor ); + mCameraActorArray.push_back(cameraActor); } -void Scene3dView::AddAnimation( Animation animation ) +void Scene3dView::AddAnimation(Animation animation) { - mAnimationArray.push_back( animation ); + mAnimationArray.push_back(animation); } -void Scene3dView::AddShader( Shader shader ) +void Scene3dView::AddShader(Shader shader) { - mShaderArray.push_back( shader ); + mShaderArray.push_back(shader); } Actor Scene3dView::GetRoot() @@ -284,10 +277,10 @@ uint32_t Scene3dView::GetCameraCount() return mCameraActorArray.size(); } -CameraActor Scene3dView::GetCamera( uint32_t cameraIndex ) +CameraActor Scene3dView::GetCamera(uint32_t cameraIndex) { CameraActor cameraActor; - if( cameraIndex >= mCameraActorArray.size() ) + if(cameraIndex >= mCameraActorArray.size()) { return cameraActor; } @@ -330,18 +323,18 @@ Texture Scene3dView::GetDiffuseTexture() return mDiffuseTexture; } -Texture Scene3dView::LoadTexture( const char *imageUrl, bool generateMipmaps ) +Texture Scene3dView::LoadTexture(const char* imageUrl, bool generateMipmaps) { Texture texture; - Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl ); - if( pixelBuffer ) + Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl); + if(pixelBuffer) { - texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() ); - PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer ); - texture.Upload( pixelData ); + texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight()); + PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); + texture.Upload(pixelData); - if( generateMipmaps ) + if(generateMipmaps) { texture.GenerateMipmaps(); } @@ -352,27 +345,26 @@ Texture Scene3dView::LoadTexture( const char *imageUrl, bool generateMipmaps ) void Scene3dView::OnInitialize() { - mRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mRoot.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + mRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mRoot.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); Layer layer = Layer::New(); - layer.SetProperty( Layer::Property::BEHAVIOR, Layer::LAYER_3D ); - layer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - layer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - layer.Add( mRoot ); + layer.SetProperty(Layer::Property::BEHAVIOR, Layer::LAYER_3D); + layer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + layer.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + layer.Add(mRoot); Actor self = Self(); // Apply some default resizing rules. - self.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - self.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - self.Add( layer ); + self.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + self.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + self.Add(layer); CreateScene(); } -}//namespace Internal - -}//namespace Toolkit +} //namespace Internal -}//namespace Dali +} //namespace Toolkit +} //namespace Dali diff --git a/dali-toolkit/internal/controls/scroll-bar/scroll-bar-impl.cpp b/dali-toolkit/internal/controls/scroll-bar/scroll-bar-impl.cpp index 0627759..4701d6c 100644 --- a/dali-toolkit/internal/controls/scroll-bar/scroll-bar-impl.cpp +++ b/dali-toolkit/internal/controls/scroll-bar/scroll-bar-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,15 +19,15 @@ #include // EXTERNAL INCLUDES -#include // for strcmp +#include +#include +#include #include #include -#include #include #include -#include -#include -#include +#include +#include // for strcmp // INTERNAL INCLUDES #include @@ -38,7 +38,6 @@ using namespace Dali; namespace { - const char* DEFAULT_INDICATOR_IMAGE_FILE_NAME = "popup_scroll.9.png"; const float DEFAULT_SLIDER_DEPTH(1.0f); const float DEFAULT_INDICATOR_SHOW_DURATION(0.5f); @@ -60,9 +59,9 @@ struct IndicatorSizeConstraint * @param[in] minimumHeight The minimum height for the indicator * @param[in] padding The sum of the padding at the start & end of the indicator */ - IndicatorSizeConstraint( float minimumHeight, float padding ) - : mMinimumHeight( minimumHeight ), - mPadding( padding ) + IndicatorSizeConstraint(float minimumHeight, float padding) + : mMinimumHeight(minimumHeight), + mPadding(padding) { } @@ -72,19 +71,17 @@ struct IndicatorSizeConstraint * @param[in] parentSizeProperty The parent size of scroll indicator. * @return The new scroll indicator size. */ - void operator()( Vector3& current, const PropertyInputContainer& inputs ) + void operator()(Vector3& current, const PropertyInputContainer& inputs) { - const Vector3& parentSize = inputs[0]->GetVector3(); - const float contentSize = inputs[1]->GetFloat(); + const Vector3& parentSize = inputs[0]->GetVector3(); + const float contentSize = inputs[1]->GetFloat(); // Take into account padding that may exist at the beginning and end of the indicator. const float parentHeightMinusPadding = parentSize.height - mPadding; - float height = contentSize > parentHeightMinusPadding ? - parentHeightMinusPadding * ( parentHeightMinusPadding / contentSize ) : - parentHeightMinusPadding * ( ( parentHeightMinusPadding - contentSize * 0.5f ) / parentHeightMinusPadding ); + float height = contentSize > parentHeightMinusPadding ? parentHeightMinusPadding * (parentHeightMinusPadding / contentSize) : parentHeightMinusPadding * ((parentHeightMinusPadding - contentSize * 0.5f) / parentHeightMinusPadding); - current.y = std::max( mMinimumHeight, height ); + current.y = std::max(mMinimumHeight, height); } float mMinimumHeight; @@ -101,9 +98,9 @@ struct IndicatorPositionConstraint * @param[in] startPadding The padding at the start of the indicator * @param[in] endPadding The padding at the end of the indicator */ - IndicatorPositionConstraint( float startPadding, float endPadding ) - : mStartPadding( startPadding ), - mEndPadding( endPadding ) + IndicatorPositionConstraint(float startPadding, float endPadding) + : mStartPadding(startPadding), + mEndPadding(endPadding) { } @@ -113,20 +110,20 @@ struct IndicatorPositionConstraint * @param[in] inputs Contains the size of indicator, the size of indicator's parent, and the scroll position of the scrollable container (from 0.0 -> 1.0 in each axis) * @return The new indicator position is returned. */ - void operator()( Vector3& current, const PropertyInputContainer& inputs ) + void operator()(Vector3& current, const PropertyInputContainer& inputs) { - const Vector3& indicatorSize = inputs[0]->GetVector3(); - const Vector3& parentSize = inputs[1]->GetVector3(); - const float scrollPosition = -inputs[2]->GetFloat(); - const float minimumScrollPosition = inputs[3]->GetFloat(); - const float maximumScrollPosition = inputs[4]->GetFloat(); + const Vector3& indicatorSize = inputs[0]->GetVector3(); + const Vector3& parentSize = inputs[1]->GetVector3(); + const float scrollPosition = -inputs[2]->GetFloat(); + const float minimumScrollPosition = inputs[3]->GetFloat(); + const float maximumScrollPosition = inputs[4]->GetFloat(); // Take into account padding that may exist at the beginning and end of the indicator. - const float parentHeightMinusPadding = parentSize.height - ( mStartPadding + mEndPadding ); + const float parentHeightMinusPadding = parentSize.height - (mStartPadding + mEndPadding); - float relativePosition = std::max( 0.0f, std::min( 1.0f, ( scrollPosition - minimumScrollPosition ) / ( maximumScrollPosition - minimumScrollPosition ) ) ); - current.y = mStartPadding + ( parentHeightMinusPadding - indicatorSize.height ) * relativePosition; - current.z = DEFAULT_SLIDER_DEPTH; + float relativePosition = std::max(0.0f, std::min(1.0f, (scrollPosition - minimumScrollPosition) / (maximumScrollPosition - minimumScrollPosition))); + current.y = mStartPadding + (parentHeightMinusPadding - indicatorSize.height) * relativePosition; + current.z = DEFAULT_SLIDER_DEPTH; } float mStartPadding; @@ -137,16 +134,12 @@ struct IndicatorPositionConstraint namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - using namespace Dali; BaseHandle Create() @@ -154,36 +147,38 @@ BaseHandle Create() return Toolkit::ScrollBar::New(); } +// clang-format off // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ScrollBar, Toolkit::Control, Create ); -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "scrollDirection", STRING, SCROLL_DIRECTION ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorHeightPolicy", STRING, INDICATOR_HEIGHT_POLICY ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorFixedHeight", FLOAT, INDICATOR_FIXED_HEIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorShowDuration", FLOAT, INDICATOR_SHOW_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorHideDuration", FLOAT, INDICATOR_HIDE_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "scrollPositionIntervals", ARRAY, SCROLL_POSITION_INTERVALS ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorMinimumHeight", FLOAT, INDICATOR_MINIMUM_HEIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorStartPadding", FLOAT, INDICATOR_START_PADDING ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorEndPadding", FLOAT, INDICATOR_END_PADDING ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollBar, "indicatorTransientDuration", FLOAT, INDICATOR_TRANSIENT_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "scrollDirection", STRING, SCROLL_DIRECTION ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorHeightPolicy", STRING, INDICATOR_HEIGHT_POLICY ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorFixedHeight", FLOAT, INDICATOR_FIXED_HEIGHT ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorShowDuration", FLOAT, INDICATOR_SHOW_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorHideDuration", FLOAT, INDICATOR_HIDE_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "scrollPositionIntervals", ARRAY, SCROLL_POSITION_INTERVALS ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorMinimumHeight", FLOAT, INDICATOR_MINIMUM_HEIGHT ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorStartPadding", FLOAT, INDICATOR_START_PADDING ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorEndPadding", FLOAT, INDICATOR_END_PADDING ) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollBar, "indicatorTransientDuration", FLOAT, INDICATOR_TRANSIENT_DURATION) -DALI_SIGNAL_REGISTRATION( Toolkit, ScrollBar, "panFinished", PAN_FINISHED_SIGNAL ) -DALI_SIGNAL_REGISTRATION( Toolkit, ScrollBar, "scrollPositionIntervalReached", SCROLL_POSITION_INTERVAL_REACHED_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, ScrollBar, "panFinished", PAN_FINISHED_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, ScrollBar, "scrollPositionIntervalReached", SCROLL_POSITION_INTERVAL_REACHED_SIGNAL) -DALI_ACTION_REGISTRATION( Toolkit, ScrollBar, "ShowIndicator", ACTION_SHOW_INDICATOR ) -DALI_ACTION_REGISTRATION( Toolkit, ScrollBar, "HideIndicator", ACTION_HIDE_INDICATOR ) -DALI_ACTION_REGISTRATION( Toolkit, ScrollBar, "ShowTransientIndicator", ACTION_SHOW_TRANSIENT_INDICATOR ) +DALI_ACTION_REGISTRATION(Toolkit, ScrollBar, "ShowIndicator", ACTION_SHOW_INDICATOR ) +DALI_ACTION_REGISTRATION(Toolkit, ScrollBar, "HideIndicator", ACTION_HIDE_INDICATOR ) +DALI_ACTION_REGISTRATION(Toolkit, ScrollBar, "ShowTransientIndicator", ACTION_SHOW_TRANSIENT_INDICATOR) DALI_TYPE_REGISTRATION_END() +// clang-format on -const char* SCROLL_DIRECTION_NAME[] = {"VERTICAL", "HORIZONTAL"}; +const char* SCROLL_DIRECTION_NAME[] = {"VERTICAL", "HORIZONTAL"}; const char* INDICATOR_HEIGHT_POLICY_NAME[] = {"VARIABLE", "FIXED"}; -} +} // namespace ScrollBar::ScrollBar(Toolkit::ScrollBar::Direction direction) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mIndicatorShowAlpha(1.0f), mDirection(direction), mScrollableObject(WeakHandle()), @@ -195,7 +190,7 @@ ScrollBar::ScrollBar(Toolkit::ScrollBar::Direction direction) mIndicatorHideDuration(DEFAULT_INDICATOR_HIDE_DURATION), mTransientIndicatorDuration(DEFAULT_INDICATOR_TRANSIENT_DURATION), mScrollStart(0.0f), - mGestureDisplacement( Vector2::ZERO ), + mGestureDisplacement(Vector2::ZERO), mCurrentScrollPosition(0.0f), mIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE), mIndicatorFixedHeight(DEFAULT_INDICATOR_FIXED_HEIGHT), @@ -214,24 +209,20 @@ ScrollBar::~ScrollBar() void ScrollBar::OnInitialize() { CreateDefaultIndicatorActor(); - Self().SetProperty( Actor::Property::DRAW_MODE,DrawMode::OVERLAY_2D); + Self().SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::SCROLL_BAR ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_BAR)); + }); } -void ScrollBar::SetScrollPropertySource( Handle handle, Property::Index propertyScrollPosition, Property::Index propertyMinScrollPosition, Property::Index propertyMaxScrollPosition, Property::Index propertyScrollContentSize ) +void ScrollBar::SetScrollPropertySource(Handle handle, Property::Index propertyScrollPosition, Property::Index propertyMinScrollPosition, Property::Index propertyMaxScrollPosition, Property::Index propertyScrollContentSize) { - if( handle - && propertyScrollPosition != Property::INVALID_INDEX - && propertyMinScrollPosition != Property::INVALID_INDEX - && propertyMaxScrollPosition != Property::INVALID_INDEX - && propertyScrollContentSize != Property::INVALID_INDEX ) + if(handle && propertyScrollPosition != Property::INVALID_INDEX && propertyMinScrollPosition != Property::INVALID_INDEX && propertyMaxScrollPosition != Property::INVALID_INDEX && propertyScrollContentSize != Property::INVALID_INDEX) { - mScrollableObject = WeakHandle(handle); - mPropertyScrollPosition = propertyScrollPosition; + mScrollableObject = WeakHandle(handle); + mPropertyScrollPosition = propertyScrollPosition; mPropertyMinScrollPosition = propertyMinScrollPosition; mPropertyMaxScrollPosition = propertyMaxScrollPosition; mPropertyScrollContentSize = propertyScrollContentSize; @@ -246,43 +237,43 @@ void ScrollBar::SetScrollPropertySource( Handle handle, Property::Index property void ScrollBar::CreateDefaultIndicatorActor() { - const std::string imageDirPath = AssetManager::GetDaliImagePath(); - Toolkit::ImageView indicator = Toolkit::ImageView::New( imageDirPath + DEFAULT_INDICATOR_IMAGE_FILE_NAME ); - indicator.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - indicator.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - indicator.SetStyleName( "ScrollBarIndicator" ); - indicator.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR ); + const std::string imageDirPath = AssetManager::GetDaliImagePath(); + Toolkit::ImageView indicator = Toolkit::ImageView::New(imageDirPath + DEFAULT_INDICATOR_IMAGE_FILE_NAME); + indicator.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + indicator.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + indicator.SetStyleName("ScrollBarIndicator"); + indicator.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR); SetScrollIndicator(indicator); } -void ScrollBar::SetScrollIndicator( Actor indicator ) +void ScrollBar::SetScrollIndicator(Actor indicator) { // Don't allow empty handle - if( indicator ) + if(indicator) { // Remove current Indicator - if( mIndicator ) + if(mIndicator) { - Self().Remove( mIndicator ); + Self().Remove(mIndicator); } mIndicator = indicator; mIndicatorFirstShow = true; - Self().Add( mIndicator ); + Self().Add(mIndicator); - EnableGestureDetection( GestureType::Value( GestureType::PAN ) ); + EnableGestureDetection(GestureType::Value(GestureType::PAN)); - PanGestureDetector detector( GetPanGestureDetector() ); + PanGestureDetector detector(GetPanGestureDetector()); detector.DetachAll(); - detector.Attach( mIndicator ); + detector.Attach(mIndicator); unsigned int childCount = mIndicator.GetChildCount(); - for ( unsigned int index = 0; index < childCount; index++ ) + for(unsigned int index = 0; index < childCount; index++) { - Actor child = mIndicator.GetChildAt( index ); - if ( child ) + Actor child = mIndicator.GetChildAt(index); + if(child) { - detector.Attach( child ); + detector.Attach(child); } } } @@ -301,7 +292,7 @@ void ScrollBar::ApplyConstraints() { Handle scrollableHandle = mScrollableObject.GetHandle(); - if( scrollableHandle ) + if(scrollableHandle) { if(mIndicatorSizeConstraint) { @@ -311,14 +302,13 @@ void ScrollBar::ApplyConstraints() // Set indicator height according to the indicator's height policy if(mIndicatorHeightPolicy == Toolkit::ScrollBar::FIXED) { - mIndicator.SetProperty( Actor::Property::SIZE, Vector2( Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).width, mIndicatorFixedHeight) ); + mIndicator.SetProperty(Actor::Property::SIZE, Vector2(Self().GetCurrentProperty(Actor::Property::SIZE).width, mIndicatorFixedHeight)); } else { - mIndicatorSizeConstraint = Constraint::New( mIndicator, Actor::Property::SIZE, - IndicatorSizeConstraint( mIndicatorMinimumHeight, mIndicatorStartPadding + mIndicatorEndPadding ) ); - mIndicatorSizeConstraint.AddSource( ParentSource( Actor::Property::SIZE ) ); - mIndicatorSizeConstraint.AddSource( Source( scrollableHandle, mPropertyScrollContentSize ) ); + mIndicatorSizeConstraint = Constraint::New(mIndicator, Actor::Property::SIZE, IndicatorSizeConstraint(mIndicatorMinimumHeight, mIndicatorStartPadding + mIndicatorEndPadding)); + mIndicatorSizeConstraint.AddSource(ParentSource(Actor::Property::SIZE)); + mIndicatorSizeConstraint.AddSource(Source(scrollableHandle, mPropertyScrollContentSize)); mIndicatorSizeConstraint.Apply(); } @@ -327,32 +317,31 @@ void ScrollBar::ApplyConstraints() mIndicatorPositionConstraint.Remove(); } - mIndicatorPositionConstraint = Constraint::New( mIndicator, Actor::Property::POSITION, - IndicatorPositionConstraint( mIndicatorStartPadding, mIndicatorEndPadding ) ); - mIndicatorPositionConstraint.AddSource( LocalSource( Actor::Property::SIZE ) ); - mIndicatorPositionConstraint.AddSource( ParentSource( Actor::Property::SIZE ) ); - mIndicatorPositionConstraint.AddSource( Source( scrollableHandle, mPropertyScrollPosition ) ); - mIndicatorPositionConstraint.AddSource( Source( scrollableHandle, mPropertyMinScrollPosition ) ); - mIndicatorPositionConstraint.AddSource( Source( scrollableHandle, mPropertyMaxScrollPosition ) ); + mIndicatorPositionConstraint = Constraint::New(mIndicator, Actor::Property::POSITION, IndicatorPositionConstraint(mIndicatorStartPadding, mIndicatorEndPadding)); + mIndicatorPositionConstraint.AddSource(LocalSource(Actor::Property::SIZE)); + mIndicatorPositionConstraint.AddSource(ParentSource(Actor::Property::SIZE)); + mIndicatorPositionConstraint.AddSource(Source(scrollableHandle, mPropertyScrollPosition)); + mIndicatorPositionConstraint.AddSource(Source(scrollableHandle, mPropertyMinScrollPosition)); + mIndicatorPositionConstraint.AddSource(Source(scrollableHandle, mPropertyMaxScrollPosition)); mIndicatorPositionConstraint.Apply(); } } -void ScrollBar::SetScrollPositionIntervals( const Dali::Vector& positions ) +void ScrollBar::SetScrollPositionIntervals(const Dali::Vector& positions) { mScrollPositionIntervals = positions; Handle scrollableHandle = mScrollableObject.GetHandle(); - if( scrollableHandle ) + if(scrollableHandle) { - if( mPositionNotification ) + if(mPositionNotification) { scrollableHandle.RemovePropertyNotification(mPositionNotification); } - mPositionNotification = scrollableHandle.AddPropertyNotification( mPropertyScrollPosition, VariableStepCondition(mScrollPositionIntervals) ); - mPositionNotification.NotifySignal().Connect( this, &ScrollBar::OnScrollPositionIntervalReached ); + mPositionNotification = scrollableHandle.AddPropertyNotification(mPropertyScrollPosition, VariableStepCondition(mScrollPositionIntervals)); + mPositionNotification.NotifySignal().Connect(this, &ScrollBar::OnScrollPositionIntervalReached); } } @@ -367,8 +356,8 @@ void ScrollBar::OnScrollPositionIntervalReached(PropertyNotification& source) Handle scrollableHandle = mScrollableObject.GetHandle(); if(scrollableHandle) { - mScrollPositionIntervalReachedSignal.Emit( scrollableHandle.GetCurrentProperty< float >( mPropertyScrollPosition ) ); - if (Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) + mScrollPositionIntervalReachedSignal.Emit(scrollableHandle.GetCurrentProperty(mPropertyScrollPosition)); + if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) { Control::Impl::GetAccessibilityObject(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::VALUE); } @@ -384,22 +373,22 @@ void ScrollBar::ShowIndicator() mAnimation.Reset(); } - if( mIndicatorFirstShow ) + if(mIndicatorFirstShow) { // Preserve the alpha value from the stylesheet - mIndicatorShowAlpha = Self().GetCurrentProperty< Vector4 >( Actor::Property::COLOR ).a; + mIndicatorShowAlpha = Self().GetCurrentProperty(Actor::Property::COLOR).a; mIndicatorFirstShow = false; } if(mIndicatorShowDuration > 0.0f) { - mAnimation = Animation::New( mIndicatorShowDuration ); - mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ), mIndicatorShowAlpha, AlphaFunction::EASE_IN ); + mAnimation = Animation::New(mIndicatorShowDuration); + mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA), mIndicatorShowAlpha, AlphaFunction::EASE_IN); mAnimation.Play(); } else { - mIndicator.SetProperty( Actor::Property::OPACITY,mIndicatorShowAlpha); + mIndicator.SetProperty(Actor::Property::OPACITY, mIndicatorShowAlpha); } } @@ -414,13 +403,13 @@ void ScrollBar::HideIndicator() if(mIndicatorHideDuration > 0.0f) { - mAnimation = Animation::New( mIndicatorHideDuration ); - mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN ); + mAnimation = Animation::New(mIndicatorHideDuration); + mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN); mAnimation.Play(); } else { - mIndicator.SetProperty( Actor::Property::OPACITY,0.0f); + mIndicator.SetProperty(Actor::Property::OPACITY, 0.0f); } } @@ -433,18 +422,22 @@ void ScrollBar::ShowTransientIndicator() mAnimation.Reset(); } - mAnimation = Animation::New( mIndicatorShowDuration + mTransientIndicatorDuration + mIndicatorHideDuration ); + mAnimation = Animation::New(mIndicatorShowDuration + mTransientIndicatorDuration + mIndicatorHideDuration); if(mIndicatorShowDuration > 0.0f) { - mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ), - mIndicatorShowAlpha, AlphaFunction::EASE_IN, TimePeriod(0, mIndicatorShowDuration) ); + mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA), + mIndicatorShowAlpha, + AlphaFunction::EASE_IN, + TimePeriod(0, mIndicatorShowDuration)); } else { - mIndicator.SetProperty( Actor::Property::OPACITY,mIndicatorShowAlpha); + mIndicator.SetProperty(Actor::Property::OPACITY, mIndicatorShowAlpha); } - mAnimation.AnimateTo( Property( mIndicator, Actor::Property::COLOR_ALPHA ), - 0.0f, AlphaFunction::EASE_IN, TimePeriod((mIndicatorShowDuration + mTransientIndicatorDuration), mIndicatorHideDuration) ); + mAnimation.AnimateTo(Property(mIndicator, Actor::Property::COLOR_ALPHA), + 0.0f, + AlphaFunction::EASE_IN, + TimePeriod((mIndicatorShowDuration + mTransientIndicatorDuration), mIndicatorHideDuration)); mAnimation.Play(); } @@ -452,7 +445,7 @@ bool ScrollBar::OnPanGestureProcessTick() { // Update the scroll position property. Handle scrollableHandle = mScrollableObject.GetHandle(); - if( scrollableHandle ) + if(scrollableHandle) { scrollableHandle.SetProperty(mPropertyScrollPosition, mCurrentScrollPosition); } @@ -460,7 +453,7 @@ bool ScrollBar::OnPanGestureProcessTick() return true; } -void ScrollBar::OnPan( const PanGesture& gesture ) +void ScrollBar::OnPan(const PanGesture& gesture) { Handle scrollableHandle = mScrollableObject.GetHandle(); @@ -472,18 +465,18 @@ void ScrollBar::OnPan( const PanGesture& gesture ) { case Dali::GestureState::STARTED: { - if( !mPanProcessTimer ) + if(!mPanProcessTimer) { // Make sure the pan gesture is only being processed once per frame. - mPanProcessTimer = Timer::New( DEFAULT_PAN_GESTURE_PROCESS_TIME ); - mPanProcessTimer.TickSignal().Connect( this, &ScrollBar::OnPanGestureProcessTick ); + mPanProcessTimer = Timer::New(DEFAULT_PAN_GESTURE_PROCESS_TIME); + mPanProcessTimer.TickSignal().Connect(this, &ScrollBar::OnPanGestureProcessTick); mPanProcessTimer.Start(); } ShowIndicator(); - mScrollStart = scrollableHandle.GetCurrentProperty< float >( mPropertyScrollPosition ); + mScrollStart = scrollableHandle.GetCurrentProperty(mPropertyScrollPosition); mGestureDisplacement = Vector2::ZERO; - mIsPanning = true; + mIsPanning = true; break; } @@ -491,15 +484,15 @@ void ScrollBar::OnPan( const PanGesture& gesture ) { mGestureDisplacement += gesture.GetDisplacement(); - float minScrollPosition = scrollableHandle.GetCurrentProperty( mPropertyMinScrollPosition ); - float maxScrollPosition = scrollableHandle.GetCurrentProperty( mPropertyMaxScrollPosition ); + float minScrollPosition = scrollableHandle.GetCurrentProperty(mPropertyMinScrollPosition); + float maxScrollPosition = scrollableHandle.GetCurrentProperty(mPropertyMaxScrollPosition); // The domain size is the internal range - float domainSize = maxScrollPosition - minScrollPosition; - float logicalSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).y - ( mIndicator.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).y + mIndicatorStartPadding + mIndicatorEndPadding ); + float domainSize = maxScrollPosition - minScrollPosition; + float logicalSize = Self().GetCurrentProperty(Actor::Property::SIZE).y - (mIndicator.GetCurrentProperty(Actor::Property::SIZE).y + mIndicatorStartPadding + mIndicatorEndPadding); - mCurrentScrollPosition = mScrollStart - ( ( mGestureDisplacement.y * domainSize ) / logicalSize ); - mCurrentScrollPosition = -std::min( maxScrollPosition, std::max( -mCurrentScrollPosition, minScrollPosition ) ); + mCurrentScrollPosition = mScrollStart - ((mGestureDisplacement.y * domainSize) / logicalSize); + mCurrentScrollPosition = -std::min(maxScrollPosition, std::max(-mCurrentScrollPosition, minScrollPosition)); break; } @@ -507,11 +500,11 @@ void ScrollBar::OnPan( const PanGesture& gesture ) { mIsPanning = false; - if( mPanProcessTimer ) + if(mPanProcessTimer) { // Destroy the timer when pan gesture is finished. mPanProcessTimer.Stop(); - mPanProcessTimer.TickSignal().Disconnect( this, &ScrollBar::OnPanGestureProcessTick ); + mPanProcessTimer.TickSignal().Disconnect(this, &ScrollBar::OnPanGestureProcessTick); mPanProcessTimer.Reset(); } @@ -535,17 +528,17 @@ void ScrollBar::OnPan( const PanGesture& gesture ) } } -void ScrollBar::OnSizeSet( const Vector3& size ) +void ScrollBar::OnSizeSet(const Vector3& size) { if(mIndicatorHeightPolicy == Toolkit::ScrollBar::FIXED) { - mIndicator.SetProperty( Actor::Property::SIZE, Vector2( size.width, mIndicatorFixedHeight ) ); + mIndicator.SetProperty(Actor::Property::SIZE, Vector2(size.width, mIndicatorFixedHeight)); } - Control::OnSizeSet( size ); + Control::OnSizeSet(size); } -void ScrollBar::SetScrollDirection( Toolkit::ScrollBar::Direction direction ) +void ScrollBar::SetScrollDirection(Toolkit::ScrollBar::Direction direction) { mDirection = direction; } @@ -555,9 +548,9 @@ Toolkit::ScrollBar::Direction ScrollBar::GetScrollDirection() const return mDirection; } -void ScrollBar::SetIndicatorHeightPolicy( Toolkit::ScrollBar::IndicatorHeightPolicy policy ) +void ScrollBar::SetIndicatorHeightPolicy(Toolkit::ScrollBar::IndicatorHeightPolicy policy) { - if( policy != mIndicatorHeightPolicy ) + if(policy != mIndicatorHeightPolicy) { mIndicatorHeightPolicy = policy; ApplyConstraints(); @@ -569,13 +562,13 @@ Toolkit::ScrollBar::IndicatorHeightPolicy ScrollBar::GetIndicatorHeightPolicy() return mIndicatorHeightPolicy; } -void ScrollBar::SetIndicatorFixedHeight( float height ) +void ScrollBar::SetIndicatorFixedHeight(float height) { mIndicatorFixedHeight = height; if(mIndicatorHeightPolicy == Toolkit::ScrollBar::FIXED) { - mIndicator.SetProperty( Actor::Property::SIZE, Vector2( Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).width, mIndicatorFixedHeight) ); + mIndicator.SetProperty(Actor::Property::SIZE, Vector2(Self().GetCurrentProperty(Actor::Property::SIZE).width, mIndicatorFixedHeight)); } } @@ -584,7 +577,7 @@ float ScrollBar::GetIndicatorFixedHeight() const return mIndicatorFixedHeight; } -void ScrollBar::SetIndicatorShowDuration( float durationSeconds ) +void ScrollBar::SetIndicatorShowDuration(float durationSeconds) { mIndicatorShowDuration = durationSeconds; } @@ -594,7 +587,7 @@ float ScrollBar::GetIndicatorShowDuration() const return mIndicatorShowDuration; } -void ScrollBar::SetIndicatorHideDuration( float durationSeconds ) +void ScrollBar::SetIndicatorHideDuration(float durationSeconds) { mIndicatorHideDuration = durationSeconds; } @@ -604,9 +597,9 @@ float ScrollBar::GetIndicatorHideDuration() const return mIndicatorHideDuration; } -void ScrollBar::OnScrollDirectionPropertySet( Property::Value propertyValue ) +void ScrollBar::OnScrollDirectionPropertySet(Property::Value propertyValue) { - std::string directionName( propertyValue.Get() ); + std::string directionName(propertyValue.Get()); if(directionName == "VERTICAL") { SetScrollDirection(Toolkit::ScrollBar::VERTICAL); @@ -617,13 +610,13 @@ void ScrollBar::OnScrollDirectionPropertySet( Property::Value propertyValue ) } else { - DALI_ASSERT_ALWAYS( !"ScrollBar::OnScrollDirectionPropertySet(). Invalid Property value." ); + DALI_ASSERT_ALWAYS(!"ScrollBar::OnScrollDirectionPropertySet(). Invalid Property value."); } } -void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValue ) +void ScrollBar::OnIndicatorHeightPolicyPropertySet(Property::Value propertyValue) { - std::string policyName( propertyValue.Get() ); + std::string policyName(propertyValue.Get()); if(policyName == "VARIABLE") { SetIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE); @@ -634,24 +627,24 @@ void ScrollBar::OnIndicatorHeightPolicyPropertySet( Property::Value propertyValu } else { - DALI_ASSERT_ALWAYS( !"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value." ); + DALI_ASSERT_ALWAYS(!"ScrollBar::OnIndicatorHeightPolicyPropertySet(). Invalid Property value."); } } -bool ScrollBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool ScrollBar::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( handle ); + bool connected(true); + Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), PAN_FINISHED_SIGNAL ) ) + if(0 == strcmp(signalName.c_str(), PAN_FINISHED_SIGNAL)) { - scrollBar.PanFinishedSignal().Connect( tracker, functor ); + scrollBar.PanFinishedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SCROLL_POSITION_INTERVAL_REACHED_SIGNAL ) ) + else if(0 == strcmp(signalName.c_str(), SCROLL_POSITION_INTERVAL_REACHED_SIGNAL)) { - scrollBar.ScrollPositionIntervalReachedSignal().Connect( tracker, functor ); + scrollBar.ScrollPositionIntervalReachedSignal().Connect(tracker, functor); } else { @@ -662,23 +655,23 @@ bool ScrollBar::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* return connected; } -void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void ScrollBar::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(Dali::BaseHandle(object)); - if( scrollBar ) + if(scrollBar) { - ScrollBar& scrollBarImpl( GetImpl( scrollBar ) ); - switch( index ) + ScrollBar& scrollBarImpl(GetImpl(scrollBar)); + switch(index) { case Toolkit::ScrollBar::Property::SCROLL_DIRECTION: { - scrollBarImpl.OnScrollDirectionPropertySet( value ); + scrollBarImpl.OnScrollDirectionPropertySet(value); break; } case Toolkit::ScrollBar::Property::INDICATOR_HEIGHT_POLICY: { - scrollBarImpl.OnIndicatorHeightPolicyPropertySet( value ); + scrollBarImpl.OnIndicatorHeightPolicyPropertySet(value); break; } case Toolkit::ScrollBar::Property::INDICATOR_FIXED_HEIGHT: @@ -699,14 +692,14 @@ void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Pr case Toolkit::ScrollBar::Property::SCROLL_POSITION_INTERVALS: { const Property::Array* array = value.GetArray(); - if( array ) + if(array) { Dali::Vector positions; - size_t positionCount = array->Count(); - positions.Resize( positionCount ); - for( size_t i = 0; i != positionCount; ++i ) + size_t positionCount = array->Count(); + positions.Resize(positionCount); + for(size_t i = 0; i != positionCount; ++i) { - array->GetElementAt( i ).Get( positions[i] ); + array->GetElementAt(i).Get(positions[i]); } scrollBarImpl.SetScrollPositionIntervals(positions); @@ -740,25 +733,25 @@ void ScrollBar::SetProperty( BaseObject* object, Property::Index index, const Pr } } -Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index index ) +Property::Value ScrollBar::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(Dali::BaseHandle(object)); - if( scrollBar ) + if(scrollBar) { - ScrollBar& scrollBarImpl( GetImpl( scrollBar ) ); - switch( index ) + ScrollBar& scrollBarImpl(GetImpl(scrollBar)); + switch(index) { case Toolkit::ScrollBar::Property::SCROLL_DIRECTION: { - value = SCROLL_DIRECTION_NAME[ scrollBarImpl.GetScrollDirection() ]; + value = SCROLL_DIRECTION_NAME[scrollBarImpl.GetScrollDirection()]; break; } case Toolkit::ScrollBar::Property::INDICATOR_HEIGHT_POLICY: { - value = INDICATOR_HEIGHT_POLICY_NAME[ scrollBarImpl.GetIndicatorHeightPolicy() ]; + value = INDICATOR_HEIGHT_POLICY_NAME[scrollBarImpl.GetIndicatorHeightPolicy()]; break; } case Toolkit::ScrollBar::Property::INDICATOR_FIXED_HEIGHT: @@ -778,17 +771,17 @@ Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::ScrollBar::Property::SCROLL_POSITION_INTERVALS: { - Property::Value tempValue( Property::ARRAY ); + Property::Value tempValue(Property::ARRAY); Property::Array* array = tempValue.GetArray(); - if( array ) + if(array) { Dali::Vector positions = scrollBarImpl.GetScrollPositionIntervals(); - size_t positionCount( positions.Count() ); + size_t positionCount(positions.Count()); - for( size_t i( 0 ); i != positionCount; ++i ) + for(size_t i(0); i != positionCount; ++i) { - array->PushBack( positions[i] ); + array->PushBack(positions[i]); } value = tempValue; @@ -820,31 +813,31 @@ Property::Value ScrollBar::GetProperty( BaseObject* object, Property::Index inde return value; } -bool ScrollBar::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes ) +bool ScrollBar::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes) { bool ret = false; - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast( handle ); + Toolkit::ScrollBar scrollBar = Toolkit::ScrollBar::DownCast(handle); - DALI_ASSERT_DEBUG( scrollBar ); + DALI_ASSERT_DEBUG(scrollBar); - if( scrollBar ) + if(scrollBar) { - if( 0 == strcmp( actionName.c_str(), ACTION_SHOW_INDICATOR ) ) + if(0 == strcmp(actionName.c_str(), ACTION_SHOW_INDICATOR)) { - GetImpl( scrollBar ).ShowIndicator(); + GetImpl(scrollBar).ShowIndicator(); ret = true; } - else if( 0 == strcmp( actionName.c_str(), ACTION_HIDE_INDICATOR ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_HIDE_INDICATOR)) { - GetImpl( scrollBar ).HideIndicator(); + GetImpl(scrollBar).HideIndicator(); ret = true; } - else if( 0 == strcmp( actionName.c_str(), ACTION_SHOW_TRANSIENT_INDICATOR ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_SHOW_TRANSIENT_INDICATOR)) { - GetImpl( scrollBar ).ShowTransientIndicator(); + GetImpl(scrollBar).ShowTransientIndicator(); ret = true; } } @@ -855,10 +848,10 @@ bool ScrollBar::DoAction( BaseObject* object, const std::string& actionName, con Toolkit::ScrollBar ScrollBar::New(Toolkit::ScrollBar::Direction direction) { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< ScrollBar > impl = new ScrollBar(direction); + IntrusivePtr impl = new ScrollBar(direction); // Pass ownership to CustomActor handle - Toolkit::ScrollBar handle( *impl ); + Toolkit::ScrollBar handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -869,47 +862,50 @@ Toolkit::ScrollBar ScrollBar::New(Toolkit::ScrollBar::Direction direction) double ScrollBar::AccessibleImpl::GetMinimum() { - auto p = Toolkit::ScrollBar::DownCast( self ); - Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle(); - return scrollableHandle ? scrollableHandle.GetCurrentProperty< float >( GetImpl( p ).mPropertyMinScrollPosition ) : 0.0f; + auto p = Toolkit::ScrollBar::DownCast(self); + Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle(); + return scrollableHandle ? scrollableHandle.GetCurrentProperty(GetImpl(p).mPropertyMinScrollPosition) : 0.0f; } double ScrollBar::AccessibleImpl::GetCurrent() { - auto p = Toolkit::ScrollBar::DownCast( self ); - Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle(); - return scrollableHandle ? scrollableHandle.GetCurrentProperty< float >( GetImpl( p ).mPropertyScrollPosition ) : 0.0f; + auto p = Toolkit::ScrollBar::DownCast(self); + Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle(); + return scrollableHandle ? scrollableHandle.GetCurrentProperty(GetImpl(p).mPropertyScrollPosition) : 0.0f; } double ScrollBar::AccessibleImpl::GetMaximum() { - auto p = Toolkit::ScrollBar::DownCast( self ); - Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle(); - return scrollableHandle ? scrollableHandle.GetCurrentProperty< float >( GetImpl( p ).mPropertyMaxScrollPosition ) : 1.0f; + auto p = Toolkit::ScrollBar::DownCast(self); + Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle(); + return scrollableHandle ? scrollableHandle.GetCurrentProperty(GetImpl(p).mPropertyMaxScrollPosition) : 1.0f; } -bool ScrollBar::AccessibleImpl::SetCurrent( double current ) +bool ScrollBar::AccessibleImpl::SetCurrent(double current) { - if( current < GetMinimum() || current > GetMaximum() ) + if(current < GetMinimum() || current > GetMaximum()) return false; auto value_before = GetCurrent(); - auto p = Toolkit::ScrollBar::DownCast( self ); - Handle scrollableHandle = GetImpl( p ).mScrollableObject.GetHandle(); - if( !scrollableHandle ) + auto p = Toolkit::ScrollBar::DownCast(self); + Handle scrollableHandle = GetImpl(p).mScrollableObject.GetHandle(); + if(!scrollableHandle) return false; - scrollableHandle.SetProperty( GetImpl( p ).mPropertyScrollPosition, static_cast< float >( current ) ); + scrollableHandle.SetProperty(GetImpl(p).mPropertyScrollPosition, static_cast(current)); auto value_after = GetCurrent(); - if( ( current != value_before ) && ( value_before == value_after ) ) + if((current != value_before) && (value_before == value_after)) return false; return true; } -double ScrollBar::AccessibleImpl::GetMinimumIncrement() { return 1.0; } +double ScrollBar::AccessibleImpl::GetMinimumIncrement() +{ + return 1.0; +} } // namespace Internal diff --git a/dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.cpp b/dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.cpp index be63772..2d61cfa 100644 --- a/dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.cpp +++ b/dali-toolkit/internal/controls/scrollable/bouncing-effect-actor.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. @@ -31,28 +31,24 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { // Bouncing effect is presented by stacked three layers with same color and opacity const float LAYER_HEIGHTS[5] = -{ - 1.f, - 26.f * 4.f/ 130.f, - 26.f * 3.f / 130.f, - 26.f * 2.f / 130.f, - 26.f / 130.f -}; + { + 1.f, + 26.f * 4.f / 130.f, + 26.f * 3.f / 130.f, + 26.f * 2.f / 130.f, + 26.f / 130.f}; -} // namespace Anon +} // namespace -Actor CreateBouncingEffectActor( Property::Index& bouncePropertyIndex ) +Actor CreateBouncingEffectActor(Property::Index& bouncePropertyIndex) { // Create the bouncing mesh geometry struct VertexPosition @@ -63,52 +59,51 @@ Actor CreateBouncingEffectActor( Property::Index& bouncePropertyIndex ) // 4 vertices 2 triangles per layer. The depth interval between each layer is 0.01 VertexPosition vertexData[20] = { // bottom layer - { Vector3( -0.5f, -0.5f, 0.f ), Vector3( -0.5f, -0.5f, 0.f ) }, - { Vector3( 0.5f, -0.5f, 0.f ), Vector3( 0.5f, -0.5f, 0.f ) }, - { Vector3( -0.5f, -0.5f, 0.f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[0], 0.f ) }, - { Vector3( 0.5f, -0.5f, 0.f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[0], 0.f ) }, + {Vector3(-0.5f, -0.5f, 0.f), Vector3(-0.5f, -0.5f, 0.f)}, + {Vector3(0.5f, -0.5f, 0.f), Vector3(0.5f, -0.5f, 0.f)}, + {Vector3(-0.5f, -0.5f, 0.f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[0], 0.f)}, + {Vector3(0.5f, -0.5f, 0.f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[0], 0.f)}, // mid-bottom layer - { Vector3( -0.5f, -0.5f, 0.01f ), Vector3( -0.5f, -0.5f, 0.01f ) }, - { Vector3( 0.5f, -0.5f, 0.01f ), Vector3( 0.5f, -0.5f, 0.01f ) }, - { Vector3( -0.5f, -0.5f, 0.01f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[1], 0.01f ) }, - { Vector3( 0.5f, -0.5f, 0.01f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[1], 0.01f ) }, + {Vector3(-0.5f, -0.5f, 0.01f), Vector3(-0.5f, -0.5f, 0.01f)}, + {Vector3(0.5f, -0.5f, 0.01f), Vector3(0.5f, -0.5f, 0.01f)}, + {Vector3(-0.5f, -0.5f, 0.01f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[1], 0.01f)}, + {Vector3(0.5f, -0.5f, 0.01f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[1], 0.01f)}, // middle layer - { Vector3( -0.5f, -0.5f, 0.02f ), Vector3( -0.5f, -0.5f, 0.02f ) }, - { Vector3( 0.5f, -0.5f, 0.02f ), Vector3( 0.5f, -0.5f, 0.02f ) }, - { Vector3( -0.5f, -0.5f, 0.02f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[2], 0.02f ) }, - { Vector3( 0.5f, -0.5f, 0.02f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[2], 0.02f ) }, + {Vector3(-0.5f, -0.5f, 0.02f), Vector3(-0.5f, -0.5f, 0.02f)}, + {Vector3(0.5f, -0.5f, 0.02f), Vector3(0.5f, -0.5f, 0.02f)}, + {Vector3(-0.5f, -0.5f, 0.02f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[2], 0.02f)}, + {Vector3(0.5f, -0.5f, 0.02f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[2], 0.02f)}, // mid-top layer - { Vector3( -0.5f, -0.5f, 0.03f ), Vector3( -0.5f, -0.5f, 0.03f ) }, - { Vector3( 0.5f, -0.5f, 0.03f ), Vector3( 0.5f, -0.5f, 0.03f ) }, - { Vector3( -0.5f, -0.5f, 0.03f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[3], 0.03f ) }, - { Vector3( 0.5f, -0.5f, 0.03f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[3], 0.03f ) }, + {Vector3(-0.5f, -0.5f, 0.03f), Vector3(-0.5f, -0.5f, 0.03f)}, + {Vector3(0.5f, -0.5f, 0.03f), Vector3(0.5f, -0.5f, 0.03f)}, + {Vector3(-0.5f, -0.5f, 0.03f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[3], 0.03f)}, + {Vector3(0.5f, -0.5f, 0.03f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[3], 0.03f)}, // top layer - { Vector3( -0.5f, -0.5f, 0.04f ), Vector3( -0.5f, -0.5f, 0.04f ) }, - { Vector3( 0.5f, -0.5f, 0.04f ), Vector3( 0.5f, -0.5f, 0.04f ) }, - { Vector3( -0.5f, -0.5f, 0.04f ), Vector3( -0.5f, -0.5f + LAYER_HEIGHTS[4], 0.04f ) }, - { Vector3( 0.5f, -0.5f, 0.04f ), Vector3( 0.5f, -0.5f+ LAYER_HEIGHTS[4], 0.04f ) } - }; + {Vector3(-0.5f, -0.5f, 0.04f), Vector3(-0.5f, -0.5f, 0.04f)}, + {Vector3(0.5f, -0.5f, 0.04f), Vector3(0.5f, -0.5f, 0.04f)}, + {Vector3(-0.5f, -0.5f, 0.04f), Vector3(-0.5f, -0.5f + LAYER_HEIGHTS[4], 0.04f)}, + {Vector3(0.5f, -0.5f, 0.04f), Vector3(0.5f, -0.5f + LAYER_HEIGHTS[4], 0.04f)}}; Property::Map vertexFormat; vertexFormat["aPosition1"] = Property::VECTOR3; vertexFormat["aPosition2"] = Property::VECTOR3; - VertexBuffer vertices = VertexBuffer::New( vertexFormat ); - vertices.SetData( vertexData, 20u ); + VertexBuffer vertices = VertexBuffer::New(vertexFormat); + vertices.SetData(vertexData, 20u); - unsigned short indexData[30] = { 0,3,1,0,2,3,4,7,5,4,6,7,8,11,9,8,10,11,12,15,13,12,14,15,16,19,17,16,18,19}; + unsigned short indexData[30] = {0, 3, 1, 0, 2, 3, 4, 7, 5, 4, 6, 7, 8, 11, 9, 8, 10, 11, 12, 15, 13, 12, 14, 15, 16, 19, 17, 16, 18, 19}; Geometry meshGeometry = Geometry::New(); - meshGeometry.AddVertexBuffer( vertices ); - meshGeometry.SetIndexBuffer( indexData, sizeof(indexData)/sizeof(indexData[0]) ); + meshGeometry.AddVertexBuffer(vertices); + meshGeometry.SetIndexBuffer(indexData, sizeof(indexData) / sizeof(indexData[0])); // Create the shader - Shader shader = Shader::New( SHADER_BOUNCING_EFFECT_MESH_SHADER_VERT, SHADER_BOUNCING_EFFECT_MESH_SHADER_FRAG ); + Shader shader = Shader::New(SHADER_BOUNCING_EFFECT_MESH_SHADER_VERT, SHADER_BOUNCING_EFFECT_MESH_SHADER_FRAG); // Create renderer - Renderer renderer = Renderer::New( meshGeometry, shader ); + Renderer renderer = Renderer::New(meshGeometry, shader); // Create actor - Actor meshActor= Actor::New(); - meshActor.AddRenderer( renderer ); + Actor meshActor = Actor::New(); + meshActor.AddRenderer(renderer); // Register property bouncePropertyIndex = meshActor.RegisterProperty("uBounceCoefficient", 0.f); diff --git a/dali-toolkit/internal/controls/scrollable/item-view/depth-layout.cpp b/dali-toolkit/internal/controls/scrollable/item-view/depth-layout.cpp old mode 100755 new mode 100644 index da233b8..36a08b5 --- a/dali-toolkit/internal/controls/scrollable/item-view/depth-layout.cpp +++ b/dali-toolkit/internal/controls/scrollable/item-view/depth-layout.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,146 +19,145 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include using namespace Dali; using namespace Dali::Toolkit; namespace // unnamed namespace { - const unsigned int DEFAULT_NUMBER_OF_COLUMNS = 3; const float DEFAULT_NUMBER_OF_ROWS = 26.0f; const float DEFAULT_ROW_SPACING = 55.0f; const float DEFAULT_BOTTOM_MARGIN_FACTOR = 0.2f; -const Radian DEFAULT_TILT_ANGLE ( Math::PI*0.15f ); -const Radian DEFAULT_ITEM_TILT_ANGLE ( -Math::PI*0.025f ); -const float DEFAULT_SCROLL_SPEED_FACTOR = 0.02f; -const float DEFAULT_MAXIMUM_SWIPE_SPEED = 50.0f; +const Radian DEFAULT_TILT_ANGLE(Math::PI * 0.15f); +const Radian DEFAULT_ITEM_TILT_ANGLE(-Math::PI * 0.025f); +const float DEFAULT_SCROLL_SPEED_FACTOR = 0.02f; +const float DEFAULT_MAXIMUM_SWIPE_SPEED = 50.0f; const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.03f; -inline float GetColumnPosition( unsigned int numberOfColumns, unsigned int columnNumber, const Vector3& itemSize, float layoutWidth ) +inline float GetColumnPosition(unsigned int numberOfColumns, unsigned int columnNumber, const Vector3& itemSize, float layoutWidth) { // Share the available space between margins & column spacings - float availableSpace = std::max( 0.0f, ( layoutWidth - itemSize.width * numberOfColumns ) ); + float availableSpace = std::max(0.0f, (layoutWidth - itemSize.width * numberOfColumns)); float leftMargin = availableSpace / numberOfColumns * 0.5f; - float columnPosition = leftMargin + itemSize.width * 0.5f + columnNumber * ( itemSize.width + availableSpace / numberOfColumns ); + float columnPosition = leftMargin + itemSize.width * 0.5f + columnNumber * (itemSize.width + availableSpace / numberOfColumns); return columnPosition - layoutWidth * 0.5f; } struct DepthPositionConstraint { - DepthPositionConstraint( unsigned int itemId, - unsigned int numberOfColumns, - unsigned int columnNumber, - const Vector3& itemSize, - float heightScale, - float depthScale ) - : mItemSize( itemSize ), - mItemId( itemId ), - mNumberOfColumns( numberOfColumns ), - mColumnNumber( columnNumber ), - mHeightScale( heightScale ), - mDepthScale( depthScale ) + DepthPositionConstraint(unsigned int itemId, + unsigned int numberOfColumns, + unsigned int columnNumber, + const Vector3& itemSize, + float heightScale, + float depthScale) + : mItemSize(itemSize), + mItemId(itemId), + mNumberOfColumns(numberOfColumns), + mColumnNumber(columnNumber), + mHeightScale(heightScale), + mDepthScale(depthScale) { } - inline void Orientation0( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation0(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber ); + float rowLayoutPositon = layoutPosition - static_cast(mColumnNumber); - current.x = GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width ); + current.x = GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width); current.y = rowLayoutPositon * mHeightScale + layoutSize.height * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.height - mItemSize.height * 0.5f; current.z = -rowLayoutPositon * mDepthScale; } - inline void Orientation90( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation90(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber ) + mNumberOfColumns * 0.5f; + float rowLayoutPositon = layoutPosition - static_cast(mColumnNumber) + mNumberOfColumns * 0.5f; current.x = rowLayoutPositon * mHeightScale + layoutSize.width * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.width - mItemSize.height * 0.5f; - current.y = -GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height ); + current.y = -GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height); current.z = -rowLayoutPositon * mDepthScale; } - inline void Orientation180( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation180(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber ); + float rowLayoutPositon = layoutPosition - static_cast(mColumnNumber); - current.x = -GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width ); - current.y = -( rowLayoutPositon * mHeightScale + layoutSize.height * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.height - mItemSize.height * 0.5f ); + current.x = -GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.width); + current.y = -(rowLayoutPositon * mHeightScale + layoutSize.height * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.height - mItemSize.height * 0.5f); current.z = -rowLayoutPositon * mDepthScale; } - inline void Orientation270( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation270(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - float rowLayoutPositon = layoutPosition - static_cast< float >( mColumnNumber ) + mNumberOfColumns * 0.5f; + float rowLayoutPositon = layoutPosition - static_cast(mColumnNumber) + mNumberOfColumns * 0.5f; - current.x = -( rowLayoutPositon * mHeightScale + layoutSize.width * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.width - mItemSize.height * 0.5f ); - current.y = GetColumnPosition( mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height ); + current.x = -(rowLayoutPositon * mHeightScale + layoutSize.width * 0.5f - DEFAULT_BOTTOM_MARGIN_FACTOR * layoutSize.width - mItemSize.height * 0.5f); + current.y = GetColumnPosition(mNumberOfColumns, mColumnNumber, mItemSize, layoutSize.height); current.z = -rowLayoutPositon * mDepthScale; } - void Orientation0( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation0(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation0( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation0(current, layoutPosition, layoutSize); } - void Orientation90( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation90(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation90( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation90(current, layoutPosition, layoutSize); } - void Orientation180( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation180(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation180( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation180(current, layoutPosition, layoutSize); } - void Orientation270( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation270(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation270( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation270(current, layoutPosition, layoutSize); } - Vector3 mItemSize; + Vector3 mItemSize; unsigned int mItemId; unsigned int mNumberOfColumns; unsigned int mColumnNumber; - float mHeightScale; - float mDepthScale; + float mHeightScale; + float mDepthScale; }; struct DepthRotationConstraint { - DepthRotationConstraint( Radian angleRadians, ControlOrientation::Type orientation ) - : mTiltAngle( angleRadians ), - mMultiplier( 0.0f ) + DepthRotationConstraint(Radian angleRadians, ControlOrientation::Type orientation) + : mTiltAngle(angleRadians), + mMultiplier(0.0f) { - if ( orientation == ControlOrientation::Up ) + if(orientation == ControlOrientation::Up) { mMultiplier = 0.0f; } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { mMultiplier = 1.5f; } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { mMultiplier = -1.0f; } @@ -168,51 +167,51 @@ struct DepthRotationConstraint } } - void operator()( Quaternion& current, const PropertyInputContainer& /* inputs */ ) + void operator()(Quaternion& current, const PropertyInputContainer& /* inputs */) { - current = Quaternion( Radian( mMultiplier * Math::PI ), Vector3::ZAXIS ) * Quaternion( mTiltAngle, Vector3::XAXIS ); + current = Quaternion(Radian(mMultiplier * Math::PI), Vector3::ZAXIS) * Quaternion(mTiltAngle, Vector3::XAXIS); } Radian mTiltAngle; - float mMultiplier; + float mMultiplier; }; struct DepthColorConstraint { - DepthColorConstraint( unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber ) - : mItemId( itemId ), - mNumberOfColumns( numberOfColumns ), - mNumberOfRows( numberOfRows ), - mColumnNumber( columnNumber ) + DepthColorConstraint(unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber) + : mItemId(itemId), + mNumberOfColumns(numberOfColumns), + mNumberOfRows(numberOfRows), + mColumnNumber(columnNumber) { } - void operator()( Vector4& current, const Dali::PropertyInputContainer& inputs ) + void operator()(Vector4& current, const Dali::PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - float row = ( layoutPosition - static_cast( mColumnNumber ) ) / mNumberOfColumns; + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + float row = (layoutPosition - static_cast(mColumnNumber)) / mNumberOfColumns; float darkness(1.0f); float alpha(1.0f); - if (row < 0.0f) + if(row < 0.0f) { darkness = alpha = std::max(0.0f, 1.0f + row); } else { - if (row > mNumberOfRows) + if(row > mNumberOfRows) { darkness = 0.0f; } else { - darkness = 1.0f - ( 1.0f * (row / mNumberOfRows) ); + darkness = 1.0f - (1.0f * (row / mNumberOfRows)); } - if (row > (mNumberOfRows-1.0f)) + if(row > (mNumberOfRows - 1.0f)) { - alpha = std::max(0.0f, 1.0f - (row-(mNumberOfRows-1.0f))); + alpha = std::max(0.0f, 1.0f - (row - (mNumberOfRows - 1.0f))); } } @@ -222,31 +221,31 @@ struct DepthColorConstraint unsigned int mItemId; unsigned int mNumberOfColumns; - float mNumberOfRows; + float mNumberOfRows; unsigned int mColumnNumber; }; struct DepthVisibilityConstraint { - DepthVisibilityConstraint( unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber ) - : mItemId( itemId ), + DepthVisibilityConstraint(unsigned int itemId, unsigned int numberOfColumns, float numberOfRows, unsigned int columnNumber) + : mItemId(itemId), mNumberOfColumns(numberOfColumns), mNumberOfRows(numberOfRows), mColumnNumber(columnNumber) { } - void operator()( bool& current, const Dali::PropertyInputContainer& inputs ) + void operator()(bool& current, const Dali::PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - float row = ( layoutPosition - static_cast< float >( mColumnNumber ) ) / mNumberOfColumns; + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + float row = (layoutPosition - static_cast(mColumnNumber)) / mNumberOfColumns; - current = ( row > -1.0f ) && ( row < mNumberOfRows ); + current = (row > -1.0f) && (row < mNumberOfRows); } unsigned int mItemId; unsigned int mNumberOfColumns; - float mNumberOfRows; + float mNumberOfRows; unsigned int mColumnNumber; }; @@ -254,13 +253,10 @@ struct DepthVisibilityConstraint namespace Dali { - namespace Toolkit { - namespace Internal { - struct DepthLayout::Impl { Impl() @@ -330,12 +326,12 @@ float DepthLayout::GetRowSpacing() const void DepthLayout::SetTiltAngle(Degree angle) { - mImpl->mTiltAngle = Degree( Clamp( angle, -45.0f, 45.0f ) ); + mImpl->mTiltAngle = Degree(Clamp(angle, -45.0f, 45.0f)); } Degree DepthLayout::GetTiltAngle() const { - return Degree( mImpl->mTiltAngle ); + return Degree(mImpl->mTiltAngle); } void DepthLayout::SetItemTiltAngle(Degree angle) @@ -345,7 +341,7 @@ void DepthLayout::SetItemTiltAngle(Degree angle) Degree DepthLayout::GetItemTiltAngle() const { - return Degree( mImpl->mItemTiltAngle ); + return Degree(mImpl->mItemTiltAngle); } void DepthLayout::SetScrollSpeedFactor(float scrollSpeed) @@ -391,19 +387,19 @@ float DepthLayout::GetClosestAnchorPosition(float layoutPosition) const float DepthLayout::GetItemScrollToPosition(unsigned int itemId) const { - float rowIndex = static_cast< float >( itemId ) / mImpl->mNumberOfColumns; + float rowIndex = static_cast(itemId) / mImpl->mNumberOfColumns; return -rowIndex * static_cast(mImpl->mNumberOfColumns); } ItemRange DepthLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const { - float firstRow = -(firstItemPosition/mImpl->mNumberOfColumns); - float lastRow = firstRow + mImpl->mNumberOfRows * 0.5f; + float firstRow = -(firstItemPosition / mImpl->mNumberOfColumns); + float lastRow = firstRow + mImpl->mNumberOfRows * 0.5f; unsigned int firstItem = static_cast(std::max(0.0f, firstRow * mImpl->mNumberOfColumns)); - unsigned int lastItem = static_cast(std::max(0.0f, lastRow * mImpl->mNumberOfColumns)); + unsigned int lastItem = static_cast(std::max(0.0f, lastRow * mImpl->mNumberOfColumns)); - return ItemRange(firstItem, lastItem+1); + return ItemRange(firstItem, lastItem + 1); } unsigned int DepthLayout::GetReserveItemCount(Vector3 layoutSize) const @@ -413,90 +409,89 @@ unsigned int DepthLayout::GetReserveItemCount(Vector3 layoutSize) const return static_cast(itemsWithinLayout); } -void DepthLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const +void DepthLayout::GetDefaultItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const { // 1x1 aspect ratio - itemSize.width = itemSize.height = itemSize.depth = ( IsVertical( GetOrientation() ) ? layoutSize.width : layoutSize.height ) / static_cast( mImpl->mNumberOfColumns + 1 ); + itemSize.width = itemSize.height = itemSize.depth = (IsVertical(GetOrientation()) ? layoutSize.width : layoutSize.height) / static_cast(mImpl->mNumberOfColumns + 1); } Degree DepthLayout::GetScrollDirection() const { - Degree scrollDirection(0.0f); + Degree scrollDirection(0.0f); ControlOrientation::Type orientation = GetOrientation(); - if ( orientation == ControlOrientation::Up ) + if(orientation == ControlOrientation::Up) { - scrollDirection = Degree( 180.0f ); + scrollDirection = Degree(180.0f); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - scrollDirection = Degree( 270.0f ); + scrollDirection = Degree(270.0f); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - scrollDirection = Degree( 0.0f ); + scrollDirection = Degree(0.0f); } else // orientation == ControlOrientation::Right { - scrollDirection = Degree( 90.0f ); + scrollDirection = Degree(90.0f); } return scrollDirection; } -void DepthLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor ) +void DepthLayout::ApplyConstraints(Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor) { - - Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor ); - if( itemView ) + Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(itemViewActor); + if(itemView) { Vector3 itemSize; - GetItemSize( itemId, layoutSize, itemSize ); + GetItemSize(itemId, layoutSize, itemSize); ControlOrientation::Type orientation = GetOrientation(); // Position constraint - Constraint constraint; - DepthPositionConstraint depthPositionStruct( itemId, - mImpl->mNumberOfColumns, - itemId % mImpl->mNumberOfColumns, - itemSize, - -sinf( mImpl->mTiltAngle ) * mImpl->mRowSpacing, - cosf( mImpl->mTiltAngle ) * mImpl->mRowSpacing ); - if ( orientation == ControlOrientation::Up ) + Constraint constraint; + DepthPositionConstraint depthPositionStruct(itemId, + mImpl->mNumberOfColumns, + itemId % mImpl->mNumberOfColumns, + itemSize, + -sinf(mImpl->mTiltAngle) * mImpl->mRowSpacing, + cosf(mImpl->mTiltAngle) * mImpl->mRowSpacing); + if(orientation == ControlOrientation::Up) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation0 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation0); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation90 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation90); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation180 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation180); } else // orientation == ControlOrientation::Right { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation270 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, depthPositionStruct, &DepthPositionConstraint::Orientation270); } - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.AddSource(ParentSource(Actor::Property::SIZE)); constraint.Apply(); // Rotation constraint - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, DepthRotationConstraint( mImpl->mItemTiltAngle, orientation ) ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, DepthRotationConstraint(mImpl->mItemTiltAngle, orientation)); constraint.Apply(); // Color constraint - constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, DepthColorConstraint( itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows*0.5f, itemId % mImpl->mNumberOfColumns ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.SetRemoveAction( Dali::Constraint::DISCARD ); + constraint = Constraint::New(actor, Actor::Property::COLOR, DepthColorConstraint(itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows * 0.5f, itemId % mImpl->mNumberOfColumns)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.SetRemoveAction(Dali::Constraint::DISCARD); constraint.Apply(); // Visibility constraint - constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, DepthVisibilityConstraint( itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows*0.5f, itemId % mImpl->mNumberOfColumns ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.SetRemoveAction( Dali::Constraint::DISCARD ); + constraint = Constraint::New(actor, Actor::Property::VISIBLE, DepthVisibilityConstraint(itemId, mImpl->mNumberOfColumns, mImpl->mNumberOfRows * 0.5f, itemId % mImpl->mNumberOfColumns)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.SetRemoveAction(Dali::Constraint::DISCARD); constraint.Apply(); } } @@ -504,9 +499,9 @@ void DepthLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector void DepthLayout::SetDepthLayoutProperties(const Property::Map& properties) { // Set any properties specified for DepthLayout. - for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx ) + for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx) { - KeyValuePair propertyPair = properties.GetKeyValue( idx ); + KeyValuePair propertyPair = properties.GetKeyValue(idx); switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey)) { case DefaultItemLayoutProperty::DEPTH_COLUMN_NUMBER: @@ -557,37 +552,37 @@ void DepthLayout::SetDepthLayoutProperties(const Property::Map& properties) } } -Vector3 DepthLayout::GetItemPosition( int itemID, float currentLayoutPosition, const Vector3& layoutSize ) const +Vector3 DepthLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const { Vector3 itemPosition = Vector3::ZERO; - const float heightScale = -sinf( mImpl->mTiltAngle ) * mImpl->mRowSpacing; - const float depthScale = cosf( mImpl->mTiltAngle ) * mImpl->mRowSpacing; + const float heightScale = -sinf(mImpl->mTiltAngle) * mImpl->mRowSpacing; + const float depthScale = cosf(mImpl->mTiltAngle) * mImpl->mRowSpacing; Vector3 itemSize; - GetItemSize( itemID, layoutSize, itemSize ); - DepthPositionConstraint positionFunctor = DepthPositionConstraint( itemID, - mImpl->mNumberOfColumns, - itemID % mImpl->mNumberOfColumns, - itemSize, - heightScale, - depthScale ); - ControlOrientation::Type orientation = GetOrientation(); - if ( orientation == ControlOrientation::Up ) + GetItemSize(itemID, layoutSize, itemSize); + DepthPositionConstraint positionFunctor = DepthPositionConstraint(itemID, + mImpl->mNumberOfColumns, + itemID % mImpl->mNumberOfColumns, + itemSize, + heightScale, + depthScale); + ControlOrientation::Type orientation = GetOrientation(); + if(orientation == ControlOrientation::Up) { - positionFunctor.Orientation0( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionFunctor.Orientation0(itemPosition, currentLayoutPosition + itemID, layoutSize); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - positionFunctor.Orientation90( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionFunctor.Orientation90(itemPosition, currentLayoutPosition + itemID, layoutSize); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - positionFunctor.Orientation180( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionFunctor.Orientation180(itemPosition, currentLayoutPosition + itemID, layoutSize); } else // orientation == ControlOrientation::Right { - positionFunctor.Orientation270( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionFunctor.Orientation270(itemPosition, currentLayoutPosition + itemID, layoutSize); } return itemPosition; @@ -602,7 +597,7 @@ DepthLayout::DepthLayout() float DepthLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) { float scrollTo = currentLayoutPosition; - float row = (currentLayoutPosition + itemID - static_cast(itemID % mImpl->mNumberOfColumns)) / mImpl->mNumberOfColumns; + float row = (currentLayoutPosition + itemID - static_cast(itemID % mImpl->mNumberOfColumns)) / mImpl->mNumberOfColumns; // Check whether item is not within viewable area if(row <= -1.0f) @@ -619,12 +614,12 @@ float DepthLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLay int DepthLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled) { - switch( direction ) + switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { itemID--; - if( itemID < 0 ) + if(itemID < 0) { itemID = loopEnabled ? maxItems - 1 : 0; } @@ -633,7 +628,7 @@ int DepthLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Con case Toolkit::Control::KeyboardFocus::UP: { itemID += mImpl->mNumberOfColumns; - if( itemID >= maxItems ) + if(itemID >= maxItems) { itemID = loopEnabled ? 0 : itemID - mImpl->mNumberOfColumns; } @@ -642,7 +637,7 @@ int DepthLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Con case Toolkit::Control::KeyboardFocus::RIGHT: { itemID++; - if( itemID >= maxItems ) + if(itemID >= maxItems) { itemID = loopEnabled ? 0 : maxItems - 1; } @@ -651,7 +646,7 @@ int DepthLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Con case Toolkit::Control::KeyboardFocus::DOWN: { itemID -= mImpl->mNumberOfColumns; - if( itemID < 0 ) + if(itemID < 0) { itemID = loopEnabled ? itemID + maxItems : itemID + mImpl->mNumberOfColumns; } diff --git a/dali-toolkit/internal/controls/scrollable/item-view/grid-layout.cpp b/dali-toolkit/internal/controls/scrollable/item-view/grid-layout.cpp old mode 100755 new mode 100644 index 435cbf3..ccab2f6 --- a/dali-toolkit/internal/controls/scrollable/item-view/grid-layout.cpp +++ b/dali-toolkit/internal/controls/scrollable/item-view/grid-layout.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,144 +19,142 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include using namespace Dali; using namespace Dali::Toolkit; namespace // unnamed namespace { - -const unsigned int DEFAULT_NUMBER_OF_COLUMNS = 4; -const float DEFAULT_TOP_MARGIN = 95.0f; -const float DEFAULT_BOTTOM_MARGIN = 20.0f; -const float DEFAULT_SIDE_MARGIN = 20.0f; -const float DEFAULT_COLUMN_SPACING = 20.0f; -const float DEFAULT_ROW_SPACING = 20.0f; -const float DEFAULT_SCROLL_SPEED_FACTOR = 0.03f; -const float DEFAULT_MAXIMUM_SWIPE_SPEED = 100.0f; -const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.015f; +const unsigned int DEFAULT_NUMBER_OF_COLUMNS = 4; +const float DEFAULT_TOP_MARGIN = 95.0f; +const float DEFAULT_BOTTOM_MARGIN = 20.0f; +const float DEFAULT_SIDE_MARGIN = 20.0f; +const float DEFAULT_COLUMN_SPACING = 20.0f; +const float DEFAULT_ROW_SPACING = 20.0f; +const float DEFAULT_SCROLL_SPEED_FACTOR = 0.03f; +const float DEFAULT_MAXIMUM_SWIPE_SPEED = 100.0f; +const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.015f; struct GridPositionConstraint { GridPositionConstraint( - unsigned int itemId, - const unsigned int columnIndex, - const unsigned int numberOfColumns, - const float rowSpacing, - const float columnSpacing, - const float topMargin, - const float sideMargin, - const Vector3& itemSize, - const float gap ) - : mItemSize( itemSize ), - mItemId( itemId ), - mColumnIndex( columnIndex ), - mNumberOfColumns( numberOfColumns ), - mRowSpacing( rowSpacing ), - mColumnSpacing( columnSpacing ), - mTopMargin( topMargin ), - mSideMargin( sideMargin ), - mZGap( gap ) + unsigned int itemId, + const unsigned int columnIndex, + const unsigned int numberOfColumns, + const float rowSpacing, + const float columnSpacing, + const float topMargin, + const float sideMargin, + const Vector3& itemSize, + const float gap) + : mItemSize(itemSize), + mItemId(itemId), + mColumnIndex(columnIndex), + mNumberOfColumns(numberOfColumns), + mRowSpacing(rowSpacing), + mColumnSpacing(columnSpacing), + mTopMargin(topMargin), + mSideMargin(sideMargin), + mZGap(gap) { } - inline void Orientation0( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation0(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - current.x = mSideMargin + ( mColumnIndex * ( mItemSize.x + mColumnSpacing ) ) + mItemSize.x * 0.5f - layoutSize.x * 0.5f; - current.y = ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex) ) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin; + current.x = mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.x * 0.5f; + current.y = ((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin; current.z = mColumnIndex * mZGap; } - inline void Orientation90( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation90(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - current.x = ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex ) ) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin; - current.y = -( mSideMargin + ( mColumnIndex * ( mItemSize.x + mColumnSpacing ) ) + mItemSize.x * 0.5f - layoutSize.y * 0.5f ); + current.x = ((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin; + current.y = -(mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.y * 0.5f); current.z = mColumnIndex * mZGap; } - inline void Orientation180( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation180(Vector3& current, float layoutPosition, const Vector3& layoutSize) { current.x = -(mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.x * 0.5f); - current.y = -( ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex ) ) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin ); + current.y = -(((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.height * 0.5f + mItemSize.y * 0.5f + mTopMargin); current.z = mColumnIndex * mZGap; } - inline void Orientation270( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void Orientation270(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - current.x = -( ( ( mItemSize.y + mRowSpacing ) * ( layoutPosition - mColumnIndex ) ) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin ); - current.y = mSideMargin + ( mColumnIndex * ( mItemSize.x + mColumnSpacing ) ) + mItemSize.x * 0.5f - layoutSize.y * 0.5f; + current.x = -(((mItemSize.y + mRowSpacing) * (layoutPosition - mColumnIndex)) / mNumberOfColumns - layoutSize.width * 0.5f + mItemSize.y * 0.5f + mTopMargin); + current.y = mSideMargin + (mColumnIndex * (mItemSize.x + mColumnSpacing)) + mItemSize.x * 0.5f - layoutSize.y * 0.5f; current.z = mColumnIndex * mZGap; } - void Orientation0( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation0(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation0( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation0(current, layoutPosition, layoutSize); } - void Orientation90( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation90(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation90( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation90(current, layoutPosition, layoutSize); } - void Orientation180( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation180(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation180( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation180(current, layoutPosition, layoutSize); } - void Orientation270( Vector3& current, const PropertyInputContainer& inputs ) + void Orientation270(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - Orientation270( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + Orientation270(current, layoutPosition, layoutSize); } public: - - Vector3 mItemSize; + Vector3 mItemSize; unsigned int mItemId; unsigned int mColumnIndex; unsigned int mNumberOfColumns; - float mRowSpacing; - float mColumnSpacing; - float mTopMargin; - float mSideMargin; - float mZGap; + float mRowSpacing; + float mColumnSpacing; + float mTopMargin; + float mSideMargin; + float mZGap; }; -void GridRotationConstraint0( Quaternion& current, const PropertyInputContainer& /* inputs */ ) +void GridRotationConstraint0(Quaternion& current, const PropertyInputContainer& /* inputs */) { - current = Quaternion( Radian( 0.0f ), Vector3::ZAXIS ); + current = Quaternion(Radian(0.0f), Vector3::ZAXIS); } -void GridRotationConstraint90( Quaternion& current, const PropertyInputContainer& /* inputs */ ) +void GridRotationConstraint90(Quaternion& current, const PropertyInputContainer& /* inputs */) { - current = Quaternion( Radian( 1.5f * Math::PI ), Vector3::ZAXIS ); + current = Quaternion(Radian(1.5f * Math::PI), Vector3::ZAXIS); } -void GridRotationConstraint180( Quaternion& current, const PropertyInputContainer& /* inputs */ ) +void GridRotationConstraint180(Quaternion& current, const PropertyInputContainer& /* inputs */) { - current = Quaternion( Radian( Math::PI ), Vector3::ZAXIS ); + current = Quaternion(Radian(Math::PI), Vector3::ZAXIS); } -void GridRotationConstraint270( Quaternion& current, const PropertyInputContainer& /* inputs */ ) +void GridRotationConstraint270(Quaternion& current, const PropertyInputContainer& /* inputs */) { - current = Quaternion( Radian( 0.5f * Math::PI ), Vector3::ZAXIS ); + current = Quaternion(Radian(0.5f * Math::PI), Vector3::ZAXIS); } -void GridColorConstraint( Vector4& current, const PropertyInputContainer& /* inputs */ ) +void GridColorConstraint(Vector4& current, const PropertyInputContainer& /* inputs */) { current.r = current.g = current.b = 1.0f; } @@ -164,67 +162,63 @@ void GridColorConstraint( Vector4& current, const PropertyInputContainer& /* inp struct GridVisibilityConstraint { GridVisibilityConstraint( - unsigned int itemId, - const unsigned int columnIndex, - const unsigned int numberOfColumns, - const float rowSpacing, - const float columnSpacing, - const float sideMargin, - const Vector3& itemSize ) - : mItemSize( itemSize ), - mItemId( itemId ), - mColumnIndex( columnIndex ), - mNumberOfColumns( numberOfColumns ), - mRowSpacing( rowSpacing ), - mColumnSpacing( columnSpacing ), - mSideMargin( sideMargin ) + unsigned int itemId, + const unsigned int columnIndex, + const unsigned int numberOfColumns, + const float rowSpacing, + const float columnSpacing, + const float sideMargin, + const Vector3& itemSize) + : mItemSize(itemSize), + mItemId(itemId), + mColumnIndex(columnIndex), + mNumberOfColumns(numberOfColumns), + mRowSpacing(rowSpacing), + mColumnSpacing(columnSpacing), + mSideMargin(sideMargin) { } - void Portrait( bool& current, const PropertyInputContainer& inputs ) + void Portrait(bool& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); - float row = ( layoutPosition - static_cast< float >( mColumnIndex ) ) / mNumberOfColumns; - int rowsPerPage = ceil( layoutSize.height / ( mItemSize.y + mRowSpacing ) ); + float row = (layoutPosition - static_cast(mColumnIndex)) / mNumberOfColumns; + int rowsPerPage = ceil(layoutSize.height / (mItemSize.y + mRowSpacing)); - current = ( row > -2.0f ) && ( row < rowsPerPage ); + current = (row > -2.0f) && (row < rowsPerPage); } - void Landscape( bool& current, const PropertyInputContainer& inputs ) + void Landscape(bool& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); - float row = ( layoutPosition - static_cast< float >( mColumnIndex ) ) / mNumberOfColumns; - int rowsPerPage = ceil( layoutSize.width / ( mItemSize.y + mRowSpacing ) ); + float row = (layoutPosition - static_cast(mColumnIndex)) / mNumberOfColumns; + int rowsPerPage = ceil(layoutSize.width / (mItemSize.y + mRowSpacing)); - current = ( row > -2.0f ) && ( row < rowsPerPage ); + current = (row > -2.0f) && (row < rowsPerPage); } public: - - Vector3 mItemSize; + Vector3 mItemSize; unsigned int mItemId; unsigned int mColumnIndex; unsigned int mNumberOfColumns; - float mRowSpacing; - float mColumnSpacing; - float mSideMargin; + float mRowSpacing; + float mColumnSpacing; + float mSideMargin; }; } // unnamed namespace namespace Dali { - namespace Toolkit { - namespace Internal { - struct GridLayout::Impl { Impl() @@ -242,12 +236,12 @@ struct GridLayout::Impl } unsigned int mNumberOfColumns; - float mRowSpacing; - float mColumnSpacing; - float mTopMargin; - float mBottomMargin; - float mSideMargin; - float mZGap; + float mRowSpacing; + float mColumnSpacing; + float mTopMargin; + float mBottomMargin; + float mSideMargin; + float mZGap; float mScrollSpeedFactor; float mMaximumSwipeSpeed; @@ -366,18 +360,18 @@ float GridLayout::GetItemFlickAnimationDuration() const float GridLayout::GetMinimumLayoutPosition(unsigned int numberOfItems, Vector3 layoutSize) const { - float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; + float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height; Vector3 itemSize; - GetItemSize( 0, layoutSize, itemSize ); + GetItemSize(0, layoutSize, itemSize); unsigned int itemsLastRow = numberOfItems % mImpl->mNumberOfColumns; - if (itemsLastRow == 0) + if(itemsLastRow == 0) { itemsLastRow = mImpl->mNumberOfColumns; } - float rowsLastPage = (layoutHeight - mImpl->mBottomMargin - mImpl->mTopMargin + mImpl->mRowSpacing) / (itemSize.y + mImpl->mRowSpacing); + float rowsLastPage = (layoutHeight - mImpl->mBottomMargin - mImpl->mTopMargin + mImpl->mRowSpacing) / (itemSize.y + mImpl->mRowSpacing); float itemsLastPage = (rowsLastPage - 1.0f) * static_cast(mImpl->mNumberOfColumns) + static_cast(itemsLastRow); return itemsLastPage - static_cast(numberOfItems); @@ -391,18 +385,18 @@ float GridLayout::GetClosestAnchorPosition(float layoutPosition) const float GridLayout::GetItemScrollToPosition(unsigned int itemId) const { - float rowIndex = static_cast< float >( itemId ) / mImpl->mNumberOfColumns; + float rowIndex = static_cast(itemId) / mImpl->mNumberOfColumns; return -rowIndex * static_cast(mImpl->mNumberOfColumns); } ItemRange GridLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const { - float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; + float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height; Vector3 itemSize; - GetItemSize( 0, layoutSize, itemSize ); + GetItemSize(0, layoutSize, itemSize); - int itemsPerPage = mImpl->mNumberOfColumns * ceil(layoutHeight / (itemSize.y + mImpl->mRowSpacing)); + int itemsPerPage = mImpl->mNumberOfColumns * ceil(layoutHeight / (itemSize.y + mImpl->mRowSpacing)); int firstVisibleItem = -(static_cast(firstItemPosition / mImpl->mNumberOfColumns)) * mImpl->mNumberOfColumns; int firstItemIndex = std::max(0, firstVisibleItem - static_cast(mImpl->mNumberOfColumns)); @@ -413,22 +407,19 @@ ItemRange GridLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layout float GridLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) { - Vector3 itemPosition = GetItemPosition( itemID, currentLayoutPosition, layoutSize ); - Vector3 itemSize; + Vector3 itemPosition = GetItemPosition(itemID, currentLayoutPosition, layoutSize); + Vector3 itemSize; ControlOrientation::Type orientation = GetOrientation(); GetItemSize(itemID, layoutSize, itemSize); - Vector3 onScreenArea = ( layoutSize - ( IsVertical( orientation ) ? itemSize : Vector3( itemSize.y, itemSize.x, itemSize.z ) ) ) * 0.5f; - if (itemPosition.x < -onScreenArea.x - || itemPosition.x > onScreenArea.x - || itemPosition.y < -onScreenArea.y - || itemPosition.y > onScreenArea.y) + Vector3 onScreenArea = (layoutSize - (IsVertical(orientation) ? itemSize : Vector3(itemSize.y, itemSize.x, itemSize.z))) * 0.5f; + if(itemPosition.x < -onScreenArea.x || itemPosition.x > onScreenArea.x || itemPosition.y < -onScreenArea.y || itemPosition.y > onScreenArea.y) { // item not within viewable area - float rowHeight = itemSize.y + mImpl->mRowSpacing; - Vector3 firstItemPosition = GetItemPosition( itemID, 0.0f, layoutSize ); - float offset = 0.0f; - switch( orientation ) + float rowHeight = itemSize.y + mImpl->mRowSpacing; + Vector3 firstItemPosition = GetItemPosition(itemID, 0.0f, layoutSize); + float offset = 0.0f; + switch(orientation) { case ControlOrientation::Up: { @@ -480,9 +471,9 @@ float GridLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayo } } // work out number of rows from first item position to an item aligned to bottom of screen - float rowDiff = offset / rowHeight; + float rowDiff = offset / rowHeight; float layoutPositionOffset = rowDiff * mImpl->mNumberOfColumns; - float scrollTo = GetItemScrollToPosition(itemID) + layoutPositionOffset; + float scrollTo = GetItemScrollToPosition(itemID) + layoutPositionOffset; return scrollTo; } return currentLayoutPosition; @@ -490,18 +481,18 @@ float GridLayout::GetClosestOnScreenLayoutPosition(int itemID, float currentLayo unsigned int GridLayout::GetReserveItemCount(Vector3 layoutSize) const { - float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; + float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height; Vector3 itemSize; - GetItemSize( 0, layoutSize, itemSize ); + GetItemSize(0, layoutSize, itemSize); int itemsPerPage = mImpl->mNumberOfColumns * ceil(layoutHeight / (itemSize.y + mImpl->mRowSpacing)); return itemsPerPage; } -void GridLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const +void GridLayout::GetDefaultItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const { - float layoutWidth = IsHorizontal( GetOrientation() ) ? layoutSize.height : layoutSize.width; - itemSize.width = ( layoutWidth - mImpl->mSideMargin * 2.0f - mImpl->mColumnSpacing * static_cast( mImpl->mNumberOfColumns - 1 ) ) / static_cast( mImpl->mNumberOfColumns ); + float layoutWidth = IsHorizontal(GetOrientation()) ? layoutSize.height : layoutSize.width; + itemSize.width = (layoutWidth - mImpl->mSideMargin * 2.0f - mImpl->mColumnSpacing * static_cast(mImpl->mNumberOfColumns - 1)) / static_cast(mImpl->mNumberOfColumns); // 4x3 aspect ratio itemSize.height = itemSize.depth = itemSize.width * 0.75f; @@ -509,115 +500,115 @@ void GridLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutS Degree GridLayout::GetScrollDirection() const { - Degree scrollDirection(0.0f); + Degree scrollDirection(0.0f); ControlOrientation::Type orientation = GetOrientation(); - if ( orientation == ControlOrientation::Up ) + if(orientation == ControlOrientation::Up) { - scrollDirection = Degree( 0.0f ); + scrollDirection = Degree(0.0f); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - scrollDirection = Degree( 90.0f ); + scrollDirection = Degree(90.0f); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - scrollDirection = Degree( 180.0f ); + scrollDirection = Degree(180.0f); } else // orientation == ControlOrientation::Right { - scrollDirection = Degree( 270.0f ); + scrollDirection = Degree(270.0f); } return scrollDirection; } -void GridLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor ) +void GridLayout::ApplyConstraints(Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor) { // This just implements the default behaviour of constraint application. // Custom layouts can override this function to apply their custom constraints. - Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor ); - if( itemView ) + Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(itemViewActor); + if(itemView) { Vector3 itemSize; - GetItemSize( itemId, layoutSize, itemSize ); - const unsigned int columnIndex = itemId % mImpl->mNumberOfColumns; + GetItemSize(itemId, layoutSize, itemSize); + const unsigned int columnIndex = itemId % mImpl->mNumberOfColumns; const ControlOrientation::Type orientation = GetOrientation(); // Position constraint - GridPositionConstraint positionConstraint( itemId, - columnIndex, - mImpl->mNumberOfColumns, - mImpl->mRowSpacing, - mImpl->mColumnSpacing, - mImpl->mTopMargin, - mImpl->mSideMargin, - itemSize, - mImpl->mZGap ); - Constraint constraint; - if ( orientation == ControlOrientation::Up ) + GridPositionConstraint positionConstraint(itemId, + columnIndex, + mImpl->mNumberOfColumns, + mImpl->mRowSpacing, + mImpl->mColumnSpacing, + mImpl->mTopMargin, + mImpl->mSideMargin, + itemSize, + mImpl->mZGap); + Constraint constraint; + if(orientation == ControlOrientation::Up) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation0 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation0); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation90 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation90); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation180 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation180); } else // orientation == ControlOrientation::Right { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation270 ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &GridPositionConstraint::Orientation270); } - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.AddSource(ParentSource(Actor::Property::SIZE)); constraint.Apply(); // Rotation constraint - if ( orientation == ControlOrientation::Up ) + if(orientation == ControlOrientation::Up) { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint0 ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, &GridRotationConstraint0); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint90 ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, &GridRotationConstraint90); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint180 ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, &GridRotationConstraint180); } else // orientation == ControlOrientation::Right { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, &GridRotationConstraint270 ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, &GridRotationConstraint270); } constraint.Apply(); // Color constraint - constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, &GridColorConstraint ); - constraint.SetRemoveAction( Dali::Constraint::DISCARD ); + constraint = Constraint::New(actor, Actor::Property::COLOR, &GridColorConstraint); + constraint.SetRemoveAction(Dali::Constraint::DISCARD); constraint.Apply(); // Visibility constraint - GridVisibilityConstraint visibilityConstraint( itemId, - columnIndex, - mImpl->mNumberOfColumns, - mImpl->mRowSpacing, - mImpl->mColumnSpacing, - mImpl->mSideMargin, - itemSize ); - if ( IsVertical( orientation ) ) + GridVisibilityConstraint visibilityConstraint(itemId, + columnIndex, + mImpl->mNumberOfColumns, + mImpl->mRowSpacing, + mImpl->mColumnSpacing, + mImpl->mSideMargin, + itemSize); + if(IsVertical(orientation)) { - constraint = Constraint::New( actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Portrait ); + constraint = Constraint::New(actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Portrait); } else // horizontal { - constraint = Constraint::New( actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Landscape ); + constraint = Constraint::New(actor, Actor::Property::VISIBLE, visibilityConstraint, &GridVisibilityConstraint::Landscape); } - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); - constraint.SetRemoveAction( Dali::Constraint::DISCARD ); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.AddSource(ParentSource(Actor::Property::SIZE)); + constraint.SetRemoveAction(Dali::Constraint::DISCARD); constraint.Apply(); } } @@ -625,9 +616,9 @@ void GridLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3 void GridLayout::SetGridLayoutProperties(const Property::Map& properties) { // Set any properties specified for gridLayout. - for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx ) + for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx) { - KeyValuePair propertyPair = properties.GetKeyValue( idx ); + KeyValuePair propertyPair = properties.GetKeyValue(idx); switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey)) { case DefaultItemLayoutProperty::GRID_COLUMN_NUMBER: @@ -685,37 +676,37 @@ void GridLayout::SetGridLayoutProperties(const Property::Map& properties) Vector3 GridLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const { - Vector3 itemPosition = Vector3::ZERO; - const unsigned int columnIndex = itemID % mImpl->mNumberOfColumns; - const ControlOrientation::Type orientation = GetOrientation(); - Vector3 itemSize; - GetItemSize( itemID, layoutSize, itemSize ); - - GridPositionConstraint positionConstraintStruct( itemID, - columnIndex, - mImpl->mNumberOfColumns, - mImpl->mRowSpacing, - mImpl->mColumnSpacing, - mImpl->mTopMargin, - mImpl->mSideMargin, - itemSize, - mImpl->mZGap ); - - if ( orientation == ControlOrientation::Up ) + Vector3 itemPosition = Vector3::ZERO; + const unsigned int columnIndex = itemID % mImpl->mNumberOfColumns; + const ControlOrientation::Type orientation = GetOrientation(); + Vector3 itemSize; + GetItemSize(itemID, layoutSize, itemSize); + + GridPositionConstraint positionConstraintStruct(itemID, + columnIndex, + mImpl->mNumberOfColumns, + mImpl->mRowSpacing, + mImpl->mColumnSpacing, + mImpl->mTopMargin, + mImpl->mSideMargin, + itemSize, + mImpl->mZGap); + + if(orientation == ControlOrientation::Up) { - positionConstraintStruct.Orientation0( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraintStruct.Orientation0(itemPosition, currentLayoutPosition + itemID, layoutSize); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - positionConstraintStruct.Orientation90( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraintStruct.Orientation90(itemPosition, currentLayoutPosition + itemID, layoutSize); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - positionConstraintStruct.Orientation180( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraintStruct.Orientation180(itemPosition, currentLayoutPosition + itemID, layoutSize); } else // orientation == ControlOrientation::Right { - positionConstraintStruct.Orientation270( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraintStruct.Orientation270(itemPosition, currentLayoutPosition + itemID, layoutSize); } return itemPosition; @@ -723,12 +714,12 @@ Vector3 GridLayout::GetItemPosition(int itemID, float currentLayoutPosition, con int GridLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Control::KeyboardFocus::Direction direction, bool loopEnabled) { - switch( direction ) + switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { itemID--; - if( itemID < 0 ) + if(itemID < 0) { itemID = loopEnabled ? maxItems - 1 : 0; } @@ -737,7 +728,7 @@ int GridLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Cont case Toolkit::Control::KeyboardFocus::UP: { itemID -= mImpl->mNumberOfColumns; - if( itemID < 0 ) + if(itemID < 0) { itemID = loopEnabled ? itemID + maxItems : itemID + mImpl->mNumberOfColumns; } @@ -746,7 +737,7 @@ int GridLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Cont case Toolkit::Control::KeyboardFocus::RIGHT: { itemID++; - if( itemID >= maxItems ) + if(itemID >= maxItems) { itemID = loopEnabled ? 0 : maxItems - 1; } @@ -755,7 +746,7 @@ int GridLayout::GetNextFocusItemID(int itemID, int maxItems, Dali::Toolkit::Cont case Toolkit::Control::KeyboardFocus::DOWN: { itemID += mImpl->mNumberOfColumns; - if( itemID >= maxItems ) + if(itemID >= maxItems) { itemID = loopEnabled ? 0 : itemID - mImpl->mNumberOfColumns; } diff --git a/dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.cpp b/dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.cpp index b8b8baf..699aee4 100644 --- a/dali-toolkit/internal/controls/scrollable/item-view/item-view-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/item-view/item-view-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,52 +19,51 @@ #include // EXTERNAL INCLUDES -#include // for strcmp -#include -#include #include +#include +#include +#include #include #include -#include -#include #include -#include +#include #include -#include +#include +#include +#include // for strcmp // INTERNAL INCLUDES #include -#include -#include -#include -#include +#include #include +#include #include -#include +#include +#include +#include using std::string; using namespace Dali; namespace // Unnamed namespace { - -const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f; -const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f; +const float DEFAULT_MINIMUM_SWIPE_SPEED = 1.0f; +const float DEFAULT_MINIMUM_SWIPE_DISTANCE = 3.0f; const float DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = 0.1f; const float DEFAULT_MINIMUM_SWIPE_DURATION = 0.45f; const float DEFAULT_MAXIMUM_SWIPE_DURATION = 2.6f; const float DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS = 20.0f; // 1 updates per 20 items -const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second +const int WHEEL_EVENT_FINISHED_TIME_OUT = 500; // 0.5 second -const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second +const float DEFAULT_ANCHORING_DURATION = 1.0f; // 1 second const float MILLISECONDS_PER_SECONDS = 1000.0f; -const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f; +const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f; const Vector4 OVERSHOOT_OVERLAY_NINE_PATCH_BORDER(0.0f, 0.0f, 1.0f, 12.0f); -const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f; +const float DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION = 0.2f; const unsigned int OVERSHOOT_SIZE_CONSTRAINT_TAG(42); @@ -84,16 +83,16 @@ float CalculateScrollDistance(Vector2 panDistance, Toolkit::ItemLayout& layout) // Overshoot overlay constraints struct OvershootOverlaySizeConstraint { - OvershootOverlaySizeConstraint( float height ) - : mOvershootHeight( height ) + OvershootOverlaySizeConstraint(float height) + : mOvershootHeight(height) { } - void operator()( Vector3& current, const PropertyInputContainer& inputs ) + void operator()(Vector3& current, const PropertyInputContainer& inputs) { - const Vector2& parentScrollDirection = inputs[0]->GetVector2(); - const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast(inputs[1]->GetInteger()); - const Vector3& parentSize = inputs[2]->GetVector3(); + const Vector2& parentScrollDirection = inputs[0]->GetVector2(); + const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast(inputs[1]->GetInteger()); + const Vector3& parentSize = inputs[2]->GetVector3(); if(Toolkit::IsVertical(layoutOrientation)) { @@ -104,25 +103,24 @@ struct OvershootOverlaySizeConstraint current.width = fabsf(parentScrollDirection.x) > Math::MACHINE_EPSILON_1 ? parentSize.y : parentSize.x; } - current.height = ( current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD ) ? mOvershootHeight : mOvershootHeight*0.5f; + current.height = (current.width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD) ? mOvershootHeight : mOvershootHeight * 0.5f; } float mOvershootHeight; }; -void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInputContainer& inputs ) +void OvershootOverlayRotationConstraint(Quaternion& current, const PropertyInputContainer& inputs) { - const Vector2& parentScrollDirection = inputs[0]->GetVector2(); - const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast(inputs[1]->GetInteger()); - const float parentOvershoot = inputs[2]->GetFloat(); + const Vector2& parentScrollDirection = inputs[0]->GetVector2(); + const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast(inputs[1]->GetInteger()); + const float parentOvershoot = inputs[2]->GetFloat(); float multiplier = 0; if(Toolkit::IsVertical(layoutOrientation)) { if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1) { - if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0) - || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) ) + if((layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0)) { multiplier = 0.5f; } @@ -131,8 +129,7 @@ void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInpu multiplier = 1.5f; } } - else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0) - || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) ) + else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0)) { multiplier = 0.0f; } @@ -145,8 +142,7 @@ void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInpu { if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1) { - if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0) - ||(layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0) ) + if((layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot > Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot < Math::MACHINE_EPSILON_0)) { multiplier = 1.0f; } @@ -155,8 +151,7 @@ void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInpu multiplier = 0.0f; } } - else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0) - || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) ) + else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0)) { multiplier = 1.5f; } @@ -166,15 +161,15 @@ void OvershootOverlayRotationConstraint( Quaternion& current, const PropertyInpu } } - current = Quaternion( Radian( multiplier * Math::PI ), Vector3::ZAXIS ); + current = Quaternion(Radian(multiplier * Math::PI), Vector3::ZAXIS); } -void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputContainer& inputs ) +void OvershootOverlayPositionConstraint(Vector3& current, const PropertyInputContainer& inputs) { - const Vector3& parentSize = inputs[0]->GetVector3(); - const Vector2& parentScrollDirection = inputs[1]->GetVector2(); - const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast(inputs[2]->GetInteger()); - const float parentOvershoot = inputs[3]->GetFloat(); + const Vector3& parentSize = inputs[0]->GetVector3(); + const Vector2& parentScrollDirection = inputs[1]->GetVector2(); + const Toolkit::ControlOrientation::Type& layoutOrientation = static_cast(inputs[2]->GetInteger()); + const float parentOvershoot = inputs[3]->GetFloat(); Vector3 relativeOffset; @@ -182,18 +177,16 @@ void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputCo { if(fabsf(parentScrollDirection.y) <= Math::MACHINE_EPSILON_1) { - if( (layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0) - || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0) ) + if((layoutOrientation == Toolkit::ControlOrientation::Up && parentOvershoot < Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Down && parentOvershoot > Math::MACHINE_EPSILON_0)) { relativeOffset = Vector3(1.0f, 0.0f, 0.0f); } else { - relativeOffset =Vector3(0.0f, 1.0f, 0.0f); + relativeOffset = Vector3(0.0f, 1.0f, 0.0f); } } - else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0) - || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0) ) + else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.y > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.y < Math::MACHINE_EPSILON_0)) { relativeOffset = Vector3(0.0f, 0.0f, 0.0f); } @@ -206,8 +199,7 @@ void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputCo { if(fabsf(parentScrollDirection.x) <= Math::MACHINE_EPSILON_1) { - if( (layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0) - || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0) ) + if((layoutOrientation == Toolkit::ControlOrientation::Left && parentOvershoot < Math::MACHINE_EPSILON_0) || (layoutOrientation == Toolkit::ControlOrientation::Right && parentOvershoot > Math::MACHINE_EPSILON_0)) { relativeOffset = Vector3(0.0f, 0.0f, 0.0f); } @@ -216,8 +208,7 @@ void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputCo relativeOffset = Vector3(1.0f, 1.0f, 0.0f); } } - else if( (parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0) - || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0) ) + else if((parentOvershoot > Math::MACHINE_EPSILON_0 && parentScrollDirection.x > Math::MACHINE_EPSILON_0) || (parentOvershoot < Math::MACHINE_EPSILON_0 && parentScrollDirection.x < Math::MACHINE_EPSILON_0)) { relativeOffset = Vector3(0.0f, 1.0f, 0.0f); } @@ -230,7 +221,7 @@ void OvershootOverlayPositionConstraint( Vector3& current, const PropertyInputCo current = relativeOffset * parentSize; } -void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputContainer& inputs ) +void OvershootOverlayVisibilityConstraint(bool& current, const PropertyInputContainer& inputs) { current = inputs[0]->GetBoolean(); } @@ -239,49 +230,46 @@ void OvershootOverlayVisibilityConstraint( bool& current, const PropertyInputCon namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // unnamed namespace { - //Type registration +// clang-format off +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ItemView, Toolkit::Scrollable, nullptr) -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ItemView, Toolkit::Scrollable, NULL) +DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED ) +DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE ) +DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP) +DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED ) +DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, ItemView, "layout", ARRAY, LAYOUT ) -DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeSpeed", FLOAT, MINIMUM_SWIPE_SPEED ) -DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "minimumSwipeDistance", FLOAT, MINIMUM_SWIPE_DISTANCE ) -DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "wheelScrollDistanceStep", FLOAT, WHEEL_SCROLL_DISTANCE_STEP ) -DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "snapToItemEnabled", BOOLEAN, SNAP_TO_ITEM_ENABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "refreshInterval", FLOAT, REFRESH_INTERVAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, ItemView, "layout", ARRAY, LAYOUT ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION ) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutPosition", FLOAT, LAYOUT_POSITION) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollSpeed", FLOAT, SCROLL_SPEED) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "overshoot", FLOAT, OVERSHOOT) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollDirection", VECTOR2, SCROLL_DIRECTION) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "layoutOrientation", INTEGER, LAYOUT_ORIENTATION) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ItemView, "scrollContentSize", FLOAT, SCROLL_CONTENT_SIZE) +DALI_SIGNAL_REGISTRATION(Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL) -DALI_SIGNAL_REGISTRATION( Toolkit, ItemView, "layoutActivated", LAYOUT_ACTIVATED_SIGNAL ) +DALI_ACTION_REGISTRATION(Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING) -DALI_ACTION_REGISTRATION( Toolkit, ItemView, "stopScrolling", ACTION_STOP_SCROLLING ) - -DALI_ACTION_REGISTRATION( Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH ) -DALI_ACTION_REGISTRATION( Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH ) +DALI_ACTION_REGISTRATION(Toolkit, ItemView, "enableRefresh", ACTION_ENABLE_REFRESH ) +DALI_ACTION_REGISTRATION(Toolkit, ItemView, "disableRefresh", ACTION_DISABLE_REFRESH) DALI_TYPE_REGISTRATION_END() +// clang-format on -const ItemIter FindItemById( ItemContainer& items, ItemId id ) +const ItemIter FindItemById(ItemContainer& items, ItemId id) { - for( ItemIter iter = items.begin(); items.end() != iter; ++iter ) + for(ItemIter iter = items.begin(); items.end() != iter; ++iter) { - if( iter->first == id ) + if(iter->first == id) { return iter; } @@ -290,28 +278,27 @@ const ItemIter FindItemById( ItemContainer& items, ItemId id ) return items.end(); } -void InsertToItemContainer( ItemContainer& items, Item item ) +void InsertToItemContainer(ItemContainer& items, Item item) { - if( items.end() == FindItemById( items, item.first ) ) + if(items.end() == FindItemById(items, item.first)) { - ItemIter iterToInsert = std::lower_bound( items.begin(), items.end(), item ); - items.insert( iterToInsert, item ); + ItemIter iterToInsert = std::lower_bound(items.begin(), items.end(), item); + items.insert(iterToInsert, item); } } - /** * Helper to apply size constraint to mOvershootOverlay * @param[in] overshootOverlay The overshootOverlay actor * @param[in] The required height */ -void ApplyOvershootSizeConstraint( Actor overshootOverlay, float height ) +void ApplyOvershootSizeConstraint(Actor overshootOverlay, float height) { - Constraint constraint = Constraint::New( overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint( height ) ); - constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION ) ); - constraint.AddSource( ParentSource( Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) ); - constraint.AddSource( ParentSource( Dali::Actor::Property::SIZE ) ); - constraint.SetTag( OVERSHOOT_SIZE_CONSTRAINT_TAG ); + Constraint constraint = Constraint::New(overshootOverlay, Actor::Property::SIZE, OvershootOverlaySizeConstraint(height)); + constraint.AddSource(ParentSource(Dali::Toolkit::ItemView::Property::SCROLL_DIRECTION)); + constraint.AddSource(ParentSource(Dali::Toolkit::ItemView::Property::LAYOUT_ORIENTATION)); + constraint.AddSource(ParentSource(Dali::Actor::Property::SIZE)); + constraint.SetTag(OVERSHOOT_SIZE_CONSTRAINT_TAG); constraint.Apply(); } @@ -333,7 +320,7 @@ Dali::Toolkit::ItemView ItemView::New(ItemFactory& factory) } ItemView::ItemView(ItemFactory& factory) -: Scrollable( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT ) ), +: Scrollable(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT)), mItemFactory(factory), mItemsParentOrigin(ParentOrigin::CENTER), mItemsAnchorPoint(AnchorPoint::CENTER), @@ -351,7 +338,7 @@ ItemView::ItemView(ItemFactory& factory) mAnimatingOvershootOn(false), mAnimateOvershootOff(false), mAnchoringEnabled(false), - mRefreshOrderHint(true/*Refresh item 0 first*/), + mRefreshOrderHint(true /*Refresh item 0 first*/), mIsFlicking(false), mAddingItems(false), mRefreshEnabled(true), @@ -366,22 +353,21 @@ void ItemView::OnInitialize() Actor self = Self(); - Vector2 stageSize = Stage::GetCurrent().GetSize(); + Vector2 stageSize = Stage::GetCurrent().GetSize(); mWheelScrollDistanceStep = stageSize.y * DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION; - self.TouchedSignal().Connect( this, &ItemView::OnTouch ); + self.TouchedSignal().Connect(this, &ItemView::OnTouch); EnableGestureDetection(GestureType::Value(GestureType::PAN)); - mWheelEventFinishedTimer = Timer::New( WHEEL_EVENT_FINISHED_TIME_OUT ); - mWheelEventFinishedTimer.TickSignal().Connect( this, &ItemView::OnWheelEventFinished ); + mWheelEventFinishedTimer = Timer::New(WHEEL_EVENT_FINISHED_TIME_OUT); + mWheelEventFinishedTimer.TickSignal().Connect(this, &ItemView::OnWheelEventFinished); SetRefreshInterval(DEFAULT_REFRESH_INTERVAL_LAYOUT_POSITIONS); // Connect wheel event - self.WheelEventSignal().Connect( this, &ItemView::OnWheelEvent ); + self.WheelEventSignal().Connect(this, &ItemView::OnWheelEvent); - DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) - { + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { return std::unique_ptr(new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE)); }); } @@ -404,7 +390,7 @@ void ItemView::RemoveLayout(unsigned int layoutIndex) { DALI_ASSERT_ALWAYS(layoutIndex < mLayouts.size()); - if (mActiveLayout == mLayouts[layoutIndex].Get()) + if(mActiveLayout == mLayouts[layoutIndex].Get()) { mActiveLayout = NULL; } @@ -424,7 +410,7 @@ ItemLayoutPtr ItemView::GetActiveLayout() const float ItemView::GetCurrentLayoutPosition(unsigned int itemId) const { - return Self().GetCurrentProperty< float >( Toolkit::ItemView::Property::LAYOUT_POSITION ) + static_cast( itemId ); + return Self().GetCurrentProperty(Toolkit::ItemView::Property::LAYOUT_POSITION) + static_cast(itemId); } void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSize, float durationSeconds) @@ -436,7 +422,7 @@ void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSiz Actor self = Self(); // The ItemView size should match the active layout size - self.SetProperty( Actor::Property::SIZE, targetSize); + self.SetProperty(Actor::Property::SIZE, targetSize); mActiveLayoutTargetSize = targetSize; // Switch to the new layout @@ -444,49 +430,49 @@ void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSiz // Move the items to the new layout positions... - for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) + for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { unsigned int itemId = iter->first; - Actor actor = iter->second; + Actor actor = iter->second; // Remove constraints from previous layout actor.RemoveConstraints(); - mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self() ); + mActiveLayout->ApplyConstraints(actor, itemId, targetSize, Self()); Vector3 size; - mActiveLayout->GetItemSize( itemId, targetSize, size ); - actor.SetProperty( Actor::Property::SIZE, size.GetVectorXY() ); + mActiveLayout->GetItemSize(itemId, targetSize, size); + actor.SetProperty(Actor::Property::SIZE, size.GetVectorXY()); } // Refresh the new layout - ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false/* don't reserve extra*/); - AddActorsWithinRange( range, targetSize ); + ItemRange range = GetItemRange(*mActiveLayout, targetSize, GetCurrentLayoutPosition(0), false /* don't reserve extra*/); + AddActorsWithinRange(range, targetSize); // Scroll to an appropriate layout position - bool scrollAnimationNeeded(false); + bool scrollAnimationNeeded(false); float firstItemScrollPosition(0.0f); float current = GetCurrentLayoutPosition(0); float minimum = ClampFirstItemPosition(current, targetSize, *mActiveLayout); - if (current < minimum) + if(current < minimum) { - scrollAnimationNeeded = true; + scrollAnimationNeeded = true; firstItemScrollPosition = minimum; } - else if (mAnchoringEnabled) + else if(mAnchoringEnabled) { - scrollAnimationNeeded = true; + scrollAnimationNeeded = true; firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(current); } - if (scrollAnimationNeeded) + if(scrollAnimationNeeded) { RemoveAnimation(mScrollAnimation); mScrollAnimation = Animation::New(durationSeconds); - mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT ); + mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT); mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnLayoutActivationScrollFinished); mScrollAnimation.Play(); } @@ -509,9 +495,9 @@ void ItemView::ActivateLayout(unsigned int layoutIndex, const Vector3& targetSiz void ItemView::DeactivateCurrentLayout() { - if (mActiveLayout) + if(mActiveLayout) { - for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) + for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { Actor actor = iter->second; actor.RemoveConstraints(); @@ -523,7 +509,7 @@ void ItemView::DeactivateCurrentLayout() void ItemView::OnRefreshNotification(PropertyNotification& source) { - if( mRefreshNotificationEnabled ) + if(mRefreshNotificationEnabled) { // Cancel scroll animation to prevent any fighting of setting the scroll position property by scroll bar during fast scroll. if(!mRefreshEnabled && mScrollAnimation) @@ -538,9 +524,9 @@ void ItemView::OnRefreshNotification(PropertyNotification& source) void ItemView::Refresh() { - for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter ) + for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { - ReleaseActor( iter->first, iter->second ); + ReleaseActor(iter->first, iter->second); } mItemPool.clear(); @@ -549,13 +535,13 @@ void ItemView::Refresh() void ItemView::DoRefresh(float currentLayoutPosition, bool cacheExtra) { - if (mActiveLayout) + if(mActiveLayout) { - ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra/*reserve extra*/); - RemoveActorsOutsideRange( range ); - AddActorsWithinRange( range, Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) ); + ItemRange range = GetItemRange(*mActiveLayout, mActiveLayoutTargetSize, currentLayoutPosition, cacheExtra /*reserve extra*/); + RemoveActorsOutsideRange(range); + AddActorsWithinRange(range, Self().GetCurrentProperty(Actor::Property::SIZE)); - mScrollUpdatedSignal.Emit( Vector2(0.0f, currentLayoutPosition) ); + mScrollUpdatedSignal.Emit(Vector2(0.0f, currentLayoutPosition)); } } @@ -611,7 +597,7 @@ float ItemView::GetAnchoringDuration() const void ItemView::SetRefreshInterval(float intervalLayoutPositions) { - if( !Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions) ) + if(!Equals(mRefreshIntervalLayoutPositions, intervalLayoutPositions)) { mRefreshIntervalLayoutPositions = intervalLayoutPositions; @@ -620,8 +606,8 @@ void ItemView::SetRefreshInterval(float intervalLayoutPositions) { self.RemovePropertyNotification(mRefreshNotification); } - mRefreshNotification = self.AddPropertyNotification( Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f) ); - mRefreshNotification.NotifySignal().Connect( this, &ItemView::OnRefreshNotification ); + mRefreshNotification = self.AddPropertyNotification(Toolkit::ItemView::Property::LAYOUT_POSITION, StepCondition(mRefreshIntervalLayoutPositions, 0.0f)); + mRefreshNotification.NotifySignal().Connect(this, &ItemView::OnRefreshNotification); } } @@ -639,9 +625,9 @@ Actor ItemView::GetItem(unsigned int itemId) const { Actor actor; - for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter ) + for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { - if( iter->first == itemId ) + if(iter->first == itemId) { actor = iter->second; break; @@ -651,13 +637,13 @@ Actor ItemView::GetItem(unsigned int itemId) const return actor; } -unsigned int ItemView::GetItemId( Actor actor ) const +unsigned int ItemView::GetItemId(Actor actor) const { - unsigned int itemId( 0 ); + unsigned int itemId(0); - for ( ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter ) + for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { - if( iter->second == actor ) + if(iter->second == actor) { itemId = iter->first; break; @@ -667,21 +653,21 @@ unsigned int ItemView::GetItemId( Actor actor ) const return itemId; } -void ItemView::InsertItem( Item newItem, float durationSeconds ) +void ItemView::InsertItem(Item newItem, float durationSeconds) { - mAddingItems = true; - Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + mAddingItems = true; + Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); - Actor displacedActor; + Actor displacedActor; ItemIter afterDisplacedIter = mItemPool.end(); - ItemIter foundIter = FindItemById( mItemPool, newItem.first ); - if( mItemPool.end() != foundIter ) + ItemIter foundIter = FindItemById(mItemPool, newItem.first); + if(mItemPool.end() != foundIter) { - SetupActor( newItem, layoutSize ); - Self().Add( newItem.second ); + SetupActor(newItem, layoutSize); + Self().Add(newItem.second); - displacedActor = foundIter->second; + displacedActor = foundIter->second; foundIter->second = newItem.second; afterDisplacedIter = ++foundIter; @@ -690,109 +676,109 @@ void ItemView::InsertItem( Item newItem, float durationSeconds ) { // Inserting before the existing item range? ItemIter iter = mItemPool.begin(); - if( iter != mItemPool.end() && - iter->first > newItem.first ) + if(iter != mItemPool.end() && + iter->first > newItem.first) { displacedActor = iter->second; - iter = mItemPool.erase( iter ); // iter is still valid after the erase + iter = mItemPool.erase(iter); // iter is still valid after the erase afterDisplacedIter = iter; } } - if( displacedActor ) + if(displacedActor) { // Move the existing actors to make room - for( ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter ) + for(ItemIter iter = afterDisplacedIter; mItemPool.end() != iter; ++iter) { - Actor temp = iter->second; - iter->second = displacedActor; + Actor temp = iter->second; + iter->second = displacedActor; displacedActor = temp; iter->second.RemoveConstraints(); - mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() ); + mActiveLayout->ApplyConstraints(iter->second, iter->first, layoutSize, Self()); } // Create last item ItemContainer::reverse_iterator lastIter = mItemPool.rbegin(); - if ( lastIter != mItemPool.rend() ) + if(lastIter != mItemPool.rend()) { ItemId lastId = lastIter->first; - Item lastItem( lastId + 1, displacedActor ); - InsertToItemContainer( mItemPool, lastItem ); + Item lastItem(lastId + 1, displacedActor); + InsertToItemContainer(mItemPool, lastItem); lastItem.second.RemoveConstraints(); - mActiveLayout->ApplyConstraints( lastItem.second, lastItem.first, layoutSize, Self() ); + mActiveLayout->ApplyConstraints(lastItem.second, lastItem.first, layoutSize, Self()); } } - CalculateDomainSize( layoutSize ); + CalculateDomainSize(layoutSize); mAddingItems = false; } -void ItemView::InsertItems( const ItemContainer& newItems, float durationSeconds ) +void ItemView::InsertItems(const ItemContainer& newItems, float durationSeconds) { - mAddingItems = true; - Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + mAddingItems = true; + Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); // Insert from lowest id to highest ItemContainer sortedItems(newItems); - std::sort( sortedItems.begin(), sortedItems.end() ); + std::sort(sortedItems.begin(), sortedItems.end()); - for( ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter ) + for(ItemIter iter = sortedItems.begin(); sortedItems.end() != iter; ++iter) { - Self().Add( iter->second ); + Self().Add(iter->second); - ItemIter foundIter = FindItemById( mItemPool, iter->first ); - if( mItemPool.end() != foundIter ) + ItemIter foundIter = FindItemById(mItemPool, iter->first); + if(mItemPool.end() != foundIter) { - Actor moveMe = foundIter->second; + Actor moveMe = foundIter->second; foundIter->second = iter->second; // Move the existing actors to make room - for( ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter ) + for(ItemIter iter = ++foundIter; mItemPool.end() != iter; ++iter) { - Actor temp = iter->second; + Actor temp = iter->second; iter->second = moveMe; - moveMe = temp; + moveMe = temp; } // Create last item ItemId lastId = mItemPool.rbegin()->first; - Item lastItem( lastId + 1, moveMe ); - InsertToItemContainer( mItemPool, lastItem ); + Item lastItem(lastId + 1, moveMe); + InsertToItemContainer(mItemPool, lastItem); } else { - InsertToItemContainer( mItemPool, *iter ); + InsertToItemContainer(mItemPool, *iter); } } // Relayout everything - for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) + for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { // If newly inserted - if( std::binary_search( sortedItems.begin(), sortedItems.end(), *iter ) ) + if(std::binary_search(sortedItems.begin(), sortedItems.end(), *iter)) { - SetupActor( *iter, layoutSize ); + SetupActor(*iter, layoutSize); } else { iter->second.RemoveConstraints(); - mActiveLayout->ApplyConstraints( iter->second, iter->first, layoutSize, Self() ); + mActiveLayout->ApplyConstraints(iter->second, iter->first, layoutSize, Self()); } } - CalculateDomainSize( layoutSize ); + CalculateDomainSize(layoutSize); mAddingItems = false; } -void ItemView::RemoveItem( unsigned int itemId, float durationSeconds ) +void ItemView::RemoveItem(unsigned int itemId, float durationSeconds) { - bool actorsReordered = RemoveActor( itemId ); - if( actorsReordered ) + bool actorsReordered = RemoveActor(itemId); + if(actorsReordered) { ReapplyAllConstraints(); @@ -800,23 +786,23 @@ void ItemView::RemoveItem( unsigned int itemId, float durationSeconds ) } } -void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSeconds ) +void ItemView::RemoveItems(const ItemIdContainer& itemIds, float durationSeconds) { - bool actorsReordered( false ); + bool actorsReordered(false); // Remove from highest id to lowest ItemIdContainer sortedItems(itemIds); - std::sort( sortedItems.begin(), sortedItems.end() ); + std::sort(sortedItems.begin(), sortedItems.end()); - for( ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter ) + for(ItemIdContainer::reverse_iterator iter = sortedItems.rbegin(); sortedItems.rend() != iter; ++iter) { - if( RemoveActor( *iter ) ) + if(RemoveActor(*iter)) { actorsReordered = true; } } - if( actorsReordered ) + if(actorsReordered) { ReapplyAllConstraints(); @@ -826,10 +812,10 @@ void ItemView::RemoveItems( const ItemIdContainer& itemIds, float durationSecond bool ItemView::RemoveActor(unsigned int itemId) { - bool reordered( false ); + bool reordered(false); - ItemIter removeIter = FindItemById( mItemPool, itemId ); - if( removeIter != mItemPool.end() ) + ItemIter removeIter = FindItemById(mItemPool, itemId); + if(removeIter != mItemPool.end()) { ReleaseActor(itemId, removeIter->second); } @@ -837,17 +823,17 @@ bool ItemView::RemoveActor(unsigned int itemId) { // Removing before the existing item range? ItemIter iter = mItemPool.begin(); - if( iter != mItemPool.end() && - iter->first > itemId ) + if(iter != mItemPool.end() && + iter->first > itemId) { // In order to decrement the first visible item ID - InsertToItemContainer( mItemPool, Item(iter->first - 1, Actor()) ); + InsertToItemContainer(mItemPool, Item(iter->first - 1, Actor())); removeIter = mItemPool.begin(); } } - if( removeIter != mItemPool.end() ) + if(removeIter != mItemPool.end()) { reordered = true; @@ -857,15 +843,15 @@ bool ItemView::RemoveActor(unsigned int itemId) // ID 2 - ActorB ID 2 - ActorC (previously ID 3) // ID 3 - ActorC ID 3 - ActorB (previously ID 4) // ID 4 - ActorD - for (ItemIter iter = removeIter; iter != mItemPool.end(); ++iter) + for(ItemIter iter = removeIter; iter != mItemPool.end(); ++iter) { - if( iter->first < mItemPool.rbegin()->first ) + if(iter->first < mItemPool.rbegin()->first) { - iter->second = ( iter + 1 )->second; + iter->second = (iter + 1)->second; } else { - mItemPool.erase( iter ); + mItemPool.erase(iter); break; } } @@ -874,50 +860,50 @@ bool ItemView::RemoveActor(unsigned int itemId) return reordered; } -void ItemView::ReplaceItem( Item replacementItem, float durationSeconds ) +void ItemView::ReplaceItem(Item replacementItem, float durationSeconds) { - mAddingItems = true; - Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + mAddingItems = true; + Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); - SetupActor( replacementItem, layoutSize ); - Self().Add( replacementItem.second ); + SetupActor(replacementItem, layoutSize); + Self().Add(replacementItem.second); - const ItemIter iter = FindItemById( mItemPool, replacementItem.first ); - if( mItemPool.end() != iter ) + const ItemIter iter = FindItemById(mItemPool, replacementItem.first); + if(mItemPool.end() != iter) { ReleaseActor(iter->first, iter->second); iter->second = replacementItem.second; } else { - InsertToItemContainer( mItemPool, replacementItem ); + InsertToItemContainer(mItemPool, replacementItem); } - CalculateDomainSize( layoutSize ); + CalculateDomainSize(layoutSize); mAddingItems = false; } -void ItemView::ReplaceItems( const ItemContainer& replacementItems, float durationSeconds ) +void ItemView::ReplaceItems(const ItemContainer& replacementItems, float durationSeconds) { - for( ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter ) + for(ConstItemIter iter = replacementItems.begin(); replacementItems.end() != iter; ++iter) { - ReplaceItem( *iter, durationSeconds ); + ReplaceItem(*iter, durationSeconds); } } -void ItemView::RemoveActorsOutsideRange( ItemRange range ) +void ItemView::RemoveActorsOutsideRange(ItemRange range) { // Remove unwanted actors from the ItemView & ItemPool - for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ) + for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end();) { unsigned int current = iter->first; - if( ! range.Within( current ) ) + if(!range.Within(current)) { ReleaseActor(iter->first, iter->second); - iter = mItemPool.erase( iter ); // iter is still valid after the erase + iter = mItemPool.erase(iter); // iter is still valid after the erase } else { @@ -926,71 +912,71 @@ void ItemView::RemoveActorsOutsideRange( ItemRange range ) } } -void ItemView::AddActorsWithinRange( ItemRange range, const Vector3& layoutSize ) +void ItemView::AddActorsWithinRange(ItemRange range, const Vector3& layoutSize) { range.end = std::min(mItemFactory.GetNumberOfItems(), range.end); // The order of addition depends on the scroll direction. - if (mRefreshOrderHint) + if(mRefreshOrderHint) { - for (unsigned int itemId = range.begin; itemId < range.end; ++itemId) + for(unsigned int itemId = range.begin; itemId < range.end; ++itemId) { - AddNewActor( itemId, layoutSize ); + AddNewActor(itemId, layoutSize); } } else { - for (unsigned int itemId = range.end; itemId > range.begin; --itemId) + for(unsigned int itemId = range.end; itemId > range.begin; --itemId) { - AddNewActor( itemId-1, layoutSize ); + AddNewActor(itemId - 1, layoutSize); } } // Total number of items may change dynamically. // Always recalculate the domain size to reflect that. - CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )); + CalculateDomainSize(Self().GetCurrentProperty(Actor::Property::SIZE)); } -void ItemView::AddNewActor( unsigned int itemId, const Vector3& layoutSize ) +void ItemView::AddNewActor(unsigned int itemId, const Vector3& layoutSize) { mAddingItems = true; - if( mItemPool.end() == FindItemById( mItemPool, itemId ) ) + if(mItemPool.end() == FindItemById(mItemPool, itemId)) { - Actor actor = mItemFactory.NewItem( itemId ); + Actor actor = mItemFactory.NewItem(itemId); - if( actor ) + if(actor) { - Item newItem( itemId, actor ); + Item newItem(itemId, actor); - InsertToItemContainer( mItemPool, newItem ); + InsertToItemContainer(mItemPool, newItem); - SetupActor( newItem, layoutSize ); - Self().Add( actor ); + SetupActor(newItem, layoutSize); + Self().Add(actor); } } mAddingItems = false; } -void ItemView::SetupActor( Item item, const Vector3& layoutSize ) +void ItemView::SetupActor(Item item, const Vector3& layoutSize) { - item.second.SetProperty( Actor::Property::PARENT_ORIGIN, mItemsParentOrigin ); - item.second.SetProperty( Actor::Property::ANCHOR_POINT, mItemsAnchorPoint ); + item.second.SetProperty(Actor::Property::PARENT_ORIGIN, mItemsParentOrigin); + item.second.SetProperty(Actor::Property::ANCHOR_POINT, mItemsAnchorPoint); - if( mActiveLayout ) + if(mActiveLayout) { Vector3 size; - mActiveLayout->GetItemSize( item.first, mActiveLayoutTargetSize, size ); - item.second.SetProperty( Actor::Property::SIZE, size.GetVectorXY() ); + mActiveLayout->GetItemSize(item.first, mActiveLayoutTargetSize, size); + item.second.SetProperty(Actor::Property::SIZE, size.GetVectorXY()); - mActiveLayout->ApplyConstraints( item.second, item.first, layoutSize, Self() ); + mActiveLayout->ApplyConstraints(item.second, item.first, layoutSize, Self()); } } -void ItemView::ReleaseActor( ItemId item, Actor actor ) +void ItemView::ReleaseActor(ItemId item, Actor actor) { - Self().Remove( actor ); + Self().Remove(actor); mItemFactory.ItemReleased(item, actor); } @@ -1000,13 +986,13 @@ ItemRange ItemView::GetItemRange(ItemLayout& layout, const Vector3& layoutSize, ItemRange available(0u, itemCount); - ItemRange range = layout.GetItemsWithinArea( layoutPosition, layoutSize ); + ItemRange range = layout.GetItemsWithinArea(layoutPosition, layoutSize); - if (reserveExtra) + if(reserveExtra) { // Add the reserve items for scrolling unsigned int extra = layout.GetReserveItemCount(layoutSize); - range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u; + range.begin = (range.begin >= extra) ? (range.begin - extra) : 0u; range.end += extra; } @@ -1029,26 +1015,26 @@ void ItemView::OnChildAdd(Actor& child) } } - Scrollable::OnChildAdd( child ); + Scrollable::OnChildAdd(child); } bool ItemView::OnWheelEvent(Actor actor, const WheelEvent& event) { // Respond the wheel event to scroll - if (mActiveLayout) + if(mActiveLayout) { - Actor self = Self(); - const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor()); - float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout); + Actor self = Self(); + const Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); + float layoutPositionDelta = GetCurrentLayoutPosition(0) - (event.GetDelta() * mWheelScrollDistanceStep * mActiveLayout->GetScrollSpeedFactor()); + float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout); - self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition ); + self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition); mScrollStartedSignal.Emit(GetCurrentScrollPosition()); mRefreshEnabled = true; } - if (mWheelEventFinishedTimer.IsRunning()) + if(mWheelEventFinishedTimer.IsRunning()) { mWheelEventFinishedTimer.Stop(); } @@ -1060,13 +1046,13 @@ bool ItemView::OnWheelEvent(Actor actor, const WheelEvent& event) bool ItemView::OnWheelEventFinished() { - if (mActiveLayout) + if(mActiveLayout) { RemoveAnimation(mScrollAnimation); // No more wheel events coming. Do the anchoring if enabled. mScrollAnimation = DoAnchoring(); - if (mScrollAnimation) + if(mScrollAnimation) { mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished); mScrollAnimation.Play(); @@ -1085,12 +1071,12 @@ bool ItemView::OnWheelEventFinished() void ItemView::ReapplyAllConstraints() { - Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); - for (ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) + for(ConstItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { - unsigned int id = iter->first; - Actor actor = iter->second; + unsigned int id = iter->first; + Actor actor = iter->second; actor.RemoveConstraints(); mActiveLayout->ApplyConstraints(actor, id, layoutSize, Self()); @@ -1099,24 +1085,24 @@ void ItemView::ReapplyAllConstraints() void ItemView::OnItemsRemoved() { - CalculateDomainSize(Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )); + CalculateDomainSize(Self().GetCurrentProperty(Actor::Property::SIZE)); // Adjust scroll-position after an item is removed - if( mActiveLayout ) + if(mActiveLayout) { - float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ), *mActiveLayout); - Self().SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition ); + float firstItemScrollPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty(Actor::Property::SIZE), *mActiveLayout); + Self().SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition); } } -float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot ) +float ItemView::ClampFirstItemPosition(float targetPosition, const Vector3& targetSize, ItemLayout& layout, bool updateOvershoot) { - Actor self = Self(); + Actor self = Self(); float minLayoutPosition = layout.GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), targetSize); - float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition)); + float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, targetPosition)); self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition)); - if( updateOvershoot ) + if(updateOvershoot) { mScrollOvershoot = targetPosition - clamppedPosition; } @@ -1124,21 +1110,21 @@ float ItemView::ClampFirstItemPosition( float targetPosition, const Vector3& tar return clamppedPosition; } -bool ItemView::OnTouch( Actor actor, const TouchEvent& touch ) +bool ItemView::OnTouch(Actor actor, const TouchEvent& touch) { // Ignore events with multiple-touch points - if (touch.GetPointCount() != 1) + if(touch.GetPointCount() != 1) { return false; } - if ( touch.GetState( 0 ) == PointState::DOWN ) + if(touch.GetState(0) == PointState::DOWN) { // Cancel ongoing scrolling etc. mGestureState = GestureState::CLEAR; mScrollDistance = 0.0f; - mScrollSpeed = 0.0f; + mScrollSpeed = 0.0f; Self().SetProperty(Toolkit::ItemView::Property::SCROLL_SPEED, mScrollSpeed); mScrollOvershoot = 0.0f; @@ -1155,15 +1141,15 @@ bool ItemView::OnTouch( Actor actor, const TouchEvent& touch ) return false; // Do not consume as we're potentially scrolling (detecting pan gestures) } -void ItemView::OnPan( const PanGesture& gesture ) +void ItemView::OnPan(const PanGesture& gesture) { - Actor self = Self(); - const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Actor self = Self(); + const Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); RemoveAnimation(mScrollAnimation); // Short-circuit if there is no active layout - if (!mActiveLayout) + if(!mActiveLayout) { mGestureState = GestureState::CLEAR; return; @@ -1171,55 +1157,54 @@ void ItemView::OnPan( const PanGesture& gesture ) mGestureState = gesture.GetState(); - switch (mGestureState) + switch(mGestureState) { case GestureState::FINISHED: { // Swipe Detection - if (fabsf(mScrollDistance) > mMinimumSwipeDistance && - mScrollSpeed > mMinimumSwipeSpeed) + if(fabsf(mScrollDistance) > mMinimumSwipeDistance && + mScrollSpeed > mMinimumSwipeSpeed) { float direction = (mScrollDistance < 0.0f) ? -1.0f : 1.0f; mRefreshOrderHint = true; - float currentLayoutPosition = GetCurrentLayoutPosition(0); + float currentLayoutPosition = GetCurrentLayoutPosition(0); float firstItemScrollPosition = ClampFirstItemPosition(currentLayoutPosition + mScrollSpeed * direction, layoutSize, *mActiveLayout); - if (mAnchoringEnabled) + if(mAnchoringEnabled) { firstItemScrollPosition = mActiveLayout->GetClosestAnchorPosition(firstItemScrollPosition); } RemoveAnimation(mScrollAnimation); - float flickAnimationDuration = Clamp( mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0))) - , DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION); + float flickAnimationDuration = Clamp(mActiveLayout->GetItemFlickAnimationDuration() * std::max(1.0f, fabsf(firstItemScrollPosition - GetCurrentLayoutPosition(0))), DEFAULT_MINIMUM_SWIPE_DURATION, DEFAULT_MAXIMUM_SWIPE_DURATION); mScrollAnimation = Animation::New(flickAnimationDuration); - mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION ), firstItemScrollPosition, AlphaFunction::EASE_OUT ); - mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT ); + mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, AlphaFunction::EASE_OUT); + mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT); mIsFlicking = true; // Check whether it has already scrolled to the end - if( fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0 ) + if(fabs(currentLayoutPosition - firstItemScrollPosition) < Math::MACHINE_EPSILON_0) { - AnimateScrollOvershoot( 0.0f ); - RemoveAnimation( mScrollAnimation ); + AnimateScrollOvershoot(0.0f); + RemoveAnimation(mScrollAnimation); } } // Anchoring may be triggered when there was no swipe - if (!mScrollAnimation) + if(!mScrollAnimation) { mScrollAnimation = DoAnchoring(); } // Reset the overshoot if no scroll animation. - if (!mScrollAnimation) + if(!mScrollAnimation) { mScrollCompletedSignal.Emit(GetCurrentScrollPosition()); @@ -1238,8 +1223,8 @@ void ItemView::OnPan( const PanGesture& gesture ) case GestureState::CONTINUING: { const Vector2& displacement = gesture.GetDisplacement(); - mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout); - mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed()); + mScrollDistance = CalculateScrollDistance(displacement, *mActiveLayout); + mScrollSpeed = Clamp((gesture.GetSpeed() * gesture.GetSpeed() * mActiveLayout->GetFlickSpeedFactor() * MILLISECONDS_PER_SECONDS), 0.0f, mActiveLayout->GetMaximumSwipeSpeed()); // Refresh order depends on the direction of the scroll; negative is towards the last item. mRefreshOrderHint = mScrollDistance < 0.0f; @@ -1248,14 +1233,14 @@ void ItemView::OnPan( const PanGesture& gesture ) float firstItemScrollPosition = ClampFirstItemPosition(layoutPositionDelta, layoutSize, *mActiveLayout); - float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT ); + float currentOvershoot = self.GetCurrentProperty(Toolkit::ItemView::Property::OVERSHOOT); - self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition ); + self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition); - if( ( firstItemScrollPosition >= 0.0f && - currentOvershoot < 1.0f ) || - ( firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) && - currentOvershoot > -1.0f ) ) + if((firstItemScrollPosition >= 0.0f && + currentOvershoot < 1.0f) || + (firstItemScrollPosition <= mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize) && + currentOvershoot > -1.0f)) { mTotalPanDisplacement += displacement; } @@ -1265,24 +1250,24 @@ void ItemView::OnPan( const PanGesture& gesture ) // If the view is moved in a direction against the overshoot indicator, then the indicator should be animated off. // First make sure we are not in an animation, otherwise a previously started // off-animation will be overwritten as the user continues scrolling. - if( !mInAnimation ) + if(!mInAnimation) { // Check if the movement is against the current overshoot amount (if we are currently displaying the indicator). - if( ( ( mScrollOvershoot > Math::MACHINE_EPSILON_0 ) && ( mScrollDistance < -Math::MACHINE_EPSILON_0 ) ) || - ( ( mScrollOvershoot < Math::MACHINE_EPSILON_0 ) && ( mScrollDistance > Math::MACHINE_EPSILON_0 ) ) ) + if(((mScrollOvershoot > Math::MACHINE_EPSILON_0) && (mScrollDistance < -Math::MACHINE_EPSILON_0)) || + ((mScrollOvershoot < Math::MACHINE_EPSILON_0) && (mScrollDistance > Math::MACHINE_EPSILON_0))) { // The user has moved against the indicator direction. // First, we reset the total displacement. This means the overshoot amount will become zero the next frame, // and if the user starts dragging in the overshoot direction again, the indicator will appear once more. mTotalPanDisplacement = Vector2::ZERO; // Animate the overshoot indicator off. - AnimateScrollOvershoot( 0.0f, false ); + AnimateScrollOvershoot(0.0f, false); } else { // Only set the property directly if we are not animating the overshoot away, // as otherwise this will overwrite the animation generated value. - self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot ); + self.SetProperty(Toolkit::ItemView::Property::OVERSHOOT, mScrollOvershoot); } } } @@ -1298,7 +1283,7 @@ void ItemView::OnPan( const PanGesture& gesture ) break; } - if (mScrollAnimation) + if(mScrollAnimation) { mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished); mScrollAnimation.Play(); @@ -1323,8 +1308,8 @@ Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::Key } else if(actor && actor.GetParent() == this->Self()) { - int itemID = GetItemId(actor); - nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled); + int itemID = GetItemId(actor); + nextItemID = mActiveLayout->GetNextFocusItemID(itemID, mItemFactory.GetNumberOfItems(), direction, loopEnabled); nextFocusActor = GetItem(nextItemID); if(nextFocusActor == actor) { @@ -1333,14 +1318,14 @@ Actor ItemView::GetNextKeyboardFocusableActor(Actor actor, Toolkit::Control::Key return nextFocusActor; } } - float layoutPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) ); - Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + float layoutPosition = mActiveLayout->GetClosestAnchorPosition(GetCurrentLayoutPosition(0)); + Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); if(!nextFocusActor) { // likely the current item is not buffered, so not in our item pool, probably best to get first viewable item ItemRange viewableItems = mActiveLayout->GetItemsWithinArea(layoutPosition, layoutSize); - nextItemID = viewableItems.begin; - nextFocusActor = GetItem(nextItemID); + nextItemID = viewableItems.begin; + nextFocusActor = GetItem(nextItemID); } } return nextFocusActor; @@ -1351,9 +1336,9 @@ void ItemView::OnKeyboardFocusChangeCommitted(Actor commitedFocusableActor) // only in this function if our chosen focus actor was actually used if(commitedFocusableActor) { - int nextItemID = GetItemId(commitedFocusableActor); - float layoutPosition = GetCurrentLayoutPosition(0); - Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + int nextItemID = GetItemId(commitedFocusableActor); + float layoutPosition = GetCurrentLayoutPosition(0); + Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); float scrollTo = mActiveLayout->GetClosestOnScreenLayoutPosition(nextItemID, layoutPosition, layoutSize); ScrollTo(Vector2(0.0f, scrollTo), DEFAULT_KEYBOARD_FOCUS_SCROLL_DURATION); @@ -1370,15 +1355,15 @@ void ItemView::AccessibleImpl::EnsureChildVisible(Actor child) Animation ItemView::DoAnchoring() { Animation anchoringAnimation; - Actor self = Self(); + Actor self = Self(); - if (mActiveLayout && mAnchoringEnabled) + if(mActiveLayout && mAnchoringEnabled) { - float anchorPosition = mActiveLayout->GetClosestAnchorPosition( GetCurrentLayoutPosition(0) ); + float anchorPosition = mActiveLayout->GetClosestAnchorPosition(GetCurrentLayoutPosition(0)); anchoringAnimation = Animation::New(mAnchoringDuration); - anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT ); - anchoringAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT ); + anchoringAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), anchorPosition, AlphaFunction::EASE_OUT); + anchoringAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::SCROLL_SPEED), 0.0f, AlphaFunction::EASE_OUT); if(!mIsFlicking) { AnimateScrollOvershoot(0.0f); @@ -1398,12 +1383,12 @@ void ItemView::OnScrollFinished(Animation& source) if(mIsFlicking && fabsf(mScrollOvershoot) > Math::MACHINE_EPSILON_1) { - AnimateScrollOvershoot( mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true); + AnimateScrollOvershoot(mScrollOvershoot > 0.0f ? 1.0f : -1.0f, true); } else { // Reset the overshoot - AnimateScrollOvershoot( 0.0f ); + AnimateScrollOvershoot(0.0f); } mIsFlicking = false; @@ -1434,21 +1419,21 @@ void ItemView::OnOvershootOnFinished(Animation& animation) void ItemView::ScrollToItem(unsigned int itemId, float durationSeconds) { - Actor self = Self(); - const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout); + Actor self = Self(); + const Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); + float firstItemScrollPosition = ClampFirstItemPosition(mActiveLayout->GetItemScrollToPosition(itemId), layoutSize, *mActiveLayout); if(durationSeconds > 0.0f) { RemoveAnimation(mScrollAnimation); mScrollAnimation = Animation::New(durationSeconds); - mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction ); + mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction); mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished); mScrollAnimation.Play(); } else { - self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition ); + self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition); AnimateScrollOvershoot(0.0f); } @@ -1475,10 +1460,10 @@ void ItemView::CalculateDomainSize(const Vector3& layoutSize) if(mActiveLayout) { - firstItemPosition = mActiveLayout->GetItemPosition( 0,0,layoutSize ); + firstItemPosition = mActiveLayout->GetItemPosition(0, 0, layoutSize); float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), layoutSize); - lastItemPosition = mActiveLayout->GetItemPosition( fabs(minLayoutPosition),fabs(minLayoutPosition),layoutSize ); + lastItemPosition = mActiveLayout->GetItemPosition(fabs(minLayoutPosition), fabs(minLayoutPosition), layoutSize); float domainSize; @@ -1506,27 +1491,27 @@ bool ItemView::IsLayoutScrollable(const Vector3& layoutSize) { Actor self = Self(); - float currentLayoutPosition = ClampFirstItemPosition( GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false ); - float forwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false ); - float backwardClampedPosition = ClampFirstItemPosition( currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false ); + float currentLayoutPosition = ClampFirstItemPosition(GetCurrentLayoutPosition(0), layoutSize, *mActiveLayout, false); + float forwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition + 1.0, layoutSize, *mActiveLayout, false); + float backwardClampedPosition = ClampFirstItemPosition(currentLayoutPosition - 1.0, layoutSize, *mActiveLayout, false); return (fabs(forwardClampedPosition - backwardClampedPosition) > Math::MACHINE_EPSILON_0); } float ItemView::GetScrollPosition(float layoutPosition, const Vector3& layoutSize) const { - Vector3 firstItemPosition( mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize ) ); - return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x: firstItemPosition.y; + Vector3 firstItemPosition(mActiveLayout->GetItemPosition(0, layoutPosition, layoutSize)); + return IsHorizontal(mActiveLayout->GetOrientation()) ? firstItemPosition.x : firstItemPosition.y; } Vector2 ItemView::GetCurrentScrollPosition() const { - return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ))); + return Vector2(0.0f, GetScrollPosition(GetCurrentLayoutPosition(0), Self().GetCurrentProperty(Actor::Property::SIZE))); } void ItemView::AddOverlay(Actor actor) { - actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D ); + actor.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D); Self().Add(actor); } @@ -1537,8 +1522,8 @@ void ItemView::RemoveOverlay(Actor actor) void ItemView::ScrollTo(const Vector2& position, float duration) { - Actor self = Self(); - const Vector3 layoutSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Actor self = Self(); + const Vector3 layoutSize = Self().GetCurrentProperty(Actor::Property::SIZE); float firstItemScrollPosition = ClampFirstItemPosition(position.y, layoutSize, *mActiveLayout); @@ -1546,13 +1531,13 @@ void ItemView::ScrollTo(const Vector2& position, float duration) { RemoveAnimation(mScrollAnimation); mScrollAnimation = Animation::New(duration); - mScrollAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction ); + mScrollAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::LAYOUT_POSITION), firstItemScrollPosition, mScrollToAlphaFunction); mScrollAnimation.FinishedSignal().Connect(this, &ItemView::OnScrollFinished); mScrollAnimation.Play(); } else { - self.SetProperty( Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition ); + self.SetProperty(Toolkit::ItemView::Property::LAYOUT_POSITION, firstItemScrollPosition); AnimateScrollOvershoot(0.0f); } @@ -1560,69 +1545,69 @@ void ItemView::ScrollTo(const Vector2& position, float duration) mRefreshEnabled = true; } -void ItemView::SetOvershootSize( const Vector2& size ) +void ItemView::SetOvershootSize(const Vector2& size) { mOvershootSize = size; - if( mOvershootOverlay ) + if(mOvershootOverlay) { // Remove old & add new size constraint - mOvershootOverlay.RemoveConstraints( OVERSHOOT_SIZE_CONSTRAINT_TAG ); - ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height ); + mOvershootOverlay.RemoveConstraints(OVERSHOOT_SIZE_CONSTRAINT_TAG); + ApplyOvershootSizeConstraint(mOvershootOverlay, mOvershootSize.height); } } -void ItemView::SetOvershootEffectColor( const Vector4& color ) +void ItemView::SetOvershootEffectColor(const Vector4& color) { mOvershootEffectColor = color; - if( mOvershootOverlay ) + if(mOvershootOverlay) { - mOvershootOverlay.SetProperty( Actor::Property::COLOR, color ); + mOvershootOverlay.SetProperty(Actor::Property::COLOR, color); } } -void ItemView::EnableScrollOvershoot( bool enable ) +void ItemView::EnableScrollOvershoot(bool enable) { Actor self = Self(); - if( enable ) + if(enable) { - if( !mOvershootOverlay ) + if(!mOvershootOverlay) { Property::Index effectOvershootPropertyIndex = Property::INVALID_INDEX; - mOvershootOverlay = CreateBouncingEffectActor( effectOvershootPropertyIndex ); - mOvershootOverlay.SetProperty( Actor::Property::COLOR,mOvershootEffectColor); - mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT ); - mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT); - mOvershootOverlay.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D ); + mOvershootOverlay = CreateBouncingEffectActor(effectOvershootPropertyIndex); + mOvershootOverlay.SetProperty(Actor::Property::COLOR, mOvershootEffectColor); + mOvershootOverlay.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + mOvershootOverlay.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mOvershootOverlay.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D); self.Add(mOvershootOverlay); - ApplyOvershootSizeConstraint( mOvershootOverlay, mOvershootSize.height ); + ApplyOvershootSizeConstraint(mOvershootOverlay, mOvershootSize.height); - Constraint constraint = Constraint::New( mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) ); + Constraint constraint = Constraint::New(mOvershootOverlay, Actor::Property::ORIENTATION, OvershootOverlayRotationConstraint); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::SCROLL_DIRECTION)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_ORIENTATION)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::OVERSHOOT)); constraint.Apply(); - constraint = Constraint::New( mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint ); - constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::SCROLL_DIRECTION ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_ORIENTATION ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) ); + constraint = Constraint::New(mOvershootOverlay, Actor::Property::POSITION, OvershootOverlayPositionConstraint); + constraint.AddSource(ParentSource(Actor::Property::SIZE)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::SCROLL_DIRECTION)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_ORIENTATION)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::OVERSHOOT)); constraint.Apply(); - constraint = Constraint::New( mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint ); - constraint.AddSource( ParentSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) ); + constraint = Constraint::New(mOvershootOverlay, Actor::Property::VISIBLE, OvershootOverlayVisibilityConstraint); + constraint.AddSource(ParentSource(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL)); constraint.Apply(); - constraint = Constraint::New( mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint() ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::OVERSHOOT ) ); + constraint = Constraint::New(mOvershootOverlay, effectOvershootPropertyIndex, EqualToConstraint()); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::OVERSHOOT)); constraint.Apply(); } } else { - if( mOvershootOverlay ) + if(mOvershootOverlay) { self.Remove(mOvershootOverlay); mOvershootOverlay.Reset(); @@ -1638,13 +1623,13 @@ float ItemView::CalculateScrollOvershoot() { // The overshoot must be calculated from the accumulated pan gesture displacement // since the pan gesture starts. - Actor self = Self(); - float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor(); - float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance; - float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE )); + Actor self = Self(); + float scrollDistance = CalculateScrollDistance(mTotalPanDisplacement, *mActiveLayout) * mActiveLayout->GetScrollSpeedFactor(); + float positionDelta = GetCurrentLayoutPosition(0) + scrollDistance; + float minLayoutPosition = mActiveLayout->GetMinimumLayoutPosition(mItemFactory.GetNumberOfItems(), Self().GetCurrentProperty(Actor::Property::SIZE)); self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, Vector2(0.0f, -minLayoutPosition)); float clamppedPosition = std::min(0.0f, std::max(minLayoutPosition, positionDelta)); - overshoot = positionDelta - clamppedPosition; + overshoot = positionDelta - clamppedPosition; } return overshoot > 0.0f ? std::min(overshoot, 1.0f) : std::max(overshoot, -1.0f); @@ -1657,7 +1642,7 @@ void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack) // make sure we animate back if needed mAnimateOvershootOff = animateBack || (!animatingOn && mAnimatingOvershootOn); - if( mAnimatingOvershootOn ) + if(mAnimatingOvershootOn) { // animating on, do not allow animate off return; @@ -1667,37 +1652,37 @@ void ItemView::AnimateScrollOvershoot(float overshootAmount, bool animateBack) if(mOvershootAnimationSpeed > Math::MACHINE_EPSILON_0) { - float currentOvershoot = self.GetCurrentProperty< float >( Toolkit::ItemView::Property::OVERSHOOT ); - float duration = 0.0f; + float currentOvershoot = self.GetCurrentProperty(Toolkit::ItemView::Property::OVERSHOOT); + float duration = 0.0f; - if (mOvershootOverlay) + if(mOvershootOverlay) { - duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed; + duration = mOvershootOverlay.GetCurrentProperty(Actor::Property::SIZE).height * (animatingOn ? (1.0f - fabsf(currentOvershoot)) : fabsf(currentOvershoot)) / mOvershootAnimationSpeed; } // Mark the animation as in progress to prevent manual property sets overwriting it. - mInAnimation = true; + mInAnimation = true; mAnimatingOvershootOn = animatingOn; RemoveAnimation(mScrollOvershootAnimation); mScrollOvershootAnimation = Animation::New(duration); mScrollOvershootAnimation.FinishedSignal().Connect(this, &ItemView::OnOvershootOnFinished); - mScrollOvershootAnimation.AnimateTo( Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration) ); + mScrollOvershootAnimation.AnimateTo(Property(self, Toolkit::ItemView::Property::OVERSHOOT), overshootAmount, TimePeriod(0.0f, duration)); mScrollOvershootAnimation.Play(); } else { - self.SetProperty( Toolkit::ItemView::Property::OVERSHOOT, overshootAmount ); + self.SetProperty(Toolkit::ItemView::Property::OVERSHOOT, overshootAmount); } } -void ItemView::SetItemsParentOrigin( const Vector3& parentOrigin ) +void ItemView::SetItemsParentOrigin(const Vector3& parentOrigin) { - if( parentOrigin != mItemsParentOrigin ) + if(parentOrigin != mItemsParentOrigin) { mItemsParentOrigin = parentOrigin; - for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) + for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { - iter->second.SetProperty( Actor::Property::PARENT_ORIGIN,parentOrigin ); + iter->second.SetProperty(Actor::Property::PARENT_ORIGIN, parentOrigin); } } } @@ -1707,14 +1692,14 @@ Vector3 ItemView::GetItemsParentOrigin() const return mItemsParentOrigin; } -void ItemView::SetItemsAnchorPoint( const Vector3& anchorPoint ) +void ItemView::SetItemsAnchorPoint(const Vector3& anchorPoint) { - if( anchorPoint != mItemsAnchorPoint ) + if(anchorPoint != mItemsAnchorPoint) { mItemsAnchorPoint = anchorPoint; - for (ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) + for(ItemIter iter = mItemPool.begin(); iter != mItemPool.end(); ++iter) { - iter->second.SetProperty( Actor::Property::ANCHOR_POINT,anchorPoint); + iter->second.SetProperty(Actor::Property::ANCHOR_POINT, anchorPoint); } } } @@ -1726,28 +1711,28 @@ Vector3 ItemView::GetItemsAnchorPoint() const void ItemView::GetItemsRange(ItemRange& range) { - if( !mItemPool.empty() ) + if(!mItemPool.empty()) { range.begin = mItemPool.begin()->first; - range.end = mItemPool.rbegin()->first + 1; + range.end = mItemPool.rbegin()->first + 1; } else { range.begin = 0; - range.end = 0; + range.end = 0; } } -bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool ItemView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle ); + bool connected(true); + Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL ) ) + if(0 == strcmp(signalName.c_str(), LAYOUT_ACTIVATED_SIGNAL)) { - itemView.LayoutActivatedSignal().Connect( tracker, functor ); + itemView.LayoutActivatedSignal().Connect(tracker, functor); } else { @@ -1758,42 +1743,42 @@ bool ItemView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* return connected; } -void ItemView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void ItemView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(Dali::BaseHandle(object)); - if( itemView ) + if(itemView) { - ItemView& itemViewImpl( GetImpl( itemView ) ); - switch( index ) + ItemView& itemViewImpl(GetImpl(itemView)); + switch(index) { case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED: { - itemViewImpl.SetMinimumSwipeSpeed( value.Get() ); + itemViewImpl.SetMinimumSwipeSpeed(value.Get()); break; } case Toolkit::ItemView::Property::MINIMUM_SWIPE_DISTANCE: { - itemViewImpl.SetMinimumSwipeDistance( value.Get() ); + itemViewImpl.SetMinimumSwipeDistance(value.Get()); break; } case Toolkit::ItemView::Property::WHEEL_SCROLL_DISTANCE_STEP: { - itemViewImpl.SetWheelScrollDistanceStep( value.Get() ); + itemViewImpl.SetWheelScrollDistanceStep(value.Get()); break; } case Toolkit::ItemView::Property::SNAP_TO_ITEM_ENABLED: { - itemViewImpl.SetAnchoring( value.Get() ); + itemViewImpl.SetAnchoring(value.Get()); break; } case Toolkit::ItemView::Property::REFRESH_INTERVAL: { - itemViewImpl.SetRefreshInterval( value.Get() ); + itemViewImpl.SetRefreshInterval(value.Get()); break; } @@ -1801,9 +1786,9 @@ void ItemView::SetProperty( BaseObject* object, Property::Index index, const Pro { // Get a Property::Array from the property if possible. Property::Array layoutArray; - if( value.Get( layoutArray ) ) + if(value.Get(layoutArray)) { - itemViewImpl.SetLayoutArray( layoutArray ); + itemViewImpl.SetLayoutArray(layoutArray); } break; } @@ -1816,11 +1801,11 @@ Property::Array ItemView::GetLayoutArray() return mlayoutArray; } -void ItemView::SetLayoutArray( const Property::Array& layouts ) +void ItemView::SetLayoutArray(const Property::Array& layouts) { - mlayoutArray = layouts; + mlayoutArray = layouts; const int layoutCount = GetLayoutCount(); - if( layoutCount > 0 ) + if(layoutCount > 0) { for(int index = layoutCount - 1; index >= 0; --index) { @@ -1829,16 +1814,16 @@ void ItemView::SetLayoutArray( const Property::Array& layouts ) } } - for( unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx ) + for(unsigned int arrayIdx = 0, arrayCount = layouts.Count(); arrayIdx < arrayCount; ++arrayIdx) { - const Property::Value& element = layouts.GetElementAt( arrayIdx ); + const Property::Value& element = layouts.GetElementAt(arrayIdx); const Property::Map* layout = element.GetMap(); - if( layout != NULL ) + if(layout != NULL) { - for( unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx ) + for(unsigned int mapIdx = 0, mapCount = (*layout).Count(); mapIdx < mapCount; ++mapIdx) { - KeyValuePair propertyPair( (*layout).GetKeyValue( mapIdx ) ); + KeyValuePair propertyPair((*layout).GetKeyValue(mapIdx)); if(propertyPair.first == DefaultItemLayoutProperty::TYPE) { @@ -1867,7 +1852,7 @@ void ItemView::SetLayoutArray( const Property::Array& layouts ) case DefaultItemLayout::LIST: { Internal::GridLayoutPtr listLayout = Internal::GridLayout::New(); - listLayout->SetNumberOfColumns( 1 ); + listLayout->SetNumberOfColumns(1); (*listLayout).SetLayoutProperties(*layout); (*listLayout).SetGridLayoutProperties(*layout); AddLayout(*listLayout); @@ -1889,16 +1874,16 @@ void ItemView::SetLayoutArray( const Property::Array& layouts ) } } -Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index ) +Property::Value ItemView::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(Dali::BaseHandle(object)); - if( itemView ) + if(itemView) { - ItemView& itemViewImpl( GetImpl( itemView ) ); - switch( index ) + ItemView& itemViewImpl(GetImpl(itemView)); + switch(index) { case Toolkit::ItemView::Property::MINIMUM_SWIPE_SPEED: { @@ -1932,8 +1917,8 @@ Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index case Toolkit::ItemView::Property::LAYOUT: { - Property::Array layouts= itemViewImpl.GetLayoutArray(); - value = layouts; + Property::Array layouts = itemViewImpl.GetLayoutArray(); + value = layouts; break; } } @@ -1942,25 +1927,25 @@ Property::Value ItemView::GetProperty( BaseObject* object, Property::Index index return value; } -bool ItemView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes ) +bool ItemView::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - Toolkit::ItemView itemView = Toolkit::ItemView::DownCast( handle ); + Toolkit::ItemView itemView = Toolkit::ItemView::DownCast(handle); - DALI_ASSERT_ALWAYS( itemView ); + DALI_ASSERT_ALWAYS(itemView); - if( 0 == strcmp( actionName.c_str(), ACTION_STOP_SCROLLING ) ) + if(0 == strcmp(actionName.c_str(), ACTION_STOP_SCROLLING)) { - GetImpl( itemView ).DoStopScrolling(); + GetImpl(itemView).DoStopScrolling(); } - else if ( 0 == strcmp( actionName.c_str(), ACTION_ENABLE_REFRESH ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_ENABLE_REFRESH)) { - GetImpl( itemView ).SetRefreshNotificationEnabled( true ); + GetImpl(itemView).SetRefreshNotificationEnabled(true); } - else if ( 0 == strcmp( actionName.c_str(), ACTION_DISABLE_REFRESH ) ) + else if(0 == strcmp(actionName.c_str(), ACTION_DISABLE_REFRESH)) { - GetImpl( itemView ).SetRefreshNotificationEnabled( false ); + GetImpl(itemView).SetRefreshNotificationEnabled(false); } return true; @@ -1968,14 +1953,14 @@ bool ItemView::DoAction( BaseObject* object, const std::string& actionName, cons void ItemView::DoStopScrolling() { - if( mScrollAnimation ) + if(mScrollAnimation) { mScrollAnimation.Stop(); mScrollAnimation.Reset(); } } -void ItemView::SetRefreshNotificationEnabled( bool enabled ) +void ItemView::SetRefreshNotificationEnabled(bool enabled) { mRefreshNotificationEnabled = enabled; } diff --git a/dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.cpp b/dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.cpp old mode 100755 new mode 100644 index 9121ebe..9c5c80b --- a/dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.cpp +++ b/dali-toolkit/internal/controls/scrollable/item-view/spiral-layout.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,178 +19,177 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include using namespace Dali; using namespace Dali::Toolkit; namespace // unnamed namespace { - const float DEFAULT_ITEMS_PER_SPIRAL_TURN = 9.5f; -const float DEFAULT_ITEM_SPACING_RADIANS = Math::PI*2.0f/DEFAULT_ITEMS_PER_SPIRAL_TURN; +const float DEFAULT_ITEM_SPACING_RADIANS = Math::PI * 2.0f / DEFAULT_ITEMS_PER_SPIRAL_TURN; const float DEFAULT_REVOLUTION_DISTANCE = 190.0f; -const float DEFAULT_ITEM_DESCENT = DEFAULT_REVOLUTION_DISTANCE / DEFAULT_ITEMS_PER_SPIRAL_TURN; +const float DEFAULT_ITEM_DESCENT = DEFAULT_REVOLUTION_DISTANCE / DEFAULT_ITEMS_PER_SPIRAL_TURN; const float DEFAULT_TOP_ITEM_ALIGNMENT = -0.125f; -const float DEFAULT_SCROLL_SPEED_FACTOR = 0.01f; -const float DEFAULT_MAXIMUM_SWIPE_SPEED = 30.0f; +const float DEFAULT_SCROLL_SPEED_FACTOR = 0.01f; +const float DEFAULT_MAXIMUM_SWIPE_SPEED = 30.0f; const float DEFAULT_ITEM_FLICK_ANIMATION_DURATION = 0.1f; float GetDefaultSpiralRadiusFunction(const Vector3& layoutSize) { - return layoutSize.width*0.4f; + return layoutSize.width * 0.4f; } struct SpiralPositionConstraint { - SpiralPositionConstraint( unsigned int itemId, float spiralRadius, float itemSpacingRadians, float itemDescent, float topItemAlignment ) - : mItemId( itemId ), - mSpiralRadius( spiralRadius ), - mItemSpacingRadians( itemSpacingRadians ), - mItemDescent( itemDescent ), - mTopItemAlignment( topItemAlignment ) + SpiralPositionConstraint(unsigned int itemId, float spiralRadius, float itemSpacingRadians, float itemDescent, float topItemAlignment) + : mItemId(itemId), + mSpiralRadius(spiralRadius), + mItemSpacingRadians(itemSpacingRadians), + mItemDescent(itemDescent), + mTopItemAlignment(topItemAlignment) { } - inline void OrientationUp( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void OrientationUp(Vector3& current, float layoutPosition, const Vector3& layoutSize) { float angle = -Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; - current.x = -mSpiralRadius * cosf( angle ); - current.y = ( mItemDescent * layoutPosition ) + layoutSize.height * mTopItemAlignment; - current.z = -mSpiralRadius * sinf( angle ); + current.x = -mSpiralRadius * cosf(angle); + current.y = (mItemDescent * layoutPosition) + layoutSize.height * mTopItemAlignment; + current.z = -mSpiralRadius * sinf(angle); } - inline void OrientationLeft( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void OrientationLeft(Vector3& current, float layoutPosition, const Vector3& layoutSize) { float angle = Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; - current.x = ( mItemDescent * layoutPosition ) + layoutSize.width * mTopItemAlignment; - current.y = -mSpiralRadius * cosf( angle ); - current.z = mSpiralRadius * sinf( angle ); + current.x = (mItemDescent * layoutPosition) + layoutSize.width * mTopItemAlignment; + current.y = -mSpiralRadius * cosf(angle); + current.z = mSpiralRadius * sinf(angle); } - inline void OrientationDown( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void OrientationDown(Vector3& current, float layoutPosition, const Vector3& layoutSize) { float angle = Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; - current.x = -mSpiralRadius * cosf( angle ); - current.y = ( -mItemDescent * layoutPosition ) - layoutSize.height * mTopItemAlignment; + current.x = -mSpiralRadius * cosf(angle); + current.y = (-mItemDescent * layoutPosition) - layoutSize.height * mTopItemAlignment; current.z = mSpiralRadius * sinf(angle); } - inline void OrientationRight( Vector3& current, float layoutPosition, const Vector3& layoutSize ) + inline void OrientationRight(Vector3& current, float layoutPosition, const Vector3& layoutSize) { - float angle = -Math::PI*0.5f + mItemSpacingRadians * layoutPosition; + float angle = -Math::PI * 0.5f + mItemSpacingRadians * layoutPosition; current.x = (-mItemDescent * layoutPosition) - layoutSize.width * mTopItemAlignment; - current.y = -mSpiralRadius * cosf( angle ); - current.z = -mSpiralRadius * sinf( angle ); + current.y = -mSpiralRadius * cosf(angle); + current.z = -mSpiralRadius * sinf(angle); } - void OrientationUp( Vector3& current, const PropertyInputContainer& inputs ) + void OrientationUp(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - OrientationUp( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + OrientationUp(current, layoutPosition, layoutSize); } - void OrientationLeft( Vector3& current, const PropertyInputContainer& inputs ) + void OrientationLeft(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - OrientationLeft( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + OrientationLeft(current, layoutPosition, layoutSize); } - void OrientationDown( Vector3& current, const PropertyInputContainer& inputs ) + void OrientationDown(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - OrientationDown( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + OrientationDown(current, layoutPosition, layoutSize); } - void OrientationRight( Vector3& current, const PropertyInputContainer& inputs ) + void OrientationRight(Vector3& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - OrientationRight( current, layoutPosition, layoutSize ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + OrientationRight(current, layoutPosition, layoutSize); } unsigned int mItemId; - float mSpiralRadius; - float mItemSpacingRadians; - float mItemDescent; - float mTopItemAlignment; + float mSpiralRadius; + float mItemSpacingRadians; + float mItemDescent; + float mTopItemAlignment; }; struct SpiralRotationConstraint { - SpiralRotationConstraint( unsigned int itemId, float itemSpacingRadians ) - : mItemId( itemId ), - mItemSpacingRadians( itemSpacingRadians ) + SpiralRotationConstraint(unsigned int itemId, float itemSpacingRadians) + : mItemId(itemId), + mItemSpacingRadians(itemSpacingRadians) { } - void OrientationUp( Quaternion& current, const PropertyInputContainer& inputs ) + void OrientationUp(Quaternion& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - float angle = -mItemSpacingRadians * layoutPosition; + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + float angle = -mItemSpacingRadians * layoutPosition; - current = Quaternion( Radian( angle ), Vector3::YAXIS); + current = Quaternion(Radian(angle), Vector3::YAXIS); } - void OrientationLeft( Quaternion& current, const PropertyInputContainer& inputs ) + void OrientationLeft(Quaternion& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - float angle = -mItemSpacingRadians * layoutPosition; + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + float angle = -mItemSpacingRadians * layoutPosition; - current = Quaternion( Radian( -Math::PI * 0.5f ), Vector3::ZAXIS ) * Quaternion( Radian( angle ), Vector3::YAXIS ); + current = Quaternion(Radian(-Math::PI * 0.5f), Vector3::ZAXIS) * Quaternion(Radian(angle), Vector3::YAXIS); } - void OrientationDown( Quaternion& current, const PropertyInputContainer& inputs ) + void OrientationDown(Quaternion& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - float angle = -mItemSpacingRadians * layoutPosition; + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + float angle = -mItemSpacingRadians * layoutPosition; - current = Quaternion( Radian( -Math::PI ), Vector3::ZAXIS) * Quaternion( Radian( angle ), Vector3::YAXIS ); + current = Quaternion(Radian(-Math::PI), Vector3::ZAXIS) * Quaternion(Radian(angle), Vector3::YAXIS); } - void OrientationRight( Quaternion& current, const PropertyInputContainer& inputs ) + void OrientationRight(Quaternion& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - float angle = -mItemSpacingRadians * layoutPosition; + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + float angle = -mItemSpacingRadians * layoutPosition; - current = Quaternion( Radian( -Math::PI * 1.5f ), Vector3::ZAXIS) * Quaternion( Radian( angle ), Vector3::YAXIS ); + current = Quaternion(Radian(-Math::PI * 1.5f), Vector3::ZAXIS) * Quaternion(Radian(angle), Vector3::YAXIS); } unsigned int mItemId; - float mItemSpacingRadians; + float mItemSpacingRadians; }; struct SpiralColorConstraint { - SpiralColorConstraint( unsigned int itemId, float itemSpacingRadians ) - : mItemId( itemId ), - mItemSpacingRadians( itemSpacingRadians ) + SpiralColorConstraint(unsigned int itemId, float itemSpacingRadians) + : mItemId(itemId), + mItemSpacingRadians(itemSpacingRadians) { } - void operator()( Vector4& current, const PropertyInputContainer& inputs ) + void operator()(Vector4& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - Radian angle( mItemSpacingRadians * fabsf( layoutPosition ) / Dali::ANGLE_360 ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + Radian angle(mItemSpacingRadians * fabsf(layoutPosition) / Dali::ANGLE_360); - float progress = angle - floorf( angle ); // take fractional bit only to get between 0.0 - 1.0 - progress = (progress > 0.5f) ? 2.0f*(1.0f - progress) : progress*2.0f; + float progress = angle - floorf(angle); // take fractional bit only to get between 0.0 - 1.0 + progress = (progress > 0.5f) ? 2.0f * (1.0f - progress) : progress * 2.0f; float darkness(1.0f); { @@ -198,13 +197,13 @@ struct SpiralColorConstraint const float endMarker = 0.35f; // The progress at which darkening ends const float minDarkness = 0.15f; // The darkness at end marker - if (progress > endMarker) + if(progress > endMarker) { darkness = minDarkness; } - else if (progress > startMarker) + else if(progress > startMarker) { - darkness = 1.0f - ( (1.0f - minDarkness) * ((progress-startMarker) / (endMarker-startMarker)) ); + darkness = 1.0f - ((1.0f - minDarkness) * ((progress - startMarker) / (endMarker - startMarker))); } } @@ -212,52 +211,49 @@ struct SpiralColorConstraint } unsigned int mItemId; - float mItemSpacingRadians; + float mItemSpacingRadians; }; struct SpiralVisibilityConstraint { - SpiralVisibilityConstraint( unsigned int itemId, float itemSpacingRadians, float itemDescent, float topItemAlignment ) - : mItemId( itemId ), - mItemSpacingRadians( itemSpacingRadians ), - mItemDescent( itemDescent ), - mTopItemAlignment( topItemAlignment ) + SpiralVisibilityConstraint(unsigned int itemId, float itemSpacingRadians, float itemDescent, float topItemAlignment) + : mItemId(itemId), + mItemSpacingRadians(itemSpacingRadians), + mItemDescent(itemDescent), + mTopItemAlignment(topItemAlignment) { } - void Portrait( bool& current, const PropertyInputContainer& inputs ) + void Portrait(bool& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - float itemsCachedBeforeTopItem = layoutSize.height*(mTopItemAlignment+0.5f) / mItemDescent; - current = ( layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= ( layoutSize.height / mItemDescent ) + 1.0f ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + float itemsCachedBeforeTopItem = layoutSize.height * (mTopItemAlignment + 0.5f) / mItemDescent; + current = (layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= (layoutSize.height / mItemDescent) + 1.0f); } - void Landscape( bool& current, const PropertyInputContainer& inputs ) + void Landscape(bool& current, const PropertyInputContainer& inputs) { - float layoutPosition = inputs[0]->GetFloat() + static_cast< float >( mItemId ); - const Vector3& layoutSize = inputs[1]->GetVector3(); - float itemsCachedBeforeTopItem = layoutSize.width*(mTopItemAlignment+0.5f) / mItemDescent; - current = ( layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= ( layoutSize.width / mItemDescent ) + 1.0f ); + float layoutPosition = inputs[0]->GetFloat() + static_cast(mItemId); + const Vector3& layoutSize = inputs[1]->GetVector3(); + float itemsCachedBeforeTopItem = layoutSize.width * (mTopItemAlignment + 0.5f) / mItemDescent; + current = (layoutPosition >= -itemsCachedBeforeTopItem - 1.0f && layoutPosition <= (layoutSize.width / mItemDescent) + 1.0f); } unsigned int mItemId; - float mItemSpacingRadians; - float mItemDescent; - float mTopItemAlignment; + float mItemSpacingRadians; + float mItemDescent; + float mTopItemAlignment; }; } // unnamed namespace namespace Dali { - namespace Toolkit { - namespace Internal { - struct SpiralLayout::Impl { Impl() @@ -294,21 +290,21 @@ void SpiralLayout::SetItemSpacing(Radian itemSpacing) { mImpl->mItemSpacingRadians = itemSpacing; - float itemsPerSpiral = std::max(1.0f, (2.0f*(float)Math::PI) / mImpl->mItemSpacingRadians); - mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral; + float itemsPerSpiral = std::max(1.0f, (2.0f * (float)Math::PI) / mImpl->mItemSpacingRadians); + mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral; } Radian SpiralLayout::GetItemSpacing() const { - return Radian( mImpl->mItemSpacingRadians ); + return Radian(mImpl->mItemSpacingRadians); } void SpiralLayout::SetRevolutionDistance(float distance) { mImpl->mRevolutionDistance = distance; - float itemsPerSpiral = std::max(1.0f, (2.0f*(float)Math::PI) / mImpl->mItemSpacingRadians); - mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral; + float itemsPerSpiral = std::max(1.0f, (2.0f * (float)Math::PI) / mImpl->mItemSpacingRadians); + mImpl->mItemDescent = mImpl->mRevolutionDistance / itemsPerSpiral; } float SpiralLayout::GetRevolutionDistance() const @@ -373,128 +369,127 @@ float SpiralLayout::GetItemScrollToPosition(unsigned int itemId) const ItemRange SpiralLayout::GetItemsWithinArea(float firstItemPosition, Vector3 layoutSize) const { - float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; - float itemsPerSpiral = layoutHeight / mImpl->mItemDescent; + float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height; + float itemsPerSpiral = layoutHeight / mImpl->mItemDescent; float itemsCachedBeforeTopItem = layoutHeight * (mImpl->mTopItemAlignment + 0.5f) / mImpl->mItemDescent; - float itemsViewable = std::min(itemsPerSpiral, itemsPerSpiral - itemsCachedBeforeTopItem - firstItemPosition + 1.0f); + float itemsViewable = std::min(itemsPerSpiral, itemsPerSpiral - itemsCachedBeforeTopItem - firstItemPosition + 1.0f); unsigned int firstItem = static_cast(std::max(0.0f, -firstItemPosition - itemsCachedBeforeTopItem - 1.0f)); unsigned int lastItem = static_cast(std::max(0.0f, firstItem + itemsViewable)); - return ItemRange(firstItem, lastItem+1); + return ItemRange(firstItem, lastItem + 1); } unsigned int SpiralLayout::GetReserveItemCount(Vector3 layoutSize) const { - float layoutHeight = IsHorizontal( GetOrientation() ) ? layoutSize.width : layoutSize.height; + float layoutHeight = IsHorizontal(GetOrientation()) ? layoutSize.width : layoutSize.height; return static_cast(layoutHeight / mImpl->mItemDescent); } -void SpiralLayout::GetDefaultItemSize( unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize ) const +void SpiralLayout::GetDefaultItemSize(unsigned int itemId, const Vector3& layoutSize, Vector3& itemSize) const { itemSize.width = layoutSize.width * 0.25f; // 4x3 aspect ratio - itemSize.height = itemSize.depth = ( itemSize.width / 4.0f ) * 3.0f; + itemSize.height = itemSize.depth = (itemSize.width / 4.0f) * 3.0f; } Degree SpiralLayout::GetScrollDirection() const { - Degree scrollDirection(0); + Degree scrollDirection(0); const ControlOrientation::Type orientation = GetOrientation(); - if ( orientation == ControlOrientation::Up ) + if(orientation == ControlOrientation::Up) { - scrollDirection = Degree( -45.0f ); // Allow swiping horizontally & vertically + scrollDirection = Degree(-45.0f); // Allow swiping horizontally & vertically } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - scrollDirection = Degree( 45.0f ); + scrollDirection = Degree(45.0f); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - scrollDirection = Degree( 180.0f - 45.0f ); + scrollDirection = Degree(180.0f - 45.0f); } else // orientation == ControlOrientation::Right { - scrollDirection = Degree( 270.0f - 45.0f ); + scrollDirection = Degree(270.0f - 45.0f); } return scrollDirection; } -void SpiralLayout::ApplyConstraints( Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor ) +void SpiralLayout::ApplyConstraints(Actor& actor, const int itemId, const Vector3& layoutSize, const Actor& itemViewActor) { - // This just implements the default behaviour of constraint application. // Custom layouts can override this function to apply their custom constraints. - Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast( itemViewActor ); - if( itemView ) + Dali::Toolkit::ItemView itemView = Dali::Toolkit::ItemView::DownCast(itemViewActor); + if(itemView) { const ControlOrientation::Type orientation = GetOrientation(); // Position constraint - SpiralPositionConstraint positionConstraint( itemId, GetDefaultSpiralRadiusFunction( layoutSize ), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment ); - Constraint constraint; - if ( orientation == ControlOrientation::Up ) + SpiralPositionConstraint positionConstraint(itemId, GetDefaultSpiralRadiusFunction(layoutSize), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment); + Constraint constraint; + if(orientation == ControlOrientation::Up) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationUp ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationUp); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationLeft ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationLeft); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationDown ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationDown); } else // orientation == ControlOrientation::Right { - constraint = Constraint::New< Vector3 >( actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationRight ); + constraint = Constraint::New(actor, Actor::Property::POSITION, positionConstraint, &SpiralPositionConstraint::OrientationRight); } - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.AddSource(ParentSource(Actor::Property::SIZE)); constraint.Apply(); // Rotation constraint - SpiralRotationConstraint rotationConstraint( itemId, mImpl->mItemSpacingRadians ); - if ( orientation == ControlOrientation::Up ) + SpiralRotationConstraint rotationConstraint(itemId, mImpl->mItemSpacingRadians); + if(orientation == ControlOrientation::Up) { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationUp ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationUp); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationLeft ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationLeft); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationDown ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationDown); } else // orientation == ControlOrientation::Right { - constraint = Constraint::New< Quaternion >( actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationRight ); + constraint = Constraint::New(actor, Actor::Property::ORIENTATION, rotationConstraint, &SpiralRotationConstraint::OrientationRight); } - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); constraint.Apply(); // Color constraint - constraint = Constraint::New< Vector4 >( actor, Actor::Property::COLOR, SpiralColorConstraint( itemId, mImpl->mItemSpacingRadians ) ); - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); + constraint = Constraint::New(actor, Actor::Property::COLOR, SpiralColorConstraint(itemId, mImpl->mItemSpacingRadians)); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); constraint.SetRemoveAction(Dali::Constraint::DISCARD); constraint.Apply(); // Visibility constraint - SpiralVisibilityConstraint visibilityConstraint( itemId, mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment ); - if (IsVertical( orientation ) ) + SpiralVisibilityConstraint visibilityConstraint(itemId, mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment); + if(IsVertical(orientation)) { - constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Portrait ); + constraint = Constraint::New(actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Portrait); } else // horizontal { - constraint = Constraint::New< bool >( actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Landscape ); + constraint = Constraint::New(actor, Actor::Property::VISIBLE, visibilityConstraint, &SpiralVisibilityConstraint::Landscape); } - constraint.AddSource( ParentSource( Toolkit::ItemView::Property::LAYOUT_POSITION ) ); - constraint.AddSource( ParentSource( Actor::Property::SIZE ) ); + constraint.AddSource(ParentSource(Toolkit::ItemView::Property::LAYOUT_POSITION)); + constraint.AddSource(ParentSource(Actor::Property::SIZE)); constraint.SetRemoveAction(Dali::Constraint::DISCARD); constraint.Apply(); } @@ -503,9 +498,9 @@ void SpiralLayout::ApplyConstraints( Actor& actor, const int itemId, const Vecto void SpiralLayout::SetSpiralLayoutProperties(const Property::Map& properties) { // Set any properties specified for SpiralLayout. - for( unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx ) + for(unsigned int idx = 0, mapCount = properties.Count(); idx < mapCount; ++idx) { - KeyValuePair propertyPair = properties.GetKeyValue( idx ); + KeyValuePair propertyPair = properties.GetKeyValue(idx); switch(DefaultItemLayoutProperty::Property(propertyPair.first.indexKey)) { case DefaultItemLayoutProperty::SPIRAL_ITEM_SPACING: @@ -548,26 +543,26 @@ void SpiralLayout::SetSpiralLayoutProperties(const Property::Map& properties) Vector3 SpiralLayout::GetItemPosition(int itemID, float currentLayoutPosition, const Vector3& layoutSize) const { - Vector3 itemPosition = Vector3::ZERO; - const ControlOrientation::Type orientation = GetOrientation(); + Vector3 itemPosition = Vector3::ZERO; + const ControlOrientation::Type orientation = GetOrientation(); - SpiralPositionConstraint positionConstraint( itemID, GetDefaultSpiralRadiusFunction( layoutSize ), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment ); + SpiralPositionConstraint positionConstraint(itemID, GetDefaultSpiralRadiusFunction(layoutSize), mImpl->mItemSpacingRadians, mImpl->mItemDescent, mImpl->mTopItemAlignment); - if ( orientation == ControlOrientation::Up ) + if(orientation == ControlOrientation::Up) { - positionConstraint.OrientationUp( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraint.OrientationUp(itemPosition, currentLayoutPosition + itemID, layoutSize); } - else if ( orientation == ControlOrientation::Left ) + else if(orientation == ControlOrientation::Left) { - positionConstraint.OrientationLeft( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraint.OrientationLeft(itemPosition, currentLayoutPosition + itemID, layoutSize); } - else if ( orientation == ControlOrientation::Down ) + else if(orientation == ControlOrientation::Down) { - positionConstraint.OrientationDown( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraint.OrientationDown(itemPosition, currentLayoutPosition + itemID, layoutSize); } else //orientation == ControlOrientation::Right { - positionConstraint.OrientationRight( itemPosition, currentLayoutPosition + itemID, layoutSize ); + positionConstraint.OrientationRight(itemPosition, currentLayoutPosition + itemID, layoutSize); } return itemPosition; diff --git a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-base-impl.cpp b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-base-impl.cpp index 1a5c766..def121d 100644 --- a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-base-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-base-impl.cpp @@ -22,25 +22,22 @@ using namespace Dali; namespace Dali { - namespace Toolkit { - namespace Internal { - /////////////////////////////////////////////////////////////////////////////////////////////////// // ScrollBase /////////////////////////////////////////////////////////////////////////////////////////////////// -ScrollBase::ScrollBase( ControlBehaviour behaviourFlags ) -: Scrollable( behaviourFlags ), +ScrollBase::ScrollBase(ControlBehaviour behaviourFlags) +: Scrollable(behaviourFlags), mParent(NULL), mDelay(0.0f) { } -void ScrollBase::SetParent(ScrollBase *parent) +void ScrollBase::SetParent(ScrollBase* parent) { mParent = parent; } @@ -55,7 +52,7 @@ void ScrollBase::BindActor(Actor child) // Apply all our constraints to this new child. ConstraintStack::iterator i; - for(i = mConstraintStack.begin();i!=mConstraintStack.end();i++) + for(i = mConstraintStack.begin(); i != mConstraintStack.end(); i++) { actorInfo->ApplyConstraint(*i); } @@ -64,11 +61,11 @@ void ScrollBase::BindActor(Actor child) void ScrollBase::UnbindActor(Actor child) { // Find the child in mBoundActors, and unparent it - for (ActorInfoIter iter = mBoundActors.begin(); iter != mBoundActors.end(); ++iter) + for(ActorInfoIter iter = mBoundActors.begin(); iter != mBoundActors.end(); ++iter) { ActorInfoPtr actorInfo = *iter; - if( actorInfo->mActor == child ) + if(actorInfo->mActor == child) { mBoundActors.erase(iter); break; @@ -95,7 +92,7 @@ void ScrollBase::ApplyConstraintToBoundActors(Constraint constraint) { mConstraintStack.push_back(constraint); - for(ActorInfoIter i = mBoundActors.begin();i != mBoundActors.end(); ++i) + for(ActorInfoIter i = mBoundActors.begin(); i != mBoundActors.end(); ++i) { (*i)->ApplyConstraint(constraint); } @@ -105,7 +102,7 @@ void ScrollBase::RemoveConstraintsFromBoundActors() { mConstraintStack.clear(); - for(ActorInfoIter i = mBoundActors.begin();i != mBoundActors.end(); ++i) + for(ActorInfoIter i = mBoundActors.begin(); i != mBoundActors.end(); ++i) { (*i)->RemoveConstraints(); } diff --git a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.cpp b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.cpp index c02c7ec..17953cd 100644 --- a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-overshoot-indicator-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,47 +19,42 @@ #include // INTERNAL INCLUDES -#include #include +#include #include using namespace Dali; namespace { - const float OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD = 180.0f; // local helper function to resize the height of the bounce actor -float GetBounceActorHeight( float width, float defaultHeight ) +float GetBounceActorHeight(float width, float defaultHeight) { return (width > OVERSHOOT_BOUNCE_ACTOR_RESIZE_THRESHOLD) ? defaultHeight : defaultHeight * 0.5f; } -const float MAX_OVERSHOOT_NOTIFY_AMOUNT = 0.99f; // maximum amount to set notification for increased overshoot, beyond this we just wait for it to reduce again -const float MIN_OVERSHOOT_NOTIFY_AMOUNT = Math::MACHINE_EPSILON_0; // minimum amount to set notification for reduced overshoot, beyond this we just wait for it to increase again -const float OVERSHOOT_NOTIFY_STEP = 0.01f; // amount to set notifications beyond current overshoot value +const float MAX_OVERSHOOT_NOTIFY_AMOUNT = 0.99f; // maximum amount to set notification for increased overshoot, beyond this we just wait for it to reduce again +const float MIN_OVERSHOOT_NOTIFY_AMOUNT = Math::MACHINE_EPSILON_0; // minimum amount to set notification for reduced overshoot, beyond this we just wait for it to increase again +const float OVERSHOOT_NOTIFY_STEP = 0.01f; // amount to set notifications beyond current overshoot value -} +} // namespace namespace Dali { - namespace Toolkit { - namespace Internal { - -ScrollOvershootIndicator::ScrollOvershootIndicator() : - mEffectX(NULL), +ScrollOvershootIndicator::ScrollOvershootIndicator() +: mEffectX(NULL), mEffectY(NULL) { } ScrollOvershootIndicator::~ScrollOvershootIndicator() { - } ScrollOvershootIndicator* ScrollOvershootIndicator::New() @@ -100,7 +95,7 @@ void ScrollOvershootIndicator::Reset() mEffectY->Reset(); } -void ScrollOvershootIndicator::SetOvershootEffectColor( const Vector4& color ) +void ScrollOvershootIndicator::SetOvershootEffectColor(const Vector4& color) { if(mEffectX) { @@ -112,10 +107,9 @@ void ScrollOvershootIndicator::SetOvershootEffectColor( const Vector4& color ) } } -ScrollOvershootEffect::ScrollOvershootEffect( bool vertical ) : - mVertical(vertical) +ScrollOvershootEffect::ScrollOvershootEffect(bool vertical) +: mVertical(vertical) { - } bool ScrollOvershootEffect::IsVertical() const @@ -123,38 +117,37 @@ bool ScrollOvershootEffect::IsVertical() const return mVertical; } -ScrollOvershootEffectRipple::ScrollOvershootEffectRipple( bool vertical, Scrollable& scrollable ) : - ScrollOvershootEffect( vertical ), - mAttachedScrollView(scrollable), - mOvershootProperty(Property::INVALID_INDEX), - mEffectOvershootProperty(Property::INVALID_INDEX), - mOvershoot(0.0f), - mOvershootSize( scrollable.GetOvershootSize() ), - mAnimationStateFlags(0) +ScrollOvershootEffectRipple::ScrollOvershootEffectRipple(bool vertical, Scrollable& scrollable) +: ScrollOvershootEffect(vertical), + mAttachedScrollView(scrollable), + mOvershootProperty(Property::INVALID_INDEX), + mEffectOvershootProperty(Property::INVALID_INDEX), + mOvershoot(0.0f), + mOvershootSize(scrollable.GetOvershootSize()), + mAnimationStateFlags(0) { mOvershootOverlay = CreateBouncingEffectActor(mEffectOvershootProperty); - mOvershootOverlay.SetProperty( Actor::Property::COLOR,mAttachedScrollView.GetOvershootEffectColor()); - mOvershootOverlay.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT ); - mOvershootOverlay.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::TOP_LEFT); - mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,false); - + mOvershootOverlay.SetProperty(Actor::Property::COLOR, mAttachedScrollView.GetOvershootEffectColor()); + mOvershootOverlay.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + mOvershootOverlay.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, false); } void ScrollOvershootEffectRipple::Apply() { - Actor self = mAttachedScrollView.Self(); + Actor self = mAttachedScrollView.Self(); mOvershootProperty = IsVertical() ? Toolkit::ScrollView::Property::OVERSHOOT_Y : Toolkit::ScrollView::Property::OVERSHOOT_X; // make sure height is set, since we only create a constraint for image width mOvershootSize = mAttachedScrollView.GetOvershootSize(); - mOvershootOverlay.SetProperty( Actor::Property::SIZE, mOvershootSize ); + mOvershootOverlay.SetProperty(Actor::Property::SIZE, mOvershootSize); mAttachedScrollView.AddOverlay(mOvershootOverlay); UpdatePropertyNotifications(); } -void ScrollOvershootEffectRipple::Remove( Scrollable& scrollable ) +void ScrollOvershootEffectRipple::Remove(Scrollable& scrollable) { if(mOvershootOverlay) { @@ -174,8 +167,8 @@ void ScrollOvershootEffectRipple::Remove( Scrollable& scrollable ) void ScrollOvershootEffectRipple::Reset() { - mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,false); - mOvershootOverlay.SetProperty( mEffectOvershootProperty, 0.f); + mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, false); + mOvershootOverlay.SetProperty(mEffectOvershootProperty, 0.f); } void ScrollOvershootEffectRipple::UpdatePropertyNotifications() @@ -184,95 +177,95 @@ void ScrollOvershootEffectRipple::UpdatePropertyNotifications() Actor self = mAttachedScrollView.Self(); // update overshoot increase notify - if( mOvershootIncreaseNotification ) + if(mOvershootIncreaseNotification) { - self.RemovePropertyNotification( mOvershootIncreaseNotification ); + self.RemovePropertyNotification(mOvershootIncreaseNotification); mOvershootIncreaseNotification.Reset(); } - if( absOvershoot < MAX_OVERSHOOT_NOTIFY_AMOUNT ) + if(absOvershoot < MAX_OVERSHOOT_NOTIFY_AMOUNT) { float increaseStep = absOvershoot + OVERSHOOT_NOTIFY_STEP; - if( increaseStep > MAX_OVERSHOOT_NOTIFY_AMOUNT ) + if(increaseStep > MAX_OVERSHOOT_NOTIFY_AMOUNT) { increaseStep = MAX_OVERSHOOT_NOTIFY_AMOUNT; } - mOvershootIncreaseNotification = self.AddPropertyNotification( mOvershootProperty, OutsideCondition(-increaseStep, increaseStep) ); + mOvershootIncreaseNotification = self.AddPropertyNotification(mOvershootProperty, OutsideCondition(-increaseStep, increaseStep)); mOvershootIncreaseNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_TRUE); mOvershootIncreaseNotification.NotifySignal().Connect(this, &ScrollOvershootEffectRipple::OnOvershootNotification); } // update overshoot decrease notify - if( mOvershootDecreaseNotification ) + if(mOvershootDecreaseNotification) { - self.RemovePropertyNotification( mOvershootDecreaseNotification ); + self.RemovePropertyNotification(mOvershootDecreaseNotification); mOvershootDecreaseNotification.Reset(); } - if( absOvershoot > MIN_OVERSHOOT_NOTIFY_AMOUNT ) + if(absOvershoot > MIN_OVERSHOOT_NOTIFY_AMOUNT) { float reduceStep = absOvershoot - OVERSHOOT_NOTIFY_STEP; - if( reduceStep < MIN_OVERSHOOT_NOTIFY_AMOUNT ) + if(reduceStep < MIN_OVERSHOOT_NOTIFY_AMOUNT) { reduceStep = MIN_OVERSHOOT_NOTIFY_AMOUNT; } - mOvershootDecreaseNotification = self.AddPropertyNotification( mOvershootProperty, InsideCondition(-reduceStep, reduceStep) ); + mOvershootDecreaseNotification = self.AddPropertyNotification(mOvershootProperty, InsideCondition(-reduceStep, reduceStep)); mOvershootDecreaseNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_TRUE); mOvershootDecreaseNotification.NotifySignal().Connect(this, &ScrollOvershootEffectRipple::OnOvershootNotification); } } -void ScrollOvershootEffectRipple::SetOvershootEffectColor( const Vector4& color ) +void ScrollOvershootEffectRipple::SetOvershootEffectColor(const Vector4& color) { if(mOvershootOverlay) { - mOvershootOverlay.SetProperty( Actor::Property::COLOR,color); + mOvershootOverlay.SetProperty(Actor::Property::COLOR, color); } } -void ScrollOvershootEffectRipple::UpdateVisibility( bool visible ) +void ScrollOvershootEffectRipple::UpdateVisibility(bool visible) { - mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,visible); + mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, visible); // make sure overshoot image is correctly placed - if( visible ) + if(visible) { Actor self = mAttachedScrollView.Self(); if(mOvershoot > 0.0f) { // positive overshoot - const Vector3 size = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - Vector3 relativeOffset; - const Vector3 parentSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + const Vector3 size = mOvershootOverlay.GetCurrentProperty(Actor::Property::SIZE); + Vector3 relativeOffset; + const Vector3 parentSize = self.GetCurrentProperty(Actor::Property::SIZE); if(IsVertical()) { - mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 0.0f ), Vector3::ZAXIS ) ) ); - mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth ) ); + mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(0.0f), Vector3::ZAXIS))); + mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth)); } else { - mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 1.5f * Math::PI ), Vector3::ZAXIS ) ) ); - mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth ) ); + mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(1.5f * Math::PI), Vector3::ZAXIS))); + mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth)); relativeOffset = Vector3(0.0f, 1.0f, 0.0f); } - mOvershootOverlay.SetProperty( Actor::Property::POSITION, relativeOffset * parentSize ); + mOvershootOverlay.SetProperty(Actor::Property::POSITION, relativeOffset * parentSize); } else { // negative overshoot - const Vector3 size = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - Vector3 relativeOffset; - const Vector3 parentSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + const Vector3 size = mOvershootOverlay.GetCurrentProperty(Actor::Property::SIZE); + Vector3 relativeOffset; + const Vector3 parentSize = self.GetCurrentProperty(Actor::Property::SIZE); if(IsVertical()) { - mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( Math::PI ), Vector3::ZAXIS ) ) ); - mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth ) ); + mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(Math::PI), Vector3::ZAXIS))); + mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.width, GetBounceActorHeight(parentSize.width, mOvershootSize.height), size.depth)); relativeOffset = Vector3(1.0f, 1.0f, 0.0f); } else { - mOvershootOverlay.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 0.5f * Math::PI ), Vector3::ZAXIS ) ) ); - mOvershootOverlay.SetProperty( Actor::Property::SIZE, Vector3( parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth ) ); + mOvershootOverlay.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(0.5f * Math::PI), Vector3::ZAXIS))); + mOvershootOverlay.SetProperty(Actor::Property::SIZE, Vector3(parentSize.height, GetBounceActorHeight(parentSize.height, mOvershootSize.height), size.depth)); relativeOffset = Vector3(1.0f, 0.0f, 0.0f); } - mOvershootOverlay.SetProperty( Actor::Property::POSITION, relativeOffset * parentSize ); + mOvershootOverlay.SetProperty(Actor::Property::POSITION, relativeOffset * parentSize); } } } @@ -280,92 +273,92 @@ void ScrollOvershootEffectRipple::UpdateVisibility( bool visible ) void ScrollOvershootEffectRipple::OnOvershootNotification(PropertyNotification& source) { Actor self = mAttachedScrollView.Self(); - mOvershoot = self.GetCurrentProperty< float >( mOvershootProperty ); + mOvershoot = self.GetCurrentProperty(mOvershootProperty); SetOvershoot(mOvershoot, false); UpdatePropertyNotifications(); } void ScrollOvershootEffectRipple::SetOvershoot(float amount, bool animate) { - float absAmount = fabsf(amount); - bool animatingOn = absAmount > Math::MACHINE_EPSILON_0; - if( (animatingOn && (mAnimationStateFlags & AnimatingIn)) ) + float absAmount = fabsf(amount); + bool animatingOn = absAmount > Math::MACHINE_EPSILON_0; + if((animatingOn && (mAnimationStateFlags & AnimatingIn))) { // trying to do what we are already doing - if( mAnimationStateFlags & AnimateBack ) + if(mAnimationStateFlags & AnimateBack) { mAnimationStateFlags &= ~AnimateBack; } return; } - if( (!animatingOn && (mAnimationStateFlags & AnimatingOut)) ) + if((!animatingOn && (mAnimationStateFlags & AnimatingOut))) { // trying to do what we are already doing return; } - if( !animatingOn && (mAnimationStateFlags & AnimatingIn) ) + if(!animatingOn && (mAnimationStateFlags & AnimatingIn)) { // dont interrupt while animating on mAnimationStateFlags |= AnimateBack; return; } - if( absAmount > Math::MACHINE_EPSILON_1 ) + if(absAmount > Math::MACHINE_EPSILON_1) { UpdateVisibility(true); } float overshootAnimationSpeed = mAttachedScrollView.Self().GetProperty(Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED); - if( animate && overshootAnimationSpeed > Math::MACHINE_EPSILON_0 ) + if(animate && overshootAnimationSpeed > Math::MACHINE_EPSILON_0) { - float currentOvershoot = fabsf( mOvershootOverlay.GetProperty( mEffectOvershootProperty ).Get() ); - float duration = mOvershootOverlay.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).height * (animatingOn ? (1.0f - currentOvershoot) : currentOvershoot) / overshootAnimationSpeed; + float currentOvershoot = fabsf(mOvershootOverlay.GetProperty(mEffectOvershootProperty).Get()); + float duration = mOvershootOverlay.GetCurrentProperty(Actor::Property::SIZE).height * (animatingOn ? (1.0f - currentOvershoot) : currentOvershoot) / overshootAnimationSpeed; - if( duration > Math::MACHINE_EPSILON_0 ) + if(duration > Math::MACHINE_EPSILON_0) { if(mScrollOvershootAnimation) { - mScrollOvershootAnimation.FinishedSignal().Disconnect( this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished ); + mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished); mScrollOvershootAnimation.Stop(); mScrollOvershootAnimation.Reset(); } mScrollOvershootAnimation = Animation::New(duration); - mScrollOvershootAnimation.FinishedSignal().Connect( this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished ); - mScrollOvershootAnimation.AnimateTo( Property(mOvershootOverlay, mEffectOvershootProperty), amount, TimePeriod(duration) ); + mScrollOvershootAnimation.FinishedSignal().Connect(this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished); + mScrollOvershootAnimation.AnimateTo(Property(mOvershootOverlay, mEffectOvershootProperty), amount, TimePeriod(duration)); mScrollOvershootAnimation.Play(); mAnimationStateFlags = animatingOn ? AnimatingIn : AnimatingOut; } } else { - mOvershootOverlay.SetProperty( mEffectOvershootProperty, amount); + mOvershootOverlay.SetProperty(mEffectOvershootProperty, amount); } } void ScrollOvershootEffectRipple::OnOvershootAnimFinished(Animation& animation) { bool animateOff = false; - if( mAnimationStateFlags & AnimatingOut ) + if(mAnimationStateFlags & AnimatingOut) { // should now be offscreen - mOvershootOverlay.SetProperty( Actor::Property::VISIBLE,false); + mOvershootOverlay.SetProperty(Actor::Property::VISIBLE, false); } - if( (mAnimationStateFlags & AnimateBack) ) + if((mAnimationStateFlags & AnimateBack)) { animateOff = true; } - mScrollOvershootAnimation.FinishedSignal().Disconnect( this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished ); + mScrollOvershootAnimation.FinishedSignal().Disconnect(this, &ScrollOvershootEffectRipple::OnOvershootAnimFinished); mScrollOvershootAnimation.Stop(); mScrollOvershootAnimation.Reset(); mAnimationStateFlags = 0; - if( animateOff ) + if(animateOff) { SetOvershoot(0.0f, true); } } -ScrollOvershootEffectRipplePtr ScrollOvershootEffectRipple::New( bool vertical, Scrollable& scrollable ) +ScrollOvershootEffectRipplePtr ScrollOvershootEffectRipple::New(bool vertical, Scrollable& scrollable) { return new ScrollOvershootEffectRipple(vertical, scrollable); } diff --git a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.cpp b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.cpp index 82bc58f..13d4913 100644 --- a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-effect-impl.cpp @@ -23,13 +23,10 @@ using namespace Dali; namespace Dali { - namespace Toolkit { - namespace Internal { - ScrollViewEffect::ScrollViewEffect() : mScrollViewImpl(NULL) { @@ -41,7 +38,7 @@ ScrollViewEffect::~ScrollViewEffect() void ScrollViewEffect::Attach(Toolkit::ScrollView& scrollView) { - DALI_ASSERT_ALWAYS( (!mScrollViewImpl) && "Already attached to a ScrollView" ); + DALI_ASSERT_ALWAYS((!mScrollViewImpl) && "Already attached to a ScrollView"); mScrollViewImpl = &GetImpl(scrollView); @@ -50,8 +47,8 @@ void ScrollViewEffect::Attach(Toolkit::ScrollView& scrollView) void ScrollViewEffect::Detach(Toolkit::ScrollView& scrollView) { - DALI_ASSERT_ALWAYS( (mScrollViewImpl) && "Already detached from ScrollView" ); - DALI_ASSERT_ALWAYS( (&GetImpl(scrollView) == mScrollViewImpl) && "Effect attached to a different ScrollView"); + DALI_ASSERT_ALWAYS((mScrollViewImpl) && "Already detached from ScrollView"); + DALI_ASSERT_ALWAYS((&GetImpl(scrollView) == mScrollViewImpl) && "Effect attached to a different ScrollView"); OnDetach(scrollView); @@ -62,7 +59,7 @@ Toolkit::ScrollView ScrollViewEffect::GetScrollView() { DALI_ASSERT_ALWAYS(mScrollViewImpl); - return DownCast( mScrollViewImpl->Self() ); + return DownCast(mScrollViewImpl->Self()); } } // namespace Internal diff --git a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.cpp b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.cpp index c0943dc..a318c6d 100644 --- a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-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,31 +19,31 @@ #include // EXTERNAL INCLUDES -#include // for strcmp #include -#include #include -#include -#include -#include -#include -#include -#include #include +#include #include +#include +#include +#include +#include +#include +#include +#include // for strcmp // INTERNAL INCLUDES #include -#include -#include -#include #include #include +#include +#include +#include //#define ENABLED_SCROLL_STATE_LOGGING #ifdef ENABLED_SCROLL_STATE_LOGGING -#define DALI_LOG_SCROLL_STATE(format, ...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ## __VA_ARGS__) +#define DALI_LOG_SCROLL_STATE(format, ...) Dali::Integration::Log::LogMessage(Dali::Integration::Log::DebugInfo, "%s:%d " format "\n", __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #else #define DALI_LOG_SCROLL_STATE(format, ...) #endif @@ -59,27 +59,27 @@ using namespace Dali; namespace { -const float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time. -const float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time. -const float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time. -const float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels +const float DEFAULT_SLOW_SNAP_ANIMATION_DURATION(0.5f); ///< Default Drag-Release animation time. +const float DEFAULT_FAST_SNAP_ANIMATION_DURATION(0.25f); ///< Default Drag-Flick animation time. +const float DEFAULT_SNAP_OVERSHOOT_DURATION(0.5f); ///< Default Overshoot snapping animation time. +const float DEFAULT_MAX_OVERSHOOT(100.0f); ///< Default maximum allowed overshoot in pixels -const float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees) -const float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second) -const float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity) -const float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second) +const float DEFAULT_AXIS_AUTO_LOCK_GRADIENT(0.36f); ///< Default Axis-AutoLock gradient threshold. default is 0.36:1 (20 degrees) +const float DEFAULT_FRICTION_COEFFICIENT(1.0f); ///< Default Friction Co-efficient. (in stage diagonals per second) +const float DEFAULT_FLICK_SPEED_COEFFICIENT(1.0f); ///< Default Flick speed coefficient (multiples input touch velocity) +const float DEFAULT_MAX_FLICK_SPEED(3.0f); ///< Default Maximum flick speed. (in stage diagonals per second) -const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed -const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s -const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms -const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared. -const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking) -const Vector2 DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = Vector2(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each wheel event received. -const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET( 150u ); -const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f; -const float DEFAULT_SCROLL_UPDATE_DISTANCE( 30.0f ); ///< Default distance to travel in pixels for scroll update signal +const Vector2 DEFAULT_MIN_FLICK_DISTANCE(30.0f, 30.0f); ///< minimum distance for pan before flick allowed +const float DEFAULT_MIN_FLICK_SPEED_THRESHOLD(500.0f); ///< Minimum pan speed required for flick in pixels/s +const float FREE_FLICK_SPEED_THRESHOLD = 200.0f; ///< Free-Flick threshold in pixels/ms +const float AUTOLOCK_AXIS_MINIMUM_DISTANCE2 = 100.0f; ///< Auto-lock axis after minimum distance squared. +const float FLICK_ORTHO_ANGLE_RANGE = 75.0f; ///< degrees. (if >45, then supports diagonal flicking) +const Vector2 DEFAULT_WHEEL_SCROLL_DISTANCE_STEP_PROPORTION = Vector2(0.17f, 0.1f); ///< The step of horizontal scroll distance in the proportion of stage size for each wheel event received. +const unsigned long MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET(150u); +const float TOUCH_DOWN_TIMER_INTERVAL = 100.0f; +const float DEFAULT_SCROLL_UPDATE_DISTANCE(30.0f); ///< Default distance to travel in pixels for scroll update signal -const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME( "internalMaxPosition" ); +const std::string INTERNAL_MAX_POSITION_PROPERTY_NAME("internalMaxPosition"); // Helpers //////////////////////////////////////////////////////////////////////////////////////// @@ -104,11 +104,11 @@ float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::Di { if(bias == Dali::Toolkit::DIRECTION_BIAS_NONE) { - return ShortestDistanceInDomain( a, b, start, end ); + return ShortestDistanceInDomain(a, b, start, end); } // (a-start + end-b) - float size = end-start; - float vect = b-a; + float size = end - start; + float vect = b - a; if(vect > 0) { @@ -119,8 +119,8 @@ float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::Di } else { - float aRight = a+size; - return b-aRight; + float aRight = a + size; + return b - aRight; } } else @@ -132,8 +132,8 @@ float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::Di } else { - float aLeft = a-size; - return b-aLeft; + float aLeft = a - size; + return b - aLeft; } } } @@ -145,11 +145,11 @@ float VectorInDomain(float a, float b, float start, float end, Dali::Toolkit::Di * @param anchor The Anchor point of interest. * @return The position of the Anchor */ -Vector3 GetPositionOfAnchor(Actor &actor, const Vector3 &anchor) +Vector3 GetPositionOfAnchor(Actor& actor, const Vector3& anchor) { - Vector3 childPosition = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION ); - Vector3 childAnchor = - actor.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) + anchor; - Vector3 childSize = actor.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Vector3 childPosition = actor.GetCurrentProperty(Actor::Property::POSITION); + Vector3 childAnchor = -actor.GetCurrentProperty(Actor::Property::ANCHOR_POINT) + anchor; + Vector3 childSize = actor.GetCurrentProperty(Actor::Property::SIZE); return childPosition + childAnchor * childSize; } @@ -186,12 +186,12 @@ float ConstantDecelerationAlphaFunction(float progress) * scroll domain. This is a value from 0.0f to 1.0f in each * scroll position axis. */ -void InternalRelativePositionConstraint( Vector2& relativePosition, const PropertyInputContainer& inputs) +void InternalRelativePositionConstraint(Vector2& relativePosition, const PropertyInputContainer& inputs) { - Vector2 position = -inputs[0]->GetVector2(); - const Vector2& min = inputs[1]->GetVector2(); - const Vector2& max = inputs[2]->GetVector2(); - const Vector3& size = inputs[3]->GetVector3(); + Vector2 position = -inputs[0]->GetVector2(); + const Vector2& min = inputs[1]->GetVector2(); + const Vector2& max = inputs[2]->GetVector2(); + const Vector3& size = inputs[3]->GetVector3(); position.x = WrapInDomain(position.x, min.x, max.x); position.y = WrapInDomain(position.y, min.y, max.y); @@ -206,10 +206,10 @@ void InternalRelativePositionConstraint( Vector2& relativePosition, const Proper * Internal scroll domain Constraint * Generates the scroll domain of the scroll view. */ -void InternalScrollDomainConstraint( Vector2& scrollDomain, const PropertyInputContainer& inputs) +void InternalScrollDomainConstraint(Vector2& scrollDomain, const PropertyInputContainer& inputs) { - const Vector2& min = inputs[0]->GetVector2(); - const Vector2& max = inputs[1]->GetVector2(); + const Vector2& min = inputs[0]->GetVector2(); + const Vector2& max = inputs[1]->GetVector2(); const Vector3& size = inputs[2]->GetVector3(); scrollDomain = (max - min) - size.GetVectorXY(); @@ -219,9 +219,9 @@ void InternalScrollDomainConstraint( Vector2& scrollDomain, const PropertyInputC * Internal maximum scroll position Constraint * Generates the maximum scroll position of the scroll view. */ -void InternalPrePositionMaxConstraint( Vector2& scrollMax, const PropertyInputContainer& inputs) +void InternalPrePositionMaxConstraint(Vector2& scrollMax, const PropertyInputContainer& inputs) { - const Vector2& max = inputs[0]->GetVector2(); + const Vector2& max = inputs[0]->GetVector2(); const Vector3& size = inputs[1]->GetVector3(); scrollMax = max - size.GetVectorXY(); @@ -231,53 +231,49 @@ void InternalPrePositionMaxConstraint( Vector2& scrollMax, const PropertyInputCo namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::ScrollView::New(); } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ScrollView, Toolkit::Scrollable, Create ) - -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP ) -DALI_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollMode", MAP, SCROLL_MODE ) - -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL,0) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL,1) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "wrap", BOOLEAN, WRAP) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "panning", BOOLEAN, PANNING) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION) - -DALI_SIGNAL_REGISTRATION( Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ScrollView, Toolkit::Scrollable, Create) + +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wrapEnabled", BOOLEAN, WRAP_ENABLED) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "panningEnabled", BOOLEAN, PANNING_ENABLED) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "axisAutoLockEnabled", BOOLEAN, AXIS_AUTO_LOCK_ENABLED) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wheelScrollDistanceStep", VECTOR2, WHEEL_SCROLL_DISTANCE_STEP) +DALI_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollMode", MAP, SCROLL_MODE) + +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPosition", VECTOR2, SCROLL_POSITION) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPrePosition", VECTOR2, SCROLL_PRE_POSITION) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionX", SCROLL_PRE_POSITION_X, SCROLL_PRE_POSITION, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionY", SCROLL_PRE_POSITION_Y, SCROLL_PRE_POSITION, 1) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMax", VECTOR2, SCROLL_PRE_POSITION_MAX) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMaxX", SCROLL_PRE_POSITION_MAX_X, SCROLL_PRE_POSITION_MAX, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollPrePositionMaxY", SCROLL_PRE_POSITION_MAX_Y, SCROLL_PRE_POSITION_MAX, 1) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "overshootX", FLOAT, OVERSHOOT_X) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "overshootY", FLOAT, OVERSHOOT_Y) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollFinal", VECTOR2, SCROLL_FINAL) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollFinalX", SCROLL_FINAL_X, SCROLL_FINAL, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollFinalY", SCROLL_FINAL_Y, SCROLL_FINAL, 1) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "wrap", BOOLEAN, WRAP) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "panning", BOOLEAN, PANNING) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrolling", BOOLEAN, SCROLLING) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollDomainSize", VECTOR2, SCROLL_DOMAIN_SIZE) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollDomainSizeX", SCROLL_DOMAIN_SIZE_X, SCROLL_DOMAIN_SIZE, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, ScrollView, "scrollDomainSizeY", SCROLL_DOMAIN_SIZE_Y, SCROLL_DOMAIN_SIZE, 1) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollDomainOffset", VECTOR2, SCROLL_DOMAIN_OFFSET) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "scrollPositionDelta", VECTOR2, SCROLL_POSITION_DELTA) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, ScrollView, "startPagePosition", VECTOR3, START_PAGE_POSITION) + +DALI_SIGNAL_REGISTRATION(Toolkit, ScrollView, "valueChanged", SIGNAL_SNAP_STARTED) DALI_TYPE_REGISTRATION_END() @@ -293,7 +289,7 @@ DALI_TYPE_REGISTRATION_END() ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis currentLockAxis, float lockGradient) { if(panDelta.LengthSquared() > AUTOLOCK_AXIS_MINIMUM_DISTANCE2 && - currentLockAxis == ScrollView::LockPossible) + currentLockAxis == ScrollView::LockPossible) { float dx = fabsf(panDelta.x); float dy = fabsf(panDelta.y); @@ -324,35 +320,36 @@ ScrollView::LockAxis GetLockAxis(const Vector2& panDelta, ScrollView::LockAxis c */ struct InternalPrePositionConstraint { - InternalPrePositionConstraint( const Vector2& initialPanPosition, - const Vector2& initialPanMask, - bool axisAutoLock, - float axisAutoLockGradient, - ScrollView::LockAxis initialLockAxis, - const Vector2& maxOvershoot, - const RulerPtr& rulerX, const RulerPtr& rulerY ) - : mLocalStart( initialPanPosition ), - mInitialPanMask( initialPanMask ), - mMaxOvershoot( maxOvershoot ), - mAxisAutoLockGradient( axisAutoLockGradient ), - mLockAxis( initialLockAxis ), - mAxisAutoLock( axisAutoLock ), - mWasPanning( false ) + InternalPrePositionConstraint(const Vector2& initialPanPosition, + const Vector2& initialPanMask, + bool axisAutoLock, + float axisAutoLockGradient, + ScrollView::LockAxis initialLockAxis, + const Vector2& maxOvershoot, + const RulerPtr& rulerX, + const RulerPtr& rulerY) + : mLocalStart(initialPanPosition), + mInitialPanMask(initialPanMask), + mMaxOvershoot(maxOvershoot), + mAxisAutoLockGradient(axisAutoLockGradient), + mLockAxis(initialLockAxis), + mAxisAutoLock(axisAutoLock), + mWasPanning(false) { const RulerDomain& rulerDomainX = rulerX->GetDomain(); const RulerDomain& rulerDomainY = rulerY->GetDomain(); - mDomainMin = Vector2( rulerDomainX.min, -rulerDomainY.min ); - mDomainMax = Vector2( -rulerDomainX.max, -rulerDomainY.max ); - mClampX = rulerDomainX.enabled; - mClampY = rulerDomainY.enabled; - mFixedRulerX = rulerX->GetType() == Ruler::FIXED; - mFixedRulerY = rulerY->GetType() == Ruler::FIXED; + mDomainMin = Vector2(rulerDomainX.min, -rulerDomainY.min); + mDomainMax = Vector2(-rulerDomainX.max, -rulerDomainY.max); + mClampX = rulerDomainX.enabled; + mClampY = rulerDomainY.enabled; + mFixedRulerX = rulerX->GetType() == Ruler::FIXED; + mFixedRulerY = rulerY->GetType() == Ruler::FIXED; } - void operator()( Vector2& scrollPostPosition, const PropertyInputContainer& inputs ) + void operator()(Vector2& scrollPostPosition, const PropertyInputContainer& inputs) { const Vector2& panPosition = inputs[0]->GetVector2(); - const bool& inGesture = inputs[1]->GetBoolean(); + const bool& inGesture = inputs[1]->GetBoolean(); // First check if we are within a gesture. // The ScrollView may have received a start gesture from ::OnPan() @@ -360,30 +357,30 @@ struct InternalPrePositionConstraint // This gesture must then be rejected as the value will be "old". // Typically the last value from the end of the last gesture. // If we are rejecting the gesture, we simply don't modify the constraint target. - if( inGesture ) + if(inGesture) { - if( !mWasPanning ) + if(!mWasPanning) { - mPrePosition = scrollPostPosition; - mStartPosition = mPrePosition; + mPrePosition = scrollPostPosition; + mStartPosition = mPrePosition; mCurrentPanMask = mInitialPanMask; - mWasPanning = true; + mWasPanning = true; } // Calculate Deltas... const Vector2& currentPosition = panPosition; - Vector2 panDelta( currentPosition - mLocalStart ); + Vector2 panDelta(currentPosition - mLocalStart); // Axis Auto Lock - locks the panning to the horizontal or vertical axis if the pan // appears mostly horizontal or mostly vertical respectively... - if( mAxisAutoLock ) + if(mAxisAutoLock) { - mLockAxis = GetLockAxis( panDelta, mLockAxis, mAxisAutoLockGradient ); - if( mLockAxis == ScrollView::LockVertical ) + mLockAxis = GetLockAxis(panDelta, mLockAxis, mAxisAutoLockGradient); + if(mLockAxis == ScrollView::LockVertical) { mCurrentPanMask.y = 0.0f; } - else if( mLockAxis == ScrollView::LockHorizontal ) + else if(mLockAxis == ScrollView::LockHorizontal) { mCurrentPanMask.x = 0.0f; } @@ -398,31 +395,29 @@ struct InternalPrePositionConstraint // if no wrapping then clamp preposition to maximum overshoot amount const Vector3& size = inputs[2]->GetVector3(); - if( mClampX ) + if(mClampX) { - float newXPosition = Clamp( scrollPostPosition.x, ( mDomainMax.x + size.x ) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x ); - if( (newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1) - || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1) ) + float newXPosition = Clamp(scrollPostPosition.x, (mDomainMax.x + size.x) - mMaxOvershoot.x, mDomainMin.x + mMaxOvershoot.x); + if((newXPosition < scrollPostPosition.x - Math::MACHINE_EPSILON_1) || (newXPosition > scrollPostPosition.x + Math::MACHINE_EPSILON_1)) { mPrePosition.x = newXPosition; - mLocalStart.x = panPosition.x; + mLocalStart.x = panPosition.x; } scrollPostPosition.x = newXPosition; } - if( mClampY ) + if(mClampY) { - float newYPosition = Clamp( scrollPostPosition.y, ( mDomainMax.y + size.y ) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y ); - if( ( newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1 ) - || ( newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1 ) ) + float newYPosition = Clamp(scrollPostPosition.y, (mDomainMax.y + size.y) - mMaxOvershoot.y, mDomainMin.y + mMaxOvershoot.y); + if((newYPosition < scrollPostPosition.y - Math::MACHINE_EPSILON_1) || (newYPosition > scrollPostPosition.y + Math::MACHINE_EPSILON_1)) { mPrePosition.y = newYPosition; - mLocalStart.y = panPosition.y; + mLocalStart.y = panPosition.y; } scrollPostPosition.y = newYPosition; } // If we are using a fixed ruler in a particular axis, limit the maximum pages scrolled on that axis. - if( mFixedRulerX || mFixedRulerY ) + if(mFixedRulerX || mFixedRulerY) { // Here we limit the maximum amount that can be moved from the starting position of the gesture to one page. // We do this only if we have a fixed ruler (on that axis) and the mode is enabled. @@ -430,17 +425,17 @@ struct InternalPrePositionConstraint // Note: A further 1.0f is subtracted to handle a compensation that happens later within the flick handling code in SnapWithVelocity(). // When a flick is completed, an adjustment of 1.0f is sometimes made to allow for the scenario where: // A flick finishes before the update thread has advanced the scroll position past the previous snap point. - Vector2 viewPageSizeLimit( size.x - ( 1.0f + 1.0f ), size.y - ( 1.0f - 1.0f ) ); - Vector2 minPosition( mStartPosition.x - viewPageSizeLimit.x, mStartPosition.y - viewPageSizeLimit.y ); - Vector2 maxPosition( mStartPosition.x + viewPageSizeLimit.x, mStartPosition.y + viewPageSizeLimit.y ); + Vector2 viewPageSizeLimit(size.x - (1.0f + 1.0f), size.y - (1.0f - 1.0f)); + Vector2 minPosition(mStartPosition.x - viewPageSizeLimit.x, mStartPosition.y - viewPageSizeLimit.y); + Vector2 maxPosition(mStartPosition.x + viewPageSizeLimit.x, mStartPosition.y + viewPageSizeLimit.y); - if( mFixedRulerX ) + if(mFixedRulerX) { - scrollPostPosition.x = Clamp( scrollPostPosition.x, minPosition.x, maxPosition.x ); + scrollPostPosition.x = Clamp(scrollPostPosition.x, minPosition.x, maxPosition.x); } - if( mFixedRulerY ) + if(mFixedRulerY) { - scrollPostPosition.y = Clamp( scrollPostPosition.y, minPosition.y, maxPosition.y ); + scrollPostPosition.y = Clamp(scrollPostPosition.y, minPosition.y, maxPosition.y); } } } @@ -448,22 +443,22 @@ struct InternalPrePositionConstraint Vector2 mPrePosition; Vector2 mLocalStart; - Vector2 mStartPosition; ///< The start position of the gesture - used to limit scroll amount (not modified by clamping). - Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings). - Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode. + Vector2 mStartPosition; ///< The start position of the gesture - used to limit scroll amount (not modified by clamping). + Vector2 mInitialPanMask; ///< Initial pan mask (based on ruler settings). + Vector2 mCurrentPanMask; ///< Current pan mask that can be altered by axis lock mode. Vector2 mDomainMin; Vector2 mDomainMax; Vector2 mMaxOvershoot; - float mAxisAutoLockGradient; ///< Set by ScrollView + float mAxisAutoLockGradient; ///< Set by ScrollView ScrollView::LockAxis mLockAxis; - bool mAxisAutoLock:1; ///< Set by ScrollView - bool mWasPanning:1; - bool mClampX:1; - bool mClampY:1; - bool mFixedRulerX:1; - bool mFixedRulerY:1; + bool mAxisAutoLock : 1; ///< Set by ScrollView + bool mWasPanning : 1; + bool mClampX : 1; + bool mClampY : 1; + bool mFixedRulerX : 1; + bool mFixedRulerY : 1; }; /** @@ -476,22 +471,22 @@ struct InternalPrePositionConstraint struct InternalPositionConstraint { InternalPositionConstraint(const RulerDomain& domainX, const RulerDomain& domainY, bool wrap) - : mDomainMin( -domainX.min, -domainY.min ), - mDomainMax( -domainX.max, -domainY.max ), - mClampX( domainX.enabled ), - mClampY( domainY.enabled ), - mWrap( wrap ) + : mDomainMin(-domainX.min, -domainY.min), + mDomainMax(-domainX.max, -domainY.max), + mClampX(domainX.enabled), + mClampY(domainY.enabled), + mWrap(wrap) { } - void operator()( Vector2& position, const PropertyInputContainer& inputs ) + void operator()(Vector2& position, const PropertyInputContainer& inputs) { - position = inputs[0]->GetVector2(); + position = inputs[0]->GetVector2(); const Vector2& size = inputs[3]->GetVector3().GetVectorXY(); - const Vector2& min = inputs[1]->GetVector2(); - const Vector2& max = inputs[2]->GetVector2(); + const Vector2& min = inputs[1]->GetVector2(); + const Vector2& max = inputs[2]->GetVector2(); - if( mWrap ) + if(mWrap) { position.x = -WrapInDomain(-position.x, min.x, max.x); position.y = -WrapInDomain(-position.y, min.y, max.y); @@ -499,17 +494,16 @@ struct InternalPositionConstraint else { // clamp post position to domain - position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x ) : position.x; - position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y ) : position.y; + position.x = mClampX ? Clamp(position.x, mDomainMax.x + size.x, mDomainMin.x) : position.x; + position.y = mClampY ? Clamp(position.y, mDomainMax.y + size.y, mDomainMin.y) : position.y; } } Vector2 mDomainMin; Vector2 mDomainMax; - bool mClampX; - bool mClampY; - bool mWrap; - + bool mClampX; + bool mClampY; + bool mWrap; }; /** @@ -518,16 +512,19 @@ struct InternalPositionConstraint */ struct OvershootXConstraint { - OvershootXConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {} + OvershootXConstraint(float maxOvershoot) + : mMaxOvershoot(maxOvershoot) + { + } - void operator()( float& current, const PropertyInputContainer& inputs ) + void operator()(float& current, const PropertyInputContainer& inputs) { - if( inputs[2]->GetBoolean() ) + if(inputs[2]->GetBoolean()) { - const Vector2& scrollPrePosition = inputs[0]->GetVector2(); + const Vector2& scrollPrePosition = inputs[0]->GetVector2(); const Vector2& scrollPostPosition = inputs[1]->GetVector2(); - float newOvershoot = scrollPrePosition.x - scrollPostPosition.x; - current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot; + float newOvershoot = scrollPrePosition.x - scrollPostPosition.x; + current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot; } else { @@ -544,16 +541,19 @@ struct OvershootXConstraint */ struct OvershootYConstraint { - OvershootYConstraint(float maxOvershoot) : mMaxOvershoot(maxOvershoot) {} + OvershootYConstraint(float maxOvershoot) + : mMaxOvershoot(maxOvershoot) + { + } - void operator()( float& current, const PropertyInputContainer& inputs ) + void operator()(float& current, const PropertyInputContainer& inputs) { - if( inputs[2]->GetBoolean() ) + if(inputs[2]->GetBoolean()) { - const Vector2& scrollPrePosition = inputs[0]->GetVector2(); + const Vector2& scrollPrePosition = inputs[0]->GetVector2(); const Vector2& scrollPostPosition = inputs[1]->GetVector2(); - float newOvershoot = scrollPrePosition.y - scrollPostPosition.y; - current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot; + float newOvershoot = scrollPrePosition.y - scrollPostPosition.y; + current = (newOvershoot > 0.0f ? std::min(newOvershoot, mMaxOvershoot) : std::max(newOvershoot, -mMaxOvershoot)) / mMaxOvershoot; } else { @@ -569,10 +569,10 @@ struct OvershootYConstraint * * Generates position-delta property based on scroll-position + scroll-offset properties. */ -void InternalPositionDeltaConstraint( Vector2& current, const PropertyInputContainer& inputs ) +void InternalPositionDeltaConstraint(Vector2& current, const PropertyInputContainer& inputs) { const Vector2& scrollPosition = inputs[0]->GetVector2(); - const Vector2& scrollOffset = inputs[1]->GetVector2(); + const Vector2& scrollOffset = inputs[1]->GetVector2(); current = scrollPosition + scrollOffset; } @@ -593,12 +593,12 @@ struct InternalFinalConstraint { } - void operator()( Vector2& current, const PropertyInputContainer& inputs ) + void operator()(Vector2& current, const PropertyInputContainer& inputs) { const float& overshootx = inputs[1]->GetFloat(); const float& overshooty = inputs[2]->GetFloat(); - Vector2 offset( mFunctionX(overshootx), - mFunctionY(overshooty) ); + Vector2 offset(mFunctionX(overshootx), + mFunctionY(overshooty)); current = inputs[0]->GetVector2() - offset; } @@ -607,8 +607,7 @@ struct InternalFinalConstraint AlphaFunctionPrototype mFunctionY; }; -} - +} // namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // ScrollView @@ -630,7 +629,7 @@ Dali::Toolkit::ScrollView ScrollView::New() } ScrollView::ScrollView() -: ScrollBase( ControlBehaviour( DISABLE_STYLE_CHANGE_SIGNALS ) ), // Enable size negotiation +: ScrollBase(ControlBehaviour(DISABLE_STYLE_CHANGE_SIGNALS)), // Enable size negotiation mTouchDownTime(0u), mGestureStackDepth(0), mScrollStateFlags(0), @@ -678,9 +677,9 @@ void ScrollView::OnInitialize() mInternalActor = Actor::New(); self.Add(mInternalActor); - mInternalActor.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mInternalActor.SetProperty( Actor::Property::ANCHOR_POINT,AnchorPoint::CENTER); - mInternalActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mInternalActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mInternalActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mInternalActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); mAlterChild = true; @@ -690,14 +689,14 @@ void ScrollView::OnInitialize() mGestureStackDepth = 0; - self.TouchedSignal().Connect( this, &ScrollView::OnTouch ); - EnableGestureDetection( GestureType::Value( GestureType::PAN ) ); + self.TouchedSignal().Connect(this, &ScrollView::OnTouch); + EnableGestureDetection(GestureType::Value(GestureType::PAN)); // By default we'll allow the user to freely drag the scroll view, // while disabling the other rulers. RulerPtr ruler = new DefaultRuler(); - mRulerX = ruler; - mRulerY = ruler; + mRulerX = ruler; + mRulerY = ruler; self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, mCanScrollVertical); self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, mCanScrollHorizontal); @@ -706,22 +705,22 @@ void ScrollView::OnInitialize() SetInternalConstraints(); // Connect wheel event - self.WheelEventSignal().Connect( this, &ScrollView::OnWheelEvent ); + self.WheelEventSignal().Connect(this, &ScrollView::OnWheelEvent); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::SCROLL_PANE ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE)); + }); } -void ScrollView::OnSceneConnection( int depth ) +void ScrollView::OnSceneConnection(int depth) { DALI_LOG_SCROLL_STATE("[0x%X]", this); - if ( mSensitive ) + if(mSensitive) { - SetScrollSensitive( false ); - SetScrollSensitive( true ); + SetScrollSensitive(false); + SetScrollSensitive(true); } if(IsOvershootEnabled()) @@ -730,7 +729,7 @@ void ScrollView::OnSceneConnection( int depth ) EnableScrollOvershoot(true); } - ScrollBase::OnSceneConnection( depth ); + ScrollBase::OnSceneConnection(depth); } void ScrollView::OnSceneDisconnection() @@ -793,9 +792,9 @@ void ScrollView::ApplyEffect(Toolkit::ScrollViewEffect effect) // Assertion check to ensure effect doesn't already exist in this scrollview bool effectAlreadyExistsInScrollView(false); - for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter) + for(ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter) { - if(*iter==effect) + if(*iter == effect) { effectAlreadyExistsInScrollView = true; break; @@ -817,9 +816,9 @@ void ScrollView::RemoveEffect(Toolkit::ScrollViewEffect effect) // remove effect from effects list bool effectExistedInScrollView(false); - for (ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter) + for(ScrollViewEffectIter iter = mEffects.begin(); iter != mEffects.end(); ++iter) { - if(*iter==effect) + if(*iter == effect) { mEffects.erase(iter); effectExistedInScrollView = true; @@ -838,7 +837,7 @@ void ScrollView::RemoveAllEffects() { Dali::Toolkit::ScrollView self = Dali::Toolkit::ScrollView::DownCast(Self()); - for (ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter) + for(ScrollViewEffectIter effectIter = mEffects.begin(); effectIter != mEffects.end(); ++effectIter) { Toolkit::ScrollViewEffect effect = *effectIter; @@ -887,104 +886,98 @@ void ScrollView::SetRulerY(RulerPtr ruler) void ScrollView::UpdatePropertyDomain() { - Actor self = Self(); - Vector3 size = self.GetTargetSize(); - Vector2 min = mMinScroll; - Vector2 max = mMaxScroll; - bool scrollPositionChanged = false; - bool domainChanged = false; + Actor self = Self(); + Vector3 size = self.GetTargetSize(); + Vector2 min = mMinScroll; + Vector2 max = mMaxScroll; + bool scrollPositionChanged = false; + bool domainChanged = false; - bool canScrollVertical = false; + bool canScrollVertical = false; bool canScrollHorizontal = false; UpdateLocalScrollProperties(); if(mRulerX->IsEnabled()) { const Toolkit::RulerDomain& rulerDomain = mRulerX->GetDomain(); - if( fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100 - || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100 ) + if(fabsf(min.x - rulerDomain.min) > Math::MACHINE_EPSILON_100 || fabsf(max.x - rulerDomain.max) > Math::MACHINE_EPSILON_100) { domainChanged = true; - min.x = rulerDomain.min; - max.x = rulerDomain.max; + min.x = rulerDomain.min; + max.x = rulerDomain.max; // make sure new scroll value is within new domain - if( mScrollPrePosition.x < min.x - || mScrollPrePosition.x > max.x ) + if(mScrollPrePosition.x < min.x || mScrollPrePosition.x > max.x) { scrollPositionChanged = true; - mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x); + mScrollPrePosition.x = Clamp(mScrollPrePosition.x, -(max.x - size.x), -min.x); } } - if( (fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100 ) + if((fabsf(rulerDomain.max - rulerDomain.min) - size.x) > Math::MACHINE_EPSILON_100) { canScrollHorizontal = true; } } - else if( fabs(min.x) > Math::MACHINE_EPSILON_100 - || fabs(max.x) > Math::MACHINE_EPSILON_100 ) + else if(fabs(min.x) > Math::MACHINE_EPSILON_100 || fabs(max.x) > Math::MACHINE_EPSILON_100) { // need to reset to 0 - domainChanged = true; - min.x = 0.0f; - max.x = 0.0f; + domainChanged = true; + min.x = 0.0f; + max.x = 0.0f; canScrollHorizontal = false; } if(mRulerY->IsEnabled()) { const Toolkit::RulerDomain& rulerDomain = mRulerY->GetDomain(); - if( fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100 - || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100 ) + if(fabsf(min.y - rulerDomain.min) > Math::MACHINE_EPSILON_100 || fabsf(max.y - rulerDomain.max) > Math::MACHINE_EPSILON_100) { domainChanged = true; - min.y = rulerDomain.min; - max.y = rulerDomain.max; + min.y = rulerDomain.min; + max.y = rulerDomain.max; // make sure new scroll value is within new domain - if( mScrollPrePosition.y < min.y - || mScrollPrePosition.y > max.y ) + if(mScrollPrePosition.y < min.y || mScrollPrePosition.y > max.y) { scrollPositionChanged = true; - mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y); + mScrollPrePosition.y = Clamp(mScrollPrePosition.y, -(max.y - size.y), -min.y); } } - if( (fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100 ) + if((fabsf(rulerDomain.max - rulerDomain.min) - size.y) > Math::MACHINE_EPSILON_100) { canScrollVertical = true; } } - else if( fabs(min.y) > Math::MACHINE_EPSILON_100 - || fabs(max.y) > Math::MACHINE_EPSILON_100 ) + else if(fabs(min.y) > Math::MACHINE_EPSILON_100 || fabs(max.y) > Math::MACHINE_EPSILON_100) { // need to reset to 0 - domainChanged = true; - min.y = 0.0f; - max.y = 0.0f; + domainChanged = true; + min.y = 0.0f; + max.y = 0.0f; canScrollVertical = false; } // avoid setting properties if possible, otherwise this will cause an entire update as well as triggering constraints using each property we update - if( mCanScrollVertical != canScrollVertical ) + if(mCanScrollVertical != canScrollVertical) { mCanScrollVertical = canScrollVertical; self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL, canScrollVertical); } - if( mCanScrollHorizontal != canScrollHorizontal ) + if(mCanScrollHorizontal != canScrollHorizontal) { mCanScrollHorizontal = canScrollHorizontal; self.SetProperty(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL, canScrollHorizontal); } - if( scrollPositionChanged ) + if(scrollPositionChanged) { - DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y ); + DALI_LOG_SCROLL_STATE("[0x%X] Domain Changed, setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y); self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition); } - if( domainChanged ) + if(domainChanged) { mMinScroll = min; mMaxScroll = max; - self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll ); - self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll ); + self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN, mMinScroll); + self.SetProperty(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX, mMaxScroll); } } @@ -995,8 +988,8 @@ bool ScrollView::GetScrollSensitive() void ScrollView::SetScrollSensitive(bool sensitive) { - Actor self = Self(); - PanGestureDetector panGesture( GetPanGestureDetector() ); + Actor self = Self(); + PanGestureDetector panGesture(GetPanGestureDetector()); DALI_LOG_SCROLL_STATE("[0x%X] sensitive: before:[%d] setting[%d]", this, int(mSensitive), int(sensitive)); @@ -1010,10 +1003,10 @@ void ScrollView::SetScrollSensitive(bool sensitive) DALI_LOG_SCROLL_STATE("[0x%X] BEFORE: panning:[%d]", this, int(mPanning)); // while the scroll view is panning, the state needs to be reset. - if ( mPanning ) + if(mPanning) { - PanGesture cancelGesture = DevelPanGesture::New( GestureState::CANCELLED ); - OnPan( cancelGesture ); + PanGesture cancelGesture = DevelPanGesture::New(GestureState::CANCELLED); + OnPan(cancelGesture); } panGesture.Detach(self); @@ -1026,9 +1019,9 @@ void ScrollView::SetScrollSensitive(bool sensitive) void ScrollView::SetMaxOvershoot(float overshootX, float overshootY) { - mMaxOvershoot.x = overshootX; - mMaxOvershoot.y = overshootY; - mUserMaxOvershoot = mMaxOvershoot; + mMaxOvershoot.x = overshootX; + mMaxOvershoot.y = overshootY; + mUserMaxOvershoot = mMaxOvershoot; mDefaultMaxOvershoot = false; UpdateMainInternalConstraint(); } @@ -1103,7 +1096,7 @@ float ScrollView::GetAxisAutoLockGradient() const void ScrollView::SetAxisAutoLockGradient(float gradient) { - DALI_ASSERT_DEBUG( gradient >= 0.0f && gradient <= 1.0f ); + DALI_ASSERT_DEBUG(gradient >= 0.0f && gradient <= 1.0f); mAxisAutoLockGradient = gradient; UpdateMainInternalConstraint(); } @@ -1115,7 +1108,7 @@ float ScrollView::GetFrictionCoefficient() const void ScrollView::SetFrictionCoefficient(float friction) { - DALI_ASSERT_DEBUG( friction > 0.0f ); + DALI_ASSERT_DEBUG(friction > 0.0f); mFrictionCoefficient = friction; } @@ -1134,7 +1127,7 @@ Vector2 ScrollView::GetMinimumDistanceForFlick() const return mMinFlickDistance; } -void ScrollView::SetMinimumDistanceForFlick( const Vector2& distance ) +void ScrollView::SetMinimumDistanceForFlick(const Vector2& distance) { mMinFlickDistance = distance; } @@ -1144,7 +1137,7 @@ float ScrollView::GetMinimumSpeedForFlick() const return mFlickSpeedThreshold; } -void ScrollView::SetMinimumSpeedForFlick( float speed ) +void ScrollView::SetMinimumSpeedForFlick(float speed) { mFlickSpeedThreshold = speed; } @@ -1174,14 +1167,14 @@ unsigned int ScrollView::GetCurrentPage() const // in case animation is currently taking place. Vector2 position = GetPropertyPosition(); - Actor self = Self(); - unsigned int page = 0; + Actor self = Self(); + unsigned int page = 0; unsigned int pagesPerVolume = 1; - unsigned int volume = 0; + unsigned int volume = 0; // if rulerX is enabled, then get page count (columns) - page = mRulerX->GetPageFromPosition(-position.x, mWrapMode); - volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode); + page = mRulerX->GetPageFromPosition(-position.x, mWrapMode); + volume = mRulerY->GetPageFromPosition(-position.y, mWrapMode); pagesPerVolume = mRulerX->GetTotalPages(); return volume * pagesPerVolume + page; @@ -1193,45 +1186,50 @@ Vector2 ScrollView::GetCurrentScrollPosition() const } void ScrollView::TransformTo(const Vector2& position, - DirectionBias horizontalBias, DirectionBias verticalBias) + DirectionBias horizontalBias, + DirectionBias verticalBias) { TransformTo(position, mSnapDuration, mSnapAlphaFunction, horizontalBias, verticalBias); } -void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha, - DirectionBias horizontalBias, DirectionBias verticalBias) +void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias) { // If this is called while the timer is running, then cancel it StopTouchDownTimer(); - Actor self( Self() ); + Actor self(Self()); // Guard against destruction during signal emission // Note that Emit() methods are called indirectly e.g. from within ScrollView::AnimateTo() - Toolkit::ScrollView handle( GetOwner() ); + Toolkit::ScrollView handle(GetOwner()); DALI_LOG_SCROLL_STATE("[0x%X] pos[%.2f,%.2f], duration[%.2f] bias[%d, %d]", - this, position.x, position.y, duration, int(horizontalBias), int(verticalBias)); + this, + position.x, + position.y, + duration, + int(horizontalBias), + int(verticalBias)); Vector2 currentScrollPosition = GetCurrentScrollPosition(); - self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition) ); + self.SetProperty(Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(currentScrollPosition)); - if( mScrolling ) // are we interrupting a current scroll? + if(mScrolling) // are we interrupting a current scroll? { // set mScrolling to false, in case user has code that interrogates mScrolling Getter() in complete. mScrolling = false; DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y); - mScrollCompletedSignal.Emit( currentScrollPosition ); + mScrollCompletedSignal.Emit(currentScrollPosition); } - if( mPanning ) // are we interrupting a current pan? + if(mPanning) // are we interrupting a current pan? { - DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this ); - mPanning = false; + DALI_LOG_SCROLL_STATE("[0x%X] Interrupting Pan, set to false", this); + mPanning = false; mGestureStackDepth = 0; - self.SetProperty( Toolkit::ScrollView::Property::PANNING, false ); + self.SetProperty(Toolkit::ScrollView::Property::PANNING, false); - if( mScrollMainInternalPrePositionConstraint ) + if(mScrollMainInternalPrePositionConstraint) { mScrollMainInternalPrePositionConstraint.Remove(); } @@ -1241,7 +1239,7 @@ void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunct mScrolling = true; DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 1 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y); - mScrollStartedSignal.Emit( currentScrollPosition ); + mScrollStartedSignal.Emit(currentScrollPosition); bool animating = AnimateTo(-position, Vector2::ONE * duration, alpha, @@ -1258,21 +1256,21 @@ void ScrollView::TransformTo(const Vector2& position, float duration, AlphaFunct // If we have no duration, then in the next update frame, we will be at the position specified as we just set. // In this scenario, we cannot return the currentScrollPosition as this is out-of-date and should instead return the requested final position - Vector2 completedPosition( currentScrollPosition ); - if( duration <= Math::MACHINE_EPSILON_10 ) + Vector2 completedPosition(currentScrollPosition); + if(duration <= Math::MACHINE_EPSILON_10) { completedPosition = position; } DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 2 [%.2f, %.2f]", this, completedPosition.x, completedPosition.y); SetScrollUpdateNotification(false); - mScrollCompletedSignal.Emit( completedPosition ); + mScrollCompletedSignal.Emit(completedPosition); } } void ScrollView::ScrollTo(const Vector2& position) { - ScrollTo(position, mSnapDuration ); + ScrollTo(position, mSnapDuration); } void ScrollView::ScrollTo(const Vector2& position, float duration) @@ -1285,14 +1283,12 @@ void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction ScrollTo(position, duration, alpha, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE); } -void ScrollView::ScrollTo(const Vector2& position, float duration, - DirectionBias horizontalBias, DirectionBias verticalBias) +void ScrollView::ScrollTo(const Vector2& position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias) { ScrollTo(position, duration, mSnapAlphaFunction, horizontalBias, verticalBias); } -void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, - DirectionBias horizontalBias, DirectionBias verticalBias) +void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias) { DALI_LOG_SCROLL_STATE("[0x%X] position[%.2f, %.2f] duration[%.2f], bias[%d, %d]", this, position.x, position.y, duration, int(horizontalBias), int(verticalBias)); TransformTo(position, duration, alpha, horizontalBias, verticalBias); @@ -1305,7 +1301,7 @@ void ScrollView::ScrollTo(unsigned int page) void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias) { - Vector2 position; + Vector2 position; unsigned int volume; unsigned int libraries; @@ -1321,18 +1317,18 @@ void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias) ScrollTo(position, duration, bias, bias); } -void ScrollView::ScrollTo(Actor &actor) +void ScrollView::ScrollTo(Actor& actor) { ScrollTo(actor, mSnapDuration); } -void ScrollView::ScrollTo(Actor &actor, float duration) +void ScrollView::ScrollTo(Actor& actor, float duration) { DALI_ASSERT_ALWAYS(actor.GetParent() == Self()); - Actor self = Self(); - Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - Vector3 position = actor.GetCurrentProperty< Vector3 >( Actor::Property::POSITION ); + Actor self = Self(); + Vector3 size = self.GetCurrentProperty(Actor::Property::SIZE); + Vector3 position = actor.GetCurrentProperty(Actor::Property::POSITION); Vector2 prePosition = GetPropertyPrePosition(); position.GetVectorXY() -= prePosition; @@ -1341,17 +1337,17 @@ void ScrollView::ScrollTo(Actor &actor, float duration) Actor ScrollView::FindClosestActor() { - Actor self = Self(); - Vector3 size = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Actor self = Self(); + Vector3 size = self.GetCurrentProperty(Actor::Property::SIZE); - return FindClosestActorToPosition(Vector3(size.width * 0.5f,size.height * 0.5f,0.0f)); + return FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f)); } Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirection dirX, FindDirection dirY, FindDirection dirZ) { - Actor closestChild; - float closestDistance2 = 0.0f; - Vector3 actualPosition = position; + Actor closestChild; + float closestDistance2 = 0.0f; + Vector3 actualPosition = position; unsigned int numChildren = Self().GetChildCount(); @@ -1382,7 +1378,7 @@ Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirect if(dirY > All) // != All,None { FindDirection deltaV = delta.y > 0 ? Down : Up; - if(dirY != deltaV) + if(dirY != deltaV) { continue; } @@ -1392,7 +1388,7 @@ Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirect if(dirZ > All) // != All,None { FindDirection deltaV = delta.y > 0 ? In : Out; - if(dirZ != deltaV) + if(dirZ != deltaV) { continue; } @@ -1421,13 +1417,13 @@ Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirect { if(distance2 < closestDistance2) { - closestChild = child; + closestChild = child; closestDistance2 = distance2; } } else // First time. { - closestChild = child; + closestChild = child; closestDistance2 = distance2; } } @@ -1437,9 +1433,9 @@ Actor ScrollView::FindClosestActorToPosition(const Vector3& position, FindDirect bool ScrollView::ScrollToSnapPoint() { - DALI_LOG_SCROLL_STATE("[0x%X]", this ); + DALI_LOG_SCROLL_STATE("[0x%X]", this); Vector2 stationaryVelocity = Vector2(0.0f, 0.0f); - return SnapWithVelocity( stationaryVelocity ); + return SnapWithVelocity(stationaryVelocity); } // TODO: In situations where axes are different (X snap, Y free) @@ -1454,19 +1450,19 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) // to current mScroll's properties, and then resume. // Note: For Flicking this may work a bit different... - float angle = atan2(velocity.y, velocity.x); - float speed2 = velocity.LengthSquared(); - AlphaFunction alphaFunction = mSnapAlphaFunction; - Vector2 positionDuration = Vector2::ONE * mSnapDuration; - float biasX = 0.5f; - float biasY = 0.5f; - FindDirection horizontal = None; - FindDirection vertical = None; + float angle = atan2(velocity.y, velocity.x); + float speed2 = velocity.LengthSquared(); + AlphaFunction alphaFunction = mSnapAlphaFunction; + Vector2 positionDuration = Vector2::ONE * mSnapDuration; + float biasX = 0.5f; + float biasY = 0.5f; + FindDirection horizontal = None; + FindDirection vertical = None; // orthoAngleRange = Angle tolerance within the Exact N,E,S,W direction // that will be accepted as a general N,E,S,W flick direction. - const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f; + const float orthoAngleRange = FLICK_ORTHO_ANGLE_RANGE * M_PI / 180.0f; const float flickSpeedThreshold2 = mFlickSpeedThreshold * mFlickSpeedThreshold; Vector2 positionSnap = mScrollPrePosition; @@ -1477,8 +1473,8 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) { horizontal = All; - if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold - mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions + if(speed2 > flickSpeedThreshold2 || // exceeds flick threshold + mInAccessibilityPan) // With AccessibilityPan its easier to move between snap positions { if((angle >= -orthoAngleRange) && (angle < orthoAngleRange)) // Swiping East { @@ -1488,7 +1484,7 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) // before the update-thread has advanced mScrollPostPosition past the the previous snap point. positionSnap.x += 1.0f; } - else if((angle >= M_PI-orthoAngleRange) || (angle < -M_PI+orthoAngleRange)) // Swiping West + else if((angle >= M_PI - orthoAngleRange) || (angle < -M_PI + orthoAngleRange)) // Swiping West { biasX = 1.0f, horizontal = Right; @@ -1505,14 +1501,14 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) { vertical = All; - if( speed2 > flickSpeedThreshold2 || // exceeds flick threshold - mInAccessibilityPan ) // With AccessibilityPan its easier to move between snap positions + if(speed2 > flickSpeedThreshold2 || // exceeds flick threshold + mInAccessibilityPan) // With AccessibilityPan its easier to move between snap positions { - if((angle >= M_PI_2-orthoAngleRange) && (angle < M_PI_2+orthoAngleRange)) // Swiping South + if((angle >= M_PI_2 - orthoAngleRange) && (angle < M_PI_2 + orthoAngleRange)) // Swiping South { biasY = 0.0f, vertical = Up; } - else if((angle >= -M_PI_2-orthoAngleRange) && (angle < -M_PI_2+orthoAngleRange)) // Swiping North + else if((angle >= -M_PI_2 - orthoAngleRange) && (angle < -M_PI_2 + orthoAngleRange)) // Swiping North { biasY = 1.0f, vertical = Down; } @@ -1522,31 +1518,31 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) // isFlick: Whether this gesture is a flick or not. bool isFlick = (horizontal != All || vertical != All); // isFreeFlick: Whether this gesture is a flick under free panning criteria. - bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD*FREE_FLICK_SPEED_THRESHOLD); + bool isFreeFlick = velocity.LengthSquared() > (FREE_FLICK_SPEED_THRESHOLD * FREE_FLICK_SPEED_THRESHOLD); if(isFlick || isFreeFlick) { positionDuration = Vector2::ONE * mFlickDuration; - alphaFunction = mFlickAlphaFunction; + alphaFunction = mFlickAlphaFunction; } // Calculate next positionSnap //////////////////////////////////////////////////////////// if(mActorAutoSnapEnabled) { - Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Vector3 size = Self().GetCurrentProperty(Actor::Property::SIZE); - Actor child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f), horizontal, vertical ); + Actor child = FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f), horizontal, vertical); - if(!child && isFlick ) + if(!child && isFlick) { // If we conducted a direction limited search and found no actor, then just snap to the closest actor. - child = FindClosestActorToPosition( Vector3(size.width * 0.5f,size.height * 0.5f,0.0f) ); + child = FindClosestActorToPosition(Vector3(size.width * 0.5f, size.height * 0.5f, 0.0f)); } if(child) { - Vector2 position = Self().GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ); + Vector2 position = Self().GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION); // Get center-point of the Actor. Vector3 childPosition = GetPositionOfAnchor(child, AnchorPoint::CENTER); @@ -1563,14 +1559,13 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) } Vector2 startPosition = positionSnap; - positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system. - positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT. + positionSnap.x = -mRulerX->Snap(-positionSnap.x, biasX); // NOTE: X & Y rulers think in -ve coordinate system. + positionSnap.y = -mRulerY->Snap(-positionSnap.y, biasY); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT. Vector2 clampDelta(Vector2::ZERO); ClampPosition(positionSnap); - if( (mRulerX->GetType() == Ruler::FREE || mRulerY->GetType() == Ruler::FREE) - && isFreeFlick && !mActorAutoSnapEnabled) + if((mRulerX->GetType() == Ruler::FREE || mRulerY->GetType() == Ruler::FREE) && isFreeFlick && !mActorAutoSnapEnabled) { // Calculate target position based on velocity of flick. @@ -1578,28 +1573,28 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) // u = Initial Velocity (Flick velocity) // v = 0 (Final Velocity) // t = Time (Velocity / Deceleration) - Vector2 stageSize = Stage::GetCurrent().GetSize(); - float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length(); - float a = (stageLength * mFrictionCoefficient); - Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient; - float speed = u.Length(); - u/= speed; + Vector2 stageSize = Stage::GetCurrent().GetSize(); + float stageLength = Vector3(stageSize.x, stageSize.y, 0.0f).Length(); + float a = (stageLength * mFrictionCoefficient); + Vector3 u = Vector3(velocity.x, velocity.y, 0.0f) * mFlickSpeedCoefficient; + float speed = u.Length(); + u /= speed; // TODO: Change this to a decay function. (faster you flick, the slower it should be) - speed = std::min(speed, stageLength * mMaxFlickSpeed ); - u*= speed; + speed = std::min(speed, stageLength * mMaxFlickSpeed); + u *= speed; alphaFunction = ConstantDecelerationAlphaFunction; float t = speed / a; if(mRulerX->IsEnabled() && mRulerX->GetType() == Ruler::FREE) { - positionSnap.x += t*u.x*0.5f; + positionSnap.x += t * u.x * 0.5f; } if(mRulerY->IsEnabled() && mRulerY->GetType() == Ruler::FREE) { - positionSnap.y += t*u.y*0.5f; + positionSnap.y += t * u.y * 0.5f; } clampDelta = positionSnap; @@ -1652,10 +1647,7 @@ bool ScrollView::SnapWithVelocity(Vector2 velocity) positionSnap += clampDelta; } - bool animating = AnimateTo(positionSnap, positionDuration, - alphaFunction, false, - DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE, - isFlick || isFreeFlick ? FLICK : SNAP); + bool animating = AnimateTo(positionSnap, positionDuration, alphaFunction, false, DIRECTION_BIAS_NONE, DIRECTION_BIAS_NONE, isFlick || isFreeFlick ? FLICK : SNAP); return animating; } @@ -1679,16 +1671,13 @@ void ScrollView::StopAnimation(Animation& animation) } } -bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration, - AlphaFunction alpha, bool findShortcuts, - DirectionBias horizontalBias, DirectionBias verticalBias, - SnapType snapType) +bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDuration, AlphaFunction alpha, bool findShortcuts, DirectionBias horizontalBias, DirectionBias verticalBias, SnapType snapType) { // Here we perform an animation on a number of properties (depending on which have changed) // The animation is applied to all ScrollBases - Actor self = Self(); + Actor self = Self(); mScrollTargetPosition = position; - float totalDuration = 0.0f; + float totalDuration = 0.0f; bool positionChanged = (mScrollTargetPosition != mScrollPostPosition); @@ -1700,7 +1689,7 @@ bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDurat else { // try to animate for a frame, on some occasions update will be changing scroll value while event side thinks it hasnt changed - totalDuration = 0.01f; + totalDuration = 0.01f; positionChanged = true; } @@ -1718,13 +1707,13 @@ bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDurat if(mRulerX->IsEnabled()) { - float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias); + float dir = VectorInDomain(-mScrollPrePosition.x, -mScrollTargetPosition.x, rulerDomainX.min, rulerDomainX.max, horizontalBias); mScrollTargetPosition.x = mScrollPrePosition.x + -dir; } if(mRulerY->IsEnabled()) { - float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias); + float dir = VectorInDomain(-mScrollPrePosition.y, -mScrollTargetPosition.y, rulerDomainY.min, rulerDomainY.max, verticalBias); mScrollTargetPosition.y = mScrollPrePosition.y + -dir; } } @@ -1734,38 +1723,38 @@ bool ScrollView::AnimateTo(const Vector2& position, const Vector2& positionDurat AnimateInternalXTo(mScrollTargetPosition.x, positionDuration.x, alpha); AnimateInternalYTo(mScrollTargetPosition.y, positionDuration.y, alpha); - if( !(mScrollStateFlags & SCROLL_ANIMATION_FLAGS) ) + if(!(mScrollStateFlags & SCROLL_ANIMATION_FLAGS)) { - DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y ); + DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y); self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollTargetPosition); - mScrollPrePosition = mScrollTargetPosition; + mScrollPrePosition = mScrollTargetPosition; mScrollPostPosition = mScrollTargetPosition; WrapPosition(mScrollPostPosition); } - DALI_LOG_SCROLL_STATE("[0x%X] position-changed, mScrollTargetPosition[%.2f, %.2f], mScrollPrePosition[%.2f, %.2f], mScrollPostPosition[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y, mScrollPrePosition.x, mScrollPrePosition.y, mScrollPostPosition.x, mScrollPostPosition.y ); - DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get().x, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get().y, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get().x, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get().y ); + DALI_LOG_SCROLL_STATE("[0x%X] position-changed, mScrollTargetPosition[%.2f, %.2f], mScrollPrePosition[%.2f, %.2f], mScrollPostPosition[%.2f, %.2f]", this, mScrollTargetPosition.x, mScrollTargetPosition.y, mScrollPrePosition.x, mScrollPrePosition.y, mScrollPostPosition.x, mScrollPostPosition.y); + DALI_LOG_SCROLL_STATE("[0x%X] SCROLL_PRE_POSITION[%.2f, %.2f], SCROLL_POSITION[%.2f, %.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get().x, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get().y, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get().x, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get().y); } SetScrollUpdateNotification(true); // Always send a snap event when AnimateTo is called. Toolkit::ScrollView::SnapEvent snapEvent; - snapEvent.type = snapType; + snapEvent.type = snapType; snapEvent.position = -mScrollTargetPosition; snapEvent.duration = totalDuration; DALI_LOG_SCROLL_STATE("[0x%X] mSnapStartedSignal [%.2f, %.2f]", this, snapEvent.position.x, snapEvent.position.y); - mSnapStartedSignal.Emit( snapEvent ); + mSnapStartedSignal.Emit(snapEvent); return (mScrollStateFlags & SCROLL_ANIMATION_FLAGS) != 0; } void ScrollView::EnableScrollOvershoot(bool enable) { - if (enable) + if(enable) { - if (!mOvershootIndicator) + if(!mOvershootIndicator) { mOvershootIndicator = ScrollOvershootIndicator::New(); } @@ -1776,7 +1765,7 @@ void ScrollView::EnableScrollOvershoot(bool enable) { mMaxOvershoot = mUserMaxOvershoot; - if (mOvershootIndicator) + if(mOvershootIndicator) { mOvershootIndicator->DetachFromScrollable(*this); } @@ -1787,46 +1776,46 @@ void ScrollView::EnableScrollOvershoot(bool enable) void ScrollView::AddOverlay(Actor actor) { - actor.SetProperty( Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D ); - mInternalActor.Add( actor ); + actor.SetProperty(Actor::Property::DRAW_MODE, DrawMode::OVERLAY_2D); + mInternalActor.Add(actor); } void ScrollView::RemoveOverlay(Actor actor) { - mInternalActor.Remove( actor ); + mInternalActor.Remove(actor); } -void ScrollView::SetOvershootSize( const Vector2& size ) +void ScrollView::SetOvershootSize(const Vector2& size) { mOvershootSize = size; - if( IsOvershootEnabled() && mOvershootIndicator ) + if(IsOvershootEnabled() && mOvershootIndicator) { mOvershootIndicator->AttachToScrollable(*this); } } -void ScrollView::SetOvershootEffectColor( const Vector4& color ) +void ScrollView::SetOvershootEffectColor(const Vector4& color) { mOvershootEffectColor = color; - if( mOvershootIndicator ) + if(mOvershootIndicator) { - mOvershootIndicator->SetOvershootEffectColor( color ); + mOvershootIndicator->SetOvershootEffectColor(color); } } -void ScrollView::SetScrollingDirection( Radian direction, Radian threshold ) +void ScrollView::SetScrollingDirection(Radian direction, Radian threshold) { - PanGestureDetector panGesture( GetPanGestureDetector() ); + PanGestureDetector panGesture(GetPanGestureDetector()); // First remove just in case we have some set, then add. - panGesture.RemoveDirection( direction ); - panGesture.AddDirection( direction, threshold ); + panGesture.RemoveDirection(direction); + panGesture.AddDirection(direction, threshold); } -void ScrollView::RemoveScrollingDirection( Radian direction ) +void ScrollView::RemoveScrollingDirection(Radian direction) { - PanGestureDetector panGesture( GetPanGestureDetector() ); - panGesture.RemoveDirection( direction ); + PanGestureDetector panGesture(GetPanGestureDetector()); + panGesture.RemoveDirection(direction); } Toolkit::ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal() @@ -1847,14 +1836,14 @@ void ScrollView::FindAndUnbindActor(Actor child) Vector2 ScrollView::GetPropertyPrePosition() const { - Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ); + Vector2 position = Self().GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION); WrapPosition(position); return position; } Vector2 ScrollView::GetPropertyPosition() const { - Vector2 position = Self().GetCurrentProperty< Vector2 >( Toolkit::ScrollView::Property::SCROLL_POSITION ); + Vector2 position = Self().GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION); WrapPosition(position); return position; @@ -1876,68 +1865,68 @@ void ScrollView::HandleSnapAnimationFinished() UpdateLocalScrollProperties(); WrapPosition(mScrollPrePosition); - DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y ); + DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y); self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition); Vector2 currentScrollPosition = GetCurrentScrollPosition(); - DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y ); - mScrollCompletedSignal.Emit( currentScrollPosition ); + DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 3 current[%.2f, %.2f], mScrollTargetPosition[%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y, -mScrollTargetPosition.x, -mScrollTargetPosition.y); + mScrollCompletedSignal.Emit(currentScrollPosition); mDomainOffset += deltaPosition - mScrollPostPosition; self.SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset); HandleStoppedAnimation(); } -void ScrollView::SetScrollUpdateNotification( bool enabled ) +void ScrollView::SetScrollUpdateNotification(bool enabled) { Actor self = Self(); - if( mScrollXUpdateNotification ) + if(mScrollXUpdateNotification) { // disconnect now to avoid a notification before removed from update thread mScrollXUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification); self.RemovePropertyNotification(mScrollXUpdateNotification); mScrollXUpdateNotification.Reset(); } - if( enabled && !mScrollUpdatedSignal.Empty()) + if(enabled && !mScrollUpdatedSignal.Empty()) { // Only set up the notification when the application has connected to the updated signal mScrollXUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 0, StepCondition(mScrollUpdateDistance, 0.0f)); - mScrollXUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification ); + mScrollXUpdateNotification.NotifySignal().Connect(this, &ScrollView::OnScrollUpdateNotification); } - if( mScrollYUpdateNotification ) + if(mScrollYUpdateNotification) { // disconnect now to avoid a notification before removed from update thread mScrollYUpdateNotification.NotifySignal().Disconnect(this, &ScrollView::OnScrollUpdateNotification); self.RemovePropertyNotification(mScrollYUpdateNotification); mScrollYUpdateNotification.Reset(); } - if( enabled && !mScrollUpdatedSignal.Empty()) + if(enabled && !mScrollUpdatedSignal.Empty()) { // Only set up the notification when the application has connected to the updated signal mScrollYUpdateNotification = self.AddPropertyNotification(Toolkit::ScrollView::Property::SCROLL_POSITION, 1, StepCondition(mScrollUpdateDistance, 0.0f)); - mScrollYUpdateNotification.NotifySignal().Connect( this, &ScrollView::OnScrollUpdateNotification ); + mScrollYUpdateNotification.NotifySignal().Connect(this, &ScrollView::OnScrollUpdateNotification); } } void ScrollView::OnScrollUpdateNotification(Dali::PropertyNotification& source) { // Guard against destruction during signal emission - Toolkit::ScrollView handle( GetOwner() ); + Toolkit::ScrollView handle(GetOwner()); Vector2 currentScrollPosition = GetCurrentScrollPosition(); - mScrollUpdatedSignal.Emit( currentScrollPosition ); + mScrollUpdatedSignal.Emit(currentScrollPosition); } -bool ScrollView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool ScrollView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::ScrollView view = Toolkit::ScrollView::DownCast( handle ); + bool connected(true); + Toolkit::ScrollView view = Toolkit::ScrollView::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_SNAP_STARTED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_SNAP_STARTED)) { - view.SnapStartedSignal().Connect( tracker, functor ); + view.SnapStartedSignal().Connect(tracker, functor); } else { @@ -1954,61 +1943,61 @@ void ScrollView::OnSizeAnimation(Animation& animation, const Vector3& targetSize UpdatePropertyDomain(); } -void ScrollView::OnSizeSet( const Vector3& size ) +void ScrollView::OnSizeSet(const Vector3& size) { // need to update domain properties for new size - if( mDefaultMaxOvershoot ) + if(mDefaultMaxOvershoot) { mUserMaxOvershoot.x = size.x * 0.5f; mUserMaxOvershoot.y = size.y * 0.5f; - if( !IsOvershootEnabled() ) + if(!IsOvershootEnabled()) { mMaxOvershoot = mUserMaxOvershoot; } } UpdatePropertyDomain(); UpdateMainInternalConstraint(); - if( IsOvershootEnabled() ) + if(IsOvershootEnabled()) { mOvershootIndicator->Reset(); } - ScrollBase::OnSizeSet( size ); + ScrollBase::OnSizeSet(size); } void ScrollView::OnChildAdd(Actor& child) { - ScrollBase::OnChildAdd( child ); + ScrollBase::OnChildAdd(child); Dali::Toolkit::ScrollBar scrollBar = Dali::Toolkit::ScrollBar::DownCast(child); - if( scrollBar ) + if(scrollBar) { mScrollBar = scrollBar; - scrollBar.SetProperty( Dali::Actor::Property::NAME,"ScrollBar"); + scrollBar.SetProperty(Dali::Actor::Property::NAME, "ScrollBar"); - mInternalActor.Add( scrollBar ); - if( scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL ) + mInternalActor.Add(scrollBar); + if(scrollBar.GetScrollDirection() == Toolkit::ScrollBar::HORIZONTAL) { - scrollBar.SetScrollPropertySource( Self(), - Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X, - Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X, - Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X, - Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X ); + scrollBar.SetScrollPropertySource(Self(), + Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_X, + Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_X, + Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_X, + Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_X); } else { - scrollBar.SetScrollPropertySource( Self(), - Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y, - Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y, - Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y, - Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y ); + scrollBar.SetScrollPropertySource(Self(), + Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_Y, + Toolkit::Scrollable::Property::SCROLL_POSITION_MIN_Y, + Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX_Y, + Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE_Y); } - if( mTransientScrollBar ) + if(mTransientScrollBar) { // Show the scroll-indicator for a brief period Property::Map emptyMap; - scrollBar.DoAction( "ShowTransientIndicator", emptyMap ); + scrollBar.DoAction("ShowTransientIndicator", emptyMap); } } else if(mAlterChild) @@ -2022,15 +2011,15 @@ void ScrollView::OnChildRemove(Actor& child) // TODO: Actor needs a RemoveConstraint method to take out an individual constraint. UnbindActor(child); - ScrollBase::OnChildRemove( child ); + ScrollBase::OnChildRemove(child); } void ScrollView::StartTouchDownTimer() { - if ( !mTouchDownTimer ) + if(!mTouchDownTimer) { - mTouchDownTimer = Timer::New( TOUCH_DOWN_TIMER_INTERVAL ); - mTouchDownTimer.TickSignal().Connect( this, &ScrollView::OnTouchDownTimeout ); + mTouchDownTimer = Timer::New(TOUCH_DOWN_TIMER_INTERVAL); + mTouchDownTimer.TickSignal().Connect(this, &ScrollView::OnTouchDownTimeout); } mTouchDownTimer.Start(); @@ -2038,7 +2027,7 @@ void ScrollView::StartTouchDownTimer() void ScrollView::StopTouchDownTimer() { - if ( mTouchDownTimer ) + if(mTouchDownTimer) { mTouchDownTimer.Stop(); } @@ -2050,13 +2039,13 @@ bool ScrollView::OnTouchDownTimeout() mTouchDownTimeoutReached = true; - unsigned int currentScrollStateFlags( mScrollStateFlags ); // Cleared in StopAnimation so keep local copy for comparison - if( currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS) ) + unsigned int currentScrollStateFlags(mScrollStateFlags); // Cleared in StopAnimation so keep local copy for comparison + if(currentScrollStateFlags & (SCROLL_ANIMATION_FLAGS | SNAP_ANIMATION_FLAGS)) { DALI_LOG_SCROLL_STATE("[0x%X] Scrolling Or snapping flags set, stopping animation", this); StopAnimation(); - if( currentScrollStateFlags & SCROLL_ANIMATION_FLAGS ) + if(currentScrollStateFlags & SCROLL_ANIMATION_FLAGS) { DALI_LOG_SCROLL_STATE("[0x%X] Scrolling flags set, emitting signal", this); @@ -2068,14 +2057,14 @@ bool ScrollView::OnTouchDownTimeout() UpdateLocalScrollProperties(); Vector2 currentScrollPosition = GetCurrentScrollPosition(); DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 4 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y); - mScrollCompletedSignal.Emit( currentScrollPosition ); + mScrollCompletedSignal.Emit(currentScrollPosition); } } return false; } -bool ScrollView::OnTouch( Actor actor, const TouchEvent& touch ) +bool ScrollView::OnTouch(Actor actor, const TouchEvent& touch) { if(!mSensitive) { @@ -2086,51 +2075,51 @@ bool ScrollView::OnTouch( Actor actor, const TouchEvent& touch ) } // Ignore events with multiple-touch points - if (touch.GetPointCount() != 1) + if(touch.GetPointCount() != 1) { DALI_LOG_SCROLL_STATE("[0x%X], multiple touch, ignoring", this); return false; } - const PointState::Type pointState = touch.GetState( 0 ); - if( pointState == PointState::DOWN ) + const PointState::Type pointState = touch.GetState(0); + if(pointState == PointState::DOWN) { DALI_LOG_SCROLL_STATE("[0x%X] Down", this); - if(mGestureStackDepth==0) + if(mGestureStackDepth == 0) { mTouchDownTime = touch.GetTime(); // This allows time for a pan-gesture to start, to avoid breaking snap-animation behavior with fast flicks. // If touch-down does not become a pan (after timeout interval), then snap-animation can be interrupted. mTouchDownTimeoutReached = false; - mScrollInterrupted = false; + mScrollInterrupted = false; StartTouchDownTimer(); } } - else if( ( pointState == PointState::UP ) || - ( ( pointState == PointState::INTERRUPTED ) && ( touch.GetHitActor( 0 )== Self() ) ) ) + else if((pointState == PointState::UP) || + ((pointState == PointState::INTERRUPTED) && (touch.GetHitActor(0) == Self()))) { - DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ( ( pointState == PointState::UP ) ? "Up" : "Interrupted" ) ); + DALI_LOG_SCROLL_STATE("[0x%X] %s", this, ((pointState == PointState::UP) ? "Up" : "Interrupted")); StopTouchDownTimer(); // if the user touches and releases without enough movement to go // into a gesture state, then we should snap to nearest point. // otherwise our scroll could be stopped (interrupted) half way through an animation. - if(mGestureStackDepth==0 && mTouchDownTimeoutReached) + if(mGestureStackDepth == 0 && mTouchDownTimeoutReached) { - if( ( pointState == PointState::INTERRUPTED ) || - ( ( touch.GetTime() - mTouchDownTime ) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET ) ) + if((pointState == PointState::INTERRUPTED) || + ((touch.GetTime() - mTouchDownTime) >= MINIMUM_TIME_BETWEEN_DOWN_AND_UP_FOR_RESET)) { // Reset the velocity only if down was received a while ago - mLastVelocity = Vector2( 0.0f, 0.0f ); + mLastVelocity = Vector2(0.0f, 0.0f); } UpdateLocalScrollProperties(); // Only finish the transform if scrolling was interrupted on down or if we are scrolling - if ( mScrollInterrupted || mScrolling ) + if(mScrollInterrupted || mScrolling) { DALI_LOG_SCROLL_STATE("[0x%X] Calling FinishTransform", this); @@ -2138,13 +2127,13 @@ bool ScrollView::OnTouch( Actor actor, const TouchEvent& touch ) } } mTouchDownTimeoutReached = false; - mScrollInterrupted = false; + mScrollInterrupted = false; } return false; } -bool ScrollView::OnWheelEvent( Actor actor, const WheelEvent& event) +bool ScrollView::OnWheelEvent(Actor actor, const WheelEvent& event) { if(!mSensitive) { @@ -2193,17 +2182,17 @@ bool ScrollView::OnWheelEvent( Actor actor, const WheelEvent& event) void ScrollView::ResetScrolling() { Actor self = Self(); - self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition ); + self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition); mScrollPrePosition = mScrollPostPosition; - DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y ); + DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPostPosition.x, mScrollPostPosition.y); self.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPostPosition); } void ScrollView::UpdateLocalScrollProperties() { Actor self = Self(); - self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get( mScrollPrePosition ); - self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_POSITION ).Get( mScrollPostPosition ); + self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get(mScrollPrePosition); + self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_POSITION).Get(mScrollPostPosition); } // private functions @@ -2220,13 +2209,13 @@ void ScrollView::PreAnimatedScrollSetup() mDomainOffset += deltaPosition - mScrollPostPosition; Self().SetProperty(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET, mDomainOffset); - if( mScrollStateFlags & SCROLL_X_STATE_MASK ) + if(mScrollStateFlags & SCROLL_X_STATE_MASK) { // already performing animation on internal x position StopAnimation(mInternalXAnimation); } - if( mScrollStateFlags & SCROLL_Y_STATE_MASK ) + if(mScrollStateFlags & SCROLL_Y_STATE_MASK) { // already performing animation on internal y position StopAnimation(mInternalYAnimation); @@ -2242,18 +2231,18 @@ void ScrollView::FinaliseAnimatedScroll() // TODO - common animation finishing code in here } -void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFunction alpha ) +void ScrollView::AnimateInternalXTo(float position, float duration, AlphaFunction alpha) { StopAnimation(mInternalXAnimation); - if( duration > Math::MACHINE_EPSILON_10 ) + if(duration > Math::MACHINE_EPSILON_10) { Actor self = Self(); - DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().x, position ); + DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get().x, position); mInternalXAnimation = Animation::New(duration); - DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr() ); + DALI_LOG_SCROLL_STATE("[0x%X], mInternalXAnimation[0x%X]", this, mInternalXAnimation.GetObjectPtr()); mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished); - mInternalXAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration)); + mInternalXAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 0), position, alpha, TimePeriod(duration)); mInternalXAnimation.Play(); // erase current state flags @@ -2263,18 +2252,18 @@ void ScrollView::AnimateInternalXTo( float position, float duration, AlphaFuncti } } -void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFunction alpha ) +void ScrollView::AnimateInternalYTo(float position, float duration, AlphaFunction alpha) { StopAnimation(mInternalYAnimation); - if( duration > Math::MACHINE_EPSILON_10 ) + if(duration > Math::MACHINE_EPSILON_10) { Actor self = Self(); - DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ).Get< Vector2 >().y, position ); + DALI_LOG_SCROLL_STATE("[0x%X], Animating from[%.2f] to[%.2f]", this, self.GetCurrentProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION).Get().y, position); mInternalYAnimation = Animation::New(duration); - DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr() ); + DALI_LOG_SCROLL_STATE("[0x%X], mInternalYAnimation[0x%X]", this, mInternalYAnimation.GetObjectPtr()); mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnScrollAnimationFinished); - mInternalYAnimation.AnimateTo( Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration)); + mInternalYAnimation.AnimateTo(Property(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, 1), position, alpha, TimePeriod(duration)); mInternalYAnimation.Play(); // erase current state flags @@ -2284,52 +2273,52 @@ void ScrollView::AnimateInternalYTo( float position, float duration, AlphaFuncti } } -void ScrollView::OnScrollAnimationFinished( Animation& source ) +void ScrollView::OnScrollAnimationFinished(Animation& source) { // Guard against destruction during signal emission // Note that ScrollCompletedSignal is emitted from HandleSnapAnimationFinished() - Toolkit::ScrollView handle( GetOwner() ); + Toolkit::ScrollView handle(GetOwner()); bool scrollingFinished = false; // update our local scroll positions UpdateLocalScrollProperties(); - if( source == mInternalXAnimation ) + if(source == mInternalXAnimation) { - DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetCurrentProperty( SCROLL_PRE_POSITION ).Get< Vector2 >().x, mScrollPostPosition.x ); + DALI_LOG_SCROLL_STATE("[0x%X] mInternalXAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalXAnimation.GetObjectPtr(), mScrollTargetPosition.x, Self().GetCurrentProperty(SCROLL_PRE_POSITION).Get().x, mScrollPostPosition.x); - if( !(mScrollStateFlags & AnimatingInternalY) ) + if(!(mScrollStateFlags & AnimatingInternalY)) { scrollingFinished = true; } mInternalXAnimation.Reset(); // wrap pre scroll x position and set it - if( mWrapMode ) + if(mWrapMode) { const RulerDomain rulerDomain = mRulerX->GetDomain(); - mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max); - DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y ); + mScrollPrePosition.x = -WrapInDomain(-mScrollPrePosition.x, rulerDomain.min, rulerDomain.max); + DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y); handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition); } SnapInternalXTo(mScrollPostPosition.x); } - if( source == mInternalYAnimation ) + if(source == mInternalYAnimation) { - DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, DevelHandle::GetProperty( Self(), SCROLL_PRE_POSITION ).Get< Vector2 >().y, mScrollPostPosition.y ); + DALI_LOG_SCROLL_STATE("[0x%X] mInternalYAnimation[0x%X], expected[%.2f], actual[%.2f], post[%.2f]", this, mInternalYAnimation.GetObjectPtr(), mScrollTargetPosition.y, DevelHandle::GetProperty(Self(), SCROLL_PRE_POSITION).Get().y, mScrollPostPosition.y); - if( !(mScrollStateFlags & AnimatingInternalX) ) + if(!(mScrollStateFlags & AnimatingInternalX)) { scrollingFinished = true; } mInternalYAnimation.Reset(); - if( mWrapMode ) + if(mWrapMode) { // wrap pre scroll y position and set it const RulerDomain rulerDomain = mRulerY->GetDomain(); - mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max); - DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y ); + mScrollPrePosition.y = -WrapInDomain(-mScrollPrePosition.y, rulerDomain.min, rulerDomain.max); + DALI_LOG_SCROLL_STATE("[0x%X] Setting SCROLL_PRE_POSITION To[%.2f, %.2f]", this, mScrollPrePosition.x, mScrollPrePosition.y); handle.SetProperty(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, mScrollPrePosition); } SnapInternalYTo(mScrollPostPosition.y); @@ -2343,22 +2332,22 @@ void ScrollView::OnScrollAnimationFinished( Animation& source ) } } -void ScrollView::OnSnapInternalPositionFinished( Animation& source ) +void ScrollView::OnSnapInternalPositionFinished(Animation& source) { Actor self = Self(); UpdateLocalScrollProperties(); - if( source == mInternalXAnimation ) + if(source == mInternalXAnimation) { - DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this ); + DALI_LOG_SCROLL_STATE("[0x%X] Finished X PostPosition Animation", this); // clear internal x animation flags mScrollStateFlags &= ~SCROLL_X_STATE_MASK; mInternalXAnimation.Reset(); WrapPosition(mScrollPrePosition); } - if( source == mInternalYAnimation ) + if(source == mInternalYAnimation) { - DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this ); + DALI_LOG_SCROLL_STATE("[0x%X] Finished Y PostPosition Animation", this); mScrollStateFlags &= ~SCROLL_Y_STATE_MASK; mInternalYAnimation.Reset(); @@ -2377,10 +2366,10 @@ void ScrollView::SnapInternalXTo(float position) // if internal x not equal to inputed parameter, animate it float duration = std::min(fabsf((position - mScrollPrePosition.x) / mMaxOvershoot.x) * mSnapOvershootDuration, mSnapOvershootDuration); - DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration ); - if( duration > Math::MACHINE_EPSILON_1 ) + DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration); + if(duration > Math::MACHINE_EPSILON_1) { - DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position ); + DALI_LOG_SCROLL_STATE("[0x%X] Starting X Snap Animation to[%.2f]", this, position); mInternalXAnimation = Animation::New(duration); mInternalXAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished); @@ -2403,10 +2392,10 @@ void ScrollView::SnapInternalYTo(float position) // if internal y not equal to inputed parameter, animate it float duration = std::min(fabsf((position - mScrollPrePosition.y) / mMaxOvershoot.y) * mSnapOvershootDuration, mSnapOvershootDuration); - DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration ); - if( duration > Math::MACHINE_EPSILON_1 ) + DALI_LOG_SCROLL_STATE("[0x%X] duration[%.2f]", this, duration); + if(duration > Math::MACHINE_EPSILON_1) { - DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position ); + DALI_LOG_SCROLL_STATE("[0x%X] Starting Y Snap Animation to[%.2f]", this, position); mInternalYAnimation = Animation::New(duration); mInternalYAnimation.FinishedSignal().Connect(this, &ScrollView::OnSnapInternalPositionFinished); @@ -2423,23 +2412,23 @@ void ScrollView::GestureStarted() // we handle the first gesture. // if we're currently doing a gesture and receive another // we continue and combine the effects of the gesture instead of reseting. - if(mGestureStackDepth++==0) + if(mGestureStackDepth++ == 0) { Actor self = Self(); StopTouchDownTimer(); StopAnimation(); - mPanDelta = Vector2::ZERO; + mPanDelta = Vector2::ZERO; mLastVelocity = Vector2::ZERO; - if( !mScrolling ) + if(!mScrolling) { mLockAxis = LockPossible; } - if( mScrollStateFlags & SCROLL_X_STATE_MASK ) + if(mScrollStateFlags & SCROLL_X_STATE_MASK) { StopAnimation(mInternalXAnimation); } - if( mScrollStateFlags & SCROLL_Y_STATE_MASK ) + if(mScrollStateFlags & SCROLL_Y_STATE_MASK) { StopAnimation(mInternalYAnimation); } @@ -2452,15 +2441,15 @@ void ScrollView::GestureStarted() // send negative scroll position since scroll internal scroll position works as an offset for actors, // give applications the position within the domain from the scroll view's anchor position DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 5 [%.2f, %.2f]", this, -mScrollPostPosition.x, -mScrollPostPosition.y); - mScrollCompletedSignal.Emit( -mScrollPostPosition ); + mScrollCompletedSignal.Emit(-mScrollPostPosition); } } } void ScrollView::GestureContinuing(const Vector2& panDelta) { - mPanDelta.x+= panDelta.x; - mPanDelta.y+= panDelta.y; + mPanDelta.x += panDelta.x; + mPanDelta.y += panDelta.y; // Save the velocity, there is a bug in PanGesture // Whereby the GestureState::FINISHED's velocity is either: @@ -2478,11 +2467,11 @@ void ScrollView::GestureContinuing(const Vector2& panDelta) // TODO: Upgrade to use a more powerful gesture detector (one that supports multiple touches on pan - so works as pan and flick gesture) // BUG: GestureState::FINISHED doesn't always return velocity on release (due to // timeDelta between last two events being 0 sometimes, or posiiton being the same) -void ScrollView::OnPan( const PanGesture& gesture ) +void ScrollView::OnPan(const PanGesture& gesture) { // Guard against destruction during signal emission // Note that Emit() methods are called indirectly e.g. from within ScrollView::OnGestureEx() - Actor self( Self() ); + Actor self(Self()); if(!mSensitive) { @@ -2500,22 +2489,22 @@ void ScrollView::OnPan( const PanGesture& gesture ) { DALI_LOG_SCROLL_STATE("[0x%X] Pan Started", this); const Vector2& position = gesture.GetPosition(); - mPanStartPosition = position - gesture.GetDisplacement(); + mPanStartPosition = position - gesture.GetDisplacement(); UpdateLocalScrollProperties(); GestureStarted(); mPanning = true; - self.SetProperty( Toolkit::ScrollView::Property::PANNING, true ); - self.SetProperty( Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f) ); + self.SetProperty(Toolkit::ScrollView::Property::PANNING, true); + self.SetProperty(Toolkit::ScrollView::Property::START_PAGE_POSITION, Vector3(position.x, position.y, 0.0f)); UpdateMainInternalConstraint(); Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle(); - if( scrollBar && mTransientScrollBar ) + if(scrollBar && mTransientScrollBar) { - Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Vector3 size = Self().GetCurrentProperty(Actor::Property::SIZE); const Toolkit::RulerDomain& rulerDomainX = mRulerX->GetDomain(); const Toolkit::RulerDomain& rulerDomainY = mRulerY->GetDomain(); - if( ( rulerDomainX.max > size.width ) || ( rulerDomainY.max > size.height ) ) + if((rulerDomainX.max > size.width) || (rulerDomainY.max > size.height)) { scrollBar.ShowIndicator(); } @@ -2525,7 +2514,7 @@ void ScrollView::OnPan( const PanGesture& gesture ) case GestureState::CONTINUING: { - if ( mPanning ) + if(mPanning) { DALI_LOG_SCROLL_STATE("[0x%X] Pan Continuing", this); GestureContinuing(gesture.GetScreenDisplacement()); @@ -2541,22 +2530,22 @@ void ScrollView::OnPan( const PanGesture& gesture ) case GestureState::FINISHED: case GestureState::CANCELLED: { - if ( mPanning ) + if(mPanning) { - DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ( ( gesture.GetState() == GestureState::FINISHED ) ? "Finished" : "Cancelled" ) ); + DALI_LOG_SCROLL_STATE("[0x%X] Pan %s", this, ((gesture.GetState() == GestureState::FINISHED) ? "Finished" : "Cancelled")); UpdateLocalScrollProperties(); mLastVelocity = gesture.GetVelocity(); - mPanning = false; - self.SetProperty( Toolkit::ScrollView::Property::PANNING, false ); + mPanning = false; + self.SetProperty(Toolkit::ScrollView::Property::PANNING, false); - if( mScrollMainInternalPrePositionConstraint ) + if(mScrollMainInternalPrePositionConstraint) { mScrollMainInternalPrePositionConstraint.Remove(); } Toolkit::ScrollBar scrollBar = mScrollBar.GetHandle(); - if( scrollBar && mTransientScrollBar ) + if(scrollBar && mTransientScrollBar) { scrollBar.HideIndicator(); } @@ -2591,21 +2580,20 @@ void ScrollView::OnGestureEx(GestureState state) Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, true); mScrolling = true; DALI_LOG_SCROLL_STATE("[0x%X] mScrollStartedSignal 2 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y); - mScrollStartedSignal.Emit( currentScrollPosition ); + mScrollStartedSignal.Emit(currentScrollPosition); } - else if( (state == GestureState::FINISHED) || - (state == GestureState::CANCELLED) ) // Finished/default + else if((state == GestureState::FINISHED) || + (state == GestureState::CANCELLED)) // Finished/default { // when all the gestures have finished, we finish the transform. // so if a user decides to pan (1 gesture), and then pan+zoom (2 gestures) // then stop panning (back to 1 gesture), and then stop zooming (0 gestures). // this is the point we end, and perform necessary snapping. mGestureStackDepth--; - if(mGestureStackDepth==0) + if(mGestureStackDepth == 0) { // no flick if we have not exceeded min flick distance - if( (fabsf(mPanDelta.x) < mMinFlickDistance.x) - && (fabsf(mPanDelta.y) < mMinFlickDistance.y) ) + if((fabsf(mPanDelta.x) < mMinFlickDistance.x) && (fabsf(mPanDelta.y) < mMinFlickDistance.y)) { // reset flick velocity mLastVelocity = Vector2::ZERO; @@ -2636,23 +2624,23 @@ void ScrollView::FinishTransform() mScrolling = false; Self().SetProperty(Toolkit::ScrollView::Property::SCROLLING, false); - if( fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10 ) + if(fabs(mScrollPrePosition.x - mScrollTargetPosition.x) > Math::MACHINE_EPSILON_10) { SnapInternalXTo(mScrollTargetPosition.x); } - if( fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10 ) + if(fabs(mScrollPrePosition.y - mScrollTargetPosition.y) > Math::MACHINE_EPSILON_10) { SnapInternalYTo(mScrollTargetPosition.y); } Vector2 currentScrollPosition = GetCurrentScrollPosition(); DALI_LOG_SCROLL_STATE("[0x%X] mScrollCompletedSignal 6 [%.2f, %.2f]", this, currentScrollPosition.x, currentScrollPosition.y); - mScrollCompletedSignal.Emit( currentScrollPosition ); + mScrollCompletedSignal.Emit(currentScrollPosition); } } Vector2 ScrollView::GetOvershoot(Vector2& position) const { - Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Vector3 size = Self().GetCurrentProperty(Actor::Property::SIZE); Vector2 overshoot; const RulerDomain rulerDomainX = mRulerX->GetDomain(); @@ -2660,13 +2648,13 @@ Vector2 ScrollView::GetOvershoot(Vector2& position) const if(mRulerX->IsEnabled() && rulerDomainX.enabled) { - const float left = rulerDomainX.min - position.x; + const float left = rulerDomainX.min - position.x; const float right = size.width - rulerDomainX.max - position.x; - if(left<0) + if(left < 0) { overshoot.x = left; } - else if(right>0) + else if(right > 0) { overshoot.x = right; } @@ -2674,13 +2662,13 @@ Vector2 ScrollView::GetOvershoot(Vector2& position) const if(mRulerY->IsEnabled() && rulerDomainY.enabled) { - const float top = rulerDomainY.min - position.y; + const float top = rulerDomainY.min - position.y; const float bottom = size.height - rulerDomainY.max - position.y; - if(top<0) + if(top < 0) { overshoot.y = top; } - else if(bottom>0) + else if(bottom > 0) { overshoot.y = bottom; } @@ -2705,12 +2693,12 @@ void ScrollView::ClampPosition(Vector2& position) const ClampPosition(position, clamped); } -void ScrollView::ClampPosition(Vector2& position, ClampState2D &clamped) const +void ScrollView::ClampPosition(Vector2& position, ClampState2D& clamped) const { - Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); + Vector3 size = Self().GetCurrentProperty(Actor::Property::SIZE); - position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system. - position.y = -mRulerY->Clamp(-position.y, size.height, 1.0f, clamped.y); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT. + position.x = -mRulerX->Clamp(-position.x, size.width, 1.0f, clamped.x); // NOTE: X & Y rulers think in -ve coordinate system. + position.y = -mRulerY->Clamp(-position.y, size.height, 1.0f, clamped.y); // That is scrolling RIGHT (e.g. 100.0, 0.0) means moving LEFT. } void ScrollView::WrapPosition(Vector2& position) const @@ -2736,8 +2724,8 @@ void ScrollView::UpdateMainInternalConstraint() { // TODO: Only update the constraints which have changed, rather than remove all and add all again. // Requires a dali-core ApplyConstraintAt, or a ReplaceConstraint. The former is probably more flexible. - Actor self = Self(); - PanGestureDetector detector( GetPanGestureDetector() ); + Actor self = Self(); + PanGestureDetector detector(GetPanGestureDetector()); if(mScrollMainInternalPositionConstraint) { @@ -2748,7 +2736,7 @@ void ScrollView::UpdateMainInternalConstraint() mScrollMainInternalDomainConstraint.Remove(); mScrollMainInternalPrePositionMaxConstraint.Remove(); } - if( mScrollMainInternalPrePositionConstraint ) + if(mScrollMainInternalPrePositionConstraint) { mScrollMainInternalPrePositionConstraint.Remove(); } @@ -2759,74 +2747,72 @@ void ScrollView::UpdateMainInternalConstraint() // 1. First calculate the pre-position (this is the scroll position if no clamping has taken place) Vector2 initialPanMask = Vector2(mRulerX->IsEnabled() ? 1.0f : 0.0f, mRulerY->IsEnabled() ? 1.0f : 0.0f); - if( mLockAxis == LockVertical ) + if(mLockAxis == LockVertical) { initialPanMask.y = 0.0f; } - else if( mLockAxis == LockHorizontal ) + else if(mLockAxis == LockHorizontal) { initialPanMask.x = 0.0f; } - if( mPanning ) - { - mScrollMainInternalPrePositionConstraint = Constraint::New( self, - Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, - InternalPrePositionConstraint( mPanStartPosition, - initialPanMask, - mAxisAutoLock, - mAxisAutoLockGradient, - mLockAxis, - mMaxOvershoot, - mRulerX, - mRulerY ) ); - mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::LOCAL_POSITION ) ); - mScrollMainInternalPrePositionConstraint.AddSource( Source( detector, PanGestureDetector::Property::PANNING ) ); - mScrollMainInternalPrePositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) ); + if(mPanning) + { + mScrollMainInternalPrePositionConstraint = Constraint::New(self, + Toolkit::ScrollView::Property::SCROLL_PRE_POSITION, + InternalPrePositionConstraint(mPanStartPosition, + initialPanMask, + mAxisAutoLock, + mAxisAutoLockGradient, + mLockAxis, + mMaxOvershoot, + mRulerX, + mRulerY)); + mScrollMainInternalPrePositionConstraint.AddSource(Source(detector, PanGestureDetector::Property::LOCAL_POSITION)); + mScrollMainInternalPrePositionConstraint.AddSource(Source(detector, PanGestureDetector::Property::PANNING)); + mScrollMainInternalPrePositionConstraint.AddSource(Source(self, Actor::Property::SIZE)); mScrollMainInternalPrePositionConstraint.Apply(); } // 2. Second calculate the clamped position (actual position) - mScrollMainInternalPositionConstraint = Constraint::New( self, - Toolkit::ScrollView::Property::SCROLL_POSITION, - InternalPositionConstraint( mRulerX->GetDomain(), - mRulerY->GetDomain(), - mWrapMode ) ); - mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) ); - mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) ); - mScrollMainInternalPositionConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) ); - mScrollMainInternalPositionConstraint.AddSource( Source( self, Actor::Property::SIZE ) ); + mScrollMainInternalPositionConstraint = Constraint::New(self, + Toolkit::ScrollView::Property::SCROLL_POSITION, + InternalPositionConstraint(mRulerX->GetDomain(), + mRulerY->GetDomain(), + mWrapMode)); + mScrollMainInternalPositionConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION)); + mScrollMainInternalPositionConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN)); + mScrollMainInternalPositionConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX)); + mScrollMainInternalPositionConstraint.AddSource(Source(self, Actor::Property::SIZE)); mScrollMainInternalPositionConstraint.Apply(); - mScrollMainInternalDeltaConstraint = Constraint::New( self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint ); - mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) ); - mScrollMainInternalDeltaConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET ) ); + mScrollMainInternalDeltaConstraint = Constraint::New(self, Toolkit::ScrollView::Property::SCROLL_POSITION_DELTA, InternalPositionDeltaConstraint); + mScrollMainInternalDeltaConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION)); + mScrollMainInternalDeltaConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_DOMAIN_OFFSET)); mScrollMainInternalDeltaConstraint.Apply(); - mScrollMainInternalFinalConstraint = Constraint::New( self, Toolkit::ScrollView::Property::SCROLL_FINAL, - InternalFinalConstraint( FinalDefaultAlphaFunction, - FinalDefaultAlphaFunction ) ); - mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) ); - mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_X ) ); - mScrollMainInternalFinalConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::OVERSHOOT_Y ) ); + mScrollMainInternalFinalConstraint = Constraint::New(self, Toolkit::ScrollView::Property::SCROLL_FINAL, InternalFinalConstraint(FinalDefaultAlphaFunction, FinalDefaultAlphaFunction)); + mScrollMainInternalFinalConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION)); + mScrollMainInternalFinalConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::OVERSHOOT_X)); + mScrollMainInternalFinalConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::OVERSHOOT_Y)); mScrollMainInternalFinalConstraint.Apply(); - mScrollMainInternalRelativeConstraint = Constraint::New( self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint ); - mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) ); - mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) ); - mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) ); - mScrollMainInternalRelativeConstraint.AddSource( LocalSource( Actor::Property::SIZE ) ); + mScrollMainInternalRelativeConstraint = Constraint::New(self, Toolkit::Scrollable::Property::SCROLL_RELATIVE_POSITION, InternalRelativePositionConstraint); + mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION)); + mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN)); + mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX)); + mScrollMainInternalRelativeConstraint.AddSource(LocalSource(Actor::Property::SIZE)); mScrollMainInternalRelativeConstraint.Apply(); - mScrollMainInternalDomainConstraint = Constraint::New( self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint ); - mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) ); - mScrollMainInternalDomainConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) ); - mScrollMainInternalDomainConstraint.AddSource( LocalSource( Actor::Property::SIZE ) ); + mScrollMainInternalDomainConstraint = Constraint::New(self, Toolkit::ScrollView::Property::SCROLL_DOMAIN_SIZE, InternalScrollDomainConstraint); + mScrollMainInternalDomainConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MIN)); + mScrollMainInternalDomainConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX)); + mScrollMainInternalDomainConstraint.AddSource(LocalSource(Actor::Property::SIZE)); mScrollMainInternalDomainConstraint.Apply(); - mScrollMainInternalPrePositionMaxConstraint = Constraint::New( self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint ); - mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) ); - mScrollMainInternalPrePositionMaxConstraint.AddSource( LocalSource( Actor::Property::SIZE ) ); + mScrollMainInternalPrePositionMaxConstraint = Constraint::New(self, Toolkit::ScrollView::Property::SCROLL_PRE_POSITION_MAX, InternalPrePositionMaxConstraint); + mScrollMainInternalPrePositionMaxConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::SCROLL_POSITION_MAX)); + mScrollMainInternalPrePositionMaxConstraint.AddSource(LocalSource(Actor::Property::SIZE)); mScrollMainInternalPrePositionMaxConstraint.Apply(); // When panning we want to make sure overshoot values are affected by pre position and post position @@ -2835,27 +2821,27 @@ void ScrollView::UpdateMainInternalConstraint() void ScrollView::SetOvershootConstraintsEnabled(bool enabled) { - Actor self( Self() ); + Actor self(Self()); // remove and reset, it may now be in wrong order with the main internal constraints - if( mScrollMainInternalOvershootXConstraint ) + if(mScrollMainInternalOvershootXConstraint) { mScrollMainInternalOvershootXConstraint.Remove(); mScrollMainInternalOvershootXConstraint.Reset(); mScrollMainInternalOvershootYConstraint.Remove(); mScrollMainInternalOvershootYConstraint.Reset(); } - if( enabled ) + if(enabled) { - mScrollMainInternalOvershootXConstraint= Constraint::New( self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x) ); - mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) ); - mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) ); - mScrollMainInternalOvershootXConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL ) ); + mScrollMainInternalOvershootXConstraint = Constraint::New(self, Toolkit::ScrollView::Property::OVERSHOOT_X, OvershootXConstraint(mMaxOvershoot.x)); + mScrollMainInternalOvershootXConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION)); + mScrollMainInternalOvershootXConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION)); + mScrollMainInternalOvershootXConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::CAN_SCROLL_HORIZONTAL)); mScrollMainInternalOvershootXConstraint.Apply(); - mScrollMainInternalOvershootYConstraint = Constraint::New( self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y) ); - mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_PRE_POSITION ) ); - mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::ScrollView::Property::SCROLL_POSITION ) ); - mScrollMainInternalOvershootYConstraint.AddSource( LocalSource( Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL ) ); + mScrollMainInternalOvershootYConstraint = Constraint::New(self, Toolkit::ScrollView::Property::OVERSHOOT_Y, OvershootYConstraint(mMaxOvershoot.y)); + mScrollMainInternalOvershootYConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_PRE_POSITION)); + mScrollMainInternalOvershootYConstraint.AddSource(LocalSource(Toolkit::ScrollView::Property::SCROLL_POSITION)); + mScrollMainInternalOvershootYConstraint.AddSource(LocalSource(Toolkit::Scrollable::Property::CAN_SCROLL_VERTICAL)); mScrollMainInternalOvershootYConstraint.Apply(); } else @@ -2879,74 +2865,74 @@ void ScrollView::SetInternalConstraints() Constraint constraint; // MoveActor (scrolling) - constraint = Constraint::New( self, Actor::Property::POSITION, MoveActorConstraint ); - constraint.AddSource( Source( self, Toolkit::ScrollView::Property::SCROLL_POSITION ) ); + constraint = Constraint::New(self, Actor::Property::POSITION, MoveActorConstraint); + constraint.AddSource(Source(self, Toolkit::ScrollView::Property::SCROLL_POSITION)); constraint.SetRemoveAction(Constraint::DISCARD); ApplyConstraintToBoundActors(constraint); // WrapActor (wrap functionality) - constraint = Constraint::New( self, Actor::Property::POSITION, WrapActorConstraint ); - constraint.AddSource( LocalSource( Actor::Property::SCALE ) ); - constraint.AddSource( LocalSource( Actor::Property::ANCHOR_POINT ) ); - constraint.AddSource( LocalSource( Actor::Property::SIZE ) ); - constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN ) ); - constraint.AddSource( Source( self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX ) ); - constraint.AddSource( Source( self, Toolkit::ScrollView::Property::WRAP ) ); + constraint = Constraint::New(self, Actor::Property::POSITION, WrapActorConstraint); + constraint.AddSource(LocalSource(Actor::Property::SCALE)); + constraint.AddSource(LocalSource(Actor::Property::ANCHOR_POINT)); + constraint.AddSource(LocalSource(Actor::Property::SIZE)); + constraint.AddSource(Source(self, Toolkit::Scrollable::Property::SCROLL_POSITION_MIN)); + constraint.AddSource(Source(self, Toolkit::Scrollable::Property::SCROLL_POSITION_MAX)); + constraint.AddSource(Source(self, Toolkit::ScrollView::Property::WRAP)); constraint.SetRemoveAction(Constraint::DISCARD); ApplyConstraintToBoundActors(constraint); } -void ScrollView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void ScrollView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast(Dali::BaseHandle(object)); - if( scrollView ) + if(scrollView) { - ScrollView& scrollViewImpl( GetImpl( scrollView ) ); - switch( index ) + ScrollView& scrollViewImpl(GetImpl(scrollView)); + switch(index) { case Toolkit::ScrollView::Property::WRAP_ENABLED: { - scrollViewImpl.SetWrapMode( value.Get() ); + scrollViewImpl.SetWrapMode(value.Get()); break; } case Toolkit::ScrollView::Property::PANNING_ENABLED: { - scrollViewImpl.SetScrollSensitive( value.Get() ); + scrollViewImpl.SetScrollSensitive(value.Get()); break; } case Toolkit::ScrollView::Property::AXIS_AUTO_LOCK_ENABLED: { - scrollViewImpl.SetAxisAutoLock( value.Get() ); + scrollViewImpl.SetAxisAutoLock(value.Get()); break; } case Toolkit::ScrollView::Property::WHEEL_SCROLL_DISTANCE_STEP: { - scrollViewImpl.SetWheelScrollDistanceStep( value.Get() ); + scrollViewImpl.SetWheelScrollDistanceStep(value.Get()); break; } case Toolkit::ScrollView::Property::SCROLL_MODE: { const Property::Map* map = value.GetMap(); - if( map ) + if(map) { - scrollViewImpl.SetScrollMode( *map ); + scrollViewImpl.SetScrollMode(*map); } } } } } -Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index index ) +Property::Value ScrollView::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::ScrollView scrollView = Toolkit::ScrollView::DownCast(Dali::BaseHandle(object)); - if( scrollView ) + if(scrollView) { - ScrollView& scrollViewImpl( GetImpl( scrollView ) ); - switch( index ) + ScrollView& scrollViewImpl(GetImpl(scrollView)); + switch(index) { case Toolkit::ScrollView::Property::WRAP_ENABLED: { @@ -2974,19 +2960,19 @@ Property::Value ScrollView::GetProperty( BaseObject* object, Property::Index ind return value; } -void ScrollView::SetScrollMode( const Property::Map& scrollModeMap ) +void ScrollView::SetScrollMode(const Property::Map& scrollModeMap) { Toolkit::RulerPtr rulerX, rulerY; // Check the scroll mode in the X axis - bool xAxisScrollEnabled = true; - Property::Value* valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled" ); - if( valuePtr && valuePtr->GetType() == Property::BOOLEAN ) + bool xAxisScrollEnabled = true; + Property::Value* valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SCROLL_ENABLED, "xAxisScrollEnabled"); + if(valuePtr && valuePtr->GetType() == Property::BOOLEAN) { - valuePtr->Get( xAxisScrollEnabled ); + valuePtr->Get(xAxisScrollEnabled); } - if( !xAxisScrollEnabled ) + if(!xAxisScrollEnabled) { // Default ruler and disabled rulerX = new Toolkit::DefaultRuler(); @@ -2994,12 +2980,12 @@ void ScrollView::SetScrollMode( const Property::Map& scrollModeMap ) } else { - valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval" ); + valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SNAP_TO_INTERVAL, "xAxisSnapToInterval"); float xAxisSnapToInterval = 0.0f; - if( valuePtr && valuePtr->Get( xAxisSnapToInterval ) ) + if(valuePtr && valuePtr->Get(xAxisSnapToInterval)) { // Fixed ruler and enabled - rulerX = new Toolkit::FixedRuler( xAxisSnapToInterval ); + rulerX = new Toolkit::FixedRuler(xAxisSnapToInterval); } else { @@ -3007,24 +2993,24 @@ void ScrollView::SetScrollMode( const Property::Map& scrollModeMap ) rulerX = new Toolkit::DefaultRuler(); } - valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary" ); + valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::X_AXIS_SCROLL_BOUNDARY, "xAxisScrollBoundary"); float xAxisScrollBoundary = 0.0f; - if( valuePtr && valuePtr->Get( xAxisScrollBoundary ) ) + if(valuePtr && valuePtr->Get(xAxisScrollBoundary)) { // By default ruler domain is disabled unless set - rulerX->SetDomain( Toolkit::RulerDomain( 0, xAxisScrollBoundary, true ) ); + rulerX->SetDomain(Toolkit::RulerDomain(0, xAxisScrollBoundary, true)); } } // Check the scroll mode in the Y axis bool yAxisScrollEnabled = true; - valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled" ); - if( valuePtr && valuePtr->GetType() == Property::BOOLEAN ) + valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SCROLL_ENABLED, "yAxisScrollEnabled"); + if(valuePtr && valuePtr->GetType() == Property::BOOLEAN) { - valuePtr->Get( yAxisScrollEnabled ); + valuePtr->Get(yAxisScrollEnabled); } - if( !yAxisScrollEnabled ) + if(!yAxisScrollEnabled) { // Default ruler and disabled rulerY = new Toolkit::DefaultRuler(); @@ -3032,9 +3018,9 @@ void ScrollView::SetScrollMode( const Property::Map& scrollModeMap ) } else { - valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval" ); + valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SNAP_TO_INTERVAL, "yAxisSnapToInterval"); float yAxisSnapToInterval = 0.0f; - if( valuePtr && valuePtr->Get( yAxisSnapToInterval ) ) + if(valuePtr && valuePtr->Get(yAxisSnapToInterval)) { // Fixed ruler and enabled rulerY = new Toolkit::FixedRuler(yAxisSnapToInterval); @@ -3045,12 +3031,12 @@ void ScrollView::SetScrollMode( const Property::Map& scrollModeMap ) rulerY = new Toolkit::DefaultRuler(); } - valuePtr = scrollModeMap.Find( Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary" ); + valuePtr = scrollModeMap.Find(Toolkit::ScrollMode::Y_AXIS_SCROLL_BOUNDARY, "yAxisScrollBoundary"); float yAxisScrollBoundary = 0.0f; - if( valuePtr && valuePtr->Get( yAxisScrollBoundary ) ) + if(valuePtr && valuePtr->Get(yAxisScrollBoundary)) { // By default ruler domain is disabled unless set - rulerY->SetDomain( Toolkit::RulerDomain( 0, yAxisScrollBoundary, true ) ); + rulerY->SetDomain(Toolkit::RulerDomain(0, yAxisScrollBoundary, true)); } } diff --git a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-page-path-effect-impl.cpp b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-page-path-effect-impl.cpp index 5d2c91b..deced96 100644 --- a/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-page-path-effect-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-page-path-effect-impl.cpp @@ -26,72 +26,68 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - ScrollViewPagePathEffect::ScrollViewPagePathEffect(Path path, const Vector3& forward, Dali::Property::Index inputPropertyIndex, const Vector3& viewPageSize, unsigned int pageCount) -:mPageSize(viewPageSize), - mInputPropertyIndex(inputPropertyIndex), - mPageCount(pageCount) +: mPageSize(viewPageSize), + mInputPropertyIndex(inputPropertyIndex), + mPageCount(pageCount) { //Create path constrainer mPathConstrainer = Dali::PathConstrainer::New(); - mPathConstrainer.SetProperty( PathConstrainer::Property::FORWARD, forward ); + mPathConstrainer.SetProperty(PathConstrainer::Property::FORWARD, forward); Dali::Property::Value pointsProperty = path.GetProperty(Path::Property::POINTS); - mPathConstrainer.SetProperty( PathConstrainer::Property::POINTS, pointsProperty ); + mPathConstrainer.SetProperty(PathConstrainer::Property::POINTS, pointsProperty); pointsProperty = path.GetProperty(Path::Property::CONTROL_POINTS); - mPathConstrainer.SetProperty( PathConstrainer::Property::CONTROL_POINTS, pointsProperty ); + mPathConstrainer.SetProperty(PathConstrainer::Property::CONTROL_POINTS, pointsProperty); //Create linear constrainer - pointsProperty = Property::Value(Property::ARRAY); + pointsProperty = Property::Value(Property::ARRAY); Property::Array* array = pointsProperty.GetArray(); - if( array ) + if(array) { array->PushBack(0.0f); array->PushBack(1.0f); array->PushBack(0.0f); } mLinearConstrainer = Dali::LinearConstrainer::New(); - mLinearConstrainer.SetProperty( LinearConstrainer::Property::VALUE, pointsProperty ); + mLinearConstrainer.SetProperty(LinearConstrainer::Property::VALUE, pointsProperty); } ScrollViewPagePathEffect::~ScrollViewPagePathEffect() { } -void ScrollViewPagePathEffect::ApplyToPage( Actor page, unsigned int pageOrder ) +void ScrollViewPagePathEffect::ApplyToPage(Actor page, unsigned int pageOrder) { - float pageHalfSize = mPageSize.x * 0.5f; - Vector2 range = Vector2( pageHalfSize - (pageHalfSize*pageOrder), -pageHalfSize - (pageHalfSize*pageOrder) ); - Vector2 wrap = Vector2( range.x, -pageHalfSize*(mPageCount-2) + range.y); + float pageHalfSize = mPageSize.x * 0.5f; + Vector2 range = Vector2(pageHalfSize - (pageHalfSize * pageOrder), -pageHalfSize - (pageHalfSize * pageOrder)); + Vector2 wrap = Vector2(range.x, -pageHalfSize * (mPageCount - 2) + range.y); Toolkit::ScrollView scrollView = GetScrollView(); //Position - mPathConstrainer.Apply( Dali::Property( page, Dali::Actor::Property::POSITION ), - Dali::Property( scrollView, mInputPropertyIndex), - range, wrap - ); + mPathConstrainer.Apply(Dali::Property(page, Dali::Actor::Property::POSITION), + Dali::Property(scrollView, mInputPropertyIndex), + range, + wrap); //Rotation - mPathConstrainer.Apply( Dali::Property( page, Dali::Actor::Property::ORIENTATION ), - Dali::Property( scrollView, mInputPropertyIndex ), - range, wrap - ); + mPathConstrainer.Apply(Dali::Property(page, Dali::Actor::Property::ORIENTATION), + Dali::Property(scrollView, mInputPropertyIndex), + range, + wrap); //Alpha - mLinearConstrainer.Apply( Dali::Property( page, Dali::Actor::Property::COLOR_ALPHA ), - Dali::Property( scrollView, mInputPropertyIndex ), - range, wrap - ); - + mLinearConstrainer.Apply(Dali::Property(page, Dali::Actor::Property::COLOR_ALPHA), + Dali::Property(scrollView, mInputPropertyIndex), + range, + wrap); } void ScrollViewPagePathEffect::OnAttach(Toolkit::ScrollView& scrollView) diff --git a/dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp b/dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp index 7077239..609476a 100644 --- a/dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp +++ b/dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp @@ -16,28 +16,24 @@ */ // EXTERNAL INCLUDES -#include // for strcmp -#include #include +#include +#include // for strcmp // INTERNAL INCLUDES -#include #include +#include using namespace Dali; namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { // empty handle as we cannot create Scrollable (but type registered for scroll signal) @@ -45,46 +41,46 @@ BaseHandle Create() } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Scrollable, Toolkit::Control, Create ); - -DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED ) -DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED ) -DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION ) - -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL) -DALI_ANIMATABLE_PROPERTY_REGISTRATION( Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL) - -DALI_SIGNAL_REGISTRATION( Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED ) -DALI_SIGNAL_REGISTRATION( Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED ) -DALI_SIGNAL_REGISTRATION( Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Scrollable, Toolkit::Control, Create); + +DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR) +DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED) +DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED) +DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION) + +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL) +DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL) + +DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED) +DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED) +DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED) DALI_TYPE_REGISTRATION_END() const Vector4 DEFAULT_OVERSHOOT_COLOUR(0.0f, 0.64f, 0.85f, 0.25f); -const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second -const Vector2 OVERSHOOT_DEFAULT_SIZE( 720.0f, 42.0f ); +const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second +const Vector2 OVERSHOOT_DEFAULT_SIZE(720.0f, 42.0f); -} +} // namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Scrollable /////////////////////////////////////////////////////////////////////////////////////////////////// -Scrollable::Scrollable( ControlBehaviour behaviourFlags ) -: Control( ControlBehaviour( behaviourFlags ) ), - mOvershootEffectColor( DEFAULT_OVERSHOOT_COLOUR ), - mOvershootAnimationSpeed ( DEFAULT_OVERSHOOT_ANIMATION_SPEED ), - mOvershootSize( OVERSHOOT_DEFAULT_SIZE ), - mScrollToAlphaFunction( AlphaFunction::EASE_OUT ), +Scrollable::Scrollable(ControlBehaviour behaviourFlags) +: Control(ControlBehaviour(behaviourFlags)), + mOvershootEffectColor(DEFAULT_OVERSHOOT_COLOUR), + mOvershootAnimationSpeed(DEFAULT_OVERSHOOT_ANIMATION_SPEED), + mOvershootSize(OVERSHOOT_DEFAULT_SIZE), + mScrollToAlphaFunction(AlphaFunction::EASE_OUT), mScrollStartedSignal(), mScrollUpdatedSignal(), mScrollCompletedSignal(), @@ -103,10 +99,10 @@ bool Scrollable::AccessibleImpl::IsScrollable() void Scrollable::OnInitialize() { - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::SCROLL_PANE ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE)); + }); } bool Scrollable::IsOvershootEnabled() const @@ -125,7 +121,7 @@ Vector4 Scrollable::GetOvershootEffectColor() const return mOvershootEffectColor; }; -void Scrollable::SetOvershootAnimationSpeed( float pixelsPerSecond ) +void Scrollable::SetOvershootAnimationSpeed(float pixelsPerSecond) { mOvershootAnimationSpeed = pixelsPerSecond; } @@ -155,24 +151,24 @@ Toolkit::Scrollable::ScrollCompletedSignalType& Scrollable::ScrollCompletedSigna return mScrollCompletedSignal; } -bool Scrollable::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool Scrollable::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast( handle ); + bool connected(true); + Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_SCROLL_STARTED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_STARTED)) { - scrollable.ScrollStartedSignal().Connect( tracker, functor ); + scrollable.ScrollStartedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_SCROLL_UPDATED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_UPDATED)) { - scrollable.ScrollUpdatedSignal().Connect( tracker, functor ); + scrollable.ScrollUpdatedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_SCROLL_COMPLETED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_COMPLETED)) { - scrollable.ScrollCompletedSignal().Connect( tracker, functor ); + scrollable.ScrollCompletedSignal().Connect(tracker, functor); } else { @@ -183,43 +179,43 @@ bool Scrollable::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface return connected; } -void Scrollable::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void Scrollable::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); - if( scrollable ) + if(scrollable) { - Scrollable& scrollableImpl( GetImpl( scrollable ) ); - switch( index ) + Scrollable& scrollableImpl(GetImpl(scrollable)); + switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { - scrollableImpl.SetOvershootEffectColor( value.Get() ); + scrollableImpl.SetOvershootEffectColor(value.Get()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { - scrollableImpl.SetOvershootAnimationSpeed( value.Get() ); + scrollableImpl.SetOvershootAnimationSpeed(value.Get()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { - scrollableImpl.SetOvershootEnabled( value.Get() ); + scrollableImpl.SetOvershootEnabled(value.Get()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { - scrollableImpl.SetOvershootSize( value.Get() ); + scrollableImpl.SetOvershootSize(value.Get()); break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { int alphaFunction = value.Get(); - if( alphaFunction >= AlphaFunction::DEFAULT && - alphaFunction < AlphaFunction::COUNT ) + if(alphaFunction >= AlphaFunction::DEFAULT && + alphaFunction < AlphaFunction::COUNT) { - scrollableImpl.mScrollToAlphaFunction = static_cast< AlphaFunction::BuiltinFunction >( alphaFunction ); + scrollableImpl.mScrollToAlphaFunction = static_cast(alphaFunction); } break; } @@ -227,16 +223,16 @@ void Scrollable::SetProperty( BaseObject* object, Property::Index index, const P } } -Property::Value Scrollable::GetProperty( BaseObject* object, Property::Index index ) +Property::Value Scrollable::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); - if( scrollable ) + if(scrollable) { - Scrollable& scrollableImpl( GetImpl( scrollable ) ); - switch( index ) + Scrollable& scrollableImpl(GetImpl(scrollable)); + switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { @@ -260,7 +256,7 @@ Property::Value Scrollable::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { - value = static_cast( scrollableImpl.mScrollToAlphaFunction ); + value = static_cast(scrollableImpl.mScrollToAlphaFunction); break; } } diff --git a/dali-toolkit/internal/controls/shadow-view/shadow-view-impl.cpp b/dali-toolkit/internal/controls/shadow-view/shadow-view-impl.cpp index 3a86588..6440bb0 100644 --- a/dali-toolkit/internal/controls/shadow-view/shadow-view-impl.cpp +++ b/dali-toolkit/internal/controls/shadow-view/shadow-view-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,29 @@ #include "shadow-view-impl.h" // EXTERNAL INCLUDES -#include -#include -#include #include -#include +#include +#include #include +#include #include #include -#include +#include +#include // INTERNAL INCLUDES -#include -#include +#include #include #include #include -#include +#include +#include // TODO: // pixel format / size - set from JSON // aspect ratio property needs to be able to be constrained also for cameras. (now do-able) // default near clip value - ///////////////////////////////////////////////////////// // IMPLEMENTATION NOTES @@ -56,16 +55,12 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - using namespace Dali; BaseHandle Create() @@ -73,26 +68,26 @@ BaseHandle Create() return Toolkit::ShadowView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ShadowView, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ShadowView, Toolkit::Control, Create) DALI_TYPE_REGISTRATION_END() const float BLUR_STRENGTH_DEFAULT = 1.0f; const Vector3 DEFAULT_LIGHT_POSITION(300.0f, 250.0f, 600.0f); -const float DEFAULT_FIELD_OF_VIEW_RADIANS = Math::PI / 4.0f; // 45 degrees +const float DEFAULT_FIELD_OF_VIEW_RADIANS = Math::PI / 4.0f; // 45 degrees const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.8f); const char* const SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME = "uLightCameraProjectionMatrix"; -const char* const SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME = "uLightCameraViewMatrix"; -const char* const SHADER_SHADOW_COLOR_PROPERTY_NAME = "uShadowColor"; -const char* const BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty"; -const char* const SHADOW_COLOR_PROPERTY_NAME = "ShadowColorProperty"; +const char* const SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME = "uLightCameraViewMatrix"; +const char* const SHADER_SHADOW_COLOR_PROPERTY_NAME = "uShadowColor"; +const char* const BLUR_STRENGTH_PROPERTY_NAME = "BlurStrengthProperty"; +const char* const SHADOW_COLOR_PROPERTY_NAME = "ShadowColorProperty"; } // namespace -ShadowView::ShadowView( float downsampleWidthScale, float downsampleHeightScale ) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +ShadowView::ShadowView(float downsampleWidthScale, float downsampleHeightScale) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mChildrenRoot(Actor::New()), mCachedShadowColor(DEFAULT_SHADOW_COLOR), mCachedBackgroundColor(DEFAULT_SHADOW_COLOR.r, DEFAULT_SHADOW_COLOR.g, DEFAULT_SHADOW_COLOR.b, 0.0f), @@ -111,7 +106,7 @@ Toolkit::ShadowView ShadowView::New(float downsampleWidthScale, float downsample { ShadowView* impl = new ShadowView(downsampleWidthScale, downsampleHeightScale); - Dali::Toolkit::ShadowView handle = Dali::Toolkit::ShadowView( *impl ); + Dali::Toolkit::ShadowView handle = Dali::Toolkit::ShadowView(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -125,29 +120,27 @@ void ShadowView::SetShadowPlaneBackground(Actor shadowPlaneBackground) mShadowPlaneBg = shadowPlaneBackground; mShadowPlane = Actor::New(); - mShadowPlane.SetProperty( Actor::Property::NAME, "SHADOW_PLANE" ); - mShadowPlane.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mShadowPlane.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - Renderer shadowRenderer = CreateRenderer( SHADER_SHADOW_VIEW_RENDER_SHADER_VERT, SHADER_SHADOW_VIEW_RENDER_SHADER_FRAG, - Shader::Hint::OUTPUT_IS_TRANSPARENT, - Uint16Pair(20,20) ); - TextureSet textureSet = shadowRenderer.GetTextures(); - textureSet.SetTexture( 0u, mOutputFrameBuffer.GetColorTexture() ); - mShadowPlane.AddRenderer( shadowRenderer ); + mShadowPlane.SetProperty(Actor::Property::NAME, "SHADOW_PLANE"); + mShadowPlane.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mShadowPlane.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + Renderer shadowRenderer = CreateRenderer(SHADER_SHADOW_VIEW_RENDER_SHADER_VERT, SHADER_SHADOW_VIEW_RENDER_SHADER_FRAG, Shader::Hint::OUTPUT_IS_TRANSPARENT, Uint16Pair(20, 20)); + TextureSet textureSet = shadowRenderer.GetTextures(); + textureSet.SetTexture(0u, mOutputFrameBuffer.GetColorTexture()); + mShadowPlane.AddRenderer(shadowRenderer); SetShaderConstants(); // Rather than parent the shadow plane drawable and have constraints to move it to the same // position, instead parent the shadow plane drawable on the shadow plane passed in. - mShadowPlaneBg.Add( mShadowPlane ); - mShadowPlane.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mShadowPlane.SetProperty( Actor::Property::POSITION_Z, 1.0f ); + mShadowPlaneBg.Add(mShadowPlane); + mShadowPlane.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mShadowPlane.SetProperty(Actor::Property::POSITION_Z, 1.0f); ConstrainCamera(); - mShadowPlane.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mShadowPlane.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); - mBlurRootActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mBlurRootActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); } void ShadowView::SetPointLight(Actor pointLight) @@ -164,24 +157,24 @@ void ShadowView::SetPointLightFieldOfView(float fieldOfView) void ShadowView::SetShadowColor(Vector4 color) { - mCachedShadowColor = color; + mCachedShadowColor = color; mCachedBackgroundColor.r = color.r; mCachedBackgroundColor.g = color.g; mCachedBackgroundColor.b = color.b; - if( mShadowPlane ) + if(mShadowPlane) { - mShadowPlane.SetProperty( mShadowColorPropertyIndex, mCachedShadowColor ); + mShadowPlane.SetProperty(mShadowColorPropertyIndex, mCachedShadowColor); } if(mRenderSceneTask) { - mRenderSceneTask.SetClearColor( mCachedBackgroundColor ); + mRenderSceneTask.SetClearColor(mCachedBackgroundColor); } } void ShadowView::Activate() { - DALI_ASSERT_ALWAYS( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && "ShadowView should be on stage before calling Activate()\n" ); + DALI_ASSERT_ALWAYS(Self().GetProperty(Actor::Property::CONNECTED_TO_SCENE) && "ShadowView should be on stage before calling Activate()\n"); // make sure resources are allocated and start the render tasks processing CreateRenderTasks(); @@ -189,7 +182,7 @@ void ShadowView::Activate() void ShadowView::Deactivate() { - DALI_ASSERT_ALWAYS( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) && "ShadowView should be on stage before calling Deactivate()\n" ) + DALI_ASSERT_ALWAYS(Self().GetProperty(Actor::Property::CONNECTED_TO_SCENE) && "ShadowView should be on stage before calling Deactivate()\n") // stop render tasks processing // Note: render target resources are automatically freed since we set the Image::Unused flag @@ -204,52 +197,52 @@ void ShadowView::Deactivate() void ShadowView::OnInitialize() { // root actor to parent all user added actors. Used as source actor for shadow render task. - mChildrenRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mChildrenRoot.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mChildrenRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mChildrenRoot.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); Vector2 stageSize = Stage::GetCurrent().GetSize(); - mCameraActor = CameraActor::New(stageSize); + mCameraActor = CameraActor::New(stageSize); - mCameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // Target is constrained to point at the shadow plane origin - mCameraActor.SetNearClippingPlane( 1.0f ); - mCameraActor.SetType( Dali::Camera::FREE_LOOK ); // Camera orientation constrained to point at shadow plane world position - mCameraActor.SetProperty( Actor::Property::ORIENTATION, Quaternion(Radian(Degree(180)), Vector3::YAXIS) ); - mCameraActor.SetProperty( Actor::Property::POSITION, DEFAULT_LIGHT_POSITION ); + mCameraActor.SetNearClippingPlane(1.0f); + mCameraActor.SetType(Dali::Camera::FREE_LOOK); // Camera orientation constrained to point at shadow plane world position + mCameraActor.SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(Degree(180)), Vector3::YAXIS)); + mCameraActor.SetProperty(Actor::Property::POSITION, DEFAULT_LIGHT_POSITION); // Create render targets needed for rendering from light's point of view - mSceneFromLightRenderTarget = FrameBuffer::New( stageSize.width, stageSize.height, FrameBuffer::Attachment::NONE ); - Texture textureFromLight = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width), unsigned(stageSize.height) ); - mSceneFromLightRenderTarget.AttachColorTexture( textureFromLight ); + mSceneFromLightRenderTarget = FrameBuffer::New(stageSize.width, stageSize.height, FrameBuffer::Attachment::NONE); + Texture textureFromLight = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width), unsigned(stageSize.height)); + mSceneFromLightRenderTarget.AttachColorTexture(textureFromLight); - mOutputFrameBuffer = FrameBuffer::New( stageSize.width * 0.5f, stageSize.height * 0.5f, FrameBuffer::Attachment::NONE ); - Texture outputTexture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width * 0.5f), unsigned(stageSize.height * 0.5f) ); - mOutputFrameBuffer.AttachColorTexture( outputTexture ); + mOutputFrameBuffer = FrameBuffer::New(stageSize.width * 0.5f, stageSize.height * 0.5f, FrameBuffer::Attachment::NONE); + Texture outputTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, unsigned(stageSize.width * 0.5f), unsigned(stageSize.height * 0.5f)); + mOutputFrameBuffer.AttachColorTexture(outputTexture); ////////////////////////////////////////////////////// // Connect to actor tree - Self().Add( mChildrenRoot ); - Stage::GetCurrent().Add( mCameraActor ); + Self().Add(mChildrenRoot); + Stage::GetCurrent().Add(mCameraActor); - mBlurFilter.SetRefreshOnDemand( false ); - mBlurFilter.SetInputTexture( mSceneFromLightRenderTarget.GetColorTexture() ); - mBlurFilter.SetOutputFrameBuffer( mOutputFrameBuffer ); - mBlurFilter.SetSize( stageSize * 0.5f ); - mBlurFilter.SetPixelFormat( Pixel::RGBA8888 ); + mBlurFilter.SetRefreshOnDemand(false); + mBlurFilter.SetInputTexture(mSceneFromLightRenderTarget.GetColorTexture()); + mBlurFilter.SetOutputFrameBuffer(mOutputFrameBuffer); + mBlurFilter.SetSize(stageSize * 0.5f); + mBlurFilter.SetPixelFormat(Pixel::RGBA8888); mBlurRootActor = Actor::New(); - mBlurRootActor.SetProperty( Actor::Property::NAME, "BLUR_ROOT_ACTOR" ); + mBlurRootActor.SetProperty(Actor::Property::NAME, "BLUR_ROOT_ACTOR"); // Turn off inheritance to ensure filter renders properly - mBlurRootActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mBlurRootActor.SetProperty( Actor::Property::INHERIT_POSITION, false ); - mBlurRootActor.SetProperty( Actor::Property::INHERIT_ORIENTATION, false ); - mBlurRootActor.SetProperty( Actor::Property::INHERIT_SCALE, false ); - mBlurRootActor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_COLOR ); + mBlurRootActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mBlurRootActor.SetProperty(Actor::Property::INHERIT_POSITION, false); + mBlurRootActor.SetProperty(Actor::Property::INHERIT_ORIENTATION, false); + mBlurRootActor.SetProperty(Actor::Property::INHERIT_SCALE, false); + mBlurRootActor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_COLOR); - Self().Add( mBlurRootActor ); + Self().Add(mBlurRootActor); mBlurFilter.SetRootActor(mBlurRootActor); mBlurFilter.SetBackgroundColor(Vector4::ZERO); @@ -258,48 +251,48 @@ void ShadowView::OnInitialize() // Register a property that the user can use to control the blur in the internal object mBlurStrengthPropertyIndex = self.RegisterProperty(BLUR_STRENGTH_PROPERTY_NAME, BLUR_STRENGTH_DEFAULT); - Constraint blurStrengthConstraint = Constraint::New( mBlurFilter.GetHandleForAnimateBlurStrength(), mBlurFilter.GetBlurStrengthPropertyIndex(), EqualToConstraint() ); - blurStrengthConstraint.AddSource( Source( self, mBlurStrengthPropertyIndex) ); + Constraint blurStrengthConstraint = Constraint::New(mBlurFilter.GetHandleForAnimateBlurStrength(), mBlurFilter.GetBlurStrengthPropertyIndex(), EqualToConstraint()); + blurStrengthConstraint.AddSource(Source(self, mBlurStrengthPropertyIndex)); blurStrengthConstraint.Apply(); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } -void ShadowView::OnChildAdd( Actor& child ) +void ShadowView::OnChildAdd(Actor& child) { - if( child != mChildrenRoot && child != mBlurRootActor) + if(child != mChildrenRoot && child != mBlurRootActor) { - mChildrenRoot.Add( child ); + mChildrenRoot.Add(child); } - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void ShadowView::OnChildRemove( Actor& child ) +void ShadowView::OnChildRemove(Actor& child) { - mChildrenRoot.Remove( child ); + mChildrenRoot.Remove(child); - Control::OnChildRemove( child ); + Control::OnChildRemove(child); } void ShadowView::ConstrainCamera() { - if( mPointLight && mShadowPlane ) + if(mPointLight && mShadowPlane) { // Constrain camera to look directly at center of shadow plane. (mPointLight position // is under control of application, can't use transform inheritance) - Constraint cameraOrientationConstraint = Constraint::New ( mCameraActor, Actor::Property::ORIENTATION, &LookAt ); - cameraOrientationConstraint.AddSource( Source( mShadowPlane, Actor::Property::WORLD_POSITION ) ); - cameraOrientationConstraint.AddSource( Source( mPointLight, Actor::Property::WORLD_POSITION ) ); - cameraOrientationConstraint.AddSource( Source( mShadowPlane, Actor::Property::WORLD_ORIENTATION ) ); + Constraint cameraOrientationConstraint = Constraint::New(mCameraActor, Actor::Property::ORIENTATION, &LookAt); + cameraOrientationConstraint.AddSource(Source(mShadowPlane, Actor::Property::WORLD_POSITION)); + cameraOrientationConstraint.AddSource(Source(mPointLight, Actor::Property::WORLD_POSITION)); + cameraOrientationConstraint.AddSource(Source(mShadowPlane, Actor::Property::WORLD_ORIENTATION)); cameraOrientationConstraint.Apply(); - Constraint pointLightPositionConstraint = Constraint::New( mCameraActor, Actor::Property::POSITION, EqualToConstraint() ); - pointLightPositionConstraint.AddSource( Source( mPointLight, Actor::Property::WORLD_POSITION ) ); + Constraint pointLightPositionConstraint = Constraint::New(mCameraActor, Actor::Property::POSITION, EqualToConstraint()); + pointLightPositionConstraint.AddSource(Source(mPointLight, Actor::Property::WORLD_POSITION)); pointLightPositionConstraint.Apply(); } } @@ -311,16 +304,16 @@ void ShadowView::CreateRenderTasks() // We want the first task to render the scene from the light mRenderSceneTask = taskList.CreateTask(); - mRenderSceneTask.SetCameraActor( mCameraActor ); - mRenderSceneTask.SetSourceActor( mChildrenRoot ); - mRenderSceneTask.SetFrameBuffer( mSceneFromLightRenderTarget ); - mRenderSceneTask.SetInputEnabled( false ); - mRenderSceneTask.SetClearEnabled( true ); + mRenderSceneTask.SetCameraActor(mCameraActor); + mRenderSceneTask.SetSourceActor(mChildrenRoot); + mRenderSceneTask.SetFrameBuffer(mSceneFromLightRenderTarget); + mRenderSceneTask.SetInputEnabled(false); + mRenderSceneTask.SetClearEnabled(true); // background color for render task should be the shadow color, but with alpha 0 // we don't want to blend the edges of the content with a BLACK at alpha 0, but // the same shadow color at alpha 0. - mRenderSceneTask.SetClearColor( mCachedBackgroundColor ); + mRenderSceneTask.SetClearColor(mCachedBackgroundColor); mBlurFilter.Enable(); } @@ -337,17 +330,17 @@ void ShadowView::RemoveRenderTasks() void ShadowView::SetShaderConstants() { - Property::Index lightCameraProjectionMatrixPropertyIndex = mShadowPlane.RegisterProperty( SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME, Matrix::IDENTITY ); - Constraint projectionMatrixConstraint = Constraint::New( mShadowPlane, lightCameraProjectionMatrixPropertyIndex, EqualToConstraint() ); - projectionMatrixConstraint.AddSource( Source( mCameraActor, CameraActor::Property::PROJECTION_MATRIX ) ); + Property::Index lightCameraProjectionMatrixPropertyIndex = mShadowPlane.RegisterProperty(SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME, Matrix::IDENTITY); + Constraint projectionMatrixConstraint = Constraint::New(mShadowPlane, lightCameraProjectionMatrixPropertyIndex, EqualToConstraint()); + projectionMatrixConstraint.AddSource(Source(mCameraActor, CameraActor::Property::PROJECTION_MATRIX)); projectionMatrixConstraint.Apply(); - Property::Index lightCameraViewMatrixPropertyIndex = mShadowPlane.RegisterProperty( SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME, Matrix::IDENTITY ); - Constraint viewMatrixConstraint = Constraint::New( mShadowPlane, lightCameraViewMatrixPropertyIndex, EqualToConstraint() ); - viewMatrixConstraint.AddSource( Source( mCameraActor, CameraActor::Property::VIEW_MATRIX ) ); + Property::Index lightCameraViewMatrixPropertyIndex = mShadowPlane.RegisterProperty(SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME, Matrix::IDENTITY); + Constraint viewMatrixConstraint = Constraint::New(mShadowPlane, lightCameraViewMatrixPropertyIndex, EqualToConstraint()); + viewMatrixConstraint.AddSource(Source(mCameraActor, CameraActor::Property::VIEW_MATRIX)); viewMatrixConstraint.Apply(); - mShadowColorPropertyIndex = mShadowPlane.RegisterProperty( SHADER_SHADOW_COLOR_PROPERTY_NAME, mCachedShadowColor ); + mShadowColorPropertyIndex = mShadowPlane.RegisterProperty(SHADER_SHADOW_COLOR_PROPERTY_NAME, mCachedShadowColor); } } // namespace Internal diff --git a/dali-toolkit/internal/controls/slider/slider-impl.cpp b/dali-toolkit/internal/controls/slider/slider-impl.cpp index e2dc5e3..6829485 100644 --- a/dali-toolkit/internal/controls/slider/slider-impl.cpp +++ b/dali-toolkit/internal/controls/slider/slider-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,99 +19,97 @@ #include // EXTERNAL INCLUDES -#include // for strcmp -#include -#include #include -#include #include +#include +#include // for strcmp +#include +#include // INTERNAL INCLUDES #include -#include #include #include +#include using namespace Dali; namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // Unnamed namespace { - BaseHandle Create() { return Dali::Toolkit::Slider::New(); } +// clang-format off // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Slider, Toolkit::Control, Create ) - -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "lowerBound", FLOAT, LOWER_BOUND ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "upperBound", FLOAT, UPPER_BOUND ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "value", FLOAT, VALUE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "trackVisual", MAP, TRACK_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "handleVisual", MAP, HANDLE_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "progressVisual", MAP, PROGRESS_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "popupVisual", MAP, POPUP_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "popupArrowVisual", MAP, POPUP_ARROW_VISUAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "disabledColor", VECTOR4, DISABLED_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "valuePrecision", INTEGER, VALUE_PRECISION ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "showPopup", BOOLEAN, SHOW_POPUP ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "showValue", BOOLEAN, SHOW_VALUE ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "marks", ARRAY, MARKS ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "snapToMarks", BOOLEAN, SNAP_TO_MARKS ) -DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "markTolerance", FLOAT, MARK_TOLERANCE ) - -DALI_SIGNAL_REGISTRATION( Toolkit, Slider, "valueChanged", SIGNAL_VALUE_CHANGED ) -DALI_SIGNAL_REGISTRATION( Toolkit, Slider, "mark", SIGNAL_MARK ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Slider, Toolkit::Control, Create ) + +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "lowerBound", FLOAT, LOWER_BOUND ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "upperBound", FLOAT, UPPER_BOUND ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "value", FLOAT, VALUE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "trackVisual", MAP, TRACK_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "handleVisual", MAP, HANDLE_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "progressVisual", MAP, PROGRESS_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "popupVisual", MAP, POPUP_VISUAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "popupArrowVisual", MAP, POPUP_ARROW_VISUAL) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "disabledColor", VECTOR4, DISABLED_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "valuePrecision", INTEGER, VALUE_PRECISION ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "showPopup", BOOLEAN, SHOW_POPUP ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "showValue", BOOLEAN, SHOW_VALUE ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "marks", ARRAY, MARKS ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "snapToMarks", BOOLEAN, SNAP_TO_MARKS ) +DALI_PROPERTY_REGISTRATION(Toolkit, Slider, "markTolerance", FLOAT, MARK_TOLERANCE ) + +DALI_SIGNAL_REGISTRATION(Toolkit, Slider, "valueChanged", SIGNAL_VALUE_CHANGED) +DALI_SIGNAL_REGISTRATION(Toolkit, Slider, "mark", SIGNAL_MARK ) DALI_TYPE_REGISTRATION_END() +// clang-format on const float MARK_SNAP_TOLERANCE = 0.05f; // 5% of slider width -const int VALUE_VIEW_SHOW_DURATION = 1000; // millisec -const int VALUE_VIEW_SHOW_DURATION_LONG = 2000; // millisec +const int VALUE_VIEW_SHOW_DURATION = 1000; // millisec +const int VALUE_VIEW_SHOW_DURATION_LONG = 2000; // millisec const float VALUE_VERTICAL_OFFSET = 48.0f; -const float DEFAULT_WIDTH = 0.0f; -const float DEFAULT_HEIGHT = 27.0f; -const float DEFAULT_HIT_HEIGHT = 72.0f; +const float DEFAULT_WIDTH = 0.0f; +const float DEFAULT_HEIGHT = 27.0f; +const float DEFAULT_HIT_HEIGHT = 72.0f; const float DEFAULT_HANDLE_HEIGHT = DEFAULT_HIT_HEIGHT; -const float POPUP_TEXT_PADDING = 10.0f; +const float POPUP_TEXT_PADDING = 10.0f; -const char* SKINNED_TRACK_VISUAL_FILE_NAME = "slider-skin.9.png"; -const char* SKINNED_HANDLE_VISUAL_FILE_NAME = "slider-skin-handle.png"; -const char* SKINNED_PROGRESS_VISUAL_FILE_NAME = "slider-skin-progress.9.png"; -const char* SKINNED_POPUP_VISUAL_FILE_NAME = "slider-popup.9.png"; +const char* SKINNED_TRACK_VISUAL_FILE_NAME = "slider-skin.9.png"; +const char* SKINNED_HANDLE_VISUAL_FILE_NAME = "slider-skin-handle.png"; +const char* SKINNED_PROGRESS_VISUAL_FILE_NAME = "slider-skin-progress.9.png"; +const char* SKINNED_POPUP_VISUAL_FILE_NAME = "slider-popup.9.png"; const char* SKINNED_POPUP_ARROW_VISUAL_FILE_NAME = "slider-popup-arrow.png"; -const Vector2 DEFAULT_HIT_REGION( DEFAULT_WIDTH, DEFAULT_HIT_HEIGHT ); -const Vector2 DEFAULT_TRACK_REGION( DEFAULT_WIDTH, DEFAULT_HEIGHT ); -const Vector2 DEFAULT_HANDLE_SIZE( DEFAULT_HANDLE_HEIGHT, DEFAULT_HANDLE_HEIGHT ); +const Vector2 DEFAULT_HIT_REGION(DEFAULT_WIDTH, DEFAULT_HIT_HEIGHT); +const Vector2 DEFAULT_TRACK_REGION(DEFAULT_WIDTH, DEFAULT_HEIGHT); +const Vector2 DEFAULT_HANDLE_SIZE(DEFAULT_HANDLE_HEIGHT, DEFAULT_HANDLE_HEIGHT); -const Vector4 DEFAULT_DISABLED_COLOR( 0.5f, 0.5f, 0.5f, 1.0f ); +const Vector4 DEFAULT_DISABLED_COLOR(0.5f, 0.5f, 0.5f, 1.0f); -const float VALUE_POPUP_MARGIN = 10.0f; -const float VALUE_POPUP_HEIGHT = 81.0f; +const float VALUE_POPUP_MARGIN = 10.0f; +const float VALUE_POPUP_HEIGHT = 81.0f; const float VALUE_POPUP_MIN_WIDTH = 54.0f; -const float DEFAULT_LOWER_BOUND = 0.0f; -const float DEFAULT_UPPER_BOUND = 1.0f; -const float DEFAULT_VALUE = 0.0f; -const int DEFAULT_VALUE_PRECISION = 0; -const bool DEFAULT_SHOW_POPUP = false; -const bool DEFAULT_SHOW_VALUE = true; -const bool DEFAULT_ENABLED = true; -const bool DEFAULT_SNAP_TO_MARKS = false; +const float DEFAULT_LOWER_BOUND = 0.0f; +const float DEFAULT_UPPER_BOUND = 1.0f; +const float DEFAULT_VALUE = 0.0f; +const int DEFAULT_VALUE_PRECISION = 0; +const bool DEFAULT_SHOW_POPUP = false; +const bool DEFAULT_SHOW_VALUE = true; +const bool DEFAULT_ENABLED = true; +const bool DEFAULT_SNAP_TO_MARKS = false; } // Unnamed namespace @@ -122,10 +120,10 @@ const bool DEFAULT_SNAP_TO_MARKS = false; Dali::Toolkit::Slider Slider::New() { // Create the implementation - SliderPtr slider( new Slider() ); + SliderPtr slider(new Slider()); // Pass ownership to CustomActor via derived handle - Dali::Toolkit::Slider handle( *slider ); + Dali::Toolkit::Slider handle(*slider); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -135,8 +133,8 @@ Dali::Toolkit::Slider Slider::New() } Slider::Slider() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mState( NORMAL ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mState(NORMAL), mPopupVisual(""), mPopupArrowVisual(""), mTrackVisual(""), @@ -146,18 +144,18 @@ Slider::Slider() mTrackMap(), mHandleMap(), mPopupArrowMap(), - mDisabledColor( 0.0f, 0.0f, 0.0f, 0.0f ), - mHitRegion( 0.0f, 0.0f ), - mTrackRegion( 0.0f, 0.0f ), - mHandleSize( 0.0f, 0.0f ), - mLowerBound( 0.0f ), - mUpperBound( 0.0f ), - mValue( 0.0f ), - mMarkTolerance( 0.0f ), - mValuePrecision( 0 ), - mShowPopup( false ), - mShowValue( false ), - mSnapToMarks( false ) + mDisabledColor(0.0f, 0.0f, 0.0f, 0.0f), + mHitRegion(0.0f, 0.0f), + mTrackRegion(0.0f, 0.0f), + mHandleSize(0.0f, 0.0f), + mLowerBound(0.0f), + mUpperBound(0.0f), + mValue(0.0f), + mMarkTolerance(0.0f), + mValuePrecision(0), + mShowPopup(false), + mShowValue(false), + mSnapToMarks(false) { } @@ -173,77 +171,77 @@ void Slider::OnInitialize() // Properties Actor self = Self(); - SetHitRegion( DEFAULT_HIT_REGION ); - SetTrackRegion( DEFAULT_TRACK_REGION ); - SetHandleSize( DEFAULT_HANDLE_SIZE ); + SetHitRegion(DEFAULT_HIT_REGION); + SetTrackRegion(DEFAULT_TRACK_REGION); + SetHandleSize(DEFAULT_HANDLE_SIZE); const std::string imageDirPath = AssetManager::GetDaliImagePath(); - SetTrackVisual( imageDirPath + SKINNED_TRACK_VISUAL_FILE_NAME ); - SetHandleVisual( imageDirPath + SKINNED_HANDLE_VISUAL_FILE_NAME ); - SetProgressVisual( imageDirPath + SKINNED_PROGRESS_VISUAL_FILE_NAME ); - SetPopupVisual( imageDirPath + SKINNED_POPUP_VISUAL_FILE_NAME ); - SetPopupArrowVisual( imageDirPath + SKINNED_POPUP_ARROW_VISUAL_FILE_NAME ); + SetTrackVisual(imageDirPath + SKINNED_TRACK_VISUAL_FILE_NAME); + SetHandleVisual(imageDirPath + SKINNED_HANDLE_VISUAL_FILE_NAME); + SetProgressVisual(imageDirPath + SKINNED_PROGRESS_VISUAL_FILE_NAME); + SetPopupVisual(imageDirPath + SKINNED_POPUP_VISUAL_FILE_NAME); + SetPopupArrowVisual(imageDirPath + SKINNED_POPUP_ARROW_VISUAL_FILE_NAME); - SetShowPopup( DEFAULT_SHOW_POPUP ); - SetShowValue( DEFAULT_SHOW_VALUE ); + SetShowPopup(DEFAULT_SHOW_POPUP); + SetShowValue(DEFAULT_SHOW_VALUE); - SetEnabled( DEFAULT_ENABLED ); - SetDisabledColor( DEFAULT_DISABLED_COLOR ); + SetEnabled(DEFAULT_ENABLED); + SetDisabledColor(DEFAULT_DISABLED_COLOR); - SetSnapToMarks( DEFAULT_SNAP_TO_MARKS ); - SetMarkTolerance( MARK_SNAP_TOLERANCE ); + SetSnapToMarks(DEFAULT_SNAP_TO_MARKS); + SetMarkTolerance(MARK_SNAP_TOLERANCE); - SetLowerBound( DEFAULT_LOWER_BOUND ); - SetUpperBound( DEFAULT_UPPER_BOUND ); + SetLowerBound(DEFAULT_LOWER_BOUND); + SetUpperBound(DEFAULT_UPPER_BOUND); UpdateSkin(); - SetValuePrecision( DEFAULT_VALUE_PRECISION ); + SetValuePrecision(DEFAULT_VALUE_PRECISION); mValue = DEFAULT_VALUE; - DisplayValue( mValue, false ); // Run this last to display the correct value + DisplayValue(mValue, false); // Run this last to display the correct value // Size the Slider actor to a default - self.SetProperty( Actor::Property::SIZE, Vector2( DEFAULT_HIT_REGION.x, DEFAULT_HIT_REGION.y ) ); + self.SetProperty(Actor::Property::SIZE, Vector2(DEFAULT_HIT_REGION.x, DEFAULT_HIT_REGION.y)); // Set the Slider to be highlightable in Screen Reader mode - self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); // Connect to the touch signal - self.TouchedSignal().Connect( this, &Slider::OnTouch ); + self.TouchedSignal().Connect(this, &Slider::OnTouch); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::SLIDER ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::SLIDER)); + }); } -void Slider::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void Slider::OnRelayout(const Vector2& size, RelayoutContainer& container) { - SetHitRegion( Vector2( size.x, GetHitRegion().y ) ); + SetHitRegion(Vector2(size.x, GetHitRegion().y)); // Factor in handle overshoot into size of backing - SetTrackRegion( Vector2( size.x - GetHandleSize().x, GetTrackRegion().y ) ); - Control::OnRelayout( size, container ); + SetTrackRegion(Vector2(size.x - GetHandleSize().x, GetTrackRegion().y)); + Control::OnRelayout(size, container); } bool Slider::OnTouch(Actor actor, const TouchEvent& touch) { - if( mState != DISABLED ) + if(mState != DISABLED) { const PointState::Type touchState = touch.GetState(0); - if( touchState == PointState::DOWN ) + if(touchState == PointState::DOWN) { mState = PRESSED; - float percentage = MapPercentage( touch.GetLocalPosition( 0 ) ); - float value = MapBounds( ( GetSnapToMarks() ) ? SnapToMark( percentage ) : MarkFilter( percentage ), GetLowerBound(), GetUpperBound() ); - SetValue( value ); - DisplayPopup( value ); + float percentage = MapPercentage(touch.GetLocalPosition(0)); + float value = MapBounds((GetSnapToMarks()) ? SnapToMark(percentage) : MarkFilter(percentage), GetLowerBound(), GetUpperBound()); + SetValue(value); + DisplayPopup(value); } - else if( touchState == PointState::UP ) + else if(touchState == PointState::UP) { - if( mState == PRESSED ) + if(mState == PRESSED) { mState = NORMAL; - mSlidingFinishedSignal.Emit( Toolkit::Slider::DownCast( Self() ), GetValue() ); + mSlidingFinishedSignal.Emit(Toolkit::Slider::DownCast(Self()), GetValue()); } } } @@ -251,34 +249,34 @@ bool Slider::OnTouch(Actor actor, const TouchEvent& touch) return false; } -void Slider::OnPan( Actor actor, const PanGesture& gesture ) +void Slider::OnPan(Actor actor, const PanGesture& gesture) { // gesture.position is in local actor coordinates - if( mState != DISABLED ) + if(mState != DISABLED) { - switch( gesture.GetState() ) + switch(gesture.GetState()) { case GestureState::CONTINUING: { - if( mState == PRESSED ) + if(mState == PRESSED) { - float value = MapBounds( MarkFilter ( MapPercentage( gesture.GetPosition() ) ), GetLowerBound(), GetUpperBound() ); - SetValue( value ); - DisplayPopup( value ); + float value = MapBounds(MarkFilter(MapPercentage(gesture.GetPosition())), GetLowerBound(), GetUpperBound()); + SetValue(value); + DisplayPopup(value); } break; } case GestureState::FINISHED: { - if( mState == PRESSED ) + if(mState == PRESSED) { - if( GetSnapToMarks() ) + if(GetSnapToMarks()) { - float value = MapBounds( SnapToMark( MapPercentage( gesture.GetPosition() ) ), GetLowerBound(), GetUpperBound() ); - SetValue( value ); - DisplayPopup( value ); + float value = MapBounds(SnapToMark(MapPercentage(gesture.GetPosition())), GetLowerBound(), GetUpperBound()); + SetValue(value); + DisplayPopup(value); } - mSlidingFinishedSignal.Emit( Toolkit::Slider::DownCast( Self() ), GetValue() ); + mSlidingFinishedSignal.Emit(Toolkit::Slider::DownCast(Self()), GetValue()); } mState = NORMAL; @@ -292,79 +290,79 @@ void Slider::OnPan( Actor actor, const PanGesture& gesture ) } } -float Slider::HitSpaceToDomain( float x ) +float Slider::HitSpaceToDomain(float x) { float halfRegionWidth = GetHitRegion().x * 0.5f; - float halfDomainWidth = ( mDomain.to.x - mDomain.from.x ) * 0.5f; - float endDiff = halfRegionWidth - halfDomainWidth; + float halfDomainWidth = (mDomain.to.x - mDomain.from.x) * 0.5f; + float endDiff = halfRegionWidth - halfDomainWidth; return x - endDiff; } -float Slider::MapPercentage( const Vector2& point ) +float Slider::MapPercentage(const Vector2& point) { - return Clamp( ( HitSpaceToDomain( point.x ) - mDomain.from.x ) / ( mDomain.to.x - mDomain.from.x ), 0.0f, 1.0f ); + return Clamp((HitSpaceToDomain(point.x) - mDomain.from.x) / (mDomain.to.x - mDomain.from.x), 0.0f, 1.0f); } -float Slider::MapValuePercentage( float value ) +float Slider::MapValuePercentage(float value) { - return ( value - GetLowerBound() ) / ( GetUpperBound() - GetLowerBound() ); + return (value - GetLowerBound()) / (GetUpperBound() - GetLowerBound()); } -float Slider::MapBounds( float percent, float lowerBound, float upperBound ) +float Slider::MapBounds(float percent, float lowerBound, float upperBound) { - return lowerBound + percent * ( upperBound - lowerBound ); + return lowerBound + percent * (upperBound - lowerBound); } -Slider::Domain Slider::CalcDomain( const Vector2& currentSize ) +Slider::Domain Slider::CalcDomain(const Vector2& currentSize) { - return Domain( Vector2( 0.0f, 0.0f ), currentSize ); + return Domain(Vector2(0.0f, 0.0f), currentSize); } -void Slider::DisplayValue( float value, bool raiseSignals ) +void Slider::DisplayValue(float value, bool raiseSignals) { - float clampedValue = Clamp( value, GetLowerBound(), GetUpperBound() ); + float clampedValue = Clamp(value, GetLowerBound(), GetUpperBound()); - float percent = MapValuePercentage( clampedValue ); + float percent = MapValuePercentage(clampedValue); - float x = mDomain.from.x + percent * ( mDomain.to.x - mDomain.from.x ); + float x = mDomain.from.x + percent * (mDomain.to.x - mDomain.from.x); - mHandle.SetProperty( Actor::Property::POSITION_X, x ); + mHandle.SetProperty(Actor::Property::POSITION_X, x); // Progress bar - if( mProgress ) + if(mProgress) { - mProgress.SetProperty( Actor::Property::SIZE, Vector2( x, GetTrackRegion().y ) ); + mProgress.SetProperty(Actor::Property::SIZE, Vector2(x, GetTrackRegion().y)); } // Signals - if( raiseSignals ) + if(raiseSignals) { - Toolkit::Slider self = Toolkit::Slider::DownCast( Self() ); - mValueChangedSignal.Emit( self, clampedValue ); + Toolkit::Slider self = Toolkit::Slider::DownCast(Self()); + mValueChangedSignal.Emit(self, clampedValue); int markIndex; - if( MarkReached( percent, markIndex ) ) + if(MarkReached(percent, markIndex)) { - mMarkReachedSignal.Emit( self, markIndex ); + mMarkReachedSignal.Emit(self, markIndex); } } - if( mHandleValueTextLabel ) + if(mHandleValueTextLabel) { std::stringstream ss; - ss.precision( GetValuePrecision() ); + ss.precision(GetValuePrecision()); ss << std::fixed << clampedValue; - std::string label = mHandleValueTextLabel.GetProperty( Toolkit::TextLabel::Property::TEXT ); - if( label.compare(ss.str()) ) + std::string label = mHandleValueTextLabel.GetProperty(Toolkit::TextLabel::Property::TEXT); + if(label.compare(ss.str())) { - mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::TEXT, ss.str() ); + mHandleValueTextLabel.SetProperty(Toolkit::TextLabel::Property::TEXT, ss.str()); } } } -void Slider::SetMarks( const MarkList& marks ) +void Slider::SetMarks(const MarkList& marks) { mMarks = marks; } @@ -374,7 +372,7 @@ const Slider::MarkList& Slider::GetMarks() const return mMarks; } -void Slider::SetSnapToMarks( bool snap ) +void Slider::SetSnapToMarks(bool snap) { mSnapToMarks = snap; } @@ -387,9 +385,9 @@ bool Slider::GetSnapToMarks() const Actor Slider::CreateHitRegion() { Actor hitRegion = Actor::New(); - hitRegion.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - hitRegion.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - hitRegion.TouchedSignal().Connect( this, &Slider::OnTouch ); + hitRegion.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + hitRegion.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + hitRegion.TouchedSignal().Connect(this, &Slider::OnTouch); return hitRegion; } @@ -397,56 +395,56 @@ Actor Slider::CreateHitRegion() Toolkit::ImageView Slider::CreateTrack() { Toolkit::ImageView track = Toolkit::ImageView::New(); - track.SetProperty( Dali::Actor::Property::NAME,"SliderTrack"); - track.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - track.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + track.SetProperty(Dali::Actor::Property::NAME, "SliderTrack"); + track.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + track.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); return track; } -void Slider::SetTrackVisual( const std::string& filename ) +void Slider::SetTrackVisual(const std::string& filename) { - if( mHandle && ( filename.size() > 0 ) ) + if(mHandle && (filename.size() > 0)) { - mTrack.SetImage( filename ); + mTrack.SetImage(filename); mTrackVisual = filename; } } -void Slider::SetTrackVisual( Property::Map map ) +void Slider::SetTrackVisual(Property::Map map) { - Property::Value* imageValue = map.Find( "url" ); - if( imageValue ) + Property::Value* imageValue = map.Find("url"); + if(imageValue) { mTrackVisual.clear(); std::string filename; - if( imageValue->Get( filename ) ) + if(imageValue->Get(filename)) { - if( mTrack && ( filename.size() > 0 ) ) + if(mTrack && (filename.size() > 0)) { - mTrack.SetImage( filename ); + mTrack.SetImage(filename); mTrackMap = map; } } } - Property::Value* sizeValue = map.Find( "size" ); - if( sizeValue ) + Property::Value* sizeValue = map.Find("size"); + if(sizeValue) { Vector2 size; - if( sizeValue->Get( size ) ) + if(sizeValue->Get(size)) { mTrackRegion = size; - if( mTrack ) + if(mTrack) { - mTrack.SetProperty( Actor::Property::SIZE, mTrackRegion ); + mTrack.SetProperty(Actor::Property::SIZE, mTrackRegion); } - ResizeProgressRegion( Vector2( 0.0f, mTrackRegion.y ) ); + ResizeProgressRegion(Vector2(0.0f, mTrackRegion.y)); - mDomain = CalcDomain( mTrackRegion ); + mDomain = CalcDomain(mTrackRegion); - // Set the progress bar to correct width - DisplayValue( GetValue(), false ); + // Set the progress bar to correct width + DisplayValue(GetValue(), false); } } } @@ -459,34 +457,34 @@ std::string Slider::GetTrackVisual() Toolkit::ImageView Slider::CreateProgress() { Toolkit::ImageView progress = Toolkit::ImageView::New(); - progress.SetProperty( Dali::Actor::Property::NAME,"SliderProgress"); - progress.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); - progress.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT ); + progress.SetProperty(Dali::Actor::Property::NAME, "SliderProgress"); + progress.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT); + progress.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT); return progress; } -void Slider::SetProgressVisual( const std::string& filename ) +void Slider::SetProgressVisual(const std::string& filename) { - if( mProgress && ( filename.size() > 0 ) ) + if(mProgress && (filename.size() > 0)) { - mProgress.SetImage( filename ); + mProgress.SetImage(filename); mProgressVisual = filename; } } -void Slider::SetProgressVisual( Property::Map map ) +void Slider::SetProgressVisual(Property::Map map) { - Property::Value* imageValue = map.Find( "url" ); - if( imageValue ) + Property::Value* imageValue = map.Find("url"); + if(imageValue) { mProgressVisual.clear(); std::string filename; - if( imageValue->Get( filename ) ) + if(imageValue->Get(filename)) { - if( mProgress && ( filename.size() > 0 ) ) + if(mProgress && (filename.size() > 0)) { - mProgress.SetImage( filename ); + mProgress.SetImage(filename); mProgressMap = map; } } @@ -498,23 +496,23 @@ std::string Slider::GetProgressVisual() return mProgressVisual; } -void Slider::SetPopupVisual( const std::string& filename ) +void Slider::SetPopupVisual(const std::string& filename) { mPopupVisual = filename; } -void Slider::SetPopupVisual( Property::Map map ) +void Slider::SetPopupVisual(Property::Map map) { - Property::Value* imageValue = map.Find( "url" ); - if( imageValue ) + Property::Value* imageValue = map.Find("url"); + if(imageValue) { mPopupVisual.clear(); std::string filename; - if( imageValue->Get( filename ) ) + if(imageValue->Get(filename)) { - if( mPopup && ( filename.size() > 0 ) ) + if(mPopup && (filename.size() > 0)) { - mPopup.SetImage( filename ); + mPopup.SetImage(filename); mPopupMap = map; } } @@ -526,33 +524,33 @@ std::string Slider::GetPopupVisual() return mPopupVisual; } -void Slider::CreatePopupImage( const std::string& filename ) +void Slider::CreatePopupImage(const std::string& filename) { - if( mPopup && ( filename.size() > 0 ) ) + if(mPopup && (filename.size() > 0)) { Property::Map map; map[Toolkit::ImageVisual::Property::URL] = filename; - mPopup.SetProperty( Toolkit::ImageView::Property::IMAGE, map ); + mPopup.SetProperty(Toolkit::ImageView::Property::IMAGE, map); } } -void Slider::SetPopupArrowVisual( const std::string& filename ) +void Slider::SetPopupArrowVisual(const std::string& filename) { mPopupArrowVisual = filename; } -void Slider::SetPopupArrowVisual( Property::Map map ) +void Slider::SetPopupArrowVisual(Property::Map map) { - Property::Value* imageValue = map.Find( "url" ); - if( imageValue ) + Property::Value* imageValue = map.Find("url"); + if(imageValue) { mPopupArrowVisual.clear(); std::string filename; - if( imageValue->Get( filename ) ) + if(imageValue->Get(filename)) { - if( mPopupArrow && ( filename.size() > 0 ) ) + if(mPopupArrow && (filename.size() > 0)) { - mPopupArrow.SetImage( filename ); + mPopupArrow.SetImage(filename); mPopupArrowMap = map; } } @@ -564,30 +562,30 @@ std::string Slider::GetPopupArrowVisual() return mPopupArrowVisual; } -void Slider::CreatePopupArrowImage( const std::string& filename ) +void Slider::CreatePopupArrowImage(const std::string& filename) { - if( mPopupArrow && ( filename.size() > 0 ) ) + if(mPopupArrow && (filename.size() > 0)) { Property::Map map; map[Toolkit::ImageVisual::Property::URL] = filename; - mPopupArrow.SetProperty( Toolkit::ImageView::Property::IMAGE, map ); + mPopupArrow.SetProperty(Toolkit::ImageView::Property::IMAGE, map); } } -void Slider::ResizeProgressRegion( const Vector2& region ) +void Slider::ResizeProgressRegion(const Vector2& region) { - if( mProgress ) + if(mProgress) { - mProgress.SetProperty( Actor::Property::SIZE, region ); + mProgress.SetProperty(Actor::Property::SIZE, region); } } Toolkit::ImageView Slider::CreateHandle() { Toolkit::ImageView handle = Toolkit::ImageView::New(); - handle.SetProperty( Dali::Actor::Property::NAME,"SliderHandle"); - handle.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); - handle.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + handle.SetProperty(Dali::Actor::Property::NAME, "SliderHandle"); + handle.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT); + handle.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); return handle; } @@ -596,9 +594,9 @@ Toolkit::ImageView Slider::CreatePopupArrow() { Toolkit::ImageView arrow = Toolkit::ImageView::New(); arrow.SetStyleName("SliderPopupArrow"); - arrow.SetProperty( Dali::Actor::Property::NAME,"SliderPopupArrow"); - arrow.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER ); - arrow.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); + arrow.SetProperty(Dali::Actor::Property::NAME, "SliderPopupArrow"); + arrow.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER); + arrow.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER); return arrow; } @@ -606,70 +604,70 @@ Toolkit::ImageView Slider::CreatePopupArrow() Toolkit::TextLabel Slider::CreatePopupText() { Toolkit::TextLabel textLabel = Toolkit::TextLabel::New(); - textLabel.SetProperty( Dali::Actor::Property::NAME, "SliderPopupTextLabel" ); - textLabel.SetStyleName( "SliderPopupTextLabel" ); - textLabel.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - textLabel.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - textLabel.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS ); - textLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" ); - textLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" ); - textLabel.SetProperty( Actor::Property::PADDING, Padding( POPUP_TEXT_PADDING, POPUP_TEXT_PADDING, 0.0f, 0.0f ) ); - textLabel.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false ); + textLabel.SetProperty(Dali::Actor::Property::NAME, "SliderPopupTextLabel"); + textLabel.SetStyleName("SliderPopupTextLabel"); + textLabel.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + textLabel.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + textLabel.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS); + textLabel.SetProperty(Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER"); + textLabel.SetProperty(Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER"); + textLabel.SetProperty(Actor::Property::PADDING, Padding(POPUP_TEXT_PADDING, POPUP_TEXT_PADDING, 0.0f, 0.0f)); + textLabel.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false); return textLabel; } Toolkit::ImageView Slider::CreatePopup() { Toolkit::ImageView popup = Toolkit::ImageView::New(); - popup.SetProperty( Dali::Actor::Property::NAME, "SliderPopup" ); - popup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); - popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); - popup.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH ); + popup.SetProperty(Dali::Actor::Property::NAME, "SliderPopup"); + popup.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER); + popup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER); + popup.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH); mValueTextLabel = CreatePopupText(); - popup.Add( mValueTextLabel ); + popup.Add(mValueTextLabel); return popup; } -void Slider::SetHandleVisual( const std::string& filename ) +void Slider::SetHandleVisual(const std::string& filename) { - if( mHandle && ( filename.size() > 0 ) ) + if(mHandle && (filename.size() > 0)) { - mHandle.SetImage( filename ); + mHandle.SetImage(filename); mHandleVisual = filename; } } -void Slider::SetHandleVisual( Property::Map map ) +void Slider::SetHandleVisual(Property::Map map) { - Property::Value* imageValue = map.Find( "url" ); - if( imageValue ) + Property::Value* imageValue = map.Find("url"); + if(imageValue) { mHandleVisual.clear(); std::string filename; - if( imageValue->Get( filename ) ) + if(imageValue->Get(filename)) { - if( mHandle && ( filename.size() > 0 ) ) + if(mHandle && (filename.size() > 0)) { - mHandle.SetImage( filename ); + mHandle.SetImage(filename); mHandleMap = map; } } } - Property::Value* sizeValue = map.Find( "size" ); - if( sizeValue ) + Property::Value* sizeValue = map.Find("size"); + if(sizeValue) { Vector2 size; - if( sizeValue->Get( size ) ) + if(sizeValue->Get(size)) { mHandleSize = size; - ResizeHandleSize( mHandleSize ); + ResizeHandleSize(mHandleSize); Vector2 hitRegion = GetHitRegion(); hitRegion.x += mHandleSize.x; - SetHitRegion( hitRegion ); + SetHitRegion(hitRegion); } } } @@ -679,27 +677,27 @@ std::string Slider::GetHandleVisual() return mHandleVisual; } -void Slider::ResizeHandleSize( const Vector2& size ) +void Slider::ResizeHandleSize(const Vector2& size) { - if( mHandle ) + if(mHandle) { - mHandle.SetProperty( Actor::Property::SIZE, size ); + mHandle.SetProperty(Actor::Property::SIZE, size); } } void Slider::CreateHandleValueDisplay() { - if( mHandle && !mHandleValueTextLabel ) + if(mHandle && !mHandleValueTextLabel) { mHandleValueTextLabel = Toolkit::TextLabel::New(); - mHandleValueTextLabel.SetProperty( Dali::Actor::Property::NAME,"SliderHandleTextLabel"); + mHandleValueTextLabel.SetProperty(Dali::Actor::Property::NAME, "SliderHandleTextLabel"); mHandleValueTextLabel.SetStyleName("SliderHandleTextLabel"); - mHandleValueTextLabel.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mHandleValueTextLabel.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" ); - mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" ); - mHandleValueTextLabel.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false ); - mHandle.Add( mHandleValueTextLabel ); + mHandleValueTextLabel.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mHandleValueTextLabel.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mHandleValueTextLabel.SetProperty(Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER"); + mHandleValueTextLabel.SetProperty(Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER"); + mHandleValueTextLabel.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false); + mHandle.Add(mHandleValueTextLabel); } } @@ -711,15 +709,15 @@ void Slider::DestroyHandleValueDisplay() Actor Slider::CreateValueDisplay() { Actor popup = Actor::New(); - popup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); - popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); + popup.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER); + popup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER); mPopupArrow = CreatePopupArrow(); - popup.Add( mPopupArrow ); + popup.Add(mPopupArrow); mPopup = CreatePopup(); - mPopup.SetProperty( Actor::Property::SIZE, Vector2( 0.0f, VALUE_POPUP_HEIGHT ) ); - mPopupArrow.Add( mPopup ); + mPopup.SetProperty(Actor::Property::SIZE, Vector2(0.0f, VALUE_POPUP_HEIGHT)); + mPopupArrow.Add(mPopup); return popup; } @@ -741,21 +739,21 @@ Toolkit::Slider::MarkReachedSignalType& Slider::MarkReachedSignal() void Slider::UpdateSkin() { - switch( mState ) + switch(mState) { case NORMAL: { - mTrack.SetProperty( Actor::Property::COLOR, Color::WHITE ); - mHandle.SetProperty( Actor::Property::COLOR, Color::WHITE ); - mProgress.SetProperty( Actor::Property::COLOR, Color::WHITE ); + mTrack.SetProperty(Actor::Property::COLOR, Color::WHITE); + mHandle.SetProperty(Actor::Property::COLOR, Color::WHITE); + mProgress.SetProperty(Actor::Property::COLOR, Color::WHITE); break; } case DISABLED: { Vector4 disabledColor = GetDisabledColor(); - mTrack.SetProperty( Actor::Property::COLOR, disabledColor ); - mHandle.SetProperty( Actor::Property::COLOR, disabledColor ); - mProgress.SetProperty( Actor::Property::COLOR, disabledColor ); + mTrack.SetProperty(Actor::Property::COLOR, disabledColor); + mHandle.SetProperty(Actor::Property::COLOR, disabledColor); + mProgress.SetProperty(Actor::Property::COLOR, disabledColor); break; } case PRESSED: @@ -774,32 +772,32 @@ void Slider::CreateChildren() Actor self = Self(); // Hit region - mHitArea = CreateHitRegion(); + mHitArea = CreateHitRegion(); mPanDetector = PanGestureDetector::New(); - mPanDetector.Attach( mHitArea ); - mPanDetector.DetectedSignal().Connect( this, &Slider::OnPan ); - self.Add( mHitArea ); + mPanDetector.Attach(mHitArea); + mPanDetector.DetectedSignal().Connect(this, &Slider::OnPan); + self.Add(mHitArea); // Track mTrack = CreateTrack(); - self.Add( mTrack ); + self.Add(mTrack); // Progress bar mProgress = CreateProgress(); - mTrack.Add( mProgress ); + mTrack.Add(mProgress); // Handle mHandle = CreateHandle(); - mProgress.Add( mHandle ); + mProgress.Add(mHandle); } -void Slider::SetHitRegion( const Vector2& size ) +void Slider::SetHitRegion(const Vector2& size) { mHitRegion = size; - if( mHitArea ) + if(mHitArea) { - mHitArea.SetProperty( Actor::Property::SIZE, mHitRegion ); + mHitArea.SetProperty(Actor::Property::SIZE, mHitRegion); } } @@ -810,23 +808,23 @@ const Vector2& Slider::GetHitRegion() const void Slider::AddPopup() { - if( !mValueDisplay ) + if(!mValueDisplay) { mValueDisplay = CreateValueDisplay(); - mValueDisplay.SetProperty( Actor::Property::VISIBLE, false ); - mHandle.Add( mValueDisplay ); + mValueDisplay.SetProperty(Actor::Property::VISIBLE, false); + mHandle.Add(mValueDisplay); - CreatePopupImage( GetPopupVisual() ); - CreatePopupArrowImage( GetPopupArrowVisual() ); + CreatePopupImage(GetPopupVisual()); + CreatePopupArrowImage(GetPopupArrowVisual()); - mValueTimer = Timer::New( VALUE_VIEW_SHOW_DURATION ); - mValueTimer.TickSignal().Connect( this, &Slider::HideValueView ); + mValueTimer = Timer::New(VALUE_VIEW_SHOW_DURATION); + mValueTimer.TickSignal().Connect(this, &Slider::HideValueView); } } void Slider::RemovePopup() { - if( mValueDisplay ) + if(mValueDisplay) { mPopup.Unparent(); mPopup.Reset(); @@ -837,37 +835,36 @@ void Slider::RemovePopup() mValueDisplay.Unparent(); mValueDisplay.Reset(); - mValueTimer.TickSignal().Disconnect( this, &Slider::HideValueView ); + mValueTimer.TickSignal().Disconnect(this, &Slider::HideValueView); mValueTimer.Reset(); } } - -float Slider::MarkFilter( float value ) +float Slider::MarkFilter(float value) { const float MARK_TOLERANCE = GetMarkTolerance(); float mark = SnapToMark(value); - if (fabsf(mark - value) < MARK_TOLERANCE) + if(fabsf(mark - value) < MARK_TOLERANCE) return mark; return value; } -float Slider::SnapToMark( float value ) +float Slider::SnapToMark(float value) { float closestMark = value; float closestDist = std::numeric_limits::max(); float mark; - for( MarkList::SizeType i = 0; i < mMarks.Count(); ++i) + for(MarkList::SizeType i = 0; i < mMarks.Count(); ++i) { const Property::Value& propertyValue = mMarks[i]; - propertyValue.Get( mark ); - mark = MapValuePercentage( mark ); + propertyValue.Get(mark); + mark = MapValuePercentage(mark); - float dist = fabsf( mark - value ); - if( dist < closestDist ) + float dist = fabsf(mark - value); + if(dist < closestDist) { closestDist = dist; closestMark = mark; @@ -877,31 +874,31 @@ float Slider::SnapToMark( float value ) return closestMark; } -bool Slider::MarkReached( float value, int& outIndex ) +bool Slider::MarkReached(float value, int& outIndex) { const float MARK_TOLERANCE = GetMarkTolerance(); // Binary search int head = 0, tail = mMarks.Size() - 1; - int current; + int current; float mark; - while( head <= tail ) + while(head <= tail) { - current = head + ( tail - head ) / 2; + current = head + (tail - head) / 2; - const Property::Value& propertyValue = mMarks[ current ]; - propertyValue.Get( mark ); - mark = MapValuePercentage( mark ); + const Property::Value& propertyValue = mMarks[current]; + propertyValue.Get(mark); + mark = MapValuePercentage(mark); - if( fabsf( mark - value ) < MARK_TOLERANCE ) + if(fabsf(mark - value) < MARK_TOLERANCE) { outIndex = current; return true; } - if( value < mark ) + if(value < mark) { tail = current - 1; } @@ -916,18 +913,18 @@ bool Slider::MarkReached( float value, int& outIndex ) bool Slider::HideValueView() { - if( mValueDisplay ) + if(mValueDisplay) { - mValueDisplay.SetProperty( Actor::Property::VISIBLE, false ); + mValueDisplay.SetProperty(Actor::Property::VISIBLE, false); } return false; } -void Slider::SetLowerBound( float bound ) +void Slider::SetLowerBound(float bound) { mLowerBound = bound; - DisplayValue( GetValue(), false ); + DisplayValue(GetValue(), false); } float Slider::GetLowerBound() const @@ -935,10 +932,10 @@ float Slider::GetLowerBound() const return mLowerBound; } -void Slider::SetUpperBound( float bound ) +void Slider::SetUpperBound(float bound) { mUpperBound = bound; - DisplayValue( GetValue(), false ); + DisplayValue(GetValue(), false); } float Slider::GetUpperBound() const @@ -946,11 +943,11 @@ float Slider::GetUpperBound() const return mUpperBound; } -void Slider::SetValue( float value ) +void Slider::SetValue(float value) { mValue = value; - DisplayValue( mValue, true ); - if (Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) + DisplayValue(mValue, true); + if(Self() == Dali::Accessibility::Accessible::GetCurrentlyHighlightedActor()) { Control::Impl::GetAccessibilityObject(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::VALUE); } @@ -961,20 +958,20 @@ float Slider::GetValue() const return mValue; } -void Slider::SetTrackRegion( const Vector2& region ) +void Slider::SetTrackRegion(const Vector2& region) { mTrackRegion = region; - if( mTrack ) + if(mTrack) { - mTrack.SetProperty( Actor::Property::SIZE, mTrackRegion ); + mTrack.SetProperty(Actor::Property::SIZE, mTrackRegion); } - ResizeProgressRegion( Vector2( 0.0f, mTrackRegion.y ) ); + ResizeProgressRegion(Vector2(0.0f, mTrackRegion.y)); - mDomain = CalcDomain( mTrackRegion ); + mDomain = CalcDomain(mTrackRegion); - DisplayValue( GetValue(), false ); // Set the progress bar to correct width + DisplayValue(GetValue(), false); // Set the progress bar to correct width } const Vector2& Slider::GetTrackRegion() const @@ -982,15 +979,15 @@ const Vector2& Slider::GetTrackRegion() const return mTrackRegion; } -void Slider::SetHandleSize( const Vector2& size ) +void Slider::SetHandleSize(const Vector2& size) { mHandleSize = size; - ResizeHandleSize( mHandleSize ); + ResizeHandleSize(mHandleSize); Vector2 hitRegion = GetHitRegion(); hitRegion.x += mHandleSize.x; - SetHitRegion( hitRegion ); + SetHitRegion(hitRegion); } const Vector2& Slider::GetHandleSize() const @@ -998,7 +995,7 @@ const Vector2& Slider::GetHandleSize() const return mHandleSize; } -void Slider::SetDisabledColor( const Vector4& color ) +void Slider::SetDisabledColor(const Vector4& color) { mDisabledColor = color; @@ -1010,7 +1007,7 @@ Vector4 Slider::GetDisabledColor() const return mDisabledColor; } -void Slider::SetValuePrecision( int precision ) +void Slider::SetValuePrecision(int precision) { mValuePrecision = precision; } @@ -1020,12 +1017,12 @@ int Slider::GetValuePrecision() const return mValuePrecision; } -void Slider::SetShowPopup( bool showPopup ) +void Slider::SetShowPopup(bool showPopup) { mShowPopup = showPopup; // Value display - if( mShowPopup ) + if(mShowPopup) { AddPopup(); } @@ -1040,11 +1037,11 @@ bool Slider::GetShowPopup() const return mShowPopup; } -void Slider::SetShowValue( bool showValue ) +void Slider::SetShowValue(bool showValue) { mShowValue = showValue; - if( mShowValue ) + if(mShowValue) { CreateHandleValueDisplay(); } @@ -1059,9 +1056,9 @@ bool Slider::GetShowValue() const return mShowValue; } -void Slider::SetEnabled( bool enabled ) +void Slider::SetEnabled(bool enabled) { - if( enabled ) + if(enabled) { mState = NORMAL; } @@ -1078,7 +1075,7 @@ bool Slider::IsEnabled() const return mState != DISABLED; } -void Slider::SetMarkTolerance( float tolerance ) +void Slider::SetMarkTolerance(float tolerance) { mMarkTolerance = tolerance; } @@ -1089,20 +1086,20 @@ float Slider::GetMarkTolerance() const } // Static class method to support script connecting signals -bool Slider::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool Slider::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected = true; - Toolkit::Slider slider = Toolkit::Slider::DownCast( handle ); + bool connected = true; + Toolkit::Slider slider = Toolkit::Slider::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_VALUE_CHANGED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_VALUE_CHANGED)) { - slider.ValueChangedSignal().Connect( tracker, functor ); + slider.ValueChangedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_MARK ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_MARK)) { - slider.MarkReachedSignal().Connect( tracker, functor ); + slider.MarkReachedSignal().Connect(tracker, functor); } else { @@ -1113,59 +1110,59 @@ bool Slider::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tr return connected; } -void Slider::DisplayPopup( float value ) +void Slider::DisplayPopup(float value) { // Value displayDoConnectSignal - if( mValueTextLabel ) + if(mValueTextLabel) { std::stringstream ss; - ss.precision( GetValuePrecision() ); + ss.precision(GetValuePrecision()); ss << std::fixed << value; - mValueTextLabel.SetProperty( Toolkit::TextLabel::Property::TEXT, ss.str() ); + mValueTextLabel.SetProperty(Toolkit::TextLabel::Property::TEXT, ss.str()); - if( mValueDisplay ) + if(mValueDisplay) { - mValueDisplay.SetProperty( Actor::Property::VISIBLE, true ); + mValueDisplay.SetProperty(Actor::Property::VISIBLE, true); - mValueTimer.SetInterval( VALUE_VIEW_SHOW_DURATION ); + mValueTimer.SetInterval(VALUE_VIEW_SHOW_DURATION); } } } -void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) +void Slider::SetProperty(BaseObject* object, Property::Index propertyIndex, const Property::Value& value) { - Toolkit::Slider slider = Toolkit::Slider::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Slider slider = Toolkit::Slider::DownCast(Dali::BaseHandle(object)); - if ( slider ) + if(slider) { - Slider& sliderImpl( GetImpl( slider ) ); + Slider& sliderImpl(GetImpl(slider)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::Slider::Property::LOWER_BOUND: { - sliderImpl.SetLowerBound( value.Get< float >() ); + sliderImpl.SetLowerBound(value.Get()); break; } case Toolkit::Slider::Property::UPPER_BOUND: { - sliderImpl.SetUpperBound( value.Get< float >() ); + sliderImpl.SetUpperBound(value.Get()); break; } case Toolkit::Slider::Property::VALUE: { - sliderImpl.SetValue( value.Get< float >() ); + sliderImpl.SetValue(value.Get()); break; } case Toolkit::Slider::Property::TRACK_VISUAL: { Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { - sliderImpl.SetTrackVisual( map ); + sliderImpl.SetTrackVisual(map); } break; } @@ -1173,9 +1170,9 @@ void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, con case Toolkit::Slider::Property::HANDLE_VISUAL: { Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { - sliderImpl.SetHandleVisual( map ); + sliderImpl.SetHandleVisual(map); } break; } @@ -1183,9 +1180,9 @@ void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, con case Toolkit::Slider::Property::PROGRESS_VISUAL: { Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { - sliderImpl.SetProgressVisual( map ); + sliderImpl.SetProgressVisual(map); } break; } @@ -1193,16 +1190,16 @@ void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, con case Toolkit::Slider::Property::POPUP_VISUAL: { std::string imageUrl; - if( value.Get( imageUrl ) ) + if(value.Get(imageUrl)) { - sliderImpl.SetPopupVisual( imageUrl ); + sliderImpl.SetPopupVisual(imageUrl); } // If it is not a string, then get a Property::Map from the property if possible. Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { - sliderImpl.SetPopupVisual( map ); + sliderImpl.SetPopupVisual(map); } break; @@ -1211,69 +1208,69 @@ void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, con case Toolkit::Slider::Property::POPUP_ARROW_VISUAL: { Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { - sliderImpl.SetPopupArrowVisual( map ); + sliderImpl.SetPopupArrowVisual(map); } break; } case Toolkit::Slider::Property::DISABLED_COLOR: { - sliderImpl.SetDisabledColor( value.Get< Vector4 >() ); + sliderImpl.SetDisabledColor(value.Get()); break; } case Toolkit::Slider::Property::VALUE_PRECISION: { - sliderImpl.SetValuePrecision( value.Get< int >() ); + sliderImpl.SetValuePrecision(value.Get()); break; } case Toolkit::Slider::Property::SHOW_POPUP: { - sliderImpl.SetShowPopup( value.Get< bool >() ); + sliderImpl.SetShowPopup(value.Get()); break; } case Toolkit::Slider::Property::SHOW_VALUE: { - sliderImpl.SetShowValue( value.Get< bool >() ); + sliderImpl.SetShowValue(value.Get()); break; } case Toolkit::Slider::Property::MARKS: { - sliderImpl.SetMarks( value.Get< Property::Array >() ); + sliderImpl.SetMarks(value.Get()); break; } case Toolkit::Slider::Property::SNAP_TO_MARKS: { - sliderImpl.SetSnapToMarks( value.Get< bool >() ); + sliderImpl.SetSnapToMarks(value.Get()); break; } case Toolkit::Slider::Property::MARK_TOLERANCE: { - sliderImpl.SetMarkTolerance( value.Get< float >() ); + sliderImpl.SetMarkTolerance(value.Get()); break; } } } } -Property::Value Slider::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value Slider::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::Slider slider = Toolkit::Slider::DownCast( Dali::BaseHandle( object ) ); + Toolkit::Slider slider = Toolkit::Slider::DownCast(Dali::BaseHandle(object)); - if ( slider ) + if(slider) { - Slider& sliderImpl( GetImpl( slider ) ); + Slider& sliderImpl(GetImpl(slider)); - switch ( propertyIndex ) + switch(propertyIndex) { case Toolkit::Slider::Property::LOWER_BOUND: { @@ -1295,11 +1292,11 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Slider::Property::TRACK_VISUAL: { - if( !sliderImpl.mTrackVisual.empty() ) + if(!sliderImpl.mTrackVisual.empty()) { value = sliderImpl.GetTrackVisual(); } - else if( !sliderImpl.mTrackMap.Empty() ) + else if(!sliderImpl.mTrackMap.Empty()) { value = sliderImpl.mTrackMap; } @@ -1308,11 +1305,11 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Slider::Property::HANDLE_VISUAL: { - if( !sliderImpl.mHandleVisual.empty() ) + if(!sliderImpl.mHandleVisual.empty()) { value = sliderImpl.GetHandleVisual(); } - else if( !sliderImpl.mHandleMap.Empty() ) + else if(!sliderImpl.mHandleMap.Empty()) { value = sliderImpl.mHandleMap; } @@ -1321,11 +1318,11 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Slider::Property::PROGRESS_VISUAL: { - if( !sliderImpl.mProgressVisual.empty() ) + if(!sliderImpl.mProgressVisual.empty()) { value = sliderImpl.GetProgressVisual(); } - else if( !sliderImpl.mProgressMap.Empty() ) + else if(!sliderImpl.mProgressMap.Empty()) { value = sliderImpl.mProgressMap; } @@ -1334,11 +1331,11 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Slider::Property::POPUP_VISUAL: { - if( !sliderImpl.mPopupVisual.empty() ) + if(!sliderImpl.mPopupVisual.empty()) { value = sliderImpl.GetPopupVisual(); } - else if( !sliderImpl.mPopupMap.Empty() ) + else if(!sliderImpl.mPopupMap.Empty()) { value = sliderImpl.mPopupMap; } @@ -1347,11 +1344,11 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Slider::Property::POPUP_ARROW_VISUAL: { - if( !sliderImpl.mPopupArrowVisual.empty() ) + if(!sliderImpl.mPopupArrowVisual.empty()) { value = sliderImpl.GetPopupArrowVisual(); } - else if( !sliderImpl.mPopupArrowMap.Empty() ) + else if(!sliderImpl.mPopupArrowMap.Empty()) { value = sliderImpl.mPopupArrowMap; } @@ -1384,10 +1381,10 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert case Toolkit::Slider::Property::MARKS: { - Property::Value value1( Property::ARRAY ); + Property::Value value1(Property::ARRAY); Property::Array* markArray = value1.GetArray(); - if( markArray ) + if(markArray) { *markArray = sliderImpl.GetMarks(); } @@ -1415,48 +1412,48 @@ Property::Value Slider::GetProperty( BaseObject* object, Property::Index propert double Slider::AccessibleImpl::GetMinimum() { - auto p = Toolkit::Slider::DownCast( self ); - return p.GetProperty( Toolkit::Slider::Property::LOWER_BOUND ).Get< float >(); + auto p = Toolkit::Slider::DownCast(self); + return p.GetProperty(Toolkit::Slider::Property::LOWER_BOUND).Get(); } double Slider::AccessibleImpl::GetCurrent() { - auto p = Toolkit::Slider::DownCast( self ); - return p.GetProperty( Toolkit::Slider::Property::VALUE ).Get< float >(); + auto p = Toolkit::Slider::DownCast(self); + return p.GetProperty(Toolkit::Slider::Property::VALUE).Get(); } double Slider::AccessibleImpl::GetMaximum() { - auto p = Toolkit::Slider::DownCast( self ); - return p.GetProperty( Toolkit::Slider::Property::UPPER_BOUND ).Get< float >(); + auto p = Toolkit::Slider::DownCast(self); + return p.GetProperty(Toolkit::Slider::Property::UPPER_BOUND).Get(); } -bool Slider::AccessibleImpl::SetCurrent( double current ) +bool Slider::AccessibleImpl::SetCurrent(double current) { - if (current < GetMinimum() || current > GetMaximum()) + if(current < GetMinimum() || current > GetMaximum()) return false; - auto p = Toolkit::Slider::DownCast( self ); - auto &impl = Toolkit::GetImpl(p); + auto p = Toolkit::Slider::DownCast(self); + auto& impl = Toolkit::GetImpl(p); const float prev = p.GetProperty(Toolkit::Slider::Property::VALUE); - float next = static_cast(current); + float next = static_cast(current); - if (fabsf(next - prev) < Math::MACHINE_EPSILON_0) + if(fabsf(next - prev) < Math::MACHINE_EPSILON_0) { // do nothing } - else if (p.GetProperty(Toolkit::Slider::Property::SNAP_TO_MARKS)) + else if(p.GetProperty(Toolkit::Slider::Property::SNAP_TO_MARKS)) { auto marks = p.GetProperty(Toolkit::Slider::Property::MARKS); int prevIdx; - if (impl.MarkReached(impl.MapValuePercentage(prev), prevIdx)) + if(impl.MarkReached(impl.MapValuePercentage(prev), prevIdx)) { int nextIdx = prevIdx; nextIdx += (next > prev) ? 1 : -1; - if (nextIdx < 0 || nextIdx >= static_cast(marks.Count())) + if(nextIdx < 0 || nextIdx >= static_cast(marks.Count())) return false; next = marks[nextIdx].Get(); @@ -1479,12 +1476,12 @@ bool Slider::AccessibleImpl::SetCurrent( double current ) double Slider::AccessibleImpl::GetMinimumIncrement() { - auto p = Toolkit::Slider::DownCast( self ); + auto p = Toolkit::Slider::DownCast(self); - bool hasMarks = !p.GetProperty(Toolkit::Slider::Property::MARKS).Empty(); + bool hasMarks = !p.GetProperty(Toolkit::Slider::Property::MARKS).Empty(); float tolerance = p.GetProperty(Toolkit::Slider::Property::MARK_TOLERANCE); - if (!hasMarks || fabsf(tolerance) < 0.01) + if(!hasMarks || fabsf(tolerance) < 0.01) return 0.0; // let screen-reader choose the increment return Math::MACHINE_EPSILON_10000 + tolerance * (GetMaximum() - GetMinimum()); diff --git a/dali-toolkit/internal/controls/super-blur-view/super-blur-view-impl.cpp b/dali-toolkit/internal/controls/super-blur-view/super-blur-view-impl.cpp index 4cd42a4..b1e60c7 100644 --- a/dali-toolkit/internal/controls/super-blur-view/super-blur-view-impl.cpp +++ b/dali-toolkit/internal/controls/super-blur-view/super-blur-view-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,40 +19,39 @@ #include "super-blur-view-impl.h" // EXTERNAL INCLUDES -#include -#include #include +#include +#include +#include #include -#include #include +#include #include -#include -#include +#include // INTERNAL_INCLUDES -#include #include -#include +#include #include +#include #include #include -#include +#include namespace //Unnamed namespace { - using namespace Dali; //Todo: make these properties instead of constants -const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11; -const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10; -const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f; -const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f; -const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888; -const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f; -const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f; +const unsigned int GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES = 11; +const unsigned int GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION = 10; +const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH = 4.5f; +const float GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION = 5.f; +const Pixel::Format GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888; +const float GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE = 0.5f; +const float GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE = 0.5f; -const char* ALPHA_UNIFORM_NAME( "uAlpha" ); +const char* ALPHA_UNIFORM_NAME("uAlpha"); /** * The constraint is used to blend the group of blurred images continuously with a unified blur strength property value which ranges from zero to one. @@ -61,12 +60,12 @@ struct ActorOpacityConstraint { ActorOpacityConstraint(int totalImageNum, int currentImageIdx) { - float rangeLength = 1.f / static_cast( totalImageNum ); - float index = static_cast( currentImageIdx ); - mRange = Vector2( index*rangeLength, (index+1.f)*rangeLength ); + float rangeLength = 1.f / static_cast(totalImageNum); + float index = static_cast(currentImageIdx); + mRange = Vector2(index * rangeLength, (index + 1.f) * rangeLength); } - void operator()( float& current, const PropertyInputContainer& inputs ) + void operator()(float& current, const PropertyInputContainer& inputs) { float blurStrength = inputs[0]->GetFloat(); if(blurStrength < mRange.x) @@ -79,7 +78,7 @@ struct ActorOpacityConstraint } else { - current = ( blurStrength - mRange.x) / ( mRange.y - mRange.x ); + current = (blurStrength - mRange.x) / (mRange.y - mRange.x); } } @@ -90,56 +89,52 @@ struct ActorOpacityConstraint namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const unsigned int DEFAULT_BLUR_LEVEL(5u); ///< The default blur level when creating SuperBlurView from the type registry BaseHandle Create() { - return Toolkit::SuperBlurView::New( DEFAULT_BLUR_LEVEL ); + return Toolkit::SuperBlurView::New(DEFAULT_BLUR_LEVEL); } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::SuperBlurView, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::SuperBlurView, Toolkit::Control, Create) -DALI_PROPERTY_REGISTRATION( Toolkit, SuperBlurView, "imageUrl", STRING, IMAGE_URL ) +DALI_PROPERTY_REGISTRATION(Toolkit, SuperBlurView, "imageUrl", STRING, IMAGE_URL) DALI_TYPE_REGISTRATION_END() } // unnamed namespace -SuperBlurView::SuperBlurView( unsigned int blurLevels ) -: Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS ) ), - mTargetSize( Vector2::ZERO ), +SuperBlurView::SuperBlurView(unsigned int blurLevels) +: Control(ControlBehaviour(DISABLE_SIZE_NEGOTIATION | DISABLE_STYLE_CHANGE_SIGNALS)), + mTargetSize(Vector2::ZERO), mBlurStrengthPropertyIndex(Property::INVALID_INDEX), - mBlurLevels( blurLevels ), - mResourcesCleared( true ) + mBlurLevels(blurLevels), + mResourcesCleared(true) { - DALI_ASSERT_ALWAYS( mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed" ); - mGaussianBlurView.assign( blurLevels, Toolkit::GaussianBlurView() ); - mBlurredImage.assign( blurLevels, FrameBuffer() ); - mRenderers.assign( blurLevels+1, Dali::Renderer() ); + DALI_ASSERT_ALWAYS(mBlurLevels > 0 && " Minimal blur level is one, otherwise no blur is needed"); + mGaussianBlurView.assign(blurLevels, Toolkit::GaussianBlurView()); + mBlurredImage.assign(blurLevels, FrameBuffer()); + mRenderers.assign(blurLevels + 1, Dali::Renderer()); } SuperBlurView::~SuperBlurView() { } -Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels ) +Toolkit::SuperBlurView SuperBlurView::New(unsigned int blurLevels) { //Create the implementation - IntrusivePtr superBlurView( new SuperBlurView( blurLevels ) ); + IntrusivePtr superBlurView(new SuperBlurView(blurLevels)); //Pass ownership to CustomActor via derived handle - Toolkit::SuperBlurView handle( *superBlurView ); + Toolkit::SuperBlurView handle(*superBlurView); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -150,40 +145,40 @@ Toolkit::SuperBlurView SuperBlurView::New( unsigned int blurLevels ) void SuperBlurView::OnInitialize() { - Actor self( Self() ); + Actor self(Self()); - mBlurStrengthPropertyIndex = self.RegisterProperty( "blurStrength", 0.f ); + mBlurStrengthPropertyIndex = self.RegisterProperty("blurStrength", 0.f); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::FILLER ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::FILLER)); + }); } -void SuperBlurView::SetTexture( Texture texture ) +void SuperBlurView::SetTexture(Texture texture) { mInputTexture = texture; - if( mTargetSize == Vector2::ZERO ) + if(mTargetSize == Vector2::ZERO) { return; } ClearBlurResource(); - Actor self( Self() ); + Actor self(Self()); - BlurTexture( 0, mInputTexture ); - SetRendererTexture( mRenderers[0], texture ); + BlurTexture(0, mInputTexture); + SetRendererTexture(mRenderers[0], texture); unsigned int i = 1; - for(; i0 && level<=mBlurLevels ); + DALI_ASSERT_ALWAYS(level > 0 && level <= mBlurLevels); - FrameBuffer frameBuffer = mBlurredImage[level-1]; + FrameBuffer frameBuffer = mBlurredImage[level - 1]; return frameBuffer.GetColorTexture(); } -void SuperBlurView::BlurTexture( unsigned int idx, Texture texture ) +void SuperBlurView::BlurTexture(unsigned int idx, Texture texture) { - DALI_ASSERT_ALWAYS( mGaussianBlurView.size()>idx ); - mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New( GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES+GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION*idx, - GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION*static_cast(idx), - GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, - GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE, GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE, true ); - mGaussianBlurView[idx].SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::CENTER ); - mGaussianBlurView[idx].SetProperty( Actor::Property::SIZE, mTargetSize ); - Stage::GetCurrent().Add( mGaussianBlurView[idx] ); - - mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget( texture, mBlurredImage[idx] ); + DALI_ASSERT_ALWAYS(mGaussianBlurView.size() > idx); + mGaussianBlurView[idx] = Toolkit::GaussianBlurView::New(GAUSSIAN_BLUR_DEFAULT_NUM_SAMPLES + GAUSSIAN_BLUR_NUM_SAMPLES_INCREMENTATION * idx, + GAUSSIAN_BLUR_BELL_CURVE_WIDTH + GAUSSIAN_BLUR_BELL_CURVE_WIDTH_INCREMENTATION * static_cast(idx), + GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, + GAUSSIAN_BLUR_DOWNSAMPLE_WIDTH_SCALE, + GAUSSIAN_BLUR_DOWNSAMPLE_HEIGHT_SCALE, + true); + mGaussianBlurView[idx].SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mGaussianBlurView[idx].SetProperty(Actor::Property::SIZE, mTargetSize); + Stage::GetCurrent().Add(mGaussianBlurView[idx]); + + mGaussianBlurView[idx].SetUserImageAndOutputRenderTarget(texture, mBlurredImage[idx]); mGaussianBlurView[idx].ActivateOnce(); - if( idx == mBlurLevels-1 ) + if(idx == mBlurLevels - 1) { - mGaussianBlurView[idx].FinishedSignal().Connect( this, &SuperBlurView::OnBlurViewFinished ); + mGaussianBlurView[idx].FinishedSignal().Connect(this, &SuperBlurView::OnBlurViewFinished); } } -void SuperBlurView::OnBlurViewFinished( Toolkit::GaussianBlurView blurView ) +void SuperBlurView::OnBlurViewFinished(Toolkit::GaussianBlurView blurView) { ClearBlurResource(); - Toolkit::SuperBlurView handle( GetOwner() ); - mBlurFinishedSignal.Emit( handle ); + Toolkit::SuperBlurView handle(GetOwner()); + mBlurFinishedSignal.Emit(handle); } void SuperBlurView::ClearBlurResource() { - if( !mResourcesCleared ) + if(!mResourcesCleared) { - DALI_ASSERT_ALWAYS( mGaussianBlurView.size() == mBlurLevels && "must synchronize the GaussianBlurView group if blur levels got changed " ); - for(unsigned int i=0; i(i); - unsigned int width = mTargetSize.width/std::pow(2.f,exponent); - unsigned int height = mTargetSize.height/std::pow(2.f,exponent); + unsigned int width = mTargetSize.width / std::pow(2.f, exponent); + unsigned int height = mTargetSize.height / std::pow(2.f, exponent); - mBlurredImage[i-1] = FrameBuffer::New( width, height, FrameBuffer::Attachment::NONE ); - Texture texture = Texture::New( TextureType::TEXTURE_2D, GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, unsigned(width), unsigned(height) ); - mBlurredImage[i-1].AttachColorTexture( texture ); + mBlurredImage[i - 1] = FrameBuffer::New(width, height, FrameBuffer::Attachment::NONE); + Texture texture = Texture::New(TextureType::TEXTURE_2D, GAUSSIAN_BLUR_RENDER_TARGET_PIXEL_FORMAT, unsigned(width), unsigned(height)); + mBlurredImage[i - 1].AttachColorTexture(texture); } - if( mInputTexture ) + if(mInputTexture) { - SetTexture( mInputTexture ); + SetTexture(mInputTexture); } } - Control::OnSizeSet( targetSize ); + Control::OnSizeSet(targetSize); } -void SuperBlurView::OnSceneConnection( int depth ) +void SuperBlurView::OnSceneConnection(int depth) { - if( mTargetSize == Vector2::ZERO ) + if(mTargetSize == Vector2::ZERO) { return; } // Exception to the rule, chaining up first ensures visuals have SetOnScene called to create their renderers - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); Actor self = Self(); - for(unsigned int i=0; i 0 ) + if(i > 0) { - Renderer renderer = mRenderers[i]; - Property::Index index = renderer.RegisterProperty( ALPHA_UNIFORM_NAME, 0.f ); - Constraint constraint = Constraint::New( renderer, index, ActorOpacityConstraint(mBlurLevels, i-1) ); - constraint.AddSource( Source( self, mBlurStrengthPropertyIndex ) ); + Renderer renderer = mRenderers[i]; + Property::Index index = renderer.RegisterProperty(ALPHA_UNIFORM_NAME, 0.f); + Constraint constraint = Constraint::New(renderer, index, ActorOpacityConstraint(mBlurLevels, i - 1)); + constraint.AddSource(Source(self, mBlurStrengthPropertyIndex)); constraint.Apply(); } } - if( mInputTexture ) + if(mInputTexture) { - SetRendererTexture( mRenderers[0], mInputTexture ); + SetRendererTexture(mRenderers[0], mInputTexture); unsigned int i = 1; - for(; i // EXTERNAL INCLUDES -#include -#include -#include -#include #include #include -#include #include +#include +#include +#include +#include +#include // INTERNAL INCLUDES #include @@ -41,9 +41,9 @@ namespace * @param[in] actor The child actor to test against * @param[dimension] The dimension to test against */ -bool FitToChild( Actor actor, Dimension::Type dimension ) +bool FitToChild(Actor actor, Dimension::Type dimension) { - return actor.GetResizePolicy( dimension ) != ResizePolicy::FILL_TO_PARENT && actor.GetRelayoutSize( dimension ) > 0.0f; + return actor.GetResizePolicy(dimension) != ResizePolicy::FILL_TO_PARENT && actor.GetRelayoutSize(dimension) > 0.0f; } #if defined(DEBUG_ENABLED) @@ -51,60 +51,58 @@ bool FitToChild( Actor actor, Dimension::Type dimension ) // currently not called from code so compiler will optimize these away, kept here for future debugging #define TABLEVIEW_TAG "DALI Toolkit::TableView " -#define TV_LOG(fmt, args,...) Debug::LogMessage(Debug::DebugInfo, TABLEVIEW_TAG fmt, ## args) +#define TV_LOG(fmt, args, ...) Debug::LogMessage(Debug::DebugInfo, TABLEVIEW_TAG fmt, ##args) //#define TABLEVIEW_DEBUG 1 #if defined(TABLEVIEW_DEBUG) -void PrintArray( Array2d& array ) +void PrintArray(Array2d& array) { - TV_LOG( "Array2d size [%d,%d] \n", array.GetRows(), array.GetColumns() ); + TV_LOG("Array2d size [%d,%d] \n", array.GetRows(), array.GetColumns()); // print values - for( unsigned int i = 0; i < array.GetRows(); ++i ) + for(unsigned int i = 0; i < array.GetRows(); ++i) { - for( unsigned int j = 0; j < array.GetColumns(); ++j ) + for(unsigned int j = 0; j < array.GetColumns(); ++j) { - Dali::Toolkit::Internal::TableView::CellData data = array[i][j]; - char actor = ' '; - std::string actorName; - if( data.actor ) + Dali::Toolkit::Internal::TableView::CellData data = array[i][j]; + char actor = ' '; + std::string actorName; + if(data.actor) { - actor = 'A'; - actorName = data.actor.GetProperty< std::string >( Dali::Actor::Property::NAME ); + actor = 'A'; + actorName = data.actor.GetProperty(Dali::Actor::Property::NAME); } - TV_LOG("Array[%d,%d]=%c %s %d,%d,%d,%d ", i, j, actor, actorName.c_str(), - data.position.rowIndex, data.position.columnIndex, - data.position.rowSpan, data.position.columnSpan ); + TV_LOG("Array[%d,%d]=%c %s %d,%d,%d,%d ", i, j, actor, actorName.c_str(), data.position.rowIndex, data.position.columnIndex, data.position.rowSpan, data.position.columnSpan); } - TV_LOG( "\n" ); + TV_LOG("\n"); } } // debugging support, very useful when new features are added or bugs are hunted down // currently not called from code so compiler will optimize these away, kept here for future debugging -void PrintArray( Array2d& array ) +void PrintArray(Array2d& array) { - TV_LOG( "Array2d size [%d,%d] \n", array.GetRows(), array.GetColumns() ); + TV_LOG("Array2d size [%d,%d] \n", array.GetRows(), array.GetColumns()); // print values - for( unsigned int i = 0; i < array.GetRows(); ++i ) + for(unsigned int i = 0; i < array.GetRows(); ++i) { - for( unsigned int j = 0; j < array.GetColumns(); ++j ) + for(unsigned int j = 0; j < array.GetColumns(); ++j) { - TV_LOG( "Array[%d,%d]=%.2f,%.2f ", i, j, array[i][j].width, array[i][j].height ); + TV_LOG("Array[%d,%d]=%.2f,%.2f ", i, j, array[i][j].width, array[i][j].height); } - TV_LOG( "\n" ); + TV_LOG("\n"); } } // debugging support, very useful when new features are added or bugs are hunted down // currently not called from code so compiler will optimize these away, kept here for future debugging -void PrintVector( std::vector& array ) +void PrintVector(std::vector& array) { - TV_LOG( "vector, size [%d]\n", array.size() ); + TV_LOG("vector, size [%d]\n", array.size()); // print values - for( unsigned int i = 0; i < array.size(); ++i ) + for(unsigned int i = 0; i < array.size(); ++i) { - TV_LOG( "vector[%d]=%.2f ", i, array[i] ); + TV_LOG("vector[%d]=%.2f ", i, array[i]); } - TV_LOG( "\n" ); + TV_LOG("\n"); } #endif // defined(TABLEVIEW_DEBUG) #endif // defined(DEBUG_ENABLED) @@ -113,72 +111,70 @@ void PrintVector( std::vector& array ) namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // Type registration BaseHandle Create() { - return Toolkit::TableView::New( 0, 0 ); + return Toolkit::TableView::New(0, 0); } +// clang-format off // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TableView, Toolkit::Control, Create ); - -DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "rows", INTEGER, ROWS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "columns", INTEGER, COLUMNS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "cellPadding", VECTOR2, CELL_PADDING ) -DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "layoutRows", MAP, LAYOUT_ROWS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TableView, "layoutColumns", MAP, LAYOUT_COLUMNS ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellIndex", VECTOR2, CELL_INDEX ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "rowSpan", INTEGER, ROW_SPAN ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "columnSpan", INTEGER, COLUMN_SPAN ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellHorizontalAlignment", STRING, CELL_HORIZONTAL_ALIGNMENT ) -DALI_CHILD_PROPERTY_REGISTRATION( Toolkit, TableView, "cellVerticalAlignment", STRING, CELL_VERTICAL_ALIGNMENT ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TableView, Toolkit::Control, Create); + +DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "rows", INTEGER, ROWS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "columns", INTEGER, COLUMNS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "cellPadding", VECTOR2, CELL_PADDING ) +DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "layoutRows", MAP, LAYOUT_ROWS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TableView, "layoutColumns", MAP, LAYOUT_COLUMNS) + +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "cellIndex", VECTOR2, CELL_INDEX ) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "rowSpan", INTEGER, ROW_SPAN ) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "columnSpan", INTEGER, COLUMN_SPAN ) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "cellHorizontalAlignment", STRING, CELL_HORIZONTAL_ALIGNMENT) +DALI_CHILD_PROPERTY_REGISTRATION(Toolkit, TableView, "cellVerticalAlignment", STRING, CELL_VERTICAL_ALIGNMENT ) DALI_TYPE_REGISTRATION_END() const Scripting::StringEnum LAYOUT_POLICY_STRING_TABLE[] = { - { "fixed", Toolkit::TableView::FIXED }, - { "relative", Toolkit::TableView::RELATIVE }, - { "fill", Toolkit::TableView::FILL }, - { "fit", Toolkit::TableView::FIT } + {"fixed", Toolkit::TableView::FIXED }, + {"relative", Toolkit::TableView::RELATIVE}, + {"fill", Toolkit::TableView::FILL }, + {"fit", Toolkit::TableView::FIT } }; -const unsigned int LAYOUT_POLICY_STRING_TABLE_COUNT = sizeof(LAYOUT_POLICY_STRING_TABLE) / sizeof( LAYOUT_POLICY_STRING_TABLE[0] ); +const unsigned int LAYOUT_POLICY_STRING_TABLE_COUNT = sizeof(LAYOUT_POLICY_STRING_TABLE) / sizeof(LAYOUT_POLICY_STRING_TABLE[0]); const Scripting::StringEnum HORIZONTAL_ALIGNMENT_STRING_TABLE[] = { - {"left", HorizontalAlignment::LEFT}, + {"left", HorizontalAlignment::LEFT }, {"center", HorizontalAlignment::CENTER}, - {"right", HorizontalAlignment::RIGHT} + {"right", HorizontalAlignment::RIGHT } }; -const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE) / sizeof( HORIZONTAL_ALIGNMENT_STRING_TABLE[0] ); +const unsigned int HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE) / sizeof(HORIZONTAL_ALIGNMENT_STRING_TABLE[0]); const Scripting::StringEnum VERTICAL_ALIGNMENT_STRING_TABLE[] = { - {"top", VerticalAlignment::TOP}, + {"top", VerticalAlignment::TOP }, {"center", VerticalAlignment::CENTER}, {"bottom", VerticalAlignment::BOTTOM} }; -const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(VERTICAL_ALIGNMENT_STRING_TABLE) / sizeof( VERTICAL_ALIGNMENT_STRING_TABLE[0] ); - +const unsigned int VERTICAL_ALIGNMENT_STRING_TABLE_COUNT = sizeof(VERTICAL_ALIGNMENT_STRING_TABLE) / sizeof(VERTICAL_ALIGNMENT_STRING_TABLE[0]); +// clang-format on } // Unnamed namespace -Toolkit::TableView TableView::New( unsigned int initialRows, unsigned int initialColumns ) +Toolkit::TableView TableView::New(unsigned int initialRows, unsigned int initialColumns) { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< TableView > impl = new TableView( initialRows, initialColumns ); + IntrusivePtr impl = new TableView(initialRows, initialColumns); // Pass ownership to CustomActor handle - Toolkit::TableView handle( *impl ); + Toolkit::TableView handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -187,112 +183,112 @@ Toolkit::TableView TableView::New( unsigned int initialRows, unsigned int initia return handle; } -bool TableView::AddChild( Actor& child, const Toolkit::TableView::CellPosition& position ) +bool TableView::AddChild(Actor& child, const Toolkit::TableView::CellPosition& position) { // check that the child is valid - DALI_ASSERT_ALWAYS( child ); + DALI_ASSERT_ALWAYS(child); // if child is already parented, we adopt it child.Unparent(); // check if we need to expand our data array - if( position.rowIndex >= mCellData.GetRows() ) + if(position.rowIndex >= mCellData.GetRows()) { // only adding new rows - ResizeContainers( position.rowIndex + 1, mCellData.GetColumns() ); + ResizeContainers(position.rowIndex + 1, mCellData.GetColumns()); } - if( position.columnIndex >= mCellData.GetColumns() ) + if(position.columnIndex >= mCellData.GetColumns()) { // only adding new columns - ResizeContainers( mCellData.GetRows(), position.columnIndex + 1 ); + ResizeContainers(mCellData.GetRows(), position.columnIndex + 1); } // check if there already is something in this cell - if( mCellData[ position.rowIndex ][ position.columnIndex ].actor ) + if(mCellData[position.rowIndex][position.columnIndex].actor) { return false; // cannot share a cell, it would complicate all logic and not bring much benefit } - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); // adopt the child - Self().Add( child ); + Self().Add(child); // if child spans multiple rows of columns - if( ( position.rowSpan > 1 ) && ( position.rowIndex + position.rowSpan > mCellData.GetRows() ) ) + if((position.rowSpan > 1) && (position.rowIndex + position.rowSpan > mCellData.GetRows())) { // increase table size for the full span, only increasing rows - ResizeContainers( position.rowIndex + position.rowSpan, mCellData.GetColumns() ); + ResizeContainers(position.rowIndex + position.rowSpan, mCellData.GetColumns()); } - if( ( position.columnSpan > 1 ) && ( position.columnIndex + position.columnSpan > mCellData.GetColumns() ) ) + if((position.columnSpan > 1) && (position.columnIndex + position.columnSpan > mCellData.GetColumns())) { // increase table size for the full span, only increasing columns - ResizeContainers( mCellData.GetRows(), position.columnIndex + position.columnSpan ); + ResizeContainers(mCellData.GetRows(), position.columnIndex + position.columnSpan); } // Fill in all cells that need the data CellData data; - data.actor = child; + data.actor = child; data.position = position; - for( unsigned int row = position.rowIndex; row < ( position.rowIndex + position.rowSpan ); ++row ) + for(unsigned int row = position.rowIndex; row < (position.rowIndex + position.rowSpan); ++row) { // store same information to all cells, this way we can identify // if a cell is the prime location of an actor or a spanned one - for( unsigned int column = position.columnIndex; column < ( position.columnIndex + position.columnSpan ); ++column ) + for(unsigned int column = position.columnIndex; column < (position.columnIndex + position.columnSpan); ++column) { // store same information to all cells, this way we can identify // if a cell is the prime location of an actor or a spanned one - mCellData[ row ][ column ] = data; + mCellData[row][column] = data; } } // Relayout the whole table - if( mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT && position.rowSpan == 1 ) + if(mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT && position.rowSpan == 1) { mRowDirty = true; } - if( mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT && position.columnSpan == 1 ) + if(mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT && position.columnSpan == 1) { mColumnDirty = true; } RelayoutRequest(); - return true; // Addition successful + return true; // Addition successful } -Actor TableView::GetChildAt( const Toolkit::TableView::CellPosition& position ) +Actor TableView::GetChildAt(const Toolkit::TableView::CellPosition& position) { - if( ( position.rowIndex < mCellData.GetRows() ) && ( position.columnIndex < mCellData.GetColumns() ) ) + if((position.rowIndex < mCellData.GetRows()) && (position.columnIndex < mCellData.GetColumns())) { - return mCellData[ position.rowIndex ][ position.columnIndex ].actor; + return mCellData[position.rowIndex][position.columnIndex].actor; } // Return an empty handle return Actor(); } -Actor TableView::RemoveChildAt( const Toolkit::TableView::CellPosition& position ) +Actor TableView::RemoveChildAt(const Toolkit::TableView::CellPosition& position) { // get the child handle - Actor child = GetChildAt( position ); + Actor child = GetChildAt(position); // if no real actor there, nothing else to be done - if( child ) + if(child) { - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); // Remove the child, this will trigger a call to OnChildRemove - Self().Remove( child ); + Self().Remove(child); // relayout the table only if instances were found - if( RemoveAllInstances( child ) ) + if(RemoveAllInstances(child)) { - if( mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT ) + if(mRowData[position.rowIndex].sizePolicy == Toolkit::TableView::FIT) { mRowDirty = true; } - if( mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT ) + if(mColumnData[position.columnIndex].sizePolicy == Toolkit::TableView::FIT) { mColumnDirty = true; } @@ -303,22 +299,22 @@ Actor TableView::RemoveChildAt( const Toolkit::TableView::CellPosition& position return child; } -bool TableView::FindChildPosition( const Actor& child, Toolkit::TableView::CellPosition& positionOut ) +bool TableView::FindChildPosition(const Actor& child, Toolkit::TableView::CellPosition& positionOut) { // Only find valid child actors - if( child ) + if(child) { // Walk through the layout data - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount; ++row ) + for(unsigned int row = 0; row < rowCount; ++row) { - for( unsigned int column = 0; column < columnCount; ++column ) + for(unsigned int column = 0; column < columnCount; ++column) { - if( mCellData[ row ][ column ].actor == child ) + if(mCellData[row][column].actor == child) { - positionOut = mCellData[ row ][ column ].position; + positionOut = mCellData[row][column].position; return true; } } @@ -328,33 +324,33 @@ bool TableView::FindChildPosition( const Actor& child, Toolkit::TableView::CellP return false; } -void TableView::InsertRow( unsigned int rowIndex ) +void TableView::InsertRow(unsigned int rowIndex) { - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); - mCellData.InsertRow( rowIndex ); + mCellData.InsertRow(rowIndex); // Need to update the cell infos for the items that moved - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount; ++row ) + for(unsigned int row = 0; row < rowCount; ++row) { - for( unsigned int column = 0; column < columnCount; ++column ) + for(unsigned int column = 0; column < columnCount; ++column) { - Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; + Toolkit::TableView::CellPosition& position = mCellData[row][column].position; // If cell is spanning and above and spans to inserted row - if( ( position.rowSpan > 1 ) && ( position.rowIndex <= rowIndex ) && - ( position.rowIndex + position.rowSpan > rowIndex ) ) + if((position.rowSpan > 1) && (position.rowIndex <= rowIndex) && + (position.rowIndex + position.rowSpan > rowIndex)) { // Increment span position.rowSpan++; // Copy cell to occupy the new column - mCellData[ rowIndex ][ column ] = mCellData[ row ][ column ]; + mCellData[rowIndex][column] = mCellData[row][column]; } - else if( row > rowIndex ) // If below of inserted row, increase row index + else if(row > rowIndex) // If below of inserted row, increase row index { // Increment index position.rowIndex++; @@ -363,51 +359,51 @@ void TableView::InsertRow( unsigned int rowIndex ) } // Expand row data array - mRowData.Insert( mRowData.Begin() + rowIndex, RowColumnData() ); + mRowData.Insert(mRowData.Begin() + rowIndex, RowColumnData()); // Sizes may have changed, so relayout mRowDirty = true; RelayoutRequest(); } -void TableView::DeleteRow( unsigned int rowIndex ) +void TableView::DeleteRow(unsigned int rowIndex) { - std::vector< Actor > ignored; - DeleteRow( rowIndex, ignored ); + std::vector ignored; + DeleteRow(rowIndex, ignored); } -void TableView::DeleteRow( unsigned int rowIndex, std::vector& removed ) +void TableView::DeleteRow(unsigned int rowIndex, std::vector& removed) { - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); // Delete the row - std::vector< CellData > lost; - mCellData.DeleteRow( rowIndex, lost ); + std::vector lost; + mCellData.DeleteRow(rowIndex, lost); // Need to update the cell infos for the items that moved - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount; ++row ) + for(unsigned int row = 0; row < rowCount; ++row) { - for( unsigned int column = 0; column < columnCount; ++column ) + for(unsigned int column = 0; column < columnCount; ++column) { - Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; + Toolkit::TableView::CellPosition& position = mCellData[row][column].position; // If cell is spanning and above and spans to deleted row - if( ( position.rowSpan > 1 ) && ( position.rowIndex <= rowIndex ) && - ( position.rowIndex + position.rowSpan > rowIndex ) ) + if((position.rowSpan > 1) && (position.rowIndex <= rowIndex) && + (position.rowIndex + position.rowSpan > rowIndex)) { // Decrement span - if( position.rowSpan > 1 ) + if(position.rowSpan > 1) { position.rowSpan--; } } - else if( row >= rowIndex ) // If below of or at the inserted row, decrease row index + else if(row >= rowIndex) // If below of or at the inserted row, decrease row index { // Decrement index - if( position.rowIndex > 0 ) + if(position.rowIndex > 0) { position.rowIndex--; } @@ -416,10 +412,10 @@ void TableView::DeleteRow( unsigned int rowIndex, std::vector& removed ) } // 1 row removed, 0 columns - RemoveAndGetLostActors( lost, removed, 1u, 0u ); + RemoveAndGetLostActors(lost, removed, 1u, 0u); // Contract row data array - mRowData.Erase( mRowData.Begin() + rowIndex ); + mRowData.Erase(mRowData.Begin() + rowIndex); // Sizes may have changed, so relayout mRowDirty = true; @@ -429,34 +425,34 @@ void TableView::DeleteRow( unsigned int rowIndex, std::vector& removed ) RelayoutRequest(); } -void TableView::InsertColumn( unsigned int columnIndex ) +void TableView::InsertColumn(unsigned int columnIndex) { - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); // Insert the new column - mCellData.InsertColumn( columnIndex ); + mCellData.InsertColumn(columnIndex); // Need to update the cell infos for the items that moved - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount; ++row ) + for(unsigned int row = 0; row < rowCount; ++row) { - for( unsigned int column = 0; column < columnCount; ++column ) + for(unsigned int column = 0; column < columnCount; ++column) { - Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; + Toolkit::TableView::CellPosition& position = mCellData[row][column].position; // If cell is spanning and left side and spans to inserted column - if( ( position.columnSpan > 1 ) && ( position.columnIndex <= columnIndex ) && - ( position.columnIndex + position.columnSpan > columnIndex ) ) + if((position.columnSpan > 1) && (position.columnIndex <= columnIndex) && + (position.columnIndex + position.columnSpan > columnIndex)) { // Increment span position.columnSpan++; // Copy cell to occupy the new column - mCellData[ row ][ columnIndex ] = mCellData[ row ][ column ]; + mCellData[row][columnIndex] = mCellData[row][column]; } - else if( column > columnIndex ) // If on the right side of inserted column, increase column index + else if(column > columnIndex) // If on the right side of inserted column, increase column index { // Increment index position.columnIndex++; @@ -465,51 +461,51 @@ void TableView::InsertColumn( unsigned int columnIndex ) } // Expand column data array - mColumnData.Insert( mColumnData.Begin() + columnIndex, RowColumnData() ); + mColumnData.Insert(mColumnData.Begin() + columnIndex, RowColumnData()); // Sizes may have changed so relayout mColumnDirty = true; RelayoutRequest(); } -void TableView::DeleteColumn( unsigned int columnIndex ) +void TableView::DeleteColumn(unsigned int columnIndex) { - std::vector< Actor > ignored; - DeleteColumn( columnIndex, ignored ); + std::vector ignored; + DeleteColumn(columnIndex, ignored); } -void TableView::DeleteColumn( unsigned int columnIndex, std::vector& removed ) +void TableView::DeleteColumn(unsigned int columnIndex, std::vector& removed) { - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); // Remove the column - std::vector< CellData > lost; - mCellData.DeleteColumn( columnIndex, lost ); + std::vector lost; + mCellData.DeleteColumn(columnIndex, lost); // Need to update the cell infos for the items that moved - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount; ++row ) + for(unsigned int row = 0; row < rowCount; ++row) { - for( unsigned int column = 0; column < columnCount; ++column ) + for(unsigned int column = 0; column < columnCount; ++column) { - Toolkit::TableView::CellPosition& position = mCellData[ row ][ column ].position; + Toolkit::TableView::CellPosition& position = mCellData[row][column].position; // If cell is spanning and left side and spans to inserted column - if( ( position.columnSpan > 1 ) && ( position.columnIndex <= columnIndex ) && - ( position.columnIndex + position.columnSpan > columnIndex ) ) + if((position.columnSpan > 1) && (position.columnIndex <= columnIndex) && + (position.columnIndex + position.columnSpan > columnIndex)) { // Decrement span - if( position.columnSpan > 1 ) + if(position.columnSpan > 1) { position.columnSpan--; } } - else if( column >= columnIndex ) // If on the right side of or at the inserted column, decrease column index + else if(column >= columnIndex) // If on the right side of or at the inserted column, decrease column index { // Decrement index - if( position.columnIndex > 0 ) + if(position.columnIndex > 0) { position.columnIndex--; } @@ -518,10 +514,10 @@ void TableView::DeleteColumn( unsigned int columnIndex, std::vector& remo } // 0 rows, 1 column removed - RemoveAndGetLostActors( lost, removed, 0u, 1u ); + RemoveAndGetLostActors(lost, removed, 0u, 1u); // Contract column data array - mColumnData.Erase( mColumnData.Begin() + columnIndex ); + mColumnData.Erase(mColumnData.Begin() + columnIndex); // Size may have changed so relayout mColumnDirty = true; @@ -531,52 +527,52 @@ void TableView::DeleteColumn( unsigned int columnIndex, std::vector& remo RelayoutRequest(); } -void TableView::Resize( unsigned int rows, unsigned int columns ) +void TableView::Resize(unsigned int rows, unsigned int columns) { - std::vector< Actor > ignored; - Resize( rows, columns, ignored ); + std::vector ignored; + Resize(rows, columns, ignored); } -void TableView::Resize( unsigned int rows, unsigned int columns, std::vector& removed ) +void TableView::Resize(unsigned int rows, unsigned int columns, std::vector& removed) { - RelayoutingLock lock( *this ); + RelayoutingLock lock(*this); - unsigned int oldRows = GetRows(); + unsigned int oldRows = GetRows(); unsigned int oldColumns = GetColumns(); // Resize data array - std::vector< CellData > lost; - ResizeContainers( rows, columns, lost ); + std::vector lost; + ResizeContainers(rows, columns, lost); // Calculate if we lost rows unsigned int rowsRemoved = 0; - unsigned int newRows = GetRows(); + unsigned int newRows = GetRows(); - if( oldRows < newRows ) + if(oldRows < newRows) { rowsRemoved = newRows - oldRows; } // Calculate if we lost columns unsigned int columnsRemoved = 0; - unsigned int newColumns = GetColumns(); - if( oldColumns < newColumns ) + unsigned int newColumns = GetColumns(); + if(oldColumns < newColumns) { rowsRemoved = newColumns - oldColumns; } - RemoveAndGetLostActors( lost, removed, rowsRemoved, columnsRemoved ); + RemoveAndGetLostActors(lost, removed, rowsRemoved, columnsRemoved); // Sizes may have changed so request a relayout - mRowDirty = true; + mRowDirty = true; mColumnDirty = true; RelayoutRequest(); } -void TableView::SetCellPadding( Size padding ) +void TableView::SetCellPadding(Size padding) { // If padding really changed - if( padding != mPadding ) + if(padding != mPadding) { mPadding = padding; @@ -589,125 +585,125 @@ Size TableView::GetCellPadding() return mPadding; } -void TableView::SetFitHeight( unsigned int rowIndex ) +void TableView::SetFitHeight(unsigned int rowIndex) { - DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); + DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size()); - if( mRowData[ rowIndex ].sizePolicy != Toolkit::TableView::FIT ) + if(mRowData[rowIndex].sizePolicy != Toolkit::TableView::FIT) { - mRowData[ rowIndex ].sizePolicy = Toolkit::TableView::FIT; + mRowData[rowIndex].sizePolicy = Toolkit::TableView::FIT; mRowDirty = true; RelayoutRequest(); } } -bool TableView::IsFitHeight( unsigned int rowIndex ) const +bool TableView::IsFitHeight(unsigned int rowIndex) const { - DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); + DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size()); - return mRowData[ rowIndex ].sizePolicy == Toolkit::TableView::FIT; + return mRowData[rowIndex].sizePolicy == Toolkit::TableView::FIT; } -void TableView::SetFitWidth( unsigned int columnIndex ) +void TableView::SetFitWidth(unsigned int columnIndex) { - DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); + DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size()); - if( mColumnData[ columnIndex ].sizePolicy != Toolkit::TableView::FIT ) + if(mColumnData[columnIndex].sizePolicy != Toolkit::TableView::FIT) { - mColumnData[ columnIndex ].sizePolicy = Toolkit::TableView::FIT; + mColumnData[columnIndex].sizePolicy = Toolkit::TableView::FIT; mColumnDirty = true; RelayoutRequest(); } } -bool TableView::IsFitWidth( unsigned int columnIndex ) const +bool TableView::IsFitWidth(unsigned int columnIndex) const { - DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); + DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size()); - return mColumnData[ columnIndex ].sizePolicy == Toolkit::TableView::FIT; + return mColumnData[columnIndex].sizePolicy == Toolkit::TableView::FIT; } -void TableView::SetFixedHeight( unsigned int rowIndex, float height ) +void TableView::SetFixedHeight(unsigned int rowIndex, float height) { - DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); + DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size()); - RowColumnData& data = mRowData[ rowIndex ]; - data.size = height; - data.sizePolicy = Toolkit::TableView::FIXED; + RowColumnData& data = mRowData[rowIndex]; + data.size = height; + data.sizePolicy = Toolkit::TableView::FIXED; mRowDirty = true; RelayoutRequest(); } -float TableView::GetFixedHeight( unsigned int rowIndex ) const +float TableView::GetFixedHeight(unsigned int rowIndex) const { - DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); + DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size()); - return mRowData[ rowIndex ].size; + return mRowData[rowIndex].size; } -void TableView::SetFixedWidth( unsigned int columnIndex, float width ) +void TableView::SetFixedWidth(unsigned int columnIndex, float width) { - DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); + DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size()); - RowColumnData& data = mColumnData[ columnIndex ]; - data.size = width; - data.sizePolicy = Toolkit::TableView::FIXED; + RowColumnData& data = mColumnData[columnIndex]; + data.size = width; + data.sizePolicy = Toolkit::TableView::FIXED; mColumnDirty = true; RelayoutRequest(); } -float TableView::GetFixedWidth( unsigned int columnIndex ) const +float TableView::GetFixedWidth(unsigned int columnIndex) const { - DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); + DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size()); - return mColumnData[ columnIndex ].size; + return mColumnData[columnIndex].size; } -void TableView::SetRelativeHeight( unsigned int rowIndex, float heightPercentage ) +void TableView::SetRelativeHeight(unsigned int rowIndex, float heightPercentage) { - DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); + DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size()); - RowColumnData& data = mRowData[ rowIndex ]; - data.fillRatio = heightPercentage; - data.sizePolicy = Toolkit::TableView::RELATIVE; + RowColumnData& data = mRowData[rowIndex]; + data.fillRatio = heightPercentage; + data.sizePolicy = Toolkit::TableView::RELATIVE; mRowDirty = true; RelayoutRequest(); } -float TableView::GetRelativeHeight( unsigned int rowIndex ) const +float TableView::GetRelativeHeight(unsigned int rowIndex) const { - DALI_ASSERT_ALWAYS( rowIndex < mRowData.Size() ); + DALI_ASSERT_ALWAYS(rowIndex < mRowData.Size()); - return mRowData[ rowIndex ].fillRatio; + return mRowData[rowIndex].fillRatio; } -void TableView::SetRelativeWidth( unsigned int columnIndex, float widthPercentage ) +void TableView::SetRelativeWidth(unsigned int columnIndex, float widthPercentage) { - DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); + DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size()); - RowColumnData& data = mColumnData[ columnIndex ]; - data.fillRatio = widthPercentage; - data.sizePolicy = Toolkit::TableView::RELATIVE; + RowColumnData& data = mColumnData[columnIndex]; + data.fillRatio = widthPercentage; + data.sizePolicy = Toolkit::TableView::RELATIVE; mColumnDirty = true; RelayoutRequest(); } -float TableView::GetRelativeWidth( unsigned int columnIndex ) const +float TableView::GetRelativeWidth(unsigned int columnIndex) const { - DALI_ASSERT_ALWAYS( columnIndex < mColumnData.Size() ); + DALI_ASSERT_ALWAYS(columnIndex < mColumnData.Size()); - return mColumnData[ columnIndex ].fillRatio; + return mColumnData[columnIndex].fillRatio; } -void TableView::OnCalculateRelayoutSize( Dimension::Type dimension ) +void TableView::OnCalculateRelayoutSize(Dimension::Type dimension) { - if( (dimension & Dimension::WIDTH) && mColumnDirty ) + if((dimension & Dimension::WIDTH) && mColumnDirty) { /* * FIXED and FIT have size in pixel @@ -715,7 +711,7 @@ void TableView::OnCalculateRelayoutSize( Dimension::Type dimension ) * * Need to update the size for FIT column here */ - CalculateFitSizes( mColumnData, Dimension::WIDTH ); + CalculateFitSizes(mColumnData, Dimension::WIDTH); /* RELATIVE and FILL have size in ratio * Their size in pixel is not available until we get the negotiated size for the whole table @@ -723,39 +719,39 @@ void TableView::OnCalculateRelayoutSize( Dimension::Type dimension ) * * Need to update the ratio for FILL column here */ - CalculateFillSizes( mColumnData ); + CalculateFillSizes(mColumnData); - mFixedTotals.width = CalculateTotalFixedSize( mColumnData ); + mFixedTotals.width = CalculateTotalFixedSize(mColumnData); } - if( (dimension & Dimension::HEIGHT) && mRowDirty ) + if((dimension & Dimension::HEIGHT) && mRowDirty) { // refer to the comment above - CalculateFitSizes( mRowData, Dimension::HEIGHT ); + CalculateFitSizes(mRowData, Dimension::HEIGHT); // refer to the comment above - CalculateFillSizes( mRowData ); + CalculateFillSizes(mRowData); - mFixedTotals.height = CalculateTotalFixedSize( mRowData ); + mFixedTotals.height = CalculateTotalFixedSize(mRowData); } } -void TableView::OnLayoutNegotiated( float size, Dimension::Type dimension ) +void TableView::OnLayoutNegotiated(float size, Dimension::Type dimension) { // Update the column sizes - if( (dimension & Dimension::WIDTH) && mColumnDirty ) + if((dimension & Dimension::WIDTH) && mColumnDirty) { float remainingSize = size - mFixedTotals.width; - if( remainingSize < 0.0f ) + if(remainingSize < 0.0f) { remainingSize = 0.0f; } // update every column position in ColumnData array float cumulatedWidth = 0.0f; - for( auto&& element : mColumnData ) + for(auto&& element : mColumnData) { - if( element.sizePolicy == Toolkit::TableView::FILL || element.sizePolicy == Toolkit::TableView::RELATIVE ) + if(element.sizePolicy == Toolkit::TableView::FILL || element.sizePolicy == Toolkit::TableView::RELATIVE) { element.size = element.fillRatio * remainingSize; } @@ -768,24 +764,24 @@ void TableView::OnLayoutNegotiated( float size, Dimension::Type dimension ) } // Update the row sizes - if( (dimension & Dimension::HEIGHT) && mRowDirty ) + if((dimension & Dimension::HEIGHT) && mRowDirty) { float remainingSize = size - mFixedTotals.height; - if( remainingSize < 0.0f ) + if(remainingSize < 0.0f) { remainingSize = 0.0f; } // update every row position in RowData array float cumulatedHeight = 0.0f; - for( unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row ) + for(unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row) { - if( mRowData[ row ].sizePolicy == Toolkit::TableView::FILL || mRowData[ row ].sizePolicy == Toolkit::TableView::RELATIVE) + if(mRowData[row].sizePolicy == Toolkit::TableView::FILL || mRowData[row].sizePolicy == Toolkit::TableView::RELATIVE) { - mRowData[ row ].size = mRowData[ row ].fillRatio * remainingSize; + mRowData[row].size = mRowData[row].fillRatio * remainingSize; } - cumulatedHeight += mRowData[ row ].size; + cumulatedHeight += mRowData[row].size; mRowData[row].position = cumulatedHeight; } @@ -793,93 +789,93 @@ void TableView::OnLayoutNegotiated( float size, Dimension::Type dimension ) } } -void TableView::OnSizeSet( const Vector3& size ) +void TableView::OnSizeSet(const Vector3& size) { // If this table view is size negotiated by another actor or control, then the // rows and columns must be recalculated or the new size will not take effect. mRowDirty = mColumnDirty = true; RelayoutRequest(); - Control::OnSizeSet( size ); + Control::OnSizeSet(size); } -void TableView::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void TableView::OnRelayout(const Vector2& size, RelayoutContainer& container) { // Go through the layout data float totalWidth = 0.0; - Dali::LayoutDirection::Type layoutDirection = static_cast( Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get() ); + Dali::LayoutDirection::Type layoutDirection = static_cast(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { - for (auto&& element : mColumnData) + for(auto&& element : mColumnData) { totalWidth += element.size; } } - for( unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row ) + for(unsigned int row = 0, rowCount = mCellData.GetRows(); row < rowCount; ++row) { - for( unsigned int column = 0, columnCount = mCellData.GetColumns(); column < columnCount; ++column ) + for(unsigned int column = 0, columnCount = mCellData.GetColumns(); column < columnCount; ++column) { - CellData& cellData= mCellData[ row ][ column ]; - Actor& actor = cellData.actor; + CellData& cellData = mCellData[row][column]; + Actor& actor = cellData.actor; const Toolkit::TableView::CellPosition position = cellData.position; // If there is an actor and this is the main cell of the actor. // An actor can be in multiple cells if its row or column span is more than 1. // We however must lay out each actor only once. - if( actor && position.rowIndex == row && position.columnIndex == column ) + if(actor && position.rowIndex == row && position.columnIndex == column) { // Anchor actor to top left of the cell - if( actor.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >() ) + if(actor.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get()) { - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); } - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); - Padding padding = actor.GetProperty( Actor::Property::PADDING ); + Padding padding = actor.GetProperty(Actor::Property::PADDING); float left = (column > 0) ? mColumnData[column - 1].position : 0.f; float right; - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { right = totalWidth - left; - left = right - mColumnData[column].size; + left = right - mColumnData[column].size; } else { right = left + mColumnData[column].size; } - float top = row > 0 ? mRowData[row-1].position : 0.f; - float bottom = mRowData[row+position.rowSpan-1].position; + float top = row > 0 ? mRowData[row - 1].position : 0.f; + float bottom = mRowData[row + position.rowSpan - 1].position; - if( cellData.horizontalAlignment == HorizontalAlignment::LEFT ) + if(cellData.horizontalAlignment == HorizontalAlignment::LEFT) { - actor.SetProperty( Actor::Property::POSITION_X, left + mPadding.width + padding.left ); + actor.SetProperty(Actor::Property::POSITION_X, left + mPadding.width + padding.left); } - else if( cellData.horizontalAlignment == HorizontalAlignment::RIGHT ) + else if(cellData.horizontalAlignment == HorizontalAlignment::RIGHT) { - actor.SetProperty( Actor::Property::POSITION_X, right - mPadding.width - padding.right - actor.GetRelayoutSize( Dimension::WIDTH ) ); + actor.SetProperty(Actor::Property::POSITION_X, right - mPadding.width - padding.right - actor.GetRelayoutSize(Dimension::WIDTH)); } else //if( cellData.horizontalAlignment == HorizontalAlignment::CENTER ) { - actor.SetProperty( Actor::Property::POSITION_X, (left + right + padding.left - padding.right - actor.GetRelayoutSize( Dimension::WIDTH )) * 0.5f ); + actor.SetProperty(Actor::Property::POSITION_X, (left + right + padding.left - padding.right - actor.GetRelayoutSize(Dimension::WIDTH)) * 0.5f); } - if( cellData.verticalAlignment == VerticalAlignment::TOP ) + if(cellData.verticalAlignment == VerticalAlignment::TOP) { - actor.SetProperty( Actor::Property::POSITION_Y, top + mPadding.height + padding.top ); + actor.SetProperty(Actor::Property::POSITION_Y, top + mPadding.height + padding.top); } - else if( cellData.verticalAlignment == VerticalAlignment::BOTTOM ) + else if(cellData.verticalAlignment == VerticalAlignment::BOTTOM) { - actor.SetProperty( Actor::Property::POSITION_Y, bottom - mPadding.height - padding.bottom - actor.GetRelayoutSize( Dimension::HEIGHT ) ); + actor.SetProperty(Actor::Property::POSITION_Y, bottom - mPadding.height - padding.bottom - actor.GetRelayoutSize(Dimension::HEIGHT)); } else //if( cellData.verticalAlignment = VerticalAlignment::CENTER ) { - actor.SetProperty( Actor::Property::POSITION_Y, (top + bottom + padding.top - padding.bottom - actor.GetRelayoutSize( Dimension::HEIGHT )) * 0.5f ); + actor.SetProperty(Actor::Property::POSITION_Y, (top + bottom + padding.top - padding.bottom - actor.GetRelayoutSize(Dimension::HEIGHT)) * 0.5f); } } } @@ -896,23 +892,23 @@ unsigned int TableView::GetColumns() return mCellData.GetColumns(); } -void TableView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void TableView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::TableView tableView = Toolkit::TableView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TableView tableView = Toolkit::TableView::DownCast(Dali::BaseHandle(object)); - if( tableView ) + if(tableView) { - TableView& tableViewImpl( GetImpl( tableView ) ); - switch( index ) + TableView& tableViewImpl(GetImpl(tableView)); + switch(index) { case Toolkit::TableView::Property::ROWS: { int rows = 0; - if( value.Get( rows ) && rows >= 0 ) + if(value.Get(rows) && rows >= 0) { - if( static_cast(rows) != tableViewImpl.GetRows() ) + if(static_cast(rows) != tableViewImpl.GetRows()) { - tableViewImpl.Resize( rows, tableViewImpl.GetColumns() ); + tableViewImpl.Resize(rows, tableViewImpl.GetColumns()); } } break; @@ -920,53 +916,53 @@ void TableView::SetProperty( BaseObject* object, Property::Index index, const Pr case Toolkit::TableView::Property::COLUMNS: { int columns = 0; - if( value.Get( columns ) && columns >= 0 ) + if(value.Get(columns) && columns >= 0) { - if( static_cast( columns ) != tableViewImpl.GetColumns() ) + if(static_cast(columns) != tableViewImpl.GetColumns()) { - tableViewImpl.Resize( tableViewImpl.GetRows(), value.Get() ); + tableViewImpl.Resize(tableViewImpl.GetRows(), value.Get()); } } break; } case Toolkit::TableView::Property::CELL_PADDING: { - tableViewImpl.SetCellPadding( value.Get() ); + tableViewImpl.SetCellPadding(value.Get()); break; } case Toolkit::TableView::Property::LAYOUT_ROWS: { - SetHeightOrWidthProperty( tableViewImpl, &TableView::SetFixedHeight, &TableView::SetRelativeHeight, &TableView::SetFitHeight, value ); + SetHeightOrWidthProperty(tableViewImpl, &TableView::SetFixedHeight, &TableView::SetRelativeHeight, &TableView::SetFitHeight, value); break; } case Toolkit::TableView::Property::LAYOUT_COLUMNS: { - SetHeightOrWidthProperty( tableViewImpl, &TableView::SetFixedWidth, &TableView::SetRelativeWidth, &TableView::SetFitWidth, value ); + SetHeightOrWidthProperty(tableViewImpl, &TableView::SetFixedWidth, &TableView::SetRelativeWidth, &TableView::SetFitWidth, value); break; } } } } -Property::Value TableView::GetProperty( BaseObject* object, Property::Index index ) +Property::Value TableView::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::TableView tableView = Toolkit::TableView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TableView tableView = Toolkit::TableView::DownCast(Dali::BaseHandle(object)); - if( tableView ) + if(tableView) { - TableView& tableViewImpl( GetImpl( tableView ) ); - switch( index ) + TableView& tableViewImpl(GetImpl(tableView)); + switch(index) { case Toolkit::TableView::Property::ROWS: { - value = static_cast( tableViewImpl.GetRows() ); + value = static_cast(tableViewImpl.GetRows()); break; } case Toolkit::TableView::Property::COLUMNS: { - value = static_cast( tableViewImpl.GetColumns() ); + value = static_cast(tableViewImpl.GetColumns()); break; } case Toolkit::TableView::Property::CELL_PADDING: @@ -990,52 +986,52 @@ Property::Value TableView::GetProperty( BaseObject* object, Property::Index inde return value; } -void TableView::OnChildAdd( Actor& child ) +void TableView::OnChildAdd(Actor& child) { - if( ! mLayoutingChild ) + if(!mLayoutingChild) { // Ensure we're not in the middle of laying out children // Check child properties on actor to decide its position inside the table HorizontalAlignment::Type horizontalAlignment = HorizontalAlignment::LEFT; - VerticalAlignment::Type verticalAlignment = VerticalAlignment::TOP; + VerticalAlignment::Type verticalAlignment = VerticalAlignment::TOP; - if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT ) != Property::NONE ) + if(child.GetPropertyType(Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT) != Property::NONE) { - std::string value = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT ).Get(); - Scripting::GetEnumeration< HorizontalAlignment::Type >( value.c_str(), - HORIZONTAL_ALIGNMENT_STRING_TABLE, - HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT, - horizontalAlignment ); + std::string value = child.GetProperty(Toolkit::TableView::ChildProperty::CELL_HORIZONTAL_ALIGNMENT).Get(); + Scripting::GetEnumeration(value.c_str(), + HORIZONTAL_ALIGNMENT_STRING_TABLE, + HORIZONTAL_ALIGNMENT_STRING_TABLE_COUNT, + horizontalAlignment); } - if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT ) != Property::NONE ) + if(child.GetPropertyType(Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT) != Property::NONE) { - std::string value = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT ).Get(); - Scripting::GetEnumeration< VerticalAlignment::Type >( value.c_str(), - VERTICAL_ALIGNMENT_STRING_TABLE, - VERTICAL_ALIGNMENT_STRING_TABLE_COUNT, - verticalAlignment ); + std::string value = child.GetProperty(Toolkit::TableView::ChildProperty::CELL_VERTICAL_ALIGNMENT).Get(); + Scripting::GetEnumeration(value.c_str(), + VERTICAL_ALIGNMENT_STRING_TABLE, + VERTICAL_ALIGNMENT_STRING_TABLE_COUNT, + verticalAlignment); } Toolkit::TableView::CellPosition cellPosition; - if( child.GetPropertyType( Toolkit::TableView::ChildProperty::ROW_SPAN ) != Property::NONE ) + if(child.GetPropertyType(Toolkit::TableView::ChildProperty::ROW_SPAN) != Property::NONE) { - cellPosition.rowSpan = child.GetProperty( Toolkit::TableView::ChildProperty::ROW_SPAN ).Get< int >(); + cellPosition.rowSpan = child.GetProperty(Toolkit::TableView::ChildProperty::ROW_SPAN).Get(); } - if( child.GetPropertyType( Toolkit::TableView::ChildProperty::COLUMN_SPAN ) != Property::NONE ) + if(child.GetPropertyType(Toolkit::TableView::ChildProperty::COLUMN_SPAN) != Property::NONE) { - cellPosition.columnSpan = child.GetProperty( Toolkit::TableView::ChildProperty::COLUMN_SPAN ).Get< int >(); + cellPosition.columnSpan = child.GetProperty(Toolkit::TableView::ChildProperty::COLUMN_SPAN).Get(); } - if( child.GetPropertyType( Toolkit::TableView::ChildProperty::CELL_INDEX ) != Property::NONE ) + if(child.GetPropertyType(Toolkit::TableView::ChildProperty::CELL_INDEX) != Property::NONE) { - Vector2 indices = child.GetProperty( Toolkit::TableView::ChildProperty::CELL_INDEX ).Get(); - cellPosition.rowIndex = static_cast( indices.x ); - cellPosition.columnIndex = static_cast( indices.y ); + Vector2 indices = child.GetProperty(Toolkit::TableView::ChildProperty::CELL_INDEX).Get(); + cellPosition.rowIndex = static_cast(indices.x); + cellPosition.columnIndex = static_cast(indices.y); - AddChild( child, cellPosition ); + AddChild(child, cellPosition); SetCellAlignment(cellPosition, horizontalAlignment, verticalAlignment); } else @@ -1043,22 +1039,22 @@ void TableView::OnChildAdd( Actor& child ) bool availableCellFound = false; // Find the first available cell to store the actor in - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount && !availableCellFound; ++row ) + for(unsigned int row = 0; row < rowCount && !availableCellFound; ++row) { - for( unsigned int column = 0; column < columnCount && !availableCellFound; ++column ) + for(unsigned int column = 0; column < columnCount && !availableCellFound; ++column) { - if( !(mCellData[ row ][ column ].actor) ) + if(!(mCellData[row][column].actor)) { // Put the actor in the cell CellData data; - data.actor = child; + data.actor = child; data.position.columnIndex = column; - data.position.rowIndex = row; - data.horizontalAlignment = horizontalAlignment; - data.verticalAlignment = verticalAlignment; - mCellData[ row ][ column ] = data; + data.position.rowIndex = row; + data.horizontalAlignment = horizontalAlignment; + data.verticalAlignment = verticalAlignment; + mCellData[row][column] = data; availableCellFound = true; break; @@ -1066,118 +1062,117 @@ void TableView::OnChildAdd( Actor& child ) } } - if( ! availableCellFound ) + if(!availableCellFound) { // No empty cells, so increase size of the table - unsigned int newColumnCount = ( columnCount > 0 ) ? columnCount : 1; - ResizeContainers( rowCount + 1, newColumnCount ); + unsigned int newColumnCount = (columnCount > 0) ? columnCount : 1; + ResizeContainers(rowCount + 1, newColumnCount); // Put the actor in the first cell of the new row CellData data; - data.actor = child; - data.position.rowIndex = rowCount; + data.actor = child; + data.position.rowIndex = rowCount; data.position.columnIndex = 0; - data.horizontalAlignment = horizontalAlignment; - data.verticalAlignment = verticalAlignment; - mCellData[ rowCount ][ 0 ] = data; + data.horizontalAlignment = horizontalAlignment; + data.verticalAlignment = verticalAlignment; + mCellData[rowCount][0] = data; } RelayoutRequest(); } } - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } -void TableView::OnChildRemove( Actor& child ) +void TableView::OnChildRemove(Actor& child) { // dont process if we're in the middle of bigger operation like delete row, column or resize - if( !mLayoutingChild ) + if(!mLayoutingChild) { // relayout the table only if instances were found - if( RemoveAllInstances( child ) ) + if(RemoveAllInstances(child)) { RelayoutRequest(); } } - Control::OnChildRemove( child ); + Control::OnChildRemove(child); } -TableView::TableView( unsigned int initialRows, unsigned int initialColumns ) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mCellData( initialRows, initialColumns ), +TableView::TableView(unsigned int initialRows, unsigned int initialColumns) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mCellData(initialRows, initialColumns), mPreviousFocusedActor(), - mLayoutingChild( false ), - mRowDirty( true ), // Force recalculation first time - mColumnDirty( true ) + mLayoutingChild(false), + mRowDirty(true), // Force recalculation first time + mColumnDirty(true) { - SetKeyboardNavigationSupport( true ); - ResizeContainers( initialRows, initialColumns ); + SetKeyboardNavigationSupport(true); + ResizeContainers(initialRows, initialColumns); } void TableView::OnInitialize() { // Make self as keyboard focusable and focus group Actor self = Self(); - self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE,true); + self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true); SetAsKeyboardFocusGroup(true); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TABLE ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::TABLE)); + }); } -void TableView::ResizeContainers( unsigned int rows, unsigned int columns ) +void TableView::ResizeContainers(unsigned int rows, unsigned int columns) { std::vector ignored; - ResizeContainers( rows, columns, ignored ); + ResizeContainers(rows, columns, ignored); } -void TableView::ResizeContainers( unsigned int rows, unsigned int columns, std::vector& removed ) +void TableView::ResizeContainers(unsigned int rows, unsigned int columns, std::vector& removed) { // Resize cell data - mCellData.Resize( rows, columns, removed ); + mCellData.Resize(rows, columns, removed); // We don't care if these go smaller, data will be regenerated or is not needed anymore - mRowData.Resize( rows ); - mColumnData.Resize( columns ); + mRowData.Resize(rows); + mColumnData.Resize(columns); } -void TableView::RemoveAndGetLostActors( const std::vector& lost, std::vector& removed, - unsigned int rowsRemoved, unsigned int columnsRemoved ) +void TableView::RemoveAndGetLostActors(const std::vector& lost, std::vector& removed, unsigned int rowsRemoved, unsigned int columnsRemoved) { // iterate through all lost cells - std::vector< CellData >::const_iterator iter = lost.begin(); - for( ; iter != lost.end(); ++iter ) + std::vector::const_iterator iter = lost.begin(); + for(; iter != lost.end(); ++iter) { // if it is a valid actor - if( (*iter).actor ) + if((*iter).actor) { // is this actor still somewhere else in the table Toolkit::TableView::CellPosition position; - if( FindChildPosition( (*iter).actor, position ) ) + if(FindChildPosition((*iter).actor, position)) { // it must be spanning multiple cells, position contains the top left most one // check if position is left of the removed location - if( position.columnIndex < (*iter).position.columnIndex ) + if(position.columnIndex < (*iter).position.columnIndex) { // if column span is greater than 1 - if( mCellData[ position.rowIndex ][ position.columnIndex ].position.columnSpan > 1 ) + if(mCellData[position.rowIndex][position.columnIndex].position.columnSpan > 1) { // decrease column span - mCellData[ position.rowIndex ][ position.columnIndex ].position.columnSpan -= columnsRemoved; + mCellData[position.rowIndex][position.columnIndex].position.columnSpan -= columnsRemoved; } } // check if position is left of the removed location - if( position.rowIndex < (*iter).position.rowIndex ) + if(position.rowIndex < (*iter).position.rowIndex) { // if row span is greater than 1 - if( mCellData[ position.rowIndex ][ position.columnIndex ].position.rowSpan > 1 ) + if(mCellData[position.rowIndex][position.columnIndex].position.rowSpan > 1) { // decrease row span - mCellData[ position.rowIndex ][ position.columnIndex ].position.rowSpan -= rowsRemoved; + mCellData[position.rowIndex][position.columnIndex].position.rowSpan -= rowsRemoved; } } } @@ -1185,29 +1180,29 @@ void TableView::RemoveAndGetLostActors( const std::vector& lost, std:: { // this actor is gone for good // add actor to removed container - removed.push_back( (*iter).actor ); + removed.push_back((*iter).actor); // we dont want the child actor anymore - Self().Remove( (*iter).actor ); + Self().Remove((*iter).actor); } } } } -bool TableView::RemoveAllInstances( const Actor& child ) +bool TableView::RemoveAllInstances(const Actor& child) { bool found = false; // walk through the layout data - const unsigned int rowCount = mCellData.GetRows(); + const unsigned int rowCount = mCellData.GetRows(); const unsigned int columnCount = mCellData.GetColumns(); - for( unsigned int row = 0; row < rowCount; ++row ) + for(unsigned int row = 0; row < rowCount; ++row) { - for( unsigned int column = 0; column < columnCount; ++column ) + for(unsigned int column = 0; column < columnCount; ++column) { - if( mCellData[ row ][ column ].actor == child ) + if(mCellData[row][column].actor == child) { // clear the cell, NOTE that the cell might be spanning multiple cells - mCellData[ row ][ column ] = CellData(); - found = true; + mCellData[row][column] = CellData(); + found = true; } } } @@ -1215,46 +1210,46 @@ bool TableView::RemoveAllInstances( const Actor& child ) } void TableView::SetHeightOrWidthProperty(TableView& tableViewImpl, - void(TableView::*funcFixed)(unsigned int, float), - void(TableView::*funcRelative)(unsigned int, float), - void(TableView::*funcFit)(unsigned int), - const Property::Value& value ) + void (TableView::*funcFixed)(unsigned int, float), + void (TableView::*funcRelative)(unsigned int, float), + void (TableView::*funcFit)(unsigned int), + const Property::Value& value) { const Property::Map* map = value.GetMap(); - if( map ) + if(map) { unsigned int index(0); - for ( unsigned int i = 0, count = map->Count(); i < count; ++i ) + for(unsigned int i = 0, count = map->Count(); i < count; ++i) { - Property::Value& item = map->GetValue(i); - Property::Map* childMap = item.GetMap(); + Property::Value& item = map->GetValue(i); + Property::Map* childMap = item.GetMap(); - std::istringstream( map->GetKey(i) ) >> index; - if( childMap ) + std::istringstream(map->GetKey(i)) >> index; + if(childMap) { - Property::Value* policy = childMap->Find( "policy" ); - Property::Value* childMapValue = childMap->Find( "value" ); - if( policy && childMapValue ) + Property::Value* policy = childMap->Find("policy"); + Property::Value* childMapValue = childMap->Find("value"); + if(policy && childMapValue) { std::string policyValue; - policy->Get( policyValue ); + policy->Get(policyValue); Toolkit::TableView::LayoutPolicy policy; - if( Scripting::GetEnumeration< Toolkit::TableView::LayoutPolicy >( policyValue.c_str(), - LAYOUT_POLICY_STRING_TABLE, - LAYOUT_POLICY_STRING_TABLE_COUNT, - policy ) ) + if(Scripting::GetEnumeration(policyValue.c_str(), + LAYOUT_POLICY_STRING_TABLE, + LAYOUT_POLICY_STRING_TABLE_COUNT, + policy)) { - if( policy == Toolkit::TableView::FIXED ) + if(policy == Toolkit::TableView::FIXED) { - (tableViewImpl.*funcFixed)( index, childMapValue->Get() ); + (tableViewImpl.*funcFixed)(index, childMapValue->Get()); } - else if( policy == Toolkit::TableView::RELATIVE ) + else if(policy == Toolkit::TableView::RELATIVE) { - (tableViewImpl.*funcRelative)( index, childMapValue->Get() ); + (tableViewImpl.*funcRelative)(index, childMapValue->Get()); } - else if( policy == Toolkit::TableView::FIT ) + else if(policy == Toolkit::TableView::FIT) { - (tableViewImpl.*funcFit)( index ); + (tableViewImpl.*funcFit)(index); } // do nothing for FILL policy } @@ -1267,69 +1262,69 @@ void TableView::SetHeightOrWidthProperty(TableView& tableViewImpl, Property::Value TableView::GetRowHeightsPropertyValue() { Property::Map map; - GetMapPropertyValue( mRowData, map); + GetMapPropertyValue(mRowData, map); return Property::Value(map); } Property::Value TableView::GetColumnWidthsPropertyValue() { Property::Map map; - GetMapPropertyValue( mColumnData, map); + GetMapPropertyValue(mColumnData, map); return Property::Value(map); } -void TableView::GetMapPropertyValue( const RowColumnArray& data, Property::Map& map ) +void TableView::GetMapPropertyValue(const RowColumnArray& data, Property::Map& map) { - const char* fixedPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FIXED, + const char* fixedPolicy = Scripting::GetEnumerationName(Toolkit::TableView::FIXED, + LAYOUT_POLICY_STRING_TABLE, + LAYOUT_POLICY_STRING_TABLE_COUNT); + const char* relativePolicy = Scripting::GetEnumerationName(Toolkit::TableView::RELATIVE, LAYOUT_POLICY_STRING_TABLE, - LAYOUT_POLICY_STRING_TABLE_COUNT ); - const char* relativePolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::RELATIVE, - LAYOUT_POLICY_STRING_TABLE, - LAYOUT_POLICY_STRING_TABLE_COUNT ); - const char* fillPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FILL, - LAYOUT_POLICY_STRING_TABLE, - LAYOUT_POLICY_STRING_TABLE_COUNT ); - const char* fitPolicy = Scripting::GetEnumerationName< Toolkit::TableView::LayoutPolicy >( Toolkit::TableView::FIT, - LAYOUT_POLICY_STRING_TABLE, - LAYOUT_POLICY_STRING_TABLE_COUNT ); + LAYOUT_POLICY_STRING_TABLE_COUNT); + const char* fillPolicy = Scripting::GetEnumerationName(Toolkit::TableView::FILL, + LAYOUT_POLICY_STRING_TABLE, + LAYOUT_POLICY_STRING_TABLE_COUNT); + const char* fitPolicy = Scripting::GetEnumerationName(Toolkit::TableView::FIT, + LAYOUT_POLICY_STRING_TABLE, + LAYOUT_POLICY_STRING_TABLE_COUNT); const RowColumnArray::SizeType count = data.Size(); - for( RowColumnArray::SizeType i = 0; i < count; i++ ) + for(RowColumnArray::SizeType i = 0; i < count; i++) { - const RowColumnData& dataInstance = data[ i ]; + const RowColumnData& dataInstance = data[i]; Property::Map item; - switch( dataInstance.sizePolicy ) + switch(dataInstance.sizePolicy) { case Toolkit::TableView::FIXED: { - item[ "policy" ] = fixedPolicy; - item[ "value" ] = dataInstance.size; + item["policy"] = fixedPolicy; + item["value"] = dataInstance.size; break; } case Toolkit::TableView::RELATIVE: { - item[ "policy" ] = relativePolicy; - item[ "value" ] = dataInstance.fillRatio; + item["policy"] = relativePolicy; + item["value"] = dataInstance.fillRatio; break; } case Toolkit::TableView::FIT: { - item[ "policy" ] = fitPolicy; - item[ "value" ] = 0.f; + item["policy"] = fitPolicy; + item["value"] = 0.f; break; } case Toolkit::TableView::FILL: default: { - item[ "policy" ] = fillPolicy; - item[ "value" ] = 0.f; + item["policy"] = fillPolicy; + item["value"] = 0.f; break; } } std::ostringstream ss; ss << i; - map[ ss.str() ] = item; + map[ss.str()] = item; } } @@ -1342,7 +1337,7 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki { Actor nextFocusableActor; - if ( !currentFocusedActor ) + if(!currentFocusedActor) { // Nothing is currently focused, so the child in the first cell should be focused. nextFocusableActor = GetChildAt(Toolkit::TableView::CellPosition(0, 0)); @@ -1350,19 +1345,19 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki else { Toolkit::TableView::CellPosition position; - if( FindChildPosition( currentFocusedActor, position ) ) + if(FindChildPosition(currentFocusedActor, position)) { // The current focused actor is a child of TableView - bool focusLost = false; - int currentRow = position.rowIndex; - int currentColumn = position.columnIndex; - int numberOfColumns = GetColumns(); - int numberOfRows = GetRows(); + bool focusLost = false; + int currentRow = position.rowIndex; + int currentColumn = position.columnIndex; + int numberOfColumns = GetColumns(); + int numberOfRows = GetRows(); - bool lastCell = false; + bool lastCell = false; Actor nextValidActor; - switch ( direction ) + switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { @@ -1373,13 +1368,13 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki currentColumn = numberOfColumns - 1; if(--currentRow < 0) { - lastCell = true; + lastCell = true; currentRow = loopEnabled ? numberOfRows - 1 : 0; - focusLost = (currentRow == 0); + focusLost = (currentRow == 0); } } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); - } while ( !nextValidActor && !lastCell ); + } while(!nextValidActor && !lastCell); break; } case Toolkit::Control::KeyboardFocus::RIGHT: @@ -1391,13 +1386,13 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki currentColumn = 0; if(++currentRow > numberOfRows - 1) { - lastCell = true; + lastCell = true; currentRow = loopEnabled ? 0 : numberOfRows - 1; - focusLost = (currentRow == numberOfRows - 1); + focusLost = (currentRow == numberOfRows - 1); } } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); - } while ( !nextValidActor && !lastCell ); + } while(!nextValidActor && !lastCell); break; } case Toolkit::Control::KeyboardFocus::UP: @@ -1406,12 +1401,12 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki { if(--currentRow < 0) { - lastCell = true; + lastCell = true; currentRow = loopEnabled ? numberOfRows - 1 : 0; - focusLost = (currentRow == 0); + focusLost = (currentRow == 0); } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); - } while ( !nextValidActor && !lastCell ); + } while(!nextValidActor && !lastCell); break; } case Toolkit::Control::KeyboardFocus::DOWN: @@ -1421,12 +1416,12 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki { if(++currentRow > numberOfRows - 1) { - lastCell = true; + lastCell = true; currentRow = loopEnabled ? 0 : numberOfRows - 1; - focusLost = (currentRow == numberOfRows - 1); + focusLost = (currentRow == numberOfRows - 1); } nextValidActor = GetChildAt(Toolkit::TableView::CellPosition(currentRow, currentColumn)); - } while ( !nextValidActor && !lastCell ); + } while(!nextValidActor && !lastCell); break; } default: @@ -1449,24 +1444,24 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki // The current focused actor is not within this TableView. unsigned int numberOfColumns = GetColumns(); - unsigned int numberOfRows = GetRows(); + unsigned int numberOfRows = GetRows(); // Check whether the previous focused actor is a focus group (i.e. a layout container) - bool wasFocusedOnLayoutContainer = false; - Actor previousFocusedActor = mPreviousFocusedActor.GetHandle(); - if( previousFocusedActor ) + bool wasFocusedOnLayoutContainer = false; + Actor previousFocusedActor = mPreviousFocusedActor.GetHandle(); + if(previousFocusedActor) { - Toolkit::Control control = Toolkit::Control::DownCast( previousFocusedActor ); - if( control ) + Toolkit::Control control = Toolkit::Control::DownCast(previousFocusedActor); + if(control) { Internal::Control& controlImpl = static_cast(control.GetImplementation()); - wasFocusedOnLayoutContainer = controlImpl.IsKeyboardFocusGroup(); + wasFocusedOnLayoutContainer = controlImpl.IsKeyboardFocusGroup(); } } // Check whether the previous focused actor is a layout container and also a child of this TableView Toolkit::TableView::CellPosition position; - if( wasFocusedOnLayoutContainer && FindChildPosition( previousFocusedActor, position ) ) + if(wasFocusedOnLayoutContainer && FindChildPosition(previousFocusedActor, position)) { nextFocusableActor = GetNextKeyboardFocusableActor(previousFocusedActor, direction, loopEnabled); } @@ -1491,24 +1486,22 @@ Actor TableView::GetNextKeyboardFocusableActor(Actor currentFocusedActor, Toolki Vector3 TableView::GetNaturalSize() { // Natural size is the size of all fixed cell widths or heights. This ignores cells with relative heights. - return Vector3( mFixedTotals.width, mFixedTotals.height, 1.0f ); + return Vector3(mFixedTotals.width, mFixedTotals.height, 1.0f); } -float TableView::CalculateChildSize( const Actor& child, Dimension::Type dimension ) +float TableView::CalculateChildSize(const Actor& child, Dimension::Type dimension) { Toolkit::TableView::CellPosition position; - if( FindChildPosition( child, position) ) + if(FindChildPosition(child, position)) { - switch( dimension ) + switch(dimension) { case Dimension::WIDTH: { float cellSize = 0.0f; - cellSize = mColumnData[position.columnIndex+position.columnSpan-1].position - - (position.columnIndex > 0 ? mColumnData[position.columnIndex-1].position : 0.f) - - mPadding.width * 2.0f; + cellSize = mColumnData[position.columnIndex + position.columnSpan - 1].position - (position.columnIndex > 0 ? mColumnData[position.columnIndex - 1].position : 0.f) - mPadding.width * 2.0f; - if( cellSize < 0.0f ) + if(cellSize < 0.0f) { cellSize = 0.0f; } @@ -1520,11 +1513,9 @@ float TableView::CalculateChildSize( const Actor& child, Dimension::Type dimensi { float cellSize = 0.0f; - cellSize = mRowData[position.rowIndex+position.rowSpan-1].position - - (position.rowIndex > 0 ? mRowData[position.rowIndex-1].position : 0.f) - - mPadding.height * 2.0f; + cellSize = mRowData[position.rowIndex + position.rowSpan - 1].position - (position.rowIndex > 0 ? mRowData[position.rowIndex - 1].position : 0.f) - mPadding.height * 2.0f; - if( cellSize < 0.0f ) + if(cellSize < 0.0f) { cellSize = 0.0f; } @@ -1538,91 +1529,91 @@ float TableView::CalculateChildSize( const Actor& child, Dimension::Type dimensi } } - return 0.0f; // Child not found + return 0.0f; // Child not found } -bool TableView::RelayoutDependentOnChildren( Dimension::Type dimension ) +bool TableView::RelayoutDependentOnChildren(Dimension::Type dimension) { - if ( Control::RelayoutDependentOnChildren( dimension ) ) + if(Control::RelayoutDependentOnChildren(dimension)) { return true; } - return FindFit( mRowData ) || FindFit( mColumnData ); + return FindFit(mRowData) || FindFit(mColumnData); } -void TableView::SetCellAlignment( Toolkit::TableView::CellPosition position, HorizontalAlignment::Type horizontal, VerticalAlignment::Type vertical ) +void TableView::SetCellAlignment(Toolkit::TableView::CellPosition position, HorizontalAlignment::Type horizontal, VerticalAlignment::Type vertical) { // Check if we need to expand our data array - if( position.rowIndex >= mCellData.GetRows() ) + if(position.rowIndex >= mCellData.GetRows()) { // Only adding new rows - ResizeContainers( position.rowIndex + 1, mCellData.GetColumns() ); + ResizeContainers(position.rowIndex + 1, mCellData.GetColumns()); } - if( position.columnIndex >= mCellData.GetColumns() ) + if(position.columnIndex >= mCellData.GetColumns()) { // Only adding new columns - ResizeContainers( mCellData.GetRows(), position.columnIndex + 1 ); + ResizeContainers(mCellData.GetRows(), position.columnIndex + 1); } // Set the alignment of the cell - CellData& data = mCellData[ position.rowIndex ][ position.columnIndex ]; + CellData& data = mCellData[position.rowIndex][position.columnIndex]; data.horizontalAlignment = horizontal; - data.verticalAlignment = vertical; + data.verticalAlignment = vertical; } -void TableView::CalculateFillSizes( RowColumnArray& data ) +void TableView::CalculateFillSizes(RowColumnArray& data) { // First pass: Count number of fill entries and calculate used relative space - Dali::Vector< RowColumnData* > fillData; - float relativeTotal = 0.0f; + Dali::Vector fillData; + float relativeTotal = 0.0f; const unsigned int dataCount = data.Size(); - for( unsigned int i = 0; i < dataCount; ++i ) + for(unsigned int i = 0; i < dataCount; ++i) { - RowColumnData& dataInstance = data[ i ]; + RowColumnData& dataInstance = data[i]; - if( dataInstance.sizePolicy == Toolkit::TableView::RELATIVE ) + if(dataInstance.sizePolicy == Toolkit::TableView::RELATIVE) { relativeTotal += dataInstance.fillRatio; } else if(dataInstance.sizePolicy == Toolkit::TableView::FILL) { - fillData.PushBack( &dataInstance ); + fillData.PushBack(&dataInstance); } } // Second pass: Distribute remaining relative space const unsigned int fillCount = fillData.Size(); - if( fillCount > 0 ) + if(fillCount > 0) { - if( relativeTotal > 1.0f ) + if(relativeTotal > 1.0f) { relativeTotal = 1.0f; } - const float evenFillRatio = (1.0f - relativeTotal ) / fillCount; + const float evenFillRatio = (1.0f - relativeTotal) / fillCount; - for( unsigned int i = 0; i < fillCount; ++i ) + for(unsigned int i = 0; i < fillCount; ++i) { - fillData[ i ]->fillRatio = evenFillRatio; + fillData[i]->fillRatio = evenFillRatio; } } } -float TableView::CalculateTotalFixedSize( const RowColumnArray& data ) +float TableView::CalculateTotalFixedSize(const RowColumnArray& data) { float totalSize = 0.0f; const unsigned int dataCount = data.Size(); - for( unsigned int i = 0; i < dataCount; ++i ) + for(unsigned int i = 0; i < dataCount; ++i) { - const RowColumnData& dataInstance = data[ i ]; + const RowColumnData& dataInstance = data[i]; - switch( dataInstance.sizePolicy ) + switch(dataInstance.sizePolicy) { // we have absolute size to FIXED and FIT column/row and relative size for RELATIVE and FILL column/row case Toolkit::TableView::FIXED: @@ -1642,17 +1633,17 @@ float TableView::CalculateTotalFixedSize( const RowColumnArray& data ) return totalSize; } -Vector2 TableView::GetCellPadding( Dimension::Type dimension ) +Vector2 TableView::GetCellPadding(Dimension::Type dimension) { - switch( dimension ) + switch(dimension) { case Dimension::WIDTH: { - return Vector2( mPadding.x, mPadding.x ); + return Vector2(mPadding.x, mPadding.x); } case Dimension::HEIGHT: { - return Vector2( mPadding.y, mPadding.y ); + return Vector2(mPadding.y, mPadding.y); } default: { @@ -1663,37 +1654,37 @@ Vector2 TableView::GetCellPadding( Dimension::Type dimension ) return Vector2(); } -void TableView::CalculateFitSizes( RowColumnArray& data, Dimension::Type dimension ) +void TableView::CalculateFitSizes(RowColumnArray& data, Dimension::Type dimension) { - Vector2 cellPadding = GetCellPadding( dimension ); + Vector2 cellPadding = GetCellPadding(dimension); const unsigned int dataCount = data.Size(); - for( unsigned int i = 0; i < dataCount; ++i ) + for(unsigned int i = 0; i < dataCount; ++i) { - RowColumnData& dataInstance = data[ i ]; + RowColumnData& dataInstance = data[i]; - if( dataInstance.sizePolicy == Toolkit::TableView::FIT ) + if(dataInstance.sizePolicy == Toolkit::TableView::FIT) { // Find the size of the biggest actor in the row or column float maxActorHeight = 0.0f; - unsigned int fitCount = ( dimension == Dimension::WIDTH ) ? mCellData.GetRows() : mCellData.GetColumns(); + unsigned int fitCount = (dimension == Dimension::WIDTH) ? mCellData.GetRows() : mCellData.GetColumns(); - for( unsigned int j = 0; j < fitCount; ++j ) + for(unsigned int j = 0; j < fitCount; ++j) { - unsigned int row = ( dimension == Dimension::WIDTH ) ? j : i; - unsigned int column = ( dimension == Dimension::WIDTH ) ? i : j; - DALI_ASSERT_DEBUG( row < mCellData.GetRows() ); - DALI_ASSERT_DEBUG( column < mCellData.GetColumns() ); - - const CellData& cellData = mCellData[ row ][ column ]; - const Actor& actor = cellData.actor; - if( actor ) + unsigned int row = (dimension == Dimension::WIDTH) ? j : i; + unsigned int column = (dimension == Dimension::WIDTH) ? i : j; + DALI_ASSERT_DEBUG(row < mCellData.GetRows()); + DALI_ASSERT_DEBUG(column < mCellData.GetColumns()); + + const CellData& cellData = mCellData[row][column]; + const Actor& actor = cellData.actor; + if(actor) { - if( FitToChild( actor, dimension ) && ( dimension == Dimension::WIDTH ) ? ( cellData.position.columnSpan == 1 ) : ( cellData.position.rowSpan == 1 ) ) + if(FitToChild(actor, dimension) && (dimension == Dimension::WIDTH) ? (cellData.position.columnSpan == 1) : (cellData.position.rowSpan == 1)) { - maxActorHeight = std::max( maxActorHeight, actor.GetRelayoutSize( dimension ) + cellPadding.x + cellPadding.y ); + maxActorHeight = std::max(maxActorHeight, actor.GetRelayoutSize(dimension) + cellPadding.x + cellPadding.y); } } } @@ -1703,11 +1694,11 @@ void TableView::CalculateFitSizes( RowColumnArray& data, Dimension::Type dimensi } } -bool TableView::FindFit( const RowColumnArray& data ) +bool TableView::FindFit(const RowColumnArray& data) { - for( unsigned int i = 0, count = data.Size(); i < count; ++i ) + for(unsigned int i = 0, count = data.Size(); i < count; ++i) { - if( data[ i ].sizePolicy == Toolkit::TableView::FIT ) + if(data[i].sizePolicy == Toolkit::TableView::FIT) { return true; } diff --git a/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp index 7e64b6e..22880d3 100644 --- a/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-editor-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,54 +19,49 @@ #include // EXTERNAL INCLUDES -#include -#include -#include -#include +#include #include #include -#include #include -#include -#include #include +#include +#include +#include +#include +#include +#include // INTERNAL INCLUDES -#include -#include -#include -#include #include +#include #include -#include -#include +#include +#include #include #include +#include #include #include -#include -#include +#include +#include +#include using namespace Dali::Toolkit::Text; namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // unnamed namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS"); #endif const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND; -const float DEFAULT_SCROLL_SPEED = 1200.f; ///< The default scroll speed for the text editor in pixels/second. +const float DEFAULT_SCROLL_SPEED = 1200.f; ///< The default scroll speed for the text editor in pixels/second. } // unnamed namespace namespace @@ -82,93 +77,95 @@ BaseHandle Create() return Toolkit::TextEditor::New(); } +// clang-format off // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextEditor, Toolkit::Control, Create ); - -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "text", STRING, TEXT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "textColor", VECTOR4, TEXT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "fontFamily", STRING, FONT_FAMILY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "fontStyle", MAP, FONT_STYLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "pointSize", FLOAT, POINT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollThreshold", FLOAT, SCROLL_THRESHOLD ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollSpeed", FLOAT, SCROLL_SPEED ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "cursorWidth", INTEGER, CURSOR_WIDTH ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableMarkup", BOOLEAN, ENABLE_MARKUP ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputColor", VECTOR4, INPUT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputFontFamily", STRING, INPUT_FONT_FAMILY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputFontStyle", MAP, INPUT_FONT_STYLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputPointSize", FLOAT, INPUT_POINT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "lineSpacing", FLOAT, LINE_SPACING ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputLineSpacing", FLOAT, INPUT_LINE_SPACING ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "underline", MAP, UNDERLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputUnderline", MAP, INPUT_UNDERLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "shadow", MAP, SHADOW ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputShadow", MAP, INPUT_SHADOW ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "emboss", MAP, EMBOSS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputEmboss", MAP, INPUT_EMBOSS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "outline", MAP, OUTLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "inputOutline", MAP, INPUT_OUTLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "smoothScroll", BOOLEAN, SMOOTH_SCROLL ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "smoothScrollDuration", FLOAT, SMOOTH_SCROLL_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollBarShowDuration", FLOAT, SCROLL_BAR_SHOW_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "scrollBarFadeDuration", FLOAT, SCROLL_BAR_FADE_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "pixelSize", FLOAT, PIXEL_SIZE ) -DALI_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextEditor, "lineCount", INTEGER, LINE_COUNT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableSelection", BOOLEAN, ENABLE_SELECTION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "placeholder", MAP, PLACEHOLDER ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextEditor, "lineWrapMode", INTEGER, LINE_WRAP_MODE ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "placeholderText", STRING, PLACEHOLDER_TEXT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "renderingBackend", INTEGER, RENDERING_BACKEND ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "maxLength", INTEGER, MAX_LENGTH ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectedTextStart", INTEGER, SELECTED_TEXT_START ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "selectedTextEnd", INTEGER, SELECTED_TEXT_END ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "horizontalScrollPosition", FLOAT, HORIZONTAL_SCROLL_POSITION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "verticalScrollPosition", INTEGER, VERTICAL_SCROLL_POSITION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "enableEditing", BOOLEAN, ENABLE_EDITING ) -DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextEditor, "selectedText", STRING, SELECTED_TEXT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "fontSizeScale", FLOAT, FONT_SIZE_SCALE ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextEditor, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION ) - -DALI_SIGNAL_REGISTRATION( Toolkit, TextEditor, "textChanged", SIGNAL_TEXT_CHANGED ) -DALI_SIGNAL_REGISTRATION( Toolkit, TextEditor, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED ) -DALI_SIGNAL_REGISTRATION( Toolkit, TextEditor, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextEditor, Toolkit::Control, Create); + +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "text", STRING, TEXT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "textColor", VECTOR4, TEXT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "fontFamily", STRING, FONT_FAMILY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "fontStyle", MAP, FONT_STYLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "pointSize", FLOAT, POINT_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollThreshold", FLOAT, SCROLL_THRESHOLD ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollSpeed", FLOAT, SCROLL_SPEED ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "cursorWidth", INTEGER, CURSOR_WIDTH ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableMarkup", BOOLEAN, ENABLE_MARKUP ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputColor", VECTOR4, INPUT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputFontFamily", STRING, INPUT_FONT_FAMILY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputFontStyle", MAP, INPUT_FONT_STYLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputPointSize", FLOAT, INPUT_POINT_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "lineSpacing", FLOAT, LINE_SPACING ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputLineSpacing", FLOAT, INPUT_LINE_SPACING ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "underline", MAP, UNDERLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputUnderline", MAP, INPUT_UNDERLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "shadow", MAP, SHADOW ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputShadow", MAP, INPUT_SHADOW ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "emboss", MAP, EMBOSS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputEmboss", MAP, INPUT_EMBOSS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "outline", MAP, OUTLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "inputOutline", MAP, INPUT_OUTLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "smoothScroll", BOOLEAN, SMOOTH_SCROLL ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "smoothScrollDuration", FLOAT, SMOOTH_SCROLL_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollBarShowDuration", FLOAT, SCROLL_BAR_SHOW_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "scrollBarFadeDuration", FLOAT, SCROLL_BAR_FADE_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "pixelSize", FLOAT, PIXEL_SIZE ) +DALI_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextEditor, "lineCount", INTEGER, LINE_COUNT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableSelection", BOOLEAN, ENABLE_SELECTION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "placeholder", MAP, PLACEHOLDER ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextEditor, "lineWrapMode", INTEGER, LINE_WRAP_MODE ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "placeholderText", STRING, PLACEHOLDER_TEXT ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "renderingBackend", INTEGER, RENDERING_BACKEND ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "maxLength", INTEGER, MAX_LENGTH ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectedTextStart", INTEGER, SELECTED_TEXT_START ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "selectedTextEnd", INTEGER, SELECTED_TEXT_END ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "horizontalScrollPosition", FLOAT, HORIZONTAL_SCROLL_POSITION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "verticalScrollPosition", INTEGER, VERTICAL_SCROLL_POSITION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "enableEditing", BOOLEAN, ENABLE_EDITING ) +DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextEditor, "selectedText", STRING, SELECTED_TEXT ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "fontSizeScale", FLOAT, FONT_SIZE_SCALE ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextEditor, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION ) + +DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "textChanged", SIGNAL_TEXT_CHANGED ) +DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED) +DALI_SIGNAL_REGISTRATION(Toolkit, TextEditor, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED ) DALI_TYPE_REGISTRATION_END() +// clang-format on -const char * const IMAGE_MAP_FILENAME_STRING = "filename"; +const char* const IMAGE_MAP_FILENAME_STRING = "filename"; /// Retrieves a filename from a value that is a Property::Map -std::string GetImageFileNameFromPropertyValue( const Property::Value& value ) +std::string GetImageFileNameFromPropertyValue(const Property::Value& value) { - std::string filename; + std::string filename; const Property::Map* map = value.GetMap(); - if( map ) + if(map) { - const Property::Value* filenameValue = map->Find( IMAGE_MAP_FILENAME_STRING ); - if( filenameValue ) + const Property::Value* filenameValue = map->Find(IMAGE_MAP_FILENAME_STRING); + if(filenameValue) { - filenameValue->Get( filename ); + filenameValue->Get(filename); } } return filename; @@ -179,10 +176,10 @@ std::string GetImageFileNameFromPropertyValue( const Property::Value& value ) Toolkit::TextEditor TextEditor::New() { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< TextEditor > impl = new TextEditor(); + IntrusivePtr impl = new TextEditor(); // Pass ownership to CustomActor handle - Toolkit::TextEditor handle( *impl ); + Toolkit::TextEditor handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -191,27 +188,26 @@ Toolkit::TextEditor TextEditor::New() return handle; } -void TextEditor::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void TextEditor::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast(Dali::BaseHandle(object)); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor SetProperty\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor SetProperty\n"); - - if( textEditor ) + if(textEditor) { - TextEditor& impl( GetImpl( textEditor ) ); - DALI_ASSERT_DEBUG( impl.mController && "No text contoller" ); - DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" ); + TextEditor& impl(GetImpl(textEditor)); + DALI_ASSERT_DEBUG(impl.mController && "No text contoller"); + DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator"); - switch( index ) + switch(index) { case Toolkit::DevelTextEditor::Property::RENDERING_BACKEND: { - int backend = value.Get< int >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend ); + int backend = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend); - if( impl.mRenderingBackend != backend ) + if(impl.mRenderingBackend != backend) { impl.mRenderingBackend = backend; impl.mRenderer.Reset(); @@ -221,267 +217,267 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::TEXT: { - const std::string& text = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p TEXT %s\n", impl.mController.Get(), text.c_str() ); + const std::string& text = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p TEXT %s\n", impl.mController.Get(), text.c_str()); - impl.mController->SetText( text ); + impl.mController->SetText(text); break; } case Toolkit::TextEditor::Property::TEXT_COLOR: { - const Vector4& textColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a ); + const Vector4& textColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a); - if( impl.mController->GetDefaultColor() != textColor ) + if(impl.mController->GetDefaultColor() != textColor) { - impl.mController->SetDefaultColor( textColor ); - impl.mController->SetInputColor( textColor ); + impl.mController->SetDefaultColor(textColor); + impl.mController->SetInputColor(textColor); impl.mRenderer.Reset(); } break; } case Toolkit::TextEditor::Property::FONT_FAMILY: { - const std::string& fontFamily = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() ); - impl.mController->SetDefaultFontFamily( fontFamily ); + const std::string& fontFamily = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str()); + impl.mController->SetDefaultFontFamily(fontFamily); break; } case Toolkit::TextEditor::Property::FONT_STYLE: { - SetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT ); + SetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT); break; } case Toolkit::TextEditor::Property::POINT_SIZE: { - const float pointSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p POINT_SIZE %f\n", impl.mController.Get(), pointSize ); + const float pointSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p POINT_SIZE %f\n", impl.mController.Get(), pointSize); - if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) ) + if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize)) { - impl.mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE ); + impl.mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE); } break; } case Toolkit::TextEditor::Property::HORIZONTAL_ALIGNMENT: { - Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( Text::GetHorizontalAlignmentEnumeration( value, alignment ) ) + Text::HorizontalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(Text::GetHorizontalAlignmentEnumeration(value, alignment)) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment ); - impl.mController->SetHorizontalAlignment( alignment ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment); + impl.mController->SetHorizontalAlignment(alignment); } break; } case Toolkit::TextEditor::Property::SCROLL_THRESHOLD: { - const float threshold = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold ); + const float threshold = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold); - impl.mDecorator->SetScrollThreshold( threshold ); + impl.mDecorator->SetScrollThreshold(threshold); break; } case Toolkit::TextEditor::Property::SCROLL_SPEED: { - const float speed = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_SPEED %f\n", impl.mController.Get(), speed ); + const float speed = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p SCROLL_SPEED %f\n", impl.mController.Get(), speed); - impl.mDecorator->SetScrollSpeed( speed ); + impl.mDecorator->SetScrollSpeed(speed); break; } case Toolkit::TextEditor::Property::PRIMARY_CURSOR_COLOR: { - const Vector4& color = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a ); + const Vector4& color = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a); - impl.mDecorator->SetCursorColor( PRIMARY_CURSOR, color ); + impl.mDecorator->SetCursorColor(PRIMARY_CURSOR, color); impl.RequestTextRelayout(); break; } case Toolkit::TextEditor::Property::SECONDARY_CURSOR_COLOR: { - const Vector4& color = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a ); + const Vector4& color = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a); - impl.mDecorator->SetCursorColor( SECONDARY_CURSOR, color ); + impl.mDecorator->SetCursorColor(SECONDARY_CURSOR, color); impl.RequestTextRelayout(); break; } case Toolkit::TextEditor::Property::ENABLE_CURSOR_BLINK: { - const bool enable = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable ); + const bool enable = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable); - impl.mController->SetEnableCursorBlink( enable ); + impl.mController->SetEnableCursorBlink(enable); impl.RequestTextRelayout(); break; } case Toolkit::TextEditor::Property::CURSOR_BLINK_INTERVAL: { - const float interval = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval ); + const float interval = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval); - impl.mDecorator->SetCursorBlinkInterval( interval ); + impl.mDecorator->SetCursorBlinkInterval(interval); break; } case Toolkit::TextEditor::Property::CURSOR_BLINK_DURATION: { - const float duration = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration ); + const float duration = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration); - impl.mDecorator->SetCursorBlinkDuration( duration ); + impl.mDecorator->SetCursorBlinkDuration(duration); break; } case Toolkit::TextEditor::Property::CURSOR_WIDTH: { - const int width = value.Get< int >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_WIDTH %d\n", impl.mController.Get(), width ); + const int width = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p CURSOR_WIDTH %d\n", impl.mController.Get(), width); - impl.mDecorator->SetCursorWidth( width ); - impl.mController->GetLayoutEngine().SetCursorWidth( width ); + impl.mDecorator->SetCursorWidth(width); + impl.mController->GetLayoutEngine().SetCursorWidth(width); break; } case Toolkit::TextEditor::Property::GRAB_HANDLE_IMAGE: { - const std::string imageFileName = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() ); + const std::string imageFileName = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str()); - if( imageFileName.size() ) + if(imageFileName.size()) { - impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName ); + impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::GRAB_HANDLE_PRESSED_IMAGE: { - const std::string imageFileName = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() ); + const std::string imageFileName = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str()); - if( imageFileName.size() ) + if(imageFileName.size()) { - impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName ); + impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_LEFT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_RIGHT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename ); + impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename ); + impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextEditor::Property::SELECTION_HIGHLIGHT_COLOR: { - const Vector4 color = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a ); + const Vector4 color = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a); - impl.mDecorator->SetHighlightColor( color ); + impl.mDecorator->SetHighlightColor(color); impl.RequestTextRelayout(); break; } case Toolkit::TextEditor::Property::DECORATION_BOUNDING_BOX: { - const Rect& box = value.Get< Rect >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height ); + const Rect& box = value.Get >(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height); - impl.mDecorator->SetBoundingBox( box ); + impl.mDecorator->SetBoundingBox(box); impl.RequestTextRelayout(); break; } case Toolkit::TextEditor::Property::ENABLE_MARKUP: { const bool enableMarkup = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup); - impl.mController->SetMarkupProcessorEnabled( enableMarkup ); + impl.mController->SetMarkupProcessorEnabled(enableMarkup); break; } case Toolkit::TextEditor::Property::INPUT_COLOR: { - const Vector4& inputColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a ); + const Vector4& inputColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a); - impl.mController->SetInputColor( inputColor ); + impl.mController->SetInputColor(inputColor); break; } case Toolkit::TextEditor::Property::INPUT_FONT_FAMILY: { - const std::string& fontFamily = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() ); - impl.mController->SetInputFontFamily( fontFamily ); + const std::string& fontFamily = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str()); + impl.mController->SetInputFontFamily(fontFamily); break; } case Toolkit::TextEditor::Property::INPUT_FONT_STYLE: { - SetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT ); + SetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT); break; } case Toolkit::TextEditor::Property::INPUT_POINT_SIZE: { - const float pointSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize ); - impl.mController->SetInputFontPointSize( pointSize ); + const float pointSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize); + impl.mController->SetInputFontPointSize(pointSize); break; } case Toolkit::TextEditor::Property::LINE_SPACING: @@ -490,23 +486,23 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P // by the TextLabel for now it must be ignored. The property is being shadowed // locally so its value isn't affected. const float lineSpacing = value.Get(); - impl.mLineSpacing = lineSpacing; + impl.mLineSpacing = lineSpacing; // set it to 0.0 due to missing implementation - impl.mController->SetDefaultLineSpacing( 0.0f ); + impl.mController->SetDefaultLineSpacing(0.0f); impl.mRenderer.Reset(); break; } case Toolkit::TextEditor::Property::INPUT_LINE_SPACING: { const float lineSpacing = value.Get(); - impl.mController->SetInputLineSpacing( lineSpacing ); + impl.mController->SetInputLineSpacing(lineSpacing); impl.mRenderer.Reset(); break; } case Toolkit::TextEditor::Property::UNDERLINE: { - const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -514,8 +510,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::INPUT_UNDERLINE: { - const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -523,8 +519,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::SHADOW: { - const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -532,8 +528,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::INPUT_SHADOW: { - const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -541,8 +537,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::EMBOSS: { - const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -550,8 +546,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::INPUT_EMBOSS: { - const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -559,8 +555,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::OUTLINE: { - const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -568,8 +564,8 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::INPUT_OUTLINE: { - const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -577,213 +573,213 @@ void TextEditor::SetProperty( BaseObject* object, Property::Index index, const P } case Toolkit::TextEditor::Property::SMOOTH_SCROLL: { - const bool enable = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor SMOOTH_SCROLL %d\n", enable ); + const bool enable = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor SMOOTH_SCROLL %d\n", enable); impl.mScrollAnimationEnabled = enable; break; } case Toolkit::TextEditor::Property::SMOOTH_SCROLL_DURATION: { - const float duration = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor SMOOTH_SCROLL_DURATION %f\n", duration ); + const float duration = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor SMOOTH_SCROLL_DURATION %f\n", duration); impl.mScrollAnimationDuration = duration; - if ( impl.mTextVerticalScroller ) + if(impl.mTextVerticalScroller) { - impl.mTextVerticalScroller->SetDuration( duration ); + impl.mTextVerticalScroller->SetDuration(duration); } break; } case Toolkit::TextEditor::Property::ENABLE_SCROLL_BAR: { - const bool enable = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor SHOW_SCROLL_BAR %d\n", enable ); + const bool enable = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor SHOW_SCROLL_BAR %d\n", enable); impl.mScrollBarEnabled = enable; break; } case Toolkit::TextEditor::Property::SCROLL_BAR_SHOW_DURATION: { - const float duration = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor SCROLL_BAR_SHOW_DURATION %f\n", duration ); + const float duration = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor SCROLL_BAR_SHOW_DURATION %f\n", duration); impl.mAnimationPeriod.delaySeconds = duration; break; } case Toolkit::TextEditor::Property::SCROLL_BAR_FADE_DURATION: { - const float duration = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor SCROLL_BAR_FADE_DURATION %f\n", duration ); + const float duration = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor SCROLL_BAR_FADE_DURATION %f\n", duration); impl.mAnimationPeriod.durationSeconds = duration; break; } case Toolkit::TextEditor::Property::PIXEL_SIZE: { - const float pixelSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize ); + const float pixelSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize); - if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) ) + if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE), pixelSize)) { - impl.mController->SetDefaultFontSize( pixelSize, Text::Controller::PIXEL_SIZE ); + impl.mController->SetDefaultFontSize(pixelSize, Text::Controller::PIXEL_SIZE); } break; } case Toolkit::DevelTextEditor::Property::PLACEHOLDER_TEXT: { - const std::string& text = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor::OnPropertySet %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str() ); + const std::string& text = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor::OnPropertySet %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str()); - impl.mController->SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text ); + impl.mController->SetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text); break; } case Toolkit::DevelTextEditor::Property::PLACEHOLDER_TEXT_COLOR: { - const Vector4& textColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a ); + const Vector4& textColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a); - if( impl.mController->GetPlaceholderTextColor() != textColor ) + if(impl.mController->GetPlaceholderTextColor() != textColor) { - impl.mController->SetPlaceholderTextColor( textColor ); + impl.mController->SetPlaceholderTextColor(textColor); impl.mRenderer.Reset(); } break; } case Toolkit::TextEditor::Property::ENABLE_SELECTION: { - const bool enableSelection = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection ); - impl.mController->SetSelectionEnabled( enableSelection ); + const bool enableSelection = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection); + impl.mController->SetSelectionEnabled(enableSelection); break; } case Toolkit::TextEditor::Property::PLACEHOLDER: { const Property::Map* map = value.GetMap(); - if( map ) + if(map) { - impl.mController->SetPlaceholderProperty( *map ); + impl.mController->SetPlaceholderProperty(*map); } break; } case Toolkit::TextEditor::Property::LINE_WRAP_MODE: { - Text::LineWrap::Mode lineWrapMode( static_cast< Text::LineWrap::Mode >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( GetLineWrapModeEnumeration( value, lineWrapMode ) ) + Text::LineWrap::Mode lineWrapMode(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(GetLineWrapModeEnumeration(value, lineWrapMode)) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode ); - impl.mController->SetLineWrapMode( lineWrapMode ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode); + impl.mController->SetLineWrapMode(lineWrapMode); } break; } case Toolkit::DevelTextEditor::Property::ENABLE_SHIFT_SELECTION: { const bool shiftSelection = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection); - impl.mController->SetShiftSelectionEnabled( shiftSelection ); + impl.mController->SetShiftSelectionEnabled(shiftSelection); break; } case Toolkit::DevelTextEditor::Property::ENABLE_GRAB_HANDLE: { const bool grabHandleEnabled = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled); - impl.mController->SetGrabHandleEnabled( grabHandleEnabled ); + impl.mController->SetGrabHandleEnabled(grabHandleEnabled); break; } case Toolkit::DevelTextEditor::Property::MATCH_SYSTEM_LANGUAGE_DIRECTION: { - impl.mController->SetMatchSystemLanguageDirection(value.Get< bool >()); + impl.mController->SetMatchSystemLanguageDirection(value.Get()); break; } case Toolkit::DevelTextEditor::Property::MAX_LENGTH: { - const int max = value.Get< int >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p MAX_LENGTH %d\n", impl.mController.Get(), max ); + const int max = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p MAX_LENGTH %d\n", impl.mController.Get(), max); - impl.mController->SetMaximumNumberOfCharacters( max ); + impl.mController->SetMaximumNumberOfCharacters(max); break; } case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_START: { - uint32_t start = static_cast(value.Get< int >()); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start ); - impl.SetTextSelectionRange( &start, nullptr ); + uint32_t start = static_cast(value.Get()); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start); + impl.SetTextSelectionRange(&start, nullptr); break; } case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_END: { - uint32_t end = static_cast(value.Get< int >()); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end ); - impl.SetTextSelectionRange( nullptr, &end ); + uint32_t end = static_cast(value.Get()); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end); + impl.SetTextSelectionRange(nullptr, &end); break; } case Toolkit::DevelTextEditor::Property::ENABLE_EDITING: { - const bool editable = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p ENABLE_EDITING %d\n", impl.mController.Get(), editable ); - impl.SetEditable( editable ); + const bool editable = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p ENABLE_EDITING %d\n", impl.mController.Get(), editable); + impl.SetEditable(editable); break; } case Toolkit::DevelTextEditor::Property::HORIZONTAL_SCROLL_POSITION: { - float horizontalScroll = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_SCROLL_POSITION %d\n", impl.mController.Get(), horizontalScroll ); - if (horizontalScroll >= 0.0f) + float horizontalScroll = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p HORIZONTAL_SCROLL_POSITION %d\n", impl.mController.Get(), horizontalScroll); + if(horizontalScroll >= 0.0f) { - impl.ScrollBy( Vector2(horizontalScroll - impl.GetHorizontalScrollPosition(), 0 )); + impl.ScrollBy(Vector2(horizontalScroll - impl.GetHorizontalScrollPosition(), 0)); } break; } case Toolkit::DevelTextEditor::Property::VERTICAL_SCROLL_POSITION: { - float verticalScroll = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p VERTICAL_SCROLL_POSITION %d\n", impl.mController.Get(), verticalScroll ); - if (verticalScroll >= 0.0f) + float verticalScroll = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p VERTICAL_SCROLL_POSITION %d\n", impl.mController.Get(), verticalScroll); + if(verticalScroll >= 0.0f) { - impl.ScrollBy( Vector2(0, verticalScroll - impl.GetVerticalScrollPosition() )); + impl.ScrollBy(Vector2(0, verticalScroll - impl.GetVerticalScrollPosition())); } break; } case Toolkit::DevelTextEditor::Property::FONT_SIZE_SCALE: { - const float scale = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale ); + const float scale = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale); - if( !Equals( impl.mController->GetFontSizeScale(), scale ) ) + if(!Equals(impl.mController->GetFontSizeScale(), scale)) { - impl.mController->SetFontSizeScale( scale ); + impl.mController->SetFontSizeScale(scale); } break; } case Toolkit::DevelTextEditor::Property::PRIMARY_CURSOR_POSITION: { - uint32_t position = static_cast(value.Get< int >()); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position ); - if (impl.mController->SetPrimaryCursorPosition( position )) + uint32_t position = static_cast(value.Get()); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position); + if(impl.mController->SetPrimaryCursorPosition(position)) { impl.SetKeyInputFocus(); } break; } } // switch - } // texteditor + } // texteditor } -Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index index ) +Property::Value TextEditor::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextEditor textEditor = Toolkit::TextEditor::DownCast(Dali::BaseHandle(object)); - if( textEditor ) + if(textEditor) { - TextEditor& impl( GetImpl( textEditor ) ); - DALI_ASSERT_DEBUG( impl.mController && "No text contoller" ); - DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" ); + TextEditor& impl(GetImpl(textEditor)); + DALI_ASSERT_DEBUG(impl.mController && "No text contoller"); + DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator"); - switch( index ) + switch(index) { case Toolkit::DevelTextEditor::Property::RENDERING_BACKEND: { @@ -793,8 +789,8 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind case Toolkit::TextEditor::Property::TEXT: { std::string text; - impl.mController->GetText( text ); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextEditor %p returning text: %s\n", impl.mController.Get(), text.c_str() ); + impl.mController->GetText(text); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextEditor %p returning text: %s\n", impl.mController.Get(), text.c_str()); value = text; break; } @@ -810,20 +806,20 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::TextEditor::Property::FONT_STYLE: { - GetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT ); + GetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT); break; } case Toolkit::TextEditor::Property::POINT_SIZE: { - value = impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ); + value = impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE); break; } case Toolkit::TextEditor::Property::HORIZONTAL_ALIGNMENT: { - const char* name = GetHorizontalAlignmentString( impl.mController->GetHorizontalAlignment() ); - if( name ) + const char* name = GetHorizontalAlignmentString(impl.mController->GetHorizontalAlignment()); + if(name) { - value = std::string( name ); + value = std::string(name); } break; } @@ -839,12 +835,12 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::TextEditor::Property::PRIMARY_CURSOR_COLOR: { - value = impl.mDecorator->GetColor( PRIMARY_CURSOR ); + value = impl.mDecorator->GetColor(PRIMARY_CURSOR); break; } case Toolkit::TextEditor::Property::SECONDARY_CURSOR_COLOR: { - value = impl.mDecorator->GetColor( SECONDARY_CURSOR ); + value = impl.mDecorator->GetColor(SECONDARY_CURSOR); break; } case Toolkit::TextEditor::Property::ENABLE_CURSOR_BLINK: @@ -869,42 +865,42 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::TextEditor::Property::GRAB_HANDLE_IMAGE: { - value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED ); + value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextEditor::Property::GRAB_HANDLE_PRESSED_IMAGE: { - value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED ); + value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED); break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_LEFT: { - impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED ); + impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_IMAGE_RIGHT: { - impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED ) ; + impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT: { - impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED ); + impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED); break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT: { - impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED ); + impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED); break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT: { - impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED ); + impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextEditor::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT: { - impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED ); + impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextEditor::Property::SELECTION_HIGHLIGHT_COLOR: @@ -915,7 +911,7 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind case Toolkit::TextEditor::Property::DECORATION_BOUNDING_BOX: { Rect boundingBox; - impl.mDecorator->GetBoundingBox( boundingBox ); + impl.mDecorator->GetBoundingBox(boundingBox); value = boundingBox; break; } @@ -936,7 +932,7 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::TextEditor::Property::INPUT_FONT_STYLE: { - GetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT ); + GetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT); break; } case Toolkit::TextEditor::Property::INPUT_POINT_SIZE: @@ -958,42 +954,42 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::TextEditor::Property::UNDERLINE: { - GetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextEditor::Property::INPUT_UNDERLINE: { - GetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextEditor::Property::SHADOW: { - GetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextEditor::Property::INPUT_SHADOW: { - GetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextEditor::Property::EMBOSS: { - GetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextEditor::Property::INPUT_EMBOSS: { - GetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextEditor::Property::OUTLINE: { - GetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextEditor::Property::INPUT_OUTLINE: { - GetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextEditor::Property::SMOOTH_SCROLL: @@ -1023,19 +1019,19 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::TextEditor::Property::PIXEL_SIZE: { - value = impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ); + value = impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE); break; } case Toolkit::TextEditor::Property::LINE_COUNT: { - float width = textEditor.GetProperty( Actor::Property::SIZE_WIDTH ).Get(); - value = impl.mController->GetLineCount( width ); + float width = textEditor.GetProperty(Actor::Property::SIZE_WIDTH).Get(); + value = impl.mController->GetLineCount(width); break; } case Toolkit::DevelTextEditor::Property::PLACEHOLDER_TEXT: { std::string text; - impl.mController->GetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text ); + impl.mController->GetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text); value = text; break; } @@ -1052,7 +1048,7 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind case Toolkit::TextEditor::Property::PLACEHOLDER: { Property::Map map; - impl.mController->GetPlaceholderProperty( map ); + impl.mController->GetPlaceholderProperty(map); value = map; break; } @@ -1083,19 +1079,19 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind } case Toolkit::DevelTextEditor::Property::SELECTED_TEXT: { - value = impl.mController->GetSelectedText( ); + value = impl.mController->GetSelectedText(); break; } case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_START: { Uint32Pair range = impl.GetTextSelectionRange(); - value = static_cast(range.first); + value = static_cast(range.first); break; } case Toolkit::DevelTextEditor::Property::SELECTED_TEXT_END: { Uint32Pair range = impl.GetTextSelectionRange(); - value = static_cast(range.second); + value = static_cast(range.second); break; } case Toolkit::DevelTextEditor::Property::ENABLE_EDITING: @@ -1131,7 +1127,7 @@ Property::Value TextEditor::GetProperty( BaseObject* object, Property::Index ind void TextEditor::SelectWholeText() { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { mController->SelectWholeText(); SetKeyInputFocus(); @@ -1140,7 +1136,7 @@ void TextEditor::SelectWholeText() void TextEditor::SelectNone() { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { mController->SelectNone(); } @@ -1148,7 +1144,7 @@ void TextEditor::SelectNone() void TextEditor::ScrollBy(Vector2 scroll) { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { mController->ScrollBy(scroll); } @@ -1156,7 +1152,7 @@ void TextEditor::ScrollBy(Vector2 scroll) float TextEditor::GetHorizontalScrollPosition() { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { return mController->GetHorizontalScrollPosition(); } @@ -1165,7 +1161,7 @@ float TextEditor::GetHorizontalScrollPosition() float TextEditor::GetVerticalScrollPosition() { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { return mController->GetVerticalScrollPosition(); } @@ -1175,9 +1171,9 @@ float TextEditor::GetVerticalScrollPosition() string TextEditor::GetSelectedText() const { string selectedText = ""; - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { - selectedText = mController->GetSelectedText( ); + selectedText = mController->GetSelectedText(); } return selectedText; } @@ -1197,27 +1193,27 @@ Text::ControllerPtr TextEditor::getController() return mController; } -bool TextEditor::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool TextEditor::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::TextEditor editor = Toolkit::TextEditor::DownCast( handle ); + bool connected(true); + Toolkit::TextEditor editor = Toolkit::TextEditor::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_TEXT_CHANGED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED)) { - editor.TextChangedSignal().Connect( tracker, functor ); + editor.TextChangedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED)) { - editor.InputStyleChangedSignal().Connect( tracker, functor ); + editor.InputStyleChangedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED)) { - if( editor ) + if(editor) { - Internal::TextEditor& editorImpl( GetImpl( editor ) ); - editorImpl.MaxLengthReachedSignal().Connect( tracker, functor ); + Internal::TextEditor& editorImpl(GetImpl(editor)); + editorImpl.MaxLengthReachedSignal().Connect(tracker, functor); } } else @@ -1248,111 +1244,110 @@ void TextEditor::OnInitialize() { Actor self = Self(); - mController = Text::Controller::New( this, this, this); + mController = Text::Controller::New(this, this, this); - mDecorator = Text::Decorator::New( *mController, - *mController ); + mDecorator = Text::Decorator::New(*mController, + *mController); - mInputMethodContext = InputMethodContext::New( self ); + mInputMethodContext = InputMethodContext::New(self); - mController->GetLayoutEngine().SetLayout( Layout::Engine::MULTI_LINE_BOX ); + mController->GetLayoutEngine().SetLayout(Layout::Engine::MULTI_LINE_BOX); // Enables the text input. - mController->EnableTextInput( mDecorator, mInputMethodContext ); + mController->EnableTextInput(mDecorator, mInputMethodContext); // Enables the vertical scrolling after the text input has been enabled. - mController->SetVerticalScrollEnabled( true ); + mController->SetVerticalScrollEnabled(true); // Disables the horizontal scrolling. - mController->SetHorizontalScrollEnabled( false ); + mController->SetHorizontalScrollEnabled(false); // Sets the maximum number of characters. - mController->SetMaximumNumberOfCharacters( std::numeric_limits::max() ); + mController->SetMaximumNumberOfCharacters(std::numeric_limits::max()); // Enable the smooth handle panning. - mController->SetSmoothHandlePanEnabled( true ); + mController->SetSmoothHandlePanEnabled(true); - mController->SetNoTextDoubleTapAction( Controller::NoTextTap::HIGHLIGHT ); - mController->SetNoTextLongPressAction( Controller::NoTextTap::HIGHLIGHT ); + mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT); + mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT); // Sets layoutDirection value - Dali::Stage stage = Dali::Stage::GetCurrent(); - Dali::LayoutDirection::Type layoutDirection = static_cast( stage.GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); - mController->SetLayoutDirection( layoutDirection ); + Dali::Stage stage = Dali::Stage::GetCurrent(); + Dali::LayoutDirection::Type layoutDirection = static_cast(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); + mController->SetLayoutDirection(layoutDirection); // Forward input events to controller - EnableGestureDetection( static_cast( GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS ) ); - GetTapGestureDetector().SetMaximumTapsRequired( 2 ); + EnableGestureDetection(static_cast(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS)); + GetTapGestureDetector().SetMaximumTapsRequired(2); - self.TouchedSignal().Connect( this, &TextEditor::OnTouched ); + self.TouchedSignal().Connect(this, &TextEditor::OnTouched); // Set BoundingBox to stage size if not already set. Rect boundingBox; - mDecorator->GetBoundingBox( boundingBox ); + mDecorator->GetBoundingBox(boundingBox); - if( boundingBox.IsEmpty() ) + if(boundingBox.IsEmpty()) { Vector2 stageSize = Dali::Stage::GetCurrent().GetSize(); - mDecorator->SetBoundingBox( Rect( 0.0f, 0.0f, stageSize.width, stageSize.height ) ); + mDecorator->SetBoundingBox(Rect(0.0f, 0.0f, stageSize.width, stageSize.height)); } // Whether to flip the selection handles as soon as they cross. - mDecorator->FlipSelectionHandlesOnCrossEnabled( true ); + mDecorator->FlipSelectionHandlesOnCrossEnabled(true); // Set the default scroll speed. - mDecorator->SetScrollSpeed( DEFAULT_SCROLL_SPEED ); + mDecorator->SetScrollSpeed(DEFAULT_SCROLL_SPEED); // Fill-parent area by default - self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); - self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT ); - self.OnSceneSignal().Connect( this, &TextEditor::OnSceneConnect ); + self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH); + self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT); + self.OnSceneSignal().Connect(this, &TextEditor::OnSceneConnect); //Enable highightability - self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); - DevelControl::SetInputMethodContext( *this, mInputMethodContext ); + DevelControl::SetInputMethodContext(*this, mInputMethodContext); // Creates an extra control to be used as stencil buffer. mStencil = Control::New(); - mStencil.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - mStencil.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); + mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); // Creates a background visual. Even if the color is transparent it updates the stencil. - mStencil.SetProperty( Toolkit::Control::Property::BACKGROUND, - Property::Map().Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR ). - Add( ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT ) ); + mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND, + Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT)); // Enable the clipping property. - mStencil.SetProperty( Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX ); - mStencil.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX); + mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); - self.Add( mStencil ); + self.Add(mStencil); - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::ENTRY ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::ENTRY)); + }); } -void TextEditor::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change ) +void TextEditor::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange\n"); - switch ( change ) + switch(change) { case StyleChange::DEFAULT_FONT_CHANGE: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange DEFAULT_FONT_CHANGE\n"); - const std::string& newFont = GetImpl( styleManager ).GetDefaultFontFamily(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnStyleChange DEFAULT_FONT_CHANGE\n"); + const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily(); // Property system did not set the font so should update it. - mController->UpdateAfterFontChange( newFont ); + mController->UpdateAfterFontChange(newFont); RelayoutRequest(); break; } case StyleChange::DEFAULT_FONT_SIZE_CHANGE: { - GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) ); + GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner())); RelayoutRequest(); break; } @@ -1364,145 +1359,144 @@ void TextEditor::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange: } // Up call to Control - Control::OnStyleChange( styleManager, change ); + Control::OnStyleChange(styleManager, change); } Vector3 TextEditor::GetNaturalSize() { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); Vector3 naturalSize = mController->GetNaturalSize(); - naturalSize.width += ( padding.start + padding.end ); - naturalSize.height += ( padding.top + padding.bottom ); + naturalSize.width += (padding.start + padding.end); + naturalSize.height += (padding.top + padding.bottom); return naturalSize; } -float TextEditor::GetHeightForWidth( float width ) +float TextEditor::GetHeightForWidth(float width) { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); - return mController->GetHeightForWidth( width ) + padding.top + padding.bottom; + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); + return mController->GetHeightForWidth(width) + padding.top + padding.bottom; } -void TextEditor::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void TextEditor::OnRelayout(const Vector2& size, RelayoutContainer& container) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor OnRelayout\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor OnRelayout\n"); Actor self = Self(); Extents padding; - padding = self.GetProperty( Toolkit::Control::Property::PADDING ); + padding = self.GetProperty(Toolkit::Control::Property::PADDING); - Vector2 contentSize( size.x - ( padding.start + padding.end ), size.y - ( padding.top + padding.bottom ) ); + Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom)); // Support Right-To-Left of padding Dali::LayoutDirection::Type layoutDirection; - if( mController->IsMatchSystemLanguageDirection() ) + if(mController->IsMatchSystemLanguageDirection()) { - layoutDirection = static_cast( DevelWindow::Get( self ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(DevelWindow::Get(self).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } else { - layoutDirection = static_cast( self.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(self.GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { - std::swap( padding.start, padding.end ); + std::swap(padding.start, padding.end); } - if( mStencil ) + if(mStencil) { - mStencil.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top )); + mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top)); } - if( mActiveLayer ) + if(mActiveLayer) { - mActiveLayer.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top )); + mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top)); } - const Text::Controller::UpdateTextType updateTextType = mController->Relayout( contentSize, layoutDirection ); + const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection); - if( ( Text::Controller::NONE_UPDATED != updateTextType ) || - !mRenderer ) + if((Text::Controller::NONE_UPDATED != updateTextType) || + !mRenderer) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnRelayout %p Displaying new contents\n", mController.Get() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnRelayout %p Displaying new contents\n", mController.Get()); - if( mDecorator && - ( Text::Controller::NONE_UPDATED != ( Text::Controller::DECORATOR_UPDATED & updateTextType ) ) ) + if(mDecorator && + (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType))) { - mDecorator->Relayout( size ); + mDecorator->Relayout(size); } - if( !mRenderer ) + if(!mRenderer) { - mRenderer = Backend::Get().NewRenderer( mRenderingBackend ); + mRenderer = Backend::Get().NewRenderer(mRenderingBackend); } - RenderText( updateTextType ); - + RenderText(updateTextType); } // The text-editor emits signals when the input style changes. These changes of style are // detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals // can't be emitted during the size negotiation as the callbacks may update the UI. // The text-editor adds an idle callback to the adaptor to emit the signals after the size negotiation. - if( !mController->IsInputStyleChangedSignalsQueueEmpty() ) + if(!mController->IsInputStyleChangedSignalsQueueEmpty()) { - if( Adaptor::IsAvailable() ) + if(Adaptor::IsAvailable()) { Adaptor& adaptor = Adaptor::Get(); - if( NULL == mIdleCallback ) + if(NULL == mIdleCallback) { // @note: The callback manager takes the ownership of the callback object. - mIdleCallback = MakeCallback( this, &TextEditor::OnIdleSignal ); - adaptor.AddIdle( mIdleCallback, false ); + mIdleCallback = MakeCallback(this, &TextEditor::OnIdleSignal); + adaptor.AddIdle(mIdleCallback, false); } } } } -void TextEditor::RenderText( Text::Controller::UpdateTextType updateTextType ) +void TextEditor::RenderText(Text::Controller::UpdateTextType updateTextType) { Actor renderableActor; - if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) ) + if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType)) { - if( mRenderer ) + if(mRenderer) { - Dali::Toolkit::TextEditor handle = Dali::Toolkit::TextEditor( GetOwner() ); + Dali::Toolkit::TextEditor handle = Dali::Toolkit::TextEditor(GetOwner()); - renderableActor = mRenderer->Render( mController->GetView(), - handle, - Property::INVALID_INDEX, // Animatable property not supported - mAlignmentOffset, - DepthIndex::CONTENT ); + renderableActor = mRenderer->Render(mController->GetView(), + handle, + Property::INVALID_INDEX, // Animatable property not supported + mAlignmentOffset, + DepthIndex::CONTENT); } - if( renderableActor != mRenderableActor ) + if(renderableActor != mRenderableActor) { - UnparentAndReset( mRenderableActor ); + UnparentAndReset(mRenderableActor); mRenderableActor = renderableActor; } } - if( mRenderableActor ) + if(mRenderableActor) { // Make sure the actors are parented correctly with/without clipping Actor self = mStencil ? mStencil : Self(); - for( std::vector::iterator it = mClippingDecorationActors.begin(), - endIt = mClippingDecorationActors.end(); - it != endIt; - ++it ) + for(std::vector::iterator it = mClippingDecorationActors.begin(), + endIt = mClippingDecorationActors.end(); + it != endIt; + ++it) { - self.Add( *it ); + self.Add(*it); it->LowerToBottom(); } mClippingDecorationActors.clear(); - self.Add( mRenderableActor ); + self.Add(mRenderableActor); ApplyScrollPosition(); } @@ -1511,59 +1505,59 @@ void TextEditor::RenderText( Text::Controller::UpdateTextType updateTextType ) void TextEditor::OnKeyInputFocusGained() { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnKeyInputFocusGained %p\n", mController.Get() ); - if ( mInputMethodContext && IsEditable() ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnKeyInputFocusGained %p\n", mController.Get()); + if(mInputMethodContext && IsEditable()) { // All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows). - mInputMethodContext.NotifyTextInputMultiLine( true ); + mInputMethodContext.NotifyTextInputMultiLine(true); - mInputMethodContext.StatusChangedSignal().Connect( this, &TextEditor::KeyboardStatusChanged ); + mInputMethodContext.StatusChangedSignal().Connect(this, &TextEditor::KeyboardStatusChanged); - mInputMethodContext.EventReceivedSignal().Connect( this, &TextEditor::OnInputMethodContextEvent ); + mInputMethodContext.EventReceivedSignal().Connect(this, &TextEditor::OnInputMethodContextEvent); // Notify that the text editing start. mInputMethodContext.Activate(); // When window gain lost focus, the InputMethodContext is deactivated. Thus when window gain focus again, the InputMethodContext must be activated. - mInputMethodContext.SetRestoreAfterFocusLost( true ); + mInputMethodContext.SetRestoreAfterFocusLost(true); } - ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() ); + ClipboardEventNotifier notifier(ClipboardEventNotifier::Get()); - if ( notifier ) + if(notifier) { - notifier.ContentSelectedSignal().Connect( this, &TextEditor::OnClipboardTextSelected ); + notifier.ContentSelectedSignal().Connect(this, &TextEditor::OnClipboardTextSelected); } mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event - EmitKeyInputFocusSignal( true ); // Calls back into the Control hence done last. + EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last. } void TextEditor::OnKeyInputFocusLost() { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor:OnKeyInputFocusLost %p\n", mController.Get() ); - if ( mInputMethodContext ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor:OnKeyInputFocusLost %p\n", mController.Get()); + if(mInputMethodContext) { - mInputMethodContext.StatusChangedSignal().Disconnect( this, &TextEditor::KeyboardStatusChanged ); + mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextEditor::KeyboardStatusChanged); // The text editing is finished. Therefore the InputMethodContext don't have restore activation. - mInputMethodContext.SetRestoreAfterFocusLost( false ); + mInputMethodContext.SetRestoreAfterFocusLost(false); // Notify that the text editing finish. mInputMethodContext.Deactivate(); - mInputMethodContext.EventReceivedSignal().Disconnect( this, &TextEditor::OnInputMethodContextEvent ); + mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextEditor::OnInputMethodContextEvent); } - ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() ); + ClipboardEventNotifier notifier(ClipboardEventNotifier::Get()); - if ( notifier ) + if(notifier) { - notifier.ContentSelectedSignal().Disconnect( this, &TextEditor::OnClipboardTextSelected ); + notifier.ContentSelectedSignal().Disconnect(this, &TextEditor::OnClipboardTextSelected); } mController->KeyboardFocusLostEvent(); - EmitKeyInputFocusSignal( false ); // Calls back into the Control hence done last. + EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last. } bool TextEditor::OnAccessibilityActivated() @@ -1572,49 +1566,49 @@ bool TextEditor::OnAccessibilityActivated() return true; } -void TextEditor::OnTap( const TapGesture& gesture ) +void TextEditor::OnTap(const TapGesture& gesture) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnTap %p\n", mController.Get() ); - if ( mInputMethodContext && IsEditable() ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnTap %p\n", mController.Get()); + if(mInputMethodContext && IsEditable()) { mInputMethodContext.Activate(); } // Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); const Vector2& localPoint = gesture.GetLocalPoint(); - mController->TapEvent( gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top ); + mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top); SetKeyInputFocus(); } -void TextEditor::OnPan( const PanGesture& gesture ) +void TextEditor::OnPan(const PanGesture& gesture) { - mController->PanEvent( gesture.GetState(), gesture.GetDisplacement() ); + mController->PanEvent(gesture.GetState(), gesture.GetDisplacement()); } -void TextEditor::OnLongPress( const LongPressGesture& gesture ) +void TextEditor::OnLongPress(const LongPressGesture& gesture) { - if ( mInputMethodContext && IsEditable() ) + if(mInputMethodContext && IsEditable()) { mInputMethodContext.Activate(); } Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); const Vector2& localPoint = gesture.GetLocalPoint(); - mController->LongPressEvent( gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top ); + mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top); SetKeyInputFocus(); } -bool TextEditor::OnKeyEvent( const KeyEvent& event ) +bool TextEditor::OnKeyEvent(const KeyEvent& event) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode()); - if( Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape() ) + if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape()) { // Make sure ClearKeyInputFocus when only key is up - if( event.GetState() == KeyEvent::UP ) + if(event.GetState() == KeyEvent::UP) { ClearKeyInputFocus(); } @@ -1622,7 +1616,7 @@ bool TextEditor::OnKeyEvent( const KeyEvent& event ) return true; } - return mController->KeyEvent( event ); + return mController->KeyEvent(event); } void TextEditor::RequestTextRelayout() @@ -1630,119 +1624,119 @@ void TextEditor::RequestTextRelayout() RelayoutRequest(); } -void TextEditor::TextInserted( unsigned int position, unsigned int length, const std::string &content ) +void TextEditor::TextInserted(unsigned int position, unsigned int length, const std::string& content) { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - Control::Impl::GetAccessibilityObject( Self() )->EmitTextInserted( position, length, content ); + Control::Impl::GetAccessibilityObject(Self())->EmitTextInserted(position, length, content); } } -void TextEditor::TextDeleted( unsigned int position, unsigned int length, const std::string &content ) +void TextEditor::TextDeleted(unsigned int position, unsigned int length, const std::string& content) { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - Control::Impl::GetAccessibilityObject( Self() )->EmitTextDeleted( position, length, content ); + Control::Impl::GetAccessibilityObject(Self())->EmitTextDeleted(position, length, content); } } -void TextEditor::CaretMoved( unsigned int position ) +void TextEditor::CaretMoved(unsigned int position) { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - Control::Impl::GetAccessibilityObject( Self() )->EmitTextCaretMoved( position ); + Control::Impl::GetAccessibilityObject(Self())->EmitTextCaretMoved(position); } } void TextEditor::TextChanged() { - Dali::Toolkit::TextEditor handle( GetOwner() ); - mTextChangedSignal.Emit( handle ); + Dali::Toolkit::TextEditor handle(GetOwner()); + mTextChangedSignal.Emit(handle); } void TextEditor::MaxLengthReached() { - Dali::Toolkit::TextEditor handle( GetOwner() ); - mMaxLengthReachedSignal.Emit( handle ); + Dali::Toolkit::TextEditor handle(GetOwner()); + mMaxLengthReachedSignal.Emit(handle); } -void TextEditor::InputStyleChanged( Text::InputStyle::Mask inputStyleMask ) +void TextEditor::InputStyleChanged(Text::InputStyle::Mask inputStyleMask) { - Dali::Toolkit::TextEditor handle( GetOwner() ); + Dali::Toolkit::TextEditor handle(GetOwner()); Toolkit::TextEditor::InputStyle::Mask editorInputStyleMask = Toolkit::TextEditor::InputStyle::NONE; - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_COLOR ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_COLOR)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::COLOR ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::COLOR); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_FAMILY ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_FAMILY)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_FAMILY ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_FAMILY); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_POINT_SIZE ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_POINT_SIZE)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::POINT_SIZE ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::POINT_SIZE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_WEIGHT ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_WEIGHT)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_WIDTH ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_WIDTH)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_SLANT ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_SLANT)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::FONT_STYLE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_LINE_SPACING ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_LINE_SPACING)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::LINE_SPACING ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::LINE_SPACING); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_UNDERLINE ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_UNDERLINE)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::UNDERLINE ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::UNDERLINE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_SHADOW ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_SHADOW)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::SHADOW ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::SHADOW); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_EMBOSS ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_EMBOSS)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::EMBOSS ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::EMBOSS); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_OUTLINE ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_OUTLINE)) { - editorInputStyleMask = static_cast( editorInputStyleMask | Toolkit::TextEditor::InputStyle::OUTLINE ); + editorInputStyleMask = static_cast(editorInputStyleMask | Toolkit::TextEditor::InputStyle::OUTLINE); } - mInputStyleChangedSignal.Emit( handle, editorInputStyleMask ); + mInputStyleChangedSignal.Emit(handle, editorInputStyleMask); } -void TextEditor::AddDecoration( Actor& actor, bool needsClipping ) +void TextEditor::AddDecoration(Actor& actor, bool needsClipping) { - if( actor ) + if(actor) { - if( needsClipping ) + if(needsClipping) { - mClippingDecorationActors.push_back( actor ); + mClippingDecorationActors.push_back(actor); } else { - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - Self().Add( actor ); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + Self().Add(actor); mActiveLayer = actor; } } } -void TextEditor::SetTextSelectionRange(const uint32_t *start, const uint32_t *end) +void TextEditor::SetTextSelectionRange(const uint32_t* start, const uint32_t* end) { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { - mController->SetTextSelectionRange( start, end ); + mController->SetTextSelectionRange(start, end); SetKeyInputFocus(); } } @@ -1750,7 +1744,7 @@ void TextEditor::SetTextSelectionRange(const uint32_t *start, const uint32_t *en Uint32Pair TextEditor::GetTextSelectionRange() const { Uint32Pair range(0, 0); - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { range = mController->GetTextSelectionRange(); } @@ -1764,100 +1758,100 @@ void TextEditor::UpdateScrollBar() float scrollPosition; float controlSize; float layoutSize; - bool latestScrolled; + bool latestScrolled; - if ( !mScrollBarEnabled ) + if(!mScrollBarEnabled) { return; } - latestScrolled = mController->GetTextScrollInfo( scrollPosition, controlSize, layoutSize ); - if ( !latestScrolled || controlSize > layoutSize) + latestScrolled = mController->GetTextScrollInfo(scrollPosition, controlSize, layoutSize); + if(!latestScrolled || controlSize > layoutSize) { return; } CustomActor self = Self(); - if( !mScrollBar ) + if(!mScrollBar) { - mScrollBar = Toolkit::ScrollBar::New( Toolkit::ScrollBar::VERTICAL ); - mScrollBar.SetIndicatorHeightPolicy( Toolkit::ScrollBar::VARIABLE ); - mScrollBar.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT ); - mScrollBar.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT ); - mScrollBar.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT ); - mScrollBar.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH ); + mScrollBar = Toolkit::ScrollBar::New(Toolkit::ScrollBar::VERTICAL); + mScrollBar.SetIndicatorHeightPolicy(Toolkit::ScrollBar::VARIABLE); + mScrollBar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT); + mScrollBar.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT); + mScrollBar.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT); + mScrollBar.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH); // Register the scroll position property - Property::Index propertyScrollPosition = self.RegisterProperty( SCROLL_BAR_POSITION, scrollPosition ); + Property::Index propertyScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION, scrollPosition); // Register the minimum scroll position property - Property::Index propertyMinScrollPosition = self.RegisterProperty( SCROLL_BAR_POSITION_MIN, 0.0f ); + Property::Index propertyMinScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MIN, 0.0f); // Register the maximum scroll position property - Property::Index propertyMaxScrollPosition = self.RegisterProperty( SCROLL_BAR_POSITION_MAX, (layoutSize - controlSize) ); + Property::Index propertyMaxScrollPosition = self.RegisterProperty(SCROLL_BAR_POSITION_MAX, (layoutSize - controlSize)); // Register the scroll content size property - Property::Index propertyScrollContentSize = self.RegisterProperty( SCROLL_BAR_CONTENT_SIZE, layoutSize ); + Property::Index propertyScrollContentSize = self.RegisterProperty(SCROLL_BAR_CONTENT_SIZE, layoutSize); mScrollBar.SetScrollPropertySource(self, propertyScrollPosition, propertyMinScrollPosition, propertyMaxScrollPosition, propertyScrollContentSize); // Set style name of ScrollBar for styling mScrollBar.SetStyleName("TextEditorScrollBar"); - Toolkit::Control scrollIndicator = Toolkit::Control::DownCast( mScrollBar.GetScrollIndicator() ); - if( scrollIndicator ) + Toolkit::Control scrollIndicator = Toolkit::Control::DownCast(mScrollBar.GetScrollIndicator()); + if(scrollIndicator) { // Set style name of ScrollBarIndicator for styling scrollIndicator.SetStyleName("TextEditorScrollBarIndicator"); } - self.Add( mScrollBar ); + self.Add(mScrollBar); } else { - Property::Index propertyScrollPosition = self.GetPropertyIndex( SCROLL_BAR_POSITION ); - Property::Index propertyMaxScrollPosition = self.GetPropertyIndex( SCROLL_BAR_POSITION_MAX ); - Property::Index propertyScrollContentSize = self.GetPropertyIndex( SCROLL_BAR_CONTENT_SIZE ); + Property::Index propertyScrollPosition = self.GetPropertyIndex(SCROLL_BAR_POSITION); + Property::Index propertyMaxScrollPosition = self.GetPropertyIndex(SCROLL_BAR_POSITION_MAX); + Property::Index propertyScrollContentSize = self.GetPropertyIndex(SCROLL_BAR_CONTENT_SIZE); - self.SetProperty( propertyScrollPosition, scrollPosition ); - self.SetProperty( propertyMaxScrollPosition, (layoutSize - controlSize) ); - self.SetProperty( propertyScrollContentSize, layoutSize ); + self.SetProperty(propertyScrollPosition, scrollPosition); + self.SetProperty(propertyMaxScrollPosition, (layoutSize - controlSize)); + self.SetProperty(propertyScrollContentSize, layoutSize); } // If scrolling is not started, start scrolling and emit ScrollStateChangedSignal - if( !mScrollStarted ) + if(!mScrollStarted) { mScrollStarted = true; - Dali::Toolkit::TextEditor handle( GetOwner() ); - mScrollStateChangedSignal.Emit( handle, Toolkit::TextEditor::Scroll::STARTED ); + Dali::Toolkit::TextEditor handle(GetOwner()); + mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::STARTED); } Actor indicator = mScrollBar.GetScrollIndicator(); - if( mAnimation ) + if(mAnimation) { mAnimation.Stop(); // Cancel any animation } else { - mAnimation = Animation::New( mAnimationPeriod.durationSeconds ); + mAnimation = Animation::New(mAnimationPeriod.durationSeconds); } - indicator.SetProperty( Actor::Property::OPACITY,1.0f); - mAnimation.AnimateTo( Property( indicator, Actor::Property::COLOR_ALPHA ), 0.0f, AlphaFunction::EASE_IN, mAnimationPeriod ); + indicator.SetProperty(Actor::Property::OPACITY, 1.0f); + mAnimation.AnimateTo(Property(indicator, Actor::Property::COLOR_ALPHA), 0.0f, AlphaFunction::EASE_IN, mAnimationPeriod); mAnimation.Play(); - mAnimation.FinishedSignal().Connect( this, &TextEditor::OnScrollIndicatorAnimationFinished ); + mAnimation.FinishedSignal().Connect(this, &TextEditor::OnScrollIndicatorAnimationFinished); } -void TextEditor::OnScrollIndicatorAnimationFinished( Animation& animation ) +void TextEditor::OnScrollIndicatorAnimationFinished(Animation& animation) { // If animation is successfully ended, then emit ScrollStateChangedSignal - if( animation.GetCurrentProgress() == 0.0f ) + if(animation.GetCurrentProgress() == 0.0f) { mScrollStarted = false; - Dali::Toolkit::TextEditor handle( GetOwner() ); - mScrollStateChangedSignal.Emit( handle, Toolkit::TextEditor::Scroll::FINISHED ); + Dali::Toolkit::TextEditor handle(GetOwner()); + mScrollStateChangedSignal.Emit(handle, Toolkit::TextEditor::Scroll::FINISHED); } } -void TextEditor::OnSceneConnect( Dali::Actor actor ) +void TextEditor::OnSceneConnect(Dali::Actor actor) { - if ( mHasBeenStaged ) + if(mHasBeenStaged) { - RenderText( static_cast( Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED ) ); + RenderText(static_cast(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED)); } else { @@ -1865,33 +1859,33 @@ void TextEditor::OnSceneConnect( Dali::Actor actor ) } } -InputMethodContext::CallbackData TextEditor::OnInputMethodContextEvent( Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent ) +InputMethodContext::CallbackData TextEditor::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName ); - return mController->OnInputMethodContextEvent( inputMethodContext, inputMethodContextEvent ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName); + return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent); } -void TextEditor::GetHandleImagePropertyValue( Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType ) +void TextEditor::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType) { - if( mDecorator ) + if(mDecorator) { Property::Map map; - map[ IMAGE_MAP_FILENAME_STRING ] = mDecorator->GetHandleImage( handleType, handleImageType ); - value = map; + map[IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType); + value = map; } } -void TextEditor::OnClipboardTextSelected( ClipboardEventNotifier& clipboard ) +void TextEditor::OnClipboardTextSelected(ClipboardEventNotifier& clipboard) { mController->PasteClipboardItemEvent(); } void TextEditor::KeyboardStatusChanged(bool keyboardShown) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextEditor::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextEditor::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown); // Just hide the grab handle when keyboard is hidden. - if (!keyboardShown ) + if(!keyboardShown) { mController->KeyboardFocusLostEvent(); } @@ -1901,18 +1895,18 @@ void TextEditor::KeyboardStatusChanged(bool keyboardShown) } } -void TextEditor::OnSceneConnection( int depth ) +void TextEditor::OnSceneConnection(int depth) { // Sets the depth to the visuals inside the text's decorator. - mDecorator->SetTextDepth( depth ); + mDecorator->SetTextDepth(depth); // The depth of the text renderer is set in the RenderText() called from OnRelayout(). // Call the Control::OnSceneConnection() to set the depth of the background. - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } -bool TextEditor::OnTouched( Actor actor, const TouchEvent& touch ) +bool TextEditor::OnTouched(Actor actor, const TouchEvent& touch) { return false; } @@ -1929,28 +1923,28 @@ void TextEditor::OnIdleSignal() void TextEditor::ApplyScrollPosition() { const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition(); - float scrollAmount = 0.0f; + float scrollAmount = 0.0f; - if ( mScrollAnimationEnabled ) + if(mScrollAnimationEnabled) { scrollAmount = mController->GetScrollAmountByUserInput(); } - if ( mTextVerticalScroller ) + if(mTextVerticalScroller) { - mTextVerticalScroller->CheckStartAnimation( mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount ); + mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount); } - else if ( Equals( scrollAmount, 0.0f, Math::MACHINE_EPSILON_1 )) + else if(Equals(scrollAmount, 0.0f, Math::MACHINE_EPSILON_1)) { - mRenderableActor.SetProperty( Actor::Property::POSITION, Vector2( scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount )); + mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount)); } else { mTextVerticalScroller = Text::TextVerticalScroller::New(); - if ( !Equals( mScrollAnimationDuration, 0.0f, Math::MACHINE_EPSILON_1 )) + if(!Equals(mScrollAnimationDuration, 0.0f, Math::MACHINE_EPSILON_1)) { - mTextVerticalScroller->SetDuration( mScrollAnimationDuration ); + mTextVerticalScroller->SetDuration(mScrollAnimationDuration); } - mTextVerticalScroller->CheckStartAnimation( mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount ); + mTextVerticalScroller->CheckStartAnimation(mRenderableActor, scrollOffset.x + mAlignmentOffset, scrollOffset.y - scrollAmount, scrollAmount); } } @@ -1959,97 +1953,97 @@ bool TextEditor::IsEditable() const return mController->IsEditable(); } -void TextEditor::SetEditable( bool editable ) +void TextEditor::SetEditable(bool editable) { mController->SetEditable(editable); - if ( mInputMethodContext && !editable ) + if(mInputMethodContext && !editable) { mInputMethodContext.Deactivate(); } } TextEditor::TextEditor() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mAnimationPeriod( 0.0f, 0.0f ), - mIdleCallback( NULL ), - mAlignmentOffset( 0.f ), - mScrollAnimationDuration( 0.f ), - mLineSpacing( 0.f ), - mRenderingBackend( DEFAULT_RENDERING_BACKEND ), - mHasBeenStaged( false ), - mScrollAnimationEnabled( false ), - mScrollBarEnabled( false ), - mScrollStarted( false ) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mAnimationPeriod(0.0f, 0.0f), + mIdleCallback(NULL), + mAlignmentOffset(0.f), + mScrollAnimationDuration(0.f), + mLineSpacing(0.f), + mRenderingBackend(DEFAULT_RENDERING_BACKEND), + mHasBeenStaged(false), + mScrollAnimationEnabled(false), + mScrollBarEnabled(false), + mScrollStarted(false) { } TextEditor::~TextEditor() { - UnparentAndReset( mStencil ); + UnparentAndReset(mStencil); - if( ( NULL != mIdleCallback ) && Adaptor::IsAvailable() ) + if((NULL != mIdleCallback) && Adaptor::IsAvailable()) { // Removes the callback from the callback manager in case the text-editor is destroyed before the callback is executed. - Adaptor::Get().RemoveIdle( mIdleCallback ); + Adaptor::Get().RemoveIdle(mIdleCallback); } } std::string TextEditor::AccessibleImpl::GetName() { - auto slf = Toolkit::TextEditor::DownCast( self ); - return slf.GetProperty( Toolkit::TextEditor::Property::TEXT ) - .Get< std::string >(); + auto slf = Toolkit::TextEditor::DownCast(self); + return slf.GetProperty(Toolkit::TextEditor::Property::TEXT) + .Get(); } -std::string TextEditor::AccessibleImpl::GetText( size_t startOffset, - size_t endOffset ) +std::string TextEditor::AccessibleImpl::GetText(size_t startOffset, + size_t endOffset) { - if( endOffset <= startOffset ) + if(endOffset <= startOffset) return {}; - auto slf = Toolkit::TextEditor::DownCast( self ); + auto slf = Toolkit::TextEditor::DownCast(self); auto txt = - slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >(); + slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get(); - if( startOffset > txt.size() || endOffset > txt.size() ) + if(startOffset > txt.size() || endOffset > txt.size()) return {}; - return txt.substr( startOffset, endOffset - startOffset ); + return txt.substr(startOffset, endOffset - startOffset); } size_t TextEditor::AccessibleImpl::GetCharacterCount() { - auto slf = Toolkit::TextEditor::DownCast( self ); + auto slf = Toolkit::TextEditor::DownCast(self); auto txt = - slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >(); + slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get(); return txt.size(); } size_t TextEditor::AccessibleImpl::GetCaretOffset() { - auto slf = Toolkit::TextEditor::DownCast( self ); - return Dali::Toolkit::GetImpl( slf ).getController()->GetCursorPosition(); + auto slf = Toolkit::TextEditor::DownCast(self); + return Dali::Toolkit::GetImpl(slf).getController()->GetCursorPosition(); } bool TextEditor::AccessibleImpl::SetCaretOffset(size_t offset) { - auto slf = Toolkit::TextEditor::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >(); - if (offset > txt.size()) + auto slf = Toolkit::TextEditor::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get(); + if(offset > txt.size()) return false; - auto& slfImpl = Dali::Toolkit::GetImpl( slf ); - slfImpl.getController()->ResetCursorPosition( offset ); + auto& slfImpl = Dali::Toolkit::GetImpl(slf); + slfImpl.getController()->ResetCursorPosition(offset); slfImpl.RequestTextRelayout(); return true; } Dali::Accessibility::Range TextEditor::AccessibleImpl::GetTextAtOffset( - size_t offset, Dali::Accessibility::TextBoundary boundary ) + size_t offset, Dali::Accessibility::TextBoundary boundary) { - auto slf = Toolkit::TextEditor::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get< std::string >(); + auto slf = Toolkit::TextEditor::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get(); auto txt_size = txt.size(); auto range = Dali::Accessibility::Range{}; @@ -2057,63 +2051,63 @@ Dali::Accessibility::Range TextEditor::AccessibleImpl::GetTextAtOffset( switch(boundary) { case Dali::Accessibility::TextBoundary::CHARACTER: + { + if(offset < txt_size) { - if (offset < txt_size) - { - range.content = txt[offset]; - range.startOffset = offset; - range.endOffset = offset + 1; - } + range.content = txt[offset]; + range.startOffset = offset; + range.endOffset = offset + 1; } - break; + } + break; case Dali::Accessibility::TextBoundary::WORD: case Dali::Accessibility::TextBoundary::LINE: - { - auto txt_c_string = txt.c_str(); - auto breaks = std::vector< char >( txt_size, 0 ); - if(boundary == Dali::Accessibility::TextBoundary::WORD) - Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data()); + { + auto txt_c_string = txt.c_str(); + auto breaks = std::vector(txt_size, 0); + if(boundary == Dali::Accessibility::TextBoundary::WORD) + Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data()); + else + Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data()); + auto index = 0u; + auto counter = 0u; + while(index < txt_size && counter <= offset) + { + auto start = index; + if(breaks[index]) + { + while(breaks[index]) + index++; + counter++; + } else - Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data()); - auto index = 0u; - auto counter = 0u; - while( index < txt_size && counter <= offset ) { - auto start = index; - if(breaks[index]) - { - while(breaks[index]) - index++; + if(boundary == Dali::Accessibility::TextBoundary::WORD) + index++; + if(boundary == Dali::Accessibility::TextBoundary::LINE) counter++; - } - else - { - if (boundary == Dali::Accessibility::TextBoundary::WORD) - index++; - if (boundary == Dali::Accessibility::TextBoundary::LINE) - counter++; - } - if ((counter > 0) && ((counter - 1) == offset)) - { - range.content = txt.substr(start, index - start + 1); - range.startOffset = start; - range.endOffset = index + 1; - } - if (boundary == Dali::Accessibility::TextBoundary::LINE) - index++; } + if((counter > 0) && ((counter - 1) == offset)) + { + range.content = txt.substr(start, index - start + 1); + range.startOffset = start; + range.endOffset = index + 1; + } + if(boundary == Dali::Accessibility::TextBoundary::LINE) + index++; } - break; + } + break; case Dali::Accessibility::TextBoundary::SENTENCE: - { - /* not supported by efl */ - } - break; + { + /* not supported by efl */ + } + break; case Dali::Accessibility::TextBoundary::PARAGRAPH: - { - /* Paragraph is not supported by libunibreak library */ - } - break; + { + /* Paragraph is not supported by libunibreak library */ + } + break; default: break; } @@ -2122,71 +2116,71 @@ Dali::Accessibility::Range TextEditor::AccessibleImpl::GetTextAtOffset( } Dali::Accessibility::Range -TextEditor::AccessibleImpl::GetSelection( size_t selectionNum ) +TextEditor::AccessibleImpl::GetSelection(size_t selectionNum) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return {}; - auto slf = Toolkit::TextEditor::DownCast( self ); - auto ctrl = Dali::Toolkit::GetImpl( slf ).getController(); + auto slf = Toolkit::TextEditor::DownCast(self); + auto ctrl = Dali::Toolkit::GetImpl(slf).getController(); std::string ret; - ctrl->RetrieveSelection( ret ); + ctrl->RetrieveSelection(ret); auto r = ctrl->GetSelectionIndexes(); - return { static_cast(r.first), static_cast(r.second), ret }; + return {static_cast(r.first), static_cast(r.second), ret}; } -bool TextEditor::AccessibleImpl::RemoveSelection( size_t selectionNum ) +bool TextEditor::AccessibleImpl::RemoveSelection(size_t selectionNum) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return false; - auto slf = Toolkit::TextEditor::DownCast( self ); - Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( 0, 0 ); + auto slf = Toolkit::TextEditor::DownCast(self); + Dali::Toolkit::GetImpl(slf).getController()->SetSelection(0, 0); return true; } -bool TextEditor::AccessibleImpl::SetSelection( size_t selectionNum, - size_t startOffset, - size_t endOffset ) +bool TextEditor::AccessibleImpl::SetSelection(size_t selectionNum, + size_t startOffset, + size_t endOffset) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return false; - auto slf = Toolkit::TextEditor::DownCast( self ); - Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( startOffset, - endOffset ); + auto slf = Toolkit::TextEditor::DownCast(self); + Dali::Toolkit::GetImpl(slf).getController()->SetSelection(startOffset, + endOffset); return true; } -bool TextEditor::AccessibleImpl::CopyText( size_t startPosition, - size_t endPosition ) +bool TextEditor::AccessibleImpl::CopyText(size_t startPosition, + size_t endPosition) { - if( endPosition <= startPosition ) + if(endPosition <= startPosition) return false; - auto slf = Toolkit::TextEditor::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get(); - Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) ); + auto slf = Toolkit::TextEditor::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get(); + Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition)); return true; } -bool TextEditor::AccessibleImpl::CutText( size_t startPosition, - size_t endPosition ) +bool TextEditor::AccessibleImpl::CutText(size_t startPosition, + size_t endPosition) { - if( endPosition <= startPosition ) + if(endPosition <= startPosition) return false; - auto slf = Toolkit::TextEditor::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextEditor::Property::TEXT ).Get(); - Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) ); + auto slf = Toolkit::TextEditor::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextEditor::Property::TEXT).Get(); + Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition)); - slf.SetProperty( Toolkit::TextEditor::Property::TEXT, - txt.substr( 0, startPosition ) + txt.substr( endPosition - startPosition, txt.size())); + slf.SetProperty(Toolkit::TextEditor::Property::TEXT, + txt.substr(0, startPosition) + txt.substr(endPosition - startPosition, txt.size())); return true; } @@ -2195,12 +2189,12 @@ Dali::Accessibility::States TextEditor::AccessibleImpl::CalculateStates() { using namespace Dali::Accessibility; - auto states = Control::Impl::AccessibleImpl::CalculateStates(); - states[State::EDITABLE] = true; + auto states = Control::Impl::AccessibleImpl::CalculateStates(); + states[State::EDITABLE] = true; states[State::FOCUSABLE] = true; Toolkit::Control focusControl = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl(); - if (self == focusControl) + if(self == focusControl) { states[State::FOCUSED] = true; } diff --git a/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp index e87ba2f..4cca3fd 100644 --- a/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-field-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,53 +19,49 @@ #include // EXTERNAL INCLUDES -#include -#include -#include +#include #include #include #include #include -#include -#include #include +#include +#include +#include +#include // INTERNAL INCLUDES -#include -#include -#include #include -#include +#include #include -#include -#include +#include +#include +#include #include #include +#include #include #include -#include -#include +#include +#include +#include #include using namespace Dali::Toolkit::Text; namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // unnamed namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_CONTROLS"); #endif - const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND; +const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND; } // unnamed namespace namespace @@ -76,90 +72,92 @@ BaseHandle Create() return Toolkit::TextField::New(); } +// clang-format off // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextField, Toolkit::Control, Create ); -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "text", STRING, TEXT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholderText", STRING, PLACEHOLDER_TEXT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholderTextFocused", STRING, PLACEHOLDER_TEXT_FOCUSED ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "fontFamily", STRING, FONT_FAMILY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "fontStyle", MAP, FONT_STYLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "pointSize", FLOAT, POINT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "maxLength", INTEGER, MAX_LENGTH ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "exceedPolicy", INTEGER, EXCEED_POLICY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "verticalAlignment", STRING, VERTICAL_ALIGNMENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "textColor", VECTOR4, TEXT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "cursorWidth", INTEGER, CURSOR_WIDTH ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "scrollThreshold", FLOAT, SCROLL_THRESHOLD ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "scrollSpeed", FLOAT, SCROLL_SPEED ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputMethodSettings", MAP, INPUT_METHOD_SETTINGS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputColor", VECTOR4, INPUT_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "enableMarkup", BOOLEAN, ENABLE_MARKUP ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputFontFamily", STRING, INPUT_FONT_FAMILY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputFontStyle", MAP, INPUT_FONT_STYLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputPointSize", FLOAT, INPUT_POINT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "underline", MAP, UNDERLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputUnderline", MAP, INPUT_UNDERLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "shadow", MAP, SHADOW ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputShadow", MAP, INPUT_SHADOW ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "emboss", MAP, EMBOSS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputEmboss", MAP, INPUT_EMBOSS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "outline", MAP, OUTLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "inputOutline", MAP, INPUT_OUTLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "hiddenInputSettings", MAP, HIDDEN_INPUT_SETTINGS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "pixelSize", FLOAT, PIXEL_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "enableSelection", BOOLEAN, ENABLE_SELECTION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "placeholder", MAP, PLACEHOLDER ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextField, "ellipsis", BOOLEAN, ELLIPSIS ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableGrabHandlePopup", BOOLEAN, ENABLE_GRAB_HANDLE_POPUP ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "textBackground", VECTOR4, BACKGROUND ) -DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextField, "selectedText", STRING, SELECTED_TEXT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "renderingBackend", INTEGER, RENDERING_BACKEND ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "selectedTextStart", INTEGER, SELECTED_TEXT_START ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "selectedTextEnd", INTEGER, SELECTED_TEXT_END ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "enableEditing", BOOLEAN, ENABLE_EDITING ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "fontSizeScale", FLOAT, FONT_SIZE_SCALE ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextField, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION ) - -DALI_SIGNAL_REGISTRATION( Toolkit, TextField, "textChanged", SIGNAL_TEXT_CHANGED ) -DALI_SIGNAL_REGISTRATION( Toolkit, TextField, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED ) -DALI_SIGNAL_REGISTRATION( Toolkit, TextField, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "text", STRING, TEXT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholderText", STRING, PLACEHOLDER_TEXT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholderTextFocused", STRING, PLACEHOLDER_TEXT_FOCUSED ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "fontFamily", STRING, FONT_FAMILY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "fontStyle", MAP, FONT_STYLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "pointSize", FLOAT, POINT_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "maxLength", INTEGER, MAX_LENGTH ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "exceedPolicy", INTEGER, EXCEED_POLICY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "verticalAlignment", STRING, VERTICAL_ALIGNMENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "textColor", VECTOR4, TEXT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholderTextColor", VECTOR4, PLACEHOLDER_TEXT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "primaryCursorColor", VECTOR4, PRIMARY_CURSOR_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "secondaryCursorColor", VECTOR4, SECONDARY_CURSOR_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "enableCursorBlink", BOOLEAN, ENABLE_CURSOR_BLINK ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "cursorBlinkInterval", FLOAT, CURSOR_BLINK_INTERVAL ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "cursorBlinkDuration", FLOAT, CURSOR_BLINK_DURATION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "cursorWidth", INTEGER, CURSOR_WIDTH ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "grabHandleImage", STRING, GRAB_HANDLE_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "grabHandlePressedImage", STRING, GRAB_HANDLE_PRESSED_IMAGE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "scrollThreshold", FLOAT, SCROLL_THRESHOLD ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "scrollSpeed", FLOAT, SCROLL_SPEED ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleImageLeft", MAP, SELECTION_HANDLE_IMAGE_LEFT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleImageRight", MAP, SELECTION_HANDLE_IMAGE_RIGHT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandlePressedImageLeft", MAP, SELECTION_HANDLE_PRESSED_IMAGE_LEFT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandlePressedImageRight", MAP, SELECTION_HANDLE_PRESSED_IMAGE_RIGHT) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleMarkerImageLeft", MAP, SELECTION_HANDLE_MARKER_IMAGE_LEFT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHandleMarkerImageRight", MAP, SELECTION_HANDLE_MARKER_IMAGE_RIGHT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "selectionHighlightColor", VECTOR4, SELECTION_HIGHLIGHT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "decorationBoundingBox", RECTANGLE, DECORATION_BOUNDING_BOX ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputMethodSettings", MAP, INPUT_METHOD_SETTINGS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputColor", VECTOR4, INPUT_COLOR ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "enableMarkup", BOOLEAN, ENABLE_MARKUP ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputFontFamily", STRING, INPUT_FONT_FAMILY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputFontStyle", MAP, INPUT_FONT_STYLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputPointSize", FLOAT, INPUT_POINT_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "underline", MAP, UNDERLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputUnderline", MAP, INPUT_UNDERLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "shadow", MAP, SHADOW ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputShadow", MAP, INPUT_SHADOW ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "emboss", MAP, EMBOSS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputEmboss", MAP, INPUT_EMBOSS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "outline", MAP, OUTLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "inputOutline", MAP, INPUT_OUTLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "hiddenInputSettings", MAP, HIDDEN_INPUT_SETTINGS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "pixelSize", FLOAT, PIXEL_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "enableSelection", BOOLEAN, ENABLE_SELECTION ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "placeholder", MAP, PLACEHOLDER ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextField, "ellipsis", BOOLEAN, ELLIPSIS ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableShiftSelection", BOOLEAN, ENABLE_SHIFT_SELECTION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableGrabHandle", BOOLEAN, ENABLE_GRAB_HANDLE ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableGrabHandlePopup", BOOLEAN, ENABLE_GRAB_HANDLE_POPUP ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "textBackground", VECTOR4, BACKGROUND ) +DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextField, "selectedText", STRING, SELECTED_TEXT ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "renderingBackend", INTEGER, RENDERING_BACKEND ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "selectedTextStart", INTEGER, SELECTED_TEXT_START ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "selectedTextEnd", INTEGER, SELECTED_TEXT_END ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "enableEditing", BOOLEAN, ENABLE_EDITING ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "fontSizeScale", FLOAT, FONT_SIZE_SCALE ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextField, "primaryCursorPosition", INTEGER, PRIMARY_CURSOR_POSITION ) + +DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "textChanged", SIGNAL_TEXT_CHANGED ) +DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "maxLengthReached", SIGNAL_MAX_LENGTH_REACHED ) +DALI_SIGNAL_REGISTRATION(Toolkit, TextField, "inputStyleChanged", SIGNAL_INPUT_STYLE_CHANGED) DALI_TYPE_REGISTRATION_END() +// clang-format on -const char * const IMAGE_MAP_FILENAME_STRING = "filename"; +const char* const IMAGE_MAP_FILENAME_STRING = "filename"; /// Retrieves a filename from a value that is a Property::Map -std::string GetImageFileNameFromPropertyValue( const Property::Value& value ) +std::string GetImageFileNameFromPropertyValue(const Property::Value& value) { - std::string filename; + std::string filename; const Property::Map* map = value.GetMap(); - if( map ) + if(map) { - const Property::Value* filenameValue = map->Find( IMAGE_MAP_FILENAME_STRING ); - if( filenameValue ) + const Property::Value* filenameValue = map->Find(IMAGE_MAP_FILENAME_STRING); + if(filenameValue) { - filenameValue->Get( filename ); + filenameValue->Get(filename); } } return filename; @@ -170,10 +168,10 @@ std::string GetImageFileNameFromPropertyValue( const Property::Value& value ) Toolkit::TextField TextField::New() { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< TextField > impl = new TextField(); + IntrusivePtr impl = new TextField(); // Pass ownership to CustomActor handle - Toolkit::TextField handle( *impl ); + Toolkit::TextField handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -182,388 +180,388 @@ Toolkit::TextField TextField::New() return handle; } -void TextField::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void TextField::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::TextField textField = Toolkit::TextField::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextField textField = Toolkit::TextField::DownCast(Dali::BaseHandle(object)); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField SetProperty\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField SetProperty\n"); - if( textField ) + if(textField) { - TextField& impl( GetImpl( textField ) ); - DALI_ASSERT_DEBUG( impl.mController && "No text contoller" ); - DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" ); + TextField& impl(GetImpl(textField)); + DALI_ASSERT_DEBUG(impl.mController && "No text contoller"); + DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator"); - switch( index ) + switch(index) { case Toolkit::DevelTextField::Property::RENDERING_BACKEND: { - int backend = value.Get< int >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend ); + int backend = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p RENDERING_BACKEND %d\n", impl.mController.Get(), backend); #ifndef ENABLE_VECTOR_BASED_TEXT_RENDERING - if( DevelText::RENDERING_VECTOR_BASED == backend ) + if(DevelText::RENDERING_VECTOR_BASED == backend) { backend = TextAbstraction::BITMAP_GLYPH; // Fallback to bitmap-based rendering } #endif - if( impl.mRenderingBackend != backend ) + if(impl.mRenderingBackend != backend) { impl.mRenderingBackend = backend; impl.mRenderer.Reset(); // When using the vector-based rendering, the size of the GLyphs are different TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == impl.mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH; - impl.mController->SetGlyphType( glyphType ); + impl.mController->SetGlyphType(glyphType); } break; } case Toolkit::TextField::Property::TEXT: { - const std::string& text = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p TEXT %s\n", impl.mController.Get(), text.c_str() ); + const std::string& text = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p TEXT %s\n", impl.mController.Get(), text.c_str()); - impl.mController->SetText( text ); + impl.mController->SetText(text); break; } case Toolkit::TextField::Property::PLACEHOLDER_TEXT: { - const std::string& text = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str() ); + const std::string& text = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT %s\n", impl.mController.Get(), text.c_str()); - impl.mController->SetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text ); + impl.mController->SetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text); break; } case Toolkit::TextField::Property::PLACEHOLDER_TEXT_FOCUSED: { - const std::string& text = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_FOCUSED %s\n", impl.mController.Get(), text.c_str() ); + const std::string& text = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_FOCUSED %s\n", impl.mController.Get(), text.c_str()); - impl.mController->SetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text ); + impl.mController->SetPlaceholderText(Controller::PLACEHOLDER_TYPE_ACTIVE, text); break; } case Toolkit::TextField::Property::FONT_FAMILY: { - const std::string& fontFamily = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() ); - impl.mController->SetDefaultFontFamily( fontFamily ); + const std::string& fontFamily = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str()); + impl.mController->SetDefaultFontFamily(fontFamily); break; } case Toolkit::TextField::Property::FONT_STYLE: { - SetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT ); + SetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT); break; } case Toolkit::TextField::Property::POINT_SIZE: { - const float pointSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p POINT_SIZE %f\n", impl.mController.Get(), pointSize ); + const float pointSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p POINT_SIZE %f\n", impl.mController.Get(), pointSize); - if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) ) + if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize)) { - impl.mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE ); + impl.mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE); } break; } case Toolkit::TextField::Property::MAX_LENGTH: { - const int max = value.Get< int >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p MAX_LENGTH %d\n", impl.mController.Get(), max ); + const int max = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p MAX_LENGTH %d\n", impl.mController.Get(), max); - impl.mController->SetMaximumNumberOfCharacters( max ); + impl.mController->SetMaximumNumberOfCharacters(max); break; } case Toolkit::TextField::Property::EXCEED_POLICY: { impl.mExceedPolicy = value.Get(); - if( Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == impl.mExceedPolicy ) + if(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == impl.mExceedPolicy) { impl.EnableClipping(); } else { - UnparentAndReset( impl.mStencil ); + UnparentAndReset(impl.mStencil); } impl.RequestTextRelayout(); break; } case Toolkit::TextField::Property::HORIZONTAL_ALIGNMENT: { - Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( GetHorizontalAlignmentEnumeration( value, alignment ) ) + Text::HorizontalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(GetHorizontalAlignmentEnumeration(value, alignment)) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment ); - impl.mController->SetHorizontalAlignment( alignment ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p HORIZONTAL_ALIGNMENT %d\n", impl.mController.Get(), alignment); + impl.mController->SetHorizontalAlignment(alignment); } break; } case Toolkit::TextField::Property::VERTICAL_ALIGNMENT: { - Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( GetVerticalAlignmentEnumeration( value, alignment ) ) + Toolkit::Text::VerticalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(GetVerticalAlignmentEnumeration(value, alignment)) { - impl.mController->SetVerticalAlignment( alignment ); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p VERTICAL_ALIGNMENT %d\n", impl.mController.Get(), alignment ); + impl.mController->SetVerticalAlignment(alignment); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p VERTICAL_ALIGNMENT %d\n", impl.mController.Get(), alignment); } break; } case Toolkit::TextField::Property::TEXT_COLOR: { - const Vector4& textColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a ); + const Vector4& textColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a); - if( impl.mController->GetDefaultColor() != textColor ) + if(impl.mController->GetDefaultColor() != textColor) { - impl.mController->SetDefaultColor( textColor ); - impl.mController->SetInputColor( textColor ); + impl.mController->SetDefaultColor(textColor); + impl.mController->SetInputColor(textColor); impl.mRenderer.Reset(); } break; } case Toolkit::TextField::Property::PLACEHOLDER_TEXT_COLOR: { - const Vector4& textColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a ); + const Vector4& textColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PLACEHOLDER_TEXT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), textColor.r, textColor.g, textColor.b, textColor.a); - if( impl.mController->GetPlaceholderTextColor() != textColor ) + if(impl.mController->GetPlaceholderTextColor() != textColor) { - impl.mController->SetPlaceholderTextColor( textColor ); + impl.mController->SetPlaceholderTextColor(textColor); impl.mRenderer.Reset(); } break; } case Toolkit::TextField::Property::PRIMARY_CURSOR_COLOR: { - const Vector4& color = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a ); + const Vector4& color = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a); - impl.mDecorator->SetCursorColor( PRIMARY_CURSOR, color ); + impl.mDecorator->SetCursorColor(PRIMARY_CURSOR, color); impl.RequestTextRelayout(); break; } case Toolkit::TextField::Property::SECONDARY_CURSOR_COLOR: { - const Vector4& color = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a ); + const Vector4& color = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SECONDARY_CURSOR_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a); - impl.mDecorator->SetCursorColor( SECONDARY_CURSOR, color ); + impl.mDecorator->SetCursorColor(SECONDARY_CURSOR, color); impl.RequestTextRelayout(); break; } case Toolkit::TextField::Property::ENABLE_CURSOR_BLINK: { - const bool enable = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable ); + const bool enable = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p ENABLE_CURSOR_BLINK %d\n", impl.mController.Get(), enable); - impl.mController->SetEnableCursorBlink( enable ); + impl.mController->SetEnableCursorBlink(enable); impl.RequestTextRelayout(); break; } case Toolkit::TextField::Property::CURSOR_BLINK_INTERVAL: { - const float interval = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval ); + const float interval = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_INTERVAL %f\n", impl.mController.Get(), interval); - impl.mDecorator->SetCursorBlinkInterval( interval ); + impl.mDecorator->SetCursorBlinkInterval(interval); break; } case Toolkit::TextField::Property::CURSOR_BLINK_DURATION: { - const float duration = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration ); + const float duration = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p CURSOR_BLINK_DURATION %f\n", impl.mController.Get(), duration); - impl.mDecorator->SetCursorBlinkDuration( duration ); + impl.mDecorator->SetCursorBlinkDuration(duration); break; } case Toolkit::TextField::Property::CURSOR_WIDTH: { - const int width = value.Get< int >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p CURSOR_WIDTH %d\n", impl.mController.Get(), width ); + const int width = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p CURSOR_WIDTH %d\n", impl.mController.Get(), width); - impl.mDecorator->SetCursorWidth( width ); - impl.mController->GetLayoutEngine().SetCursorWidth( width ); + impl.mDecorator->SetCursorWidth(width); + impl.mController->GetLayoutEngine().SetCursorWidth(width); break; } case Toolkit::TextField::Property::GRAB_HANDLE_IMAGE: { - const std::string imageFileName = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() ); + const std::string imageFileName = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str()); - if( imageFileName.size() ) + if(imageFileName.size()) { - impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName ); + impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED, imageFileName); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::GRAB_HANDLE_PRESSED_IMAGE: { - const std::string imageFileName = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str() ); + const std::string imageFileName = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p GRAB_HANDLE_PRESSED_IMAGE %s\n", impl.mController.Get(), imageFileName.c_str()); - if( imageFileName.size() ) + if(imageFileName.size()) { - impl.mDecorator->SetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName ); + impl.mDecorator->SetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED, imageFileName); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SCROLL_THRESHOLD: { - const float threshold = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold ); + const float threshold = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p SCROLL_THRESHOLD %f\n", impl.mController.Get(), threshold); - impl.mDecorator->SetScrollThreshold( threshold ); + impl.mDecorator->SetScrollThreshold(threshold); break; } case Toolkit::TextField::Property::SCROLL_SPEED: { - const float speed = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField %p SCROLL_SPEED %f\n", impl.mController.Get(), speed ); + const float speed = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField %p SCROLL_SPEED %f\n", impl.mController.Get(), speed); - impl.mDecorator->SetScrollSpeed( speed ); + impl.mDecorator->SetScrollSpeed(speed); break; } case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_LEFT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_RIGHT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename ); + impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename ); + impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT: { - const std::string filename = GetImageFileNameFromPropertyValue( value ); + const std::string filename = GetImageFileNameFromPropertyValue(value); - if( filename.size() ) + if(filename.size()) { - impl.mDecorator->SetHandleImage( RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename ); + impl.mDecorator->SetHandleImage(RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED, filename); impl.RequestTextRelayout(); } break; } case Toolkit::TextField::Property::SELECTION_HIGHLIGHT_COLOR: { - const Vector4 color = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a ); + const Vector4 color = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SELECTION_HIGHLIGHT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), color.r, color.g, color.b, color.a); - impl.mDecorator->SetHighlightColor( color ); + impl.mDecorator->SetHighlightColor(color); impl.RequestTextRelayout(); break; } case Toolkit::TextField::Property::DECORATION_BOUNDING_BOX: { - const Rect box = value.Get< Rect >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height ); + const Rect box = value.Get >(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p DECORATION_BOUNDING_BOX %d,%d %dx%d\n", impl.mController.Get(), box.x, box.y, box.width, box.height); - impl.mDecorator->SetBoundingBox( box ); + impl.mDecorator->SetBoundingBox(box); impl.RequestTextRelayout(); break; } case Toolkit::TextField::Property::INPUT_METHOD_SETTINGS: { const Property::Map* map = value.GetMap(); - if (map) + if(map) { - impl.mInputMethodOptions.ApplyProperty( *map ); + impl.mInputMethodOptions.ApplyProperty(*map); } - impl.mController->SetInputModePassword( impl.mInputMethodOptions.IsPassword() ); + impl.mController->SetInputModePassword(impl.mInputMethodOptions.IsPassword()); Toolkit::Control control = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl(); - if (control == textField) + if(control == textField) { - impl.mInputMethodContext.ApplyOptions( impl.mInputMethodOptions ); + impl.mInputMethodContext.ApplyOptions(impl.mInputMethodOptions); } break; } case Toolkit::TextField::Property::INPUT_COLOR: { - const Vector4 inputColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a ); + const Vector4 inputColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p INPUT_COLOR %f,%f,%f,%f\n", impl.mController.Get(), inputColor.r, inputColor.g, inputColor.b, inputColor.a); - impl.mController->SetInputColor( inputColor ); + impl.mController->SetInputColor(inputColor); break; } case Toolkit::TextField::Property::ENABLE_MARKUP: { const bool enableMarkup = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_MARKUP %d\n", impl.mController.Get(), enableMarkup); - impl.mController->SetMarkupProcessorEnabled( enableMarkup ); + impl.mController->SetMarkupProcessorEnabled(enableMarkup); break; } case Toolkit::TextField::Property::INPUT_FONT_FAMILY: { - const std::string& fontFamily = value.Get< std::string >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str() ); - impl.mController->SetInputFontFamily( fontFamily ); + const std::string& fontFamily = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p INPUT_FONT_FAMILY %s\n", impl.mController.Get(), fontFamily.c_str()); + impl.mController->SetInputFontFamily(fontFamily); break; } case Toolkit::TextField::Property::INPUT_FONT_STYLE: { - SetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT ); + SetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT); break; } case Toolkit::TextField::Property::INPUT_POINT_SIZE: { - const float pointSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize ); - impl.mController->SetInputFontPointSize( pointSize ); + const float pointSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p INPUT_POINT_SIZE %f\n", impl.mController.Get(), pointSize); + impl.mController->SetInputFontPointSize(pointSize); break; } case Toolkit::TextField::Property::UNDERLINE: { - const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -571,8 +569,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::INPUT_UNDERLINE: { - const bool update = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -580,8 +578,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::SHADOW: { - const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -589,8 +587,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::INPUT_SHADOW: { - const bool update = SetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -598,8 +596,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::EMBOSS: { - const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -607,8 +605,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::INPUT_EMBOSS: { - const bool update = SetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -616,8 +614,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::OUTLINE: { - const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); - if( update ) + const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); + if(update) { impl.mRenderer.Reset(); } @@ -625,8 +623,8 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::INPUT_OUTLINE: { - const bool update = SetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); - if( update ) + const bool update = SetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT); + if(update) { impl.mRenderer.Reset(); } @@ -635,7 +633,7 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr case Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS: { const Property::Map* map = value.GetMap(); - if (map) + if(map) { impl.mController->SetHiddenInputOption(*map); } @@ -643,58 +641,58 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::TextField::Property::PIXEL_SIZE: { - const float pixelSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize ); + const float pixelSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize); - if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) ) + if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE), pixelSize)) { - impl.mController->SetDefaultFontSize( pixelSize, Text::Controller::PIXEL_SIZE ); + impl.mController->SetDefaultFontSize(pixelSize, Text::Controller::PIXEL_SIZE); } break; } case Toolkit::TextField::Property::ENABLE_SELECTION: { - const bool enableSelection = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection ); - impl.mController->SetSelectionEnabled( enableSelection ); + const bool enableSelection = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_SELECTION %d\n", impl.mController.Get(), enableSelection); + impl.mController->SetSelectionEnabled(enableSelection); break; } case Toolkit::TextField::Property::PLACEHOLDER: { const Property::Map* map = value.GetMap(); - if( map ) + if(map) { - impl.mController->SetPlaceholderProperty( *map ); + impl.mController->SetPlaceholderProperty(*map); } break; } case Toolkit::TextField::Property::ELLIPSIS: { const bool ellipsis = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis); - impl.mController->SetTextElideEnabled( ellipsis ); + impl.mController->SetTextElideEnabled(ellipsis); break; } case Toolkit::DevelTextField::Property::ENABLE_SHIFT_SELECTION: { const bool shiftSelection = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_SHIFT_SELECTION %d\n", impl.mController.Get(), shiftSelection); - impl.mController->SetShiftSelectionEnabled( shiftSelection ); + impl.mController->SetShiftSelectionEnabled(shiftSelection); break; } case Toolkit::DevelTextField::Property::ENABLE_GRAB_HANDLE: { const bool grabHandleEnabled = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_GRAB_HANDLE %d\n", impl.mController.Get(), grabHandleEnabled); - impl.mController->SetGrabHandleEnabled( grabHandleEnabled ); + impl.mController->SetGrabHandleEnabled(grabHandleEnabled); break; } case Toolkit::DevelTextField::Property::MATCH_SYSTEM_LANGUAGE_DIRECTION: { - impl.mController->SetMatchSystemLanguageDirection(value.Get< bool >()); + impl.mController->SetMatchSystemLanguageDirection(value.Get()); break; } case Toolkit::DevelTextField::Property::ENABLE_GRAB_HANDLE_POPUP: @@ -707,72 +705,72 @@ void TextField::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::DevelTextField::Property::BACKGROUND: { - const Vector4 backgroundColor = value.Get< Vector4 >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p BACKGROUND %f,%f,%f,%f\n", impl.mController.Get(), backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a ); + const Vector4 backgroundColor = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p BACKGROUND %f,%f,%f,%f\n", impl.mController.Get(), backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a); - impl.mController->SetBackgroundEnabled( true ); - impl.mController->SetBackgroundColor( backgroundColor ); + impl.mController->SetBackgroundEnabled(true); + impl.mController->SetBackgroundColor(backgroundColor); break; } case Toolkit::DevelTextField::Property::SELECTED_TEXT_START: { - uint32_t start = static_cast(value.Get< int >()); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start ); - impl.SetTextSelectionRange( &start, nullptr ); + uint32_t start = static_cast(value.Get()); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_START %d\n", impl.mController.Get(), start); + impl.SetTextSelectionRange(&start, nullptr); break; } case Toolkit::DevelTextField::Property::SELECTED_TEXT_END: { - uint32_t end = static_cast(value.Get< int >()); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end ); - impl.SetTextSelectionRange( nullptr, &end ); + uint32_t end = static_cast(value.Get()); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p SELECTED_TEXT_END %d\n", impl.mController.Get(), end); + impl.SetTextSelectionRange(nullptr, &end); break; } case Toolkit::DevelTextField::Property::ENABLE_EDITING: { - const bool editable = value.Get< bool >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p ENABLE_EDITING %d\n", impl.mController.Get(), editable ); - impl.SetEditable( editable ); + const bool editable = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p ENABLE_EDITING %d\n", impl.mController.Get(), editable); + impl.SetEditable(editable); break; } case Toolkit::DevelTextField::Property::FONT_SIZE_SCALE: { - const float scale = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale ); + const float scale = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale); - if( !Equals( impl.mController->GetFontSizeScale(), scale ) ) + if(!Equals(impl.mController->GetFontSizeScale(), scale)) { - impl.mController->SetFontSizeScale( scale ); + impl.mController->SetFontSizeScale(scale); } break; } case Toolkit::DevelTextField::Property::PRIMARY_CURSOR_POSITION: { - uint32_t position = static_cast(value.Get< int >()); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position ); - if (impl.mController->SetPrimaryCursorPosition( position )) + uint32_t position = static_cast(value.Get()); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p PRIMARY_CURSOR_POSITION %d\n", impl.mController.Get(), position); + if(impl.mController->SetPrimaryCursorPosition(position)) { impl.SetKeyInputFocus(); } break; } } // switch - } // textfield + } // textfield } -Property::Value TextField::GetProperty( BaseObject* object, Property::Index index ) +Property::Value TextField::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::TextField textField = Toolkit::TextField::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextField textField = Toolkit::TextField::DownCast(Dali::BaseHandle(object)); - if( textField ) + if(textField) { - TextField& impl( GetImpl( textField ) ); - DALI_ASSERT_DEBUG( impl.mController && "No text contoller" ); - DALI_ASSERT_DEBUG( impl.mDecorator && "No text decorator" ); + TextField& impl(GetImpl(textField)); + DALI_ASSERT_DEBUG(impl.mController && "No text contoller"); + DALI_ASSERT_DEBUG(impl.mDecorator && "No text decorator"); - switch( index ) + switch(index) { case Toolkit::DevelTextField::Property::RENDERING_BACKEND: { @@ -782,22 +780,22 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde case Toolkit::TextField::Property::TEXT: { std::string text; - impl.mController->GetText( text ); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextField %p returning text: %s\n", impl.mController.Get(), text.c_str() ); + impl.mController->GetText(text); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextField %p returning text: %s\n", impl.mController.Get(), text.c_str()); value = text; break; } case Toolkit::TextField::Property::PLACEHOLDER_TEXT: { std::string text; - impl.mController->GetPlaceholderText( Controller::PLACEHOLDER_TYPE_INACTIVE, text ); + impl.mController->GetPlaceholderText(Controller::PLACEHOLDER_TYPE_INACTIVE, text); value = text; break; } case Toolkit::TextField::Property::PLACEHOLDER_TEXT_FOCUSED: { std::string text; - impl.mController->GetPlaceholderText( Controller::PLACEHOLDER_TYPE_ACTIVE, text ); + impl.mController->GetPlaceholderText(Controller::PLACEHOLDER_TYPE_ACTIVE, text); value = text; break; } @@ -808,12 +806,12 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::FONT_STYLE: { - GetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT ); + GetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT); break; } case Toolkit::TextField::Property::POINT_SIZE: { - value = impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ); + value = impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE); break; } case Toolkit::TextField::Property::MAX_LENGTH: @@ -828,21 +826,21 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::HORIZONTAL_ALIGNMENT: { - const char* name = Text::GetHorizontalAlignmentString( impl.mController->GetHorizontalAlignment() ); + const char* name = Text::GetHorizontalAlignmentString(impl.mController->GetHorizontalAlignment()); - if ( name ) + if(name) { - value = std::string( name ); + value = std::string(name); } break; } case Toolkit::TextField::Property::VERTICAL_ALIGNMENT: { - const char* name = Text::GetVerticalAlignmentString( impl.mController->GetVerticalAlignment() ); + const char* name = Text::GetVerticalAlignmentString(impl.mController->GetVerticalAlignment()); - if( name ) + if(name) { - value = std::string( name ); + value = std::string(name); } break; } @@ -858,12 +856,12 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::PRIMARY_CURSOR_COLOR: { - value = impl.mDecorator->GetColor( PRIMARY_CURSOR ); + value = impl.mDecorator->GetColor(PRIMARY_CURSOR); break; } case Toolkit::TextField::Property::SECONDARY_CURSOR_COLOR: { - value = impl.mDecorator->GetColor( SECONDARY_CURSOR ); + value = impl.mDecorator->GetColor(SECONDARY_CURSOR); break; } case Toolkit::TextField::Property::ENABLE_CURSOR_BLINK: @@ -888,12 +886,12 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::GRAB_HANDLE_IMAGE: { - value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_RELEASED ); + value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextField::Property::GRAB_HANDLE_PRESSED_IMAGE: { - value = impl.mDecorator->GetHandleImage( GRAB_HANDLE, HANDLE_IMAGE_PRESSED ); + value = impl.mDecorator->GetHandleImage(GRAB_HANDLE, HANDLE_IMAGE_PRESSED); break; } case Toolkit::TextField::Property::SCROLL_THRESHOLD: @@ -908,32 +906,32 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_LEFT: { - impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED ); + impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextField::Property::SELECTION_HANDLE_IMAGE_RIGHT: { - impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED ) ; + impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_LEFT: { - impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED ); + impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED); break; } case Toolkit::TextField::Property::SELECTION_HANDLE_PRESSED_IMAGE_RIGHT: { - impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED ); + impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE, HANDLE_IMAGE_PRESSED); break; } case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_LEFT: { - impl.GetHandleImagePropertyValue( value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED ); + impl.GetHandleImagePropertyValue(value, LEFT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextField::Property::SELECTION_HANDLE_MARKER_IMAGE_RIGHT: { - impl.GetHandleImagePropertyValue( value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED ); + impl.GetHandleImagePropertyValue(value, RIGHT_SELECTION_HANDLE_MARKER, HANDLE_IMAGE_RELEASED); break; } case Toolkit::TextField::Property::SELECTION_HIGHLIGHT_COLOR: @@ -944,14 +942,14 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde case Toolkit::TextField::Property::DECORATION_BOUNDING_BOX: { Rect boundingBox; - impl.mDecorator->GetBoundingBox( boundingBox ); + impl.mDecorator->GetBoundingBox(boundingBox); value = boundingBox; break; } case Toolkit::TextField::Property::INPUT_METHOD_SETTINGS: { Property::Map map; - impl.mInputMethodOptions.RetrieveProperty( map ); + impl.mInputMethodOptions.RetrieveProperty(map); value = map; break; } @@ -972,7 +970,7 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::INPUT_FONT_STYLE: { - GetFontStyleProperty( impl.mController, value, Text::FontStyle::INPUT ); + GetFontStyleProperty(impl.mController, value, Text::FontStyle::INPUT); break; } case Toolkit::TextField::Property::INPUT_POINT_SIZE: @@ -982,42 +980,42 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::UNDERLINE: { - GetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextField::Property::INPUT_UNDERLINE: { - GetUnderlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetUnderlineProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextField::Property::SHADOW: { - GetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextField::Property::INPUT_SHADOW: { - GetShadowProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetShadowProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextField::Property::EMBOSS: { - GetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextField::Property::INPUT_EMBOSS: { - GetEmbossProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetEmbossProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextField::Property::OUTLINE: { - GetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextField::Property::INPUT_OUTLINE: { - GetOutlineProperties( impl.mController, value, Text::EffectStyle::INPUT ); + GetOutlineProperties(impl.mController, value, Text::EffectStyle::INPUT); break; } case Toolkit::TextField::Property::HIDDEN_INPUT_SETTINGS: @@ -1029,7 +1027,7 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextField::Property::PIXEL_SIZE: { - value = impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ); + value = impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE); break; } case Toolkit::TextField::Property::ENABLE_SELECTION: @@ -1040,7 +1038,7 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde case Toolkit::TextField::Property::PLACEHOLDER: { Property::Map map; - impl.mController->GetPlaceholderProperty( map ); + impl.mController->GetPlaceholderProperty(map); value = map; break; } @@ -1076,19 +1074,19 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::DevelTextField::Property::SELECTED_TEXT: { - value = impl.mController->GetSelectedText( ); + value = impl.mController->GetSelectedText(); break; } case Toolkit::DevelTextField::Property::SELECTED_TEXT_START: { - Uint32Pair range = impl.GetTextSelectionRange( ); - value = static_cast(range.first); + Uint32Pair range = impl.GetTextSelectionRange(); + value = static_cast(range.first); break; } case Toolkit::DevelTextField::Property::SELECTED_TEXT_END: { - Uint32Pair range = impl.GetTextSelectionRange( ); - value = static_cast(range.second); + Uint32Pair range = impl.GetTextSelectionRange(); + value = static_cast(range.second); break; } case Toolkit::DevelTextField::Property::ENABLE_EDITING: @@ -1114,7 +1112,7 @@ Property::Value TextField::GetProperty( BaseObject* object, Property::Index inde void TextField::SelectWholeText() { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { mController->SelectWholeText(); SetKeyInputFocus(); @@ -1123,7 +1121,7 @@ void TextField::SelectWholeText() void TextField::SelectNone() { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { mController->SelectNone(); } @@ -1132,18 +1130,18 @@ void TextField::SelectNone() string TextField::GetSelectedText() const { string selectedText = ""; - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { - selectedText = mController->GetSelectedText( ); + selectedText = mController->GetSelectedText(); } return selectedText; } -void TextField::SetTextSelectionRange(const uint32_t *start, const uint32_t *end) +void TextField::SetTextSelectionRange(const uint32_t* start, const uint32_t* end) { - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { - mController->SetTextSelectionRange( start, end ); + mController->SetTextSelectionRange(start, end); SetKeyInputFocus(); } } @@ -1151,37 +1149,36 @@ void TextField::SetTextSelectionRange(const uint32_t *start, const uint32_t *end Uint32Pair TextField::GetTextSelectionRange() const { Uint32Pair range; - if( mController && mController->IsShowingRealText() ) + if(mController && mController->IsShowingRealText()) { range = mController->GetTextSelectionRange(); } return range; } - InputMethodContext TextField::GetInputMethodContext() { return mInputMethodContext; } -bool TextField::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool TextField::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::TextField field = Toolkit::TextField::DownCast( handle ); + bool connected(true); + Toolkit::TextField field = Toolkit::TextField::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_TEXT_CHANGED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_TEXT_CHANGED)) { - field.TextChangedSignal().Connect( tracker, functor ); + field.TextChangedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_MAX_LENGTH_REACHED)) { - field.MaxLengthReachedSignal().Connect( tracker, functor ); + field.MaxLengthReachedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_INPUT_STYLE_CHANGED)) { - field.InputStyleChangedSignal().Connect( tracker, functor ); + field.InputStyleChangedSignal().Connect(tracker, functor); } else { @@ -1211,98 +1208,98 @@ void TextField::OnInitialize() { Actor self = Self(); - mController = Text::Controller::New( this, this ,this); + mController = Text::Controller::New(this, this, this); // When using the vector-based rendering, the size of the GLyphs are different TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH; - mController->SetGlyphType( glyphType ); + mController->SetGlyphType(glyphType); - mDecorator = Text::Decorator::New( *mController, - *mController ); + mDecorator = Text::Decorator::New(*mController, + *mController); - mInputMethodContext = InputMethodContext::New( self ); + mInputMethodContext = InputMethodContext::New(self); - mController->GetLayoutEngine().SetLayout( Layout::Engine::SINGLE_LINE_BOX ); + mController->GetLayoutEngine().SetLayout(Layout::Engine::SINGLE_LINE_BOX); // Enables the text input. - mController->EnableTextInput( mDecorator, mInputMethodContext ); + mController->EnableTextInput(mDecorator, mInputMethodContext); // Enables the horizontal scrolling after the text input has been enabled. - mController->SetHorizontalScrollEnabled( true ); + mController->SetHorizontalScrollEnabled(true); // Disables the vertical scrolling. - mController->SetVerticalScrollEnabled( false ); + mController->SetVerticalScrollEnabled(false); // Disable the smooth handle panning. - mController->SetSmoothHandlePanEnabled( false ); + mController->SetSmoothHandlePanEnabled(false); - mController->SetNoTextDoubleTapAction( Controller::NoTextTap::HIGHLIGHT ); - mController->SetNoTextLongPressAction( Controller::NoTextTap::HIGHLIGHT ); + mController->SetNoTextDoubleTapAction(Controller::NoTextTap::HIGHLIGHT); + mController->SetNoTextLongPressAction(Controller::NoTextTap::HIGHLIGHT); // Sets layoutDirection value - Dali::Stage stage = Dali::Stage::GetCurrent(); - Dali::LayoutDirection::Type layoutDirection = static_cast( stage.GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); - mController->SetLayoutDirection( layoutDirection ); + Dali::Stage stage = Dali::Stage::GetCurrent(); + Dali::LayoutDirection::Type layoutDirection = static_cast(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); + mController->SetLayoutDirection(layoutDirection); // Forward input events to controller - EnableGestureDetection( static_cast( GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS ) ); - GetTapGestureDetector().SetMaximumTapsRequired( 2 ); + EnableGestureDetection(static_cast(GestureType::TAP | GestureType::PAN | GestureType::LONG_PRESS)); + GetTapGestureDetector().SetMaximumTapsRequired(2); - self.TouchedSignal().Connect( this, &TextField::OnTouched ); + self.TouchedSignal().Connect(this, &TextField::OnTouched); // Set BoundingBox to stage size if not already set. Rect boundingBox; - mDecorator->GetBoundingBox( boundingBox ); + mDecorator->GetBoundingBox(boundingBox); - if( boundingBox.IsEmpty() ) + if(boundingBox.IsEmpty()) { Vector2 stageSize = Dali::Stage::GetCurrent().GetSize(); - mDecorator->SetBoundingBox( Rect( 0.0f, 0.0f, stageSize.width, stageSize.height ) ); + mDecorator->SetBoundingBox(Rect(0.0f, 0.0f, stageSize.width, stageSize.height)); } // Flip vertically the 'left' selection handle - mDecorator->FlipHandleVertically( LEFT_SELECTION_HANDLE, true ); + mDecorator->FlipHandleVertically(LEFT_SELECTION_HANDLE, true); // Fill-parent area by default - self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); - self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT ); - self.OnSceneSignal().Connect( this, &TextField::OnSceneConnect ); + self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH); + self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT); + self.OnSceneSignal().Connect(this, &TextField::OnSceneConnect); //Enable highightability - self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); - DevelControl::SetInputMethodContext( *this, mInputMethodContext ); + DevelControl::SetInputMethodContext(*this, mInputMethodContext); - if( Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == mExceedPolicy ) + if(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP == mExceedPolicy) { EnableClipping(); } - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::ENTRY ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::ENTRY)); + }); } -void TextField::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change ) +void TextField::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnStyleChange\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnStyleChange\n"); - switch ( change ) + switch(change) { case StyleChange::DEFAULT_FONT_CHANGE: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnStyleChange DEFAULT_FONT_CHANGE\n"); - const std::string& newFont = GetImpl( styleManager ).GetDefaultFontFamily(); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnStyleChange DEFAULT_FONT_CHANGE\n"); + const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily(); // Property system did not set the font so should update it. - mController->UpdateAfterFontChange( newFont ); + mController->UpdateAfterFontChange(newFont); RelayoutRequest(); break; } case StyleChange::DEFAULT_FONT_SIZE_CHANGE: { - GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) ); + GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner())); RelayoutRequest(); break; } @@ -1314,144 +1311,146 @@ void TextField::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange:: } // Up call to Control - Control::OnStyleChange( styleManager, change ); + Control::OnStyleChange(styleManager, change); } Vector3 TextField::GetNaturalSize() { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); Vector3 naturalSize = mController->GetNaturalSize(); - naturalSize.width += ( padding.start + padding.end ); - naturalSize.height += ( padding.top + padding.bottom ); + naturalSize.width += (padding.start + padding.end); + naturalSize.height += (padding.top + padding.bottom); return naturalSize; } -float TextField::GetHeightForWidth( float width ) +float TextField::GetHeightForWidth(float width) { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); - return mController->GetHeightForWidth( width ) + padding.top + padding.bottom; + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); + return mController->GetHeightForWidth(width) + padding.top + padding.bottom; } -void TextField::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void TextField::OnRelayout(const Vector2& size, RelayoutContainer& container) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField OnRelayout\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField OnRelayout\n"); Actor self = Self(); Extents padding; - padding = self.GetProperty( Toolkit::Control::Property::PADDING ); + padding = self.GetProperty(Toolkit::Control::Property::PADDING); - Vector2 contentSize( size.x - ( padding.start + padding.end ), size.y - ( padding.top + padding.bottom ) ); + Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom)); // Support Right-To-Left of padding Dali::LayoutDirection::Type layoutDirection; - if( mController->IsMatchSystemLanguageDirection() ) + if(mController->IsMatchSystemLanguageDirection()) { - layoutDirection = static_cast( DevelWindow::Get( self ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(DevelWindow::Get(self).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } else { - layoutDirection = static_cast( self.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(self.GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { - std::swap( padding.start, padding.end ); + std::swap(padding.start, padding.end); } - if( mStencil ) + if(mStencil) { - mStencil.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top )); + mStencil.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top)); } - if( mActiveLayer ) + if(mActiveLayer) { - mActiveLayer.SetProperty( Actor::Property::POSITION, Vector2( padding.start, padding.top )); + mActiveLayer.SetProperty(Actor::Property::POSITION, Vector2(padding.start, padding.top)); } - const Text::Controller::UpdateTextType updateTextType = mController->Relayout( contentSize, layoutDirection ); + const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection); - if( ( Text::Controller::NONE_UPDATED != updateTextType ) || - !mRenderer ) + if((Text::Controller::NONE_UPDATED != updateTextType) || + !mRenderer) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnRelayout %p Displaying new contents\n", mController.Get() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnRelayout %p Displaying new contents\n", mController.Get()); - if( mDecorator && - ( Text::Controller::NONE_UPDATED != ( Text::Controller::DECORATOR_UPDATED & updateTextType ) ) ) + if(mDecorator && + (Text::Controller::NONE_UPDATED != (Text::Controller::DECORATOR_UPDATED & updateTextType))) { - mDecorator->Relayout( size ); + mDecorator->Relayout(size); } - if( !mRenderer ) + if(!mRenderer) { - mRenderer = Backend::Get().NewRenderer( mRenderingBackend ); + mRenderer = Backend::Get().NewRenderer(mRenderingBackend); } - RenderText( updateTextType ); - + RenderText(updateTextType); } // The text-field emits signals when the input style changes. These changes of style are // detected during the relayout process (size negotiation), i.e after the cursor has been moved. Signals // can't be emitted during the size negotiation as the callbacks may update the UI. // The text-field adds an idle callback to the adaptor to emit the signals after the size negotiation. - if( !mController->IsInputStyleChangedSignalsQueueEmpty() ) + if(!mController->IsInputStyleChangedSignalsQueueEmpty()) { - if( Adaptor::IsAvailable() ) + if(Adaptor::IsAvailable()) { Adaptor& adaptor = Adaptor::Get(); - if( NULL == mIdleCallback ) + if(NULL == mIdleCallback) { // @note: The callback manager takes the ownership of the callback object. - mIdleCallback = MakeCallback( this, &TextField::OnIdleSignal ); - adaptor.AddIdle( mIdleCallback, false ); + mIdleCallback = MakeCallback(this, &TextField::OnIdleSignal); + adaptor.AddIdle(mIdleCallback, false); } } } } -Text::ControllerPtr TextField::getController() { return mController; } +Text::ControllerPtr TextField::getController() +{ + return mController; +} -void TextField::RenderText( Text::Controller::UpdateTextType updateTextType ) +void TextField::RenderText(Text::Controller::UpdateTextType updateTextType) { Actor renderableActor; - if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) ) + if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType)) { - if( mRenderer ) + if(mRenderer) { - Dali::Toolkit::TextField handle = Dali::Toolkit::TextField( GetOwner() ); + Dali::Toolkit::TextField handle = Dali::Toolkit::TextField(GetOwner()); - renderableActor = mRenderer->Render( mController->GetView(), - handle, - Property::INVALID_INDEX, // Animatable property not supported - mAlignmentOffset, - DepthIndex::CONTENT ); + renderableActor = mRenderer->Render(mController->GetView(), + handle, + Property::INVALID_INDEX, // Animatable property not supported + mAlignmentOffset, + DepthIndex::CONTENT); } - if( renderableActor != mRenderableActor ) + if(renderableActor != mRenderableActor) { - UnparentAndReset( mBackgroundActor ); - UnparentAndReset( mRenderableActor ); + UnparentAndReset(mBackgroundActor); + UnparentAndReset(mRenderableActor); mRenderableActor = renderableActor; - if ( mRenderableActor ) + if(mRenderableActor) { mBackgroundActor = mController->CreateBackgroundActor(); } } } - if( mRenderableActor ) + if(mRenderableActor) { const Vector2& scrollOffset = mController->GetTextModel()->GetScrollPosition(); float renderableActorPositionX, renderableActorPositionY; - if( mStencil ) + if(mStencil) { renderableActorPositionX = scrollOffset.x + mAlignmentOffset; renderableActorPositionY = scrollOffset.y; @@ -1459,55 +1458,55 @@ void TextField::RenderText( Text::Controller::UpdateTextType updateTextType ) else { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); // Support Right-To-Left of padding - Dali::LayoutDirection::Type layoutDirection = static_cast( Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + Dali::LayoutDirection::Type layoutDirection = static_cast(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { - std::swap( padding.start, padding.end ); + std::swap(padding.start, padding.end); } renderableActorPositionX = scrollOffset.x + mAlignmentOffset + padding.start; renderableActorPositionY = scrollOffset.y + padding.top; } - mRenderableActor.SetProperty( Actor::Property::POSITION, Vector2( renderableActorPositionX, renderableActorPositionY )); + mRenderableActor.SetProperty(Actor::Property::POSITION, Vector2(renderableActorPositionX, renderableActorPositionY)); // Make sure the actors are parented correctly with/without clipping Actor self = mStencil ? mStencil : Self(); Actor highlightActor; - for( std::vector::iterator it = mClippingDecorationActors.begin(), - endIt = mClippingDecorationActors.end(); - it != endIt; - ++it ) + for(std::vector::iterator it = mClippingDecorationActors.begin(), + endIt = mClippingDecorationActors.end(); + it != endIt; + ++it) { - self.Add( *it ); + self.Add(*it); it->LowerToBottom(); - if ( it->GetProperty< std::string >( Dali::Actor::Property::NAME ) == "HighlightActor" ) + if(it->GetProperty(Dali::Actor::Property::NAME) == "HighlightActor") { highlightActor = *it; } } mClippingDecorationActors.clear(); - self.Add( mRenderableActor ); + self.Add(mRenderableActor); - if ( mBackgroundActor ) + if(mBackgroundActor) { - if ( mDecorator && mDecorator->IsHighlightVisible() ) + if(mDecorator && mDecorator->IsHighlightVisible()) { - self.Add( mBackgroundActor ); - mBackgroundActor.SetProperty( Actor::Property::POSITION, Vector2( renderableActorPositionX, renderableActorPositionY) ); // In text field's coords. - mBackgroundActor.LowerBelow( highlightActor ); + self.Add(mBackgroundActor); + mBackgroundActor.SetProperty(Actor::Property::POSITION, Vector2(renderableActorPositionX, renderableActorPositionY)); // In text field's coords. + mBackgroundActor.LowerBelow(highlightActor); } else { - mRenderableActor.Add( mBackgroundActor ); - mBackgroundActor.SetProperty( Actor::Property::POSITION, Vector2( 0.0f, 0.0f ) ); // In renderable actor's coords. + mRenderableActor.Add(mBackgroundActor); + mBackgroundActor.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f)); // In renderable actor's coords. mBackgroundActor.LowerToBottom(); } } @@ -1516,59 +1515,59 @@ void TextField::RenderText( Text::Controller::UpdateTextType updateTextType ) void TextField::OnKeyInputFocusGained() { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnKeyInputFocusGained %p\n", mController.Get() ); - if ( mInputMethodContext && IsEditable() ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnKeyInputFocusGained %p\n", mController.Get()); + if(mInputMethodContext && IsEditable()) { // All input panel properties, such as layout, return key type, and input hint, should be set before input panel activates (or shows). - mInputMethodContext.ApplyOptions( mInputMethodOptions ); - mInputMethodContext.NotifyTextInputMultiLine( false ); + mInputMethodContext.ApplyOptions(mInputMethodOptions); + mInputMethodContext.NotifyTextInputMultiLine(false); - mInputMethodContext.StatusChangedSignal().Connect( this, &TextField::KeyboardStatusChanged ); + mInputMethodContext.StatusChangedSignal().Connect(this, &TextField::KeyboardStatusChanged); - mInputMethodContext.EventReceivedSignal().Connect( this, &TextField::OnInputMethodContextEvent ); + mInputMethodContext.EventReceivedSignal().Connect(this, &TextField::OnInputMethodContextEvent); // Notify that the text editing start. mInputMethodContext.Activate(); // When window gain lost focus, the inputMethodContext is deactivated. Thus when window gain focus again, the inputMethodContext must be activated. - mInputMethodContext.SetRestoreAfterFocusLost( true ); + mInputMethodContext.SetRestoreAfterFocusLost(true); } - ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() ); + ClipboardEventNotifier notifier(ClipboardEventNotifier::Get()); - if ( notifier ) + if(notifier) { - notifier.ContentSelectedSignal().Connect( this, &TextField::OnClipboardTextSelected ); + notifier.ContentSelectedSignal().Connect(this, &TextField::OnClipboardTextSelected); } mController->KeyboardFocusGainEvent(); // Called in the case of no virtual keyboard to trigger this event - EmitKeyInputFocusSignal( true ); // Calls back into the Control hence done last. + EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last. } void TextField::OnKeyInputFocusLost() { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField:OnKeyInputFocusLost %p\n", mController.Get() ); - if ( mInputMethodContext ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField:OnKeyInputFocusLost %p\n", mController.Get()); + if(mInputMethodContext) { - mInputMethodContext.StatusChangedSignal().Disconnect( this, &TextField::KeyboardStatusChanged ); + mInputMethodContext.StatusChangedSignal().Disconnect(this, &TextField::KeyboardStatusChanged); // The text editing is finished. Therefore the inputMethodContext don't have restore activation. - mInputMethodContext.SetRestoreAfterFocusLost( false ); + mInputMethodContext.SetRestoreAfterFocusLost(false); // Notify that the text editing finish. mInputMethodContext.Deactivate(); - mInputMethodContext.EventReceivedSignal().Disconnect( this, &TextField::OnInputMethodContextEvent ); + mInputMethodContext.EventReceivedSignal().Disconnect(this, &TextField::OnInputMethodContextEvent); } - ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() ); + ClipboardEventNotifier notifier(ClipboardEventNotifier::Get()); - if ( notifier ) + if(notifier) { - notifier.ContentSelectedSignal().Disconnect( this, &TextField::OnClipboardTextSelected ); + notifier.ContentSelectedSignal().Disconnect(this, &TextField::OnClipboardTextSelected); } mController->KeyboardFocusLostEvent(); - EmitKeyInputFocusSignal( false ); // Calls back into the Control hence done last. + EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last. } bool TextField::OnAccessibilityActivated() @@ -1577,62 +1576,62 @@ bool TextField::OnAccessibilityActivated() return true; } -void TextField::OnTap( const TapGesture& gesture ) +void TextField::OnTap(const TapGesture& gesture) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnTap %p\n", mController.Get() ); - if ( mInputMethodContext && IsEditable() ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnTap %p\n", mController.Get()); + if(mInputMethodContext && IsEditable()) { mInputMethodContext.Activate(); } // Deliver the tap before the focus event to controller; this allows us to detect when focus is gained due to tap-gestures Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); const Vector2& localPoint = gesture.GetLocalPoint(); - mController->TapEvent( gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top ); + mController->TapEvent(gesture.GetNumberOfTaps(), localPoint.x - padding.start, localPoint.y - padding.top); SetKeyInputFocus(); } -void TextField::OnPan( const PanGesture& gesture ) +void TextField::OnPan(const PanGesture& gesture) { - mController->PanEvent( gesture.GetState(), gesture.GetDisplacement() ); + mController->PanEvent(gesture.GetState(), gesture.GetDisplacement()); } -void TextField::OnLongPress( const LongPressGesture& gesture ) +void TextField::OnLongPress(const LongPressGesture& gesture) { - if ( mInputMethodContext && IsEditable() ) + if(mInputMethodContext && IsEditable()) { mInputMethodContext.Activate(); } Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); const Vector2& localPoint = gesture.GetLocalPoint(); - mController->LongPressEvent( gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top ); + mController->LongPressEvent(gesture.GetState(), localPoint.x - padding.start, localPoint.y - padding.top); SetKeyInputFocus(); } -bool TextField::OnKeyEvent( const KeyEvent& event ) +bool TextField::OnKeyEvent(const KeyEvent& event) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnKeyEvent %p keyCode %d\n", mController.Get(), event.GetKeyCode()); - if( Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape() ) + if(Dali::DALI_KEY_ESCAPE == event.GetKeyCode() && mController->ShouldClearFocusOnEscape()) { // Make sure ClearKeyInputFocus when only key is up - if( event.GetState() == KeyEvent::UP ) + if(event.GetState() == KeyEvent::UP) { ClearKeyInputFocus(); } return true; } - else if( Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode() ) + else if(Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode()) { // Do nothing when enter is comming. return false; } - return mController->KeyEvent( event ); + return mController->KeyEvent(event); } void TextField::RequestTextRelayout() @@ -1645,124 +1644,124 @@ bool TextField::IsEditable() const return mController->IsEditable(); } -void TextField::SetEditable( bool editable ) +void TextField::SetEditable(bool editable) { mController->SetEditable(editable); - if ( mInputMethodContext && !editable ) + if(mInputMethodContext && !editable) { mInputMethodContext.Deactivate(); } } -void TextField::TextInserted( unsigned int position, unsigned int length, const std::string &content ) +void TextField::TextInserted(unsigned int position, unsigned int length, const std::string& content) { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - Control::Impl::GetAccessibilityObject( Self() )->EmitTextInserted( position, length, content ); + Control::Impl::GetAccessibilityObject(Self())->EmitTextInserted(position, length, content); } } -void TextField::TextDeleted( unsigned int position, unsigned int length, const std::string &content ) +void TextField::TextDeleted(unsigned int position, unsigned int length, const std::string& content) { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - Control::Impl::GetAccessibilityObject( Self() )->EmitTextDeleted( position, length, content ); + Control::Impl::GetAccessibilityObject(Self())->EmitTextDeleted(position, length, content); } } -void TextField::CaretMoved( unsigned int position ) +void TextField::CaretMoved(unsigned int position) { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - Control::Impl::GetAccessibilityObject( Self() )->EmitTextCaretMoved( position ); + Control::Impl::GetAccessibilityObject(Self())->EmitTextCaretMoved(position); } } void TextField::TextChanged() { - Dali::Toolkit::TextField handle( GetOwner() ); - mTextChangedSignal.Emit( handle ); + Dali::Toolkit::TextField handle(GetOwner()); + mTextChangedSignal.Emit(handle); } void TextField::MaxLengthReached() { - Dali::Toolkit::TextField handle( GetOwner() ); - mMaxLengthReachedSignal.Emit( handle ); + Dali::Toolkit::TextField handle(GetOwner()); + mMaxLengthReachedSignal.Emit(handle); } -void TextField::InputStyleChanged( Text::InputStyle::Mask inputStyleMask ) +void TextField::InputStyleChanged(Text::InputStyle::Mask inputStyleMask) { - Dali::Toolkit::TextField handle( GetOwner() ); + Dali::Toolkit::TextField handle(GetOwner()); Toolkit::TextField::InputStyle::Mask fieldInputStyleMask = Toolkit::TextField::InputStyle::NONE; - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_COLOR ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_COLOR)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::COLOR ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::COLOR); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_FAMILY ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_FAMILY)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_FAMILY ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_FAMILY); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_POINT_SIZE ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_POINT_SIZE)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::POINT_SIZE ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::POINT_SIZE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_WEIGHT ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_WEIGHT)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_WIDTH ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_WIDTH)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_FONT_SLANT ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_FONT_SLANT)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::FONT_STYLE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_UNDERLINE ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_UNDERLINE)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::UNDERLINE ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::UNDERLINE); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_SHADOW ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_SHADOW)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::SHADOW ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::SHADOW); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_EMBOSS ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_EMBOSS)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::EMBOSS ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::EMBOSS); } - if( InputStyle::NONE != static_cast( inputStyleMask & InputStyle::INPUT_OUTLINE ) ) + if(InputStyle::NONE != static_cast(inputStyleMask & InputStyle::INPUT_OUTLINE)) { - fieldInputStyleMask = static_cast( fieldInputStyleMask | Toolkit::TextField::InputStyle::OUTLINE ); + fieldInputStyleMask = static_cast(fieldInputStyleMask | Toolkit::TextField::InputStyle::OUTLINE); } - mInputStyleChangedSignal.Emit( handle, fieldInputStyleMask ); + mInputStyleChangedSignal.Emit(handle, fieldInputStyleMask); } -void TextField::AddDecoration( Actor& actor, bool needsClipping ) +void TextField::AddDecoration(Actor& actor, bool needsClipping) { - if( actor ) + if(actor) { - if( needsClipping ) + if(needsClipping) { - mClippingDecorationActors.push_back( actor ); + mClippingDecorationActors.push_back(actor); } else { - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - Self().Add( actor ); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + Self().Add(actor); mActiveLayer = actor; } } } -void TextField::OnSceneConnect( Dali::Actor actor ) +void TextField::OnSceneConnect(Dali::Actor actor) { - if ( mHasBeenStaged ) + if(mHasBeenStaged) { - RenderText( static_cast( Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED ) ); + RenderText(static_cast(Text::Controller::MODEL_UPDATED | Text::Controller::DECORATOR_UPDATED)); } else { @@ -1770,55 +1769,54 @@ void TextField::OnSceneConnect( Dali::Actor actor ) } } -InputMethodContext::CallbackData TextField::OnInputMethodContextEvent( Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent ) +InputMethodContext::CallbackData TextField::OnInputMethodContextEvent(Dali::InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName ); - return mController->OnInputMethodContextEvent( inputMethodContext, inputMethodContextEvent ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::OnInputMethodContextEvent %p eventName %d\n", mController.Get(), inputMethodContextEvent.eventName); + return mController->OnInputMethodContextEvent(inputMethodContext, inputMethodContextEvent); } -void TextField::GetHandleImagePropertyValue( Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType ) +void TextField::GetHandleImagePropertyValue(Property::Value& value, Text::HandleType handleType, Text::HandleImageType handleImageType) { - if( mDecorator ) + if(mDecorator) { Property::Map map; - map[ IMAGE_MAP_FILENAME_STRING ] = mDecorator->GetHandleImage( handleType, handleImageType ); - value = map; + map[IMAGE_MAP_FILENAME_STRING] = mDecorator->GetHandleImage(handleType, handleImageType); + value = map; } } void TextField::EnableClipping() { - if( !mStencil ) + if(!mStencil) { // Creates an extra control to be used as stencil buffer. mStencil = Control::New(); - mStencil.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - mStencil.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); + mStencil.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mStencil.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); // Creates a background visual. Even if the color is transparent it updates the stencil. - mStencil.SetProperty( Toolkit::Control::Property::BACKGROUND, - Property::Map().Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR ). - Add( ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT ) ); + mStencil.SetProperty(Toolkit::Control::Property::BACKGROUND, + Property::Map().Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR).Add(ColorVisual::Property::MIX_COLOR, Color::TRANSPARENT)); // Enable the clipping property. - mStencil.SetProperty( Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX ); - mStencil.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mStencil.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX); + mStencil.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); - Self().Add( mStencil ); + Self().Add(mStencil); } } -void TextField::OnClipboardTextSelected( ClipboardEventNotifier& clipboard ) +void TextField::OnClipboardTextSelected(ClipboardEventNotifier& clipboard) { mController->PasteClipboardItemEvent(); } void TextField::KeyboardStatusChanged(bool keyboardShown) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextField::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextField::KeyboardStatusChanged %p keyboardShown %d\n", mController.Get(), keyboardShown); // Just hide the grab handle when keyboard is hidden. - if (!keyboardShown ) + if(!keyboardShown) { mController->KeyboardFocusLostEvent(); } @@ -1828,18 +1826,18 @@ void TextField::KeyboardStatusChanged(bool keyboardShown) } } -void TextField::OnSceneConnection( int depth ) +void TextField::OnSceneConnection(int depth) { // Sets the depth to the visuals inside the text's decorator. - mDecorator->SetTextDepth( depth ); + mDecorator->SetTextDepth(depth); // The depth of the text renderer is set in the RenderText() called from OnRelayout(). // Call the Control::OnSceneConnection() to set the depth of the background. - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); } -bool TextField::OnTouched( Actor actor, const TouchEvent& touch ) +bool TextField::OnTouched(Actor actor, const TouchEvent& touch) { return false; } @@ -1854,80 +1852,80 @@ void TextField::OnIdleSignal() } TextField::TextField() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mIdleCallback( NULL ), - mAlignmentOffset( 0.f ), - mRenderingBackend( DEFAULT_RENDERING_BACKEND ), - mExceedPolicy( Dali::Toolkit::TextField::EXCEED_POLICY_CLIP ), - mHasBeenStaged( false ) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mIdleCallback(NULL), + mAlignmentOffset(0.f), + mRenderingBackend(DEFAULT_RENDERING_BACKEND), + mExceedPolicy(Dali::Toolkit::TextField::EXCEED_POLICY_CLIP), + mHasBeenStaged(false) { } TextField::~TextField() { - UnparentAndReset( mStencil ); + UnparentAndReset(mStencil); - if( ( NULL != mIdleCallback ) && Adaptor::IsAvailable() ) + if((NULL != mIdleCallback) && Adaptor::IsAvailable()) { - Adaptor::Get().RemoveIdle( mIdleCallback ); + Adaptor::Get().RemoveIdle(mIdleCallback); } } std::string TextField::AccessibleImpl::GetName() { - auto slf = Toolkit::TextField::DownCast( self ); - return slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >(); + auto slf = Toolkit::TextField::DownCast(self); + return slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); } -std::string TextField::AccessibleImpl::GetText( size_t startOffset, - size_t endOffset ) +std::string TextField::AccessibleImpl::GetText(size_t startOffset, + size_t endOffset) { - if( endOffset <= startOffset ) + if(endOffset <= startOffset) return {}; - auto slf = Toolkit::TextField::DownCast( self ); + auto slf = Toolkit::TextField::DownCast(self); auto txt = - slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >(); + slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); - if( startOffset > txt.size() || endOffset > txt.size() ) + if(startOffset > txt.size() || endOffset > txt.size()) return {}; - return txt.substr( startOffset, endOffset - startOffset ); + return txt.substr(startOffset, endOffset - startOffset); } size_t TextField::AccessibleImpl::GetCharacterCount() { - auto slf = Toolkit::TextField::DownCast( self ); + auto slf = Toolkit::TextField::DownCast(self); auto txt = - slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >(); + slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); return txt.size(); } size_t TextField::AccessibleImpl::GetCaretOffset() { - auto slf = Toolkit::TextField::DownCast( self ); - return Dali::Toolkit::GetImpl( slf ).getController()->GetCursorPosition(); + auto slf = Toolkit::TextField::DownCast(self); + return Dali::Toolkit::GetImpl(slf).getController()->GetCursorPosition(); } bool TextField::AccessibleImpl::SetCaretOffset(size_t offset) { - auto slf = Toolkit::TextField::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >(); - if (offset > txt.size()) + auto slf = Toolkit::TextField::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); + if(offset > txt.size()) return false; - auto& slfImpl = Dali::Toolkit::GetImpl( slf ); - slfImpl.getController()->ResetCursorPosition( offset ); + auto& slfImpl = Dali::Toolkit::GetImpl(slf); + slfImpl.getController()->ResetCursorPosition(offset); slfImpl.RequestTextRelayout(); return true; } Dali::Accessibility::Range TextField::AccessibleImpl::GetTextAtOffset( - size_t offset, Dali::Accessibility::TextBoundary boundary ) + size_t offset, Dali::Accessibility::TextBoundary boundary) { - auto slf = Toolkit::TextField::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get< std::string >(); + auto slf = Toolkit::TextField::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); auto txt_size = txt.size(); auto range = Dali::Accessibility::Range{}; @@ -1935,63 +1933,63 @@ Dali::Accessibility::Range TextField::AccessibleImpl::GetTextAtOffset( switch(boundary) { case Dali::Accessibility::TextBoundary::CHARACTER: + { + if(offset < txt_size) { - if (offset < txt_size) - { - range.content = txt[offset]; - range.startOffset = offset; - range.endOffset = offset + 1; - } + range.content = txt[offset]; + range.startOffset = offset; + range.endOffset = offset + 1; } - break; + } + break; case Dali::Accessibility::TextBoundary::WORD: case Dali::Accessibility::TextBoundary::LINE: + { + auto txt_c_string = txt.c_str(); + auto breaks = std::vector(txt_size, 0); + if(boundary == Dali::Accessibility::TextBoundary::WORD) + Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data()); + else + Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data()); + auto index = 0u; + auto counter = 0u; + while(index < txt_size && counter <= offset) { - auto txt_c_string = txt.c_str(); - auto breaks = std::vector< char >( txt_size, 0 ); - if(boundary == Dali::Accessibility::TextBoundary::WORD) - Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data()); + auto start = index; + if(breaks[index]) + { + while(breaks[index]) + index++; + counter++; + } else - Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data()); - auto index = 0u; - auto counter = 0u; - while( index < txt_size && counter <= offset ) { - auto start = index; - if(breaks[index]) - { - while(breaks[index]) - index++; + if(boundary == Dali::Accessibility::TextBoundary::WORD) + index++; + if(boundary == Dali::Accessibility::TextBoundary::LINE) counter++; - } - else - { - if (boundary == Dali::Accessibility::TextBoundary::WORD) - index++; - if (boundary == Dali::Accessibility::TextBoundary::LINE) - counter++; - } - if ((counter > 0) && ((counter - 1) == offset)) - { - range.content = txt.substr(start, index - start + 1); - range.startOffset = start; - range.endOffset = index + 1; - } - if (boundary == Dali::Accessibility::TextBoundary::LINE) - index++; } + if((counter > 0) && ((counter - 1) == offset)) + { + range.content = txt.substr(start, index - start + 1); + range.startOffset = start; + range.endOffset = index + 1; + } + if(boundary == Dali::Accessibility::TextBoundary::LINE) + index++; } - break; + } + break; case Dali::Accessibility::TextBoundary::SENTENCE: - { - /* not supported by efl */ - } - break; + { + /* not supported by efl */ + } + break; case Dali::Accessibility::TextBoundary::PARAGRAPH: - { - /* Paragraph is not supported by libunibreak library */ - } - break; + { + /* Paragraph is not supported by libunibreak library */ + } + break; default: break; } @@ -2000,71 +1998,71 @@ Dali::Accessibility::Range TextField::AccessibleImpl::GetTextAtOffset( } Dali::Accessibility::Range -TextField::AccessibleImpl::GetSelection( size_t selectionNum ) +TextField::AccessibleImpl::GetSelection(size_t selectionNum) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return {}; - auto slf = Toolkit::TextField::DownCast( self ); - auto ctrl = Dali::Toolkit::GetImpl( slf ).getController(); + auto slf = Toolkit::TextField::DownCast(self); + auto ctrl = Dali::Toolkit::GetImpl(slf).getController(); std::string ret; - ctrl->RetrieveSelection( ret ); + ctrl->RetrieveSelection(ret); auto r = ctrl->GetSelectionIndexes(); - return { static_cast(r.first), static_cast(r.second), ret }; + return {static_cast(r.first), static_cast(r.second), ret}; } -bool TextField::AccessibleImpl::RemoveSelection( size_t selectionNum ) +bool TextField::AccessibleImpl::RemoveSelection(size_t selectionNum) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return false; - auto slf = Toolkit::TextField::DownCast( self ); - Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( 0, 0 ); + auto slf = Toolkit::TextField::DownCast(self); + Dali::Toolkit::GetImpl(slf).getController()->SetSelection(0, 0); return true; } -bool TextField::AccessibleImpl::SetSelection( size_t selectionNum, - size_t startOffset, - size_t endOffset ) +bool TextField::AccessibleImpl::SetSelection(size_t selectionNum, + size_t startOffset, + size_t endOffset) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return false; - auto slf = Toolkit::TextField::DownCast( self ); - Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( startOffset, - endOffset ); + auto slf = Toolkit::TextField::DownCast(self); + Dali::Toolkit::GetImpl(slf).getController()->SetSelection(startOffset, + endOffset); return true; } -bool TextField::AccessibleImpl::CopyText( size_t startPosition, - size_t endPosition ) +bool TextField::AccessibleImpl::CopyText(size_t startPosition, + size_t endPosition) { - if( endPosition <= startPosition ) + if(endPosition <= startPosition) return false; - auto slf = Toolkit::TextField::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get(); - Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) ); + auto slf = Toolkit::TextField::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); + Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition)); return true; } -bool TextField::AccessibleImpl::CutText( size_t startPosition, - size_t endPosition ) +bool TextField::AccessibleImpl::CutText(size_t startPosition, + size_t endPosition) { - if( endPosition <= startPosition ) + if(endPosition <= startPosition) return false; - auto slf = Toolkit::TextField::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextField::Property::TEXT ).Get(); - Dali::Toolkit::GetImpl( slf ).getController()->CopyStringToClipboard( txt.substr(startPosition, endPosition - startPosition) ); + auto slf = Toolkit::TextField::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextField::Property::TEXT).Get(); + Dali::Toolkit::GetImpl(slf).getController()->CopyStringToClipboard(txt.substr(startPosition, endPosition - startPosition)); - slf.SetProperty( Toolkit::TextField::Property::TEXT, - txt.substr( 0, startPosition ) + txt.substr( endPosition - startPosition, txt.size())); + slf.SetProperty(Toolkit::TextField::Property::TEXT, + txt.substr(0, startPosition) + txt.substr(endPosition - startPosition, txt.size())); return true; } @@ -2075,11 +2073,11 @@ Dali::Accessibility::States TextField::AccessibleImpl::CalculateStates() auto states = Control::Impl::AccessibleImpl::CalculateStates(); - states[State::EDITABLE] = true; + states[State::EDITABLE] = true; states[State::FOCUSABLE] = true; Toolkit::Control focusControl = Toolkit::KeyInputFocusManager::Get().GetCurrentFocusControl(); - if (self == focusControl) + if(self == focusControl) { states[State::FOCUSED] = true; } diff --git a/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp old mode 100755 new mode 100644 index 1c03203..3ee507d --- a/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-label-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,33 +19,33 @@ #include // EXTERNAL INCLUDES -#include -#include -#include -#include #include #include +#include +#include #include +#include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include #include #include +#include #include #include #include -#include -#include +#include -#include -#include #include #include +#include +#include +#include #include #include -#include #include @@ -53,13 +53,10 @@ using namespace Dali::Toolkit::Text; namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT_RENDERING_BACKEND; @@ -70,29 +67,29 @@ const unsigned int DEFAULT_RENDERING_BACKEND = Dali::Toolkit::DevelText::DEFAULT * 0.0f aligns the text to the top, 0.5f aligns the text to the center, 1.0f aligns the text to the bottom. * The alignment depends on the alignment value of the text label (Use Text::VerticalAlignment enumerations). */ -const float VERTICAL_ALIGNMENT_TABLE[ Text::VerticalAlignment::BOTTOM + 1 ] = -{ - 0.0f, // VerticalAlignment::TOP - 0.5f, // VerticalAlignment::CENTER - 1.0f // VerticalAlignment::BOTTOM +const float VERTICAL_ALIGNMENT_TABLE[Text::VerticalAlignment::BOTTOM + 1] = + { + 0.0f, // VerticalAlignment::TOP + 0.5f, // VerticalAlignment::CENTER + 1.0f // VerticalAlignment::BOTTOM }; -const std::string TEXT_FIT_ENABLE_KEY( "enable" ); -const std::string TEXT_FIT_MIN_SIZE_KEY( "minSize" ); -const std::string TEXT_FIT_MAX_SIZE_KEY( "maxSize" ); -const std::string TEXT_FIT_STEP_SIZE_KEY( "stepSize" ); -const std::string TEXT_FIT_FONT_SIZE_TYPE_KEY( "fontSizeType" ); +const std::string TEXT_FIT_ENABLE_KEY("enable"); +const std::string TEXT_FIT_MIN_SIZE_KEY("minSize"); +const std::string TEXT_FIT_MAX_SIZE_KEY("maxSize"); +const std::string TEXT_FIT_STEP_SIZE_KEY("stepSize"); +const std::string TEXT_FIT_FONT_SIZE_TYPE_KEY("fontSizeType"); -#if defined ( DEBUG_ENABLED ) +#if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif const Scripting::StringEnum AUTO_SCROLL_STOP_MODE_TABLE[] = -{ - { "IMMEDIATE", Toolkit::TextLabel::AutoScrollStopMode::IMMEDIATE }, - { "FINISH_LOOP", Toolkit::TextLabel::AutoScrollStopMode::FINISH_LOOP }, + { + {"IMMEDIATE", Toolkit::TextLabel::AutoScrollStopMode::IMMEDIATE}, + {"FINISH_LOOP", Toolkit::TextLabel::AutoScrollStopMode::FINISH_LOOP}, }; -const unsigned int AUTO_SCROLL_STOP_MODE_TABLE_COUNT = sizeof( AUTO_SCROLL_STOP_MODE_TABLE ) / sizeof( AUTO_SCROLL_STOP_MODE_TABLE[0] ); +const unsigned int AUTO_SCROLL_STOP_MODE_TABLE_COUNT = sizeof(AUTO_SCROLL_STOP_MODE_TABLE) / sizeof(AUTO_SCROLL_STOP_MODE_TABLE[0]); // Type registration BaseHandle Create() @@ -100,111 +97,114 @@ BaseHandle Create() return Toolkit::TextLabel::New(); } +// clang-format off // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextLabel, Toolkit::Control, Create ); - -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "text", STRING, TEXT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "fontFamily", STRING, FONT_FAMILY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "fontStyle", MAP, FONT_STYLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "pointSize", FLOAT, POINT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "multiLine", BOOLEAN, MULTI_LINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "verticalAlignment", STRING, VERTICAL_ALIGNMENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "enableMarkup", BOOLEAN, ENABLE_MARKUP ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "enableAutoScroll", BOOLEAN, ENABLE_AUTO_SCROLL ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollSpeed", INTEGER, AUTO_SCROLL_SPEED ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollLoopCount", INTEGER, AUTO_SCROLL_LOOP_COUNT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollGap", FLOAT, AUTO_SCROLL_GAP ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "lineSpacing", FLOAT, LINE_SPACING ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "underline", MAP, UNDERLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "shadow", MAP, SHADOW ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "emboss", MAP, EMBOSS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "outline", MAP, OUTLINE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "pixelSize", FLOAT, PIXEL_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "ellipsis", BOOLEAN, ELLIPSIS ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollLoopDelay", FLOAT, AUTO_SCROLL_LOOP_DELAY ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "autoScrollStopMode", STRING, AUTO_SCROLL_STOP_MODE ) -DALI_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextLabel, "lineCount", INTEGER, LINE_COUNT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextLabel, "lineWrapMode", INTEGER, LINE_WRAP_MODE ) -DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY( Toolkit, TextLabel, "textDirection", INTEGER, TEXT_DIRECTION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "verticalLineAlignment", INTEGER, VERTICAL_LINE_ALIGNMENT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "textBackground", MAP, BACKGROUND ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "ignoreSpacesAfterText", BOOLEAN, IGNORE_SPACES_AFTER_TEXT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "textFit", MAP, TEXT_FIT ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "minLineSize", FLOAT, MIN_LINE_SIZE ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "renderingBackend", INTEGER, RENDERING_BACKEND ) -DALI_DEVEL_PROPERTY_REGISTRATION( Toolkit, TextLabel, "fontSizeScale", FLOAT, FONT_SIZE_SCALE ) -DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT( Toolkit, TextLabel, "textColor", Color::BLACK, TEXT_COLOR ) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorRed", TEXT_COLOR_RED, TEXT_COLOR, 0 ) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorGreen", TEXT_COLOR_GREEN, TEXT_COLOR, 1 ) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorBlue", TEXT_COLOR_BLUE, TEXT_COLOR, 2 ) -DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION( Toolkit, TextLabel, "textColorAlpha", TEXT_COLOR_ALPHA, TEXT_COLOR, 3 ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextLabel, Toolkit::Control, Create); + +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "text", STRING, TEXT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "fontFamily", STRING, FONT_FAMILY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "fontStyle", MAP, FONT_STYLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "pointSize", FLOAT, POINT_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "multiLine", BOOLEAN, MULTI_LINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "horizontalAlignment", STRING, HORIZONTAL_ALIGNMENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "verticalAlignment", STRING, VERTICAL_ALIGNMENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "enableMarkup", BOOLEAN, ENABLE_MARKUP ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "enableAutoScroll", BOOLEAN, ENABLE_AUTO_SCROLL ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollSpeed", INTEGER, AUTO_SCROLL_SPEED ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollLoopCount", INTEGER, AUTO_SCROLL_LOOP_COUNT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollGap", FLOAT, AUTO_SCROLL_GAP ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "lineSpacing", FLOAT, LINE_SPACING ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "underline", MAP, UNDERLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "shadow", MAP, SHADOW ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "emboss", MAP, EMBOSS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "outline", MAP, OUTLINE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "pixelSize", FLOAT, PIXEL_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "ellipsis", BOOLEAN, ELLIPSIS ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollLoopDelay", FLOAT, AUTO_SCROLL_LOOP_DELAY ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "autoScrollStopMode", STRING, AUTO_SCROLL_STOP_MODE ) +DALI_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextLabel, "lineCount", INTEGER, LINE_COUNT ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextLabel, "lineWrapMode", INTEGER, LINE_WRAP_MODE ) +DALI_DEVEL_PROPERTY_REGISTRATION_READ_ONLY(Toolkit, TextLabel, "textDirection", INTEGER, TEXT_DIRECTION ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "verticalLineAlignment", INTEGER, VERTICAL_LINE_ALIGNMENT ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "textBackground", MAP, BACKGROUND ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "ignoreSpacesAfterText", BOOLEAN, IGNORE_SPACES_AFTER_TEXT ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "matchSystemLanguageDirection", BOOLEAN, MATCH_SYSTEM_LANGUAGE_DIRECTION) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "textFit", MAP, TEXT_FIT ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "minLineSize", FLOAT, MIN_LINE_SIZE ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "renderingBackend", INTEGER, RENDERING_BACKEND ) +DALI_DEVEL_PROPERTY_REGISTRATION(Toolkit, TextLabel, "fontSizeScale", FLOAT, FONT_SIZE_SCALE ) + +DALI_ANIMATABLE_PROPERTY_REGISTRATION_WITH_DEFAULT(Toolkit, TextLabel, "textColor", Color::BLACK, TEXT_COLOR ) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorRed", TEXT_COLOR_RED, TEXT_COLOR, 0) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorGreen", TEXT_COLOR_GREEN, TEXT_COLOR, 1) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorBlue", TEXT_COLOR_BLUE, TEXT_COLOR, 2) +DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, TextLabel, "textColorAlpha", TEXT_COLOR_ALPHA, TEXT_COLOR, 3) DALI_TYPE_REGISTRATION_END() +// clang-format on /// Parses the property map for the TEXT_FIT property void ParseTextFitProperty(Text::ControllerPtr& controller, const Property::Map* propertiesMap) { - if ( propertiesMap && !propertiesMap->Empty() ) + if(propertiesMap && !propertiesMap->Empty()) { - bool enabled = false; - float minSize = 0.f; - float maxSize = 0.f; - float stepSize = 0.f; - bool isMinSizeSet = false, isMaxSizeSet = false, isStepSizeSet = false; + bool enabled = false; + float minSize = 0.f; + float maxSize = 0.f; + float stepSize = 0.f; + bool isMinSizeSet = false, isMaxSizeSet = false, isStepSizeSet = false; Controller::FontSizeType type = Controller::FontSizeType::POINT_SIZE; const unsigned int numberOfItems = propertiesMap->Count(); // Parses and applies - for( unsigned int index = 0u; index < numberOfItems; ++index ) + for(unsigned int index = 0u; index < numberOfItems; ++index) { - const KeyValuePair& valueGet = propertiesMap->GetKeyValue( index ); + const KeyValuePair& valueGet = propertiesMap->GetKeyValue(index); - if( ( Controller::TextFitInfo::Property::TEXT_FIT_ENABLE == valueGet.first.indexKey ) || ( TEXT_FIT_ENABLE_KEY == valueGet.first.stringKey ) ) + if((Controller::TextFitInfo::Property::TEXT_FIT_ENABLE == valueGet.first.indexKey) || (TEXT_FIT_ENABLE_KEY == valueGet.first.stringKey)) { /// Enable key. - enabled = valueGet.second.Get< bool >(); + enabled = valueGet.second.Get(); } - else if( ( Controller::TextFitInfo::Property::TEXT_FIT_MIN_SIZE == valueGet.first.indexKey ) || ( TEXT_FIT_MIN_SIZE_KEY == valueGet.first.stringKey ) ) + else if((Controller::TextFitInfo::Property::TEXT_FIT_MIN_SIZE == valueGet.first.indexKey) || (TEXT_FIT_MIN_SIZE_KEY == valueGet.first.stringKey)) { /// min size. - minSize = valueGet.second.Get< float >(); + minSize = valueGet.second.Get(); isMinSizeSet = true; } - else if( ( Controller::TextFitInfo::Property::TEXT_FIT_MAX_SIZE == valueGet.first.indexKey ) || ( TEXT_FIT_MAX_SIZE_KEY == valueGet.first.stringKey ) ) + else if((Controller::TextFitInfo::Property::TEXT_FIT_MAX_SIZE == valueGet.first.indexKey) || (TEXT_FIT_MAX_SIZE_KEY == valueGet.first.stringKey)) { /// max size. - maxSize = valueGet.second.Get< float >(); + maxSize = valueGet.second.Get(); isMaxSizeSet = true; } - else if( ( Controller::TextFitInfo::Property::TEXT_FIT_STEP_SIZE == valueGet.first.indexKey ) || ( TEXT_FIT_STEP_SIZE_KEY == valueGet.first.stringKey ) ) + else if((Controller::TextFitInfo::Property::TEXT_FIT_STEP_SIZE == valueGet.first.indexKey) || (TEXT_FIT_STEP_SIZE_KEY == valueGet.first.stringKey)) { /// step size. - stepSize = valueGet.second.Get< float >(); + stepSize = valueGet.second.Get(); isStepSizeSet = true; } - else if( ( Controller::TextFitInfo::Property::TEXT_FIT_FONT_SIZE_TYPE == valueGet.first.indexKey ) || ( TEXT_FIT_FONT_SIZE_TYPE_KEY == valueGet.first.stringKey ) ) + else if((Controller::TextFitInfo::Property::TEXT_FIT_FONT_SIZE_TYPE == valueGet.first.indexKey) || (TEXT_FIT_FONT_SIZE_TYPE_KEY == valueGet.first.stringKey)) { - if( "pixelSize" == valueGet.second.Get< std::string >() ) + if("pixelSize" == valueGet.second.Get()) { type = Controller::FontSizeType::PIXEL_SIZE; } } } - controller->SetTextFitEnabled( enabled ); - if( isMinSizeSet ) + controller->SetTextFitEnabled(enabled); + if(isMinSizeSet) { - controller->SetTextFitMinSize( minSize, type ); + controller->SetTextFitMinSize(minSize, type); } - if( isMaxSizeSet ) + if(isMaxSizeSet) { - controller->SetTextFitMaxSize( maxSize, type ); + controller->SetTextFitMaxSize(maxSize, type); } - if( isStepSizeSet ) + if(isStepSizeSet) { - controller->SetTextFitStepSize( stepSize, type ); + controller->SetTextFitStepSize(stepSize, type); } } } @@ -214,10 +214,10 @@ void ParseTextFitProperty(Text::ControllerPtr& controller, const Property::Map* Toolkit::TextLabel TextLabel::New() { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< TextLabel > impl = new TextLabel(); + IntrusivePtr impl = new TextLabel(); // Pass ownership to CustomActor handle - Toolkit::TextLabel handle( *impl ); + Toolkit::TextLabel handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -226,234 +226,234 @@ Toolkit::TextLabel TextLabel::New() return handle; } -void TextLabel::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void TextLabel::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::TextLabel label = Toolkit::TextLabel::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextLabel label = Toolkit::TextLabel::DownCast(Dali::BaseHandle(object)); - if( label ) + if(label) { - TextLabel& impl( GetImpl( label ) ); - DALI_ASSERT_ALWAYS( impl.mController && "No text contoller" ); + TextLabel& impl(GetImpl(label)); + DALI_ASSERT_ALWAYS(impl.mController && "No text contoller"); - switch( index ) + switch(index) { case Toolkit::DevelTextLabel::Property::RENDERING_BACKEND: { - int backend = value.Get< int >(); + int backend = value.Get(); #ifndef ENABLE_VECTOR_BASED_TEXT_RENDERING - if( DevelText::RENDERING_VECTOR_BASED == backend ) + if(DevelText::RENDERING_VECTOR_BASED == backend) { backend = TextAbstraction::BITMAP_GLYPH; // Fallback to bitmap-based rendering } #endif - if( impl.mRenderingBackend != backend ) + if(impl.mRenderingBackend != backend) { impl.mRenderingBackend = backend; impl.mTextUpdateNeeded = true; // When using the vector-based rendering, the size of the GLyphs are different TextAbstraction::GlyphType glyphType = (DevelText::RENDERING_VECTOR_BASED == impl.mRenderingBackend) ? TextAbstraction::VECTOR_GLYPH : TextAbstraction::BITMAP_GLYPH; - impl.mController->SetGlyphType( glyphType ); + impl.mController->SetGlyphType(glyphType); } break; } case Toolkit::TextLabel::Property::TEXT: { - impl.mController->SetText( value.Get< std::string >() ); + impl.mController->SetText(value.Get()); break; } case Toolkit::TextLabel::Property::FONT_FAMILY: { - const std::string& fontFamily = value.Get< std::string >(); + const std::string& fontFamily = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextLabel::SetProperty Property::FONT_FAMILY newFont(%s)\n", fontFamily.c_str() ); - impl.mController->SetDefaultFontFamily( fontFamily ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextLabel::SetProperty Property::FONT_FAMILY newFont(%s)\n", fontFamily.c_str()); + impl.mController->SetDefaultFontFamily(fontFamily); break; } case Toolkit::TextLabel::Property::FONT_STYLE: { - SetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT ); + SetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT); break; } case Toolkit::TextLabel::Property::POINT_SIZE: { - const float pointSize = value.Get< float >(); + const float pointSize = value.Get(); - if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) ) + if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize)) { - impl.mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE ); + impl.mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE); } break; } case Toolkit::TextLabel::Property::MULTI_LINE: { - impl.mController->SetMultiLineEnabled( value.Get< bool >() ); + impl.mController->SetMultiLineEnabled(value.Get()); break; } case Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT: { - Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( Text::GetHorizontalAlignmentEnumeration( value, alignment ) ) + Text::HorizontalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(Text::GetHorizontalAlignmentEnumeration(value, alignment)) { - impl.mController->SetHorizontalAlignment( alignment ); + impl.mController->SetHorizontalAlignment(alignment); } break; } case Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT: { - Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( Text::GetVerticalAlignmentEnumeration( value, alignment ) ) + Toolkit::Text::VerticalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(Text::GetVerticalAlignmentEnumeration(value, alignment)) { - impl.mController->SetVerticalAlignment( alignment ); + impl.mController->SetVerticalAlignment(alignment); } break; } case Toolkit::TextLabel::Property::ENABLE_MARKUP: { const bool enableMarkup = value.Get(); - impl.mController->SetMarkupProcessorEnabled( enableMarkup ); + impl.mController->SetMarkupProcessorEnabled(enableMarkup); break; } case Toolkit::TextLabel::Property::ENABLE_AUTO_SCROLL: { const bool enableAutoScroll = value.Get(); // If request to auto scroll is the same as current state then do nothing. - if ( enableAutoScroll != impl.mController->IsAutoScrollEnabled() ) + if(enableAutoScroll != impl.mController->IsAutoScrollEnabled()) { - // If request is disable (false) and auto scrolling is enabled then need to stop it - if ( enableAutoScroll == false ) - { - if( impl.mTextScroller ) - { - impl.mTextScroller->StopScrolling(); - } - } - // If request is enable (true) then start autoscroll as not already running - else - { - impl.mController->SetAutoScrollEnabled( enableAutoScroll ); - } + // If request is disable (false) and auto scrolling is enabled then need to stop it + if(enableAutoScroll == false) + { + if(impl.mTextScroller) + { + impl.mTextScroller->StopScrolling(); + } + } + // If request is enable (true) then start autoscroll as not already running + else + { + impl.mController->SetAutoScrollEnabled(enableAutoScroll); + } } break; } case Toolkit::TextLabel::Property::AUTO_SCROLL_STOP_MODE: { - Text::TextScrollerPtr textScroller = impl.GetTextScroller(); - Toolkit::TextLabel::AutoScrollStopMode::Type stopMode = textScroller->GetStopMode(); - if( Scripting::GetEnumerationProperty< Toolkit::TextLabel::AutoScrollStopMode::Type >( value, - AUTO_SCROLL_STOP_MODE_TABLE, - AUTO_SCROLL_STOP_MODE_TABLE_COUNT, - stopMode ) ) + Text::TextScrollerPtr textScroller = impl.GetTextScroller(); + Toolkit::TextLabel::AutoScrollStopMode::Type stopMode = textScroller->GetStopMode(); + if(Scripting::GetEnumerationProperty(value, + AUTO_SCROLL_STOP_MODE_TABLE, + AUTO_SCROLL_STOP_MODE_TABLE_COUNT, + stopMode)) { - textScroller->SetStopMode( stopMode ); + textScroller->SetStopMode(stopMode); } break; } case Toolkit::TextLabel::Property::AUTO_SCROLL_SPEED: { - impl.GetTextScroller()->SetSpeed( value.Get() ); + impl.GetTextScroller()->SetSpeed(value.Get()); break; } case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_COUNT: { - impl.GetTextScroller()->SetLoopCount( value.Get() ); + impl.GetTextScroller()->SetLoopCount(value.Get()); break; } case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_DELAY: { - impl.GetTextScroller()->SetLoopDelay( value.Get() ); + impl.GetTextScroller()->SetLoopDelay(value.Get()); break; } case Toolkit::TextLabel::Property::AUTO_SCROLL_GAP: { - impl.GetTextScroller()->SetGap( value.Get() ); + impl.GetTextScroller()->SetGap(value.Get()); break; } case Toolkit::TextLabel::Property::LINE_SPACING: { const float lineSpacing = value.Get(); - impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSpacing( lineSpacing ) || impl.mTextUpdateNeeded; + impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSpacing(lineSpacing) || impl.mTextUpdateNeeded; break; } case Toolkit::TextLabel::Property::UNDERLINE: { - impl.mTextUpdateNeeded = SetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded; + impl.mTextUpdateNeeded = SetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded; break; } case Toolkit::TextLabel::Property::SHADOW: { - impl.mTextUpdateNeeded = SetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded; + impl.mTextUpdateNeeded = SetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded; break; } case Toolkit::TextLabel::Property::EMBOSS: { - impl.mTextUpdateNeeded = SetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded; + impl.mTextUpdateNeeded = SetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded; break; } case Toolkit::TextLabel::Property::OUTLINE: { - impl.mTextUpdateNeeded = SetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded; + impl.mTextUpdateNeeded = SetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded; break; } case Toolkit::TextLabel::Property::PIXEL_SIZE: { - const float pixelSize = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize ); + const float pixelSize = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p PIXEL_SIZE %f\n", impl.mController.Get(), pixelSize); - if( !Equals( impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ), pixelSize ) ) + if(!Equals(impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE), pixelSize)) { - impl.mController->SetDefaultFontSize( pixelSize, Text::Controller::PIXEL_SIZE ); + impl.mController->SetDefaultFontSize(pixelSize, Text::Controller::PIXEL_SIZE); } break; } case Toolkit::TextLabel::Property::ELLIPSIS: { const bool ellipsis = value.Get(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p ELLIPSIS %d\n", impl.mController.Get(), ellipsis); - impl.mController->SetTextElideEnabled( ellipsis ); + impl.mController->SetTextElideEnabled(ellipsis); break; } case Toolkit::TextLabel::Property::LINE_WRAP_MODE: { - Text::LineWrap::Mode lineWrapMode( static_cast< Text::LineWrap::Mode >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( GetLineWrapModeEnumeration( value, lineWrapMode ) ) + Text::LineWrap::Mode lineWrapMode(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(GetLineWrapModeEnumeration(value, lineWrapMode)) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode ); - impl.mController->SetLineWrapMode( lineWrapMode ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p LineWrap::MODE %d\n", impl.mController.Get(), lineWrapMode); + impl.mController->SetLineWrapMode(lineWrapMode); } break; } case Toolkit::DevelTextLabel::Property::VERTICAL_LINE_ALIGNMENT: { - if( impl.mController->GetTextModel() ) + if(impl.mController->GetTextModel()) { - DevelText::VerticalLineAlignment::Type alignment = static_cast( value.Get() ); + DevelText::VerticalLineAlignment::Type alignment = static_cast(value.Get()); - impl.mController->SetVerticalLineAlignment( alignment ); + impl.mController->SetVerticalLineAlignment(alignment); // Property doesn't affect the layout, only Visual must be updated - TextVisual::EnableRendererUpdate( impl.mVisual ); + TextVisual::EnableRendererUpdate(impl.mVisual); // No need to trigger full re-layout. Instead call UpdateRenderer() directly - TextVisual::UpdateRenderer( impl.mVisual ); + TextVisual::UpdateRenderer(impl.mVisual); } break; } case Toolkit::DevelTextLabel::Property::BACKGROUND: { - impl.mTextUpdateNeeded = SetBackgroundProperties( impl.mController, value, Text::EffectStyle::DEFAULT ) || impl.mTextUpdateNeeded; + impl.mTextUpdateNeeded = SetBackgroundProperties(impl.mController, value, Text::EffectStyle::DEFAULT) || impl.mTextUpdateNeeded; break; } case Toolkit::DevelTextLabel::Property::IGNORE_SPACES_AFTER_TEXT: { - impl.mController->SetIgnoreSpacesAfterText(value.Get< bool >()); + impl.mController->SetIgnoreSpacesAfterText(value.Get()); break; } case Toolkit::DevelTextLabel::Property::MATCH_SYSTEM_LANGUAGE_DIRECTION: { - impl.mController->SetMatchSystemLanguageDirection(value.Get< bool >()); + impl.mController->SetMatchSystemLanguageDirection(value.Get()); break; } case Toolkit::DevelTextLabel::Property::TEXT_FIT: @@ -463,18 +463,18 @@ void TextLabel::SetProperty( BaseObject* object, Property::Index index, const Pr } case Toolkit::DevelTextLabel::Property::MIN_LINE_SIZE: { - const float lineSize = value.Get(); - impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSize( lineSize ) || impl.mTextUpdateNeeded; + const float lineSize = value.Get(); + impl.mTextUpdateNeeded = impl.mController->SetDefaultLineSize(lineSize) || impl.mTextUpdateNeeded; break; } case Toolkit::DevelTextLabel::Property::FONT_SIZE_SCALE: { - const float scale = value.Get< float >(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale ); + const float scale = value.Get(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel %p FONT_SIZE_SCALE %f\n", impl.mController.Get(), scale); - if( !Equals( impl.mController->GetFontSizeScale(), scale ) ) + if(!Equals(impl.mController->GetFontSizeScale(), scale)) { - impl.mController->SetFontSizeScale( scale ); + impl.mController->SetFontSizeScale(scale); } break; } @@ -483,7 +483,7 @@ void TextLabel::SetProperty( BaseObject* object, Property::Index index, const Pr // Request relayout when text update is needed. It's necessary to call it // as changing the property not via UI interaction brings no effect if only // the mTextUpdateNeeded is changed. - if( impl.mTextUpdateNeeded ) + if(impl.mTextUpdateNeeded) { // need to request relayout as size of text may have changed impl.RequestTextRelayout(); @@ -491,20 +491,23 @@ void TextLabel::SetProperty( BaseObject* object, Property::Index index, const Pr } } -Text::ControllerPtr TextLabel::getController() { return mController; } +Text::ControllerPtr TextLabel::getController() +{ + return mController; +} -Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index index ) +Property::Value TextLabel::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::TextLabel label = Toolkit::TextLabel::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextLabel label = Toolkit::TextLabel::DownCast(Dali::BaseHandle(object)); - if( label ) + if(label) { - TextLabel& impl( GetImpl( label ) ); - DALI_ASSERT_DEBUG( impl.mController && "No text contoller" ); + TextLabel& impl(GetImpl(label)); + DALI_ASSERT_DEBUG(impl.mController && "No text contoller"); - switch( index ) + switch(index) { case Toolkit::DevelTextLabel::Property::RENDERING_BACKEND: { @@ -514,7 +517,7 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde case Toolkit::TextLabel::Property::TEXT: { std::string text; - impl.mController->GetText( text ); + impl.mController->GetText(text); value = text; break; } @@ -525,12 +528,12 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::FONT_STYLE: { - GetFontStyleProperty( impl.mController, value, Text::FontStyle::DEFAULT ); + GetFontStyleProperty(impl.mController, value, Text::FontStyle::DEFAULT); break; } case Toolkit::TextLabel::Property::POINT_SIZE: { - value = impl.mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ); + value = impl.mController->GetDefaultFontSize(Text::Controller::POINT_SIZE); break; } case Toolkit::TextLabel::Property::MULTI_LINE: @@ -540,20 +543,20 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT: { - const char* name = Text::GetHorizontalAlignmentString( impl.mController->GetHorizontalAlignment() ); + const char* name = Text::GetHorizontalAlignmentString(impl.mController->GetHorizontalAlignment()); - if ( name ) + if(name) { - value = std::string( name ); + value = std::string(name); } break; } case Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT: { - const char* name = Text::GetVerticalAlignmentString( impl.mController->GetVerticalAlignment() ); - if( name ) + const char* name = Text::GetVerticalAlignmentString(impl.mController->GetVerticalAlignment()); + if(name) { - value = std::string( name ); + value = std::string(name); } break; } @@ -569,21 +572,21 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::AUTO_SCROLL_STOP_MODE: { - if( impl.mTextScroller ) + if(impl.mTextScroller) { - const char* mode = Scripting::GetEnumerationName< Toolkit::TextLabel::AutoScrollStopMode::Type >( impl.mTextScroller->GetStopMode(), - AUTO_SCROLL_STOP_MODE_TABLE, - AUTO_SCROLL_STOP_MODE_TABLE_COUNT ); - if( mode ) + const char* mode = Scripting::GetEnumerationName(impl.mTextScroller->GetStopMode(), + AUTO_SCROLL_STOP_MODE_TABLE, + AUTO_SCROLL_STOP_MODE_TABLE_COUNT); + if(mode) { - value = std::string( mode ); + value = std::string(mode); } } break; } case Toolkit::TextLabel::Property::AUTO_SCROLL_SPEED: { - if ( impl.mTextScroller ) + if(impl.mTextScroller) { value = impl.mTextScroller->GetSpeed(); } @@ -591,7 +594,7 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_COUNT: { - if ( impl.mTextScroller ) + if(impl.mTextScroller) { value = impl.mTextScroller->GetLoopCount(); } @@ -599,7 +602,7 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::AUTO_SCROLL_LOOP_DELAY: { - if ( impl.mTextScroller ) + if(impl.mTextScroller) { value = impl.mTextScroller->GetLoopDelay(); } @@ -607,7 +610,7 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::AUTO_SCROLL_GAP: { - if ( impl.mTextScroller ) + if(impl.mTextScroller) { value = impl.mTextScroller->GetGap(); } @@ -620,27 +623,27 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::UNDERLINE: { - GetUnderlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetUnderlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextLabel::Property::SHADOW: { - GetShadowProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetShadowProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextLabel::Property::EMBOSS: { - GetEmbossProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetEmbossProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextLabel::Property::OUTLINE: { - GetOutlineProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetOutlineProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextLabel::Property::PIXEL_SIZE: { - value = impl.mController->GetDefaultFontSize( Text::Controller::PIXEL_SIZE ); + value = impl.mController->GetDefaultFontSize(Text::Controller::PIXEL_SIZE); break; } case Toolkit::TextLabel::Property::ELLIPSIS: @@ -655,8 +658,8 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::TextLabel::Property::LINE_COUNT: { - float width = label.GetProperty( Actor::Property::SIZE_WIDTH ).Get(); - value = impl.mController->GetLineCount( width ); + float width = label.GetProperty(Actor::Property::SIZE_WIDTH).Get(); + value = impl.mController->GetLineCount(width); break; } case Toolkit::DevelTextLabel::Property::TEXT_DIRECTION: @@ -671,7 +674,7 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::DevelTextLabel::Property::BACKGROUND: { - GetBackgroundProperties( impl.mController, value, Text::EffectStyle::DEFAULT ); + GetBackgroundProperties(impl.mController, value, Text::EffectStyle::DEFAULT); break; } case Toolkit::DevelTextLabel::Property::IGNORE_SPACES_AFTER_TEXT: @@ -686,17 +689,17 @@ Property::Value TextLabel::GetProperty( BaseObject* object, Property::Index inde } case Toolkit::DevelTextLabel::Property::TEXT_FIT: { - const bool enabled = impl.mController->IsTextFitEnabled(); - const float minSize = impl.mController->GetTextFitMinSize(); - const float maxSize = impl.mController->GetTextFitMaxSize(); + const bool enabled = impl.mController->IsTextFitEnabled(); + const float minSize = impl.mController->GetTextFitMinSize(); + const float maxSize = impl.mController->GetTextFitMaxSize(); const float stepSize = impl.mController->GetTextFitStepSize(); Property::Map map; - map.Insert( TEXT_FIT_ENABLE_KEY, enabled ); - map.Insert( TEXT_FIT_MIN_SIZE_KEY, minSize ); - map.Insert( TEXT_FIT_MAX_SIZE_KEY, maxSize ); - map.Insert( TEXT_FIT_STEP_SIZE_KEY, stepSize ); - map.Insert( TEXT_FIT_FONT_SIZE_TYPE_KEY, "pointSize" ); + map.Insert(TEXT_FIT_ENABLE_KEY, enabled); + map.Insert(TEXT_FIT_MIN_SIZE_KEY, minSize); + map.Insert(TEXT_FIT_MAX_SIZE_KEY, maxSize); + map.Insert(TEXT_FIT_STEP_SIZE_KEY, stepSize); + map.Insert(TEXT_FIT_FONT_SIZE_TYPE_KEY, "pointSize"); value = map; break; @@ -722,60 +725,60 @@ void TextLabel::OnInitialize() Actor self = Self(); Property::Map propertyMap; - propertyMap.Add( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT ); + propertyMap.Add(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT); - mVisual = Toolkit::VisualFactory::Get().CreateVisual( propertyMap ); - DevelControl::RegisterVisual( *this, Toolkit::TextLabel::Property::TEXT, mVisual ); + mVisual = Toolkit::VisualFactory::Get().CreateVisual(propertyMap); + DevelControl::RegisterVisual(*this, Toolkit::TextLabel::Property::TEXT, mVisual); - TextVisual::SetAnimatableTextColorProperty( mVisual, Toolkit::TextLabel::Property::TEXT_COLOR ); + TextVisual::SetAnimatableTextColorProperty(mVisual, Toolkit::TextLabel::Property::TEXT_COLOR); mController = TextVisual::GetController(mVisual); - DALI_ASSERT_DEBUG( mController && "Invalid Text Controller") + DALI_ASSERT_DEBUG(mController && "Invalid Text Controller") mController->SetControlInterface(this); // Use height-for-width negotiation by default - self.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); - self.SetResizePolicy( ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT ); + self.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH); + self.SetResizePolicy(ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT); // Enable highlightability - self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); // Enable the text ellipsis. - mController->SetTextElideEnabled( true ); // If false then text larger than control will overflow + mController->SetTextElideEnabled(true); // If false then text larger than control will overflow // Sets layoutDirection value - Dali::Stage stage = Dali::Stage::GetCurrent(); - Dali::LayoutDirection::Type layoutDirection = static_cast( stage.GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); - mController->SetLayoutDirection( layoutDirection ); + Dali::Stage stage = Dali::Stage::GetCurrent(); + Dali::LayoutDirection::Type layoutDirection = static_cast(stage.GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); + mController->SetLayoutDirection(layoutDirection); Layout::Engine& engine = mController->GetLayoutEngine(); - engine.SetCursorWidth( 0u ); // Do not layout space for the cursor. + engine.SetCursorWidth(0u); // Do not layout space for the cursor. - DevelControl::SetAccessibilityConstructor( self, []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new AccessibleImpl( actor, Dali::Accessibility::Role::LABEL ) ); - } ); + DevelControl::SetAccessibilityConstructor(self, [](Dali::Actor actor) { + return std::unique_ptr( + new AccessibleImpl(actor, Dali::Accessibility::Role::LABEL)); + }); } -void TextLabel::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange::Type change ) +void TextLabel::OnStyleChange(Toolkit::StyleManager styleManager, StyleChange::Type change) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextLabel::OnStyleChange\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextLabel::OnStyleChange\n"); - switch ( change ) + switch(change) { case StyleChange::DEFAULT_FONT_CHANGE: { // Property system did not set the font so should update it. - const std::string& newFont = GetImpl( styleManager ).GetDefaultFontFamily(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::OnStyleChange StyleChange::DEFAULT_FONT_CHANGE newFont(%s)\n", newFont.c_str() ); - mController->UpdateAfterFontChange( newFont ); + const std::string& newFont = GetImpl(styleManager).GetDefaultFontFamily(); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::OnStyleChange StyleChange::DEFAULT_FONT_CHANGE newFont(%s)\n", newFont.c_str()); + mController->UpdateAfterFontChange(newFont); RelayoutRequest(); break; } case StyleChange::DEFAULT_FONT_SIZE_CHANGE: { - GetImpl( styleManager ).ApplyThemeStyle( Toolkit::Control( GetOwner() ) ); + GetImpl(styleManager).ApplyThemeStyle(Toolkit::Control(GetOwner())); RelayoutRequest(); break; } @@ -787,123 +790,122 @@ void TextLabel::OnStyleChange( Toolkit::StyleManager styleManager, StyleChange:: } // Up call to Control - Control::OnStyleChange( styleManager, change ); + Control::OnStyleChange(styleManager, change); } Vector3 TextLabel::GetNaturalSize() { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); Vector3 naturalSize = mController->GetNaturalSize(); - naturalSize.width += ( padding.start + padding.end ); - naturalSize.height += ( padding.top + padding.bottom ); + naturalSize.width += (padding.start + padding.end); + naturalSize.height += (padding.top + padding.bottom); return naturalSize; } -float TextLabel::GetHeightForWidth( float width ) +float TextLabel::GetHeightForWidth(float width) { Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); - return mController->GetHeightForWidth( width ) + padding.top + padding.bottom; + return mController->GetHeightForWidth(width) + padding.top + padding.bottom; } -void TextLabel::OnPropertySet( Property::Index index, const Property::Value& propertyValue ) +void TextLabel::OnPropertySet(Property::Index index, const Property::Value& propertyValue) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextLabel::OnPropertySet index[%d]\n", index ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextLabel::OnPropertySet index[%d]\n", index); - switch ( index ) + switch(index) { case Toolkit::TextLabel::Property::TEXT_COLOR: { - const Vector4& textColor = propertyValue.Get< Vector4 >(); - if( mController->GetDefaultColor() != textColor ) + const Vector4& textColor = propertyValue.Get(); + if(mController->GetDefaultColor() != textColor) { - mController->SetDefaultColor( textColor ); - mTextUpdateNeeded = true; + mController->SetDefaultColor(textColor); + mTextUpdateNeeded = true; } break; } default: { - Control::OnPropertySet( index, propertyValue ); // up call to control for non-handled properties + Control::OnPropertySet(index, propertyValue); // up call to control for non-handled properties break; } } } -void TextLabel::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void TextLabel::OnRelayout(const Vector2& size, RelayoutContainer& container) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::OnRelayout\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::OnRelayout\n"); Extents padding; - padding = Self().GetProperty( Toolkit::Control::Property::PADDING ); + padding = Self().GetProperty(Toolkit::Control::Property::PADDING); - Vector2 contentSize( size.x - ( padding.start + padding.end ), size.y - ( padding.top + padding.bottom ) ); + Vector2 contentSize(size.x - (padding.start + padding.end), size.y - (padding.top + padding.bottom)); - if( mController->IsTextFitEnabled() ) + if(mController->IsTextFitEnabled()) { - mController->FitPointSizeforLayout( contentSize ); - mController->SetTextFitContentSize( contentSize ); + mController->FitPointSizeforLayout(contentSize); + mController->SetTextFitContentSize(contentSize); } // Support Right-To-Left Dali::LayoutDirection::Type layoutDirection; - if( mController->IsMatchSystemLanguageDirection() ) + if(mController->IsMatchSystemLanguageDirection()) { - layoutDirection = static_cast( DevelWindow::Get( Self() ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(DevelWindow::Get(Self()).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } else { - layoutDirection = static_cast( Self().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(Self().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } - const Text::Controller::UpdateTextType updateTextType = mController->Relayout( contentSize, layoutDirection ); + const Text::Controller::UpdateTextType updateTextType = mController->Relayout(contentSize, layoutDirection); - if( ( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) ) - || mTextUpdateNeeded ) + if((Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType)) || mTextUpdateNeeded) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::OnRelayout IsAutoScrollEnabled[%s] [%p]\n", ( mController->IsAutoScrollEnabled())?"true":"false", this ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::OnRelayout IsAutoScrollEnabled[%s] [%p]\n", (mController->IsAutoScrollEnabled()) ? "true" : "false", this); // Update the visual - TextVisual::EnableRendererUpdate( mVisual ); + TextVisual::EnableRendererUpdate(mVisual); // Support Right-To-Left of padding - if( Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection ) + if(Dali::LayoutDirection::RIGHT_TO_LEFT == layoutDirection) { - std::swap( padding.start, padding.end ); + std::swap(padding.start, padding.end); } // Calculate the size of the visual that can fit the text Size layoutSize = mController->GetTextModel()->GetLayoutSize(); - layoutSize.x = contentSize.x; + layoutSize.x = contentSize.x; const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset(); - if ( shadowOffset.y > Math::MACHINE_EPSILON_1 ) + if(shadowOffset.y > Math::MACHINE_EPSILON_1) { layoutSize.y += shadowOffset.y; } float outlineWidth = mController->GetTextModel()->GetOutlineWidth(); layoutSize.y += outlineWidth * 2.0f; - layoutSize.y = std::min( layoutSize.y, contentSize.y ); + layoutSize.y = std::min(layoutSize.y, contentSize.y); // Calculate the offset for vertical alignment only, as the layout engine will do the horizontal alignment. Vector2 alignmentOffset; alignmentOffset.x = 0.0f; - alignmentOffset.y = ( contentSize.y - layoutSize.y ) * VERTICAL_ALIGNMENT_TABLE[mController->GetVerticalAlignment()]; + alignmentOffset.y = (contentSize.y - layoutSize.y) * VERTICAL_ALIGNMENT_TABLE[mController->GetVerticalAlignment()]; Property::Map visualTransform; - visualTransform.Add( Toolkit::Visual::Transform::Property::SIZE, layoutSize ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::OFFSET, Vector2( padding.start, padding.top ) + alignmentOffset ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE ) ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN ); - mVisual.SetTransformAndSize( visualTransform, size ); - - if ( mController->IsAutoScrollEnabled() ) + visualTransform.Add(Toolkit::Visual::Transform::Property::SIZE, layoutSize) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::OFFSET, Vector2(padding.start, padding.top) + alignmentOffset) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(Toolkit::Visual::Transform::Policy::ABSOLUTE, Toolkit::Visual::Transform::Policy::ABSOLUTE)) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, Toolkit::Align::TOP_BEGIN) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, Toolkit::Align::TOP_BEGIN); + mVisual.SetTransformAndSize(visualTransform, size); + + if(mController->IsAutoScrollEnabled()) { SetUpAutoScrolling(); } @@ -920,79 +922,78 @@ void TextLabel::RequestTextRelayout() void TextLabel::SetUpAutoScrolling() { - const Size& controlSize = mController->GetView().GetControlSize(); - const Size textNaturalSize = GetNaturalSize().GetVectorXY(); // As relayout of text may not be done at this point natural size is used to get size. Single line scrolling only. - const Text::CharacterDirection direction = mController->GetAutoScrollDirection(); + const Size& controlSize = mController->GetView().GetControlSize(); + const Size textNaturalSize = GetNaturalSize().GetVectorXY(); // As relayout of text may not be done at this point natural size is used to get size. Single line scrolling only. + const Text::CharacterDirection direction = mController->GetAutoScrollDirection(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling textNaturalSize[%f,%f] controlSize[%f,%f]\n", - textNaturalSize.x,textNaturalSize.y , controlSize.x,controlSize.y ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling textNaturalSize[%f,%f] controlSize[%f,%f]\n", textNaturalSize.x, textNaturalSize.y, controlSize.x, controlSize.y); - if ( !mTextScroller ) + if(!mTextScroller) { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling Creating default TextScoller\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::SetUpAutoScrolling Creating default TextScoller\n"); // If speed, loopCount or gap not set via property system then will need to create a TextScroller with defaults - mTextScroller = Text::TextScroller::New( *this ); + mTextScroller = Text::TextScroller::New(*this); } // Calculate the actual gap before scrolling wraps. - int textPadding = std::max( controlSize.x - textNaturalSize.x, 0.0f ); - float wrapGap = std::max( mTextScroller->GetGap(), textPadding ); + int textPadding = std::max(controlSize.x - textNaturalSize.x, 0.0f); + float wrapGap = std::max(mTextScroller->GetGap(), textPadding); Vector2 textureSize = textNaturalSize + Vector2(wrapGap, 0.0f); // Add the gap as a part of the texture // Create a texture of the text for scrolling - Size verifiedSize = textureSize; + Size verifiedSize = textureSize; const int maxTextureSize = Dali::GetMaxTextureSize(); //if the texture size width exceed maxTextureSize, modify the visual model size and enabled the ellipsis bool actualellipsis = mController->IsTextElideEnabled(); - if( verifiedSize.width > maxTextureSize ) + if(verifiedSize.width > maxTextureSize) { verifiedSize.width = maxTextureSize; - if( textNaturalSize.width > maxTextureSize ) + if(textNaturalSize.width > maxTextureSize) { - mController->SetTextElideEnabled( true ); + mController->SetTextElideEnabled(true); } - GetHeightForWidth( maxTextureSize ); - wrapGap = std::max( maxTextureSize - textNaturalSize.width, 0.0f ); + GetHeightForWidth(maxTextureSize); + wrapGap = std::max(maxTextureSize - textNaturalSize.width, 0.0f); } - Text::TypesetterPtr typesetter = Text::Typesetter::New( mController->GetTextModel() ); + Text::TypesetterPtr typesetter = Text::Typesetter::New(mController->GetTextModel()); - PixelData data = typesetter->Render( verifiedSize, mController->GetTextDirection(), Text::Typesetter::RENDER_TEXT_AND_STYLES, true, Pixel::RGBA8888 ); // ignore the horizontal alignment - Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, - data.GetPixelFormat(), - data.GetWidth(), - data.GetHeight() ); - texture.Upload( data ); + PixelData data = typesetter->Render(verifiedSize, mController->GetTextDirection(), Text::Typesetter::RENDER_TEXT_AND_STYLES, true, Pixel::RGBA8888); // ignore the horizontal alignment + Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, + data.GetPixelFormat(), + data.GetWidth(), + data.GetHeight()); + texture.Upload(data); TextureSet textureSet = TextureSet::New(); - textureSet.SetTexture( 0u, texture ); + textureSet.SetTexture(0u, texture); // Filter mode needs to be set to linear to produce better quality while scaling. Sampler sampler = Sampler::New(); - sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR ); - sampler.SetWrapMode( Dali::WrapMode::DEFAULT, Dali::WrapMode::REPEAT, Dali::WrapMode::DEFAULT ); // Wrap the texture in the x direction - textureSet.SetSampler( 0u, sampler ); + sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR); + sampler.SetWrapMode(Dali::WrapMode::DEFAULT, Dali::WrapMode::REPEAT, Dali::WrapMode::DEFAULT); // Wrap the texture in the x direction + textureSet.SetSampler(0u, sampler); // Set parameters for scrolling - Renderer renderer = static_cast( GetImplementation( mVisual ) ).GetRenderer(); - mTextScroller->SetParameters( Self(), renderer, textureSet, controlSize, verifiedSize, wrapGap, direction, mController->GetHorizontalAlignment(), mController->GetVerticalAlignment() ); - mController->SetTextElideEnabled( actualellipsis ); + Renderer renderer = static_cast(GetImplementation(mVisual)).GetRenderer(); + mTextScroller->SetParameters(Self(), renderer, textureSet, controlSize, verifiedSize, wrapGap, direction, mController->GetHorizontalAlignment(), mController->GetVerticalAlignment()); + mController->SetTextElideEnabled(actualellipsis); } void TextLabel::ScrollingFinished() { // Pure Virtual from TextScroller Interface - DALI_LOG_INFO( gLogFilter, Debug::General, "TextLabel::ScrollingFinished\n"); - mController->SetAutoScrollEnabled( false ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextLabel::ScrollingFinished\n"); + mController->SetAutoScrollEnabled(false); RequestTextRelayout(); } TextLabel::TextLabel() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), - mRenderingBackend( DEFAULT_RENDERING_BACKEND ), - mTextUpdateNeeded( false ) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), + mRenderingBackend(DEFAULT_RENDERING_BACKEND), + mTextUpdateNeeded(false) { } @@ -1002,8 +1003,8 @@ TextLabel::~TextLabel() std::string TextLabel::AccessibleImpl::GetNameRaw() { - auto slf = Toolkit::TextLabel::DownCast( self ); - return slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >(); + auto slf = Toolkit::TextLabel::DownCast(self); + return slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get(); } Property::Index TextLabel::AccessibleImpl::GetNamePropertyIndex() @@ -1011,46 +1012,46 @@ Property::Index TextLabel::AccessibleImpl::GetNamePropertyIndex() return Toolkit::TextLabel::Property::TEXT; } -std::string TextLabel::AccessibleImpl::GetText( size_t startOffset, - size_t endOffset ) +std::string TextLabel::AccessibleImpl::GetText(size_t startOffset, + size_t endOffset) { - if( endOffset <= startOffset ) + if(endOffset <= startOffset) return {}; - auto slf = Toolkit::TextLabel::DownCast( self ); + auto slf = Toolkit::TextLabel::DownCast(self); auto txt = - slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >(); + slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get(); - if( startOffset > txt.size() || endOffset > txt.size() ) + if(startOffset > txt.size() || endOffset > txt.size()) return {}; - return txt.substr( startOffset, endOffset - startOffset ); + return txt.substr(startOffset, endOffset - startOffset); } size_t TextLabel::AccessibleImpl::GetCharacterCount() { - auto slf = Toolkit::TextLabel::DownCast( self ); + auto slf = Toolkit::TextLabel::DownCast(self); auto txt = - slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >(); + slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get(); return txt.size(); } size_t TextLabel::AccessibleImpl::GetCaretOffset() { - return {}; + return {}; } bool TextLabel::AccessibleImpl::SetCaretOffset(size_t offset) { - return {}; + return {}; } Dali::Accessibility::Range TextLabel::AccessibleImpl::GetTextAtOffset( - size_t offset, Dali::Accessibility::TextBoundary boundary ) + size_t offset, Dali::Accessibility::TextBoundary boundary) { - auto slf = Toolkit::TextLabel::DownCast( self ); - auto txt = slf.GetProperty( Toolkit::TextLabel::Property::TEXT ).Get< std::string >(); + auto slf = Toolkit::TextLabel::DownCast(self); + auto txt = slf.GetProperty(Toolkit::TextLabel::Property::TEXT).Get(); auto txt_size = txt.size(); auto range = Dali::Accessibility::Range{}; @@ -1058,63 +1059,63 @@ Dali::Accessibility::Range TextLabel::AccessibleImpl::GetTextAtOffset( switch(boundary) { case Dali::Accessibility::TextBoundary::CHARACTER: + { + if(offset < txt_size) { - if (offset < txt_size) - { - range.content = txt[offset]; - range.startOffset = offset; - range.endOffset = offset + 1; - } + range.content = txt[offset]; + range.startOffset = offset; + range.endOffset = offset + 1; } - break; + } + break; case Dali::Accessibility::TextBoundary::WORD: case Dali::Accessibility::TextBoundary::LINE: - { - auto txt_c_string = txt.c_str(); - auto breaks = std::vector< char >( txt_size, 0 ); - if(boundary == Dali::Accessibility::TextBoundary::WORD) - Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data()); + { + auto txt_c_string = txt.c_str(); + auto breaks = std::vector(txt_size, 0); + if(boundary == Dali::Accessibility::TextBoundary::WORD) + Accessibility::Accessible::FindWordSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data()); + else + Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t*)txt_c_string, txt_size, "", breaks.data()); + auto index = 0u; + auto counter = 0u; + while(index < txt_size && counter <= offset) + { + auto start = index; + if(breaks[index]) + { + while(breaks[index]) + index++; + counter++; + } else - Accessibility::Accessible::FindLineSeparationsUtf8((const utf8_t *) txt_c_string, txt_size, "", breaks.data()); - auto index = 0u; - auto counter = 0u; - while( index < txt_size && counter <= offset ) { - auto start = index; - if(breaks[index]) - { - while(breaks[index]) - index++; + if(boundary == Dali::Accessibility::TextBoundary::WORD) + index++; + if(boundary == Dali::Accessibility::TextBoundary::LINE) counter++; - } - else - { - if (boundary == Dali::Accessibility::TextBoundary::WORD) - index++; - if (boundary == Dali::Accessibility::TextBoundary::LINE) - counter++; - } - if ((counter > 0) && ((counter - 1) == offset)) - { - range.content = txt.substr(start, index - start + 1); - range.startOffset = start; - range.endOffset = index + 1; - } - if (boundary == Dali::Accessibility::TextBoundary::LINE) - index++; } + if((counter > 0) && ((counter - 1) == offset)) + { + range.content = txt.substr(start, index - start + 1); + range.startOffset = start; + range.endOffset = index + 1; + } + if(boundary == Dali::Accessibility::TextBoundary::LINE) + index++; } - break; + } + break; case Dali::Accessibility::TextBoundary::SENTENCE: - { - /* not supported by efl */ - } - break; + { + /* not supported by efl */ + } + break; case Dali::Accessibility::TextBoundary::PARAGRAPH: - { - /* Paragraph is not supported by libunibreak library */ - } - break; + { + /* Paragraph is not supported by libunibreak library */ + } + break; default: break; } @@ -1123,43 +1124,43 @@ Dali::Accessibility::Range TextLabel::AccessibleImpl::GetTextAtOffset( } Dali::Accessibility::Range -TextLabel::AccessibleImpl::GetSelection( size_t selectionNum ) +TextLabel::AccessibleImpl::GetSelection(size_t selectionNum) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return {}; - auto slf = Toolkit::TextLabel::DownCast( self ); - auto ctrl = Dali::Toolkit::GetImpl( slf ).getController(); + auto slf = Toolkit::TextLabel::DownCast(self); + auto ctrl = Dali::Toolkit::GetImpl(slf).getController(); std::string ret; - ctrl->RetrieveSelection( ret ); + ctrl->RetrieveSelection(ret); auto r = ctrl->GetSelectionIndexes(); - return { static_cast(r.first), static_cast(r.second), ret }; + return {static_cast(r.first), static_cast(r.second), ret}; } -bool TextLabel::AccessibleImpl::RemoveSelection( size_t selectionNum ) +bool TextLabel::AccessibleImpl::RemoveSelection(size_t selectionNum) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return false; - auto slf = Toolkit::TextLabel::DownCast( self ); - Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( 0, 0 ); + auto slf = Toolkit::TextLabel::DownCast(self); + Dali::Toolkit::GetImpl(slf).getController()->SetSelection(0, 0); return true; } -bool TextLabel::AccessibleImpl::SetSelection( size_t selectionNum, - size_t startOffset, - size_t endOffset ) +bool TextLabel::AccessibleImpl::SetSelection(size_t selectionNum, + size_t startOffset, + size_t endOffset) { // Since DALi supports only one selection indexes higher than 0 are ignored - if( selectionNum > 0 ) + if(selectionNum > 0) return false; - auto slf = Toolkit::TextLabel::DownCast( self ); - Dali::Toolkit::GetImpl( slf ).getController()->SetSelection( startOffset, - endOffset ); + auto slf = Toolkit::TextLabel::DownCast(self); + Dali::Toolkit::GetImpl(slf).getController()->SetSelection(startOffset, + endOffset); return true; } diff --git a/dali-toolkit/internal/controls/text-controls/text-selection-popup-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-selection-popup-impl.cpp index bf7b618..ebc01b6 100644 --- a/dali-toolkit/internal/controls/text-controls/text-selection-popup-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-selection-popup-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,48 +22,45 @@ #if defined(__GLIBC__) #include #endif -#include -#include +#include #include #include #include #include #include -#include +#include +#include // INTERNAL INCLUDES -#include +#include #include #include -#include #include +#include +#include +#include +#include #include #include #include -#include -#include -#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { #if defined(__GLIBC__) #define GET_LOCALE_TEXT(string) dgettext("dali-toolkit", string) #endif -const std::string TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME( "TextSelectionPopupButton" ); -const Dali::Vector4 DEFAULT_OPTION_PRESSED_COLOR( Dali::Vector4( 0.24f, 0.72f, 0.8f, 1.0f ) ); +const std::string TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME("TextSelectionPopupButton"); +const Dali::Vector4 DEFAULT_OPTION_PRESSED_COLOR(Dali::Vector4(0.24f, 0.72f, 0.8f, 1.0f)); #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif #ifdef DGETTEXT_ENABLED @@ -77,67 +74,66 @@ const Dali::Vector4 DEFAULT_OPTION_PRESSED_COLOR( Dali::Vector4( 0.24f, 0.72f, 0 #else -#define POPUP_CUT_STRING "Cut" -#define POPUP_COPY_STRING "Copy" -#define POPUP_PASTE_STRING "Paste" -#define POPUP_SELECT_STRING "Select" -#define POPUP_SELECT_ALL_STRING "Select All" -#define POPUP_CLIPBOARD_STRING "Clipboard" +#define POPUP_CUT_STRING "Cut" +#define POPUP_COPY_STRING "Copy" +#define POPUP_PASTE_STRING "Paste" +#define POPUP_SELECT_STRING "Select" +#define POPUP_SELECT_ALL_STRING "Select All" +#define POPUP_CLIPBOARD_STRING "Clipboard" #endif -const char* const OPTION_SELECT_WORD = "option-select_word"; // "Select Word" popup option. -const char* const OPTION_SELECT_ALL("option-select_all"); // "Select All" popup option. -const char* const OPTION_CUT("optionCut"); // "Cut" popup option. -const char* const OPTION_COPY("optionCopy"); // "Copy" popup option. -const char* const OPTION_PASTE("optionPaste"); // "Paste" popup option. -const char* const OPTION_CLIPBOARD("optionClipboard"); // "Clipboard" popup option. +const char* const OPTION_SELECT_WORD = "option-select_word"; // "Select Word" popup option. +const char* const OPTION_SELECT_ALL("option-select_all"); // "Select All" popup option. +const char* const OPTION_CUT("optionCut"); // "Cut" popup option. +const char* const OPTION_COPY("optionCopy"); // "Copy" popup option. +const char* const OPTION_PASTE("optionPaste"); // "Paste" popup option. +const char* const OPTION_CLIPBOARD("optionClipboard"); // "Clipboard" popup option. -const std::string IDS_LTR( "IDS_LTR" ); -const std::string RTL_DIRECTION( "RTL" ); +const std::string IDS_LTR("IDS_LTR"); +const std::string RTL_DIRECTION("RTL"); BaseHandle Create() { - return Toolkit::TextSelectionPopup::New( NULL ); + return Toolkit::TextSelectionPopup::New(NULL); } // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextSelectionPopup, Toolkit::Control, Create ); - -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupMaxSize", VECTOR2, POPUP_MAX_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupMinSize", VECTOR2, POPUP_MIN_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "optionMaxSize", VECTOR2, OPTION_MAX_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "optionMinSize", VECTOR2, OPTION_MIN_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "optionDividerSize", VECTOR2, OPTION_DIVIDER_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupClipboardButtonImage", STRING, POPUP_CLIPBOARD_BUTTON_ICON_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupCutButtonImage", STRING, POPUP_CUT_BUTTON_ICON_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupCopyButtonImage", STRING, POPUP_COPY_BUTTON_ICON_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupPasteButtonImage", STRING, POPUP_PASTE_BUTTON_ICON_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupSelectButtonImage", STRING, POPUP_SELECT_BUTTON_ICON_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupSelectAllButtonImage", STRING, POPUP_SELECT_ALL_BUTTON_ICON_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupDividerColor", VECTOR4, POPUP_DIVIDER_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupIconColor", VECTOR4, POPUP_ICON_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupPressedColor", VECTOR4, POPUP_PRESSED_COLOR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupPressedImage", STRING, POPUP_PRESSED_IMAGE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupFadeInDuration", FLOAT, POPUP_FADE_IN_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "popupFadeOutDuration", FLOAT, POPUP_FADE_OUT_DURATION ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionPopup, "backgroundBorder", MAP, BACKGROUND_BORDER ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextSelectionPopup, Toolkit::Control, Create); + +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupMaxSize", VECTOR2, POPUP_MAX_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupMinSize", VECTOR2, POPUP_MIN_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "optionMaxSize", VECTOR2, OPTION_MAX_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "optionMinSize", VECTOR2, OPTION_MIN_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "optionDividerSize", VECTOR2, OPTION_DIVIDER_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupClipboardButtonImage", STRING, POPUP_CLIPBOARD_BUTTON_ICON_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupCutButtonImage", STRING, POPUP_CUT_BUTTON_ICON_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupCopyButtonImage", STRING, POPUP_COPY_BUTTON_ICON_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupPasteButtonImage", STRING, POPUP_PASTE_BUTTON_ICON_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupSelectButtonImage", STRING, POPUP_SELECT_BUTTON_ICON_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupSelectAllButtonImage", STRING, POPUP_SELECT_ALL_BUTTON_ICON_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupDividerColor", VECTOR4, POPUP_DIVIDER_COLOR) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupIconColor", VECTOR4, POPUP_ICON_COLOR) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupPressedColor", VECTOR4, POPUP_PRESSED_COLOR) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupPressedImage", STRING, POPUP_PRESSED_IMAGE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupFadeInDuration", FLOAT, POPUP_FADE_IN_DURATION) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "popupFadeOutDuration", FLOAT, POPUP_FADE_OUT_DURATION) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionPopup, "backgroundBorder", MAP, BACKGROUND_BORDER) DALI_TYPE_REGISTRATION_END() } // namespace - -Dali::Toolkit::TextSelectionPopup TextSelectionPopup::New( TextSelectionPopupCallbackInterface* callbackInterface ) +Dali::Toolkit::TextSelectionPopup TextSelectionPopup::New(TextSelectionPopupCallbackInterface* callbackInterface) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextSelectionPopup::New\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextSelectionPopup::New\n"); - // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< TextSelectionPopup > impl = new TextSelectionPopup( callbackInterface ); + // Create the implementation, temporarily owned by this handle on stack + IntrusivePtr impl = new TextSelectionPopup(callbackInterface); // Pass ownership to CustomActor handle - Dali::Toolkit::TextSelectionPopup handle( *impl ); + Dali::Toolkit::TextSelectionPopup handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -146,166 +142,166 @@ Dali::Toolkit::TextSelectionPopup TextSelectionPopup::New( TextSelectionPopupCal return handle; } -void TextSelectionPopup::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void TextSelectionPopup::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast(Dali::BaseHandle(object)); - if( selectionPopup ) + if(selectionPopup) { - TextSelectionPopup& impl( GetImpl( selectionPopup ) ); + TextSelectionPopup& impl(GetImpl(selectionPopup)); - switch( index ) + switch(index) { case Toolkit::TextSelectionPopup::Property::POPUP_MAX_SIZE: { - impl.SetDimensionToCustomise( POPUP_MAXIMUM_SIZE, value.Get< Vector2 >() ); - break; + impl.SetDimensionToCustomise(POPUP_MAXIMUM_SIZE, value.Get()); + break; } case Toolkit::TextSelectionPopup::Property::OPTION_MAX_SIZE: { - impl.SetDimensionToCustomise( OPTION_MAXIMUM_SIZE, value.Get< Vector2 >() ); + impl.SetDimensionToCustomise(OPTION_MAXIMUM_SIZE, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::OPTION_MIN_SIZE: { - impl.SetDimensionToCustomise( OPTION_MINIMUM_SIZE, value.Get< Vector2>() ); + impl.SetDimensionToCustomise(OPTION_MINIMUM_SIZE, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::OPTION_DIVIDER_SIZE: { - impl.SetDimensionToCustomise( OPTION_DIVIDER_SIZE, value.Get< Vector2>() ); + impl.SetDimensionToCustomise(OPTION_DIVIDER_SIZE, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_CLIPBOARD_BUTTON_ICON_IMAGE: { - impl.SetButtonImage( Toolkit::TextSelectionPopup::CLIPBOARD, value.Get< std::string >() ); + impl.SetButtonImage(Toolkit::TextSelectionPopup::CLIPBOARD, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_CUT_BUTTON_ICON_IMAGE: { - impl.SetButtonImage( Toolkit::TextSelectionPopup::CUT, value.Get< std::string >() ); + impl.SetButtonImage(Toolkit::TextSelectionPopup::CUT, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_COPY_BUTTON_ICON_IMAGE: { - impl.SetButtonImage( Toolkit::TextSelectionPopup::COPY, value.Get< std::string >() ); + impl.SetButtonImage(Toolkit::TextSelectionPopup::COPY, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_PASTE_BUTTON_ICON_IMAGE: { - impl.SetButtonImage( Toolkit::TextSelectionPopup::PASTE, value.Get< std::string >() ); + impl.SetButtonImage(Toolkit::TextSelectionPopup::PASTE, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_BUTTON_ICON_IMAGE: { - impl.SetButtonImage( Toolkit::TextSelectionPopup::SELECT, value.Get< std::string >() ); + impl.SetButtonImage(Toolkit::TextSelectionPopup::SELECT, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_ALL_BUTTON_ICON_IMAGE: { - impl.SetButtonImage( Toolkit::TextSelectionPopup::SELECT_ALL, value.Get< std::string >() ); + impl.SetButtonImage(Toolkit::TextSelectionPopup::SELECT_ALL, value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_DIVIDER_COLOR: { - impl.mDividerColor = value.Get< Vector4 >(); + impl.mDividerColor = value.Get(); break; } case Toolkit::TextSelectionPopup::Property::POPUP_ICON_COLOR: { - impl.mIconColor = value.Get< Vector4 >(); + impl.mIconColor = value.Get(); break; } case Toolkit::TextSelectionPopup::Property::POPUP_PRESSED_COLOR: { - impl.mPressedColor = value.Get< Vector4 >(); + impl.mPressedColor = value.Get(); break; } case Toolkit::TextSelectionPopup::Property::POPUP_PRESSED_IMAGE: { - impl.SetPressedImage( value.Get< std::string >() ); + impl.SetPressedImage(value.Get()); break; } case Toolkit::TextSelectionPopup::Property::POPUP_FADE_IN_DURATION: { - impl.mFadeInDuration = value.Get < float >(); + impl.mFadeInDuration = value.Get(); break; } case Toolkit::TextSelectionPopup::Property::POPUP_FADE_OUT_DURATION: { - impl.mFadeOutDuration = value.Get < float >(); + impl.mFadeOutDuration = value.Get(); break; } case Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER: { Property::Map map = value.Get(); - impl.CreateBackgroundBorder( map ); + impl.CreateBackgroundBorder(map); break; } } // switch - } // TextSelectionPopup + } // TextSelectionPopup } -Property::Value TextSelectionPopup::GetProperty( BaseObject* object, Property::Index index ) +Property::Value TextSelectionPopup::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextSelectionPopup selectionPopup = Toolkit::TextSelectionPopup::DownCast(Dali::BaseHandle(object)); - if( selectionPopup ) + if(selectionPopup) { - TextSelectionPopup& impl( GetImpl( selectionPopup ) ); + TextSelectionPopup& impl(GetImpl(selectionPopup)); - switch( index ) + switch(index) { case Toolkit::TextSelectionPopup::Property::POPUP_MAX_SIZE: { - value = impl.GetDimensionToCustomise( POPUP_MAXIMUM_SIZE ); + value = impl.GetDimensionToCustomise(POPUP_MAXIMUM_SIZE); break; } case Toolkit::TextSelectionPopup::Property::OPTION_MAX_SIZE: { - value = impl.GetDimensionToCustomise( OPTION_MAXIMUM_SIZE ); + value = impl.GetDimensionToCustomise(OPTION_MAXIMUM_SIZE); break; } case Toolkit::TextSelectionPopup::Property::OPTION_MIN_SIZE: { - value = impl.GetDimensionToCustomise( OPTION_MINIMUM_SIZE ); + value = impl.GetDimensionToCustomise(OPTION_MINIMUM_SIZE); break; } case Toolkit::TextSelectionPopup::Property::OPTION_DIVIDER_SIZE: { - value = impl.GetDimensionToCustomise( OPTION_DIVIDER_SIZE ); + value = impl.GetDimensionToCustomise(OPTION_DIVIDER_SIZE); break; } case Toolkit::TextSelectionPopup::Property::POPUP_CLIPBOARD_BUTTON_ICON_IMAGE: { - value = impl.GetButtonImage( Toolkit::TextSelectionPopup::CLIPBOARD ); + value = impl.GetButtonImage(Toolkit::TextSelectionPopup::CLIPBOARD); break; } case Toolkit::TextSelectionPopup::Property::POPUP_CUT_BUTTON_ICON_IMAGE: { - value = impl.GetButtonImage( Toolkit::TextSelectionPopup::CUT ); + value = impl.GetButtonImage(Toolkit::TextSelectionPopup::CUT); break; } case Toolkit::TextSelectionPopup::Property::POPUP_COPY_BUTTON_ICON_IMAGE: { - value = impl.GetButtonImage( Toolkit::TextSelectionPopup::COPY ); + value = impl.GetButtonImage(Toolkit::TextSelectionPopup::COPY); break; } case Toolkit::TextSelectionPopup::Property::POPUP_PASTE_BUTTON_ICON_IMAGE: { - value = impl.GetButtonImage( Toolkit::TextSelectionPopup::PASTE ); + value = impl.GetButtonImage(Toolkit::TextSelectionPopup::PASTE); break; } case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_BUTTON_ICON_IMAGE: { - value = impl.GetButtonImage( Toolkit::TextSelectionPopup::SELECT ); + value = impl.GetButtonImage(Toolkit::TextSelectionPopup::SELECT); break; } case Toolkit::TextSelectionPopup::Property::POPUP_SELECT_ALL_BUTTON_ICON_IMAGE: { - value = impl.GetButtonImage( Toolkit::TextSelectionPopup::SELECT_ALL ); + value = impl.GetButtonImage(Toolkit::TextSelectionPopup::SELECT_ALL); break; } case Toolkit::TextSelectionPopup::Property::POPUP_PRESSED_IMAGE: @@ -325,11 +321,11 @@ Property::Value TextSelectionPopup::GetProperty( BaseObject* object, Property::I } case Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER: { - Property::Map map; - Toolkit::Visual::Base visual = DevelControl::GetVisual( impl, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER ); - if( visual ) + Property::Map map; + Toolkit::Visual::Base visual = DevelControl::GetVisual(impl, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER); + if(visual) { - visual.CreatePropertyMap( map ); + visual.CreatePropertyMap(map); } value = map; break; @@ -339,30 +335,30 @@ Property::Value TextSelectionPopup::GetProperty( BaseObject* object, Property::I return value; } -void TextSelectionPopup::EnableButtons( Toolkit::TextSelectionPopup::Buttons buttonsToEnable ) +void TextSelectionPopup::EnableButtons(Toolkit::TextSelectionPopup::Buttons buttonsToEnable) { mEnabledButtons = buttonsToEnable; mButtonsChanged = true; } -void TextSelectionPopup::RaiseAbove( Actor target ) +void TextSelectionPopup::RaiseAbove(Actor target) { - if( mToolbar ) + if(mToolbar) { - mToolbar.RaiseAbove( target ); + mToolbar.RaiseAbove(target); } } void TextSelectionPopup::ShowPopup() { - if( ( !mPopupShowing || mButtonsChanged ) && - ( Toolkit::TextSelectionPopup::NONE != mEnabledButtons ) ) + if((!mPopupShowing || mButtonsChanged) && + (Toolkit::TextSelectionPopup::NONE != mEnabledButtons)) { Actor self = Self(); - AddPopupOptionsToToolbar( mShowIcons, mShowCaptions ); + AddPopupOptionsToToolbar(mShowIcons, mShowCaptions); - Animation animation = Animation::New( mFadeInDuration ); - animation.AnimateTo( Property(self, Actor::Property::COLOR_ALPHA), 1.0f ); + Animation animation = Animation::New(mFadeInDuration); + animation.AnimateTo(Property(self, Actor::Property::COLOR_ALPHA), 1.0f); animation.Play(); mPopupShowing = true; } @@ -370,132 +366,132 @@ void TextSelectionPopup::ShowPopup() void TextSelectionPopup::HidePopup() { - if ( mPopupShowing ) + if(mPopupShowing) { - mPopupShowing = false; - Actor self = Self(); - Animation animation = Animation::New( mFadeOutDuration ); - animation.AnimateTo( Property(self, Actor::Property::COLOR_ALPHA), 0.0f ); - animation.FinishedSignal().Connect( this, &TextSelectionPopup::HideAnimationFinished ); + mPopupShowing = false; + Actor self = Self(); + Animation animation = Animation::New(mFadeOutDuration); + animation.AnimateTo(Property(self, Actor::Property::COLOR_ALPHA), 0.0f); + animation.FinishedSignal().Connect(this, &TextSelectionPopup::HideAnimationFinished); animation.Play(); } } void TextSelectionPopup::OnInitialize() { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::OnInitialize\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::OnInitialize\n"); Actor self = Self(); - self.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS ); - self.SetProperty( Actor::Property::COLOR_ALPHA, 0.0f ); - - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::DIALOG, true ) ); - } ); - + self.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS); + self.SetProperty(Actor::Property::COLOR_ALPHA, 0.0f); + + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::DIALOG, true)); + }); + //Enable highightability - self.SetProperty( Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true ); + self.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true); } -void TextSelectionPopup::HideAnimationFinished( Animation& animation ) +void TextSelectionPopup::HideAnimationFinished(Animation& animation) { Actor self = Self(); - if ( !mPopupShowing ) // During the Hide/Fade animation there could be a call to Show the Popup again, mPopupShowing will be true in this case. + if(!mPopupShowing) // During the Hide/Fade animation there could be a call to Show the Popup again, mPopupShowing will be true in this case. { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::HideAnimationFinished\n" ); - UnparentAndReset( mToolbar ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::HideAnimationFinished\n"); + UnparentAndReset(mToolbar); } } -bool TextSelectionPopup::OnCutButtonPressed( Toolkit::Button button ) +bool TextSelectionPopup::OnCutButtonPressed(Toolkit::Button button) { - if( mCallbackInterface ) + if(mCallbackInterface) { - mCallbackInterface->TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT ); + mCallbackInterface->TextPopupButtonTouched(Toolkit::TextSelectionPopup::CUT); } return true; } -bool TextSelectionPopup::OnCopyButtonPressed( Toolkit::Button button ) +bool TextSelectionPopup::OnCopyButtonPressed(Toolkit::Button button) { - if( mCallbackInterface ) + if(mCallbackInterface) { - mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::COPY ); + mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::COPY); } return true; } -bool TextSelectionPopup::OnPasteButtonPressed( Toolkit::Button button ) +bool TextSelectionPopup::OnPasteButtonPressed(Toolkit::Button button) { - if( mCallbackInterface ) + if(mCallbackInterface) { - mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::PASTE ); + mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::PASTE); } return true; } -bool TextSelectionPopup::OnSelectButtonPressed( Toolkit::Button button ) +bool TextSelectionPopup::OnSelectButtonPressed(Toolkit::Button button) { - if( mCallbackInterface ) + if(mCallbackInterface) { - mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::SELECT ); + mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::SELECT); } return true; } -bool TextSelectionPopup::OnSelectAllButtonPressed( Toolkit::Button button ) +bool TextSelectionPopup::OnSelectAllButtonPressed(Toolkit::Button button) { - if( mCallbackInterface ) + if(mCallbackInterface) { - mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::SELECT_ALL ); + mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::SELECT_ALL); } return true; } -bool TextSelectionPopup::OnClipboardButtonPressed( Toolkit::Button button ) +bool TextSelectionPopup::OnClipboardButtonPressed(Toolkit::Button button) { - if( mCallbackInterface ) + if(mCallbackInterface) { - mCallbackInterface->TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::CLIPBOARD ); + mCallbackInterface->TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::CLIPBOARD); } return true; } -void TextSelectionPopup::SetDimensionToCustomise( const PopupCustomisations& settingToCustomise, const Size& dimension ) +void TextSelectionPopup::SetDimensionToCustomise(const PopupCustomisations& settingToCustomise, const Size& dimension) { - switch( settingToCustomise ) + switch(settingToCustomise) { - case POPUP_MAXIMUM_SIZE : + case POPUP_MAXIMUM_SIZE: { mPopupMaxSize = dimension; - if ( mToolbar ) + if(mToolbar) { - mToolbar.SetProperty( Toolkit::TextSelectionToolbar::Property::MAX_SIZE, dimension ); + mToolbar.SetProperty(Toolkit::TextSelectionToolbar::Property::MAX_SIZE, dimension); } break; } - case OPTION_MAXIMUM_SIZE : + case OPTION_MAXIMUM_SIZE: { mOptionMaxSize = dimension; // Option max size not currently currently supported break; } - case OPTION_MINIMUM_SIZE : + case OPTION_MINIMUM_SIZE: { mOptionMinSize = dimension; // Option min size not currently currently supported break; } - case OPTION_DIVIDER_SIZE : + case OPTION_DIVIDER_SIZE: { mOptionDividerSize = dimension; - if ( mToolbar ) + if(mToolbar) { // Resize Dividers not currently supported } @@ -504,30 +500,30 @@ void TextSelectionPopup::SetDimensionToCustomise( const PopupCustomisations& set } // switch } -Size TextSelectionPopup::GetDimensionToCustomise( const PopupCustomisations& settingToCustomise ) const +Size TextSelectionPopup::GetDimensionToCustomise(const PopupCustomisations& settingToCustomise) const { - switch( settingToCustomise ) + switch(settingToCustomise) { - case POPUP_MAXIMUM_SIZE : + case POPUP_MAXIMUM_SIZE: { - if ( mToolbar ) + if(mToolbar) { - return mToolbar.GetProperty( Toolkit::TextSelectionToolbar::Property::MAX_SIZE ).Get< Vector2 >(); + return mToolbar.GetProperty(Toolkit::TextSelectionToolbar::Property::MAX_SIZE).Get(); } else { return mPopupMaxSize; } } - case OPTION_MAXIMUM_SIZE : + case OPTION_MAXIMUM_SIZE: { return mOptionMaxSize; } - case OPTION_MINIMUM_SIZE : + case OPTION_MINIMUM_SIZE: { return mOptionMinSize; } - case OPTION_DIVIDER_SIZE : + case OPTION_DIVIDER_SIZE: { return mOptionDividerSize; } @@ -536,50 +532,50 @@ Size TextSelectionPopup::GetDimensionToCustomise( const PopupCustomisations& set return Size::ZERO; } -void TextSelectionPopup::SetButtonImage( Toolkit::TextSelectionPopup::Buttons button, const std::string& image ) -{ - switch ( button ) - { - case Toolkit::TextSelectionPopup::CLIPBOARD: - { - mClipboardIconImage = image; - break; - } - case Toolkit::TextSelectionPopup::CUT : - { - mCutIconImage = image; - break; - } - case Toolkit::TextSelectionPopup::COPY : - { - mCopyIconImage = image; - break; - } - case Toolkit::TextSelectionPopup::PASTE : - { - mPasteIconImage = image; - break; - } - case Toolkit::TextSelectionPopup::SELECT : - { - mSelectIconImage = image; - break; - } - case Toolkit::TextSelectionPopup::SELECT_ALL : - { - mSelectAllIconImage = image; - break; - } - default : - { - DALI_ASSERT_DEBUG( "TextSelectionPopup SetPopupImage Unknown Button" ); - } - } // switch +void TextSelectionPopup::SetButtonImage(Toolkit::TextSelectionPopup::Buttons button, const std::string& image) +{ + switch(button) + { + case Toolkit::TextSelectionPopup::CLIPBOARD: + { + mClipboardIconImage = image; + break; + } + case Toolkit::TextSelectionPopup::CUT: + { + mCutIconImage = image; + break; + } + case Toolkit::TextSelectionPopup::COPY: + { + mCopyIconImage = image; + break; + } + case Toolkit::TextSelectionPopup::PASTE: + { + mPasteIconImage = image; + break; + } + case Toolkit::TextSelectionPopup::SELECT: + { + mSelectIconImage = image; + break; + } + case Toolkit::TextSelectionPopup::SELECT_ALL: + { + mSelectAllIconImage = image; + break; + } + default: + { + DALI_ASSERT_DEBUG("TextSelectionPopup SetPopupImage Unknown Button"); + } + } // switch } -const std::string& TextSelectionPopup::GetButtonImage( Toolkit::TextSelectionPopup::Buttons button ) const +const std::string& TextSelectionPopup::GetButtonImage(Toolkit::TextSelectionPopup::Buttons button) const { - switch ( button ) + switch(button) { case Toolkit::TextSelectionPopup::CLIPBOARD: { @@ -617,12 +613,12 @@ const std::string& TextSelectionPopup::GetButtonImage( Toolkit::TextSelectionPop } } // switch - DALI_ASSERT_DEBUG( "TextSelectionPopup GetPopupImage Unknown Button" ); + DALI_ASSERT_DEBUG("TextSelectionPopup GetPopupImage Unknown Button"); static std::string empty; return empty; } -void TextSelectionPopup::SetPressedImage( const std::string& filename ) +void TextSelectionPopup::SetPressedImage(const std::string& filename) { mPressedImage = filename; } @@ -632,238 +628,238 @@ std::string TextSelectionPopup::GetPressedImage() const return mPressedImage; } - void TextSelectionPopup::CreateOrderedListOfPopupOptions() - { - mOrderListOfButtons.clear(); - mOrderListOfButtons.reserve( 8u ); - - // Create button for each possible option using Option priority - mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::CUT, mCutOptionPriority, OPTION_CUT, POPUP_CUT_STRING , 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::CUT) ) ); - mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::COPY, mCopyOptionPriority, OPTION_COPY, POPUP_COPY_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::COPY) ) ); - mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::PASTE, mPasteOptionPriority, OPTION_PASTE, POPUP_PASTE_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::PASTE) ) ); - mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::SELECT, mSelectOptionPriority, OPTION_SELECT_WORD, POPUP_SELECT_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::SELECT) ) ); - mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::SELECT_ALL, mSelectAllOptionPriority, OPTION_SELECT_ALL, POPUP_SELECT_ALL_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::SELECT_ALL) ) ); - mOrderListOfButtons.push_back( ButtonRequirement( Toolkit::TextSelectionPopup::CLIPBOARD, mClipboardOptionPriority, OPTION_CLIPBOARD, POPUP_CLIPBOARD_STRING, 0 != ( mEnabledButtons & Toolkit::TextSelectionPopup::CLIPBOARD) ) ); - - // Sort the buttons according their priorities. - std::sort( mOrderListOfButtons.begin(), mOrderListOfButtons.end(), TextSelectionPopup::ButtonPriorityCompare() ); - } - - void TextSelectionPopup::AddOption( const ButtonRequirement& button, bool showDivider, bool showIcons, bool showCaption ) - { - // 1. Create a option. - DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::AddOption\n" ); - - Toolkit::PushButton option = Toolkit::PushButton::New(); - option.SetProperty( Dali::Actor::Property::NAME, button.name ); - option.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS ); - - switch( button.id ) - { - case Toolkit::TextSelectionPopup::CUT: - { - option.ClickedSignal().Connect( this, &TextSelectionPopup::OnCutButtonPressed ); - break; - } - case Toolkit::TextSelectionPopup::COPY: - { - option.ClickedSignal().Connect( this, &TextSelectionPopup::OnCopyButtonPressed ); - break; - } - case Toolkit::TextSelectionPopup::PASTE: - { - option.ClickedSignal().Connect( this, &TextSelectionPopup::OnPasteButtonPressed ); - break; - } - case Toolkit::TextSelectionPopup::SELECT: - { - option.ClickedSignal().Connect( this, &TextSelectionPopup::OnSelectButtonPressed ); - break; - } - case Toolkit::TextSelectionPopup::SELECT_ALL: - { - option.ClickedSignal().Connect( this, &TextSelectionPopup::OnSelectAllButtonPressed ); - break; - } - case Toolkit::TextSelectionPopup::CLIPBOARD: - { - option.ClickedSignal().Connect( this, &TextSelectionPopup::OnClipboardButtonPressed ); - break; - } - case Toolkit::TextSelectionPopup::NONE: - { - // Nothing to do: - break; - } - } - - // 2. Set the options contents. - if( showCaption ) - { - // PushButton layout properties. - option.SetProperty( Toolkit::PushButton::Property::LABEL_PADDING, Vector4( 24.0f, 24.0f, 14.0f, 14.0f ) ); - - // Label properties. - Property::Map buttonLabelProperties; - buttonLabelProperties.Insert( Toolkit::TextVisual::Property::TEXT, button.caption ); - option.SetProperty( Toolkit::Button::Property::LABEL, buttonLabelProperties ); - } - if( showIcons ) - { - option.SetProperty( Toolkit::PushButton::Property::ICON_PADDING, Vector4( 10.0f, 10.0f, 10.0f, 10.0f ) ); - option.SetProperty( Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT, "BOTTOM" ); - - // TODO: This is temporarily disabled until the text-selection-popup image API is changed to strings. - //option.SetProperty( Toolkit::Button::Property::SELECTED_VISUAL, button.icon ); - //option.SetProperty( Toolkit::Button::Property::UNSELECTED_VISUAL, button.icon ); - } - - // 3. Set the normal option image (blank / Transparent). - option.SetProperty( Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, "" ); - - // 4. Set the pressed option image. - Property::Value selectedBackgroundValue( mPressedImage ); - if( mPressedImage.empty() ) - { - // The image can be blank, the color can be used in that case. - selectedBackgroundValue = Property::Value{ { Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR }, - { Toolkit::ColorVisual::Property::MIX_COLOR, mPressedColor } }; - } - option.SetProperty( Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, selectedBackgroundValue ); - option.SetProperty( Toolkit::Control::Property::STYLE_NAME, TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME ); - - // 5 Add option to tool bar - mToolbar.AddOption( option ); - - // 6. Add the divider - if( showDivider ) - { - const Size size( mOptionDividerSize.width, 0.0f ); // Height FILL_TO_PARENT - - Toolkit::Control divider = Toolkit::Control::New(); +void TextSelectionPopup::CreateOrderedListOfPopupOptions() +{ + mOrderListOfButtons.clear(); + mOrderListOfButtons.reserve(8u); + + // Create button for each possible option using Option priority + mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::CUT, mCutOptionPriority, OPTION_CUT, POPUP_CUT_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::CUT))); + mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::COPY, mCopyOptionPriority, OPTION_COPY, POPUP_COPY_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::COPY))); + mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::PASTE, mPasteOptionPriority, OPTION_PASTE, POPUP_PASTE_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::PASTE))); + mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::SELECT, mSelectOptionPriority, OPTION_SELECT_WORD, POPUP_SELECT_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::SELECT))); + mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::SELECT_ALL, mSelectAllOptionPriority, OPTION_SELECT_ALL, POPUP_SELECT_ALL_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::SELECT_ALL))); + mOrderListOfButtons.push_back(ButtonRequirement(Toolkit::TextSelectionPopup::CLIPBOARD, mClipboardOptionPriority, OPTION_CLIPBOARD, POPUP_CLIPBOARD_STRING, 0 != (mEnabledButtons & Toolkit::TextSelectionPopup::CLIPBOARD))); + + // Sort the buttons according their priorities. + std::sort(mOrderListOfButtons.begin(), mOrderListOfButtons.end(), TextSelectionPopup::ButtonPriorityCompare()); +} + +void TextSelectionPopup::AddOption(const ButtonRequirement& button, bool showDivider, bool showIcons, bool showCaption) +{ + // 1. Create a option. + DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::AddOption\n"); + + Toolkit::PushButton option = Toolkit::PushButton::New(); + option.SetProperty(Dali::Actor::Property::NAME, button.name); + option.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS); + + switch(button.id) + { + case Toolkit::TextSelectionPopup::CUT: + { + option.ClickedSignal().Connect(this, &TextSelectionPopup::OnCutButtonPressed); + break; + } + case Toolkit::TextSelectionPopup::COPY: + { + option.ClickedSignal().Connect(this, &TextSelectionPopup::OnCopyButtonPressed); + break; + } + case Toolkit::TextSelectionPopup::PASTE: + { + option.ClickedSignal().Connect(this, &TextSelectionPopup::OnPasteButtonPressed); + break; + } + case Toolkit::TextSelectionPopup::SELECT: + { + option.ClickedSignal().Connect(this, &TextSelectionPopup::OnSelectButtonPressed); + break; + } + case Toolkit::TextSelectionPopup::SELECT_ALL: + { + option.ClickedSignal().Connect(this, &TextSelectionPopup::OnSelectAllButtonPressed); + break; + } + case Toolkit::TextSelectionPopup::CLIPBOARD: + { + option.ClickedSignal().Connect(this, &TextSelectionPopup::OnClipboardButtonPressed); + break; + } + case Toolkit::TextSelectionPopup::NONE: + { + // Nothing to do: + break; + } + } + + // 2. Set the options contents. + if(showCaption) + { + // PushButton layout properties. + option.SetProperty(Toolkit::PushButton::Property::LABEL_PADDING, Vector4(24.0f, 24.0f, 14.0f, 14.0f)); + + // Label properties. + Property::Map buttonLabelProperties; + buttonLabelProperties.Insert(Toolkit::TextVisual::Property::TEXT, button.caption); + option.SetProperty(Toolkit::Button::Property::LABEL, buttonLabelProperties); + } + if(showIcons) + { + option.SetProperty(Toolkit::PushButton::Property::ICON_PADDING, Vector4(10.0f, 10.0f, 10.0f, 10.0f)); + option.SetProperty(Toolkit::DevelButton::Property::LABEL_RELATIVE_ALIGNMENT, "BOTTOM"); + + // TODO: This is temporarily disabled until the text-selection-popup image API is changed to strings. + //option.SetProperty( Toolkit::Button::Property::SELECTED_VISUAL, button.icon ); + //option.SetProperty( Toolkit::Button::Property::UNSELECTED_VISUAL, button.icon ); + } + + // 3. Set the normal option image (blank / Transparent). + option.SetProperty(Toolkit::Button::Property::UNSELECTED_BACKGROUND_VISUAL, ""); + + // 4. Set the pressed option image. + Property::Value selectedBackgroundValue(mPressedImage); + if(mPressedImage.empty()) + { + // The image can be blank, the color can be used in that case. + selectedBackgroundValue = Property::Value{{Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR}, + {Toolkit::ColorVisual::Property::MIX_COLOR, mPressedColor}}; + } + option.SetProperty(Toolkit::Button::Property::SELECTED_BACKGROUND_VISUAL, selectedBackgroundValue); + option.SetProperty(Toolkit::Control::Property::STYLE_NAME, TEXT_SELECTION_POPUP_BUTTON_STYLE_NAME); + + // 5 Add option to tool bar + mToolbar.AddOption(option); + + // 6. Add the divider + if(showDivider) + { + const Size size(mOptionDividerSize.width, 0.0f); // Height FILL_TO_PARENT + + Toolkit::Control divider = Toolkit::Control::New(); #ifdef DECORATOR_DEBUG - divider.SetProperty( Dali::Actor::Property::NAME,"Text's popup divider"); + divider.SetProperty(Dali::Actor::Property::NAME, "Text's popup divider"); #endif - divider.SetProperty( Actor::Property::SIZE, size ); - divider.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT ); - divider.SetBackgroundColor( mDividerColor ); - mToolbar.AddDivider( divider ); - } - } - - std::size_t TextSelectionPopup::GetNumberOfEnabledOptions() const - { - std::size_t numberOfOptions = 0u; - for( std::vector::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); ( it != endIt ); ++it ) - { - const ButtonRequirement& button( *it ); - if( button.enabled ) - { - ++numberOfOptions; - } - } - - return numberOfOptions; - } - - void TextSelectionPopup::AddPopupOptionsToToolbar( bool showIcons, bool showCaptions ) - { - DALI_LOG_INFO( gLogFilter, Debug::General, "TextSelectionPopup::AddPopupOptionsToToolbar\n" ); - - CreateOrderedListOfPopupOptions(); - - mButtonsChanged = false; - UnparentAndReset( mToolbar); - - if( !mToolbar ) - { - Actor self = Self(); - mToolbar = Toolkit::TextSelectionToolbar::New(); - if ( mPopupMaxSize != Vector2::ZERO ) // If PopupMaxSize property set then apply to Toolbar. Toolbar currently is not retriving this from json - { - mToolbar.SetProperty( Toolkit::TextSelectionToolbar::Property::MAX_SIZE, mPopupMaxSize ); - } - mToolbar.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + divider.SetProperty(Actor::Property::SIZE, size); + divider.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::HEIGHT); + divider.SetBackgroundColor(mDividerColor); + mToolbar.AddDivider(divider); + } +} + +std::size_t TextSelectionPopup::GetNumberOfEnabledOptions() const +{ + std::size_t numberOfOptions = 0u; + for(std::vector::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); (it != endIt); ++it) + { + const ButtonRequirement& button(*it); + if(button.enabled) + { + ++numberOfOptions; + } + } + + return numberOfOptions; +} + +void TextSelectionPopup::AddPopupOptionsToToolbar(bool showIcons, bool showCaptions) +{ + DALI_LOG_INFO(gLogFilter, Debug::General, "TextSelectionPopup::AddPopupOptionsToToolbar\n"); + + CreateOrderedListOfPopupOptions(); + + mButtonsChanged = false; + UnparentAndReset(mToolbar); + + if(!mToolbar) + { + Actor self = Self(); + mToolbar = Toolkit::TextSelectionToolbar::New(); + if(mPopupMaxSize != Vector2::ZERO) // If PopupMaxSize property set then apply to Toolbar. Toolbar currently is not retriving this from json + { + mToolbar.SetProperty(Toolkit::TextSelectionToolbar::Property::MAX_SIZE, mPopupMaxSize); + } + mToolbar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); #ifdef DECORATOR_DEBUG - mToolbar.SetProperty( Dali::Actor::Property::NAME,"TextSelectionToolbar"); + mToolbar.SetProperty(Dali::Actor::Property::NAME, "TextSelectionToolbar"); #endif - self.Add( mToolbar ); - } + self.Add(mToolbar); + } - // Whether to mirror the list of buttons (for right to left languages) - bool mirror = false; + // Whether to mirror the list of buttons (for right to left languages) + bool mirror = false; #if defined(__GLIBC__) - char* idsLtr = GET_LOCALE_TEXT( IDS_LTR.c_str() ); - if( NULL != idsLtr ) - { - mirror = ( 0 == strcmp( idsLtr, RTL_DIRECTION.c_str() ) ); - - if( mirror ) - { - std::reverse( mOrderListOfButtons.begin(), mOrderListOfButtons.end() ); - } - } + char* idsLtr = GET_LOCALE_TEXT(IDS_LTR.c_str()); + if(NULL != idsLtr) + { + mirror = (0 == strcmp(idsLtr, RTL_DIRECTION.c_str())); + + if(mirror) + { + std::reverse(mOrderListOfButtons.begin(), mOrderListOfButtons.end()); + } + } #endif - // Iterate list of buttons and add active ones to Toolbar - std::size_t numberOfOptionsRequired = GetNumberOfEnabledOptions(); - std::size_t numberOfOptionsAdded = 0u; - for( std::vector::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); ( it != endIt ); ++it ) - { - const ButtonRequirement& button( *it ); - if ( button.enabled ) - { - numberOfOptionsAdded++; - AddOption( button, ( numberOfOptionsAdded < numberOfOptionsRequired ) , showIcons, showCaptions ); - } - } - - if( mirror ) - { - mToolbar.ScrollTo( Vector2( mPopupMaxSize.x, 0.f ) ); - } - } - -void TextSelectionPopup::CreateBackgroundBorder( Property::Map& propertyMap ) + // Iterate list of buttons and add active ones to Toolbar + std::size_t numberOfOptionsRequired = GetNumberOfEnabledOptions(); + std::size_t numberOfOptionsAdded = 0u; + for(std::vector::const_iterator it = mOrderListOfButtons.begin(), endIt = mOrderListOfButtons.end(); (it != endIt); ++it) + { + const ButtonRequirement& button(*it); + if(button.enabled) + { + numberOfOptionsAdded++; + AddOption(button, (numberOfOptionsAdded < numberOfOptionsRequired), showIcons, showCaptions); + } + } + + if(mirror) + { + mToolbar.ScrollTo(Vector2(mPopupMaxSize.x, 0.f)); + } +} + +void TextSelectionPopup::CreateBackgroundBorder(Property::Map& propertyMap) { // Removes previous image if necessary - DevelControl::UnregisterVisual( *this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER ); + DevelControl::UnregisterVisual(*this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER); - if( ! propertyMap.Empty() ) + if(!propertyMap.Empty()) { - Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual( propertyMap ); + Toolkit::Visual::Base visual = Toolkit::VisualFactory::Get().CreateVisual(propertyMap); - if( visual ) + if(visual) { - DevelControl::RegisterVisual( *this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER, visual, DepthIndex::CONTENT ); + DevelControl::RegisterVisual(*this, Toolkit::TextSelectionPopup::Property::BACKGROUND_BORDER, visual, DepthIndex::CONTENT); } } } -TextSelectionPopup::TextSelectionPopup( TextSelectionPopupCallbackInterface* callbackInterface ) -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +TextSelectionPopup::TextSelectionPopup(TextSelectionPopupCallbackInterface* callbackInterface) +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mToolbar(), mPopupMaxSize(), mOptionMaxSize(), mOptionMinSize(), mOptionDividerSize(), - mEnabledButtons( Toolkit::TextSelectionPopup::NONE ), - mCallbackInterface( callbackInterface ), - mPressedColor( DEFAULT_OPTION_PRESSED_COLOR ), - mDividerColor( Color::WHITE ), - mIconColor( Color::WHITE ), - mSelectOptionPriority( 1 ), - mSelectAllOptionPriority ( 2 ), - mCutOptionPriority ( 4 ), - mCopyOptionPriority ( 3 ), - mPasteOptionPriority ( 5 ), - mClipboardOptionPriority( 6 ), + mEnabledButtons(Toolkit::TextSelectionPopup::NONE), + mCallbackInterface(callbackInterface), + mPressedColor(DEFAULT_OPTION_PRESSED_COLOR), + mDividerColor(Color::WHITE), + mIconColor(Color::WHITE), + mSelectOptionPriority(1), + mSelectAllOptionPriority(2), + mCutOptionPriority(4), + mCopyOptionPriority(3), + mPasteOptionPriority(5), + mClipboardOptionPriority(6), mFadeInDuration(0.0f), mFadeOutDuration(0.0f), - mShowIcons( false ), - mShowCaptions( true ), - mPopupShowing( false ), - mButtonsChanged( false ) + mShowIcons(false), + mShowCaptions(true), + mPopupShowing(false), + mButtonsChanged(false) { } @@ -871,7 +867,6 @@ TextSelectionPopup::~TextSelectionPopup() { } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/controls/text-controls/text-selection-toolbar-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-selection-toolbar-impl.cpp index 792dead..2e1251e 100644 --- a/dali-toolkit/internal/controls/text-controls/text-selection-toolbar-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-selection-toolbar-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,31 +19,27 @@ #include // EXTERNAL INCLUDES -#include #include #include #include #include +#include // INTERNAL INCLUDES -#include #include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -const Dali::Vector2 DEFAULT_SCROLL_BAR_PADDING( 8.0f, 6.0f ); +const Dali::Vector2 DEFAULT_SCROLL_BAR_PADDING(8.0f, 6.0f); BaseHandle Create() { @@ -52,13 +48,13 @@ BaseHandle Create() // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::TextSelectionToolbar, Toolkit::Control, Create ); +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::TextSelectionToolbar, Toolkit::Control, Create); -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "maxSize", VECTOR2, MAX_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "enableOvershoot", BOOLEAN, ENABLE_OVERSHOOT ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "scrollBarPadding", VECTOR2, SCROLL_BAR_PADDING ) -DALI_PROPERTY_REGISTRATION( Toolkit, TextSelectionToolbar, "scrollView", MAP, SCROLL_VIEW ) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "maxSize", VECTOR2, MAX_SIZE) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "enableOvershoot", BOOLEAN, ENABLE_OVERSHOOT) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "enableScrollBar", BOOLEAN, ENABLE_SCROLL_BAR) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "scrollBarPadding", VECTOR2, SCROLL_BAR_PADDING) +DALI_PROPERTY_REGISTRATION(Toolkit, TextSelectionToolbar, "scrollView", MAP, SCROLL_VIEW) DALI_TYPE_REGISTRATION_END() @@ -67,10 +63,10 @@ DALI_TYPE_REGISTRATION_END() Dali::Toolkit::TextSelectionToolbar TextSelectionToolbar::New() { // Create the implementation, temporarily owned by this handle on stack - IntrusivePtr< TextSelectionToolbar > impl = new TextSelectionToolbar(); + IntrusivePtr impl = new TextSelectionToolbar(); // Pass ownership to CustomActor handle - Dali::Toolkit::TextSelectionToolbar handle( *impl ); + Dali::Toolkit::TextSelectionToolbar handle(*impl); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -79,65 +75,65 @@ Dali::Toolkit::TextSelectionToolbar TextSelectionToolbar::New() return handle; } -void TextSelectionToolbar::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void TextSelectionToolbar::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast(Dali::BaseHandle(object)); - if( selectionPopup ) + if(selectionPopup) { - TextSelectionToolbar& impl( GetImpl( selectionPopup ) ); + TextSelectionToolbar& impl(GetImpl(selectionPopup)); - switch( index ) + switch(index) { case Toolkit::TextSelectionToolbar::Property::MAX_SIZE: { - impl.SetPopupMaxSize( value.Get< Vector2 >() ); - break; + impl.SetPopupMaxSize(value.Get()); + break; } case Toolkit::TextSelectionToolbar::Property::ENABLE_OVERSHOOT: { - if( !impl.mScrollView ) + if(!impl.mScrollView) { - impl.mScrollView = Toolkit::ScrollView::New(); + impl.mScrollView = Toolkit::ScrollView::New(); } - impl.mScrollView.SetOvershootEnabled( value.Get< bool >() ); + impl.mScrollView.SetOvershootEnabled(value.Get()); break; } case Toolkit::TextSelectionToolbar::Property::ENABLE_SCROLL_BAR: { - impl.SetUpScrollBar( value.Get< bool >() ); + impl.SetUpScrollBar(value.Get()); break; } case Toolkit::TextSelectionToolbar::Property::SCROLL_BAR_PADDING: { - impl.SetScrollBarPadding( value.Get< Vector2 >() ); + impl.SetScrollBarPadding(value.Get()); break; } case Toolkit::TextSelectionToolbar::Property::SCROLL_VIEW: { // Get a Property::Map from the property if possible. Property::Map setPropertyMap; - if( value.Get( setPropertyMap ) ) + if(value.Get(setPropertyMap)) { - impl.ConfigureScrollview( setPropertyMap ); + impl.ConfigureScrollview(setPropertyMap); } break; } } // switch - } // TextSelectionToolbar + } // TextSelectionToolbar } -Property::Value TextSelectionToolbar::GetProperty( BaseObject* object, Property::Index index ) +Property::Value TextSelectionToolbar::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; - Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast( Dali::BaseHandle( object ) ); + Toolkit::TextSelectionToolbar selectionPopup = Toolkit::TextSelectionToolbar::DownCast(Dali::BaseHandle(object)); - if( selectionPopup ) + if(selectionPopup) { - TextSelectionToolbar& impl( GetImpl( selectionPopup ) ); + TextSelectionToolbar& impl(GetImpl(selectionPopup)); - switch( index ) + switch(index) { case Toolkit::TextSelectionToolbar::Property::MAX_SIZE: { @@ -168,32 +164,32 @@ void TextSelectionToolbar::OnInitialize() { SetUp(); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TOOL_BAR )); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::TOOL_BAR)); + }); } -void TextSelectionToolbar::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void TextSelectionToolbar::OnRelayout(const Vector2& size, RelayoutContainer& container) { - float width = std::max ( mTableOfButtons.GetNaturalSize().width, size.width ); - mRulerX->SetDomain( RulerDomain( 0.0, width, true ) ); - mScrollView.SetRulerX( mRulerX ); + float width = std::max(mTableOfButtons.GetNaturalSize().width, size.width); + mRulerX->SetDomain(RulerDomain(0.0, width, true)); + mScrollView.SetRulerX(mRulerX); - if( mScrollBar ) + if(mScrollBar) { - float barWidth = std::min( mTableOfButtons.GetNaturalSize().width, size.width ) - 2.f * mScrollBarPadding.x; - mScrollBar.SetProperty( Actor::Property::SIZE, Vector2( 0.0f, barWidth ) ); + float barWidth = std::min(mTableOfButtons.GetNaturalSize().width, size.width) - 2.f * mScrollBarPadding.x; + mScrollBar.SetProperty(Actor::Property::SIZE, Vector2(0.0f, barWidth)); } } -void TextSelectionToolbar::SetPopupMaxSize( const Size& maxSize ) +void TextSelectionToolbar::SetPopupMaxSize(const Size& maxSize) { mMaxSize = maxSize; - if( mScrollView && mToolbarActor ) + if(mScrollView && mToolbarActor) { - mScrollView.SetProperty( Actor::Property::MAXIMUM_SIZE, mMaxSize ); - mToolbarActor.SetProperty( Actor::Property::MAXIMUM_SIZE, mMaxSize ); + mScrollView.SetProperty(Actor::Property::MAXIMUM_SIZE, mMaxSize); + mToolbarActor.SetProperty(Actor::Property::MAXIMUM_SIZE, mMaxSize); } } @@ -204,172 +200,172 @@ const Dali::Vector2& TextSelectionToolbar::GetPopupMaxSize() const void TextSelectionToolbar::SetUpScrollView() { - mScrollView.SetProperty( Dali::Actor::Property::NAME,"TextSelectionScrollView"); - mScrollView.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS ); - mScrollView.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); - mScrollView.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT ); + mScrollView.SetProperty(Dali::Actor::Property::NAME, "TextSelectionScrollView"); + mScrollView.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS); + mScrollView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT); + mScrollView.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT); - mScrollView.SetScrollingDirection( PanGestureDetector::DIRECTION_HORIZONTAL, Degree( 40.0f ) ); - mScrollView.SetAxisAutoLock( true ); - mScrollView.ScrollStartedSignal().Connect( this, &TextSelectionToolbar::OnScrollStarted ); - mScrollView.ScrollCompletedSignal().Connect( this, &TextSelectionToolbar::OnScrollCompleted ); - mScrollView.SetProperty( Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX ); // In a new layer, so clip to scroll-view's bounding box + mScrollView.SetScrollingDirection(PanGestureDetector::DIRECTION_HORIZONTAL, Degree(40.0f)); + mScrollView.SetAxisAutoLock(true); + mScrollView.ScrollStartedSignal().Connect(this, &TextSelectionToolbar::OnScrollStarted); + mScrollView.ScrollCompletedSignal().Connect(this, &TextSelectionToolbar::OnScrollCompleted); + mScrollView.SetProperty(Actor::Property::CLIPPING_MODE, ClippingMode::CLIP_TO_BOUNDING_BOX); // In a new layer, so clip to scroll-view's bounding box - mRulerX = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed. + mRulerX = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed. - RulerPtr rulerY = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed. + RulerPtr rulerY = new DefaultRuler(); // IntrusivePtr which is unreferenced when ScrollView is destroyed. rulerY->Disable(); - mScrollView.SetRulerY( rulerY ); + mScrollView.SetRulerY(rulerY); - mScrollView.SetOvershootEnabled( true ); + mScrollView.SetOvershootEnabled(true); } void TextSelectionToolbar::SetUp() { Actor self = Self(); - self.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS ); + self.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS); // Create Actor to house the toolbar. mToolbarActor = Actor::New(); - mToolbarActor.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS ); - mToolbarActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mToolbarActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mToolbarActor.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS); + mToolbarActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mToolbarActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); - if( !mScrollView ) + if(!mScrollView) { mScrollView = Toolkit::ScrollView::New(); } SetUpScrollView(); // Toolbar must start with at least one option, adding further options with increase it's size - mTableOfButtons = Dali::Toolkit::TableView::New( 1, 1 ); - mTableOfButtons.SetFitHeight( 0 ); - mTableOfButtons.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); - mTableOfButtons.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT ); + mTableOfButtons = Dali::Toolkit::TableView::New(1, 1); + mTableOfButtons.SetFitHeight(0); + mTableOfButtons.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT); + mTableOfButtons.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT); - mScrollView.Add( mTableOfButtons ); - mToolbarActor.Add( mScrollView ); + mScrollView.Add(mTableOfButtons); + mToolbarActor.Add(mScrollView); - self.Add( mToolbarActor ); + self.Add(mToolbarActor); } -void TextSelectionToolbar::SetUpScrollBar( bool enable ) +void TextSelectionToolbar::SetUpScrollBar(bool enable) { - if( enable ) + if(enable) { - if( ! mScrollBar ) + if(!mScrollBar) { Toolkit::ImageView indicator = Toolkit::ImageView::New(); - indicator.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - indicator.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - indicator.SetStyleName( "TextSelectionScrollIndicator" ); - - mScrollBar = Toolkit::ScrollBar::New( Toolkit::ScrollBar::HORIZONTAL ); - mScrollBar.SetProperty( Dali::Actor::Property::NAME, "Text popup scroll bar" ); - mScrollBar.SetStyleName( "TextSelectionScrollBar" ); - mScrollBar.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_LEFT ); - mScrollBar.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - mScrollBar.SetProperty( Actor::Property::POSITION, Vector2( mScrollBarPadding.x, -mScrollBarPadding.y )); - mScrollBar.SetResizePolicy( Dali::ResizePolicy::FIT_TO_CHILDREN, Dali::Dimension::WIDTH ); - mScrollBar.SetProperty( Actor::Property::ORIENTATION, Quaternion( Quaternion( Radian( 1.5f * Math::PI ), Vector3::ZAXIS ) ) ); - mScrollBar.SetScrollIndicator( indicator ); + indicator.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + indicator.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + indicator.SetStyleName("TextSelectionScrollIndicator"); + + mScrollBar = Toolkit::ScrollBar::New(Toolkit::ScrollBar::HORIZONTAL); + mScrollBar.SetProperty(Dali::Actor::Property::NAME, "Text popup scroll bar"); + mScrollBar.SetStyleName("TextSelectionScrollBar"); + mScrollBar.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_LEFT); + mScrollBar.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mScrollBar.SetProperty(Actor::Property::POSITION, Vector2(mScrollBarPadding.x, -mScrollBarPadding.y)); + mScrollBar.SetResizePolicy(Dali::ResizePolicy::FIT_TO_CHILDREN, Dali::Dimension::WIDTH); + mScrollBar.SetProperty(Actor::Property::ORIENTATION, Quaternion(Quaternion(Radian(1.5f * Math::PI), Vector3::ZAXIS))); + mScrollBar.SetScrollIndicator(indicator); mScrollBar.GetPanGestureDetector().DetachAll(); - mScrollView.Add( mScrollBar ); + mScrollView.Add(mScrollBar); } } else { - UnparentAndReset( mScrollBar ); + UnparentAndReset(mScrollBar); } } -void TextSelectionToolbar::OnScrollStarted( const Vector2& position ) +void TextSelectionToolbar::OnScrollStarted(const Vector2& position) { - if( mFirstScrollEnd ) + if(mFirstScrollEnd) { - mScrollView.SetOvershootEnabled( true ); + mScrollView.SetOvershootEnabled(true); } - mTableOfButtons.SetProperty( Actor::Property::SENSITIVE, false ); + mTableOfButtons.SetProperty(Actor::Property::SENSITIVE, false); } -void TextSelectionToolbar::OnScrollCompleted( const Vector2& position ) +void TextSelectionToolbar::OnScrollCompleted(const Vector2& position) { mFirstScrollEnd = true; - mTableOfButtons.SetProperty( Actor::Property::SENSITIVE, true ); + mTableOfButtons.SetProperty(Actor::Property::SENSITIVE, true); } -void TextSelectionToolbar::AddOption( Actor& option ) +void TextSelectionToolbar::AddOption(Actor& option) { - mTableOfButtons.AddChild( option, Toolkit::TableView::CellPosition( 0, mIndexInTable ) ); - mTableOfButtons.SetFitWidth( mIndexInTable ); + mTableOfButtons.AddChild(option, Toolkit::TableView::CellPosition(0, mIndexInTable)); + mTableOfButtons.SetFitWidth(mIndexInTable); mIndexInTable++; } -void TextSelectionToolbar::AddDivider( Actor& divider ) +void TextSelectionToolbar::AddDivider(Actor& divider) { - AddOption( divider ); - mDividerIndexes.PushBack( mIndexInTable - 1u ); + AddOption(divider); + mDividerIndexes.PushBack(mIndexInTable - 1u); } -void TextSelectionToolbar::ResizeDividers( Size& size ) +void TextSelectionToolbar::ResizeDividers(Size& size) { - for( unsigned int i = 0; i < mDividerIndexes.Count(); ++i ) + for(unsigned int i = 0; i < mDividerIndexes.Count(); ++i) { - Actor divider = mTableOfButtons.GetChildAt( Toolkit::TableView::CellPosition( 0, mDividerIndexes[ i ] ) ); - divider.SetProperty( Actor::Property::SIZE, size ); + Actor divider = mTableOfButtons.GetChildAt(Toolkit::TableView::CellPosition(0, mDividerIndexes[i])); + divider.SetProperty(Actor::Property::SIZE, size); } RelayoutRequest(); } -void TextSelectionToolbar::RaiseAbove( Actor target ) +void TextSelectionToolbar::RaiseAbove(Actor target) { - mToolbarActor.RaiseAbove( target ); + mToolbarActor.RaiseAbove(target); } -void TextSelectionToolbar::SetScrollBarPadding( const Vector2& padding ) +void TextSelectionToolbar::SetScrollBarPadding(const Vector2& padding) { mScrollBarPadding = padding; - if( mScrollBar ) + if(mScrollBar) { - mScrollBar.SetProperty( Actor::Property::POSITION, Vector2( mScrollBarPadding.x, -mScrollBarPadding.y )); + mScrollBar.SetProperty(Actor::Property::POSITION, Vector2(mScrollBarPadding.x, -mScrollBarPadding.y)); } RelayoutRequest(); } -void TextSelectionToolbar::ScrollTo( const Vector2& position ) +void TextSelectionToolbar::ScrollTo(const Vector2& position) { mFirstScrollEnd = false; - mScrollView.SetOvershootEnabled( false ); - mScrollView.ScrollTo( position, 0.f ); + mScrollView.SetOvershootEnabled(false); + mScrollView.ScrollTo(position, 0.f); } -void TextSelectionToolbar::ConfigureScrollview( const Property::Map& properties ) +void TextSelectionToolbar::ConfigureScrollview(const Property::Map& properties) { // Set any properties specified for the label by iterating through all property key-value pairs. - for( unsigned int i = 0, mapCount = properties.Count(); i < mapCount; ++i ) + for(unsigned int i = 0, mapCount = properties.Count(); i < mapCount; ++i) { - const StringValuePair& propertyPair( properties.GetPair( i ) ); + const StringValuePair& propertyPair(properties.GetPair(i)); // Convert the property string to a property index. - Property::Index setPropertyIndex = mScrollView.GetPropertyIndex( propertyPair.first ); - if( setPropertyIndex != Property::INVALID_INDEX ) + Property::Index setPropertyIndex = mScrollView.GetPropertyIndex(propertyPair.first); + if(setPropertyIndex != Property::INVALID_INDEX) { // Convert the string representation of a color into a Vector4 - if( setPropertyIndex == Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR ) + if(setPropertyIndex == Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR) { Vector4 color; - if( ConvertPropertyToColor( propertyPair.second, color ) ) + if(ConvertPropertyToColor(propertyPair.second, color)) { - mScrollView.SetOvershootEffectColor( color ); + mScrollView.SetOvershootEffectColor(color); } } else { // If the conversion worked, we have a valid property index, // Set the property to the new value. - mScrollView.SetProperty( setPropertyIndex, propertyPair.second ); + mScrollView.SetProperty(setPropertyIndex, propertyPair.second); } } } @@ -383,12 +379,12 @@ const Vector2& TextSelectionToolbar::GetScrollBarPadding() const } TextSelectionToolbar::TextSelectionToolbar() -: Control( ControlBehaviour( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ) ), - mMaxSize (), - mScrollBarPadding( DEFAULT_SCROLL_BAR_PADDING ), - mIndexInTable( 0 ), +: Control(ControlBehaviour(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT))), + mMaxSize(), + mScrollBarPadding(DEFAULT_SCROLL_BAR_PADDING), + mIndexInTable(0), mDividerIndexes(), - mFirstScrollEnd( false ) + mFirstScrollEnd(false) { } diff --git a/dali-toolkit/internal/controls/tool-bar/tool-bar-impl.cpp b/dali-toolkit/internal/controls/tool-bar/tool-bar-impl.cpp index 1519920..a0cd9e4 100644 --- a/dali-toolkit/internal/controls/tool-bar/tool-bar-impl.cpp +++ b/dali-toolkit/internal/controls/tool-bar/tool-bar-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. @@ -20,8 +20,8 @@ // EXTERNAL INCLUDES #include -#include #include +#include // INTERNAL INCLUDES #include @@ -29,35 +29,31 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::ToolBar::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::ToolBar, Toolkit::Control, Create ) +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::ToolBar, Toolkit::Control, Create) DALI_TYPE_REGISTRATION_END() -const float DEFAULT_RELATIVE_SIZE( 0.1f ); -const Toolkit::Alignment::Type DEFAULT_ALIGNMENT( Toolkit::Alignment::HORIZONTAL_LEFT ); +const float DEFAULT_RELATIVE_SIZE(0.1f); +const Toolkit::Alignment::Type DEFAULT_ALIGNMENT(Toolkit::Alignment::HORIZONTAL_LEFT); } // namespace Toolkit::ToolBar ToolBar::New() { // Create the implementation, temporarily owned on stack - IntrusivePtr< ToolBar > internalToolBar = new ToolBar(); + IntrusivePtr internalToolBar = new ToolBar(); // Pass ownership to Toolkit::Toolbar - Toolkit::ToolBar toolBar( *internalToolBar ); + Toolkit::ToolBar toolBar(*internalToolBar); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... @@ -66,11 +62,11 @@ Toolkit::ToolBar ToolBar::New() return toolBar; } -void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment::Type alignment, const Toolkit::Alignment::Padding& padding ) +void ToolBar::AddControl(Actor control, float relativeSize, Toolkit::Alignment::Type alignment, const Toolkit::Alignment::Padding& padding) { // Work out index and update bases and offsets for further insertions. unsigned int index = 0; - switch( alignment ) + switch(alignment) { case Toolkit::Alignment::HORIZONTAL_LEFT: { @@ -96,23 +92,23 @@ void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment: } default: { - DALI_ASSERT_ALWAYS( false ); + DALI_ASSERT_ALWAYS(false); } } // Create a new column for the new control. - mLayout.InsertColumn( index ); + mLayout.InsertColumn(index); // Create an alignment container where to place the control. - Toolkit::Alignment alignmentContainer = Toolkit::Alignment::New( alignment ); - alignmentContainer.SetProperty( Actor::Property::SIZE_SCALE_POLICY, SizeScalePolicy::FIT_WITH_ASPECT_RATIO ); - alignmentContainer.SetPadding( padding ); - alignmentContainer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); - alignmentContainer.Add( control ); + Toolkit::Alignment alignmentContainer = Toolkit::Alignment::New(alignment); + alignmentContainer.SetProperty(Actor::Property::SIZE_SCALE_POLICY, SizeScalePolicy::FIT_WITH_ASPECT_RATIO); + alignmentContainer.SetPadding(padding); + alignmentContainer.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); + alignmentContainer.Add(control); // Insert the control in the table view. - mLayout.AddChild( alignmentContainer, Toolkit::TableView::CellPosition( 0, index ) ); - mLayout.SetRelativeWidth( index, relativeSize ); + mLayout.AddChild(alignmentContainer, Toolkit::TableView::CellPosition(0, index)); + mLayout.SetRelativeWidth(index, relativeSize); // Relate control and alignmentContainer in order to allow removing controls. mControls[control] = alignmentContainer; @@ -121,12 +117,12 @@ void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment: mAccumulatedRelativeSpace += relativeSize; // Update spaces between left, center and right groups of controls. - switch( alignment ) + switch(alignment) { case Toolkit::Alignment::HORIZONTAL_LEFT: { mLeftRelativeSpace -= relativeSize; - if ( mLeftRelativeSpace < 0.f ) + if(mLeftRelativeSpace < 0.f) { mLeftRelativeSpace = 0.f; } @@ -135,12 +131,12 @@ void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment: case Toolkit::Alignment::HORIZONTAL_CENTER: { mLeftRelativeSpace -= 0.5f * relativeSize; - if ( mLeftRelativeSpace < 0.f ) + if(mLeftRelativeSpace < 0.f) { mLeftRelativeSpace = 0.f; } mRightRelativeSpace -= 0.5f * relativeSize; - if ( mRightRelativeSpace < 0.f ) + if(mRightRelativeSpace < 0.f) { mRightRelativeSpace = 0.f; } @@ -149,7 +145,7 @@ void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment: case Toolkit::Alignment::HORIZONTAL_RIGHT: { mRightRelativeSpace -= relativeSize; - if ( mRightRelativeSpace < 0.f ) + if(mRightRelativeSpace < 0.f) { mRightRelativeSpace = 0.f; } @@ -157,55 +153,55 @@ void ToolBar::AddControl( Actor control, float relativeSize, Toolkit::Alignment: } default: { - DALI_ASSERT_ALWAYS( false ); + DALI_ASSERT_ALWAYS(false); } } - mLayout.SetRelativeWidth( mLeftOffset, mLeftRelativeSpace ); - mLayout.SetRelativeWidth( mCenterBase + mCenterOffset, mRightRelativeSpace ); + mLayout.SetRelativeWidth(mLeftOffset, mLeftRelativeSpace); + mLayout.SetRelativeWidth(mCenterBase + mCenterOffset, mRightRelativeSpace); } -void ToolBar::RemoveControl( Actor control ) +void ToolBar::RemoveControl(Actor control) { Toolkit::TableView::CellPosition position; // Find the alignment where the control is placed. - std::map::iterator it = mControls.find( control ); + std::map::iterator it = mControls.find(control); - if( ( it != mControls.end() ) && ( mLayout.FindChildPosition( it->second, position ) ) ) + if((it != mControls.end()) && (mLayout.FindChildPosition(it->second, position))) { // Update accumulated relative space. - mAccumulatedRelativeSpace -= mLayout.GetRelativeWidth( position.columnIndex ); + mAccumulatedRelativeSpace -= mLayout.GetRelativeWidth(position.columnIndex); // Update spaces between left, center and right groups of controls. - if( 1.0 > mAccumulatedRelativeSpace ) + if(1.0 > mAccumulatedRelativeSpace) { Toolkit::Alignment::Type alignment = Toolkit::Alignment::HORIZONTAL_LEFT; - if( position.columnIndex < mLeftOffset ) + if(position.columnIndex < mLeftOffset) { alignment = Toolkit::Alignment::HORIZONTAL_LEFT; } - else if( ( position.columnIndex > mLeftOffset ) && ( position.columnIndex < mCenterBase + mCenterOffset ) ) + else if((position.columnIndex > mLeftOffset) && (position.columnIndex < mCenterBase + mCenterOffset)) { alignment = Toolkit::Alignment::HORIZONTAL_CENTER; } - else if( position.columnIndex > mCenterBase + mCenterOffset ) + else if(position.columnIndex > mCenterBase + mCenterOffset) { alignment = Toolkit::Alignment::HORIZONTAL_RIGHT; } else { - DALI_ASSERT_ALWAYS( false ); + DALI_ASSERT_ALWAYS(false); } - float relativeSize = mLayout.GetRelativeWidth( position.columnIndex ); + float relativeSize = mLayout.GetRelativeWidth(position.columnIndex); - switch( alignment ) + switch(alignment) { case Toolkit::Alignment::HORIZONTAL_LEFT: { mLeftRelativeSpace += relativeSize; - if ( mLeftRelativeSpace < 0.f ) + if(mLeftRelativeSpace < 0.f) { mLeftRelativeSpace = 0.f; } @@ -214,12 +210,12 @@ void ToolBar::RemoveControl( Actor control ) case Toolkit::Alignment::HORIZONTAL_CENTER: { mLeftRelativeSpace += 0.5f * relativeSize; - if ( mLeftRelativeSpace < 0.f ) + if(mLeftRelativeSpace < 0.f) { mLeftRelativeSpace = 0.f; } mRightRelativeSpace += 0.5f * relativeSize; - if ( mRightRelativeSpace < 0.f ) + if(mRightRelativeSpace < 0.f) { mRightRelativeSpace = 0.f; } @@ -228,7 +224,7 @@ void ToolBar::RemoveControl( Actor control ) case Toolkit::Alignment::HORIZONTAL_RIGHT: { mRightRelativeSpace += relativeSize; - if ( mRightRelativeSpace < 0.f ) + if(mRightRelativeSpace < 0.f) { mRightRelativeSpace = 0.f; } @@ -236,31 +232,31 @@ void ToolBar::RemoveControl( Actor control ) } default: { - DALI_ASSERT_ALWAYS( false ); + DALI_ASSERT_ALWAYS(false); } } - mLayout.SetRelativeWidth( mLeftOffset, mLeftRelativeSpace ); - mLayout.SetRelativeWidth( mCenterBase + mCenterOffset, mRightRelativeSpace ); + mLayout.SetRelativeWidth(mLeftOffset, mLeftRelativeSpace); + mLayout.SetRelativeWidth(mCenterBase + mCenterOffset, mRightRelativeSpace); } // Remove alignment as parent of control. - it->second.Remove( control ); + it->second.Remove(control); // Remove the relationship between control and alignment. - mControls.erase( it ); + mControls.erase(it); // Remove column from tableview. - mLayout.DeleteColumn( position.columnIndex ); + mLayout.DeleteColumn(position.columnIndex); // Update bases and offsets. - if( position.columnIndex < mCenterBase ) + if(position.columnIndex < mCenterBase) { // Control is on the left side. Decrease left offset and center and right bases. --mLeftOffset; --mCenterBase; --mRightBase; } - else if( position.columnIndex < mCenterBase + mCenterOffset ) + else if(position.columnIndex < mCenterBase + mCenterOffset) { // Control is on the center side. Decrease center offset and right base. --mCenterOffset; @@ -276,17 +272,17 @@ void ToolBar::RemoveControl( Actor control ) } ToolBar::ToolBar() -: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), +: Control(ControlBehaviour(CONTROL_BEHAVIOUR_DEFAULT)), mLayout(), - mLeftOffset( 0 ), - mCenterBase( 1 ), - mCenterOffset( 0 ), - mRightBase( 2 ), - mRightOffset( 0 ), - mLeftRelativeSpace( 0.5f ), - mRightRelativeSpace( 0.5f ), - mAccumulatedRelativeSpace( 0.f ), - mInitializing( false ), + mLeftOffset(0), + mCenterBase(1), + mCenterOffset(0), + mRightBase(2), + mRightOffset(0), + mLeftRelativeSpace(0.5f), + mRightRelativeSpace(0.5f), + mAccumulatedRelativeSpace(0.f), + mInitializing(false), mControls() { } @@ -297,50 +293,50 @@ ToolBar::~ToolBar() void ToolBar::OnInitialize() { - Lock lock( mInitializing ); + Lock lock(mInitializing); // Layout - mLayout = Toolkit::TableView::New( 1, 1 ); - mLayout.SetProperty( Dali::Actor::Property::NAME, "TOOLBAR_LAYOUT" ); - mLayout.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); - mLayout.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mLayout = Toolkit::TableView::New(1, 1); + mLayout.SetProperty(Dali::Actor::Property::NAME, "TOOLBAR_LAYOUT"); + mLayout.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); + mLayout.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); - Self().Add( mLayout ); + Self().Add(mLayout); // Add two default actors to create spaces between controls grouped on the left, center and right. - Actor leftSpace = Actor::New(); + Actor leftSpace = Actor::New(); Actor rightSpace = Actor::New(); - mLayout.AddChild( leftSpace, Toolkit::TableView::CellPosition( 0, 0 ) ); - mLayout.AddChild( rightSpace, Toolkit::TableView::CellPosition( 0, 1 ) ); - mLayout.SetRelativeWidth( 0, mLeftRelativeSpace ); - mLayout.SetRelativeWidth( 1, mRightRelativeSpace ); - - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::TOOL_BAR )); - } ); + mLayout.AddChild(leftSpace, Toolkit::TableView::CellPosition(0, 0)); + mLayout.AddChild(rightSpace, Toolkit::TableView::CellPosition(0, 1)); + mLayout.SetRelativeWidth(0, mLeftRelativeSpace); + mLayout.SetRelativeWidth(1, mRightRelativeSpace); + + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::TOOL_BAR)); + }); } void ToolBar::OnChildAdd(Actor& child) { - if( !mInitializing ) + if(!mInitializing) { // An actor is being added through the Actor's API. // Remove child from tool bar actor and insert it in table view with some 'default' values - if ( child && child.GetParent() ) + if(child && child.GetParent()) { - child.GetParent().Remove( child ); + child.GetParent().Remove(child); } - AddControl( child, DEFAULT_RELATIVE_SIZE, DEFAULT_ALIGNMENT, Toolkit::ToolBar::DEFAULT_PADDING ); + AddControl(child, DEFAULT_RELATIVE_SIZE, DEFAULT_ALIGNMENT, Toolkit::ToolBar::DEFAULT_PADDING); } // No OnChildRemove method required because Actors are added to the mLayout table view, so if an // actor is removed using the Actor::RemoveChild method it will not remove anything because the // actor is in mLayout not in Self(). - Control::OnChildAdd( child ); + Control::OnChildAdd(child); } } // namespace Internal diff --git a/dali-toolkit/internal/controls/tooltip/tooltip.cpp b/dali-toolkit/internal/controls/tooltip/tooltip.cpp index 3a2ccc0..e8274d1 100644 --- a/dali-toolkit/internal/controls/tooltip/tooltip.cpp +++ b/dali-toolkit/internal/controls/tooltip/tooltip.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,204 +21,196 @@ // EXTERNAL INCLUDES #include -#include -#include #include #include +#include +#include // INTERNAL INCLUDES #include -#include -#include #include -#include -#include #include #include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -DALI_ENUM_TO_STRING_TABLE_BEGIN( TOOLTIP_POSITION ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Tooltip::Position, ABOVE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Tooltip::Position, BELOW ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Tooltip::Position, HOVER_POINT ) -DALI_ENUM_TO_STRING_TABLE_END( TOOLTIP_POSITION ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(TOOLTIP_POSITION) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Tooltip::Position, ABOVE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Tooltip::Position, BELOW) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Tooltip::Position, HOVER_POINT) +DALI_ENUM_TO_STRING_TABLE_END(TOOLTIP_POSITION) const float MILLISECONDS_PER_SECOND = 1000.0f; -const char * const PROPERTY_CONTENT_NAME = "content"; -const char * const PROPERTY_LAYOUT_NAME = "layout"; -const char * const PROPERTY_WAIT_TIME_NAME = "waitTime"; -const char * const PROPERTY_BACKGROUND_NAME = "background"; -const char * const PROPERTY_TAIL_NAME = "tail"; -const char * const PROPERTY_POSITION_NAME = "position"; -const char * const PROPERTY_HOVER_POINT_OFFSET_NAME = "hoverPointOffset"; -const char * const PROPERTY_MOVEMENT_THRESHOLD = "movementThreshold"; -const char * const PROPERTY_DISAPPEAR_ON_MOVEMENT = "disappearOnMovement"; +const char* const PROPERTY_CONTENT_NAME = "content"; +const char* const PROPERTY_LAYOUT_NAME = "layout"; +const char* const PROPERTY_WAIT_TIME_NAME = "waitTime"; +const char* const PROPERTY_BACKGROUND_NAME = "background"; +const char* const PROPERTY_TAIL_NAME = "tail"; +const char* const PROPERTY_POSITION_NAME = "position"; +const char* const PROPERTY_HOVER_POINT_OFFSET_NAME = "hoverPointOffset"; +const char* const PROPERTY_MOVEMENT_THRESHOLD = "movementThreshold"; +const char* const PROPERTY_DISAPPEAR_ON_MOVEMENT = "disappearOnMovement"; -const char * const PROPERTY_BACKGROUND_VISUAL = "visual"; -const char * const PROPERTY_BACKGROUND_BORDER = "border"; +const char* const PROPERTY_BACKGROUND_VISUAL = "visual"; +const char* const PROPERTY_BACKGROUND_BORDER = "border"; -const char * const PROPERTY_TAIL_VISIBILITY = "visibility"; -const char * const PROPERTY_TAIL_ABOVE_VISUAL = "aboveVisual"; -const char * const PROPERTY_TAIL_BELOW_VISUAL = "belowVisual"; +const char* const PROPERTY_TAIL_VISIBILITY = "visibility"; +const char* const PROPERTY_TAIL_ABOVE_VISUAL = "aboveVisual"; +const char* const PROPERTY_TAIL_BELOW_VISUAL = "belowVisual"; } // unnamed namespace -TooltipPtr Tooltip::New( Toolkit::Control control ) +TooltipPtr Tooltip::New(Toolkit::Control control) { - return new Tooltip( control ); + return new Tooltip(control); } -void Tooltip::SetProperties( const Property::Value& value ) +void Tooltip::SetProperties(const Property::Value& value) { Toolkit::Control control = mControl.GetHandle(); - if( control ) + if(control) { const Property::Map* properties = value.GetMap(); - if( properties ) + if(properties) { const Property::Map::SizeType count = properties->Count(); - for( Property::Map::SizeType position = 0; position < count; ++position ) + for(Property::Map::SizeType position = 0; position < count; ++position) { - KeyValuePair keyValue = properties->GetKeyValue( position ); - Property::Key& key = keyValue.first; - Property::Value& value = keyValue.second; + KeyValuePair keyValue = properties->GetKeyValue(position); + Property::Key& key = keyValue.first; + Property::Value& value = keyValue.second; - if( key == Toolkit::Tooltip::Property::CONTENT || key == PROPERTY_CONTENT_NAME ) + if(key == Toolkit::Tooltip::Property::CONTENT || key == PROPERTY_CONTENT_NAME) { - SetContent( control, value ); + SetContent(control, value); } - else if( key == Toolkit::Tooltip::Property::LAYOUT || key == PROPERTY_LAYOUT_NAME ) + else if(key == Toolkit::Tooltip::Property::LAYOUT || key == PROPERTY_LAYOUT_NAME) { - value.Get( mLayout ); + value.Get(mLayout); } - else if( key == Toolkit::Tooltip::Property::WAIT_TIME || key == PROPERTY_WAIT_TIME_NAME ) + else if(key == Toolkit::Tooltip::Property::WAIT_TIME || key == PROPERTY_WAIT_TIME_NAME) { float waitTime = 0.0f; - if( value.Get( waitTime ) ) + if(value.Get(waitTime)) { mWaitTime = waitTime * MILLISECONDS_PER_SECOND; } } - else if( key == Toolkit::Tooltip::Property::BACKGROUND || key == PROPERTY_BACKGROUND_NAME ) + else if(key == Toolkit::Tooltip::Property::BACKGROUND || key == PROPERTY_BACKGROUND_NAME) { - SetBackground( value ); + SetBackground(value); } - else if( key == Toolkit::Tooltip::Property::TAIL || key == PROPERTY_TAIL_NAME ) + else if(key == Toolkit::Tooltip::Property::TAIL || key == PROPERTY_TAIL_NAME) { - SetTail( value ); + SetTail(value); } - else if( key == Toolkit::Tooltip::Property::POSITION || key == PROPERTY_POSITION_NAME ) + else if(key == Toolkit::Tooltip::Property::POSITION || key == PROPERTY_POSITION_NAME) { - Scripting::GetEnumerationProperty< Toolkit::Tooltip::Position::Type >( value, TOOLTIP_POSITION_TABLE, TOOLTIP_POSITION_TABLE_COUNT, mPositionType ); + Scripting::GetEnumerationProperty(value, TOOLTIP_POSITION_TABLE, TOOLTIP_POSITION_TABLE_COUNT, mPositionType); } - else if( key == Toolkit::Tooltip::Property::HOVER_POINT_OFFSET || key == PROPERTY_HOVER_POINT_OFFSET_NAME ) + else if(key == Toolkit::Tooltip::Property::HOVER_POINT_OFFSET || key == PROPERTY_HOVER_POINT_OFFSET_NAME) { - value.Get( mHoverPointOffset ); + value.Get(mHoverPointOffset); } - else if( key == Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD || key == PROPERTY_MOVEMENT_THRESHOLD ) + else if(key == Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD || key == PROPERTY_MOVEMENT_THRESHOLD) { - value.Get( mMovementThreshold ); + value.Get(mMovementThreshold); } - else if( key == Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT || key == PROPERTY_DISAPPEAR_ON_MOVEMENT ) + else if(key == Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT || key == PROPERTY_DISAPPEAR_ON_MOVEMENT) { - value.Get( mDisappearOnMovement ); + value.Get(mDisappearOnMovement); } } } else { Property::Type type = value.GetType(); - if( ( value.GetType() == Property::STRING ) || ( type == Property::ARRAY ) ) + if((value.GetType() == Property::STRING) || (type == Property::ARRAY)) { - SetContent( control, value ); + SetContent(control, value); } } } } -void Tooltip::CreatePropertyMap( Property::Map& map ) const +void Tooltip::CreatePropertyMap(Property::Map& map) const { - if( ! mContentTextVisual.Empty() ) + if(!mContentTextVisual.Empty()) { Property::Map content = mContentTextVisual; // Need this copy as there's no Value constructor which takes in a 'const Property::Map&'. - map.Insert( Toolkit::Tooltip::Property::CONTENT, content ); + map.Insert(Toolkit::Tooltip::Property::CONTENT, content); } - else if( ! mContentArray.Empty() ) + else if(!mContentArray.Empty()) { Property::Array content = mContentArray; // Need this copy as there's no Value constructor which takes in a 'const Property::Array&'. - map.Insert( Toolkit::Tooltip::Property::CONTENT, content ); + map.Insert(Toolkit::Tooltip::Property::CONTENT, content); } - map.Insert( Toolkit::Tooltip::Property::LAYOUT, mLayout ); - map.Insert( Toolkit::Tooltip::Property::WAIT_TIME, static_cast( mWaitTime ) / MILLISECONDS_PER_SECOND ); - map.Insert( Toolkit::Tooltip::Property::BACKGROUND, - Property::Map().Add( Toolkit::Tooltip::Background::Property::VISUAL, mBackgroundImage ) - .Add( Toolkit::Tooltip::Background::Property::BORDER, mBackgroundBorder ) ); - map.Insert( Toolkit::Tooltip::Property::TAIL, - Property::Map().Add( Toolkit::Tooltip::Tail::Property::VISIBILITY, mTailVisibility ) - .Add( Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL, mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ]) - .Add( Toolkit::Tooltip::Tail::Property::BELOW_VISUAL, mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ]) ); - map.Insert( Toolkit::Tooltip::Property::POSITION, mPositionType ); - map.Insert( Toolkit::Tooltip::Property::HOVER_POINT_OFFSET, mHoverPointOffset ); - map.Insert( Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD, mMovementThreshold ); - map.Insert( Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT, mDisappearOnMovement ); + map.Insert(Toolkit::Tooltip::Property::LAYOUT, mLayout); + map.Insert(Toolkit::Tooltip::Property::WAIT_TIME, static_cast(mWaitTime) / MILLISECONDS_PER_SECOND); + map.Insert(Toolkit::Tooltip::Property::BACKGROUND, + Property::Map().Add(Toolkit::Tooltip::Background::Property::VISUAL, mBackgroundImage).Add(Toolkit::Tooltip::Background::Property::BORDER, mBackgroundBorder)); + map.Insert(Toolkit::Tooltip::Property::TAIL, + Property::Map().Add(Toolkit::Tooltip::Tail::Property::VISIBILITY, mTailVisibility).Add(Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL, mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL]).Add(Toolkit::Tooltip::Tail::Property::BELOW_VISUAL, mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL])); + map.Insert(Toolkit::Tooltip::Property::POSITION, mPositionType); + map.Insert(Toolkit::Tooltip::Property::HOVER_POINT_OFFSET, mHoverPointOffset); + map.Insert(Toolkit::Tooltip::Property::MOVEMENT_THRESHOLD, mMovementThreshold); + map.Insert(Toolkit::Tooltip::Property::DISAPPEAR_ON_MOVEMENT, mDisappearOnMovement); } -Tooltip::Tooltip( Toolkit::Control control ) +Tooltip::Tooltip(Toolkit::Control control) : mPopup(), mTooltipTimer(), - mControl( control ), + mControl(control), mContentTextVisual(), mTailImages(), mContentArray(), - mBackgroundBorder( 0, 0, 0, 0 ), - mLayout( 1, 1 ), + mBackgroundBorder(0, 0, 0, 0), + mLayout(1, 1), mHoverPoint(), - mHoverPointOffset( 10.0f, 10.0f ), + mHoverPointOffset(10.0f, 10.0f), mBackgroundImage(), - mMovementThreshold( 5.0f ), - mWaitTime( 500 ), - mPositionType( Toolkit::Tooltip::Position::ABOVE ), - mTailVisibility( false ), - mDisappearOnMovement( false ), - mSignalsConnected( false ) + mMovementThreshold(5.0f), + mWaitTime(500), + mPositionType(Toolkit::Tooltip::Position::ABOVE), + mTailVisibility(false), + mDisappearOnMovement(false), + mSignalsConnected(false) { - mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ] = ""; - mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ] = ""; + mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL] = ""; + mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL] = ""; } Tooltip::~Tooltip() { - if( mPopup ) + if(mPopup) { mPopup.Unparent(); mPopup.Reset(); } } -void Tooltip::SetContent( Toolkit::Control& control, const Property::Value& value ) +void Tooltip::SetContent(Toolkit::Control& control, const Property::Value& value) { // Delete popup & timer - if( mTooltipTimer ) + if(mTooltipTimer) { mTooltipTimer.Stop(); mTooltipTimer.Reset(); } - if( mPopup ) + if(mPopup) { mPopup.Unparent(); mPopup.Reset(); @@ -227,26 +219,26 @@ void Tooltip::SetContent( Toolkit::Control& control, const Property::Value& valu bool connectSignals = false; Property::Type type = value.GetType(); - if( type == Property::MAP ) + if(type == Property::MAP) { const Property::Map* map = value.GetMap(); - if( map ) + if(map) { - mContentTextVisual.Merge( *map ); + mContentTextVisual.Merge(*map); - Property::Value* typeValue = map->Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE ); - if( typeValue ) + Property::Value* typeValue = map->Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE); + if(typeValue) { // Set to an invalid value so it definitely changes if set in Scripting::GetEnumerationProperty - Toolkit::Visual::Type visualType = static_cast< Toolkit::Visual::Type >( -1 ); + Toolkit::Visual::Type visualType = static_cast(-1); - if( Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType ) ) + if(Scripting::GetEnumerationProperty(*typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType)) { - if( visualType == Toolkit::Visual::TEXT ) + if(visualType == Toolkit::Visual::TEXT) { // Visual Type is text, ensure we have a the TEXT property set before we connect to the signals. - if( map->Find( Toolkit::TextVisual::Property::TEXT, TEXT_PROPERTY ) ) + if(map->Find(Toolkit::TextVisual::Property::TEXT, TEXT_PROPERTY)) { mContentArray.Clear(); connectSignals = true; @@ -263,66 +255,66 @@ void Tooltip::SetContent( Toolkit::Control& control, const Property::Value& valu } } } - else if( type == Property::ARRAY ) + else if(type == Property::ARRAY) { - if( value.Get( mContentArray ) ) + if(value.Get(mContentArray)) { mContentTextVisual.Clear(); connectSignals = true; } } - else if( type == Property::STRING ) + else if(type == Property::STRING) { std::string text; - if( value.Get( text ) ) + if(value.Get(text)) { - mContentTextVisual[ Toolkit::TextVisual::Property::TEXT ] = text; - mContentTextVisual[ Toolkit::Visual::Property::TYPE ] = Toolkit::Visual::TEXT; + mContentTextVisual[Toolkit::TextVisual::Property::TEXT] = text; + mContentTextVisual[Toolkit::Visual::Property::TYPE] = Toolkit::Visual::TEXT; mContentArray.Clear(); connectSignals = true; } } - if( connectSignals && ! mSignalsConnected ) + if(connectSignals && !mSignalsConnected) { - control.HoveredSignal().Connect( this, &Tooltip::OnHovered ); - control.SetProperty( Actor::Property::LEAVE_REQUIRED, true ); + control.HoveredSignal().Connect(this, &Tooltip::OnHovered); + control.SetProperty(Actor::Property::LEAVE_REQUIRED, true); mSignalsConnected = true; } } -void Tooltip::SetBackground( const Property::Value& value ) +void Tooltip::SetBackground(const Property::Value& value) { Property::Type type = value.GetType(); - if( type == Property::STRING ) + if(type == Property::STRING) { - value.Get( mBackgroundImage ); - mBackgroundBorder.Set( 0, 0, 0, 0 ); + value.Get(mBackgroundImage); + mBackgroundBorder.Set(0, 0, 0, 0); } - else if( type == Property::MAP ) + else if(type == Property::MAP) { const Property::Map* map = value.GetMap(); - if( map ) + if(map) { const Property::Map::SizeType count = map->Count(); - for( Property::Map::SizeType position = 0; position < count; ++position ) + for(Property::Map::SizeType position = 0; position < count; ++position) { - KeyValuePair keyValue = map->GetKeyValue( position ); - Property::Key& key = keyValue.first; - Property::Value& value = keyValue.second; + KeyValuePair keyValue = map->GetKeyValue(position); + Property::Key& key = keyValue.first; + Property::Value& value = keyValue.second; - if( key == Toolkit::Tooltip::Background::Property::VISUAL || key == PROPERTY_BACKGROUND_VISUAL ) + if(key == Toolkit::Tooltip::Background::Property::VISUAL || key == PROPERTY_BACKGROUND_VISUAL) { - value.Get( mBackgroundImage ); + value.Get(mBackgroundImage); } - else if( key == Toolkit::Tooltip::Background::Property::BORDER || key == PROPERTY_BACKGROUND_BORDER ) + else if(key == Toolkit::Tooltip::Background::Property::BORDER || key == PROPERTY_BACKGROUND_BORDER) { - if( ! value.Get( mBackgroundBorder ) ) + if(!value.Get(mBackgroundBorder)) { // If not a Property::RECTANGLE, then check if it's a Vector4 and set it accordingly Vector4 valueVector4; - if( value.Get( valueVector4 ) ) + if(value.Get(valueVector4)) { mBackgroundBorder.left = valueVector4.x; mBackgroundBorder.right = valueVector4.y; @@ -336,46 +328,46 @@ void Tooltip::SetBackground( const Property::Value& value ) } } -void Tooltip::SetTail( const Property::Value& value ) +void Tooltip::SetTail(const Property::Value& value) { Property::Type type = value.GetType(); - if( type == Property::BOOLEAN ) + if(type == Property::BOOLEAN) { - value.Get( mTailVisibility ); + value.Get(mTailVisibility); } - else if( type == Property::MAP ) + else if(type == Property::MAP) { Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { const Property::Map::SizeType count = map.Count(); - for( Property::Map::SizeType position = 0; position < count; ++position ) + for(Property::Map::SizeType position = 0; position < count; ++position) { - KeyValuePair keyValue = map.GetKeyValue( position ); - Property::Key& key = keyValue.first; - Property::Value& value = keyValue.second; + KeyValuePair keyValue = map.GetKeyValue(position); + Property::Key& key = keyValue.first; + Property::Value& value = keyValue.second; // Set the values manually rather than merging so that we only have to deal with Property indices when creating the actual tooltip. - if( key == Toolkit::Tooltip::Tail::Property::VISIBILITY || key == PROPERTY_TAIL_VISIBILITY ) + if(key == Toolkit::Tooltip::Tail::Property::VISIBILITY || key == PROPERTY_TAIL_VISIBILITY) { - value.Get( mTailVisibility ); + value.Get(mTailVisibility); } - else if( key == Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL || key == PROPERTY_TAIL_ABOVE_VISUAL ) + else if(key == Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL || key == PROPERTY_TAIL_ABOVE_VISUAL) { std::string path; - if( value.Get( path ) ) + if(value.Get(path)) { - mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ] = path; + mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL] = path; } } - else if( key == Toolkit::Tooltip::Tail::Property::BELOW_VISUAL || key == PROPERTY_TAIL_BELOW_VISUAL ) + else if(key == Toolkit::Tooltip::Tail::Property::BELOW_VISUAL || key == PROPERTY_TAIL_BELOW_VISUAL) { std::string path; - if( value.Get( path ) ) + if(value.Get(path)) { - mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ] = path; + mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL] = path; } } } @@ -383,53 +375,53 @@ void Tooltip::SetTail( const Property::Value& value ) } } -bool Tooltip::OnHovered( Actor /* actor */, const HoverEvent& hover ) +bool Tooltip::OnHovered(Actor /* actor */, const HoverEvent& hover) { - const PointState::Type state = hover.GetState( 0 ); - switch( state ) + const PointState::Type state = hover.GetState(0); + switch(state) { case PointState::STARTED: case PointState::MOTION: { - if( ! mPopup ) + if(!mPopup) { - if( ! mTooltipTimer ) + if(!mTooltipTimer) { - mHoverPoint = hover.GetScreenPosition( 0 ); - mTooltipTimer = Timer::New( mWaitTime ); - mTooltipTimer.TickSignal().Connect( this, &Tooltip::OnTimeout ); + mHoverPoint = hover.GetScreenPosition(0); + mTooltipTimer = Timer::New(mWaitTime); + mTooltipTimer.TickSignal().Connect(this, &Tooltip::OnTimeout); mTooltipTimer.Start(); } else { - Vector2 movement = mHoverPoint - hover.GetScreenPosition( 0 ); - if( std::abs( movement.Length() ) > mMovementThreshold ) + Vector2 movement = mHoverPoint - hover.GetScreenPosition(0); + if(std::abs(movement.Length()) > mMovementThreshold) { mTooltipTimer.Stop(); mTooltipTimer.Reset(); - mHoverPoint = hover.GetScreenPosition( 0 ); - mTooltipTimer = Timer::New( mWaitTime ); - mTooltipTimer.TickSignal().Connect( this, &Tooltip::OnTimeout ); + mHoverPoint = hover.GetScreenPosition(0); + mTooltipTimer = Timer::New(mWaitTime); + mTooltipTimer.TickSignal().Connect(this, &Tooltip::OnTimeout); mTooltipTimer.Start(); } } } - else if( mDisappearOnMovement ) + else if(mDisappearOnMovement) { // Popup is showing, and we're set to disappear on excessive movement so make sure we're still within the threshold. - Vector2 movement = mHoverPoint - hover.GetScreenPosition( 0 ); - if( std::abs( movement.Length() ) > mMovementThreshold ) + Vector2 movement = mHoverPoint - hover.GetScreenPosition(0); + if(std::abs(movement.Length()) > mMovementThreshold) { // Exceeding the threshold, hide the popup. - if( mTooltipTimer ) + if(mTooltipTimer) { mTooltipTimer.Stop(); mTooltipTimer.Reset(); } - if( mPopup ) + if(mPopup) { mPopup.Unparent(); mPopup.Reset(); @@ -442,12 +434,12 @@ bool Tooltip::OnHovered( Actor /* actor */, const HoverEvent& hover ) case PointState::LEAVE: case PointState::INTERRUPTED: { - if( mTooltipTimer ) + if(mTooltipTimer) { mTooltipTimer.Stop(); mTooltipTimer.Reset(); } - if( mPopup ) + if(mPopup) { mPopup.Unparent(); mPopup.Reset(); @@ -467,122 +459,122 @@ bool Tooltip::OnHovered( Actor /* actor */, const HoverEvent& hover ) bool Tooltip::OnTimeout() { Toolkit::Control control = mControl.GetHandle(); - if( ! mPopup && control ) + if(!mPopup && control) { mPopup = Toolkit::Popup::New(); // General set up of popup - mPopup.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS ); - mPopup.SetProperty( Toolkit::Popup::Property::CONTEXTUAL_MODE, "NON_CONTEXTUAL" ); - mPopup.SetProperty( Toolkit::Popup::Property::ANIMATION_MODE, "NONE" ); - mPopup.SetProperty( Toolkit::Popup::Property::BACKING_ENABLED, false ); // Disable the dimmed backing. - mPopup.SetProperty( Toolkit::Popup::Property::TOUCH_TRANSPARENT, true ); // Let events pass through the popup - mPopup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - mPopup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); + mPopup.SetResizePolicy(ResizePolicy::FIT_TO_CHILDREN, Dimension::ALL_DIMENSIONS); + mPopup.SetProperty(Toolkit::Popup::Property::CONTEXTUAL_MODE, "NON_CONTEXTUAL"); + mPopup.SetProperty(Toolkit::Popup::Property::ANIMATION_MODE, "NONE"); + mPopup.SetProperty(Toolkit::Popup::Property::BACKING_ENABLED, false); // Disable the dimmed backing. + mPopup.SetProperty(Toolkit::Popup::Property::TOUCH_TRANSPARENT, true); // Let events pass through the popup + mPopup.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + mPopup.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); // Background - mPopup.SetProperty( Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE, mBackgroundImage ); - mPopup.SetProperty( Toolkit::Popup::Property::POPUP_BACKGROUND_BORDER, mBackgroundBorder ); + mPopup.SetProperty(Toolkit::Popup::Property::POPUP_BACKGROUND_IMAGE, mBackgroundImage); + mPopup.SetProperty(Toolkit::Popup::Property::POPUP_BACKGROUND_BORDER, mBackgroundBorder); // Tail - mPopup.SetProperty( Toolkit::Popup::Property::TAIL_VISIBILITY, mTailVisibility ); - mPopup.SetProperty( Toolkit::Popup::Property::TAIL_UP_IMAGE, mTailImages[ Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL ] ); - mPopup.SetProperty( Toolkit::Popup::Property::TAIL_DOWN_IMAGE, mTailImages[ Toolkit::Tooltip::Tail::Property::BELOW_VISUAL ] ); + mPopup.SetProperty(Toolkit::Popup::Property::TAIL_VISIBILITY, mTailVisibility); + mPopup.SetProperty(Toolkit::Popup::Property::TAIL_UP_IMAGE, mTailImages[Toolkit::Tooltip::Tail::Property::ABOVE_VISUAL]); + mPopup.SetProperty(Toolkit::Popup::Property::TAIL_DOWN_IMAGE, mTailImages[Toolkit::Tooltip::Tail::Property::BELOW_VISUAL]); Vector3 tailPosition; - switch( mPositionType ) + switch(mPositionType) { case Toolkit::Tooltip::Position::HOVER_POINT: case Toolkit::Tooltip::Position::BELOW: { - tailPosition = Vector3( 0.5f, 0.0f, 0.0 ); + tailPosition = Vector3(0.5f, 0.0f, 0.0); break; } case Toolkit::Tooltip::Position::ABOVE: { - tailPosition = Vector3( 0.5f, 1.0f, 0.0 ); + tailPosition = Vector3(0.5f, 1.0f, 0.0); break; } } - mPopup.SetProperty( Toolkit::Popup::Property::TAIL_POSITION, tailPosition ); + mPopup.SetProperty(Toolkit::Popup::Property::TAIL_POSITION, tailPosition); // Content Actor content; - if( ! mContentTextVisual.Empty() ) + if(!mContentTextVisual.Empty()) { content = Toolkit::Control::New(); - content.SetProperty( Toolkit::Control::Property::BACKGROUND, mContentTextVisual ); + content.SetProperty(Toolkit::Control::Property::BACKGROUND, mContentTextVisual); } - else if( ! mContentArray.Empty() ) + else if(!mContentArray.Empty()) { const unsigned int visuals = mContentArray.Size(); - unsigned int rows = mLayout.x; - unsigned int columns = mLayout.y; - if( Equals( mLayout.x, 1.0f, Math::MACHINE_EPSILON_1 ) && - Equals( mLayout.y, 1.0f, Math::MACHINE_EPSILON_1 ) && - visuals > 1 ) + unsigned int rows = mLayout.x; + unsigned int columns = mLayout.y; + if(Equals(mLayout.x, 1.0f, Math::MACHINE_EPSILON_1) && + Equals(mLayout.y, 1.0f, Math::MACHINE_EPSILON_1) && + visuals > 1) { - rows = mLayout.x; + rows = mLayout.x; columns = visuals; } - Toolkit::TableView tableView = Toolkit::TableView::New( rows, columns ); - tableView.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS ); + Toolkit::TableView tableView = Toolkit::TableView::New(rows, columns); + tableView.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS); - for( unsigned int currentContent = 0, currentRow = 0; currentRow < rows && currentContent < visuals; ++currentRow ) + for(unsigned int currentContent = 0, currentRow = 0; currentRow < rows && currentContent < visuals; ++currentRow) { - tableView.SetFitHeight( currentRow ); - for( unsigned int currentColumn = 0; currentColumn < columns && currentContent < visuals; ++currentColumn ) + tableView.SetFitHeight(currentRow); + for(unsigned int currentColumn = 0; currentColumn < columns && currentContent < visuals; ++currentColumn) { Actor child = Toolkit::Control::New(); - child.SetProperty( Toolkit::Control::Property::BACKGROUND, mContentArray[ currentContent ] ); + child.SetProperty(Toolkit::Control::Property::BACKGROUND, mContentArray[currentContent]); - Toolkit::TableView::CellPosition cellPosition( currentRow, currentColumn ); - tableView.AddChild( child, cellPosition ); - tableView.SetCellAlignment( cellPosition, HorizontalAlignment::CENTER, VerticalAlignment::CENTER ); - tableView.SetFitWidth( currentColumn ); + Toolkit::TableView::CellPosition cellPosition(currentRow, currentColumn); + tableView.AddChild(child, cellPosition); + tableView.SetCellAlignment(cellPosition, HorizontalAlignment::CENTER, VerticalAlignment::CENTER); + tableView.SetFitWidth(currentColumn); ++currentContent; } } content = tableView; } - mPopup.SetContent( content ); + mPopup.SetContent(content); // Connect to the relayout signal of the background of the popup as at that point we have the full size - Actor popupBackground = GetImpl( mPopup ).GetPopupBackgroundImage(); - if( popupBackground ) + Actor popupBackground = GetImpl(mPopup).GetPopupBackgroundImage(); + if(popupBackground) { - popupBackground.OnRelayoutSignal().Connect( this, &Tooltip::OnRelayout ); + popupBackground.OnRelayoutSignal().Connect(this, &Tooltip::OnRelayout); } - mPopup.SetDisplayState( Toolkit::Popup::SHOWN ); + mPopup.SetDisplayState(Toolkit::Popup::SHOWN); - Stage::GetCurrent().Add( mPopup ); + Stage::GetCurrent().Add(mPopup); } return false; } -void Tooltip::OnRelayout( Actor actor ) +void Tooltip::OnRelayout(Actor actor) { - if( mPopup && actor ) + if(mPopup && actor) { - float popupWidth = actor.GetRelayoutSize( Dimension::WIDTH ); - float popupHeight = actor.GetRelayoutSize( Dimension::HEIGHT ); - float tailHeight = 0.0f; + float popupWidth = actor.GetRelayoutSize(Dimension::WIDTH); + float popupHeight = actor.GetRelayoutSize(Dimension::HEIGHT); + float tailHeight = 0.0f; Actor tail; - if( mTailVisibility ) + if(mTailVisibility) { // Popup's background has the tail, we want to know the tail size as well. - if( actor.GetChildCount() ) + if(actor.GetChildCount()) { - tail = actor.GetChildAt( 0 ); - if( tail ) + tail = actor.GetChildAt(0); + if(tail) { - tailHeight = tail.GetRelayoutSize( Dimension::HEIGHT ); + tailHeight = tail.GetRelayoutSize(Dimension::HEIGHT); } } } @@ -590,7 +582,7 @@ void Tooltip::OnRelayout( Actor actor ) Vector2 stageSize = Stage::GetCurrent().GetSize(); Vector3 position; - switch( mPositionType ) + switch(mPositionType) { case Toolkit::Tooltip::Position::HOVER_POINT: { @@ -602,10 +594,10 @@ void Tooltip::OnRelayout( Actor actor ) case Toolkit::Tooltip::Position::ABOVE: { Toolkit::Control control = mControl.GetHandle(); - if( control ) + if(control) { - Vector3 worldPos = control.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ); - float height = control.GetRelayoutSize( Dimension::HEIGHT ); + Vector3 worldPos = control.GetCurrentProperty(Actor::Property::WORLD_POSITION); + float height = control.GetRelayoutSize(Dimension::HEIGHT); position.x = stageSize.width * 0.5f + worldPos.x - popupWidth * 0.5f; position.y = stageSize.height * 0.5f + worldPos.y - height * 0.5f - popupHeight * 1.0f - tailHeight; @@ -616,10 +608,10 @@ void Tooltip::OnRelayout( Actor actor ) case Toolkit::Tooltip::Position::BELOW: { Toolkit::Control control = mControl.GetHandle(); - if( control ) + if(control) { - Vector3 worldPos = control.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ); - float height = control.GetRelayoutSize( Dimension::HEIGHT ); + Vector3 worldPos = control.GetCurrentProperty(Actor::Property::WORLD_POSITION); + float height = control.GetRelayoutSize(Dimension::HEIGHT); position.x = stageSize.width * 0.5f + worldPos.x - popupWidth * 0.5f; position.y = stageSize.height * 0.5f + worldPos.y + height * 0.5f + tailHeight; @@ -630,34 +622,34 @@ void Tooltip::OnRelayout( Actor actor ) // Ensure the Popup is still on the screen - if( position.x < 0.0f ) + if(position.x < 0.0f) { position.x = 0.0f; } - else if( ( position.x + popupWidth ) > stageSize.width ) + else if((position.x + popupWidth) > stageSize.width) { position.x -= position.x + popupWidth - stageSize.width; } bool yPosChanged = false; - if( position.y < 0.0f ) + if(position.y < 0.0f) { yPosChanged = true; - position.y = 0.0f; + position.y = 0.0f; } - else if( ( position.y + popupHeight ) > stageSize.height ) + else if((position.y + popupHeight) > stageSize.height) { yPosChanged = true; position.y -= position.y + popupHeight - stageSize.height; } - if( yPosChanged && tail ) + if(yPosChanged && tail) { // If we change the y position, then the tail may be shown pointing to the wrong control so just hide it. - tail.SetProperty( Actor::Property::VISIBLE, false ); + tail.SetProperty(Actor::Property::VISIBLE, false); } - mPopup.SetProperty( Actor::Property::POSITION, position ); + mPopup.SetProperty(Actor::Property::POSITION, position); } } diff --git a/dali-toolkit/internal/controls/video-view/video-view-impl.cpp b/dali-toolkit/internal/controls/video-view/video-view-impl.cpp old mode 100755 new mode 100644 index 8052be2..d45b21f --- a/dali-toolkit/internal/controls/video-view/video-view-impl.cpp +++ b/dali-toolkit/internal/controls/video-view/video-view-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,83 +19,79 @@ #include "video-view-impl.h" // EXTERNAL INCLUDES -#include -#include -#include -#include +#include #include -#include +#include #include +#include #include -#include +#include +#include +#include // INTERNAL INCLUDES -#include -#include -#include #include #include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::VideoView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::VideoView, Toolkit::Control, Create ); +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::VideoView, Toolkit::Control, Create); -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "video", MAP, VIDEO ) -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "looping", BOOLEAN, LOOPING ) -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "muted", BOOLEAN, MUTED ) -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "volume", MAP, VOLUME ) -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "underlay", BOOLEAN, UNDERLAY ) -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "playPosition", INTEGER, PLAY_POSITION ) -DALI_PROPERTY_REGISTRATION( Toolkit, VideoView, "displayMode", INTEGER, DISPLAY_MODE ) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "video", MAP, VIDEO) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "looping", BOOLEAN, LOOPING) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "muted", BOOLEAN, MUTED) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "volume", MAP, VOLUME) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "underlay", BOOLEAN, UNDERLAY) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "playPosition", INTEGER, PLAY_POSITION) +DALI_PROPERTY_REGISTRATION(Toolkit, VideoView, "displayMode", INTEGER, DISPLAY_MODE) -DALI_SIGNAL_REGISTRATION( Toolkit, VideoView, "finished", FINISHED_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, VideoView, "finished", FINISHED_SIGNAL) -DALI_ACTION_REGISTRATION( Toolkit, VideoView, "play", ACTION_VIDEOVIEW_PLAY ) -DALI_ACTION_REGISTRATION( Toolkit, VideoView, "pause", ACTION_VIDEOVIEW_PAUSE ) -DALI_ACTION_REGISTRATION( Toolkit, VideoView, "stop", ACTION_VIDEOVIEW_STOP ) -DALI_ACTION_REGISTRATION( Toolkit, VideoView, "forward", ACTION_VIDEOVIEW_FORWARD ) -DALI_ACTION_REGISTRATION( Toolkit, VideoView, "backward", ACTION_VIDEOVIEW_BACKWARD ) +DALI_ACTION_REGISTRATION(Toolkit, VideoView, "play", ACTION_VIDEOVIEW_PLAY) +DALI_ACTION_REGISTRATION(Toolkit, VideoView, "pause", ACTION_VIDEOVIEW_PAUSE) +DALI_ACTION_REGISTRATION(Toolkit, VideoView, "stop", ACTION_VIDEOVIEW_STOP) +DALI_ACTION_REGISTRATION(Toolkit, VideoView, "forward", ACTION_VIDEOVIEW_FORWARD) +DALI_ACTION_REGISTRATION(Toolkit, VideoView, "backward", ACTION_VIDEOVIEW_BACKWARD) DALI_TYPE_REGISTRATION_END() -const char* const VOLUME_LEFT( "volumeLeft" ); -const char* const VOLUME_RIGHT( "volumeRight" ); +const char* const VOLUME_LEFT("volumeLeft"); +const char* const VOLUME_RIGHT("volumeRight"); // 3.0 TC uses RENDERING_TARGET. It should be removed in next release -const char* const RENDERING_TARGET( "renderingTarget" ); -const char* const WINDOW_SURFACE_TARGET( "windowSurfaceTarget" ); -const char* const NATIVE_IMAGE_TARGET( "nativeImageTarget" ); +const char* const RENDERING_TARGET("renderingTarget"); +const char* const WINDOW_SURFACE_TARGET("windowSurfaceTarget"); +const char* const NATIVE_IMAGE_TARGET("nativeImageTarget"); -const char* const CUSTOM_SHADER( "shader" ); -const char* const CUSTOM_VERTEX_SHADER( "vertexShader" ); -const char* const CUSTOM_FRAGMENT_SHADER( "fragmentShader" ); -const char* const DEFAULT_SAMPLER_TYPE_NAME( "sampler2D" ); -const char* const CUSTOM_SAMPLER_TYPE_NAME( "samplerExternalOES" ); +const char* const CUSTOM_SHADER("shader"); +const char* const CUSTOM_VERTEX_SHADER("vertexShader"); +const char* const CUSTOM_FRAGMENT_SHADER("fragmentShader"); +const char* const DEFAULT_SAMPLER_TYPE_NAME("sampler2D"); +const char* const CUSTOM_SAMPLER_TYPE_NAME("samplerExternalOES"); -} // anonymous namepsace +} // namespace -VideoView::VideoView( Dali::VideoSyncMode syncMode ) -: Control( ControlBehaviour( ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS ) ), - mCurrentVideoPlayPosition( 0 ), - mFrameID( 0 ), - mIsPlay( false ), - mIsUnderlay( true ), - mSyncMode( syncMode ) +VideoView::VideoView(Dali::VideoSyncMode syncMode) +: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)), + mCurrentVideoPlayPosition(0), + mFrameID(0), + mIsPlay(false), + mIsUnderlay(true), + mSyncMode(syncMode) { } @@ -103,47 +99,47 @@ VideoView::~VideoView() { } -Toolkit::VideoView VideoView::New( VideoSyncMode syncMode ) +Toolkit::VideoView VideoView::New(VideoSyncMode syncMode) { - VideoView* impl = new VideoView( syncMode ); - Toolkit::VideoView handle = Toolkit::VideoView( *impl ); + VideoView* impl = new VideoView(syncMode); + Toolkit::VideoView handle = Toolkit::VideoView(*impl); - impl->mVideoPlayer = Dali::VideoPlayer::New( impl->Self(), syncMode ); + impl->mVideoPlayer = Dali::VideoPlayer::New(impl->Self(), syncMode); impl->Initialize(); return handle; } void VideoView::OnInitialize() { - mVideoPlayer.FinishedSignal().Connect( this, &VideoView::EmitSignalFinish ); + mVideoPlayer.FinishedSignal().Connect(this, &VideoView::EmitSignalFinish); - DevelControl::SetAccessibilityConstructor( Self(), []( Dali::Actor actor ) { - return std::unique_ptr< Dali::Accessibility::Accessible >( - new Control::Impl::AccessibleImpl( actor, Dali::Accessibility::Role::VIDEO )); - } ); + DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { + return std::unique_ptr( + new Control::Impl::AccessibleImpl(actor, Dali::Accessibility::Role::VIDEO)); + }); } -void VideoView::SetUrl( const std::string& url ) +void VideoView::SetUrl(const std::string& url) { - mUrl = url; - mPropertyMap.Clear(); + mUrl = url; + mPropertyMap.Clear(); - mVideoPlayer.SetUrl( mUrl ); + mVideoPlayer.SetUrl(mUrl); } -void VideoView::SetPropertyMap( Property::Map map ) +void VideoView::SetPropertyMap(Property::Map map) { mPropertyMap = map; - Property::Value* target = map.Find( RENDERING_TARGET ); - std::string targetType; + Property::Value* target = map.Find(RENDERING_TARGET); + std::string targetType; - if( target && target->Get( targetType ) && targetType == WINDOW_SURFACE_TARGET ) + if(target && target->Get(targetType) && targetType == WINDOW_SURFACE_TARGET) { mIsUnderlay = true; SetWindowSurfaceTarget(); } - else if( target && target->Get( targetType ) && targetType == NATIVE_IMAGE_TARGET ) + else if(target && target->Get(targetType) && targetType == NATIVE_IMAGE_TARGET) { mIsUnderlay = false; SetNativeImageTarget(); @@ -151,24 +147,24 @@ void VideoView::SetPropertyMap( Property::Map map ) // Custom shader Property::Value* shaderValue; - if( !map.Empty() ) + if(!map.Empty()) { - shaderValue = map.Find( CUSTOM_SHADER ); + shaderValue = map.Find(CUSTOM_SHADER); - if( shaderValue ) + if(shaderValue) { Property::Map* shaderMap = shaderValue->GetMap(); - if( shaderMap ) + if(shaderMap) { mEffectPropertyMap = *shaderMap; } } } - if( mTextureRenderer && !mEffectPropertyMap.Empty() ) + if(mTextureRenderer && !mEffectPropertyMap.Empty()) { Dali::Shader shader = CreateShader(); - mTextureRenderer.SetShader( shader ); + mTextureRenderer.SetShader(shader); } RelayoutRequest(); @@ -179,9 +175,9 @@ std::string VideoView::GetUrl() return mUrl; } -void VideoView::SetLooping( bool looping ) +void VideoView::SetLooping(bool looping) { - mVideoPlayer.SetLooping( looping ); + mVideoPlayer.SetLooping(looping); } bool VideoView::IsLooping() @@ -207,28 +203,28 @@ void VideoView::Stop() mIsPlay = false; } -void VideoView::Forward( int millisecond ) +void VideoView::Forward(int millisecond) { int curPos = mVideoPlayer.GetPlayPosition(); int nextPos = curPos + millisecond; - mVideoPlayer.SetPlayPosition( nextPos ); + mVideoPlayer.SetPlayPosition(nextPos); } -void VideoView::Backward( int millisecond ) +void VideoView::Backward(int millisecond) { int curPos = mVideoPlayer.GetPlayPosition(); int nextPos = curPos - millisecond; - nextPos = ( nextPos < 0 )? 0: nextPos; + nextPos = (nextPos < 0) ? 0 : nextPos; - mVideoPlayer.SetPlayPosition( nextPos ); + mVideoPlayer.SetPlayPosition(nextPos); } -void VideoView::SetMute( bool mute ) +void VideoView::SetMute(bool mute) { - mVideoPlayer.SetMute( mute ); + mVideoPlayer.SetMute(mute); } bool VideoView::IsMuted() @@ -236,14 +232,14 @@ bool VideoView::IsMuted() return mVideoPlayer.IsMuted(); } -void VideoView::SetVolume( float left, float right ) +void VideoView::SetVolume(float left, float right) { - mVideoPlayer.SetVolume( left, right ); + mVideoPlayer.SetVolume(left, right); } -void VideoView::GetVolume( float& left, float& right ) +void VideoView::GetVolume(float& left, float& right) { - mVideoPlayer.GetVolume( left, right ); + mVideoPlayer.GetVolume(left, right); } Dali::Toolkit::VideoView::VideoViewSignalType& VideoView::FinishedSignal() @@ -253,57 +249,57 @@ Dali::Toolkit::VideoView::VideoViewSignalType& VideoView::FinishedSignal() void VideoView::EmitSignalFinish() { - if ( !mFinishedSignal.Empty() ) + if(!mFinishedSignal.Empty()) { - Dali::Toolkit::VideoView handle( GetOwner() ); - mFinishedSignal.Emit( handle ); + Dali::Toolkit::VideoView handle(GetOwner()); + mFinishedSignal.Emit(handle); } } -bool VideoView::DoAction( BaseObject* object, const std::string& actionName, const Property::Map& attributes ) +bool VideoView::DoAction(BaseObject* object, const std::string& actionName, const Property::Map& attributes) { bool ret = false; - Dali::BaseHandle handle( object ); - Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( handle ); + Dali::BaseHandle handle(object); + Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(handle); - if( !videoView ) + if(!videoView) { return ret; } - VideoView& impl = GetImpl( videoView ); + VideoView& impl = GetImpl(videoView); - if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_PLAY ) == 0 ) + if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_PLAY) == 0) { impl.Play(); ret = true; } - else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_PAUSE ) == 0 ) + else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_PAUSE) == 0) { impl.Pause(); ret = true; } - else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_STOP ) == 0 ) + else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_STOP) == 0) { impl.Stop(); ret = true; } - else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_FORWARD ) == 0 ) + else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_FORWARD) == 0) { int millisecond = 0; - if( attributes["videoForward"].Get( millisecond ) ) + if(attributes["videoForward"].Get(millisecond)) { - impl.Forward( millisecond ); + impl.Forward(millisecond); ret = true; } } - else if( strcmp( actionName.c_str(), ACTION_VIDEOVIEW_BACKWARD ) == 0 ) + else if(strcmp(actionName.c_str(), ACTION_VIDEOVIEW_BACKWARD) == 0) { int millisecond = 0; - if( attributes["videoBackward"].Get( millisecond ) ) + if(attributes["videoBackward"].Get(millisecond)) { - impl.Backward( millisecond ); + impl.Backward(millisecond); ret = true; } } @@ -311,16 +307,16 @@ bool VideoView::DoAction( BaseObject* object, const std::string& actionName, con return ret; } -bool VideoView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool VideoView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( handle ); + bool connected(true); + Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), FINISHED_SIGNAL ) ) + if(0 == strcmp(signalName.c_str(), FINISHED_SIGNAL)) { - videoView.FinishedSignal().Connect( tracker, functor ); + videoView.FinishedSignal().Connect(tracker, functor); } else { @@ -331,54 +327,54 @@ bool VideoView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* return connected; } -void VideoView::SetPropertyInternal( Property::Index index, const Property::Value& value ) +void VideoView::SetPropertyInternal(Property::Index index, const Property::Value& value) { - switch( index ) + switch(index) { case Toolkit::VideoView::Property::VIDEO: { - std::string videoUrl; + std::string videoUrl; Property::Map map; - if( value.Get( videoUrl ) ) + if(value.Get(videoUrl)) { - SetUrl( videoUrl ); + SetUrl(videoUrl); } - else if( value.Get( map ) ) + else if(value.Get(map)) { - SetPropertyMap( map ); + SetPropertyMap(map); } break; } case Toolkit::VideoView::Property::LOOPING: { bool looping; - if( value.Get( looping ) ) + if(value.Get(looping)) { - SetLooping( looping ); + SetLooping(looping); } break; } case Toolkit::VideoView::Property::MUTED: { bool mute; - if( value.Get( mute ) ) + if(value.Get(mute)) { - SetMute( mute ); + SetMute(mute); } break; } case Toolkit::VideoView::Property::VOLUME: { Property::Map map; - float left, right; - if( value.Get( map ) ) + float left, right; + if(value.Get(map)) { - Property::Value* volumeLeft = map.Find( VOLUME_LEFT ); - Property::Value* volumeRight = map.Find( VOLUME_RIGHT ); - if( volumeLeft && volumeLeft->Get( left ) && volumeRight && volumeRight->Get( right ) ) + Property::Value* volumeLeft = map.Find(VOLUME_LEFT); + Property::Value* volumeRight = map.Find(VOLUME_RIGHT); + if(volumeLeft && volumeLeft->Get(left) && volumeRight && volumeRight->Get(right)) { - SetVolume( left, right ); + SetVolume(left, right); } } break; @@ -386,44 +382,44 @@ void VideoView::SetPropertyInternal( Property::Index index, const Property::Valu case Toolkit::VideoView::Property::UNDERLAY: { bool underlay; - if( value.Get( underlay ) ) + if(value.Get(underlay)) { - SetUnderlay( underlay ); + SetUnderlay(underlay); } break; } case Toolkit::VideoView::Property::PLAY_POSITION: { int pos; - if( value.Get( pos ) ) + if(value.Get(pos)) { - SetPlayPosition( pos ); + SetPlayPosition(pos); } break; } case Toolkit::VideoView::Property::DISPLAY_MODE: { int mode; - if( value.Get( mode ) ) + if(value.Get(mode)) { - SetDisplayMode( mode ); + SetDisplayMode(mode); } break; } } } -void VideoView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void VideoView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(Dali::BaseHandle(object)); - if( videoView ) + if(videoView) { - VideoView& impl = GetImpl( videoView ); + VideoView& impl = GetImpl(videoView); - impl.SetPropertyInternal( index, value ); + impl.SetPropertyInternal(index, value); - if( index != Toolkit::VideoView::Property::UNDERLAY ) + if(index != Toolkit::VideoView::Property::UNDERLAY) { // Backup values. // These values will be used when underlay mode is changed. @@ -432,24 +428,24 @@ void VideoView::SetProperty( BaseObject* object, Property::Index index, const Pr } } -Property::Value VideoView::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value VideoView::GetProperty(BaseObject* object, Property::Index propertyIndex) { - Property::Value value; - Toolkit::VideoView videoView = Toolkit::VideoView::DownCast( Dali::BaseHandle( object ) ); + Property::Value value; + Toolkit::VideoView videoView = Toolkit::VideoView::DownCast(Dali::BaseHandle(object)); - if( videoView ) + if(videoView) { - VideoView& impl = GetImpl( videoView ); + VideoView& impl = GetImpl(videoView); - switch( propertyIndex ) + switch(propertyIndex) { case Toolkit::VideoView::Property::VIDEO: { - if( !impl.mUrl.empty() ) + if(!impl.mUrl.empty()) { value = impl.mUrl; } - else if( !impl.mPropertyMap.Empty() ) + else if(!impl.mPropertyMap.Empty()) { value = impl.mPropertyMap; } @@ -468,11 +464,11 @@ Property::Value VideoView::GetProperty( BaseObject* object, Property::Index prop case Toolkit::VideoView::Property::VOLUME: { Property::Map map; - float left, right; + float left, right; - impl.GetVolume( left, right ); - map.Insert( VOLUME_LEFT, left ); - map.Insert( VOLUME_RIGHT, right ); + impl.GetVolume(left, right); + map.Insert(VOLUME_LEFT, left); + map.Insert(VOLUME_RIGHT, right); value = map; break; } @@ -497,19 +493,19 @@ Property::Value VideoView::GetProperty( BaseObject* object, Property::Index prop return value; } -void VideoView::SetDepthIndex( int depthIndex ) +void VideoView::SetDepthIndex(int depthIndex) { - if( mTextureRenderer ) + if(mTextureRenderer) { - mTextureRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, depthIndex ); + mTextureRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, depthIndex); } } -void VideoView::OnSceneConnection( int depth ) +void VideoView::OnSceneConnection(int depth) { - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); - if( mIsUnderlay ) + if(mIsUnderlay) { SetWindowSurfaceTarget(); } @@ -520,14 +516,14 @@ void VideoView::OnSceneDisconnection() Control::OnSceneDisconnection(); } -void VideoView::OnSizeSet( const Vector3& targetSize ) +void VideoView::OnSizeSet(const Vector3& targetSize) { - if( mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED ) + if(mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED) { SetFrameRenderCallback(); mVideoPlayer.StartSynchronization(); } - Control::OnSizeSet( targetSize ); + Control::OnSizeSet(targetSize); } Vector3 VideoView::GetNaturalSize() @@ -536,9 +532,9 @@ Vector3 VideoView::GetNaturalSize() size.x = mVideoSize.GetWidth(); size.y = mVideoSize.GetHeight(); - if( size.x > 0 && size.y > 0 ) + if(size.x > 0 && size.y > 0) { - size.z = std::min( size.x, size.y ); + size.z = std::min(size.x, size.y); return size; } else @@ -547,27 +543,27 @@ Vector3 VideoView::GetNaturalSize() } } -float VideoView::GetHeightForWidth( float width ) +float VideoView::GetHeightForWidth(float width) { - if( mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0 ) + if(mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0) { - return GetHeightForWidthBase( width ); + return GetHeightForWidthBase(width); } else { - return Control::GetHeightForWidthBase( width ); + return Control::GetHeightForWidthBase(width); } } -float VideoView::GetWidthForHeight( float height ) +float VideoView::GetWidthForHeight(float height) { - if( mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0 ) + if(mVideoSize.GetWidth() > 0 && mVideoSize.GetHeight() > 0) { - return GetWidthForHeightBase( height ); + return GetWidthForHeightBase(height); } else { - return Control::GetWidthForHeightBase( height ); + return Control::GetWidthForHeightBase(height); } } @@ -575,7 +571,7 @@ void VideoView::SetWindowSurfaceTarget() { Actor self = Self(); - if( !self.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(!self.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { // When the control is off the stage, it does not have Window. return; @@ -583,147 +579,147 @@ void VideoView::SetWindowSurfaceTarget() int curPos = mVideoPlayer.GetPlayPosition(); - if( mIsPlay ) + if(mIsPlay) { mVideoPlayer.Pause(); } - mPositionUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_POSITION, StepCondition( 1.0f, 1.0f ) ); - mSizeUpdateNotification = self.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 1.0f, 1.0f ) ); - mScaleUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) ); - mPositionUpdateNotification.NotifySignal().Connect( this, &VideoView::UpdateDisplayArea ); - mSizeUpdateNotification.NotifySignal().Connect( this, &VideoView::UpdateDisplayArea ); - mScaleUpdateNotification.NotifySignal().Connect( this, &VideoView::UpdateDisplayArea ); + mPositionUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_POSITION, StepCondition(1.0f, 1.0f)); + mSizeUpdateNotification = self.AddPropertyNotification(Actor::Property::SIZE, StepCondition(1.0f, 1.0f)); + mScaleUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f)); + mPositionUpdateNotification.NotifySignal().Connect(this, &VideoView::UpdateDisplayArea); + mSizeUpdateNotification.NotifySignal().Connect(this, &VideoView::UpdateDisplayArea); + mScaleUpdateNotification.NotifySignal().Connect(this, &VideoView::UpdateDisplayArea); - if( mTextureRenderer ) + if(mTextureRenderer) { - self.RemoveRenderer( mTextureRenderer ); + self.RemoveRenderer(mTextureRenderer); } // Note VideoPlayer::SetRenderingTarget resets all the options. (e.g. url, mute, looping) - mVideoPlayer.SetRenderingTarget( Dali::Adaptor::Get().GetNativeWindowHandle( self ) ); + mVideoPlayer.SetRenderingTarget(Dali::Adaptor::Get().GetNativeWindowHandle(self)); ApplyBackupProperties(); - if( !mOverlayRenderer ) + if(!mOverlayRenderer) { // For underlay rendering mode, video display area have to be transparent. Geometry geometry = VisualFactoryCache::CreateQuadGeometry(); - Shader shader = Shader::New( SHADER_VIDEO_VIEW_VERT, SHADER_VIDEO_VIEW_FRAG ); - mOverlayRenderer = Renderer::New( geometry, shader ); - mOverlayRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::OFF ); + Shader shader = Shader::New(SHADER_VIDEO_VIEW_VERT, SHADER_VIDEO_VIEW_FRAG); + mOverlayRenderer = Renderer::New(geometry, shader); + mOverlayRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::OFF); } - Self().AddRenderer( mOverlayRenderer ); + Self().AddRenderer(mOverlayRenderer); - if( mIsPlay ) + if(mIsPlay) { Play(); } - if( curPos > 0 ) + if(curPos > 0) { - mVideoPlayer.SetPlayPosition( curPos ); + mVideoPlayer.SetPlayPosition(curPos); } } void VideoView::SetNativeImageTarget() { - if( mVideoPlayer.IsVideoTextureSupported() == false ) + if(mVideoPlayer.IsVideoTextureSupported() == false) { - DALI_LOG_ERROR( "Platform doesn't support decoded video frame images\n" ); + DALI_LOG_ERROR("Platform doesn't support decoded video frame images\n"); mIsUnderlay = true; return; } - if( mIsPlay ) + if(mIsPlay) { mVideoPlayer.Pause(); } - Actor self( Self() ); + Actor self(Self()); - if( mOverlayRenderer ) + if(mOverlayRenderer) { - self.RemoveRenderer( mOverlayRenderer ); + self.RemoveRenderer(mOverlayRenderer); mOverlayRenderer.Reset(); } - self.RemovePropertyNotification( mPositionUpdateNotification ); - self.RemovePropertyNotification( mSizeUpdateNotification ); - self.RemovePropertyNotification( mScaleUpdateNotification ); + self.RemovePropertyNotification(mPositionUpdateNotification); + self.RemovePropertyNotification(mSizeUpdateNotification); + self.RemovePropertyNotification(mScaleUpdateNotification); int curPos = mVideoPlayer.GetPlayPosition(); - Any source; - Dali::NativeImageSourcePtr nativeImageSourcePtr = Dali::NativeImageSource::New( source ); - mNativeTexture = Dali::Texture::New( *nativeImageSourcePtr ); + Any source; + Dali::NativeImageSourcePtr nativeImageSourcePtr = Dali::NativeImageSource::New(source); + mNativeTexture = Dali::Texture::New(*nativeImageSourcePtr); - if( !mTextureRenderer ) + if(!mTextureRenderer) { - Dali::Geometry geometry = VisualFactoryCache::CreateQuadGeometry(); - Dali::Shader shader = CreateShader(); + Dali::Geometry geometry = VisualFactoryCache::CreateQuadGeometry(); + Dali::Shader shader = CreateShader(); Dali::TextureSet textureSet = Dali::TextureSet::New(); - textureSet.SetTexture( 0u, mNativeTexture ); + textureSet.SetTexture(0u, mNativeTexture); - mTextureRenderer = Renderer::New( geometry, shader ); - mTextureRenderer.SetTextures( textureSet ); + mTextureRenderer = Renderer::New(geometry, shader); + mTextureRenderer.SetTextures(textureSet); } else { Dali::TextureSet textureSet = mTextureRenderer.GetTextures(); - textureSet.SetTexture( 0u, mNativeTexture ); + textureSet.SetTexture(0u, mNativeTexture); } - Self().AddRenderer( mTextureRenderer ); + Self().AddRenderer(mTextureRenderer); // Note VideoPlayer::SetRenderingTarget resets all the options. (e.g. url, mute, looping) - mVideoPlayer.SetRenderingTarget( nativeImageSourcePtr ); + mVideoPlayer.SetRenderingTarget(nativeImageSourcePtr); ApplyBackupProperties(); - if( mIsPlay ) + if(mIsPlay) { Play(); } - if( curPos > 0 ) + if(curPos > 0) { - mVideoPlayer.SetPlayPosition( curPos ); + mVideoPlayer.SetPlayPosition(curPos); } } -void VideoView::UpdateDisplayArea( Dali::PropertyNotification& source ) +void VideoView::UpdateDisplayArea(Dali::PropertyNotification& source) { // If mSyncMode is enabled, Video player's size and poistion is updated in Video player's constraint. // Because video view and player should be work syncronization. - if( !mIsUnderlay || mSyncMode == Dali::VideoSyncMode::ENABLED ) + if(!mIsUnderlay || mSyncMode == Dali::VideoSyncMode::ENABLED) { return; } - Actor self( Self() ); + Actor self(Self()); - bool positionUsesAnchorPoint = self.GetProperty( Actor::Property::POSITION_USES_ANCHOR_POINT ).Get< bool >(); - Vector3 actorSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * self.GetCurrentProperty< Vector3 >( Actor::Property::SCALE ); - Vector3 anchorPointOffSet = actorSize * ( positionUsesAnchorPoint ? self.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) : AnchorPoint::TOP_LEFT ); + bool positionUsesAnchorPoint = self.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT).Get(); + Vector3 actorSize = self.GetCurrentProperty(Actor::Property::SIZE) * self.GetCurrentProperty(Actor::Property::SCALE); + Vector3 anchorPointOffSet = actorSize * (positionUsesAnchorPoint ? self.GetCurrentProperty(Actor::Property::ANCHOR_POINT) : AnchorPoint::TOP_LEFT); - Vector2 screenPosition = self.GetProperty( Actor::Property::SCREEN_POSITION ).Get< Vector2 >(); + Vector2 screenPosition = self.GetProperty(Actor::Property::SCREEN_POSITION).Get(); - mDisplayArea.x = screenPosition.x - anchorPointOffSet.x; - mDisplayArea.y = screenPosition.y - anchorPointOffSet.y; - mDisplayArea.width = actorSize.x; + mDisplayArea.x = screenPosition.x - anchorPointOffSet.x; + mDisplayArea.y = screenPosition.y - anchorPointOffSet.y; + mDisplayArea.width = actorSize.x; mDisplayArea.height = actorSize.y; - mVideoPlayer.SetDisplayArea( mDisplayArea ); + mVideoPlayer.SetDisplayArea(mDisplayArea); } -void VideoView::SetUnderlay( bool set ) +void VideoView::SetUnderlay(bool set) { - if( set != mIsUnderlay ) + if(set != mIsUnderlay) { mIsUnderlay = set; - if( mIsUnderlay ) + if(mIsUnderlay) { SetWindowSurfaceTarget(); } @@ -741,17 +737,17 @@ bool VideoView::IsUnderlay() return mIsUnderlay; } -void VideoView::SetSWCodec( bool on ) +void VideoView::SetSWCodec(bool on) { // If setting SW or HW type is failed , video-view shows video by default codec type. // The default codec type is selected by platform. - if( on ) + if(on) { - mVideoPlayer.SetCodecType( Dali::VideoPlayerPlugin::CodecType::SW ); + mVideoPlayer.SetCodecType(Dali::VideoPlayerPlugin::CodecType::SW); } else { - mVideoPlayer.SetCodecType( Dali::VideoPlayerPlugin::CodecType::HW ); + mVideoPlayer.SetCodecType(Dali::VideoPlayerPlugin::CodecType::HW); } } @@ -760,19 +756,19 @@ int VideoView::GetPlayPosition() return mVideoPlayer.GetPlayPosition(); } -void VideoView::SetPlayPosition( int pos ) +void VideoView::SetPlayPosition(int pos) { - mVideoPlayer.SetPlayPosition( pos ); + mVideoPlayer.SetPlayPosition(pos); } -void VideoView::SetDisplayMode( int mode ) +void VideoView::SetDisplayMode(int mode) { - mVideoPlayer.SetDisplayMode( static_cast< Dali::VideoPlayerPlugin::DisplayMode::Type >( mode ) ); + mVideoPlayer.SetDisplayMode(static_cast(mode)); } int VideoView::GetDisplayMode() const { - return static_cast< int >( mVideoPlayer.GetDisplayMode() ); + return static_cast(mVideoPlayer.GetDisplayMode()); } Any VideoView::GetMediaPlayer() @@ -780,18 +776,18 @@ Any VideoView::GetMediaPlayer() return mVideoPlayer.GetMediaPlayer(); } -void VideoView::OnAnimationFinished( Animation& animation ) +void VideoView::OnAnimationFinished(Animation& animation) { // send desync SetFrameRenderCallback(); } -void VideoView::PlayAnimation( Dali::Animation animation ) +void VideoView::PlayAnimation(Dali::Animation animation) { - if( mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED ) + if(mIsUnderlay && mSyncMode == Dali::VideoSyncMode::ENABLED) { mVideoPlayer.StartSynchronization(); - animation.FinishedSignal().Connect( this, &VideoView::OnAnimationFinished ); + animation.FinishedSignal().Connect(this, &VideoView::OnAnimationFinished); } animation.Play(); } @@ -801,33 +797,33 @@ Dali::Shader VideoView::CreateShader() std::string fragmentShader = "#extension GL_OES_EGL_image_external:require\n"; std::string vertexShader; std::string customFragmentShader; - bool checkShader = false; + bool checkShader = false; - if( !mEffectPropertyMap.Empty() ) + if(!mEffectPropertyMap.Empty()) { - Property::Value* vertexShaderValue = mEffectPropertyMap.Find( CUSTOM_VERTEX_SHADER ); - if( vertexShaderValue ) + Property::Value* vertexShaderValue = mEffectPropertyMap.Find(CUSTOM_VERTEX_SHADER); + if(vertexShaderValue) { - checkShader = GetStringFromProperty( *vertexShaderValue, vertexShader ); + checkShader = GetStringFromProperty(*vertexShaderValue, vertexShader); } - if( !vertexShaderValue || !checkShader ) + if(!vertexShaderValue || !checkShader) { vertexShader = SHADER_VIDEO_VIEW_TEXTURE_VERT.data(); } - Property::Value* fragmentShaderValue = mEffectPropertyMap.Find( CUSTOM_FRAGMENT_SHADER ); - if( fragmentShaderValue ) + Property::Value* fragmentShaderValue = mEffectPropertyMap.Find(CUSTOM_FRAGMENT_SHADER); + if(fragmentShaderValue) { - checkShader = GetStringFromProperty( *fragmentShaderValue, customFragmentShader ); + checkShader = GetStringFromProperty(*fragmentShaderValue, customFragmentShader); - if( checkShader ) + if(checkShader) { fragmentShader = customFragmentShader; } } - if( !fragmentShaderValue || !checkShader ) + if(!fragmentShaderValue || !checkShader) { fragmentShader += SHADER_VIDEO_VIEW_TEXTURE_FRAG.data(); } @@ -838,13 +834,13 @@ Dali::Shader VideoView::CreateShader() fragmentShader += SHADER_VIDEO_VIEW_TEXTURE_FRAG.data(); } - return Dali::Shader::New( vertexShader, fragmentShader ); + return Dali::Shader::New(vertexShader, fragmentShader); } -bool VideoView::GetStringFromProperty( const Dali::Property::Value& value, std::string& output ) +bool VideoView::GetStringFromProperty(const Dali::Property::Value& value, std::string& output) { bool extracted = false; - if( value.Get( output ) ) + if(value.Get(output)) { extracted = true; } @@ -854,21 +850,21 @@ bool VideoView::GetStringFromProperty( const Dali::Property::Value& value, std:: void VideoView::ApplyBackupProperties() { - Property::Map::SizeType pos = 0; + Property::Map::SizeType pos = 0; Property::Map::SizeType count = mPropertyBackup.Count(); - for( ; pos < count; pos++ ) + for(; pos < count; pos++) { - KeyValuePair property = mPropertyBackup.GetKeyValue( pos ); + KeyValuePair property = mPropertyBackup.GetKeyValue(pos); - SetPropertyInternal( property.first.indexKey, property.second ); + SetPropertyInternal(property.first.indexKey, property.second); } } -void VideoView::FrameRenderCallback( int frameID ) +void VideoView::FrameRenderCallback(int frameID) { // send desync - if( frameID == mFrameID ) + if(frameID == mFrameID) { mVideoPlayer.FinishSynchronization(); mFrameID = 0; @@ -878,12 +874,13 @@ void VideoView::FrameRenderCallback( int frameID ) void VideoView::SetFrameRenderCallback() { mFrameID++; - DevelWindow::AddFrameRenderedCallback( DevelWindow::Get( Self() ), - std::unique_ptr< CallbackBase >( MakeCallback( this, &VideoView::FrameRenderCallback ) ), mFrameID ); + DevelWindow::AddFrameRenderedCallback(DevelWindow::Get(Self()), + std::unique_ptr(MakeCallback(this, &VideoView::FrameRenderCallback)), + mFrameID); } } // namespace Internal -} // namespace toolkit +} // namespace Toolkit } // namespace Dali diff --git a/dali-toolkit/internal/controls/web-view/web-view-impl.cpp b/dali-toolkit/internal/controls/web-view/web-view-impl.cpp old mode 100755 new mode 100644 index 9e31e46..f7f1663 --- a/dali-toolkit/internal/controls/web-view/web-view-impl.cpp +++ b/dali-toolkit/internal/controls/web-view/web-view-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,17 +19,17 @@ #include "web-view-impl.h" // EXTERNAL INCLUDES -#include #include #include #include #include +#include #include #include -#include #include -#include #include +#include +#include // INTERNAL INCLUDES #include @@ -44,98 +44,96 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { return Toolkit::WebView::New(); } -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::WebView, Toolkit::Control, Create ) +// clang-format off +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::WebView, Toolkit::Control, Create) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "url", STRING, URL ) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "userAgent", STRING, USER_AGENT ) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "scrollPosition", VECTOR2, SCROLL_POSITION ) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "scrollSize", VECTOR2, SCROLL_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "contentSize", VECTOR2, CONTENT_SIZE ) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "title", STRING, TITLE ) -DALI_PROPERTY_REGISTRATION( Toolkit, WebView, "videoHoleEnabled", BOOLEAN, VIDEO_HOLE_ENABLED ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "url", STRING, URL ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "userAgent", STRING, USER_AGENT ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "scrollPosition", VECTOR2, SCROLL_POSITION ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "scrollSize", VECTOR2, SCROLL_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "contentSize", VECTOR2, CONTENT_SIZE ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "title", STRING, TITLE ) +DALI_PROPERTY_REGISTRATION(Toolkit, WebView, "videoHoleEnabled", BOOLEAN, VIDEO_HOLE_ENABLED) -DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "pageLoadStarted", PAGE_LOAD_STARTED_SIGNAL ) -DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "pageLoadFinished", PAGE_LOAD_FINISHED_SIGNAL ) -DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "pageLoadError", PAGE_LOAD_ERROR_SIGNAL ) -DALI_SIGNAL_REGISTRATION( Toolkit, WebView, "scrollEdgeReached", SCROLL_EDGE_REACHED_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "pageLoadStarted", PAGE_LOAD_STARTED_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "pageLoadFinished", PAGE_LOAD_FINISHED_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "pageLoadError", PAGE_LOAD_ERROR_SIGNAL ) +DALI_SIGNAL_REGISTRATION(Toolkit, WebView, "scrollEdgeReached", SCROLL_EDGE_REACHED_SIGNAL) DALI_TYPE_REGISTRATION_END() +// clang-format on const std::string kEmptyString; -} // anonymous namepsace +} // namespace -#define GET_ENUM_STRING( structName, inputExp ) \ - Scripting::GetLinearEnumerationName< Toolkit::WebView::structName::Type >( static_cast< Toolkit::WebView::structName::Type >( inputExp ), structName##_TABLE, structName##_TABLE_COUNT ) +#define GET_ENUM_STRING(structName, inputExp) \ + Scripting::GetLinearEnumerationName(static_cast(inputExp), structName##_TABLE, structName##_TABLE_COUNT) -#define GET_ENUM_VALUE( structName, inputExp, outputExp ) \ - Scripting::GetEnumerationProperty< Toolkit::WebView::structName::Type >( inputExp, structName##_TABLE, structName##_TABLE_COUNT, outputExp ) +#define GET_ENUM_VALUE(structName, inputExp, outputExp) \ + Scripting::GetEnumerationProperty(inputExp, structName##_TABLE, structName##_TABLE_COUNT, outputExp) -WebView::WebView( const std::string& locale, const std::string& timezoneId ) -: Control( ControlBehaviour( ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS ) ), +WebView::WebView(const std::string& locale, const std::string& timezoneId) +: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)), mUrl(), mVisual(), - mWebViewSize( Stage::GetCurrent().GetSize() ), + mWebViewSize(Stage::GetCurrent().GetSize()), mWebEngine(), mPageLoadStartedSignal(), mPageLoadFinishedSignal(), mPageLoadErrorSignal(), - mVideoHoleEnabled( true ), - mWebViewArea ( 0, 0, mWebViewSize.width, mWebViewSize.height ) + mVideoHoleEnabled(true), + mWebViewArea(0, 0, mWebViewSize.width, mWebViewSize.height) { mWebEngine = Dali::WebEngine::New(); // WebEngine is empty when it is not properly initialized. - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.Create( mWebViewSize.width, mWebViewSize.height, locale, timezoneId ); + mWebEngine.Create(mWebViewSize.width, mWebViewSize.height, locale, timezoneId); } } -WebView::WebView( int argc, char** argv ) -: Control( ControlBehaviour( ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS ) ), +WebView::WebView(int argc, char** argv) +: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)), mUrl(), mVisual(), - mWebViewSize( Stage::GetCurrent().GetSize() ), + mWebViewSize(Stage::GetCurrent().GetSize()), mWebEngine(), mPageLoadStartedSignal(), mPageLoadFinishedSignal(), mPageLoadErrorSignal(), - mVideoHoleEnabled( true ), - mWebViewArea ( 0, 0, mWebViewSize.width, mWebViewSize.height ) + mVideoHoleEnabled(true), + mWebViewArea(0, 0, mWebViewSize.width, mWebViewSize.height) { mWebEngine = Dali::WebEngine::New(); // WebEngine is empty when it is not properly initialized. - if ( mWebEngine ) + if(mWebEngine) { - mWebEngine.Create( mWebViewSize.width, mWebViewSize.height, argc, argv ); + mWebEngine.Create(mWebViewSize.width, mWebViewSize.height, argc, argv); } } WebView::WebView() -: WebView( "", "" ) +: WebView("", "") { } WebView::~WebView() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.Destroy(); } @@ -143,26 +141,26 @@ WebView::~WebView() Toolkit::WebView WebView::New() { - WebView* impl = new WebView(); - Toolkit::WebView handle = Toolkit::WebView( *impl ); + WebView* impl = new WebView(); + Toolkit::WebView handle = Toolkit::WebView(*impl); impl->Initialize(); return handle; } -Toolkit::WebView WebView::New( const std::string& locale, const std::string& timezoneId ) +Toolkit::WebView WebView::New(const std::string& locale, const std::string& timezoneId) { - WebView* impl = new WebView( locale, timezoneId ); - Toolkit::WebView handle = Toolkit::WebView( *impl ); + WebView* impl = new WebView(locale, timezoneId); + Toolkit::WebView handle = Toolkit::WebView(*impl); impl->Initialize(); return handle; } -Toolkit::WebView WebView::New( int argc, char** argv ) +Toolkit::WebView WebView::New(int argc, char** argv) { - WebView* impl = new WebView( argc, argv ); - Toolkit::WebView handle = Toolkit::WebView( *impl ); + WebView* impl = new WebView(argc, argv); + Toolkit::WebView handle = Toolkit::WebView(*impl); impl->Initialize(); return handle; @@ -172,27 +170,27 @@ void WebView::OnInitialize() { Actor self = Self(); - self.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true ); - self.TouchedSignal().Connect( this, &WebView::OnTouchEvent ); + self.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true); + self.TouchedSignal().Connect(this, &WebView::OnTouchEvent); - mPositionUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_POSITION, StepCondition( 1.0f, 1.0f ) ); - mSizeUpdateNotification = self.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 1.0f, 1.0f ) ); - mScaleUpdateNotification = self.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) ); - mPositionUpdateNotification.NotifySignal().Connect( this, &WebView::UpdateDisplayArea ); - mSizeUpdateNotification.NotifySignal().Connect( this, &WebView::UpdateDisplayArea ); - mScaleUpdateNotification.NotifySignal().Connect( this, &WebView::UpdateDisplayArea ); + mPositionUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_POSITION, StepCondition(1.0f, 1.0f)); + mSizeUpdateNotification = self.AddPropertyNotification(Actor::Property::SIZE, StepCondition(1.0f, 1.0f)); + mScaleUpdateNotification = self.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f)); + mPositionUpdateNotification.NotifySignal().Connect(this, &WebView::UpdateDisplayArea); + mSizeUpdateNotification.NotifySignal().Connect(this, &WebView::UpdateDisplayArea); + mScaleUpdateNotification.NotifySignal().Connect(this, &WebView::UpdateDisplayArea); - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.PageLoadStartedSignal().Connect( this, &WebView::OnPageLoadStarted ); - mWebEngine.PageLoadFinishedSignal().Connect( this, &WebView::OnPageLoadFinished ); - mWebEngine.PageLoadErrorSignal().Connect( this, &WebView::OnPageLoadError ); - mWebEngine.ScrollEdgeReachedSignal().Connect( this, &WebView::OnScrollEdgeReached ); + mWebEngine.PageLoadStartedSignal().Connect(this, &WebView::OnPageLoadStarted); + mWebEngine.PageLoadFinishedSignal().Connect(this, &WebView::OnPageLoadFinished); + mWebEngine.PageLoadErrorSignal().Connect(this, &WebView::OnPageLoadError); + mWebEngine.ScrollEdgeReachedSignal().Connect(this, &WebView::OnScrollEdgeReached); - mWebContext = std::unique_ptr( new WebContext( mWebEngine.GetContext() ) ); - mWebCookieManager = std::unique_ptr( new WebCookieManager( mWebEngine.GetCookieManager() ) ); - mWebSettings = std::unique_ptr( new WebSettings( mWebEngine.GetSettings() ) ); - mWebBackForwardList = std::unique_ptr( new WebBackForwardList( mWebEngine.GetBackForwardList() ) ); + mWebContext = std::unique_ptr(new WebContext(mWebEngine.GetContext())); + mWebCookieManager = std::unique_ptr(new WebCookieManager(mWebEngine.GetCookieManager())); + mWebSettings = std::unique_ptr(new WebSettings(mWebEngine.GetSettings())); + mWebBackForwardList = std::unique_ptr(new WebBackForwardList(mWebEngine.GetBackForwardList())); } } @@ -218,68 +216,68 @@ Dali::Toolkit::WebBackForwardList* WebView::GetBackForwardList() const Dali::Toolkit::ImageView& WebView::GetFavicon() { - if ( mWebEngine ) + if(mWebEngine) { Dali::PixelData pixelData = mWebEngine.GetFavicon(); - std::string url = Dali::Toolkit::Image::GenerateUrl( pixelData ); - mFaviconView = Dali::Toolkit::ImageView::New( url ); - mFaviconView.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS ); - mFaviconView.SetProperty( Dali::Actor::Property::SIZE, Vector2( pixelData.GetWidth(), pixelData.GetHeight() ) ); + std::string url = Dali::Toolkit::Image::GenerateUrl(pixelData); + mFaviconView = Dali::Toolkit::ImageView::New(url); + mFaviconView.SetResizePolicy(ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS); + mFaviconView.SetProperty(Dali::Actor::Property::SIZE, Vector2(pixelData.GetWidth(), pixelData.GetHeight())); } return mFaviconView; } -void WebView::LoadUrl( const std::string& url ) +void WebView::LoadUrl(const std::string& url) { mUrl = url; - if( mWebEngine ) + if(mWebEngine) { - Texture texture = Dali::Texture::New( *mWebEngine.GetNativeImageSource() ); - const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture( texture ); - mVisual = Toolkit::VisualFactory::Get().CreateVisual( - { { Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE } , - { Toolkit::ImageVisual::Property::URL, nativeImageUrl } } ); + Texture texture = Dali::Texture::New(*mWebEngine.GetNativeImageSource()); + const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture(texture); + mVisual = Toolkit::VisualFactory::Get().CreateVisual( + {{Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE}, + {Toolkit::ImageVisual::Property::URL, nativeImageUrl}}); - if( mVisual ) + if(mVisual) { // Clean up previously registered visual and add new one. - DevelControl::RegisterVisual( *this, Toolkit::WebView::Property::URL, mVisual ); - mWebEngine.LoadUrl( url ); + DevelControl::RegisterVisual(*this, Toolkit::WebView::Property::URL, mVisual); + mWebEngine.LoadUrl(url); } - if ( mVideoHoleEnabled ) + if(mVideoHoleEnabled) { - EnableBlendMode( false ); + EnableBlendMode(false); } } } -void WebView::LoadHtmlString( const std::string& htmlString ) +void WebView::LoadHtmlString(const std::string& htmlString) { - if( mWebEngine ) + if(mWebEngine) { - Texture texture = Dali::Texture::New( *mWebEngine.GetNativeImageSource() ); - const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture( texture ); - mVisual = Toolkit::VisualFactory::Get().CreateVisual( - { { Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE } , - { Toolkit::ImageVisual::Property::URL, nativeImageUrl } } ); + Texture texture = Dali::Texture::New(*mWebEngine.GetNativeImageSource()); + const std::string nativeImageUrl = Dali::Toolkit::TextureManager::AddTexture(texture); + mVisual = Toolkit::VisualFactory::Get().CreateVisual( + {{Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE}, + {Toolkit::ImageVisual::Property::URL, nativeImageUrl}}); - if( mVisual ) + if(mVisual) { - DevelControl::RegisterVisual( *this, Toolkit::WebView::Property::URL, mVisual ); - mWebEngine.LoadHtmlString( htmlString ); + DevelControl::RegisterVisual(*this, Toolkit::WebView::Property::URL, mVisual); + mWebEngine.LoadHtmlString(htmlString); } - if ( mVideoHoleEnabled ) + if(mVideoHoleEnabled) { - EnableBlendMode( false ); + EnableBlendMode(false); } } } void WebView::Reload() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.Reload(); } @@ -287,7 +285,7 @@ void WebView::Reload() void WebView::StopLoading() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.StopLoading(); } @@ -295,7 +293,7 @@ void WebView::StopLoading() void WebView::Suspend() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.Suspend(); } @@ -303,17 +301,17 @@ void WebView::Suspend() void WebView::Resume() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.Resume(); } } -void WebView::ScrollBy( int deltaX, int deltaY ) +void WebView::ScrollBy(int deltaX, int deltaY) { - if ( mWebEngine ) + if(mWebEngine) { - mWebEngine.ScrollBy( deltaX, deltaY ); + mWebEngine.ScrollBy(deltaX, deltaY); } } @@ -324,7 +322,7 @@ bool WebView::CanGoForward() void WebView::GoForward() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.GoForward(); } @@ -337,31 +335,31 @@ bool WebView::CanGoBack() void WebView::GoBack() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.GoBack(); } } -void WebView::EvaluateJavaScript( const std::string& script, std::function< void( const std::string& ) > resultHandler ) +void WebView::EvaluateJavaScript(const std::string& script, std::function resultHandler) { - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.EvaluateJavaScript( script, resultHandler ); + mWebEngine.EvaluateJavaScript(script, resultHandler); } } -void WebView::AddJavaScriptMessageHandler( const std::string& exposedObjectName, std::function< void( const std::string& ) > handler ) +void WebView::AddJavaScriptMessageHandler(const std::string& exposedObjectName, std::function handler) { - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.AddJavaScriptMessageHandler( exposedObjectName, handler ); + mWebEngine.AddJavaScriptMessageHandler(exposedObjectName, handler); } } void WebView::ClearAllTilesResources() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.ClearAllTilesResources(); } @@ -369,62 +367,62 @@ void WebView::ClearAllTilesResources() void WebView::ClearHistory() { - if( mWebEngine ) + if(mWebEngine) { mWebEngine.ClearHistory(); } } -void WebView::UpdateDisplayArea( Dali::PropertyNotification& /*source*/ ) +void WebView::UpdateDisplayArea(Dali::PropertyNotification& /*source*/) { - if( !mWebEngine ) + if(!mWebEngine) return; - Actor self( Self() ); + Actor self(Self()); - bool positionUsesAnchorPoint = self.GetProperty< bool >( Actor::Property::POSITION_USES_ANCHOR_POINT ); - Vector3 actorSize = self.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * self.GetCurrentProperty< Vector3 >( Actor::Property::SCALE ); - Vector3 anchorPointOffSet = actorSize * ( positionUsesAnchorPoint ? self.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT ) : AnchorPoint::TOP_LEFT ); - Vector2 screenPosition = self.GetProperty< Vector2 >( Actor::Property::SCREEN_POSITION ); + bool positionUsesAnchorPoint = self.GetProperty(Actor::Property::POSITION_USES_ANCHOR_POINT); + Vector3 actorSize = self.GetCurrentProperty(Actor::Property::SIZE) * self.GetCurrentProperty(Actor::Property::SCALE); + Vector3 anchorPointOffSet = actorSize * (positionUsesAnchorPoint ? self.GetCurrentProperty(Actor::Property::ANCHOR_POINT) : AnchorPoint::TOP_LEFT); + Vector2 screenPosition = self.GetProperty(Actor::Property::SCREEN_POSITION); - Dali::Rect< int > displayArea; - displayArea.x = screenPosition.x - anchorPointOffSet.x; - displayArea.y = screenPosition.y - anchorPointOffSet.y; - displayArea.width = actorSize.x; + Dali::Rect displayArea; + displayArea.x = screenPosition.x - anchorPointOffSet.x; + displayArea.y = screenPosition.y - anchorPointOffSet.y; + displayArea.width = actorSize.x; displayArea.height = actorSize.y; - Size displaySize = Size( displayArea.width, displayArea.height ); - if ( mWebViewSize != displaySize ) + Size displaySize = Size(displayArea.width, displayArea.height); + if(mWebViewSize != displaySize) { mWebViewSize = displaySize; } - if (mWebViewArea != displayArea ) + if(mWebViewArea != displayArea) { mWebViewArea = displayArea; - mWebEngine.UpdateDisplayArea( mWebViewArea ); + mWebEngine.UpdateDisplayArea(mWebViewArea); } } -void WebView::EnableVideoHole( bool enabled ) +void WebView::EnableVideoHole(bool enabled) { mVideoHoleEnabled = enabled; - EnableBlendMode( !mVideoHoleEnabled ); + EnableBlendMode(!mVideoHoleEnabled); - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.EnableVideoHole( mVideoHoleEnabled ); + mWebEngine.EnableVideoHole(mVideoHoleEnabled); } } -void WebView::EnableBlendMode( bool blendEnabled ) +void WebView::EnableBlendMode(bool blendEnabled) { Actor self = Self(); - for (uint32_t i = 0; i < self.GetRendererCount(); i++) + for(uint32_t i = 0; i < self.GetRendererCount(); i++) { - Dali::Renderer render = self.GetRendererAt( i ); - render.SetProperty( Renderer::Property::BLEND_MODE, blendEnabled ? BlendMode::ON : BlendMode::OFF ); + Dali::Renderer render = self.GetRendererAt(i); + render.SetProperty(Renderer::Property::BLEND_MODE, blendEnabled ? BlendMode::ON : BlendMode::OFF); } } @@ -448,67 +446,67 @@ Dali::Toolkit::WebView::WebViewScrollEdgeReachedSignalType& WebView::ScrollEdgeR return mScrollEdgeReachedSignal; } -void WebView::OnPageLoadStarted( const std::string& url ) +void WebView::OnPageLoadStarted(const std::string& url) { - if( !mPageLoadStartedSignal.Empty() ) + if(!mPageLoadStartedSignal.Empty()) { - Dali::Toolkit::WebView handle( GetOwner() ); - mPageLoadStartedSignal.Emit( handle, url ); + Dali::Toolkit::WebView handle(GetOwner()); + mPageLoadStartedSignal.Emit(handle, url); } } -void WebView::OnPageLoadFinished( const std::string& url ) +void WebView::OnPageLoadFinished(const std::string& url) { - if( !mPageLoadFinishedSignal.Empty() ) + if(!mPageLoadFinishedSignal.Empty()) { - Dali::Toolkit::WebView handle( GetOwner() ); - mPageLoadFinishedSignal.Emit( handle, url ); + Dali::Toolkit::WebView handle(GetOwner()); + mPageLoadFinishedSignal.Emit(handle, url); } } -void WebView::OnPageLoadError( const std::string& url, int errorCode ) +void WebView::OnPageLoadError(const std::string& url, int errorCode) { - if( !mPageLoadErrorSignal.Empty() ) + if(!mPageLoadErrorSignal.Empty()) { - Dali::Toolkit::WebView handle( GetOwner() ); - mPageLoadErrorSignal.Emit( handle, url, static_cast< Toolkit::WebView::LoadErrorCode >( errorCode ) ); + Dali::Toolkit::WebView handle(GetOwner()); + mPageLoadErrorSignal.Emit(handle, url, static_cast(errorCode)); } } -void WebView::OnScrollEdgeReached( Dali::WebEnginePlugin::ScrollEdge edge ) +void WebView::OnScrollEdgeReached(Dali::WebEnginePlugin::ScrollEdge edge) { - if( !mScrollEdgeReachedSignal.Empty() ) + if(!mScrollEdgeReachedSignal.Empty()) { - Dali::Toolkit::WebView handle( GetOwner() ); - mScrollEdgeReachedSignal.Emit( handle, edge ); + Dali::Toolkit::WebView handle(GetOwner()); + mScrollEdgeReachedSignal.Emit(handle, edge); } } -bool WebView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool WebView::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected = false; - Toolkit::WebView webView = Toolkit::WebView::DownCast( handle ); + bool connected = false; + Toolkit::WebView webView = Toolkit::WebView::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), PAGE_LOAD_STARTED_SIGNAL ) ) + if(0 == strcmp(signalName.c_str(), PAGE_LOAD_STARTED_SIGNAL)) { - webView.PageLoadStartedSignal().Connect( tracker, functor ); + webView.PageLoadStartedSignal().Connect(tracker, functor); connected = true; } - else if( 0 == strcmp( signalName.c_str(), PAGE_LOAD_FINISHED_SIGNAL ) ) + else if(0 == strcmp(signalName.c_str(), PAGE_LOAD_FINISHED_SIGNAL)) { - webView.PageLoadFinishedSignal().Connect( tracker, functor ); + webView.PageLoadFinishedSignal().Connect(tracker, functor); connected = true; } - else if( 0 == strcmp( signalName.c_str(), PAGE_LOAD_ERROR_SIGNAL ) ) + else if(0 == strcmp(signalName.c_str(), PAGE_LOAD_ERROR_SIGNAL)) { - webView.PageLoadErrorSignal().Connect( tracker, functor ); + webView.PageLoadErrorSignal().Connect(tracker, functor); connected = true; } - else if( 0 == strcmp( signalName.c_str(), SCROLL_EDGE_REACHED_SIGNAL ) ) + else if(0 == strcmp(signalName.c_str(), SCROLL_EDGE_REACHED_SIGNAL)) { - webView.ScrollEdgeReachedSignal().Connect( tracker, functor ); + webView.ScrollEdgeReachedSignal().Connect(tracker, functor); connected = true; } @@ -517,65 +515,65 @@ bool WebView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* t Vector3 WebView::GetNaturalSize() { - if( mVisual ) + if(mVisual) { Vector2 rendererNaturalSize; - mVisual.GetNaturalSize( rendererNaturalSize ); - return Vector3( rendererNaturalSize ); + mVisual.GetNaturalSize(rendererNaturalSize); + return Vector3(rendererNaturalSize); } - return Vector3( mWebViewSize ); + return Vector3(mWebViewSize); } -void WebView::OnSceneConnection( int depth ) +void WebView::OnSceneConnection(int depth) { - Control::OnSceneConnection( depth ); + Control::OnSceneConnection(depth); - EnableBlendMode( !mVideoHoleEnabled ); + EnableBlendMode(!mVideoHoleEnabled); } -void WebView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) +void WebView::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { - Toolkit::WebView webView = Toolkit::WebView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::WebView webView = Toolkit::WebView::DownCast(Dali::BaseHandle(object)); - if( webView ) + if(webView) { - WebView& impl = GetImpl( webView ); - switch( index ) + WebView& impl = GetImpl(webView); + switch(index) { case Toolkit::WebView::Property::URL: { std::string url; - if( value.Get( url ) ) + if(value.Get(url)) { - impl.LoadUrl( url ); + impl.LoadUrl(url); } break; } case Toolkit::WebView::Property::USER_AGENT: { std::string input; - if( value.Get( input ) ) + if(value.Get(input)) { - impl.SetUserAgent( input ); + impl.SetUserAgent(input); } break; } case Toolkit::WebView::Property::SCROLL_POSITION: { Vector2 input; - if ( value.Get( input ) ) + if(value.Get(input)) { - impl.SetScrollPosition( input.x, input.y ); + impl.SetScrollPosition(input.x, input.y); } break; } case Toolkit::WebView::Property::VIDEO_HOLE_ENABLED: { bool input; - if( value.Get( input ) ) + if(value.Get(input)) { - impl.EnableVideoHole( input ); + impl.EnableVideoHole(input); } break; } @@ -583,16 +581,16 @@ void WebView::SetProperty( BaseObject* object, Property::Index index, const Prop } } -Property::Value WebView::GetProperty( BaseObject* object, Property::Index propertyIndex ) +Property::Value WebView::GetProperty(BaseObject* object, Property::Index propertyIndex) { Property::Value value; - Toolkit::WebView webView = Toolkit::WebView::DownCast( Dali::BaseHandle( object ) ); + Toolkit::WebView webView = Toolkit::WebView::DownCast(Dali::BaseHandle(object)); - if( webView ) + if(webView) { - WebView& impl = GetImpl( webView ); - switch( propertyIndex ) + WebView& impl = GetImpl(webView); + switch(propertyIndex) { case Toolkit::WebView::Property::URL: { @@ -630,60 +628,60 @@ Property::Value WebView::GetProperty( BaseObject* object, Property::Index proper break; } default: - break; + break; } } return value; } -bool WebView::OnTouchEvent( Actor actor, const Dali::TouchEvent& touch ) +bool WebView::OnTouchEvent(Actor actor, const Dali::TouchEvent& touch) { bool result = false; - if( mWebEngine ) + if(mWebEngine) { - result = mWebEngine.SendTouchEvent( touch ); + result = mWebEngine.SendTouchEvent(touch); } return result; } -bool WebView::OnKeyEvent( const Dali::KeyEvent& event ) +bool WebView::OnKeyEvent(const Dali::KeyEvent& event) { bool result = false; - if( mWebEngine ) + if(mWebEngine) { - result = mWebEngine.SendKeyEvent( event ); + result = mWebEngine.SendKeyEvent(event); } return result; } void WebView::OnKeyInputFocusGained() { - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.SetFocus( true ); + mWebEngine.SetFocus(true); } - EmitKeyInputFocusSignal( true ); // Calls back into the Control hence done last. + EmitKeyInputFocusSignal(true); // Calls back into the Control hence done last. } void WebView::OnKeyInputFocusLost() { - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.SetFocus( false ); + mWebEngine.SetFocus(false); } - EmitKeyInputFocusSignal( false ); // Calls back into the Control hence done last. + EmitKeyInputFocusSignal(false); // Calls back into the Control hence done last. } -void WebView::SetScrollPosition( int x, int y ) +void WebView::SetScrollPosition(int x, int y) { - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.SetScrollPosition( x, y ); + mWebEngine.SetScrollPosition(x, y); } } @@ -704,7 +702,7 @@ Dali::Vector2 WebView::GetContentSize() const std::string WebView::GetTitle() const { - return mWebEngine ? mWebEngine.GetTitle() : kEmptyString; + return mWebEngine ? mWebEngine.GetTitle() : kEmptyString; } const std::string& WebView::GetUserAgent() const @@ -712,11 +710,11 @@ const std::string& WebView::GetUserAgent() const return mWebEngine ? mWebEngine.GetUserAgent() : kEmptyString; } -void WebView::SetUserAgent( const std::string& userAgent ) +void WebView::SetUserAgent(const std::string& userAgent) { - if( mWebEngine ) + if(mWebEngine) { - mWebEngine.SetUserAgent( userAgent ); + mWebEngine.SetUserAgent(userAgent); } } diff --git a/dali-toolkit/internal/drag-drop-detector/drag-and-drop-detector-impl.cpp b/dali-toolkit/internal/drag-drop-detector/drag-and-drop-detector-impl.cpp index 994932e..23a6b2d 100644 --- a/dali-toolkit/internal/drag-drop-detector/drag-and-drop-detector-impl.cpp +++ b/dali-toolkit/internal/drag-drop-detector/drag-and-drop-detector-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,13 +23,10 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - Dali::Toolkit::DragAndDropDetector DragAndDropDetector::New() { Dali::Toolkit::DragAndDropDetector detector = Dali::Toolkit::DragAndDropDetector(new DragAndDropDetector()); @@ -51,11 +48,10 @@ void DragAndDropDetector::Attach(Dali::Toolkit::Control& control) } mControls.push_back(control); control.TouchedSignal().Connect(this, &DragAndDropDetector::OnDrag); - mFirstEnter.push_back(control.GetProperty< int >( Actor::Property::ID )); + mFirstEnter.push_back(control.GetProperty(Actor::Property::ID)); mPanGestureDetector.Attach(control); mPanGestureDetector.DetectedSignal().Connect(this, &DragAndDropDetector::OnPan); } - } void DragAndDropDetector::Detach(Dali::Toolkit::Control& control) @@ -73,7 +69,7 @@ void DragAndDropDetector::Detach(Dali::Toolkit::Control& control) { match->TouchedSignal().Disconnect(this, &DragAndDropDetector::OnDrag); mPanGestureDetector.Detach(*match); - mFirstEnter.erase(std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty< int >( Actor::Property::ID ))); + mFirstEnter.erase(std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty(Actor::Property::ID))); mControls.erase(match); } } @@ -84,7 +80,7 @@ void DragAndDropDetector::DetachAll() if(!mControls.empty()) { auto iter = mControls.begin(); - for(;iter != mControls.end();) + for(; iter != mControls.end();) { iter->TouchedSignal().Disconnect(this, &DragAndDropDetector::OnDrag); mPanGestureDetector.Detach(*iter); @@ -95,7 +91,7 @@ void DragAndDropDetector::DetachAll() if(!mFirstEnter.empty()) { auto iter = mFirstEnter.begin(); - for(;iter != mFirstEnter.end();) + for(; iter != mFirstEnter.end();) { iter = mFirstEnter.erase(iter); } @@ -128,32 +124,32 @@ void DragAndDropDetector::OnPan(Dali::Actor actor, const PanGesture& gesture) if(state == GestureState::STARTED) { mDragLocalPosition = gesture.GetPosition(); - mPointDown = true; - mDragControl = control; + mPointDown = true; + mDragControl = control; mFirstEnter.clear(); - for( auto&& control : mControls) + for(auto&& control : mControls) { - mFirstEnter.push_back(control.GetProperty< int >( Actor::Property::ID )); + mFirstEnter.push_back(control.GetProperty(Actor::Property::ID)); } - float width = control.GetProperty(Dali::Actor::Property::SIZE_WIDTH); - float height = control.GetProperty(Dali::Actor::Property::SIZE_HEIGHT); + float width = control.GetProperty(Dali::Actor::Property::SIZE_WIDTH); + float height = control.GetProperty(Dali::Actor::Property::SIZE_HEIGHT); Vector3 actorPos = control.GetProperty(Dali::Actor::Property::POSITION); mShadowControl = Dali::Toolkit::Control::New(); - mShadowControl.SetProperty( Actor::Property::POSITION, actorPos ); - mShadowControl.SetProperty( Actor::Property::SIZE, Vector2( width, height ) ); + mShadowControl.SetProperty(Actor::Property::POSITION, actorPos); + mShadowControl.SetProperty(Actor::Property::SIZE, Vector2(width, height)); mShadowControl.SetBackgroundColor(Vector4(0.3f, 0.3f, 0.3f, 0.7f)); - mShadowControl.SetProperty( Actor::Property::PARENT_ORIGIN, control.GetCurrentProperty< Vector3 >( Actor::Property::PARENT_ORIGIN ) ); - mShadowControl.SetProperty( Actor::Property::ANCHOR_POINT,control.GetCurrentProperty< Vector3 >( Actor::Property::ANCHOR_POINT )); + mShadowControl.SetProperty(Actor::Property::PARENT_ORIGIN, control.GetCurrentProperty(Actor::Property::PARENT_ORIGIN)); + mShadowControl.SetProperty(Actor::Property::ANCHOR_POINT, control.GetCurrentProperty(Actor::Property::ANCHOR_POINT)); control.GetParent().Add(mShadowControl); SetPosition(gesture.GetScreenPosition()); EmitStartedSignal(control); } if(state == GestureState::CONTINUING) { - Vector2 screenPosition = gesture.GetScreenPosition(); - control.GetParent().ScreenToLocal(mLocalPosition.x, mLocalPosition.y, screenPosition.x, screenPosition.y); - mShadowControl.SetProperty( Actor::Property::POSITION, Vector2(mLocalPosition.x - mDragLocalPosition.x, mLocalPosition.y - mDragLocalPosition.y)); + Vector2 screenPosition = gesture.GetScreenPosition(); + control.GetParent().ScreenToLocal(mLocalPosition.x, mLocalPosition.y, screenPosition.x, screenPosition.y); + mShadowControl.SetProperty(Actor::Property::POSITION, Vector2(mLocalPosition.x - mDragLocalPosition.x, mLocalPosition.y - mDragLocalPosition.y)); } if(state == GestureState::FINISHED) { @@ -165,13 +161,13 @@ void DragAndDropDetector::OnPan(Dali::Actor actor, const PanGesture& gesture) bool DragAndDropDetector::OnDrag(Dali::Actor actor, const Dali::TouchEvent& data) { Dali::Toolkit::Control control = Dali::Toolkit::Control::DownCast(actor); - PointState::Type type = data.GetState(0); + PointState::Type type = data.GetState(0); if(type == PointState::MOTION) { if(mDragControl != control && mPointDown) { - auto found = std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty< int >( Actor::Property::ID )); + auto found = std::find(mFirstEnter.begin(), mFirstEnter.end(), control.GetProperty(Actor::Property::ID)); if(mFirstEnter.end() != found) { SetPosition(data.GetScreenPosition(0)); @@ -190,7 +186,7 @@ bool DragAndDropDetector::OnDrag(Dali::Actor actor, const Dali::TouchEvent& data { if(mDragControl != control && mPointDown) { - mFirstEnter.push_back(control.GetProperty< int >( Actor::Property::ID )); + mFirstEnter.push_back(control.GetProperty(Actor::Property::ID)); EmitExitedSignal(control); } } @@ -201,13 +197,13 @@ bool DragAndDropDetector::OnDrag(Dali::Actor actor, const Dali::TouchEvent& data { SetPosition(data.GetScreenPosition(0)); ClearContent(); - SetContent(mDragControl.GetProperty< std::string >( Dali::Actor::Property::NAME )); + SetContent(mDragControl.GetProperty(Dali::Actor::Property::NAME)); EmitDroppedSignal(control); } if(mShadowControl) { - control.GetParent().Remove(mShadowControl); + control.GetParent().Remove(mShadowControl); } mPointDown = false; } @@ -224,7 +220,7 @@ const Vector2& DragAndDropDetector::GetCurrentScreenPosition() const return mScreenPosition; } -void DragAndDropDetector::SetContent( const std::string& content ) +void DragAndDropDetector::SetContent(const std::string& content) { mContent = content; } @@ -234,61 +230,61 @@ void DragAndDropDetector::ClearContent() mContent.clear(); } -void DragAndDropDetector::SetPosition( const Vector2& screenPosition ) +void DragAndDropDetector::SetPosition(const Vector2& screenPosition) { mScreenPosition = screenPosition; } void DragAndDropDetector::EmitStartedSignal(Dali::Toolkit::Control& control) { - if( !mStartedSignal.Empty() ) + if(!mStartedSignal.Empty()) { - Dali::Toolkit::DragAndDropDetector handle( this ); - mStartedSignal.Emit( control, handle ); + Dali::Toolkit::DragAndDropDetector handle(this); + mStartedSignal.Emit(control, handle); } } void DragAndDropDetector::EmitEnteredSignal(Dali::Toolkit::Control& control) { - if ( !mEnteredSignal.Empty() ) + if(!mEnteredSignal.Empty()) { - Dali::Toolkit::DragAndDropDetector handle( this ); - mEnteredSignal.Emit( control, handle ); + Dali::Toolkit::DragAndDropDetector handle(this); + mEnteredSignal.Emit(control, handle); } } void DragAndDropDetector::EmitExitedSignal(Dali::Toolkit::Control& control) { - if ( !mExitedSignal.Empty() ) + if(!mExitedSignal.Empty()) { - Dali::Toolkit::DragAndDropDetector handle( this ); - mExitedSignal.Emit( control, handle ); + Dali::Toolkit::DragAndDropDetector handle(this); + mExitedSignal.Emit(control, handle); } } void DragAndDropDetector::EmitMovedSignal(Dali::Toolkit::Control& control) { - if ( !mMovedSignal.Empty() ) + if(!mMovedSignal.Empty()) { - Dali::Toolkit::DragAndDropDetector handle( this ); - mMovedSignal.Emit( control, handle ); + Dali::Toolkit::DragAndDropDetector handle(this); + mMovedSignal.Emit(control, handle); } } void DragAndDropDetector::EmitDroppedSignal(Dali::Toolkit::Control& control) { - if ( !mDroppedSignal.Empty() ) + if(!mDroppedSignal.Empty()) { - Dali::Toolkit::DragAndDropDetector handle( this ); - mDroppedSignal.Emit( control, handle ); + Dali::Toolkit::DragAndDropDetector handle(this); + mDroppedSignal.Emit(control, handle); } } void DragAndDropDetector::EmitEndedSignal(Dali::Toolkit::Control& control) { - if( !mEndedSignal.Empty() ) + if(!mEndedSignal.Empty()) { - Dali::Toolkit::DragAndDropDetector handle( this ); - mEndedSignal.Emit( control, handle ); + Dali::Toolkit::DragAndDropDetector handle(this); + mEndedSignal.Emit(control, handle); } } @@ -297,7 +293,7 @@ DragAndDropDetector::DragAndDropDetector() mScreenPosition() { mPanGestureDetector = Dali::PanGestureDetector::New(); - mPointDown = false; + mPointDown = false; } DragAndDropDetector::~DragAndDropDetector() diff --git a/dali-toolkit/internal/feedback/feedback-style.cpp b/dali-toolkit/internal/feedback/feedback-style.cpp index c96cd17..1e8607e 100644 --- a/dali-toolkit/internal/feedback/feedback-style.cpp +++ b/dali-toolkit/internal/feedback/feedback-style.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 // EXTERNAL INCLUDES -#include +#include #include +#include #include -#include // INTERNAL INCLUDES #include @@ -31,7 +31,6 @@ namespace // unnamed namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::General, false, "LOG_FEEDBACK"); #endif @@ -42,11 +41,11 @@ const char* DEFAULT_FEEDBACK_THEME_FILE_NAME = "default-feedback-theme.json"; void GetIfString(const Dali::Toolkit::TreeNode& node, const std::string& name, bool& exists, std::string& str) { const Dali::Toolkit::TreeNode* child = node.GetChild(name); - if( child && - Dali::Toolkit::TreeNode::STRING == child->GetType() ) + if(child && + Dali::Toolkit::TreeNode::STRING == child->GetType()) { exists = true; - str = child->GetString(); + str = child->GetString(); } } @@ -54,26 +53,23 @@ void GetIfString(const Dali::Toolkit::TreeNode& node, const std::string& name, b namespace Dali { - namespace Toolkit { - namespace Internal { - struct SignalFeedbackInfo { /** * Default constructor. */ SignalFeedbackInfo() - :mHasHapticFeedbackInfo(false), - mHasSoundFeedbackInfo(false) + : mHasHapticFeedbackInfo(false), + mHasSoundFeedbackInfo(false) { } - bool mHasHapticFeedbackInfo; - bool mHasSoundFeedbackInfo; + bool mHasHapticFeedbackInfo; + bool mHasSoundFeedbackInfo; std::string mSignalName; std::string mHapticFeedbackPattern; std::string mSoundFeedbackPattern; @@ -81,7 +77,7 @@ struct SignalFeedbackInfo std::string mSoundFeedbackFile; }; -typedef std::vector SignalFeedbackInfoContainer; +typedef std::vector SignalFeedbackInfoContainer; typedef SignalFeedbackInfoContainer::const_iterator SignalFeedbackInfoConstIter; struct FeedbackStyleInfo @@ -104,22 +100,20 @@ FeedbackStyle::FeedbackStyle() { mFeedback = Dali::FeedbackPlayer::Get(); - const std::string styleDirPath = AssetManager::GetDaliStylePath(); + const std::string styleDirPath = AssetManager::GetDaliStylePath(); const std::string defaultThemeFilePath = styleDirPath + DEFAULT_FEEDBACK_THEME_FILE_NAME; std::string defaultTheme; - if( mFeedback && mFeedback.LoadFile( defaultThemeFilePath, defaultTheme ) ) + if(mFeedback && mFeedback.LoadFile(defaultThemeFilePath, defaultTheme)) { - LoadTheme( defaultTheme ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n", - defaultThemeFilePath.c_str(), defaultTheme.size() ); + LoadTheme(defaultTheme); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n", defaultThemeFilePath.c_str(), defaultTheme.size()); } else { DALI_LOG_ERROR("ResourceLoader::LoadTheme(%s) - failed to load\n", defaultThemeFilePath.c_str()); } - } FeedbackStyle::~FeedbackStyle() @@ -128,47 +122,45 @@ FeedbackStyle::~FeedbackStyle() struct PlayFeedbackFromSignal { - PlayFeedbackFromSignal( FeedbackStyle& controller, const std::string& typeName, const std::string& signalName ) - : mController( controller ), - mTypeName( typeName ), - mSignalName( signalName ) + PlayFeedbackFromSignal(FeedbackStyle& controller, const std::string& typeName, const std::string& signalName) + : mController(controller), + mTypeName(typeName), + mSignalName(signalName) { } void operator()() { - mController.PlayFeedback( mTypeName, mSignalName ); + mController.PlayFeedback(mTypeName, mSignalName); } FeedbackStyle& mController; - std::string mTypeName; - std::string mSignalName; + std::string mTypeName; + std::string mSignalName; }; - -void FeedbackStyle::ObjectCreated( BaseHandle handle ) +void FeedbackStyle::ObjectCreated(BaseHandle handle) { - if( handle ) + if(handle) { const std::string& type = handle.GetTypeName(); - const FeedbackStyleInfo styleInfo = GetStyleInfo( type ); + const FeedbackStyleInfo styleInfo = GetStyleInfo(type); - for( SignalFeedbackInfoConstIter iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter ) + for(SignalFeedbackInfoConstIter iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter) { const SignalFeedbackInfo& info = *iter; - if( info.mHasHapticFeedbackInfo || info.mHasSoundFeedbackInfo ) + if(info.mHasHapticFeedbackInfo || info.mHasSoundFeedbackInfo) { - if( !info.mHapticFeedbackPattern.empty() || !info.mHapticFeedbackFile.empty() || - !info.mSoundFeedbackPattern.empty() || !info.mSoundFeedbackFile.empty() ) + if(!info.mHapticFeedbackPattern.empty() || !info.mHapticFeedbackFile.empty() || + !info.mSoundFeedbackPattern.empty() || !info.mSoundFeedbackFile.empty()) { - handle.ConnectSignal( this, - info.mSignalName, - PlayFeedbackFromSignal( *this, type, info.mSignalName ) ); + handle.ConnectSignal(this, + info.mSignalName, + PlayFeedbackFromSignal(*this, type, info.mSignalName)); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FeedbackStyle::Set found Haptic pattern %s for Object type: %s, Signal Type: %s\n", - info.mHapticFeedbackPattern.c_str(), type.c_str(), info.mSignalName.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FeedbackStyle::Set found Haptic pattern %s for Object type: %s, Signal Type: %s\n", info.mHapticFeedbackPattern.c_str(), type.c_str(), info.mSignalName.c_str()); } else { @@ -179,10 +171,10 @@ void FeedbackStyle::ObjectCreated( BaseHandle handle ) } } -const FeedbackStyleInfo& FeedbackStyle::GetStyleInfo( const std::string& type ) const +const FeedbackStyleInfo& FeedbackStyle::GetStyleInfo(const std::string& type) const { - std::map::const_iterator iter( mStyleInfoLut.find( type ) ); - if( iter != mStyleInfoLut.end() ) + std::map::const_iterator iter(mStyleInfoLut.find(type)); + if(iter != mStyleInfoLut.end()) { return iter->second; } @@ -192,23 +184,23 @@ const FeedbackStyleInfo& FeedbackStyle::GetStyleInfo( const std::string& type ) } } -void FeedbackStyle::StyleChanged( const std::string& userDefinedThemePath, Dali::StyleChange::Type styleChange ) +void FeedbackStyle::StyleChanged(const std::string& userDefinedThemePath, Dali::StyleChange::Type styleChange) { - if( styleChange == StyleChange::THEME_CHANGE ) + if(styleChange == StyleChange::THEME_CHANGE) { std::string userDefinedTheme; - if( mFeedback && mFeedback.LoadFile( userDefinedThemePath, userDefinedTheme ) ) + if(mFeedback && mFeedback.LoadFile(userDefinedThemePath, userDefinedTheme)) { - if( !LoadTheme( userDefinedTheme ) ) + if(!LoadTheme(userDefinedTheme)) { DALI_LOG_ERROR("FeedbackStyle::StyleChanged() User defined theme failed to load! \n"); - const std::string styleDirPath = AssetManager::GetDaliStylePath(); + const std::string styleDirPath = AssetManager::GetDaliStylePath(); const std::string defaultThemeFilePath = styleDirPath + DEFAULT_FEEDBACK_THEME_FILE_NAME; //If there is any problem is using the user defined theme, then fall back to default theme - if( !LoadTheme( defaultThemeFilePath ) ) + if(!LoadTheme(defaultThemeFilePath)) { //If the default theme fails, Then No luck! DALI_LOG_ERROR("FeedbackStyle::StyleChanged() Default theme failed to load! \n"); @@ -216,8 +208,7 @@ void FeedbackStyle::StyleChanged( const std::string& userDefinedThemePath, Dali: } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n", - userDefinedThemePath.c_str(), userDefinedTheme.size() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "ResourceLoader::LoadTheme(%s) - loaded %d bytes\n", userDefinedThemePath.c_str(), userDefinedTheme.size()); } } else @@ -227,36 +218,36 @@ void FeedbackStyle::StyleChanged( const std::string& userDefinedThemePath, Dali: } } -bool FeedbackStyle::LoadTheme( const std::string& data ) +bool FeedbackStyle::LoadTheme(const std::string& data) { bool result = false; try { - LoadFromString( data ); + LoadFromString(data); result = true; } catch(...) { //Problem in user set theme, So fallback to use default theme. - DALI_LOG_ERROR( "FeedbackStyle::LoadTheme() Failed to load theme\n" ); + DALI_LOG_ERROR("FeedbackStyle::LoadTheme() Failed to load theme\n"); } return result; } -void FeedbackStyle::LoadFromString( const std::string& data ) +void FeedbackStyle::LoadFromString(const std::string& data) { - Toolkit::JsonParser parser = Toolkit::JsonParser::New(); - const Toolkit::TreeNode* root = NULL; + Toolkit::JsonParser parser = Toolkit::JsonParser::New(); + const Toolkit::TreeNode* root = NULL; - if( !parser.Parse( data ) ) + if(!parser.Parse(data)) { - DALI_LOG_WARNING( "JSON Parse Error:'%s'\n", parser.GetErrorDescription().c_str() ); - DALI_LOG_WARNING( "JSON Parse Line :'%d (%d)'\n", - parser.GetErrorLineNumber(), - parser.GetErrorColumn() ); + DALI_LOG_WARNING("JSON Parse Error:'%s'\n", parser.GetErrorDescription().c_str()); + DALI_LOG_WARNING("JSON Parse Line :'%d (%d)'\n", + parser.GetErrorLineNumber(), + parser.GetErrorColumn()); } else { @@ -269,21 +260,21 @@ void FeedbackStyle::LoadFromString( const std::string& data ) mStyleInfoLut.clear(); // Parse style - if( const TreeNode* node = root->GetChild("style") ) + if(const TreeNode* node = root->GetChild("style")) { Toolkit::TreeNode::ConstIterator iter = node->CBegin(); - Toolkit::TreeNode::ConstIterator end = node->CEnd(); - for( ; iter != end; ++iter ) + Toolkit::TreeNode::ConstIterator end = node->CEnd(); + for(; iter != end; ++iter) { - const char* key = (*iter).first; + const char* key = (*iter).first; FeedbackStyleInfo themeInfo; themeInfo.mTypeName = key; - if( const TreeNode* signals = (*iter).second.GetChild("signals") ) + if(const TreeNode* signals = (*iter).second.GetChild("signals")) { TreeNode::ConstIterator signalIter = signals->CBegin(); - TreeNode::ConstIterator signalEnd = signals->CEnd(); - for( ; signalIter != signalEnd; ++signalIter ) + TreeNode::ConstIterator signalEnd = signals->CEnd(); + for(; signalIter != signalEnd; ++signalIter) { SignalFeedbackInfo signalFeedbackInfo; @@ -291,25 +282,17 @@ void FeedbackStyle::LoadFromString( const std::string& data ) DALI_ASSERT_ALWAYS(type && TreeNode::STRING == type->GetType() && "Signal must have a type"); signalFeedbackInfo.mSignalName = type->GetString(); - GetIfString( (*signalIter).second, "hapticFeedbackPattern", - signalFeedbackInfo.mHasHapticFeedbackInfo, - signalFeedbackInfo.mHapticFeedbackPattern ); + GetIfString((*signalIter).second, "hapticFeedbackPattern", signalFeedbackInfo.mHasHapticFeedbackInfo, signalFeedbackInfo.mHapticFeedbackPattern); - GetIfString( (*signalIter).second, "hapticFeedbackFile", - signalFeedbackInfo.mHasHapticFeedbackInfo, - signalFeedbackInfo.mHapticFeedbackFile ); + GetIfString((*signalIter).second, "hapticFeedbackFile", signalFeedbackInfo.mHasHapticFeedbackInfo, signalFeedbackInfo.mHapticFeedbackFile); - GetIfString( (*signalIter).second, "soundFeedbackPattern", - signalFeedbackInfo.mHasSoundFeedbackInfo, - signalFeedbackInfo.mSoundFeedbackPattern ); + GetIfString((*signalIter).second, "soundFeedbackPattern", signalFeedbackInfo.mHasSoundFeedbackInfo, signalFeedbackInfo.mSoundFeedbackPattern); - GetIfString( (*signalIter).second, "hapticFeedbackFile", - signalFeedbackInfo.mHasSoundFeedbackInfo, - signalFeedbackInfo.mSoundFeedbackFile ); + GetIfString((*signalIter).second, "hapticFeedbackFile", signalFeedbackInfo.mHasSoundFeedbackInfo, signalFeedbackInfo.mSoundFeedbackFile); - if( signalFeedbackInfo.mHasHapticFeedbackInfo || signalFeedbackInfo.mHasSoundFeedbackInfo ) + if(signalFeedbackInfo.mHasHapticFeedbackInfo || signalFeedbackInfo.mHasSoundFeedbackInfo) { - AddSignalInfo( themeInfo, std::move( signalFeedbackInfo ) ); + AddSignalInfo(themeInfo, std::move(signalFeedbackInfo)); } } } @@ -317,20 +300,20 @@ void FeedbackStyle::LoadFromString( const std::string& data ) mStyleInfoLut[key] = themeInfo; } // for styles - } // if(style) - } // if(root) + } // if(style) + } // if(root) } // LoadFromString() -void FeedbackStyle::AddSignalInfo( FeedbackStyleInfo& styleInfo, SignalFeedbackInfo&& signalInfo ) +void FeedbackStyle::AddSignalInfo(FeedbackStyleInfo& styleInfo, SignalFeedbackInfo&& signalInfo) { - bool updated = false; + bool updated = false; SignalFeedbackInfoContainer::iterator iter; // If info exists for the signal then update it, else add new - for( iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter ) + for(iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter) { - if( (*iter).mSignalName == signalInfo.mSignalName ) + if((*iter).mSignalName == signalInfo.mSignalName) { (*iter).mHasHapticFeedbackInfo = signalInfo.mHasHapticFeedbackInfo; (*iter).mHapticFeedbackPattern = signalInfo.mHapticFeedbackPattern; @@ -344,15 +327,15 @@ void FeedbackStyle::AddSignalInfo( FeedbackStyleInfo& styleInfo, SignalFeedbackI } } - if( !updated ) + if(!updated) { - styleInfo.mSignalFeedbackInfoList.emplace_back( std::move( signalInfo ) ); + styleInfo.mSignalFeedbackInfoList.emplace_back(std::move(signalInfo)); } } void FeedbackStyle::PlayFeedback(const std::string& type, const std::string& signalName) { - const FeedbackStyleInfo styleInfo = GetStyleInfo(type); + const FeedbackStyleInfo styleInfo = GetStyleInfo(type); SignalFeedbackInfoConstIter iter; for(iter = styleInfo.mSignalFeedbackInfoList.begin(); iter != styleInfo.mSignalFeedbackInfoList.end(); ++iter) @@ -365,14 +348,13 @@ void FeedbackStyle::PlayFeedback(const std::string& type, const std::string& sig { if(!info.mHapticFeedbackPattern.empty()) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Haptic effect: Object type: %s, Signal type: %s, pattern type: %s\n", - type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Haptic effect: Object type: %s, Signal type: %s, pattern type: %s\n", type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str()); - mFeedback.PlayFeedbackPattern( FEEDBACK_TYPE_VIBRATION, GetFeedbackPattern(info.mHapticFeedbackPattern) ); + mFeedback.PlayFeedbackPattern(FEEDBACK_TYPE_VIBRATION, GetFeedbackPattern(info.mHapticFeedbackPattern)); } else if(!info.mHapticFeedbackFile.empty()) { - mFeedback.PlayFile( info.mHapticFeedbackFile ); + mFeedback.PlayFile(info.mHapticFeedbackFile); } } @@ -380,14 +362,13 @@ void FeedbackStyle::PlayFeedback(const std::string& type, const std::string& sig { if(!info.mSoundFeedbackPattern.empty()) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Sound effect: Object type: %s, Signal type: %s, pattern type: %s\n", - type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FeedbackStyle::PlayFeedback Playing Sound effect: Object type: %s, Signal type: %s, pattern type: %s\n", type.c_str(), signalName.c_str(), info.mHapticFeedbackPattern.c_str()); - mFeedback.PlayFeedbackPattern( FEEDBACK_TYPE_SOUND, GetFeedbackPattern(info.mSoundFeedbackPattern) ); + mFeedback.PlayFeedbackPattern(FEEDBACK_TYPE_SOUND, GetFeedbackPattern(info.mSoundFeedbackPattern)); } else if(!info.mSoundFeedbackFile.empty()) { - mFeedback.PlaySound( info.mSoundFeedbackFile ); + mFeedback.PlaySound(info.mSoundFeedbackFile); } } @@ -396,9 +377,9 @@ void FeedbackStyle::PlayFeedback(const std::string& type, const std::string& sig } } -FeedbackPattern FeedbackStyle::GetFeedbackPattern( const std::string &pattern ) +FeedbackPattern FeedbackStyle::GetFeedbackPattern(const std::string& pattern) { - if( 0 == mFeedbackPatternLut.size() ) + if(0 == mFeedbackPatternLut.size()) { mFeedbackPatternLut["FEEDBACK_PATTERN_NONE"] = Dali::FEEDBACK_PATTERN_NONE; mFeedbackPatternLut["FEEDBACK_PATTERN_TAP"] = Dali::FEEDBACK_PATTERN_TAP; @@ -452,21 +433,21 @@ FeedbackPattern FeedbackStyle::GetFeedbackPattern( const std::string &pattern ) mFeedbackPatternLut["FEEDBACK_PATTERN_SLIDER_SWEEP"] = Dali::FEEDBACK_PATTERN_SLIDER_SWEEP; } - std::map::const_iterator iter( mFeedbackPatternLut.find( pattern ) ); + std::map::const_iterator iter(mFeedbackPatternLut.find(pattern)); - if( iter != mFeedbackPatternLut.end() ) + if(iter != mFeedbackPatternLut.end()) { return iter->second; } else { - DALI_LOG_ERROR( "Unknown feedback pattern type: %s, So Defaulting to FEEDBACK_PATTERN_NONE!\n" ); + DALI_LOG_ERROR("Unknown feedback pattern type: %s, So Defaulting to FEEDBACK_PATTERN_NONE!\n"); return Dali::FEEDBACK_PATTERN_NONE; } } -} // namespace Toolkit - } // namespace Internal +} // namespace Toolkit + } // namespace Dali diff --git a/dali-toolkit/internal/filters/blur-two-pass-filter.cpp b/dali-toolkit/internal/filters/blur-two-pass-filter.cpp index f86ffd4..a6fae1f 100644 --- a/dali-toolkit/internal/filters/blur-two-pass-filter.cpp +++ b/dali-toolkit/internal/filters/blur-two-pass-filter.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,12 +19,12 @@ #include "blur-two-pass-filter.h" // EXTERNAL INCLUDES -#include -#include #include +#include #include #include #include +#include // INTERNAL INCLUDES #include @@ -32,60 +32,48 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { +const float DEFAULT_KERNEL0[] = {12.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f}; -const float DEFAULT_KERNEL0[] = { 12.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f }; +const float DEFAULT_KERNEL1[] = {8.0f / 16.0f, 2.75f / 16.0f, 2.75f / 16.0f, 1.25f / 16.0f, 1.25f / 16.0f}; -const float DEFAULT_KERNEL1[] = { 8.0f/16.0f, 2.75f/16.0f, 2.75f/16.0f, 1.25f/16.0f, - 1.25f/16.0f }; +const float DEFAULT_KERNEL2[] = {5.0f / 16.0f, 2.75f / 16.0f, 2.75f / 16.0f, 1.75f / 16.0f, 1.75f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f}; -const float DEFAULT_KERNEL2[] = { 5.0f/16.0f, 2.75f/16.0f, 2.75f/16.0f, 1.75f/16.0f, - 1.75f/16.0f, 1.5f/16.0f, 1.5f/16.0f }; +const float DEFAULT_KERNEL3[] = {3.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 2.0f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f}; -const float DEFAULT_KERNEL3[] = { 3.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f, - 2.0f/16.0f, 2.0f/16.0f, 2.0f/16.0f, 0.5f/16.0f, - 0.5f/16.0f }; +const float DEFAULT_KERNEL4[] = {2.0f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f, 1.5f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 1.0f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f, 0.5f / 16.0f}; -const float DEFAULT_KERNEL4[] = { 2.0f/16.0f, 1.5f/16.0f, 1.5f/16.0f, 1.5f/16.0f, - 1.5f/16.0f, 1.0f/16.0f, 1.0f/16.0f, 1.0f/16.0f, - 1.0f/16.0f, 1.0f/16.0f, 1.0f/16.0f, 0.5f/16.0f, - 0.5f/16.0f, 0.5f/16.0f, 0.5f/16.0f }; - -std::string GetOffsetUniformName( int index ) +std::string GetOffsetUniformName(int index) { std::ostringstream oss; oss << "uSampleOffsets[" << index << "]"; return oss.str(); } -std::string GetWeightUniformName( int index ) +std::string GetWeightUniformName(int index) { std::ostringstream oss; oss << "uSampleWeights[" << index << "]"; return oss.str(); } -const char* const BLUR_STRENGTH_UNIFORM_NAME( "uBlurStrength" ); -const char* const EFFECT_IMAGE_NAME( "sEffect" ); +const char* const BLUR_STRENGTH_UNIFORM_NAME("uBlurStrength"); +const char* const EFFECT_IMAGE_NAME("sEffect"); } // namespace - BlurTwoPassFilter::BlurTwoPassFilter() : ImageFilter() { // create blending actor and register the property in constructor // to make sure that GetBlurStrengthPropertyIndex() always returns a valid index - mActorForBlending = Actor::New(); - mBlurStrengthPropertyIndex = mActorForBlending.RegisterProperty( BLUR_STRENGTH_UNIFORM_NAME, 1.f ); + mActorForBlending = Actor::New(); + mBlurStrengthPropertyIndex = mActorForBlending.RegisterProperty(BLUR_STRENGTH_UNIFORM_NAME, 1.f); } BlurTwoPassFilter::~BlurTwoPassFilter() @@ -95,68 +83,68 @@ BlurTwoPassFilter::~BlurTwoPassFilter() void BlurTwoPassFilter::Enable() { // create custom shader effect - if( !GetKernelSize() ) + if(!GetKernelSize()) { - CreateKernel( DEFAULT_KERNEL4, sizeof(DEFAULT_KERNEL4)/sizeof(DEFAULT_KERNEL4[0]) ); + CreateKernel(DEFAULT_KERNEL4, sizeof(DEFAULT_KERNEL4) / sizeof(DEFAULT_KERNEL4[0])); } - int kernelSize( static_cast< int >(GetKernelSize()) ); + int kernelSize(static_cast(GetKernelSize())); // Set up blur-two-pass custom shader std::ostringstream sstream; sstream << "#define NUM_SAMPLES " << kernelSize << "\n"; sstream << SHADER_BLUR_TWO_PASS_SHADER_FRAG; - std::string fragmentSource( sstream.str() ); + std::string fragmentSource(sstream.str()); // create actor to render input with applied emboss effect mActorForInput = Actor::New(); - mActorForInput.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize ); - Renderer rendererForInput = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() ); - SetRendererTexture( rendererForInput, mInputTexture ); - mActorForInput.AddRenderer( rendererForInput ); + mActorForInput.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize); + Renderer rendererForInput = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str()); + SetRendererTexture(rendererForInput, mInputTexture); + mActorForInput.AddRenderer(rendererForInput); // create internal offscreen for result of horizontal pass - mFrameBufferForHorz = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture textureForHorz = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mFrameBufferForHorz.AttachColorTexture( textureForHorz ); + mFrameBufferForHorz = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture textureForHorz = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mFrameBufferForHorz.AttachColorTexture(textureForHorz); // create an actor to render mImageForHorz for vertical blur pass mActorForHorz = Actor::New(); - mActorForHorz.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize ); - Renderer rendererForHorz = CreateRenderer( BASIC_VERTEX_SOURCE, fragmentSource.c_str() ); - SetRendererTexture( rendererForHorz, textureForHorz ); - mActorForHorz.AddRenderer( rendererForHorz ); + mActorForHorz.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize); + Renderer rendererForHorz = CreateRenderer(BASIC_VERTEX_SOURCE, fragmentSource.c_str()); + SetRendererTexture(rendererForHorz, textureForHorz); + mActorForHorz.AddRenderer(rendererForHorz); // create internal offscreen for result of the two pass blurred image - mBlurredFrameBuffer = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture blurredTexture = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mBlurredFrameBuffer.AttachColorTexture( blurredTexture ); + mBlurredFrameBuffer = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture blurredTexture = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mBlurredFrameBuffer.AttachColorTexture(blurredTexture); // create an actor to blend the blurred image and the input image with the given blur strength - Renderer rendererForBlending = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_BLUR_TWO_IMAGES_SHADER_FRAG ); + Renderer rendererForBlending = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_BLUR_TWO_IMAGES_SHADER_FRAG); TextureSet textureSetForBlending = rendererForBlending.GetTextures(); - textureSetForBlending.SetTexture( 0u, blurredTexture ); - textureSetForBlending.SetTexture( 1u, mInputTexture ); - mActorForBlending.AddRenderer( rendererForBlending ); - mActorForBlending.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForBlending.SetProperty( Actor::Property::SIZE, mTargetSize ); + textureSetForBlending.SetTexture(0u, blurredTexture); + textureSetForBlending.SetTexture(1u, mInputTexture); + mActorForBlending.AddRenderer(rendererForBlending); + mActorForBlending.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForBlending.SetProperty(Actor::Property::SIZE, mTargetSize); - for( int i = 0; i < kernelSize; ++i ) + for(int i = 0; i < kernelSize; ++i) { - const std::string offsetUniform( GetOffsetUniformName( i ) ); - const std::string weightUniform( GetWeightUniformName( i ) ); + const std::string offsetUniform(GetOffsetUniformName(i)); + const std::string weightUniform(GetWeightUniformName(i)); - mActorForInput.RegisterProperty( offsetUniform, Vector2(mKernel[i]) * Vector2::XAXIS ); - mActorForInput.RegisterProperty( weightUniform, mKernel[i].z ); + mActorForInput.RegisterProperty(offsetUniform, Vector2(mKernel[i]) * Vector2::XAXIS); + mActorForInput.RegisterProperty(weightUniform, mKernel[i].z); - mActorForHorz.RegisterProperty( offsetUniform, Vector2(mKernel[i]) * Vector2::YAXIS ); - mActorForHorz.RegisterProperty( weightUniform, mKernel[i].z ); + mActorForHorz.RegisterProperty(offsetUniform, Vector2(mKernel[i]) * Vector2::YAXIS); + mActorForHorz.RegisterProperty(weightUniform, mKernel[i].z); } - mRootActor.Add( mActorForInput ); - mRootActor.Add( mActorForHorz ); - mRootActor.Add( mActorForBlending ); + mRootActor.Add(mActorForInput); + mRootActor.Add(mActorForHorz); + mRootActor.Add(mActorForBlending); SetupCamera(); CreateRenderTasks(); @@ -164,37 +152,37 @@ void BlurTwoPassFilter::Enable() void BlurTwoPassFilter::Disable() { - if( mRootActor ) + if(mRootActor) { - if( mCameraActor ) + if(mCameraActor) { - mRootActor.Remove( mCameraActor ); + mRootActor.Remove(mCameraActor); mCameraActor.Reset(); } - if( mActorForInput ) + if(mActorForInput) { - mRootActor.Remove( mActorForInput ); + mRootActor.Remove(mActorForInput); mActorForInput.Reset(); } - if( mActorForHorz ) + if(mActorForHorz) { - mRootActor.Remove( mActorForHorz ); + mRootActor.Remove(mActorForHorz); mActorForHorz.Reset(); } RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); - if( mRenderTaskForHorz ) + if(mRenderTaskForHorz) { taskList.RemoveTask(mRenderTaskForHorz); } - if( mRenderTaskForVert ) + if(mRenderTaskForVert) { taskList.RemoveTask(mRenderTaskForVert); } - if( mRenderTaskForBlending ) + if(mRenderTaskForBlending) { taskList.RemoveTask(mRenderTaskForBlending); } @@ -205,36 +193,36 @@ void BlurTwoPassFilter::Disable() void BlurTwoPassFilter::Refresh() { - if( mRenderTaskForHorz ) + if(mRenderTaskForHorz) { - mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } - if( mRenderTaskForVert ) + if(mRenderTaskForVert) { - mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } - if( mRenderTaskForBlending ) + if(mRenderTaskForBlending) { - mRenderTaskForBlending.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForBlending.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } } -void BlurTwoPassFilter::SetSize( const Vector2& size ) +void BlurTwoPassFilter::SetSize(const Vector2& size) { mTargetSize = size; - if( mActorForInput ) + if(mActorForInput) { - mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize); } - if( mActorForHorz ) + if(mActorForHorz) { - mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize); } - if( mActorForBlending ) + if(mActorForBlending) { - mActorForBlending.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForBlending.SetProperty(Actor::Property::SIZE, mTargetSize); } } @@ -249,36 +237,36 @@ void BlurTwoPassFilter::CreateRenderTasks() // perform a horizontal blur targeting the internal buffer mRenderTaskForHorz = taskList.CreateTask(); - mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForHorz.SetSourceActor( mActorForInput ); + mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForHorz.SetSourceActor(mActorForInput); mRenderTaskForHorz.SetExclusive(true); - mRenderTaskForHorz.SetInputEnabled( false ); - mRenderTaskForHorz.SetClearEnabled( true ); - mRenderTaskForHorz.SetClearColor( mBackgroundColor ); - mRenderTaskForHorz.SetFrameBuffer( mFrameBufferForHorz ); - mRenderTaskForHorz.SetCameraActor( mCameraActor ); + mRenderTaskForHorz.SetInputEnabled(false); + mRenderTaskForHorz.SetClearEnabled(true); + mRenderTaskForHorz.SetClearColor(mBackgroundColor); + mRenderTaskForHorz.SetFrameBuffer(mFrameBufferForHorz); + mRenderTaskForHorz.SetCameraActor(mCameraActor); // use the internal buffer and perform a horizontal blur targeting the output buffer mRenderTaskForVert = taskList.CreateTask(); - mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForVert.SetSourceActor( mActorForHorz ); + mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForVert.SetSourceActor(mActorForHorz); mRenderTaskForVert.SetExclusive(true); - mRenderTaskForVert.SetInputEnabled( false ); - mRenderTaskForVert.SetClearEnabled( true ); - mRenderTaskForVert.SetClearColor( mBackgroundColor ); - mRenderTaskForVert.SetFrameBuffer( mBlurredFrameBuffer ); - mRenderTaskForVert.SetCameraActor( mCameraActor ); + mRenderTaskForVert.SetInputEnabled(false); + mRenderTaskForVert.SetClearEnabled(true); + mRenderTaskForVert.SetClearColor(mBackgroundColor); + mRenderTaskForVert.SetFrameBuffer(mBlurredFrameBuffer); + mRenderTaskForVert.SetCameraActor(mCameraActor); //Perform a blending between the blurred image and the input image mRenderTaskForBlending = taskList.CreateTask(); - mRenderTaskForBlending.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForBlending.SetSourceActor( mActorForBlending ); + mRenderTaskForBlending.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForBlending.SetSourceActor(mActorForBlending); mRenderTaskForBlending.SetExclusive(true); - mRenderTaskForBlending.SetInputEnabled( false ); - mRenderTaskForBlending.SetClearEnabled( true ); - mRenderTaskForBlending.SetClearColor( mBackgroundColor ); - mRenderTaskForBlending.SetFrameBuffer( mOutputFrameBuffer ); - mRenderTaskForBlending.SetCameraActor( mCameraActor ); + mRenderTaskForBlending.SetInputEnabled(false); + mRenderTaskForBlending.SetClearEnabled(true); + mRenderTaskForBlending.SetClearColor(mBackgroundColor); + mRenderTaskForBlending.SetFrameBuffer(mOutputFrameBuffer); + mRenderTaskForBlending.SetCameraActor(mCameraActor); } } // namespace Internal diff --git a/dali-toolkit/internal/filters/emboss-filter.cpp b/dali-toolkit/internal/filters/emboss-filter.cpp index 7ea7fe1..0e8de06 100644 --- a/dali-toolkit/internal/filters/emboss-filter.cpp +++ b/dali-toolkit/internal/filters/emboss-filter.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,12 +19,12 @@ #include "emboss-filter.h" // EXTERNAL INCLUDES -#include -#include #include +#include #include #include #include +#include // INTERNAL INCLUDES #include @@ -32,19 +32,15 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -const char* const TEX_SCALE_UNIFORM_NAME( "uTexScale" ); -const char* const COEFFICIENT_UNIFORM_NAME( "uCoefficient" ); -const char* const COLOR_UNIFORM_NAME( "uEffectColor" ); +const char* const TEX_SCALE_UNIFORM_NAME("uTexScale"); +const char* const COEFFICIENT_UNIFORM_NAME("uCoefficient"); +const char* const COLOR_UNIFORM_NAME("uEffectColor"); } // namespace @@ -59,54 +55,54 @@ EmbossFilter::~EmbossFilter() void EmbossFilter::Enable() { - mFrameBufferForEmboss1 = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture texture1 = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mFrameBufferForEmboss1.AttachColorTexture( texture1 ); + mFrameBufferForEmboss1 = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture texture1 = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mFrameBufferForEmboss1.AttachColorTexture(texture1); - mFrameBufferForEmboss2 = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture texture2 = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mFrameBufferForEmboss2.AttachColorTexture( texture2 ); + mFrameBufferForEmboss2 = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture texture2 = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mFrameBufferForEmboss2.AttachColorTexture(texture2); // create actor to render input with applied emboss effect mActorForInput1 = Actor::New(); - mActorForInput1.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForInput1.SetProperty( Actor::Property::SIZE, mTargetSize); - Vector2 textureScale( 1.5f/mTargetSize.width, 1.5f/mTargetSize.height); - mActorForInput1.RegisterProperty( TEX_SCALE_UNIFORM_NAME, textureScale ); - mActorForInput1.RegisterProperty( COEFFICIENT_UNIFORM_NAME, Vector3( 2.f, -1.f, -1.f ) ); + mActorForInput1.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForInput1.SetProperty(Actor::Property::SIZE, mTargetSize); + Vector2 textureScale(1.5f / mTargetSize.width, 1.5f / mTargetSize.height); + mActorForInput1.RegisterProperty(TEX_SCALE_UNIFORM_NAME, textureScale); + mActorForInput1.RegisterProperty(COEFFICIENT_UNIFORM_NAME, Vector3(2.f, -1.f, -1.f)); // set EMBOSS custom shader - Renderer renderer1 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG ); - SetRendererTexture( renderer1, mInputTexture ); - mActorForInput1.AddRenderer( renderer1 ); - mRootActor.Add( mActorForInput1 ); + Renderer renderer1 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG); + SetRendererTexture(renderer1, mInputTexture); + mActorForInput1.AddRenderer(renderer1); + mRootActor.Add(mActorForInput1); mActorForInput2 = Actor::New(); - mActorForInput2.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForInput2.SetProperty( Actor::Property::SIZE, mTargetSize); - mActorForInput2.RegisterProperty( TEX_SCALE_UNIFORM_NAME, textureScale ); - mActorForInput2.RegisterProperty( COEFFICIENT_UNIFORM_NAME, Vector3( -1.f, -1.f, 2.f ) ); + mActorForInput2.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForInput2.SetProperty(Actor::Property::SIZE, mTargetSize); + mActorForInput2.RegisterProperty(TEX_SCALE_UNIFORM_NAME, textureScale); + mActorForInput2.RegisterProperty(COEFFICIENT_UNIFORM_NAME, Vector3(-1.f, -1.f, 2.f)); // set EMBOSS custom shader - Renderer renderer2 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG ); - SetRendererTexture( renderer2, mInputTexture ); - mActorForInput2.AddRenderer( renderer2 ); - mRootActor.Add( mActorForInput2 ); + Renderer renderer2 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_SHADER_FRAG); + SetRendererTexture(renderer2, mInputTexture); + mActorForInput2.AddRenderer(renderer2); + mRootActor.Add(mActorForInput2); mActorForComposite = Actor::New(); - mActorForComposite.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForComposite.SetProperty( Actor::Property::SIZE, mTargetSize); - mActorForComposite.SetProperty( Actor::Property::COLOR, Color::BLACK ); + mActorForComposite.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForComposite.SetProperty(Actor::Property::SIZE, mTargetSize); + mActorForComposite.SetProperty(Actor::Property::COLOR, Color::BLACK); - mRootActor.Add( mActorForComposite ); + mRootActor.Add(mActorForComposite); - mRendererForEmboss1 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG ); - SetRendererTexture( mRendererForEmboss1, mFrameBufferForEmboss1 ); - mRendererForEmboss1.RegisterProperty( COLOR_UNIFORM_NAME, Color::BLACK ); - mActorForComposite.AddRenderer( mRendererForEmboss1 ); + mRendererForEmboss1 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG); + SetRendererTexture(mRendererForEmboss1, mFrameBufferForEmboss1); + mRendererForEmboss1.RegisterProperty(COLOR_UNIFORM_NAME, Color::BLACK); + mActorForComposite.AddRenderer(mRendererForEmboss1); - mRendererForEmboss2 = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG ); - SetRendererTexture( mRendererForEmboss2, mFrameBufferForEmboss2 ); - mRendererForEmboss2.RegisterProperty( COLOR_UNIFORM_NAME, Color::WHITE ); - mActorForComposite.AddRenderer( mRendererForEmboss2 ); + mRendererForEmboss2 = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_EMBOSS_FILTER_COMPOSITE_SHADER_FRAG); + SetRendererTexture(mRendererForEmboss2, mFrameBufferForEmboss2); + mRendererForEmboss2.RegisterProperty(COLOR_UNIFORM_NAME, Color::WHITE); + mActorForComposite.AddRenderer(mRendererForEmboss2); SetupCamera(); CreateRenderTasks(); @@ -114,52 +110,52 @@ void EmbossFilter::Enable() void EmbossFilter::Disable() { - if( mRootActor ) + if(mRootActor) { - if( mCameraActor ) + if(mCameraActor) { - mRootActor.Remove( mCameraActor ); + mRootActor.Remove(mCameraActor); mCameraActor.Reset(); } - if( mActorForInput1 ) + if(mActorForInput1) { - mRootActor.Remove( mActorForInput1 ); + mRootActor.Remove(mActorForInput1); mActorForInput1.Reset(); } - if( mActorForInput2 ) + if(mActorForInput2) { - mRootActor.Remove( mActorForInput2 ); + mRootActor.Remove(mActorForInput2); mActorForInput2.Reset(); } - if( mActorForComposite ) + if(mActorForComposite) { - mActorForComposite.RemoveRenderer( mRendererForEmboss1 ); + mActorForComposite.RemoveRenderer(mRendererForEmboss1); mRendererForEmboss1.Reset(); - mActorForComposite.RemoveRenderer( mRendererForEmboss2 ); + mActorForComposite.RemoveRenderer(mRendererForEmboss2); mRendererForEmboss2.Reset(); - mRootActor.Remove( mActorForComposite ); + mRootActor.Remove(mActorForComposite); mActorForComposite.Reset(); } RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); - if( mRenderTaskForEmboss1 ) + if(mRenderTaskForEmboss1) { taskList.RemoveTask(mRenderTaskForEmboss1); } - if( mRenderTaskForEmboss2 ) + if(mRenderTaskForEmboss2) { taskList.RemoveTask(mRenderTaskForEmboss2); } - if( mRenderTaskForOutput ) + if(mRenderTaskForOutput) { - taskList.RemoveTask( mRenderTaskForOutput ); + taskList.RemoveTask(mRenderTaskForOutput); } mRootActor.Reset(); @@ -168,30 +164,30 @@ void EmbossFilter::Disable() void EmbossFilter::Refresh() { - if( mRenderTaskForEmboss1 ) + if(mRenderTaskForEmboss1) { - mRenderTaskForEmboss1.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForEmboss1.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } - if( mRenderTaskForEmboss2 ) + if(mRenderTaskForEmboss2) { - mRenderTaskForEmboss2.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForEmboss2.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } } -void EmbossFilter::SetSize( const Vector2& size ) +void EmbossFilter::SetSize(const Vector2& size) { mTargetSize = size; - if( mActorForInput1 ) + if(mActorForInput1) { - mActorForInput1.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForInput1.SetProperty(Actor::Property::SIZE, mTargetSize); } - if( mActorForInput2 ) + if(mActorForInput2) { - mActorForInput2.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForInput2.SetProperty(Actor::Property::SIZE, mTargetSize); } - if( mActorForComposite ) + if(mActorForComposite) { - mActorForComposite.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForComposite.SetProperty(Actor::Property::SIZE, mTargetSize); } } @@ -200,34 +196,34 @@ void EmbossFilter::CreateRenderTasks() RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); mRenderTaskForEmboss1 = taskList.CreateTask(); - mRenderTaskForEmboss1.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForEmboss1.SetSourceActor( mActorForInput1 ); + mRenderTaskForEmboss1.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForEmboss1.SetSourceActor(mActorForInput1); mRenderTaskForEmboss1.SetExclusive(true); - mRenderTaskForEmboss1.SetInputEnabled( false ); - mRenderTaskForEmboss1.SetClearColor( Vector4( 0.0f, 0.0f, 0.0f, 0.0f ) ); - mRenderTaskForEmboss1.SetClearEnabled( true ); - mRenderTaskForEmboss1.SetFrameBuffer( mFrameBufferForEmboss1 ); - mRenderTaskForEmboss1.SetCameraActor( mCameraActor ); + mRenderTaskForEmboss1.SetInputEnabled(false); + mRenderTaskForEmboss1.SetClearColor(Vector4(0.0f, 0.0f, 0.0f, 0.0f)); + mRenderTaskForEmboss1.SetClearEnabled(true); + mRenderTaskForEmboss1.SetFrameBuffer(mFrameBufferForEmboss1); + mRenderTaskForEmboss1.SetCameraActor(mCameraActor); mRenderTaskForEmboss2 = taskList.CreateTask(); - mRenderTaskForEmboss2.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForEmboss2.SetSourceActor( mActorForInput2 ); + mRenderTaskForEmboss2.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForEmboss2.SetSourceActor(mActorForInput2); mRenderTaskForEmboss2.SetExclusive(true); - mRenderTaskForEmboss2.SetInputEnabled( false ); - mRenderTaskForEmboss2.SetClearColor( Vector4( 1.0f, 1.0f, 1.0f, 0.0f ) ); - mRenderTaskForEmboss2.SetClearEnabled( true ); - mRenderTaskForEmboss2.SetFrameBuffer( mFrameBufferForEmboss2 ); - mRenderTaskForEmboss2.SetCameraActor( mCameraActor ); + mRenderTaskForEmboss2.SetInputEnabled(false); + mRenderTaskForEmboss2.SetClearColor(Vector4(1.0f, 1.0f, 1.0f, 0.0f)); + mRenderTaskForEmboss2.SetClearEnabled(true); + mRenderTaskForEmboss2.SetFrameBuffer(mFrameBufferForEmboss2); + mRenderTaskForEmboss2.SetCameraActor(mCameraActor); mRenderTaskForOutput = taskList.CreateTask(); - mRenderTaskForOutput.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForOutput.SetSourceActor( mActorForComposite ); + mRenderTaskForOutput.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForOutput.SetSourceActor(mActorForComposite); mRenderTaskForOutput.SetExclusive(true); - mRenderTaskForOutput.SetInputEnabled( false ); - mRenderTaskForOutput.SetClearColor( Vector4( 0.5f, 0.5f, 0.5f, 0.0f ) ); - mRenderTaskForOutput.SetClearEnabled( true ); - mRenderTaskForOutput.SetFrameBuffer( mOutputFrameBuffer ); - mRenderTaskForOutput.SetCameraActor( mCameraActor ); + mRenderTaskForOutput.SetInputEnabled(false); + mRenderTaskForOutput.SetClearColor(Vector4(0.5f, 0.5f, 0.5f, 0.0f)); + mRenderTaskForOutput.SetClearEnabled(true); + mRenderTaskForOutput.SetFrameBuffer(mOutputFrameBuffer); + mRenderTaskForOutput.SetCameraActor(mCameraActor); } } // namespace Internal diff --git a/dali-toolkit/internal/filters/image-filter.cpp b/dali-toolkit/internal/filters/image-filter.cpp index 1d786d6..c155afb 100644 --- a/dali-toolkit/internal/filters/image-filter.cpp +++ b/dali-toolkit/internal/filters/image-filter.cpp @@ -22,23 +22,20 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f; } // namespace ImageFilter::ImageFilter() -: mBackgroundColor( Vector4( 1.0f, 1.0f, 1.0f, 0.0f ) ), - mTargetSize( Vector2::ZERO ), - mPixelFormat( Pixel::RGBA8888 ), - mRefreshOnDemand( false ) +: mBackgroundColor(Vector4(1.0f, 1.0f, 1.0f, 0.0f)), + mTargetSize(Vector2::ZERO), + mPixelFormat(Pixel::RGBA8888), + mRefreshOnDemand(false) { } @@ -46,32 +43,32 @@ ImageFilter::~ImageFilter() { } -void ImageFilter::SetRefreshOnDemand( bool onDemand ) +void ImageFilter::SetRefreshOnDemand(bool onDemand) { mRefreshOnDemand = onDemand; } -void ImageFilter::SetInputTexture( Texture texture ) +void ImageFilter::SetInputTexture(Texture texture) { mInputTexture = texture; } -void ImageFilter::SetOutputFrameBuffer( FrameBuffer frameBuffer ) +void ImageFilter::SetOutputFrameBuffer(FrameBuffer frameBuffer) { mOutputFrameBuffer = frameBuffer; } -void ImageFilter::SetSize( const Vector2& size ) +void ImageFilter::SetSize(const Vector2& size) { mTargetSize = size; } -void ImageFilter::SetPixelFormat( Pixel::Format pixelFormat ) +void ImageFilter::SetPixelFormat(Pixel::Format pixelFormat) { mPixelFormat = pixelFormat; } -void ImageFilter::SetKernel( const FilterKernel& kernel ) +void ImageFilter::SetKernel(const FilterKernel& kernel) { mKernel = kernel; } @@ -86,44 +83,44 @@ size_t ImageFilter::GetKernelSize() const return mKernel.size(); } -void ImageFilter::CreateKernel( const float* weights, size_t count ) +void ImageFilter::CreateKernel(const float* weights, size_t count) { - if( (mTargetSize.width * mTargetSize.height ) > 0.0f ) + if((mTargetSize.width * mTargetSize.height) > 0.0f) { - Vector2 pixelsToUV( 1.0f / mTargetSize.width, 1.0f / mTargetSize.height ); + Vector2 pixelsToUV(1.0f / mTargetSize.width, 1.0f / mTargetSize.height); mKernel.clear(); - mKernel.push_back( Vector3( 0.0f, 0.0f, weights[0] ) ); - for( size_t i = 0; i < count >> 1; ++i ) + mKernel.push_back(Vector3(0.0f, 0.0f, weights[0])); + for(size_t i = 0; i < count >> 1; ++i) { float offset = 1.5f + (i << 1); - mKernel.push_back( Vector3( pixelsToUV.x * offset, pixelsToUV.y * offset, weights[(i << 1) + 1] ) ); - mKernel.push_back( Vector3( -pixelsToUV.x * offset, -pixelsToUV.y * offset, weights[(i << 1) + 2] ) ); + mKernel.push_back(Vector3(pixelsToUV.x * offset, pixelsToUV.y * offset, weights[(i << 1) + 1])); + mKernel.push_back(Vector3(-pixelsToUV.x * offset, -pixelsToUV.y * offset, weights[(i << 1) + 2])); } } } -void ImageFilter::SetRootActor( Actor rootActor ) +void ImageFilter::SetRootActor(Actor rootActor) { mRootActor = rootActor; } -void ImageFilter::SetBackgroundColor( const Vector4& color ) +void ImageFilter::SetBackgroundColor(const Vector4& color) { mBackgroundColor = color; } void ImageFilter::SetupCamera() { - if( !mCameraActor ) + if(!mCameraActor) { // create a camera for the render task, corresponding to its render target size mCameraActor = CameraActor::New(mTargetSize); - mCameraActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mCameraActor.SetInvertYAxis( true ); - mRootActor.Add( mCameraActor ); + mCameraActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mCameraActor.SetInvertYAxis(true); + mRootActor.Add(mCameraActor); } else { @@ -132,11 +129,10 @@ void ImageFilter::SetupCamera() mCameraActor.SetNearClippingPlane(1.0f); mCameraActor.SetAspectRatio(mTargetSize.width / mTargetSize.height); mCameraActor.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor - mCameraActor.SetProperty( Actor::Property::POSITION, Vector3( 0.0f, 0.0f, ( (mTargetSize.height * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f) ) ) ); + mCameraActor.SetProperty(Actor::Property::POSITION, Vector3(0.0f, 0.0f, ((mTargetSize.height * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)))); } } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/filters/spread-filter.cpp b/dali-toolkit/internal/filters/spread-filter.cpp index 55b060b..09d6ff6 100644 --- a/dali-toolkit/internal/filters/spread-filter.cpp +++ b/dali-toolkit/internal/filters/spread-filter.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 "spread-filter.h" // EXTERNAL INCLUDES -#include #include +#include #include #include @@ -30,22 +30,17 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -const char* const SPREAD_UNIFORM_NAME( "uSpread" ); -const char* const TEX_SCALE_UNIFORM_NAME( "uTexScale" ); +const char* const SPREAD_UNIFORM_NAME("uSpread"); +const char* const TEX_SCALE_UNIFORM_NAME("uTexScale"); } // namespace - SpreadFilter::SpreadFilter() : ImageFilter(), mSpread(2) @@ -56,7 +51,7 @@ SpreadFilter::~SpreadFilter() { } -void SpreadFilter::SetSpread( float spread ) +void SpreadFilter::SetSpread(float spread) { mSpread = spread; } @@ -65,34 +60,34 @@ void SpreadFilter::Enable() { // create actor to render input with applied emboss effect mActorForInput = Actor::New(); - mActorForInput.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForInput.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize); // register properties as shader uniforms - mActorForInput.RegisterProperty( SPREAD_UNIFORM_NAME, mSpread ); - mActorForInput.RegisterProperty( TEX_SCALE_UNIFORM_NAME, Vector2( 1.0f / mTargetSize.width, 0.0f ) ); + mActorForInput.RegisterProperty(SPREAD_UNIFORM_NAME, mSpread); + mActorForInput.RegisterProperty(TEX_SCALE_UNIFORM_NAME, Vector2(1.0f / mTargetSize.width, 0.0f)); - Renderer rendererForInput = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG ); - SetRendererTexture( rendererForInput, mInputTexture ); - mActorForInput.AddRenderer( rendererForInput ); + Renderer rendererForInput = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG); + SetRendererTexture(rendererForInput, mInputTexture); + mActorForInput.AddRenderer(rendererForInput); // create internal offscreen for result of horizontal pass - mFrameBufferForHorz = FrameBuffer::New( mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE ); - Texture textureForHorz = Texture::New( TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height) ); - mFrameBufferForHorz.AttachColorTexture( textureForHorz ); + mFrameBufferForHorz = FrameBuffer::New(mTargetSize.width, mTargetSize.height, FrameBuffer::Attachment::NONE); + Texture textureForHorz = Texture::New(TextureType::TEXTURE_2D, mPixelFormat, unsigned(mTargetSize.width), unsigned(mTargetSize.height)); + mFrameBufferForHorz.AttachColorTexture(textureForHorz); // create an actor to render mImageForHorz for vertical blur pass mActorForHorz = Actor::New(); - mActorForHorz.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForHorz.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize); // register properties as shader uniforms - mActorForHorz.RegisterProperty( SPREAD_UNIFORM_NAME, mSpread ); - mActorForHorz.RegisterProperty( TEX_SCALE_UNIFORM_NAME, Vector2( 0.0f, 1.0f / mTargetSize.height ) ); - Renderer rendererForHorz = CreateRenderer( BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG ); - SetRendererTexture( rendererForHorz, textureForHorz ); - mActorForHorz.AddRenderer( rendererForHorz ); + mActorForHorz.RegisterProperty(SPREAD_UNIFORM_NAME, mSpread); + mActorForHorz.RegisterProperty(TEX_SCALE_UNIFORM_NAME, Vector2(0.0f, 1.0f / mTargetSize.height)); + Renderer rendererForHorz = CreateRenderer(BASIC_VERTEX_SOURCE, SHADER_SPREAD_FILTER_SHADER_FRAG); + SetRendererTexture(rendererForHorz, textureForHorz); + mActorForHorz.AddRenderer(rendererForHorz); - mRootActor.Add( mActorForInput ); - mRootActor.Add( mActorForHorz ); + mRootActor.Add(mActorForInput); + mRootActor.Add(mActorForHorz); SetupCamera(); CreateRenderTasks(); @@ -100,33 +95,33 @@ void SpreadFilter::Enable() void SpreadFilter::Disable() { - if( mRootActor ) + if(mRootActor) { - if( mCameraActor ) + if(mCameraActor) { - mRootActor.Remove( mCameraActor ); + mRootActor.Remove(mCameraActor); mCameraActor.Reset(); } - if( mActorForInput ) + if(mActorForInput) { - mRootActor.Remove( mActorForInput ); + mRootActor.Remove(mActorForInput); mActorForInput.Reset(); } - if( mActorForHorz ) + if(mActorForHorz) { - mRootActor.Remove( mActorForHorz ); + mRootActor.Remove(mActorForHorz); mActorForHorz.Reset(); } RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList(); - if( mRenderTaskForHorz ) + if(mRenderTaskForHorz) { taskList.RemoveTask(mRenderTaskForHorz); } - if( mRenderTaskForVert ) + if(mRenderTaskForVert) { taskList.RemoveTask(mRenderTaskForVert); } @@ -137,27 +132,27 @@ void SpreadFilter::Disable() void SpreadFilter::Refresh() { - if( mRenderTaskForHorz ) + if(mRenderTaskForHorz) { - mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } - if( mRenderTaskForVert ) + if(mRenderTaskForVert) { - mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); + mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); } } -void SpreadFilter::SetSize( const Vector2& size ) +void SpreadFilter::SetSize(const Vector2& size) { mTargetSize = size; - if( mActorForInput ) + if(mActorForInput) { - mActorForInput.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForInput.SetProperty(Actor::Property::SIZE, mTargetSize); } - if( mActorForHorz ) + if(mActorForHorz) { - mActorForHorz.SetProperty( Actor::Property::SIZE, mTargetSize); + mActorForHorz.SetProperty(Actor::Property::SIZE, mTargetSize); } } @@ -167,25 +162,25 @@ void SpreadFilter::CreateRenderTasks() // perform a horizontal blur targeting the internal buffer mRenderTaskForHorz = taskList.CreateTask(); - mRenderTaskForHorz.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForHorz.SetSourceActor( mActorForInput ); + mRenderTaskForHorz.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForHorz.SetSourceActor(mActorForInput); mRenderTaskForHorz.SetExclusive(true); - mRenderTaskForHorz.SetInputEnabled( false ); - mRenderTaskForHorz.SetClearEnabled( true ); - mRenderTaskForHorz.SetClearColor( mBackgroundColor ); - mRenderTaskForHorz.SetFrameBuffer( mFrameBufferForHorz ); - mRenderTaskForHorz.SetCameraActor( mCameraActor ); + mRenderTaskForHorz.SetInputEnabled(false); + mRenderTaskForHorz.SetClearEnabled(true); + mRenderTaskForHorz.SetClearColor(mBackgroundColor); + mRenderTaskForHorz.SetFrameBuffer(mFrameBufferForHorz); + mRenderTaskForHorz.SetCameraActor(mCameraActor); // use the internal buffer and perform a horizontal blur targeting the output buffer mRenderTaskForVert = taskList.CreateTask(); - mRenderTaskForVert.SetRefreshRate( mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS ); - mRenderTaskForVert.SetSourceActor( mActorForHorz ); + mRenderTaskForVert.SetRefreshRate(mRefreshOnDemand ? RenderTask::REFRESH_ONCE : RenderTask::REFRESH_ALWAYS); + mRenderTaskForVert.SetSourceActor(mActorForHorz); mRenderTaskForVert.SetExclusive(true); - mRenderTaskForVert.SetInputEnabled( false ); - mRenderTaskForVert.SetClearEnabled( true ); - mRenderTaskForVert.SetClearColor( mBackgroundColor ); - mRenderTaskForVert.SetFrameBuffer( mOutputFrameBuffer ); - mRenderTaskForVert.SetCameraActor( mCameraActor ); + mRenderTaskForVert.SetInputEnabled(false); + mRenderTaskForVert.SetClearEnabled(true); + mRenderTaskForVert.SetClearColor(mBackgroundColor); + mRenderTaskForVert.SetFrameBuffer(mOutputFrameBuffer); + mRenderTaskForVert.SetCameraActor(mCameraActor); } } // namespace Internal diff --git a/dali-toolkit/internal/focus-manager/keyboard-focus-manager-impl.cpp b/dali-toolkit/internal/focus-manager/keyboard-focus-manager-impl.cpp index 04c15c4..0d7bbfd 100644 --- a/dali-toolkit/internal/focus-manager/keyboard-focus-manager-impl.cpp +++ b/dali-toolkit/internal/focus-manager/keyboard-focus-manager-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,42 +19,38 @@ #include "keyboard-focus-manager-impl.h" // EXTERNAL INCLUDES -#include // for strcmp -#include -#include #include +#include +#include +#include +#include +#include #include #include #include -#include -#include #include -#include -#include -#include +#include +#include +#include // for strcmp // INTERNAL INCLUDES #include -#include +#include +#include #include +#include #include -#include #include -#include #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace // Unnamed namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_KEYBOARD_FOCUS_MANAGER"); #endif @@ -67,13 +63,13 @@ BaseHandle Create() { BaseHandle handle = KeyboardFocusManager::Get(); - if ( !handle ) + if(!handle) { - SingletonService singletonService( SingletonService::Get() ); - if ( singletonService ) + SingletonService singletonService(SingletonService::Get()); + if(singletonService) { - Toolkit::KeyboardFocusManager manager = Toolkit::KeyboardFocusManager( new Internal::KeyboardFocusManager() ); - singletonService.Register( typeid( manager ), manager ); + Toolkit::KeyboardFocusManager manager = Toolkit::KeyboardFocusManager(new Internal::KeyboardFocusManager()); + singletonService.Register(typeid(manager), manager); handle = manager; } } @@ -81,12 +77,12 @@ BaseHandle Create() return handle; } -DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::KeyboardFocusManager, Dali::BaseHandle, Create, true ) +DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::KeyboardFocusManager, Dali::BaseHandle, Create, true) -DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardPreFocusChange", SIGNAL_PRE_FOCUS_CHANGE ) -DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusChanged", SIGNAL_FOCUS_CHANGED ) -DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusGroupChanged", SIGNAL_FOCUS_GROUP_CHANGED ) -DALI_SIGNAL_REGISTRATION( Toolkit, KeyboardFocusManager, "keyboardFocusedActorEnterKey", SIGNAL_FOCUSED_ACTOR_ENTER_KEY ) +DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardPreFocusChange", SIGNAL_PRE_FOCUS_CHANGE) +DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusChanged", SIGNAL_FOCUS_CHANGED) +DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusGroupChanged", SIGNAL_FOCUS_GROUP_CHANGED) +DALI_SIGNAL_REGISTRATION(Toolkit, KeyboardFocusManager, "keyboardFocusedActorEnterKey", SIGNAL_FOCUSED_ACTOR_ENTER_KEY) DALI_TYPE_REGISTRATION_END() @@ -98,15 +94,15 @@ Toolkit::KeyboardFocusManager KeyboardFocusManager::Get() { Toolkit::KeyboardFocusManager manager; - SingletonService singletonService( SingletonService::Get() ); - if ( singletonService ) + SingletonService singletonService(SingletonService::Get()); + if(singletonService) { // Check whether the keyboard focus manager is already created - Dali::BaseHandle handle = singletonService.GetSingleton( typeid( Toolkit::KeyboardFocusManager ) ); + Dali::BaseHandle handle = singletonService.GetSingleton(typeid(Toolkit::KeyboardFocusManager)); if(handle) { // If so, downcast the handle of singleton to keyboard focus manager - manager = Toolkit::KeyboardFocusManager( dynamic_cast< KeyboardFocusManager* >( handle.GetObjectPtr() ) ); + manager = Toolkit::KeyboardFocusManager(dynamic_cast(handle.GetObjectPtr())); } } @@ -121,51 +117,51 @@ KeyboardFocusManager::KeyboardFocusManager() mCurrentFocusActor(), mFocusIndicatorActor(), mFocusHistory(), - mSlotDelegate( this ), + mSlotDelegate(this), mCustomAlgorithmInterface(NULL), mCurrentFocusedWindow(), - mIsFocusIndicatorShown( UNKNOWN ), - mEnableFocusIndicator( ENABLE ), - mAlwaysShowIndicator( ALWAYS_SHOW ), - mFocusGroupLoopEnabled( false ), - mIsWaitingKeyboardFocusChangeCommit( false ), - mClearFocusOnTouch( true ) + mIsFocusIndicatorShown(UNKNOWN), + mEnableFocusIndicator(ENABLE), + mAlwaysShowIndicator(ALWAYS_SHOW), + mFocusGroupLoopEnabled(false), + mIsWaitingKeyboardFocusChangeCommit(false), + mClearFocusOnTouch(true) { // TODO: Get FocusIndicatorEnable constant from stylesheet to set mIsFocusIndicatorShown. - LifecycleController::Get().InitSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnAdaptorInit ); + LifecycleController::Get().InitSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnAdaptorInit); } void KeyboardFocusManager::OnAdaptorInit() { - if( Adaptor::IsAvailable() ) + if(Adaptor::IsAvailable()) { // Retrieve all the existing scene holders Dali::SceneHolderList sceneHolders = Adaptor::Get().GetSceneHolders(); - for( auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter ) + for(auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter) { - ( *iter ).KeyEventSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnKeyEvent ); - ( *iter ).TouchedSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnTouch ); - Dali::Window window = DevelWindow::DownCast( *iter ); - if( window ) + (*iter).KeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent); + (*iter).TouchedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnTouch); + Dali::Window window = DevelWindow::DownCast(*iter); + if(window) { - window.FocusChangeSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged); + window.FocusChangeSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged); } } // Get notified when any new scene holder is created afterwards - Adaptor::Get().WindowCreatedSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnSceneHolderCreated ); + Adaptor::Get().WindowCreatedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnSceneHolderCreated); } } -void KeyboardFocusManager::OnSceneHolderCreated( Dali::Integration::SceneHolder& sceneHolder ) +void KeyboardFocusManager::OnSceneHolderCreated(Dali::Integration::SceneHolder& sceneHolder) { - sceneHolder.KeyEventSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnKeyEvent ); - sceneHolder.TouchedSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnTouch ); - Dali::Window window = DevelWindow::DownCast( sceneHolder ); - if( window ) + sceneHolder.KeyEventSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnKeyEvent); + sceneHolder.TouchedSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnTouch); + Dali::Window window = DevelWindow::DownCast(sceneHolder); + if(window) { - window.FocusChangeSignal().Connect( mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged); + window.FocusChangeSignal().Connect(mSlotDelegate, &KeyboardFocusManager::OnWindowFocusChanged); } } @@ -175,38 +171,38 @@ KeyboardFocusManager::~KeyboardFocusManager() void KeyboardFocusManager::GetConfigurationFromStyleManger() { - Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get(); - if( styleManager ) - { - Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager ); - mAlwaysShowIndicator = config["alwaysShowFocus"].Get() ? ALWAYS_SHOW : NONE; - mIsFocusIndicatorShown = ( mAlwaysShowIndicator == ALWAYS_SHOW )? SHOW : HIDE; - mClearFocusOnTouch = ( mIsFocusIndicatorShown == SHOW ) ? false : true; - } + Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get(); + if(styleManager) + { + Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager); + mAlwaysShowIndicator = config["alwaysShowFocus"].Get() ? ALWAYS_SHOW : NONE; + mIsFocusIndicatorShown = (mAlwaysShowIndicator == ALWAYS_SHOW) ? SHOW : HIDE; + mClearFocusOnTouch = (mIsFocusIndicatorShown == SHOW) ? false : true; + } } -bool KeyboardFocusManager::SetCurrentFocusActor( Actor actor ) +bool KeyboardFocusManager::SetCurrentFocusActor(Actor actor) { - DALI_ASSERT_DEBUG( !mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?" ); + DALI_ASSERT_DEBUG(!mIsWaitingKeyboardFocusChangeCommit && "Calling this function in the PreFocusChangeSignal callback?"); - if( mIsFocusIndicatorShown == UNKNOWN ) + if(mIsFocusIndicatorShown == UNKNOWN) { GetConfigurationFromStyleManger(); } - return DoSetCurrentFocusActor( actor ); + return DoSetCurrentFocusActor(actor); } -bool KeyboardFocusManager::DoSetCurrentFocusActor( Actor actor ) +bool KeyboardFocusManager::DoSetCurrentFocusActor(Actor actor) { bool success = false; - if( actor && actor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) && actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(actor && actor.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { - Integration::SceneHolder currentWindow = Integration::SceneHolder::Get( actor ); + Integration::SceneHolder currentWindow = Integration::SceneHolder::Get(actor); - if( currentWindow.GetRootLayer() != mCurrentFocusedWindow.GetHandle()) + if(currentWindow.GetRootLayer() != mCurrentFocusedWindow.GetHandle()) { - Layer rootLayer = currentWindow.GetRootLayer(); + Layer rootLayer = currentWindow.GetRootLayer(); mCurrentFocusedWindow = rootLayer; } } @@ -214,9 +210,9 @@ bool KeyboardFocusManager::DoSetCurrentFocusActor( Actor actor ) Actor currentFocusedActor = GetCurrentFocusActor(); // If developer set focus on same actor, doing nothing - if( actor == currentFocusedActor ) + if(actor == currentFocusedActor) { - if( !actor ) + if(!actor) { return false; } @@ -224,66 +220,66 @@ bool KeyboardFocusManager::DoSetCurrentFocusActor( Actor actor ) } // Check whether the actor is in the stage and is keyboard focusable. - if( actor && actor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) && actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(actor && actor.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { - if( ( mIsFocusIndicatorShown == SHOW ) && ( mEnableFocusIndicator == ENABLE ) ) + if((mIsFocusIndicatorShown == SHOW) && (mEnableFocusIndicator == ENABLE)) { - actor.Add( GetFocusIndicatorActor() ); + actor.Add(GetFocusIndicatorActor()); } // Send notification for the change of focus actor - if( !mFocusChangedSignal.Empty() ) + if(!mFocusChangedSignal.Empty()) { mFocusChangedSignal.Emit(currentFocusedActor, actor); } Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast(currentFocusedActor); - if( currentlyFocusedControl ) + if(currentlyFocusedControl) { // Do we need it to remember if it was previously DISABLED? - currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL ); + currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL); currentlyFocusedControl.ClearKeyInputFocus(); } - DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] Focus Changed\n", __FUNCTION__, __LINE__); + DALI_LOG_INFO(gLogFilter, Debug::General, "[%s:%d] Focus Changed\n", __FUNCTION__, __LINE__); // Save the current focused actor mCurrentFocusActor = actor; bool focusedWindowFound = false; - for( unsigned int i = 0; i < mCurrentFocusActors.size(); i++ ) + for(unsigned int i = 0; i < mCurrentFocusActors.size(); i++) { - if( mCurrentFocusActors[i].first == mCurrentFocusedWindow ) + if(mCurrentFocusActors[i].first == mCurrentFocusedWindow) { mCurrentFocusActors[i].second = actor; - focusedWindowFound = true; + focusedWindowFound = true; break; } } - if( !focusedWindowFound) + if(!focusedWindowFound) { // A new window gains the focus, so store the focused actor in that window. - mCurrentFocusActors.push_back( std::pair< WeakHandle< Layer>, WeakHandle< Actor > >( mCurrentFocusedWindow , actor )); + mCurrentFocusActors.push_back(std::pair, WeakHandle >(mCurrentFocusedWindow, actor)); } Toolkit::Control newlyFocusedControl = Toolkit::Control::DownCast(actor); - if( newlyFocusedControl ) + if(newlyFocusedControl) { - newlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::FOCUSED ); + newlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::FOCUSED); newlyFocusedControl.SetKeyInputFocus(); } // Push Current Focused Actor to FocusHistory - mFocusHistory.push_back( actor ); + mFocusHistory.push_back(actor); // Delete first element before add new element when Stack is full. - if( mFocusHistory.size() > MAX_HISTORY_AMOUNT ) + if(mFocusHistory.size() > MAX_HISTORY_AMOUNT) { - FocusStackIterator beginPos = mFocusHistory.begin(); - mFocusHistory.erase( beginPos ); + FocusStackIterator beginPos = mFocusHistory.begin(); + mFocusHistory.erase(beginPos); } - DALI_LOG_INFO( gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__); + DALI_LOG_INFO(gLogFilter, Debug::General, "[%s:%d] SUCCEED\n", __FUNCTION__, __LINE__); success = true; } else @@ -298,7 +294,7 @@ Actor KeyboardFocusManager::GetCurrentFocusActor() { Actor actor = mCurrentFocusActor.GetHandle(); - if( actor && ! actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(actor && !actor.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { // If the actor has been removed from the stage, then it should not be focused actor.Reset(); @@ -309,22 +305,22 @@ Actor KeyboardFocusManager::GetCurrentFocusActor() Actor KeyboardFocusManager::GetFocusActorFromCurrentWindow() { - Actor actor; + Actor actor; unsigned int index; - for( index = 0; index < mCurrentFocusActors.size(); index++ ) + for(index = 0; index < mCurrentFocusActors.size(); index++) { - if( mCurrentFocusActors[index].first == mCurrentFocusedWindow ) + if(mCurrentFocusActors[index].first == mCurrentFocusedWindow) { actor = mCurrentFocusActors[index].second.GetHandle(); break; } } - if( actor && ! actor.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(actor && !actor.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { // If the actor has been removed from the window, then the window doesn't have any focused actor actor.Reset(); - mCurrentFocusActors.erase( mCurrentFocusActors.begin() + index ); + mCurrentFocusActors.erase(mCurrentFocusActors.begin() + index); } return actor; @@ -338,23 +334,23 @@ Actor KeyboardFocusManager::GetCurrentFocusGroup() void KeyboardFocusManager::MoveFocusBackward() { // Find Pre Focused Actor when the list size is more than 1 - if( mFocusHistory.size() > 1 ) + if(mFocusHistory.size() > 1) { // Delete current focused actor in history mFocusHistory.pop_back(); // If pre-focused actors are not on stage or deleted, remove them in stack - while( mFocusHistory.size() > 0 ) + while(mFocusHistory.size() > 0) { // Get pre focused actor - Actor target = mFocusHistory[ mFocusHistory.size() -1 ].GetHandle(); + Actor target = mFocusHistory[mFocusHistory.size() - 1].GetHandle(); // Impl of Actor is not null - if( target && target.GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE ) ) + if(target && target.GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { // Delete pre focused actor in history because it will pushed again by SetCurrentFocusActor() mFocusHistory.pop_back(); - SetCurrentFocusActor( target ); + SetCurrentFocusActor(target); break; } else @@ -365,10 +361,10 @@ void KeyboardFocusManager::MoveFocusBackward() } // if there is no actor which can get focus, then push current focus actor in stack again - if( mFocusHistory.size() == 0 ) + if(mFocusHistory.size() == 0) { Actor currentFocusedActor = GetCurrentFocusActor(); - mFocusHistory.push_back( currentFocusedActor ); + mFocusHistory.push_back(currentFocusedActor); } } } @@ -376,7 +372,7 @@ void KeyboardFocusManager::MoveFocusBackward() bool KeyboardFocusManager::IsLayoutControl(Actor actor) const { Toolkit::Control control = Toolkit::Control::DownCast(actor); - return control && GetImplementation( control ).IsKeyboardNavigationSupported(); + return control && GetImplementation(control).IsKeyboardNavigationSupported(); } Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const @@ -386,8 +382,8 @@ Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const Actor parent; if(actor) { - Integration::SceneHolder window = Integration::SceneHolder::Get( actor ); - if ( window ) + Integration::SceneHolder window = Integration::SceneHolder::Get(actor); + if(window) { rootActor = window.GetRootLayer(); } @@ -395,7 +391,7 @@ Toolkit::Control KeyboardFocusManager::GetParentLayoutControl(Actor actor) const parent = actor.GetParent(); } - while( parent && !IsLayoutControl(parent) && parent != rootActor ) + while(parent && !IsLayoutControl(parent) && parent != rootActor) { parent = parent.GetParent(); } @@ -410,28 +406,28 @@ bool KeyboardFocusManager::MoveFocus(Toolkit::Control::KeyboardFocus::Direction bool succeed = false; // Go through the actor's hierarchy until we find a layout control that knows how to move the focus - Toolkit::Control parentLayoutControl = GetParentLayoutControl( currentFocusActor ); - while( parentLayoutControl && !succeed ) + Toolkit::Control parentLayoutControl = GetParentLayoutControl(currentFocusActor); + while(parentLayoutControl && !succeed) { - succeed = DoMoveFocusWithinLayoutControl( parentLayoutControl, currentFocusActor, direction ); - parentLayoutControl = GetParentLayoutControl( parentLayoutControl ); + succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, currentFocusActor, direction); + parentLayoutControl = GetParentLayoutControl(parentLayoutControl); } - if( !succeed ) + if(!succeed) { Actor nextFocusableActor; Toolkit::Control currentFocusControl = Toolkit::Control::DownCast(currentFocusActor); // If the current focused actor is a control, then find the next focusable actor via the focusable properties. - if( currentFocusControl ) + if(currentFocusControl) { - int actorId = -1; - Property::Index index = Property::INVALID_INDEX; + int actorId = -1; + Property::Index index = Property::INVALID_INDEX; Property::Value value; // Find property index based upon focus direction - switch ( direction ) + switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { @@ -458,62 +454,62 @@ bool KeyboardFocusManager::MoveFocus(Toolkit::Control::KeyboardFocus::Direction } // If the focusable property is set then determine next focusable actor - if( index != Property::INVALID_INDEX) + if(index != Property::INVALID_INDEX) { - value = currentFocusActor.GetProperty( index ); + value = currentFocusActor.GetProperty(index); actorId = value.Get(); // If actor's id is valid then find actor form actor's id. The actor should be on the stage. - if( actorId != -1 ) + if(actorId != -1) { - if( currentFocusActor.GetParent() ) + if(currentFocusActor.GetParent()) { - nextFocusableActor = currentFocusActor.GetParent().FindChildById( actorId ); + nextFocusableActor = currentFocusActor.GetParent().FindChildById(actorId); } - if( !nextFocusableActor ) + if(!nextFocusableActor) { - Integration::SceneHolder window = Integration::SceneHolder::Get( currentFocusActor ); - if ( window ) + Integration::SceneHolder window = Integration::SceneHolder::Get(currentFocusActor); + if(window) { - nextFocusableActor = window.GetRootLayer().FindChildById( actorId ); + nextFocusableActor = window.GetRootLayer().FindChildById(actorId); } } } } } - if( !nextFocusableActor ) + if(!nextFocusableActor) { // If the implementation of CustomAlgorithmInterface is provided then the PreFocusChangeSignal is no longer emitted. - if( mCustomAlgorithmInterface ) + if(mCustomAlgorithmInterface) { mIsWaitingKeyboardFocusChangeCommit = true; - nextFocusableActor = mCustomAlgorithmInterface->GetNextFocusableActor( currentFocusActor, Actor(), direction ); + nextFocusableActor = mCustomAlgorithmInterface->GetNextFocusableActor(currentFocusActor, Actor(), direction); mIsWaitingKeyboardFocusChangeCommit = false; } - else if( !mPreFocusChangeSignal.Empty() ) + else if(!mPreFocusChangeSignal.Empty()) { // Don't know how to move the focus further. The application needs to tell us which actor to move the focus to mIsWaitingKeyboardFocusChangeCommit = true; - nextFocusableActor = mPreFocusChangeSignal.Emit( currentFocusActor, Actor(), direction ); + nextFocusableActor = mPreFocusChangeSignal.Emit(currentFocusActor, Actor(), direction); mIsWaitingKeyboardFocusChangeCommit = false; } } - if( nextFocusableActor && nextFocusableActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE ) ) + if(nextFocusableActor && nextFocusableActor.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // Whether the next focusable actor is a layout control - if( IsLayoutControl( nextFocusableActor ) ) + if(IsLayoutControl(nextFocusableActor)) { // If so, move the focus inside it. - Toolkit::Control layoutControl = Toolkit::Control::DownCast( nextFocusableActor) ; - succeed = DoMoveFocusWithinLayoutControl( layoutControl, currentFocusActor, direction ); + Toolkit::Control layoutControl = Toolkit::Control::DownCast(nextFocusableActor); + succeed = DoMoveFocusWithinLayoutControl(layoutControl, currentFocusActor, direction); } else { // Otherwise, just set focus to the next focusable actor - succeed = SetCurrentFocusActor( nextFocusableActor ); + succeed = SetCurrentFocusActor(nextFocusableActor); } } } @@ -524,29 +520,29 @@ bool KeyboardFocusManager::MoveFocus(Toolkit::Control::KeyboardFocus::Direction bool KeyboardFocusManager::DoMoveFocusWithinLayoutControl(Toolkit::Control control, Actor actor, Toolkit::Control::KeyboardFocus::Direction direction) { // Ask the control for the next actor to focus - Actor nextFocusableActor = GetImplementation( control ).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled); + Actor nextFocusableActor = GetImplementation(control).GetNextKeyboardFocusableActor(actor, direction, mFocusGroupLoopEnabled); if(nextFocusableActor) { - if(!nextFocusableActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE )) + if(!nextFocusableActor.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // If the actor is not focusable, ask the same layout control for the next actor to focus return DoMoveFocusWithinLayoutControl(control, nextFocusableActor, direction); } else { - Actor currentFocusActor = GetCurrentFocusActor(); + Actor currentFocusActor = GetCurrentFocusActor(); Actor committedFocusActor = nextFocusableActor; // We will try to move the focus to the actor. Emit a signal to notify the proposed actor to focus // Signal handler can check the proposed actor and return a different actor if it wishes. - if( !mPreFocusChangeSignal.Empty() ) + if(!mPreFocusChangeSignal.Empty()) { mIsWaitingKeyboardFocusChangeCommit = true; - committedFocusActor = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction); + committedFocusActor = mPreFocusChangeSignal.Emit(currentFocusActor, nextFocusableActor, direction); mIsWaitingKeyboardFocusChangeCommit = false; } - if (committedFocusActor && committedFocusActor.GetProperty< bool >( Actor::Property::KEYBOARD_FOCUSABLE )) + if(committedFocusActor && committedFocusActor.GetProperty(Actor::Property::KEYBOARD_FOCUSABLE)) { // Whether the commited focusable actor is a layout control if(IsLayoutControl(committedFocusActor)) @@ -563,7 +559,7 @@ bool KeyboardFocusManager::DoMoveFocusWithinLayoutControl(Toolkit::Control contr // If the application hasn't changed our proposed actor, we informs the layout control we will // move the focus to what the control returns. The control might wish to perform some actions // before the focus is actually moved. - GetImplementation( control ).OnKeyboardFocusChangeCommitted( committedFocusActor ); + GetImplementation(control).OnKeyboardFocusChangeCommitted(committedFocusActor); } return SetCurrentFocusActor(committedFocusActor); @@ -594,8 +590,8 @@ bool KeyboardFocusManager::DoMoveFocusToNextFocusGroup(bool forward) // If the current focus group has a parent layout control, we can probably automatically // move the focus to the next focus group in the forward or backward direction. Toolkit::Control::KeyboardFocus::Direction direction = forward ? Toolkit::Control::KeyboardFocus::RIGHT : Toolkit::Control::KeyboardFocus::LEFT; - succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction); - parentLayoutControl = GetParentLayoutControl(parentLayoutControl); + succeed = DoMoveFocusWithinLayoutControl(parentLayoutControl, GetCurrentFocusActor(), direction); + parentLayoutControl = GetParentLayoutControl(parentLayoutControl); } if(!mFocusGroupChangedSignal.Empty()) @@ -609,19 +605,19 @@ bool KeyboardFocusManager::DoMoveFocusToNextFocusGroup(bool forward) void KeyboardFocusManager::DoKeyboardEnter(Actor actor) { - if( actor ) + if(actor) { - Toolkit::Control control = Toolkit::Control::DownCast( actor ); - if( control ) + Toolkit::Control control = Toolkit::Control::DownCast(actor); + if(control) { // Notify the control that enter has been pressed on it. - GetImplementation( control ).KeyboardEnter(); + GetImplementation(control).KeyboardEnter(); } // Send a notification for the actor. - if( !mFocusedActorEnterKeySignal.Empty() ) + if(!mFocusedActorEnterKeySignal.Empty()) { - mFocusedActorEnterKeySignal.Emit( actor ); + mFocusedActorEnterKeySignal.Emit(actor); } } } @@ -629,29 +625,29 @@ void KeyboardFocusManager::DoKeyboardEnter(Actor actor) void KeyboardFocusManager::ClearFocus() { Actor actor = GetCurrentFocusActor(); - if( actor ) + if(actor) { - if( mFocusIndicatorActor ) + if(mFocusIndicatorActor) { - actor.Remove( mFocusIndicatorActor ); + actor.Remove(mFocusIndicatorActor); } // Send notification for the change of focus actor - if( !mFocusChangedSignal.Empty() ) + if(!mFocusChangedSignal.Empty()) { - mFocusChangedSignal.Emit( actor, Actor() ); + mFocusChangedSignal.Emit(actor, Actor()); } - Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast( actor ); - if( currentlyFocusedControl ) + Toolkit::Control currentlyFocusedControl = Toolkit::Control::DownCast(actor); + if(currentlyFocusedControl) { - currentlyFocusedControl.SetProperty( DevelControl::Property::STATE, DevelControl::NORMAL ); + currentlyFocusedControl.SetProperty(DevelControl::Property::STATE, DevelControl::NORMAL); currentlyFocusedControl.ClearKeyInputFocus(); } } mCurrentFocusActor.Reset(); - mIsFocusIndicatorShown = ( mAlwaysShowIndicator == ALWAYS_SHOW ) ? SHOW : HIDE; + mIsFocusIndicatorShown = (mAlwaysShowIndicator == ALWAYS_SHOW) ? SHOW : HIDE; } void KeyboardFocusManager::SetFocusGroupLoop(bool enabled) @@ -669,7 +665,7 @@ void KeyboardFocusManager::SetAsFocusGroup(Actor actor, bool isFocusGroup) if(actor) { // Create/Set focus group property. - actor.RegisterProperty( IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE ); + actor.RegisterProperty(IS_FOCUS_GROUP_PROPERTY_NAME, isFocusGroup, Property::READ_WRITE); } } @@ -693,7 +689,7 @@ bool KeyboardFocusManager::IsFocusGroup(Actor actor) const Actor KeyboardFocusManager::GetFocusGroup(Actor actor) { // Go through the actor's hierarchy to check which focus group the actor belongs to - while (actor && !IsFocusGroup(actor)) + while(actor && !IsFocusGroup(actor)) { actor = actor.GetParent(); } @@ -726,19 +722,19 @@ void KeyboardFocusManager::SetFocusIndicatorActor(Actor indicator) Actor KeyboardFocusManager::GetFocusIndicatorActor() { - if( ! mFocusIndicatorActor ) + if(!mFocusIndicatorActor) { // Create the default if it hasn't been set and one that's shared by all the keyboard focusable actors const std::string imageDirPath = AssetManager::GetDaliImagePath(); - mFocusIndicatorActor = Toolkit::ImageView::New( imageDirPath + FOCUS_BORDER_IMAGE_FILE_NAME ); + mFocusIndicatorActor = Toolkit::ImageView::New(imageDirPath + FOCUS_BORDER_IMAGE_FILE_NAME); // Apply size constraint to the focus indicator - mFocusIndicatorActor.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mFocusIndicatorActor.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); } - mFocusIndicatorActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mFocusIndicatorActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mFocusIndicatorActor.SetProperty( Actor::Property::POSITION, Vector2(0.0f, 0.0f)); + mFocusIndicatorActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mFocusIndicatorActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mFocusIndicatorActor.SetProperty(Actor::Property::POSITION, Vector2(0.0f, 0.0f)); return mFocusIndicatorActor; } @@ -747,7 +743,7 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) { std::string keyName = event.GetKeyName(); - if( mIsFocusIndicatorShown == UNKNOWN ) + if(mIsFocusIndicatorShown == UNKNOWN) { GetConfigurationFromStyleManger(); } @@ -756,7 +752,7 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) if(event.GetState() == KeyEvent::DOWN) { - if (keyName == "Left") + if(keyName == "Left") { if(!mIsFocusIndicatorShown) { @@ -781,11 +777,11 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Right") + else if(keyName == "Right") { if(!mIsFocusIndicatorShown) { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -804,9 +800,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Up") + else if(keyName == "Up") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -819,9 +815,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Down") + else if(keyName == "Down") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -834,9 +830,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Prior") + else if(keyName == "Prior") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -849,9 +845,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Next") + else if(keyName == "Next") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -864,9 +860,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Tab") + else if(keyName == "Tab") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -880,9 +876,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "space") + else if(keyName == "space") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -890,10 +886,10 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "") + else if(keyName == "") { // Check the fake key event for evas-plugin case - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -901,19 +897,19 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) isFocusStartableKey = true; } - else if (keyName == "Backspace") + else if(keyName == "Backspace") { // Emit signal to go back to the previous view??? } - else if (keyName == "Escape") + else if(keyName == "Escape") { } } else if(event.GetState() == KeyEvent::UP) { - if (keyName == "Return") + if(keyName == "Return") { - if( mIsFocusIndicatorShown == HIDE ) + if(mIsFocusIndicatorShown == HIDE) { // Show focus indicator mIsFocusIndicatorShown = SHOW; @@ -922,9 +918,9 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) { // The focused actor has enter pressed on it Actor actor = GetCurrentFocusActor(); - if( actor ) + if(actor) { - DoKeyboardEnter( actor ); + DoKeyboardEnter(actor); } } @@ -932,15 +928,15 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) } } - if( isFocusStartableKey && mIsFocusIndicatorShown == SHOW ) + if(isFocusStartableKey && mIsFocusIndicatorShown == SHOW) { Actor actor = GetCurrentFocusActor(); - if( actor ) + if(actor) { - if( mEnableFocusIndicator == ENABLE ) + if(mEnableFocusIndicator == ENABLE) { // Make sure the focused actor is highlighted - actor.Add( GetFocusIndicatorActor() ); + actor.Add(GetFocusIndicatorActor()); } } else @@ -949,7 +945,6 @@ void KeyboardFocusManager::OnKeyEvent(const KeyEvent& event) // Let's try to move the initial focus MoveFocus(Toolkit::Control::KeyboardFocus::RIGHT); } - } } @@ -957,7 +952,7 @@ void KeyboardFocusManager::OnTouch(const TouchEvent& touch) { // if mIsFocusIndicatorShown is UNKNOWN, it means Configuration is not loaded. // Try to load configuration. - if( mIsFocusIndicatorShown == UNKNOWN ) + if(mIsFocusIndicatorShown == UNKNOWN) { GetConfigurationFromStyleManger(); } @@ -965,28 +960,28 @@ void KeyboardFocusManager::OnTouch(const TouchEvent& touch) // Clear the focus when user touch the screen. // We only do this on a Down event, otherwise the clear action may override a manually focused actor. // If mClearFocusOnTouch is false, do not clear the focus even if user touch the screen. - if( (( touch.GetPointCount() < 1 ) || ( touch.GetState( 0 ) == PointState::DOWN )) && mClearFocusOnTouch ) + if(((touch.GetPointCount() < 1) || (touch.GetState(0) == PointState::DOWN)) && mClearFocusOnTouch) { ClearFocus(); } } -void KeyboardFocusManager::OnWindowFocusChanged(Window window, bool focusIn ) +void KeyboardFocusManager::OnWindowFocusChanged(Window window, bool focusIn) { - if( focusIn && mCurrentFocusedWindow.GetHandle() != window.GetRootLayer() ) + if(focusIn && mCurrentFocusedWindow.GetHandle() != window.GetRootLayer()) { // Change Current Focused Window - Layer rootLayer = window.GetRootLayer(); + Layer rootLayer = window.GetRootLayer(); mCurrentFocusedWindow = rootLayer; // Get Current Focused Actor from window Actor currentFocusedActor = GetFocusActorFromCurrentWindow(); - SetCurrentFocusActor( currentFocusedActor ); + SetCurrentFocusActor(currentFocusedActor); - if( currentFocusedActor && ( mEnableFocusIndicator == ENABLE ) ) + if(currentFocusedActor && (mEnableFocusIndicator == ENABLE)) { // Make sure the focused actor is highlighted - currentFocusedActor.Add( GetFocusIndicatorActor() ); + currentFocusedActor.Add(GetFocusIndicatorActor()); mIsFocusIndicatorShown = SHOW; } } @@ -1012,28 +1007,28 @@ Toolkit::KeyboardFocusManager::FocusedActorEnterKeySignalType& KeyboardFocusMana return mFocusedActorEnterKeySignal; } -bool KeyboardFocusManager::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool KeyboardFocusManager::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - KeyboardFocusManager* manager = static_cast< KeyboardFocusManager* >( object ); // TypeRegistry guarantees that this is the correct type. + bool connected(true); + KeyboardFocusManager* manager = static_cast(object); // TypeRegistry guarantees that this is the correct type. - if( 0 == strcmp( signalName.c_str(), SIGNAL_PRE_FOCUS_CHANGE ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_PRE_FOCUS_CHANGE)) { - manager->PreFocusChangeSignal().Connect( tracker, functor ); + manager->PreFocusChangeSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUS_CHANGED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUS_CHANGED)) { - manager->FocusChangedSignal().Connect( tracker, functor ); + manager->FocusChangedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUS_GROUP_CHANGED ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUS_GROUP_CHANGED)) { - manager->FocusGroupChangedSignal().Connect( tracker, functor ); + manager->FocusGroupChangedSignal().Connect(tracker, functor); } - else if( 0 == strcmp( signalName.c_str(), SIGNAL_FOCUSED_ACTOR_ENTER_KEY ) ) + else if(0 == strcmp(signalName.c_str(), SIGNAL_FOCUSED_ACTOR_ENTER_KEY)) { - manager->FocusedActorEnterKeySignal().Connect( tracker, functor ); + manager->FocusedActorEnterKeySignal().Connect(tracker, functor); } else { @@ -1051,18 +1046,17 @@ void KeyboardFocusManager::SetCustomAlgorithm(CustomAlgorithmInterface& interfac void KeyboardFocusManager::EnableFocusIndicator(bool enable) { - if( !enable && mFocusIndicatorActor ) + if(!enable && mFocusIndicatorActor) { mFocusIndicatorActor.Unparent(); } - mEnableFocusIndicator = enable? ENABLE : DISABLE; - + mEnableFocusIndicator = enable ? ENABLE : DISABLE; } bool KeyboardFocusManager::IsFocusIndicatorEnabled() const { - return ( mEnableFocusIndicator == ENABLE ); + return (mEnableFocusIndicator == ENABLE); } } // namespace Internal diff --git a/dali-toolkit/internal/focus-manager/keyinput-focus-manager-impl.cpp b/dali-toolkit/internal/focus-manager/keyinput-focus-manager-impl.cpp index 2549e52..ad87ac3 100644 --- a/dali-toolkit/internal/focus-manager/keyinput-focus-manager-impl.cpp +++ b/dali-toolkit/internal/focus-manager/keyinput-focus-manager-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,99 +19,95 @@ #include "keyinput-focus-manager-impl.h" // EXTERNAL INCLUDES -#include // for strcmp -#include #include -#include #include #include +#include +#include +#include // for strcmp namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // Signals const char* const SIGNAL_KEY_INPUT_FOCUS_CHANGED = "keyInputFocusChanged"; -} +} // namespace KeyInputFocusManager::KeyInputFocusManager() -: mSlotDelegate( this ), +: mSlotDelegate(this), mCurrentFocusControl() { // Retrieve all the existing widnows Dali::SceneHolderList sceneHolders = Adaptor::Get().GetSceneHolders(); - for( auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter ) + for(auto iter = sceneHolders.begin(); iter != sceneHolders.end(); ++iter) { - ( *iter ).KeyEventGeneratedSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnKeyEvent ); + (*iter).KeyEventGeneratedSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnKeyEvent); } // Get notified when any new scene holder is created afterwards - Adaptor::Get().WindowCreatedSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnSceneHolderCreated ); + Adaptor::Get().WindowCreatedSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnSceneHolderCreated); } KeyInputFocusManager::~KeyInputFocusManager() { } -void KeyInputFocusManager::OnSceneHolderCreated( Dali::Integration::SceneHolder& sceneHolder ) +void KeyInputFocusManager::OnSceneHolderCreated(Dali::Integration::SceneHolder& sceneHolder) { - sceneHolder.KeyEventGeneratedSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnKeyEvent ); + sceneHolder.KeyEventGeneratedSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnKeyEvent); } -void KeyInputFocusManager::SetFocus( Toolkit::Control control ) +void KeyInputFocusManager::SetFocus(Toolkit::Control control) { - if( !control ) + if(!control) { // No-op return; } - if( control == mCurrentFocusControl ) + if(control == mCurrentFocusControl) { // Control already has focus return; } - control.OffSceneSignal().Connect( mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection ); + control.OffSceneSignal().Connect(mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection); Dali::Toolkit::Control previousFocusControl = GetCurrentFocusControl(); - if( previousFocusControl ) + if(previousFocusControl) { // Notify the control that it has lost key input focus - GetImplementation( previousFocusControl ).OnKeyInputFocusLost(); + GetImplementation(previousFocusControl).OnKeyInputFocusLost(); } // Set control to currentFocusControl mCurrentFocusControl = control; // Tell the new actor that it has gained focus. - GetImplementation( control ).OnKeyInputFocusGained(); + GetImplementation(control).OnKeyInputFocusGained(); // Emit the signal to inform focus change to the application. - if ( !mKeyInputFocusChangedSignal.Empty() ) + if(!mKeyInputFocusChangedSignal.Empty()) { - mKeyInputFocusChangedSignal.Emit( control, previousFocusControl ); + mKeyInputFocusChangedSignal.Emit(control, previousFocusControl); } } -void KeyInputFocusManager::RemoveFocus( Toolkit::Control control ) +void KeyInputFocusManager::RemoveFocus(Toolkit::Control control) { - if( control == mCurrentFocusControl ) + if(control == mCurrentFocusControl) { - control.OffSceneSignal().Disconnect( mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection ); + control.OffSceneSignal().Disconnect(mSlotDelegate, &KeyInputFocusManager::OnFocusControlSceneDisconnection); // Notify the control that it has lost key input focus - GetImplementation( control ).OnKeyInputFocusLost(); + GetImplementation(control).OnKeyInputFocusLost(); mCurrentFocusControl.Reset(); } @@ -127,36 +123,36 @@ Toolkit::KeyInputFocusManager::KeyInputFocusChangedSignalType& KeyInputFocusMana return mKeyInputFocusChangedSignal; } -bool KeyInputFocusManager::OnKeyEvent( const KeyEvent& event ) +bool KeyInputFocusManager::OnKeyEvent(const KeyEvent& event) { bool consumed = false; Toolkit::Control control = GetCurrentFocusControl(); - if( control ) + if(control) { // Notify the control about the key event - consumed = EmitKeyEventSignal( control, event ); + consumed = EmitKeyEventSignal(control, event); } return consumed; } -bool KeyInputFocusManager::EmitKeyEventSignal( Toolkit::Control control, const KeyEvent& event ) +bool KeyInputFocusManager::EmitKeyEventSignal(Toolkit::Control control, const KeyEvent& event) { bool consumed = false; - if( control ) + if(control) { - consumed = GetImplementation( control ).EmitKeyEventSignal( event ); + consumed = GetImplementation(control).EmitKeyEventSignal(event); // if control doesn't consume KeyEvent, give KeyEvent to its parent. - if( !consumed ) + if(!consumed) { - Toolkit::Control parent = Toolkit::Control::DownCast( control.GetParent() ); + Toolkit::Control parent = Toolkit::Control::DownCast(control.GetParent()); - if( parent ) + if(parent) { - consumed = EmitKeyEventSignal( parent, event ); + consumed = EmitKeyEventSignal(parent, event); } } } @@ -164,22 +160,21 @@ bool KeyInputFocusManager::EmitKeyEventSignal( Toolkit::Control control, const K return consumed; } -void KeyInputFocusManager::OnFocusControlSceneDisconnection( Dali::Actor actor ) +void KeyInputFocusManager::OnFocusControlSceneDisconnection(Dali::Actor actor) { - RemoveFocus( Dali::Toolkit::Control::DownCast( actor ) ); + RemoveFocus(Dali::Toolkit::Control::DownCast(actor)); } - -bool KeyInputFocusManager::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool KeyInputFocusManager::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - bool connected( true ); - KeyInputFocusManager* manager = dynamic_cast( object ); + bool connected(true); + KeyInputFocusManager* manager = dynamic_cast(object); - if( manager ) + if(manager) { - if( 0 == strcmp( signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_CHANGED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_KEY_INPUT_FOCUS_CHANGED)) { - manager->KeyInputFocusChangedSignal().Connect( tracker, functor ); + manager->KeyInputFocusChangedSignal().Connect(tracker, functor); } else { diff --git a/dali-toolkit/internal/helpers/color-conversion.cpp b/dali-toolkit/internal/helpers/color-conversion.cpp index 6789cee..76415ff 100644 --- a/dali-toolkit/internal/helpers/color-conversion.cpp +++ b/dali-toolkit/internal/helpers/color-conversion.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. @@ -18,29 +18,28 @@ #include // EXTERNAL INCLUDES -#include -#include #include +#include +#include using Dali::Vector4; namespace { - /** * Converts a HTML style 'color' hex string ("#FF0000" for bright red) to a Vector4. * The Vector4 alpha component will be set to 1.0f * @param hexString The HTML style hex string * @return a Vector4 containing the new color value */ -Vector4 HexStringToVector4( const char* s ) +Vector4 HexStringToVector4(const char* s) { unsigned int value(0u); - std::istringstream( s ) >> std::hex >> value; - return Vector4( ((value >> 16 ) & 0xff ) / 255.0f, - ((value >> 8 ) & 0xff ) / 255.0f, - (value & 0xff ) / 255.0f, - 1.0f ); + std::istringstream(s) >> std::hex >> value; + return Vector4(((value >> 16) & 0xff) / 255.0f, + ((value >> 8) & 0xff) / 255.0f, + (value & 0xff) / 255.0f, + 1.0f); } } // unnamed namespace @@ -51,51 +50,50 @@ namespace Toolkit { namespace Internal { - -bool ConvertStringToColor( const std::string& colorString, Vector4& outColor ) +bool ConvertStringToColor(const std::string& colorString, Vector4& outColor) { - bool success( false ); + bool success(false); - if( ( '#' == colorString[0] ) && - ( 7 == colorString.size() ) ) + if(('#' == colorString[0]) && + (7 == colorString.size())) { const char* cString = colorString.c_str(); - outColor = HexStringToVector4( &cString[1] ); - success = true; + outColor = HexStringToVector4(&cString[1]); + success = true; } else { Dali::ColorController controller = Dali::ColorController::Get(); - if( controller ) + if(controller) { - success = controller.RetrieveColor( colorString, outColor ); + success = controller.RetrieveColor(colorString, outColor); } } return success; } -bool ConvertPropertyToColor( const Property::Value& colorValue, Vector4& outColor ) +bool ConvertPropertyToColor(const Property::Value& colorValue, Vector4& outColor) { - bool success( false ); + bool success(false); - if( Property::VECTOR4 == colorValue.GetType() ) + if(Property::VECTOR4 == colorValue.GetType()) { - success = colorValue.Get( outColor ); + success = colorValue.Get(outColor); } - else if( Property::STRING == colorValue.GetType() ) + else if(Property::STRING == colorValue.GetType()) { std::string colorString; - if( colorValue.Get( colorString ) ) + if(colorValue.Get(colorString)) { - success = ConvertStringToColor( colorString, outColor ); + success = ConvertStringToColor(colorString, outColor); } } return success; } -} // Internal -} // Toolkit -} // Dali +} // namespace Internal +} // namespace Toolkit +} // namespace Dali diff --git a/dali-toolkit/internal/helpers/property-helper.cpp b/dali-toolkit/internal/helpers/property-helper.cpp index db8597b..3fa1b7a 100644 --- a/dali-toolkit/internal/helpers/property-helper.cpp +++ b/dali-toolkit/internal/helpers/property-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. @@ -23,30 +23,27 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - -bool GetStringFromProperty( const Property::Value& value, std::string& output ) +bool GetStringFromProperty(const Property::Value& value, std::string& output) { bool extracted = false; - if( value.Get( output ) ) + if(value.Get(output)) { extracted = true; } else { const Property::Array* array = value.GetArray(); - if( array ) + if(array) { const unsigned int arraySize = array->Size(); - for( unsigned int i = 0; i < arraySize; ++i ) + for(unsigned int i = 0; i < arraySize; ++i) { std::string element; - if( array->GetElementAt( i ).Get( element ) ) + if(array->GetElementAt(i).Get(element)) { extracted = true; output += element + '\n'; diff --git a/dali-toolkit/internal/image-loader/async-image-loader-impl.cpp b/dali-toolkit/internal/image-loader/async-image-loader-impl.cpp index 912a441..412eda7 100644 --- a/dali-toolkit/internal/image-loader/async-image-loader-impl.cpp +++ b/dali-toolkit/internal/image-loader/async-image-loader-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,18 +23,15 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - AsyncImageLoader::AsyncImageLoader() : mLoadedSignal(), - mLoadThread( new EventThreadCallback( MakeCallback( this, &AsyncImageLoader::ProcessLoadedImage ) ) ), - mLoadTaskId( 0u ), - mIsLoadThreadStarted( false ) + mLoadThread(new EventThreadCallback(MakeCallback(this, &AsyncImageLoader::ProcessLoadedImage))), + mLoadTaskId(0u), + mIsLoadThreadStarted(false) { } @@ -49,48 +46,48 @@ IntrusivePtr AsyncImageLoader::New() return internal; } -uint32_t AsyncImageLoader::LoadAnimatedImage( Dali::AnimatedImageLoading animatedImageLoading, - uint32_t frameIndex ) +uint32_t AsyncImageLoader::LoadAnimatedImage(Dali::AnimatedImageLoading animatedImageLoading, + uint32_t frameIndex) { - if( !mIsLoadThreadStarted ) + if(!mIsLoadThreadStarted) { mLoadThread.Start(); mIsLoadThreadStarted = true; } - mLoadThread.AddTask( new LoadingTask( ++mLoadTaskId, animatedImageLoading, frameIndex ) ); + mLoadThread.AddTask(new LoadingTask(++mLoadTaskId, animatedImageLoading, frameIndex)); return mLoadTaskId; } -uint32_t AsyncImageLoader::Load( const VisualUrl& url, - ImageDimensions dimensions, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection, - DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) +uint32_t AsyncImageLoader::Load(const VisualUrl& url, + ImageDimensions dimensions, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection, + DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) { - if( !mIsLoadThreadStarted ) + if(!mIsLoadThreadStarted) { mLoadThread.Start(); mIsLoadThreadStarted = true; } - mLoadThread.AddTask( new LoadingTask( ++mLoadTaskId, url, dimensions, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad ) ); + mLoadThread.AddTask(new LoadingTask(++mLoadTaskId, url, dimensions, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad)); return mLoadTaskId; } -uint32_t AsyncImageLoader::ApplyMask( Devel::PixelBuffer pixelBuffer, - Devel::PixelBuffer maskPixelBuffer, - float contentScale, - bool cropToMask, - DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) +uint32_t AsyncImageLoader::ApplyMask(Devel::PixelBuffer pixelBuffer, + Devel::PixelBuffer maskPixelBuffer, + float contentScale, + bool cropToMask, + DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) { - if( !mIsLoadThreadStarted ) + if(!mIsLoadThreadStarted) { mLoadThread.Start(); mIsLoadThreadStarted = true; } - mLoadThread.AddTask( new LoadingTask( ++mLoadTaskId, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad ) ); + mLoadThread.AddTask(new LoadingTask(++mLoadTaskId, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad)); return mLoadTaskId; } @@ -105,9 +102,9 @@ Toolkit::DevelAsyncImageLoader::PixelBufferLoadedSignalType& AsyncImageLoader::P return mPixelBufferLoadedSignal; } -bool AsyncImageLoader::Cancel( uint32_t loadingTaskId ) +bool AsyncImageLoader::Cancel(uint32_t loadingTaskId) { - return mLoadThread.CancelTask( loadingTaskId ); + return mLoadThread.CancelTask(loadingTaskId); } void AsyncImageLoader::CancelAll() @@ -117,20 +114,20 @@ void AsyncImageLoader::CancelAll() void AsyncImageLoader::ProcessLoadedImage() { - while( LoadingTask *next = mLoadThread.NextCompletedTask() ) + while(LoadingTask* next = mLoadThread.NextCompletedTask()) { - if( mPixelBufferLoadedSignal.GetConnectionCount() > 0 ) + if(mPixelBufferLoadedSignal.GetConnectionCount() > 0) { - mPixelBufferLoadedSignal.Emit( next->id, next->pixelBuffer ); + mPixelBufferLoadedSignal.Emit(next->id, next->pixelBuffer); } - else if( mLoadedSignal.GetConnectionCount() > 0 ) + else if(mLoadedSignal.GetConnectionCount() > 0) { PixelData pixelData; - if( next->pixelBuffer ) + if(next->pixelBuffer) { - pixelData = Devel::PixelBuffer::Convert( next->pixelBuffer ); + pixelData = Devel::PixelBuffer::Convert(next->pixelBuffer); } - mLoadedSignal.Emit( next->id, pixelData ); + mLoadedSignal.Emit(next->id, pixelData); } delete next; diff --git a/dali-toolkit/internal/image-loader/atlas-packer.cpp b/dali-toolkit/internal/image-loader/atlas-packer.cpp index 4becddf..88a8744 100644 --- a/dali-toolkit/internal/image-loader/atlas-packer.cpp +++ b/dali-toolkit/internal/image-loader/atlas-packer.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,82 +19,77 @@ #include "atlas-packer.h" // EXTERNAL HEADER -#include // For abs() #include +#include // For abs() namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -bool ApproximatelyEqual( uint32_t a, uint32_t b ) +bool ApproximatelyEqual(uint32_t a, uint32_t b) { - return std::abs( static_cast( a - b ) ) <= 1; + return std::abs(static_cast(a - b)) <= 1; } -uint16_t MaxDimension( const Uint16Pair& dimensions ) +uint16_t MaxDimension(const Uint16Pair& dimensions) { return dimensions.GetWidth() >= dimensions.GetHeight() ? dimensions.GetWidth() : dimensions.GetHeight(); } -void Swap( Uint16Pair& first, Uint16Pair& second ) +void Swap(Uint16Pair& first, Uint16Pair& second) { Uint16Pair temp = first; - first = second; - second = temp; + first = second; + second = temp; } -} +} // namespace -AtlasPacker::Node::Node( Node* parent, SizeType x, SizeType y, SizeType width, SizeType height ) -: rectArea( x, y, width, height ), +AtlasPacker::Node::Node(Node* parent, SizeType x, SizeType y, SizeType width, SizeType height) +: rectArea(x, y, width, height), parent(parent), - occupied( false ) + occupied(false) { child[0] = NULL; child[1] = NULL; } -AtlasPacker:: AtlasPacker( SizeType atlasWidth, SizeType atlasHeight ) -: mAvailableArea( atlasWidth * atlasHeight ) +AtlasPacker::AtlasPacker(SizeType atlasWidth, SizeType atlasHeight) +: mAvailableArea(atlasWidth * atlasHeight) { - mRoot = new Node( NULL, 0u, 0u, atlasWidth, atlasHeight ); + mRoot = new Node(NULL, 0u, 0u, atlasWidth, atlasHeight); } AtlasPacker::~AtlasPacker() { - DeleteNode( mRoot ); + DeleteNode(mRoot); } -bool AtlasPacker::Pack( SizeType blockWidth, SizeType blockHeight, - SizeType& packPositionX, SizeType& packPositionY) +bool AtlasPacker::Pack(SizeType blockWidth, SizeType blockHeight, SizeType& packPositionX, SizeType& packPositionY) { - Node* firstFit = InsertNode( mRoot, blockWidth, blockHeight ); - if( firstFit != NULL ) + Node* firstFit = InsertNode(mRoot, blockWidth, blockHeight); + if(firstFit != NULL) { firstFit->occupied = true; - packPositionX = firstFit->rectArea.x; - packPositionY = firstFit->rectArea.y; - mAvailableArea -= blockWidth*blockHeight; + packPositionX = firstFit->rectArea.x; + packPositionY = firstFit->rectArea.y; + mAvailableArea -= blockWidth * blockHeight; return true; } return false; } -void AtlasPacker::DeleteBlock( SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight ) +void AtlasPacker::DeleteBlock(SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight) { - Node* node = SearchNode( mRoot, packPositionX, packPositionY, blockWidth, blockHeight ); - if( node != NULL ) + Node* node = SearchNode(mRoot, packPositionX, packPositionY, blockWidth, blockHeight); + if(node != NULL) { - mAvailableArea += blockWidth*blockHeight; - MergeToNonOccupied( node ); + mAvailableArea += blockWidth * blockHeight; + MergeToNonOccupied(node); } } @@ -103,18 +98,18 @@ unsigned int AtlasPacker::GetAvailableArea() const return mAvailableArea; } -AtlasPacker::Node* AtlasPacker::InsertNode( Node* root, SizeType blockWidth, SizeType blockHeight ) +AtlasPacker::Node* AtlasPacker::InsertNode(Node* root, SizeType blockWidth, SizeType blockHeight) { - if( root == NULL ) + if(root == NULL) { return NULL; } - if( root->occupied ) + if(root->occupied) { // if not the leaf, then try insert into the first child. Node* newNode = InsertNode(root->child[0], blockWidth, blockHeight); - if( newNode == NULL )// no room, try insert into the second child. + if(newNode == NULL) // no room, try insert into the second child. { newNode = InsertNode(root->child[1], blockWidth, blockHeight); } @@ -122,58 +117,57 @@ AtlasPacker::Node* AtlasPacker::InsertNode( Node* root, SizeType blockWidth, Siz } // too small, return - if( root->rectArea.width < blockWidth || root->rectArea.height < blockHeight ) + if(root->rectArea.width < blockWidth || root->rectArea.height < blockHeight) { return NULL; } // right size, accept - if( root->rectArea.width == blockWidth && root->rectArea.height == blockHeight ) + if(root->rectArea.width == blockWidth && root->rectArea.height == blockHeight) { return root; } //too much room, need to split - SplitNode( root, blockWidth, blockHeight ); + SplitNode(root, blockWidth, blockHeight); // insert into the first child created. - return InsertNode( root->child[0], blockWidth, blockHeight); + return InsertNode(root->child[0], blockWidth, blockHeight); } -void AtlasPacker::SplitNode( Node* node, SizeType blockWidth, SizeType blockHeight ) +void AtlasPacker::SplitNode(Node* node, SizeType blockWidth, SizeType blockHeight) { node->occupied = true; // decide which way to split - SizeType remainingWidth = node->rectArea.width - blockWidth; + SizeType remainingWidth = node->rectArea.width - blockWidth; SizeType remainingHeight = node->rectArea.height - blockHeight; - if( remainingWidth > remainingHeight ) // split vertically + if(remainingWidth > remainingHeight) // split vertically { - node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, blockWidth, node->rectArea.height ); - node->child[1] = new Node( node, node->rectArea.x+blockWidth, node->rectArea.y, node->rectArea.width-blockWidth, node->rectArea.height ); + node->child[0] = new Node(node, node->rectArea.x, node->rectArea.y, blockWidth, node->rectArea.height); + node->child[1] = new Node(node, node->rectArea.x + blockWidth, node->rectArea.y, node->rectArea.width - blockWidth, node->rectArea.height); } else // split horizontally { - node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, node->rectArea.width, blockHeight ); - node->child[1] = new Node( node, node->rectArea.x, node->rectArea.y+blockHeight, node->rectArea.width, node->rectArea.height-blockHeight ); + node->child[0] = new Node(node, node->rectArea.x, node->rectArea.y, node->rectArea.width, blockHeight); + node->child[1] = new Node(node, node->rectArea.x, node->rectArea.y + blockHeight, node->rectArea.width, node->rectArea.height - blockHeight); } } -AtlasPacker::Node* AtlasPacker::SearchNode( Node* node, SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight ) +AtlasPacker::Node* AtlasPacker::SearchNode(Node* node, SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight) { - if( node != NULL ) + if(node != NULL) { - if( node->child[0] != NULL) //not a leaf + if(node->child[0] != NULL) //not a leaf { Node* newNode = SearchNode(node->child[0], packPositionX, packPositionY, blockWidth, blockHeight); - if( newNode == NULL )// try search from the second child. + if(newNode == NULL) // try search from the second child. { newNode = SearchNode(node->child[1], packPositionX, packPositionY, blockWidth, blockHeight); } return newNode; } - else if( ApproximatelyEqual(node->rectArea.x, packPositionX) && ApproximatelyEqual(node->rectArea.y, packPositionY ) - && ApproximatelyEqual(node->rectArea.width, blockWidth) && ApproximatelyEqual( node->rectArea.height, blockHeight) ) + else if(ApproximatelyEqual(node->rectArea.x, packPositionX) && ApproximatelyEqual(node->rectArea.y, packPositionY) && ApproximatelyEqual(node->rectArea.width, blockWidth) && ApproximatelyEqual(node->rectArea.height, blockHeight)) { return node; } @@ -182,125 +176,123 @@ AtlasPacker::Node* AtlasPacker::SearchNode( Node* node, SizeType packPositionX, return NULL; } -void AtlasPacker::MergeToNonOccupied( Node* node ) +void AtlasPacker::MergeToNonOccupied(Node* node) { node->occupied = false; - Node* parent = node->parent; + Node* parent = node->parent; // both child are not occupied, merge the space to parent - if( parent != NULL && parent->child[0]->occupied == false && parent->child[1]->occupied == false) + if(parent != NULL && parent->child[0]->occupied == false && parent->child[1]->occupied == false) { delete parent->child[0]; parent->child[0] = NULL; delete parent->child[1]; parent->child[1] = NULL; - MergeToNonOccupied( parent ); + MergeToNonOccupied(parent); } } -void AtlasPacker::DeleteNode( Node *node ) +void AtlasPacker::DeleteNode(Node* node) { - if( node != NULL ) + if(node != NULL) { - DeleteNode( node->child[0] ); - DeleteNode( node->child[1] ); + DeleteNode(node->child[0]); + DeleteNode(node->child[1]); delete node; } } -Uint16Pair AtlasPacker::GroupPack( const Dali::Vector& blockSizes, Dali::Vector& packPositions ) +Uint16Pair AtlasPacker::GroupPack(const Dali::Vector& blockSizes, Dali::Vector& packPositions) { uint16_t count = blockSizes.Count(); - packPositions.Resize( count ); + packPositions.Resize(count); // Sort the blocks according to its maximum dimension. The bigger blocks are packed first. Dali::Vector packOrder; - packOrder.Resize( count ); - for( uint16_t i = 0; i < count; i++ ) + packOrder.Resize(count); + for(uint16_t i = 0; i < count; i++) { - packOrder[i].SetX( MaxDimension( blockSizes[i] ) ); - packOrder[i].SetY( i ); + packOrder[i].SetX(MaxDimension(blockSizes[i])); + packOrder[i].SetY(i); } - for( uint16_t i = 0; i < count-1; i++ ) - for( uint16_t j = 0; j < count-i-1; j++ ) + for(uint16_t i = 0; i < count - 1; i++) + for(uint16_t j = 0; j < count - i - 1; j++) { - if( packOrder[j].GetX() < packOrder[j+1].GetX() ) + if(packOrder[j].GetX() < packOrder[j + 1].GetX()) { - Swap( packOrder[j], packOrder[j+1] ); + Swap(packOrder[j], packOrder[j + 1]); } } - int index = packOrder[0].GetY(); - AtlasPacker packer( blockSizes[index].GetWidth(), blockSizes[index].GetHeight() ); + int index = packOrder[0].GetY(); + AtlasPacker packer(blockSizes[index].GetWidth(), blockSizes[index].GetHeight()); SizeType packPositionX, packPositionY; // pack the blocks one by one with descending size, grows as necessary to accommodate each subsequent block. - for( uint16_t i = 0; i < count; i++ ) + for(uint16_t i = 0; i < count; i++) { index = packOrder[i].GetY(); - packer.GrowPack( blockSizes[index].GetWidth(), blockSizes[index].GetHeight(), - packPositionX, packPositionY ); - packPositions[index].SetX( packPositionX ); - packPositions[index].SetY( packPositionY ); + packer.GrowPack(blockSizes[index].GetWidth(), blockSizes[index].GetHeight(), packPositionX, packPositionY); + packPositions[index].SetX(packPositionX); + packPositions[index].SetY(packPositionY); } - return Uint16Pair( packer.mRoot->rectArea.width, packer.mRoot->rectArea.height ); + return Uint16Pair(packer.mRoot->rectArea.width, packer.mRoot->rectArea.height); } -void AtlasPacker::GrowPack( SizeType blockWidth, SizeType blockHeight, - SizeType& packPositionX, SizeType& packPositionY ) +void AtlasPacker::GrowPack(SizeType blockWidth, SizeType blockHeight, SizeType& packPositionX, SizeType& packPositionY) { - Node* firstFit = InsertNode( mRoot, blockWidth, blockHeight ); - if( firstFit == NULL ) + Node* firstFit = InsertNode(mRoot, blockWidth, blockHeight); + if(firstFit == NULL) { // Could fit in the current left space, grow the partition tree to get more space. - GrowNode( blockWidth, blockHeight ); - firstFit = InsertNode( mRoot->child[1], blockWidth, blockHeight ); + GrowNode(blockWidth, blockHeight); + firstFit = InsertNode(mRoot->child[1], blockWidth, blockHeight); } - DALI_ASSERT_ALWAYS( firstFit != NULL && "It should never happen!") + DALI_ASSERT_ALWAYS(firstFit != NULL && "It should never happen!") firstFit->occupied = true; - packPositionX = firstFit->rectArea.x; - packPositionY = firstFit->rectArea.y; + packPositionX = firstFit->rectArea.x; + packPositionY = firstFit->rectArea.y; } -void AtlasPacker::GrowNode( SizeType blockWidth, SizeType blockHeight ) +void AtlasPacker::GrowNode(SizeType blockWidth, SizeType blockHeight) { // Attempts to maintain a roughly square ratio when choosing the growing direction: right or down bool canGrowRight = blockWidth <= mRoot->rectArea.width; - bool canGrowDown = blockHeight <= mRoot->rectArea.height; + bool canGrowDown = blockHeight <= mRoot->rectArea.height; - bool shouldGrowRight = canGrowRight && mRoot->rectArea.height >= mRoot->rectArea.width+blockWidth; - bool shouldGrowDown = canGrowDown && mRoot->rectArea.width >= mRoot->rectArea.height+blockHeight; + bool shouldGrowRight = canGrowRight && mRoot->rectArea.height >= mRoot->rectArea.width + blockWidth; + bool shouldGrowDown = canGrowDown && mRoot->rectArea.width >= mRoot->rectArea.height + blockHeight; - if( canGrowRight && canGrowDown ) + if(canGrowRight && canGrowDown) { - shouldGrowRight = mRoot->rectArea.width+blockWidth <= mRoot->rectArea.height+blockHeight; - shouldGrowDown = !shouldGrowRight; + shouldGrowRight = mRoot->rectArea.width + blockWidth <= mRoot->rectArea.height + blockHeight; + shouldGrowDown = !shouldGrowRight; } - if( shouldGrowRight || ( canGrowRight && !shouldGrowDown ) ) + if(shouldGrowRight || (canGrowRight && !shouldGrowDown)) { - Node* newRoot = new Node( NULL, 0u, 0u, mRoot->rectArea.width+blockWidth, mRoot->rectArea.height ); + Node* newRoot = new Node(NULL, 0u, 0u, mRoot->rectArea.width + blockWidth, mRoot->rectArea.height); newRoot->occupied = true; newRoot->child[0] = mRoot; - newRoot->child[1] = new Node( newRoot, mRoot->rectArea.width, 0u, blockWidth, mRoot->rectArea.height ); + newRoot->child[1] = new Node(newRoot, mRoot->rectArea.width, 0u, blockWidth, mRoot->rectArea.height); mRoot = newRoot; } - else if( shouldGrowDown || ( canGrowDown && !shouldGrowRight ) ) + else if(shouldGrowDown || (canGrowDown && !shouldGrowRight)) { - Node* newRoot = new Node( NULL, 0u, 0u, mRoot->rectArea.width, mRoot->rectArea.height+blockHeight ); + Node* newRoot = new Node(NULL, 0u, 0u, mRoot->rectArea.width, mRoot->rectArea.height + blockHeight); newRoot->occupied = true; newRoot->child[0] = mRoot; - newRoot->child[1] = new Node( newRoot, 0u, mRoot->rectArea.height, mRoot->rectArea.width, blockHeight ); + newRoot->child[1] = new Node(newRoot, 0u, mRoot->rectArea.height, mRoot->rectArea.width, blockHeight); mRoot = newRoot; } else { - DALI_LOG_ERROR( " Atlas Packer failed to grow: make sure the packing order is sorted with the block size to avoid this happening"); + DALI_LOG_ERROR(" Atlas Packer failed to grow: make sure the packing order is sorted with the block size to avoid this happening"); } } diff --git a/dali-toolkit/internal/image-loader/image-atlas-impl.cpp b/dali-toolkit/internal/image-loader/image-atlas-impl.cpp index d167499..8c4dba6 100644 --- a/dali-toolkit/internal/image-loader/image-atlas-impl.cpp +++ b/dali-toolkit/internal/image-loader/image-atlas-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,97 +19,93 @@ #include "image-atlas-impl.h" // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { typedef unsigned char PixelBuffer; -Texture ImageAtlas::PackToAtlas( const std::vector& pixelData, Dali::Vector& textureRects ) +Texture ImageAtlas::PackToAtlas(const std::vector& pixelData, Dali::Vector& textureRects) { // Record each block size Dali::Vector blockSizes; - SizeType count = pixelData.size(); - for( SizeType index = 0; index < count; index++ ) + SizeType count = pixelData.size(); + for(SizeType index = 0; index < count; index++) { - blockSizes.PushBack( ImageDimensions( pixelData[index].GetWidth(), pixelData[index].GetHeight() ) ); + blockSizes.PushBack(ImageDimensions(pixelData[index].GetWidth(), pixelData[index].GetHeight())); } // Ask atlasPacker for packing position of each block Dali::Vector packPositions; - ImageDimensions atlasSize = AtlasPacker::GroupPack( blockSizes, packPositions ); + ImageDimensions atlasSize = AtlasPacker::GroupPack(blockSizes, packPositions); // Prepare for outout texture rect array textureRects.Clear(); - textureRects.Resize( count ); + textureRects.Resize(count); // create the texture for uploading the multiple pixel data - Texture atlasTexture = Texture::New( Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, atlasSize.GetWidth(), atlasSize.GetHeight() ); + Texture atlasTexture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, atlasSize.GetWidth(), atlasSize.GetHeight()); - float atlasWidth = static_cast( atlasTexture.GetWidth() ); - float atlasHeight = static_cast( atlasTexture.GetHeight() ); - int packPositionX, packPositionY; + float atlasWidth = static_cast(atlasTexture.GetWidth()); + float atlasHeight = static_cast(atlasTexture.GetHeight()); + int packPositionX, packPositionY; // Upload the pixel data one by one to its packing position, and record the texture rects - for( SizeType index = 0; index < count; index++ ) + for(SizeType index = 0; index < count; index++) { packPositionX = packPositions[index].GetX(); packPositionY = packPositions[index].GetY(); - atlasTexture.Upload( pixelData[index], 0u, 0u, - packPositionX, packPositionY, - pixelData[index].GetWidth(), pixelData[index].GetHeight() ); + atlasTexture.Upload(pixelData[index], 0u, 0u, packPositionX, packPositionY, pixelData[index].GetWidth(), pixelData[index].GetHeight()); // Apply the half pixel correction to avoid the color bleeding between neighbour blocks - textureRects[index].x = ( static_cast( packPositionX ) +0.5f ) / atlasWidth; // left - textureRects[index].y = ( static_cast( packPositionY ) +0.5f ) / atlasHeight; // right - textureRects[index].z = ( static_cast( packPositionX + pixelData[index].GetWidth() )-0.5f ) / atlasWidth; // right - textureRects[index].w = ( static_cast( packPositionY + pixelData[index].GetHeight() )-0.5f ) / atlasHeight;// bottom + textureRects[index].x = (static_cast(packPositionX) + 0.5f) / atlasWidth; // left + textureRects[index].y = (static_cast(packPositionY) + 0.5f) / atlasHeight; // right + textureRects[index].z = (static_cast(packPositionX + pixelData[index].GetWidth()) - 0.5f) / atlasWidth; // right + textureRects[index].w = (static_cast(packPositionY + pixelData[index].GetHeight()) - 0.5f) / atlasHeight; // bottom } return atlasTexture; } -ImageAtlas::ImageAtlas( SizeType width, SizeType height, Pixel::Format pixelFormat ) -: mAtlas( Texture::New( Dali::TextureType::TEXTURE_2D, pixelFormat, width, height ) ), - mPacker( width, height ), - mAsyncLoader( Toolkit::AsyncImageLoader::New() ), +ImageAtlas::ImageAtlas(SizeType width, SizeType height, Pixel::Format pixelFormat) +: mAtlas(Texture::New(Dali::TextureType::TEXTURE_2D, pixelFormat, width, height)), + mPacker(width, height), + mAsyncLoader(Toolkit::AsyncImageLoader::New()), mBrokenImageUrl(""), mBrokenImageSize(), - mWidth( static_cast(width) ), - mHeight( static_cast( height ) ), - mPixelFormat( pixelFormat ) + mWidth(static_cast(width)), + mHeight(static_cast(height)), + mPixelFormat(pixelFormat) { - mAsyncLoader.ImageLoadedSignal().Connect( this, &ImageAtlas::UploadToAtlas ); + mAsyncLoader.ImageLoadedSignal().Connect(this, &ImageAtlas::UploadToAtlas); } ImageAtlas::~ImageAtlas() { const std::size_t count = mLoadingTaskInfoContainer.Count(); - for( std::size_t i=0; i < count; ++i ) + for(std::size_t i = 0; i < count; ++i) { // Call unregister to every observer in the list. // Note that, the Atlas can be registered to same observer multiple times, and the Unregister method only remove one item each time. // In this way, the atlas is actually detached from a observer either every upload call invoked by this observer is completed or atlas is destroyed. - if( mLoadingTaskInfoContainer[i]->observer ) + if(mLoadingTaskInfoContainer[i]->observer) { - mLoadingTaskInfoContainer[i]->observer->Unregister( *this ); + mLoadingTaskInfoContainer[i]->observer->Unregister(*this); } } mLoadingTaskInfoContainer.Clear(); } -IntrusivePtr ImageAtlas::New( SizeType width, SizeType height, Pixel::Format pixelFormat ) +IntrusivePtr ImageAtlas::New(SizeType width, SizeType height, Pixel::Format pixelFormat) { - IntrusivePtr internal = new ImageAtlas( width, height, pixelFormat ); + IntrusivePtr internal = new ImageAtlas(width, height, pixelFormat); return internal; } @@ -121,35 +117,35 @@ Texture ImageAtlas::GetAtlas() float ImageAtlas::GetOccupancyRate() const { - return 1.f - static_cast( mPacker.GetAvailableArea() ) / ( mWidth*mHeight ); + return 1.f - static_cast(mPacker.GetAvailableArea()) / (mWidth * mHeight); } -void ImageAtlas::SetBrokenImage( const std::string& brokenImageUrl ) +void ImageAtlas::SetBrokenImage(const std::string& brokenImageUrl) { - mBrokenImageSize = Dali::GetClosestImageSize( brokenImageUrl ); - if(mBrokenImageSize.GetWidth() > 0 && mBrokenImageSize.GetHeight() > 0 ) // check the url is valid + mBrokenImageSize = Dali::GetClosestImageSize(brokenImageUrl); + if(mBrokenImageSize.GetWidth() > 0 && mBrokenImageSize.GetHeight() > 0) // check the url is valid { mBrokenImageUrl = brokenImageUrl; } } -bool ImageAtlas::Upload( Vector4& textureRect, - const std::string& url, - ImageDimensions size, - FittingMode::Type fittingMode, - bool orientationCorrection, - AtlasUploadObserver* atlasUploadObserver ) +bool ImageAtlas::Upload(Vector4& textureRect, + const std::string& url, + ImageDimensions size, + FittingMode::Type fittingMode, + bool orientationCorrection, + AtlasUploadObserver* atlasUploadObserver) { ImageDimensions dimensions = size; ImageDimensions zero; - if( size == zero ) // image size not provided + if(size == zero) // image size not provided { - dimensions = Dali::GetClosestImageSize( url ); - if( dimensions == zero ) // Fail to read the image & broken image file exists + dimensions = Dali::GetClosestImageSize(url); + if(dimensions == zero) // Fail to read the image & broken image file exists { - if( !mBrokenImageUrl.empty() ) + if(!mBrokenImageUrl.empty()) { - return Upload( textureRect, mBrokenImageUrl, mBrokenImageSize, FittingMode::DEFAULT, true, atlasUploadObserver ); + return Upload(textureRect, mBrokenImageUrl, mBrokenImageSize, FittingMode::DEFAULT, true, atlasUploadObserver); } else { @@ -161,21 +157,21 @@ bool ImageAtlas::Upload( Vector4& textureRect, unsigned int packPositionX = 0; unsigned int packPositionY = 0; - if( mPacker.Pack( dimensions.GetWidth(), dimensions.GetHeight(), packPositionX, packPositionY ) ) + if(mPacker.Pack(dimensions.GetWidth(), dimensions.GetHeight(), packPositionX, packPositionY)) { - unsigned short loadId = mAsyncLoader.Load( url, size, fittingMode, SamplingMode::BOX_THEN_LINEAR, orientationCorrection); - mLoadingTaskInfoContainer.PushBack( new LoadingTaskInfo( loadId, packPositionX, packPositionY, dimensions.GetWidth(), dimensions.GetHeight(), atlasUploadObserver ) ); + unsigned short loadId = mAsyncLoader.Load(url, size, fittingMode, SamplingMode::BOX_THEN_LINEAR, orientationCorrection); + mLoadingTaskInfoContainer.PushBack(new LoadingTaskInfo(loadId, packPositionX, packPositionY, dimensions.GetWidth(), dimensions.GetHeight(), atlasUploadObserver)); // apply the half pixel correction - textureRect.x = ( static_cast( packPositionX ) +0.5f ) / mWidth; // left - textureRect.y = ( static_cast( packPositionY ) +0.5f ) / mHeight; // right - textureRect.z = ( static_cast( packPositionX + dimensions.GetX() )-0.5f ) / mWidth; // right - textureRect.w = ( static_cast( packPositionY + dimensions.GetY() )-0.5f ) / mHeight;// bottom + textureRect.x = (static_cast(packPositionX) + 0.5f) / mWidth; // left + textureRect.y = (static_cast(packPositionY) + 0.5f) / mHeight; // right + textureRect.z = (static_cast(packPositionX + dimensions.GetX()) - 0.5f) / mWidth; // right + textureRect.w = (static_cast(packPositionY + dimensions.GetY()) - 0.5f) / mHeight; // bottom - if( atlasUploadObserver ) + if(atlasUploadObserver) { // register to the observer, // Not that a matching unregister call should be invoked in UploadToAtlas if the observer is still alive by then. - atlasUploadObserver->Register( *this ); + atlasUploadObserver->Register(*this); } return true; @@ -184,19 +180,19 @@ bool ImageAtlas::Upload( Vector4& textureRect, return false; } -bool ImageAtlas::Upload( Vector4& textureRect, PixelData pixelData ) +bool ImageAtlas::Upload(Vector4& textureRect, PixelData pixelData) { unsigned int packPositionX = 0; unsigned int packPositionY = 0; - if( mPacker.Pack( pixelData.GetWidth(), pixelData.GetHeight(), packPositionX, packPositionY ) ) + if(mPacker.Pack(pixelData.GetWidth(), pixelData.GetHeight(), packPositionX, packPositionY)) { - mAtlas.Upload( pixelData, 0u, 0u, packPositionX, packPositionY, pixelData.GetWidth(), pixelData.GetHeight() ); + mAtlas.Upload(pixelData, 0u, 0u, packPositionX, packPositionY, pixelData.GetWidth(), pixelData.GetHeight()); // apply the half pixel correction - textureRect.x = ( static_cast( packPositionX ) +0.5f ) / mWidth; // left - textureRect.y = ( static_cast( packPositionY ) +0.5f ) / mHeight; // right - textureRect.z = ( static_cast( packPositionX + pixelData.GetWidth() )-0.5f ) / mWidth; // right - textureRect.w = ( static_cast( packPositionY + pixelData.GetHeight() )-0.5f ) / mHeight;// bottom + textureRect.x = (static_cast(packPositionX) + 0.5f) / mWidth; // left + textureRect.y = (static_cast(packPositionY) + 0.5f) / mHeight; // right + textureRect.z = (static_cast(packPositionX + pixelData.GetWidth()) - 0.5f) / mWidth; // right + textureRect.w = (static_cast(packPositionY + pixelData.GetHeight()) - 0.5f) / mHeight; // bottom return true; } @@ -204,20 +200,20 @@ bool ImageAtlas::Upload( Vector4& textureRect, PixelData pixelData ) return false; } -void ImageAtlas::Remove( const Vector4& textureRect ) +void ImageAtlas::Remove(const Vector4& textureRect) { - mPacker.DeleteBlock( static_cast(textureRect.x*mWidth), - static_cast(textureRect.y*mHeight), - static_cast((textureRect.z-textureRect.x)*mWidth+1.f), - static_cast((textureRect.w-textureRect.y)*mHeight+1.f) ); + mPacker.DeleteBlock(static_cast(textureRect.x * mWidth), + static_cast(textureRect.y * mHeight), + static_cast((textureRect.z - textureRect.x) * mWidth + 1.f), + static_cast((textureRect.w - textureRect.y) * mHeight + 1.f)); } -void ImageAtlas::ObserverDestroyed( AtlasUploadObserver* observer ) +void ImageAtlas::ObserverDestroyed(AtlasUploadObserver* observer) { const std::size_t count = mLoadingTaskInfoContainer.Count(); - for( std::size_t i=0; i < count; ++i ) + for(std::size_t i = 0; i < count; ++i) { - if( mLoadingTaskInfoContainer[i]->observer == observer ) + if(mLoadingTaskInfoContainer[i]->observer == observer) { // the observer is destructing, so its member function should not be called anymore mLoadingTaskInfoContainer[i]->observer = NULL; @@ -225,76 +221,78 @@ void ImageAtlas::ObserverDestroyed( AtlasUploadObserver* observer ) } } -void ImageAtlas::UploadToAtlas( uint32_t id, PixelData pixelData ) +void ImageAtlas::UploadToAtlas(uint32_t id, PixelData pixelData) { - if( mLoadingTaskInfoContainer[0]->loadTaskId == id) + if(mLoadingTaskInfoContainer[0]->loadTaskId == id) { - Rect packRect( mLoadingTaskInfoContainer[0]->packRect ); - if( !pixelData || ( pixelData.GetWidth() ==0 && pixelData.GetHeight() == 0 )) + Rect packRect(mLoadingTaskInfoContainer[0]->packRect); + if(!pixelData || (pixelData.GetWidth() == 0 && pixelData.GetHeight() == 0)) { if(!mBrokenImageUrl.empty()) // replace with the broken image { - UploadBrokenImage( packRect ); + UploadBrokenImage(packRect); } } else { - if( pixelData.GetWidth() < packRect.width || pixelData.GetHeight() < packRect.height ) + if(pixelData.GetWidth() < packRect.width || pixelData.GetHeight() < packRect.height) { - DALI_LOG_ERROR( "Can not upscale the image from actual loaded size [ %d, %d ] to specified size [ %d, %d ]\n", - pixelData.GetWidth(), pixelData.GetHeight(), - packRect.width, packRect.height ); + DALI_LOG_ERROR("Can not upscale the image from actual loaded size [ %d, %d ] to specified size [ %d, %d ]\n", + pixelData.GetWidth(), + pixelData.GetHeight(), + packRect.width, + packRect.height); } - mAtlas.Upload( pixelData, 0u, 0u, packRect.x, packRect.y, packRect.width, packRect.height ); + mAtlas.Upload(pixelData, 0u, 0u, packRect.x, packRect.y, packRect.width, packRect.height); } - if( mLoadingTaskInfoContainer[0]->observer ) + if(mLoadingTaskInfoContainer[0]->observer) { mLoadingTaskInfoContainer[0]->observer->UploadCompleted(); - mLoadingTaskInfoContainer[0]->observer->Unregister( *this ); + mLoadingTaskInfoContainer[0]->observer->Unregister(*this); } - mLoadingTaskInfoContainer.Erase( mLoadingTaskInfoContainer.Begin() ); + mLoadingTaskInfoContainer.Erase(mLoadingTaskInfoContainer.Begin()); } } -void ImageAtlas::UploadBrokenImage( const Rect& area ) +void ImageAtlas::UploadBrokenImage(const Rect& area) { - Devel::PixelBuffer brokenBuffer = LoadImageFromFile( mBrokenImageUrl, ImageDimensions( area.width, area.height ) ); - SizeType loadedWidth = brokenBuffer.GetWidth(); - SizeType loadedHeight = brokenBuffer.GetHeight(); + Devel::PixelBuffer brokenBuffer = LoadImageFromFile(mBrokenImageUrl, ImageDimensions(area.width, area.height)); + SizeType loadedWidth = brokenBuffer.GetWidth(); + SizeType loadedHeight = brokenBuffer.GetHeight(); - bool needBackgroundClear = false; - SizeType packX = area.x; - SizeType packY = area.y; + bool needBackgroundClear = false; + SizeType packX = area.x; + SizeType packY = area.y; // locate the broken image in the middle. - if( area.width > loadedWidth) + if(area.width > loadedWidth) { - packX += (area.width - loadedWidth)/2; + packX += (area.width - loadedWidth) / 2; needBackgroundClear = true; } - if( area.height > loadedHeight) + if(area.height > loadedHeight) { - packY += (area.height - loadedHeight)/2; + packY += (area.height - loadedHeight) / 2; needBackgroundClear = true; } - if( needBackgroundClear ) + if(needBackgroundClear) { - SizeType size = area.width * area.height * Pixel::GetBytesPerPixel( mPixelFormat ); - Devel::PixelBuffer background = Devel::PixelBuffer::New( area.width, area.height, mPixelFormat ); - unsigned char* buffer = background.GetBuffer(); - for( SizeType idx = 0; idx < size; idx++ ) + SizeType size = area.width * area.height * Pixel::GetBytesPerPixel(mPixelFormat); + Devel::PixelBuffer background = Devel::PixelBuffer::New(area.width, area.height, mPixelFormat); + unsigned char* buffer = background.GetBuffer(); + for(SizeType idx = 0; idx < size; idx++) { buffer[idx] = 0x00; } - PixelData pixelData = Devel::PixelBuffer::Convert( background ); - mAtlas.Upload( pixelData, 0u, 0u, area.x, area.y, area.width, area.height ); + PixelData pixelData = Devel::PixelBuffer::Convert(background); + mAtlas.Upload(pixelData, 0u, 0u, area.x, area.y, area.width, area.height); } - PixelData brokenPixelData = Devel::PixelBuffer::Convert( brokenBuffer ); - mAtlas.Upload( brokenPixelData, 0u, 0u, packX, packY, loadedWidth, loadedHeight ); + PixelData brokenPixelData = Devel::PixelBuffer::Convert(brokenBuffer); + mAtlas.Upload(brokenPixelData, 0u, 0u, packX, packY, loadedWidth, loadedHeight); } } // namespace Internal diff --git a/dali-toolkit/internal/image-loader/image-load-thread.cpp b/dali-toolkit/internal/image-loader/image-load-thread.cpp index 9b68176..7fc344f 100644 --- a/dali-toolkit/internal/image-loader/image-load-thread.cpp +++ b/dali-toolkit/internal/image-loader/image-load-thread.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,128 +26,123 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - -LoadingTask::LoadingTask( uint32_t id, Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex ) +LoadingTask::LoadingTask(uint32_t id, Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex) : pixelBuffer(), url(), - id( id ), + id(id), dimensions(), fittingMode(), samplingMode(), orientationCorrection(), - preMultiplyOnLoad( DevelAsyncImageLoader::PreMultiplyOnLoad::OFF ), - isMaskTask( false ), + preMultiplyOnLoad(DevelAsyncImageLoader::PreMultiplyOnLoad::OFF), + isMaskTask(false), maskPixelBuffer(), - contentScale( 1.0f ), - cropToMask( false ), - animatedImageLoading( animatedImageLoading ), - frameIndex( frameIndex ) + contentScale(1.0f), + cropToMask(false), + animatedImageLoading(animatedImageLoading), + frameIndex(frameIndex) { } -LoadingTask::LoadingTask( uint32_t id, const VisualUrl& url, ImageDimensions dimensions, - FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection, DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad ) +LoadingTask::LoadingTask(uint32_t id, const VisualUrl& url, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode, bool orientationCorrection, DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) : pixelBuffer(), - url( url ), - id( id ), - dimensions( dimensions ), - fittingMode( fittingMode ), - samplingMode( samplingMode ), - orientationCorrection( orientationCorrection ), - preMultiplyOnLoad( preMultiplyOnLoad ), - isMaskTask( false ), + url(url), + id(id), + dimensions(dimensions), + fittingMode(fittingMode), + samplingMode(samplingMode), + orientationCorrection(orientationCorrection), + preMultiplyOnLoad(preMultiplyOnLoad), + isMaskTask(false), maskPixelBuffer(), - contentScale( 1.0f ), - cropToMask( false ), + contentScale(1.0f), + cropToMask(false), animatedImageLoading(), - frameIndex( 0u ) + frameIndex(0u) { } -LoadingTask::LoadingTask( uint32_t id, Devel::PixelBuffer pixelBuffer, Devel::PixelBuffer maskPixelBuffer, float contentScale, bool cropToMask, - DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad ) -: pixelBuffer( pixelBuffer ), - url( "" ), - id( id ), +LoadingTask::LoadingTask(uint32_t id, Devel::PixelBuffer pixelBuffer, Devel::PixelBuffer maskPixelBuffer, float contentScale, bool cropToMask, DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) +: pixelBuffer(pixelBuffer), + url(""), + id(id), dimensions(), fittingMode(), samplingMode(), orientationCorrection(), - preMultiplyOnLoad( preMultiplyOnLoad ), - isMaskTask( true ), - maskPixelBuffer( maskPixelBuffer ), - contentScale( contentScale ), - cropToMask( cropToMask ), + preMultiplyOnLoad(preMultiplyOnLoad), + isMaskTask(true), + maskPixelBuffer(maskPixelBuffer), + contentScale(contentScale), + cropToMask(cropToMask), animatedImageLoading(), - frameIndex( 0u ) + frameIndex(0u) { } void LoadingTask::Load() { - if( animatedImageLoading ) + if(animatedImageLoading) { - pixelBuffer = animatedImageLoading.LoadFrame( frameIndex ); + pixelBuffer = animatedImageLoading.LoadFrame(frameIndex); } - else if( url.IsLocalResource() ) + else if(url.IsLocalResource()) { - pixelBuffer = Dali::LoadImageFromFile( url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection ); + pixelBuffer = Dali::LoadImageFromFile(url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection); } else { - pixelBuffer = Dali::DownloadImageSynchronously ( url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection ); + pixelBuffer = Dali::DownloadImageSynchronously(url.GetUrl(), dimensions, fittingMode, samplingMode, orientationCorrection); } - if( !pixelBuffer ) + if(!pixelBuffer) { - DALI_LOG_ERROR( "LoadingTask::Load: Loading is failed: %s\n", url.GetUrl().c_str() ); + DALI_LOG_ERROR("LoadingTask::Load: Loading is failed: %s\n", url.GetUrl().c_str()); } } void LoadingTask::ApplyMask() { - pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask ); + pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask); } void LoadingTask::MultiplyAlpha() { - if( pixelBuffer && Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) ) + if(pixelBuffer && Pixel::HasAlpha(pixelBuffer.GetPixelFormat())) { - if( preMultiplyOnLoad == DevelAsyncImageLoader::PreMultiplyOnLoad::ON ) + if(preMultiplyOnLoad == DevelAsyncImageLoader::PreMultiplyOnLoad::ON) { pixelBuffer.MultiplyColorByAlpha(); } } } -ImageLoadThread::ImageLoadThread( EventThreadCallback* trigger ) -: mTrigger( trigger ), - mLogFactory( Dali::Adaptor::Get().GetLogFactory() ) +ImageLoadThread::ImageLoadThread(EventThreadCallback* trigger) +: mTrigger(trigger), + mLogFactory(Dali::Adaptor::Get().GetLogFactory()) { } ImageLoadThread::~ImageLoadThread() { // add an empty task would stop the thread from conditional wait. - AddTask( NULL ); + AddTask(NULL); // stop the thread Join(); delete mTrigger; - for( auto&& iter : mLoadQueue ) + for(auto&& iter : mLoadQueue) { delete iter; } mLoadQueue.Clear(); - for( auto&& iter : mCompleteQueue ) + for(auto&& iter : mCompleteQueue) { delete iter; } @@ -156,12 +151,12 @@ ImageLoadThread::~ImageLoadThread() void ImageLoadThread::Run() { - SetThreadName( "ImageLoadThread" ); + SetThreadName("ImageLoadThread"); mLogFactory.InstallLogFunction(); - while( LoadingTask* task = NextTaskToProcess() ) + while(LoadingTask* task = NextTaskToProcess()) { - if( !task->isMaskTask ) + if(!task->isMaskTask) { task->Load(); } @@ -171,21 +166,21 @@ void ImageLoadThread::Run() } task->MultiplyAlpha(); - AddCompletedTask( task ); + AddCompletedTask(task); } } -void ImageLoadThread::AddTask( LoadingTask* task ) +void ImageLoadThread::AddTask(LoadingTask* task) { bool wasEmpty = false; { // Lock while adding task to the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); wasEmpty = mLoadQueue.Empty(); - mLoadQueue.PushBack( task ); + mLoadQueue.PushBack(task); } - if( wasEmpty ) + if(wasEmpty) { // wake up the image loading thread mConditionalWait.Notify(); @@ -195,31 +190,31 @@ void ImageLoadThread::AddTask( LoadingTask* task ) LoadingTask* ImageLoadThread::NextCompletedTask() { // Lock while popping task out from the queue - Mutex::ScopedLock lock( mMutex ); + Mutex::ScopedLock lock(mMutex); - if( mCompleteQueue.Empty() ) + if(mCompleteQueue.Empty()) { return NULL; } - Vector< LoadingTask* >::Iterator next = mCompleteQueue.Begin(); - LoadingTask* nextTask = *next; - mCompleteQueue.Erase( next ); + Vector::Iterator next = mCompleteQueue.Begin(); + LoadingTask* nextTask = *next; + mCompleteQueue.Erase(next); return nextTask; } -bool ImageLoadThread::CancelTask( uint32_t loadingTaskId ) +bool ImageLoadThread::CancelTask(uint32_t loadingTaskId) { // Lock while remove task from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - for( Vector< LoadingTask* >::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter ) + for(Vector::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter) { - if( (*iter)->id == loadingTaskId ) + if((*iter)->id == loadingTaskId) { - delete (*iter); - mLoadQueue.Erase( iter ); + delete(*iter); + mLoadQueue.Erase(iter); return true; } } @@ -227,15 +222,14 @@ bool ImageLoadThread::CancelTask( uint32_t loadingTaskId ) return false; } - void ImageLoadThread::CancelAll() { // Lock while remove task from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - for( Vector< LoadingTask* >::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter ) + for(Vector::Iterator iter = mLoadQueue.Begin(); iter != mLoadQueue.End(); ++iter) { - delete ( *iter ); + delete(*iter); } mLoadQueue.Clear(); } @@ -243,25 +237,25 @@ void ImageLoadThread::CancelAll() LoadingTask* ImageLoadThread::NextTaskToProcess() { // Lock while popping task out from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - while( mLoadQueue.Empty() ) + while(mLoadQueue.Empty()) { - mConditionalWait.Wait( lock ); + mConditionalWait.Wait(lock); } - Vector< LoadingTask* >::Iterator next = mLoadQueue.Begin(); - LoadingTask* nextTask = *next; - mLoadQueue.Erase( next ); + Vector::Iterator next = mLoadQueue.Begin(); + LoadingTask* nextTask = *next; + mLoadQueue.Erase(next); return nextTask; } -void ImageLoadThread::AddCompletedTask( LoadingTask* task ) +void ImageLoadThread::AddCompletedTask(LoadingTask* task) { // Lock while adding task to the queue - Mutex::ScopedLock lock( mMutex ); - mCompleteQueue.PushBack( task ); + Mutex::ScopedLock lock(mMutex); + mCompleteQueue.PushBack(task); // wake up the main thread mTrigger->Trigger(); diff --git a/dali-toolkit/internal/styling/style-manager-impl.cpp b/dali-toolkit/internal/styling/style-manager-impl.cpp index a5a02dd..0968081 100644 --- a/dali-toolkit/internal/styling/style-manager-impl.cpp +++ b/dali-toolkit/internal/styling/style-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. @@ -19,62 +19,57 @@ // EXTERNAL INCLUDES #include -#include -#include #include #include +#include +#include // INTERNAL INCLUDES #include #include -#include +#include #include +#include #include -#include namespace { - //const char* LANDSCAPE_QUALIFIER = "landscape"; const char* PORTRAIT_QUALIFIER = "portrait"; const char* FONT_SIZE_QUALIFIER = "fontsize"; const char* DEFAULT_THEME_FILE_NAME = "dali-toolkit-default-theme.json"; -const char* PACKAGE_PATH_KEY = "PACKAGE_PATH"; +const char* PACKAGE_PATH_KEY = "PACKAGE_PATH"; const char* APPLICATION_RESOURCE_PATH_KEY = "APPLICATION_RESOURCE_PATH"; const char* DEFAULT_TOOLKIT_PACKAGE_PATH = "/toolkit/"; #if defined(DEBUG_ENABLED) -Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_STYLE"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_STYLE"); #endif } // namespace namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - BaseHandle Create() { BaseHandle handle = StyleManager::Get(); - if ( !handle ) + if(!handle) { - SingletonService singletonService( SingletonService::Get() ); - if ( singletonService ) + SingletonService singletonService(SingletonService::Get()); + if(singletonService) { - Toolkit::StyleManager manager = Toolkit::StyleManager( new Internal::StyleManager() ); - singletonService.Register( typeid( manager ), manager ); + Toolkit::StyleManager manager = Toolkit::StyleManager(new Internal::StyleManager()); + singletonService.Register(typeid(manager), manager); handle = manager; } } @@ -82,7 +77,7 @@ BaseHandle Create() return handle; } -DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::StyleManager, Dali::BaseHandle, Create, true ) +DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::StyleManager, Dali::BaseHandle, Create, true) DALI_TYPE_REGISTRATION_END() } // namespace @@ -91,15 +86,15 @@ Toolkit::StyleManager StyleManager::Get() { Toolkit::StyleManager manager; - SingletonService singletonService( SingletonService::Get() ); - if ( singletonService ) + SingletonService singletonService(SingletonService::Get()); + if(singletonService) { // Check whether the style manager is already created - Dali::BaseHandle handle = singletonService.GetSingleton( typeid( Toolkit::StyleManager ) ); - if( handle ) + Dali::BaseHandle handle = singletonService.GetSingleton(typeid(Toolkit::StyleManager)); + if(handle) { // If so, downcast the handle of singleton - manager = Toolkit::StyleManager( dynamic_cast< StyleManager* >( handle.GetObjectPtr() ) ); + manager = Toolkit::StyleManager(dynamic_cast(handle.GetObjectPtr())); } } @@ -107,26 +102,26 @@ Toolkit::StyleManager StyleManager::Get() } StyleManager::StyleManager() -: mDefaultFontSize( -1 ), +: mDefaultFontSize(-1), mDefaultFontFamily(""), mDefaultThemeFilePath(), - mFeedbackStyle( nullptr ) + mFeedbackStyle(nullptr) { // Add theme builder constants - const std::string dataReadOnlyDir = AssetManager::GetDaliDataReadOnlyPath(); - mThemeBuilderConstants[ PACKAGE_PATH_KEY ] = dataReadOnlyDir + DEFAULT_TOOLKIT_PACKAGE_PATH; - mThemeBuilderConstants[ APPLICATION_RESOURCE_PATH_KEY ] = Application::GetResourcePath(); + const std::string dataReadOnlyDir = AssetManager::GetDaliDataReadOnlyPath(); + mThemeBuilderConstants[PACKAGE_PATH_KEY] = dataReadOnlyDir + DEFAULT_TOOLKIT_PACKAGE_PATH; + mThemeBuilderConstants[APPLICATION_RESOURCE_PATH_KEY] = Application::GetResourcePath(); mStyleMonitor = StyleMonitor::Get(); - if( mStyleMonitor ) + if(mStyleMonitor) { - mStyleMonitor.StyleChangeSignal().Connect( this, &StyleManager::StyleMonitorChange ); + mStyleMonitor.StyleChangeSignal().Connect(this, &StyleManager::StyleMonitorChange); mDefaultFontSize = mStyleMonitor.GetDefaultFontSize(); } // Set the full path for the default style theme. const std::string styleDirPath = AssetManager::GetDaliStylePath(); - mDefaultThemeFilePath = styleDirPath + DEFAULT_THEME_FILE_NAME; + mDefaultThemeFilePath = styleDirPath + DEFAULT_THEME_FILE_NAME; // Sound & haptic style mFeedbackStyle = new FeedbackStyle(); @@ -137,9 +132,9 @@ StyleManager::~StyleManager() delete mFeedbackStyle; } -void StyleManager::ApplyTheme( const std::string& themeFile ) +void StyleManager::ApplyTheme(const std::string& themeFile) { - SetTheme( themeFile ); + SetTheme(themeFile); } void StyleManager::ApplyDefaultTheme() @@ -152,15 +147,15 @@ const std::string& StyleManager::GetDefaultFontFamily() const return mDefaultFontFamily; } -void StyleManager::SetStyleConstant( const std::string& key, const Property::Value& value ) +void StyleManager::SetStyleConstant(const std::string& key, const Property::Value& value) { - mStyleBuilderConstants[ key ] = value; + mStyleBuilderConstants[key] = value; } -bool StyleManager::GetStyleConstant( const std::string& key, Property::Value& valueOut ) +bool StyleManager::GetStyleConstant(const std::string& key, Property::Value& valueOut) { - Property::Value* value = mStyleBuilderConstants.Find( key ); - if( value ) + Property::Value* value = mStyleBuilderConstants.Find(key); + if(value) { valueOut = *value; return true; @@ -169,59 +164,59 @@ bool StyleManager::GetStyleConstant( const std::string& key, Property::Value& va return false; } -void StyleManager::ApplyThemeStyle( Toolkit::Control control ) +void StyleManager::ApplyThemeStyle(Toolkit::Control control) { - if( !mThemeBuilder ) + if(!mThemeBuilder) { ApplyDefaultTheme(); } - if( mThemeBuilder ) + if(mThemeBuilder) { - ApplyStyle( mThemeBuilder, control ); + ApplyStyle(mThemeBuilder, control); } } -void StyleManager::ApplyThemeStyleAtInit( Toolkit::Control control ) +void StyleManager::ApplyThemeStyleAtInit(Toolkit::Control control) { - ApplyThemeStyle( control ); + ApplyThemeStyle(control); if(mFeedbackStyle) { - mFeedbackStyle->ObjectCreated( control ); + mFeedbackStyle->ObjectCreated(control); } } -void StyleManager::ApplyStyle( Toolkit::Control control, const std::string& jsonFileName, const std::string& styleName ) +void StyleManager::ApplyStyle(Toolkit::Control control, const std::string& jsonFileName, const std::string& styleName) { bool builderReady = false; // First look in the cache - Toolkit::Builder builder = FindCachedBuilder( jsonFileName ); - if( builder ) + Toolkit::Builder builder = FindCachedBuilder(jsonFileName); + if(builder) { builderReady = true; } else { // Merge theme and style constants - Property::Map constants( mThemeBuilderConstants ); - constants.Merge( mStyleBuilderConstants ); + Property::Map constants(mThemeBuilderConstants); + constants.Merge(mStyleBuilderConstants); // Create it - builder = CreateBuilder( constants ); + builder = CreateBuilder(constants); - if( LoadJSON( builder, jsonFileName ) ) + if(LoadJSON(builder, jsonFileName)) { - CacheBuilder( builder, jsonFileName ); + CacheBuilder(builder, jsonFileName); builderReady = true; } } // Apply the style to the control - if( builderReady ) + if(builderReady) { - builder.ApplyStyle( styleName, control ); + builder.ApplyStyle(styleName, control); } } @@ -235,38 +230,38 @@ Toolkit::StyleManager::StyleChangedSignalType& StyleManager::ControlStyleChangeS return mControlStyleChangeSignal; } -void StyleManager::SetTheme( const std::string& themeFile ) +void StyleManager::SetTheme(const std::string& themeFile) { bool themeLoaded = false; - bool loading = false; + bool loading = false; // If we haven't loaded a theme, or the stored theme file is empty, or // the previously loaded theme is different to the requested theme, // first reset the builder and load the default theme. - if( ! mThemeBuilder || mThemeFile.empty() || mThemeFile.compare( themeFile ) != 0 ) + if(!mThemeBuilder || mThemeFile.empty() || mThemeFile.compare(themeFile) != 0) { - loading = true; - mThemeBuilder = CreateBuilder( mThemeBuilderConstants ); - themeLoaded = LoadJSON( mThemeBuilder, mDefaultThemeFilePath ); // Sets themeLoaded to true if theme exists + loading = true; + mThemeBuilder = CreateBuilder(mThemeBuilderConstants); + themeLoaded = LoadJSON(mThemeBuilder, mDefaultThemeFilePath); // Sets themeLoaded to true if theme exists } - if( themeFile.compare(mDefaultThemeFilePath) != 0 ) + if(themeFile.compare(mDefaultThemeFilePath) != 0) { // The theme is different to the default: Merge it loading = true; - themeLoaded |= LoadJSON( mThemeBuilder, themeFile ); + themeLoaded |= LoadJSON(mThemeBuilder, themeFile); } - if( loading ) + if(loading) { mThemeFile = themeFile; - if( themeLoaded ) + if(themeLoaded) { // We've successfully loaded the theme file if(mFeedbackStyle) { - mFeedbackStyle->StyleChanged( mThemeFile, StyleChange::THEME_CHANGE ); + mFeedbackStyle->StyleChanged(mThemeFile, StyleChange::THEME_CHANGE); } EmitStyleChangeSignals(StyleChange::THEME_CHANGE); @@ -282,66 +277,66 @@ void StyleManager::SetTheme( const std::string& themeFile ) const Property::Map StyleManager::GetConfigurations() { - DALI_LOG_STREAM( gLogFilter, Debug::Concise, "GetConfigurations()\n On entry, mThemeBuilder: " << (bool(mThemeBuilder)?"Created":"Empty") << " mThemeFile: " << mThemeFile); + DALI_LOG_STREAM(gLogFilter, Debug::Concise, "GetConfigurations()\n On entry, mThemeBuilder: " << (bool(mThemeBuilder) ? "Created" : "Empty") << " mThemeFile: " << mThemeFile); Property::Map result; - if( mThemeBuilder ) + if(mThemeBuilder) { result = mThemeBuilder.GetConfigurations(); } else { - DALI_LOG_STREAM( gLogFilter, Debug::Concise, "GetConfigurations() Loading default theme" ); + DALI_LOG_STREAM(gLogFilter, Debug::Concise, "GetConfigurations() Loading default theme"); bool themeLoaded = false; - mThemeBuilder = CreateBuilder( mThemeBuilderConstants ); + mThemeBuilder = CreateBuilder(mThemeBuilderConstants); // Load default theme because this is first try to load stylesheet. - themeLoaded = LoadJSON( mThemeBuilder, mDefaultThemeFilePath ); - mThemeFile = mDefaultThemeFilePath; + themeLoaded = LoadJSON(mThemeBuilder, mDefaultThemeFilePath); + mThemeFile = mDefaultThemeFilePath; - if( themeLoaded ) + if(themeLoaded) { result = mThemeBuilder.GetConfigurations(); } - DALI_LOG_STREAM( gLogFilter, Debug::Concise, " themeLoaded" << (themeLoaded?"success":"failure") ); + DALI_LOG_STREAM(gLogFilter, Debug::Concise, " themeLoaded" << (themeLoaded ? "success" : "failure")); } - DALI_LOG_STREAM( gLogFilter, Debug::Concise, "GetConfigurations()\n On exit, result Count: " << (result.Count() != 0) ); - DALI_LOG_STREAM( gLogFilter, Debug::Verbose, " result: " << result ); + DALI_LOG_STREAM(gLogFilter, Debug::Concise, "GetConfigurations()\n On exit, result Count: " << (result.Count() != 0)); + DALI_LOG_STREAM(gLogFilter, Debug::Verbose, " result: " << result); return result; } -bool StyleManager::LoadFile( const std::string& filename, std::string& stringOut ) +bool StyleManager::LoadFile(const std::string& filename, std::string& stringOut) { - DALI_ASSERT_DEBUG( 0 != filename.length()); + DALI_ASSERT_DEBUG(0 != filename.length()); // as toolkit is platform agnostic, it cannot load files from filesystem // ask style monitor to load the style sheet - if( mStyleMonitor ) + if(mStyleMonitor) { - return mStyleMonitor.LoadThemeFile( filename, stringOut ); + return mStyleMonitor.LoadThemeFile(filename, stringOut); } return false; } -Toolkit::Builder StyleManager::CreateBuilder( const Property::Map& constants ) +Toolkit::Builder StyleManager::CreateBuilder(const Property::Map& constants) { Toolkit::Builder builder = Toolkit::Builder::New(); - builder.AddConstants( constants ); + builder.AddConstants(constants); return builder; } -bool StyleManager::LoadJSON( Toolkit::Builder builder, const std::string& jsonFilePath ) +bool StyleManager::LoadJSON(Toolkit::Builder builder, const std::string& jsonFilePath) { std::string fileString; - if( LoadFile( jsonFilePath, fileString ) ) + if(LoadFile(jsonFilePath, fileString)) { - builder.LoadFromString( fileString ); + builder.LoadFromString(fileString); return true; } else @@ -351,7 +346,7 @@ bool StyleManager::LoadJSON( Toolkit::Builder builder, const std::string& jsonFi } } -static void CollectQualifiers( std::vector& qualifiersOut ) +static void CollectQualifiers(std::vector& qualifiersOut) { // Append the relevant qualifier for orientation // int orientation = 0; // Get the orientation from the system @@ -362,8 +357,7 @@ static void CollectQualifiers( std::vector& qualifiersOut ) orientation 90, 270 : LANDSCAPE_QUALIFIER */ - qualifiersOut.push_back( std::string( PORTRAIT_QUALIFIER ) ); - + qualifiersOut.push_back(std::string(PORTRAIT_QUALIFIER)); } /** @@ -376,55 +370,57 @@ static void CollectQualifiers( std::vector& qualifiersOut ) * @param[out] qualifiedStyleOut The qualified style name */ static void BuildQualifiedStyleName( - const std::string& styleName, + const std::string& styleName, const std::vector& qualifiers, - std::string& qualifiedStyleOut ) + std::string& qualifiedStyleOut) { - qualifiedStyleOut.append( styleName ); + qualifiedStyleOut.append(styleName); - for( std::vector::const_iterator it = qualifiers.begin(), - itEnd = qualifiers.end(); it != itEnd; ++it ) + for(std::vector::const_iterator it = qualifiers.begin(), + itEnd = qualifiers.end(); + it != itEnd; + ++it) { const std::string& str = *it; - qualifiedStyleOut.append( "-" ); - qualifiedStyleOut.append( str ); + qualifiedStyleOut.append("-"); + qualifiedStyleOut.append(str); } } -static bool GetStyleNameForControl( Toolkit::Builder builder, Toolkit::Control control, std::string& styleName) +static bool GetStyleNameForControl(Toolkit::Builder builder, Toolkit::Control control, std::string& styleName) { styleName = control.GetStyleName(); - if( styleName.empty() ) + if(styleName.empty()) { styleName = control.GetTypeName(); } // Apply the style after choosing the correct actual style (e.g. landscape or portrait) std::vector qualifiers; - CollectQualifiers( qualifiers ); + CollectQualifiers(qualifiers); - bool found = 0; + bool found = 0; std::string qualifiedStyleName; do { qualifiedStyleName.clear(); - BuildQualifiedStyleName( styleName, qualifiers, qualifiedStyleName ); + BuildQualifiedStyleName(styleName, qualifiers, qualifiedStyleName); // Break if style found or we have tried the root style name (qualifiers is empty) - if( GetImpl(builder).LookupStyleName( qualifiedStyleName ) ) + if(GetImpl(builder).LookupStyleName(qualifiedStyleName)) { found = true; break; } - if( qualifiers.size() == 0 ) + if(qualifiers.size() == 0) { break; } // Remove the last qualifier in an attempt to find a style that is valid qualifiers.pop_back(); - } while (!found); + } while(!found); if(found) { @@ -433,42 +429,42 @@ static bool GetStyleNameForControl( Toolkit::Builder builder, Toolkit::Control c return found; } -void StyleManager::ApplyStyle( Toolkit::Builder builder, Toolkit::Control control ) +void StyleManager::ApplyStyle(Toolkit::Builder builder, Toolkit::Control control) { std::string styleName = control.GetStyleName(); - if( GetStyleNameForControl( builder, control, styleName ) ) + if(GetStyleNameForControl(builder, control, styleName)) { - builder.ApplyStyle( styleName, control ); + builder.ApplyStyle(styleName, control); } - if( mDefaultFontSize >= 0 ) + if(mDefaultFontSize >= 0) { // Apply the style for logical font size std::stringstream fontSizeQualifier; fontSizeQualifier << styleName << FONT_SIZE_QUALIFIER << mDefaultFontSize; - builder.ApplyStyle( fontSizeQualifier.str(), control ); + builder.ApplyStyle(fontSizeQualifier.str(), control); } } -const StylePtr StyleManager::GetRecordedStyle( Toolkit::Control control ) +const StylePtr StyleManager::GetRecordedStyle(Toolkit::Control control) { - if( mThemeBuilder ) + if(mThemeBuilder) { std::string styleName = control.GetStyleName(); - if( GetStyleNameForControl( mThemeBuilder, control, styleName ) ) + if(GetStyleNameForControl(mThemeBuilder, control, styleName)) { - const StylePtr style = GetImpl(mThemeBuilder).GetStyle( styleName ); + const StylePtr style = GetImpl(mThemeBuilder).GetStyle(styleName); return style; } } return StylePtr(NULL); } -Toolkit::Builder StyleManager::FindCachedBuilder( const std::string& key ) +Toolkit::Builder StyleManager::FindCachedBuilder(const std::string& key) { - BuilderMap::iterator builderIt = mBuilderCache.find( key ); - if( builderIt != mBuilderCache.end() ) + BuilderMap::iterator builderIt = mBuilderCache.find(key); + if(builderIt != mBuilderCache.end()) { return builderIt->second; } @@ -476,14 +472,14 @@ Toolkit::Builder StyleManager::FindCachedBuilder( const std::string& key ) return Toolkit::Builder(); } -void StyleManager::CacheBuilder( Toolkit::Builder builder, const std::string& key ) +void StyleManager::CacheBuilder(Toolkit::Builder builder, const std::string& key) { - mBuilderCache[ key ] = builder; + mBuilderCache[key] = builder; } -void StyleManager::StyleMonitorChange( StyleMonitor styleMonitor, StyleChange::Type styleChange ) +void StyleManager::StyleMonitorChange(StyleMonitor styleMonitor, StyleChange::Type styleChange) { - switch ( styleChange ) + switch(styleChange) { case StyleChange::DEFAULT_FONT_CHANGE: { @@ -499,25 +495,24 @@ void StyleManager::StyleMonitorChange( StyleMonitor styleMonitor, StyleChange::T case StyleChange::THEME_CHANGE: { - SetTheme( styleMonitor.GetTheme() ); + SetTheme(styleMonitor.GetTheme()); break; } } - EmitStyleChangeSignals( styleChange ); + EmitStyleChangeSignals(styleChange); } -void StyleManager::EmitStyleChangeSignals( StyleChange::Type styleChange ) +void StyleManager::EmitStyleChangeSignals(StyleChange::Type styleChange) { Toolkit::StyleManager styleManager = StyleManager::Get(); // Update Controls first - mControlStyleChangeSignal.Emit( styleManager, styleChange ); + mControlStyleChangeSignal.Emit(styleManager, styleChange); // Inform application last - mStyleChangedSignal.Emit( styleManager, styleChange ); + mStyleChangedSignal.Emit(styleManager, styleChange); } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/text/bidirectional-support.cpp b/dali-toolkit/internal/text/bidirectional-support.cpp old mode 100755 new mode 100644 index 165ae0d..da8f961 --- a/dali-toolkit/internal/text/bidirectional-support.cpp +++ b/dali-toolkit/internal/text/bidirectional-support.cpp @@ -19,37 +19,34 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Text { - -void SetBidirectionalInfo( const Vector& text, - const Vector& scripts, - const Vector& lineBreakInfo, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& bidirectionalInfo, - bool matchSystemLanguageDirection, - Dali::LayoutDirection::Type layoutDirection ) +void SetBidirectionalInfo(const Vector& text, + const Vector& scripts, + const Vector& lineBreakInfo, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& bidirectionalInfo, + bool matchSystemLanguageDirection, + Dali::LayoutDirection::Type layoutDirection) { // Find where to insert the new paragraphs. BidirectionalRunIndex bidiInfoIndex = 0u; - for( Vector::ConstIterator it = bidirectionalInfo.Begin(), - endIt = bidirectionalInfo.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = bidirectionalInfo.Begin(), + endIt = bidirectionalInfo.End(); + it != endIt; + ++it) { const BidirectionalParagraphInfoRun& run = *it; - if( startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters ) + if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters) { // Found where to insert the bidi info. break; @@ -76,52 +73,52 @@ void SetBidirectionalInfo( const Vector& text, bool hasRightToLeftScript = false; - for( Vector::ConstIterator it = scripts.Begin(), - endIt = scripts.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = scripts.Begin(), + endIt = scripts.End(); + it != endIt; + ++it) { - const ScriptRun& scriptRun = *it; + const ScriptRun& scriptRun = *it; const CharacterIndex lastScriptRunIndex = scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters - 1u; - if( startIndex > lastScriptRunIndex ) + if(startIndex > lastScriptRunIndex) { // Skip the run as it has already been processed. continue; } - if( lastCharacter <= scriptRun.characterRun.characterIndex ) + if(lastCharacter <= scriptRun.characterRun.characterIndex) { // Do not get bidirectional info beyond startIndex + numberOfCharacters. break; } - if( !hasRightToLeftScript && scriptRun.isRightToLeft ) + if(!hasRightToLeftScript && scriptRun.isRightToLeft) { // The script is right to left. hasRightToLeftScript = true; } - if( TextAbstraction::LINE_MUST_BREAK == *( lineBreakInfoBuffer + lastScriptRunIndex ) ) + if(TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + lastScriptRunIndex)) { // A new paragraph has been found. - if( hasRightToLeftScript ) + if(hasRightToLeftScript) { // The Bidirectional run must have the same number of characters than the paragraph. BidirectionalParagraphInfoRun bidirectionalRun; - bidirectionalRun.characterRun.characterIndex = paragraphCharacterIndex; - bidirectionalRun.characterRun.numberOfCharacters = ( lastScriptRunIndex - paragraphCharacterIndex ) + 1u; // The must break character is part of the paragrah. + bidirectionalRun.characterRun.characterIndex = paragraphCharacterIndex; + bidirectionalRun.characterRun.numberOfCharacters = (lastScriptRunIndex - paragraphCharacterIndex) + 1u; // The must break character is part of the paragrah. // Create the bidirectional info for the whole paragraph and store the index to the table with this info in the run. - bidirectionalRun.bidirectionalInfoIndex = bidirectionalSupport.CreateInfo( textBuffer + bidirectionalRun.characterRun.characterIndex, - bidirectionalRun.characterRun.numberOfCharacters, - matchSystemLanguageDirection, - layoutDirection ); + bidirectionalRun.bidirectionalInfoIndex = bidirectionalSupport.CreateInfo(textBuffer + bidirectionalRun.characterRun.characterIndex, + bidirectionalRun.characterRun.numberOfCharacters, + matchSystemLanguageDirection, + layoutDirection); - bidirectionalRun.direction = bidirectionalSupport.GetParagraphDirection( bidirectionalRun.bidirectionalInfoIndex ); + bidirectionalRun.direction = bidirectionalSupport.GetParagraphDirection(bidirectionalRun.bidirectionalInfoIndex); - bidirectionalInfo.Insert( bidirectionalInfo.Begin() + bidiInfoIndex, bidirectionalRun ); + bidirectionalInfo.Insert(bidirectionalInfo.Begin() + bidiInfoIndex, bidirectionalRun); ++bidiInfoIndex; } @@ -134,10 +131,10 @@ void SetBidirectionalInfo( const Vector& text, } // Update indices of the bidi runs. - for( Vector::Iterator it = bidirectionalInfo.Begin() + bidiInfoIndex, - endIt = bidirectionalInfo.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = bidirectionalInfo.Begin() + bidiInfoIndex, + endIt = bidirectionalInfo.End(); + it != endIt; + ++it) { BidirectionalParagraphInfoRun& run = *it; @@ -145,40 +142,40 @@ void SetBidirectionalInfo( const Vector& text, } } -void ReorderLine( const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo, - Vector& lineInfoRuns, - BidirectionalLineRunIndex bidiLineIndex, - CharacterIndex startIndex, - Length numberOfCharacters, - CharacterDirection direction ) +void ReorderLine(const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo, + Vector& lineInfoRuns, + BidirectionalLineRunIndex bidiLineIndex, + CharacterIndex startIndex, + Length numberOfCharacters, + CharacterDirection direction) { // Handle to the bidirectional info module in text-abstraction. TextAbstraction::BidirectionalSupport bidirectionalSupport = TextAbstraction::BidirectionalSupport::Get(); // Creates a bidirectional info for the line run. BidirectionalLineInfoRun lineInfoRun; - lineInfoRun.characterRun.characterIndex = startIndex; + lineInfoRun.characterRun.characterIndex = startIndex; lineInfoRun.characterRun.numberOfCharacters = numberOfCharacters; - lineInfoRun.direction = direction; - lineInfoRun.isIdentity = true; + lineInfoRun.direction = direction; + lineInfoRun.isIdentity = true; // Allocate space for the conversion maps. // The memory is freed after the visual to logical to visual conversion tables are built in the logical model. - lineInfoRun.visualToLogicalMap = reinterpret_cast( malloc( numberOfCharacters * sizeof( CharacterIndex ) ) ); + lineInfoRun.visualToLogicalMap = reinterpret_cast(malloc(numberOfCharacters * sizeof(CharacterIndex))); - if( nullptr != lineInfoRun.visualToLogicalMap ) + if(nullptr != lineInfoRun.visualToLogicalMap) { // Reorders the line. - bidirectionalSupport.Reorder( bidirectionalParagraphInfo.bidirectionalInfoIndex, - lineInfoRun.characterRun.characterIndex - bidirectionalParagraphInfo.characterRun.characterIndex, - lineInfoRun.characterRun.numberOfCharacters, - lineInfoRun.visualToLogicalMap ); + bidirectionalSupport.Reorder(bidirectionalParagraphInfo.bidirectionalInfoIndex, + lineInfoRun.characterRun.characterIndex - bidirectionalParagraphInfo.characterRun.characterIndex, + lineInfoRun.characterRun.numberOfCharacters, + lineInfoRun.visualToLogicalMap); // For those LTR lines inside a bidirectional paragraph. // It will save to relayout the line after reordering. - for( unsigned int i=0; i& text, - const Vector& directions, - const Vector& bidirectionalInfo, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& mirroredText ) +bool GetMirroredText(const Vector& text, + const Vector& directions, + const Vector& bidirectionalInfo, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& mirroredText) { bool hasTextMirrored = false; @@ -204,36 +201,36 @@ bool GetMirroredText( const Vector& text, mirroredText = text; - Character* mirroredTextBuffer = mirroredText.Begin(); - CharacterDirection* directionsBuffer = directions.Begin(); + Character* mirroredTextBuffer = mirroredText.Begin(); + CharacterDirection* directionsBuffer = directions.Begin(); - CharacterIndex index = startIndex; + CharacterIndex index = startIndex; const CharacterIndex lastCharacter = startIndex + numberOfCharacters; // Traverse the paragraphs and mirror the right to left ones. - for( Vector::ConstIterator it = bidirectionalInfo.Begin(), - endIt = bidirectionalInfo.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = bidirectionalInfo.Begin(), + endIt = bidirectionalInfo.End(); + it != endIt; + ++it) { const BidirectionalParagraphInfoRun& paragraph = *it; - if( index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters ) + if(index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters) { // Skip the paragraph as it has already been processed. continue; } - if( lastCharacter <= paragraph.characterRun.characterIndex ) + if(lastCharacter <= paragraph.characterRun.characterIndex) { // Do not get mirror characters beyond startIndex + numberOfCharacters. break; } index += paragraph.characterRun.numberOfCharacters; - const bool tmpMirrored = bidirectionalSupport.GetMirroredText( mirroredTextBuffer + paragraph.characterRun.characterIndex, - directionsBuffer + paragraph.characterRun.characterIndex, - paragraph.characterRun.numberOfCharacters ); + const bool tmpMirrored = bidirectionalSupport.GetMirroredText(mirroredTextBuffer + paragraph.characterRun.characterIndex, + directionsBuffer + paragraph.characterRun.characterIndex, + paragraph.characterRun.numberOfCharacters); hasTextMirrored = hasTextMirrored || tmpMirrored; } @@ -241,27 +238,27 @@ bool GetMirroredText( const Vector& text, return hasTextMirrored; } -void GetCharactersDirection( const Vector& bidirectionalInfo, - Length totalNumberOfCharacters, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& directions ) +void GetCharactersDirection(const Vector& bidirectionalInfo, + Length totalNumberOfCharacters, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& directions) { // Handle to the bidirectional info module in text-abstraction. TextAbstraction::BidirectionalSupport bidirectionalSupport = TextAbstraction::BidirectionalSupport::Get(); // Resize the vector. - directions.Resize( totalNumberOfCharacters ); + directions.Resize(totalNumberOfCharacters); // Whether the current buffer is being updated or is set from scratch. const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters; - CharacterDirection* directionsBuffer = NULL; + CharacterDirection* directionsBuffer = NULL; Vector newDirections; - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newDirections.Resize( numberOfCharacters ); + newDirections.Resize(numberOfCharacters); directionsBuffer = newDirections.Begin(); } else @@ -270,22 +267,22 @@ void GetCharactersDirection( const Vector& bidire } const CharacterIndex lastCharacter = startIndex + numberOfCharacters; - CharacterIndex index = startIndex; + CharacterIndex index = startIndex; - for( Vector::ConstIterator it = bidirectionalInfo.Begin(), - endIt = bidirectionalInfo.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = bidirectionalInfo.Begin(), + endIt = bidirectionalInfo.End(); + it != endIt; + ++it) { const BidirectionalParagraphInfoRun& paragraph = *it; - if( index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters ) + if(index >= paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters) { // Skip the paragraph as it has already been processed. continue; } - if( lastCharacter <= paragraph.characterRun.characterIndex ) + if(lastCharacter <= paragraph.characterRun.characterIndex) { // Do not get the character directions beyond startIndex + numberOfCharacters. break; @@ -293,31 +290,31 @@ void GetCharactersDirection( const Vector& bidire // Set the directions of any previous left to right characters. const Length numberOfLeftToRightCharacters = paragraph.characterRun.characterIndex - index; - if( numberOfLeftToRightCharacters > 0u ) + if(numberOfLeftToRightCharacters > 0u) { - memset( directionsBuffer + index - startIndex, false, numberOfLeftToRightCharacters * sizeof( bool ) ); + memset(directionsBuffer + index - startIndex, false, numberOfLeftToRightCharacters * sizeof(bool)); } // Set the directions of the bidirectional text. - bidirectionalSupport.GetCharactersDirection( paragraph.bidirectionalInfoIndex, - directionsBuffer + paragraph.characterRun.characterIndex - startIndex, - paragraph.characterRun.numberOfCharacters ); + bidirectionalSupport.GetCharactersDirection(paragraph.bidirectionalInfoIndex, + directionsBuffer + paragraph.characterRun.characterIndex - startIndex, + paragraph.characterRun.numberOfCharacters); // Update the index. index += paragraph.characterRun.numberOfCharacters + numberOfLeftToRightCharacters; } // Fills with left to right those paragraphs without right to left characters. - memset( directionsBuffer + index - startIndex, false, ( lastCharacter - index ) * sizeof( bool ) ); + memset(directionsBuffer + index - startIndex, false, (lastCharacter - index) * sizeof(bool)); // If the direction info is updated, it needs to be inserted in the model. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { // Insert the directions in the given buffer. - directions.Insert( directions.Begin() + startIndex, - newDirections.Begin(), - newDirections.End() ); - directions.Resize( totalNumberOfCharacters ); + directions.Insert(directions.Begin() + startIndex, + newDirections.Begin(), + newDirections.End()); + directions.Resize(totalNumberOfCharacters); } } diff --git a/dali-toolkit/internal/text/character-set-conversion.cpp b/dali-toolkit/internal/text/character-set-conversion.cpp index 7402292..9b84c3b 100644 --- a/dali-toolkit/internal/text/character-set-conversion.cpp +++ b/dali-toolkit/internal/text/character-set-conversion.cpp @@ -20,114 +20,116 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { - const static uint8_t U1 = 1u; - const static uint8_t U2 = 2u; - const static uint8_t U3 = 3u; - const static uint8_t U4 = 4u; - const static uint8_t U5 = 5u; - const static uint8_t U6 = 6u; - const static uint8_t U0 = 0u; - const static uint8_t UTF8_LENGTH[256] = { - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // lead byte = 0xxx xxxx (U+0000 - U+007F + some extended ascii characters) - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // - U1, U1, // - - U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // - U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // lead byte = 110x xxxx (U+0080 - U+07FF) - U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // - U2, U2, // - - U3, U3, U3, U3, U3, U3, U3, U3, U3, U3, // lead byte = 1110 xxxx (U+0800 - U+FFFF) - U3, U3, U3, U3, U3, U3, // - - U4, U4, U4, U4, U4, U4, U4, U4, // lead byte = 1111 0xxx (U+10000 - U+1FFFFF) - - U5, U5, U5, U5, // lead byte = 1111 10xx (U+200000 - U+3FFFFFF) - - U6, U6, // lead byte = 1111 110x (U+4000000 - U+7FFFFFFF) - - U0, U0, // Non valid. - }; - - const uint8_t CR = 0xd; - const uint8_t LF = 0xa; +// clang-format off +constexpr uint8_t U1 = 1u; +constexpr uint8_t U2 = 2u; +constexpr uint8_t U3 = 3u; +constexpr uint8_t U4 = 4u; +constexpr uint8_t U5 = 5u; +constexpr uint8_t U6 = 6u; +constexpr uint8_t U0 = 0u; +constexpr uint8_t UTF8_LENGTH[256] = { + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // lead byte = 0xxx xxxx (U+0000 - U+007F + some extended ascii characters) + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, U1, U1, U1, U1, U1, U1, U1, U1, // + U1, U1, // + + U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // + U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // lead byte = 110x xxxx (U+0080 - U+07FF) + U2, U2, U2, U2, U2, U2, U2, U2, U2, U2, // + U2, U2, // + + U3, U3, U3, U3, U3, U3, U3, U3, U3, U3, // lead byte = 1110 xxxx (U+0800 - U+FFFF) + U3, U3, U3, U3, U3, U3, // + + U4, U4, U4, U4, U4, U4, U4, U4, // lead byte = 1111 0xxx (U+10000 - U+1FFFFF) + + U5, U5, U5, U5, // lead byte = 1111 10xx (U+200000 - U+3FFFFFF) + + U6, U6, // lead byte = 1111 110x (U+4000000 - U+7FFFFFFF) + + U0, U0, // Non valid. +}; + +constexpr uint8_t CR = 0xd; +constexpr uint8_t LF = 0xa; +// clang-format on } // namespace -uint8_t GetUtf8Length( uint8_t utf8LeadByte ) +uint8_t GetUtf8Length(uint8_t utf8LeadByte) { return UTF8_LENGTH[utf8LeadByte]; } -uint32_t GetNumberOfUtf8Characters( const uint8_t* const utf8, uint32_t length ) +uint32_t GetNumberOfUtf8Characters(const uint8_t* const utf8, uint32_t length) { uint32_t numberOfCharacters = 0u; const uint8_t* begin = utf8; - const uint8_t* end = utf8 + length; + const uint8_t* end = utf8 + length; - for( ; begin < end ; begin += UTF8_LENGTH[*begin], ++numberOfCharacters ); + for(; begin < end; begin += UTF8_LENGTH[*begin]) + { + ++numberOfCharacters; + } return numberOfCharacters; } -uint32_t GetNumberOfUtf8Bytes( const uint32_t* const utf32, uint32_t numberOfCharacters ) +uint32_t GetNumberOfUtf8Bytes(const uint32_t* const utf32, uint32_t numberOfCharacters) { uint32_t numberOfBytes = 0u; const uint32_t* begin = utf32; - const uint32_t* end = utf32 + numberOfCharacters; + const uint32_t* end = utf32 + numberOfCharacters; - for( ; begin < end; ++begin ) + for(; begin < end; ++begin) { const uint32_t code = *begin; - if( code < 0x80u ) + if(code < 0x80u) { ++numberOfBytes; } - else if( code < 0x800u ) + else if(code < 0x800u) { numberOfBytes += U2; } - else if( code < 0x10000u ) + else if(code < 0x10000u) { numberOfBytes += U3; } - else if( code < 0x200000u ) + else if(code < 0x200000u) { numberOfBytes += U4; } - else if( code < 0x4000000u ) + else if(code < 0x4000000u) { numberOfBytes += U5; } - else if( code < 0x80000000u ) + else if(code < 0x80000000u) { numberOfBytes += U6; } @@ -136,31 +138,31 @@ uint32_t GetNumberOfUtf8Bytes( const uint32_t* const utf32, uint32_t numberOfCha return numberOfBytes; } -uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf32 ) +uint32_t Utf8ToUtf32(const uint8_t* const utf8, uint32_t length, uint32_t* utf32) { uint32_t numberOfCharacters = 0u; const uint8_t* begin = utf8; - const uint8_t* end = utf8 + length; + const uint8_t* end = utf8 + length; - for( ; begin < end ; ++numberOfCharacters ) + for(; begin < end; ++numberOfCharacters) { const uint8_t leadByte = *begin; - switch( UTF8_LENGTH[leadByte] ) + switch(UTF8_LENGTH[leadByte]) { case U1: { - if( CR == leadByte ) + if(CR == leadByte) { // Replace CR+LF or CR by LF *utf32++ = LF; // Look ahead if the next one is a LF. ++begin; - if( begin < end ) + if(begin < end) { - if( LF == *begin ) + if(LF == *begin) { ++begin; } @@ -177,7 +179,7 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 case U2: { uint32_t& code = *utf32++; - code = leadByte & 0x1fu; + code = leadByte & 0x1fu; begin++; code <<= 6u; code |= *begin++ & 0x3fu; @@ -187,7 +189,7 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 case U3: { uint32_t& code = *utf32++; - code = leadByte & 0x0fu; + code = leadByte & 0x0fu; begin++; code <<= 6u; code |= *begin++ & 0x3fu; @@ -199,7 +201,7 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 case U4: { uint32_t& code = *utf32++; - code = leadByte & 0x07u; + code = leadByte & 0x07u; begin++; code <<= 6u; code |= *begin++ & 0x3fu; @@ -213,7 +215,7 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 case U5: { uint32_t& code = *utf32++; - code = leadByte & 0x03u; + code = leadByte & 0x03u; begin++; code <<= 6u; code |= *begin++ & 0x3fu; @@ -229,7 +231,7 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 case U6: { uint32_t& code = *utf32++; - code = leadByte & 0x01u; + code = leadByte & 0x01u; begin++; code <<= 6u; code |= *begin++ & 0x3fu; @@ -244,10 +246,10 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 break; } - case U0: // Invalid case + case U0: // Invalid case { begin++; - *utf32++ = 0x20; // Use white space + *utf32++ = 0x20; // Use white space break; } } @@ -256,70 +258,72 @@ uint32_t Utf8ToUtf32( const uint8_t* const utf8, uint32_t length, uint32_t* utf3 return numberOfCharacters; } -uint32_t Utf32ToUtf8( const uint32_t* const utf32, uint32_t numberOfCharacters, uint8_t* utf8 ) +uint32_t Utf32ToUtf8(const uint32_t* const utf32, uint32_t numberOfCharacters, uint8_t* utf8) { const uint32_t* begin = utf32; - const uint32_t* end = utf32 + numberOfCharacters; + const uint32_t* end = utf32 + numberOfCharacters; uint8_t* utf8Begin = utf8; - for( ; begin < end; ++begin ) + for(; begin < end; ++begin) { const uint32_t code = *begin; + // clang-format off if( code < 0x80u ) { *utf8++ = code; } else if( code < 0x800u ) { - *utf8++ = static_cast( code >> 6u ) | 0xc0u; // lead byte for 2 byte sequence - *utf8++ = static_cast( code & 0x3f ) | 0x80u; // continuation byte + *utf8++ = static_cast( code >> 6u) | 0xc0u; // lead byte for 2 byte sequence + *utf8++ = static_cast( code & 0x3f) | 0x80u; // continuation byte } else if( code < 0x10000u ) { - *utf8++ = static_cast( code >> 12u ) | 0xe0u; // lead byte for 3 byte sequence - *utf8++ = static_cast( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( code & 0x3f ) | 0x80u; // continuation byte + *utf8++ = static_cast( code >> 12u) | 0xe0u; // lead byte for 3 byte sequence + *utf8++ = static_cast((code >> 6u ) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast( code & 0x3f) | 0x80u; // continuation byte } else if( code < 0x200000u ) { - *utf8++ = static_cast( code >> 18u ) | 0xf0u; // lead byte for 4 byte sequence - *utf8++ = static_cast( ( code >> 12u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( code & 0x3f ) | 0x80u; // continuation byte + *utf8++ = static_cast( code >> 18u) | 0xf0u; // lead byte for 4 byte sequence + *utf8++ = static_cast((code >> 12u) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast((code >> 6u ) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast( code & 0x3f) | 0x80u; // continuation byte } else if( code < 0x4000000u ) { - *utf8++ = static_cast( code >> 24u ) | 0xf8u; // lead byte for 5 byte sequence - *utf8++ = static_cast( ( code >> 18u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( ( code >> 12u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( code & 0x3f ) | 0x80u; // continuation byte + *utf8++ = static_cast( code >> 24u) | 0xf8u; // lead byte for 5 byte sequence + *utf8++ = static_cast((code >> 18u) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast((code >> 12u) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast((code >> 6u ) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast( code & 0x3f) | 0x80u; // continuation byte } else if( code < 0x80000000u ) { - *utf8++ = static_cast( code >> 30u ) | 0xfcu; // lead byte for 6 byte sequence - *utf8++ = static_cast( ( code >> 24u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( ( code >> 18u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( ( code >> 12u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( ( code >> 6u ) & 0x3f ) | 0x80u; // continuation byte - *utf8++ = static_cast( code & 0x3f ) | 0x80u; // continuation byte + *utf8++ = static_cast( code >> 30u) | 0xfcu; // lead byte for 6 byte sequence + *utf8++ = static_cast((code >> 24u) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast((code >> 18u) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast((code >> 12u) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast((code >> 6u ) & 0x3f) | 0x80u; // continuation byte + *utf8++ = static_cast( code & 0x3f) | 0x80u; // continuation byte } + // clang-format on } return utf8 - utf8Begin; } -void Utf32ToUtf8( const uint32_t* const utf32, uint32_t numberOfCharacters, std::string& utf8 ) +void Utf32ToUtf8(const uint32_t* const utf32, uint32_t numberOfCharacters, std::string& utf8) { utf8.clear(); - uint32_t numberOfBytes = GetNumberOfUtf8Bytes( &utf32[0], numberOfCharacters ); - utf8.resize( numberOfBytes ); + uint32_t numberOfBytes = GetNumberOfUtf8Bytes(&utf32[0], numberOfCharacters); + utf8.resize(numberOfBytes); // This is a bit horrible but std::string returns a (signed) char* - Utf32ToUtf8( utf32, numberOfCharacters, reinterpret_cast(&utf8[0]) ); + Utf32ToUtf8(utf32, numberOfCharacters, reinterpret_cast(&utf8[0])); } } // namespace Text diff --git a/dali-toolkit/internal/text/color-segmentation.cpp b/dali-toolkit/internal/text/color-segmentation.cpp index 3c2f76a..9476480 100644 --- a/dali-toolkit/internal/text/color-segmentation.cpp +++ b/dali-toolkit/internal/text/color-segmentation.cpp @@ -26,13 +26,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - /** * @brief Finds a color in the vector of colors. * It inserts the color in the vector if it's not in. @@ -42,16 +39,16 @@ namespace Text * * @return The index + 1 where the color is in the vector. The index zero is reserved for the default color. */ -ColorIndex FindColor( Vector& colors, - const Vector4& color ) +ColorIndex FindColor(Vector& colors, + const Vector4& color) { ColorIndex index = 1u; // The index zero is reserved for the default color. - for( Vector::Iterator it = colors.Begin(), - endIt = colors.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = colors.Begin(), + endIt = colors.End(); + it != endIt; + ++it) { - if( color == *it ) + if(color == *it) { return index; } @@ -59,77 +56,77 @@ ColorIndex FindColor( Vector& colors, ++index; } - colors.PushBack( color ); + colors.PushBack(color); return index; } -void SetColorSegmentationInfo( const Vector& colorRuns, - const Vector& charactersToGlyph, - const Vector& glyphsPerCharacter, - CharacterIndex startCharacterIndex, - GlyphIndex startGlyphIndex, - Length numberOfCharacters, - Vector& colors, - Vector& colorIndices ) +void SetColorSegmentationInfo(const Vector& colorRuns, + const Vector& charactersToGlyph, + const Vector& glyphsPerCharacter, + CharacterIndex startCharacterIndex, + GlyphIndex startGlyphIndex, + Length numberOfCharacters, + Vector& colors, + Vector& colorIndices) { - if( 0u == charactersToGlyph.Count() ) + if(0u == charactersToGlyph.Count()) { // Nothing to do if there is no text. return; } // Get pointers to the buffers. - const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin(); - const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin(); + const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin(); + const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin(); // Calculate the number of glyphs to insert. const CharacterIndex lastCharacterIndex = startCharacterIndex + numberOfCharacters - 1u; - const Length numberOfNewGlyphs = *( charactersToGlyphBuffer + lastCharacterIndex ) + *( glyphsPerCharacterBuffer + lastCharacterIndex ) - *( charactersToGlyphBuffer + startCharacterIndex ); + const Length numberOfNewGlyphs = *(charactersToGlyphBuffer + lastCharacterIndex) + *(glyphsPerCharacterBuffer + lastCharacterIndex) - *(charactersToGlyphBuffer + startCharacterIndex); // Reserve space for the new color indices. Vector newColorIndices; - newColorIndices.Resize( numberOfNewGlyphs ); + newColorIndices.Resize(numberOfNewGlyphs); ColorIndex* newColorIndicesBuffer = newColorIndices.Begin(); // Convert from characters to glyphs. Length index = 0u; - for( Vector::ConstIterator it = colorRuns.Begin(), - endIt = colorRuns.End(); - it != endIt; - ++it, ++index ) + for(Vector::ConstIterator it = colorRuns.Begin(), + endIt = colorRuns.End(); + it != endIt; + ++it, ++index) { const ColorRun& colorRun = *it; - if( ( startCharacterIndex < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters ) && - ( colorRun.characterRun.characterIndex < startCharacterIndex + numberOfCharacters ) ) + if((startCharacterIndex < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters) && + (colorRun.characterRun.characterIndex < startCharacterIndex + numberOfCharacters)) { - if( 0u < colorRun.characterRun.numberOfCharacters ) + if(0u < colorRun.characterRun.numberOfCharacters) { // Find the color index. - const ColorIndex colorIndex = FindColor( colors, colorRun.color ); + const ColorIndex colorIndex = FindColor(colors, colorRun.color); // Get the index to the last character of the run. const CharacterIndex lastIndex = colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters - 1u; - const GlyphIndex glyphIndex = std::max( startGlyphIndex, *( charactersToGlyphBuffer + colorRun.characterRun.characterIndex ) ) - startGlyphIndex; + const GlyphIndex glyphIndex = std::max(startGlyphIndex, *(charactersToGlyphBuffer + colorRun.characterRun.characterIndex)) - startGlyphIndex; // Get the number of glyphs of the run. - const Length lastGlyphIndexPlusOne = std::min( numberOfNewGlyphs, *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex ); + const Length lastGlyphIndexPlusOne = std::min(numberOfNewGlyphs, *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex); // Set the indices. - for( GlyphIndex i = glyphIndex; i < lastGlyphIndexPlusOne; ++i ) + for(GlyphIndex i = glyphIndex; i < lastGlyphIndexPlusOne; ++i) { - *( newColorIndicesBuffer + i ) = colorIndex; + *(newColorIndicesBuffer + i) = colorIndex; } } } } // Insert the new indices. - colorIndices.Insert( colorIndices.Begin() + startGlyphIndex, - newColorIndices.Begin(), - newColorIndices.End() ); + colorIndices.Insert(colorIndices.Begin() + startGlyphIndex, + newColorIndices.Begin(), + newColorIndices.End()); } } // namespace Text diff --git a/dali-toolkit/internal/text/cursor-helper-functions.cpp b/dali-toolkit/internal/text/cursor-helper-functions.cpp index 19db7ae..1df142c 100644 --- a/dali-toolkit/internal/text/cursor-helper-functions.cpp +++ b/dali-toolkit/internal/text/cursor-helper-functions.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,98 +26,99 @@ namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction. struct FindWordData { - FindWordData( const Dali::Toolkit::Text::Character* const textBuffer, - Dali::Toolkit::Text::Length totalNumberOfCharacters, - Dali::Toolkit::Text::CharacterIndex hitCharacter, - bool isWhiteSpace, - bool isNewParagraph ) - : textBuffer( textBuffer ), - totalNumberOfCharacters( totalNumberOfCharacters ), - hitCharacter( hitCharacter ), - foundIndex( 0 ), - isWhiteSpace( isWhiteSpace ), - isNewParagraph( isNewParagraph ) - {} + FindWordData(const Dali::Toolkit::Text::Character* const textBuffer, + Dali::Toolkit::Text::Length totalNumberOfCharacters, + Dali::Toolkit::Text::CharacterIndex hitCharacter, + bool isWhiteSpace, + bool isNewParagraph) + : textBuffer(textBuffer), + totalNumberOfCharacters(totalNumberOfCharacters), + hitCharacter(hitCharacter), + foundIndex(0), + isWhiteSpace(isWhiteSpace), + isNewParagraph(isNewParagraph) + { + } ~FindWordData() - {} + { + } const Dali::Toolkit::Text::Character* const textBuffer; Dali::Toolkit::Text::Length totalNumberOfCharacters; Dali::Toolkit::Text::CharacterIndex hitCharacter; Dali::Toolkit::Text::CharacterIndex foundIndex; - bool isWhiteSpace : 1u; + bool isWhiteSpace : 1u; bool isNewParagraph : 1u; }; -bool IsWhiteSpaceOrNewParagraph( Dali::Toolkit::Text::Character character, - bool isHitWhiteSpace, - bool isHitWhiteSpaceOrNewParagraph ) +bool IsWhiteSpaceOrNewParagraph(Dali::Toolkit::Text::Character character, + bool isHitWhiteSpace, + bool isHitWhiteSpaceOrNewParagraph) { bool isWhiteSpaceOrNewParagraph = false; - if( isHitWhiteSpaceOrNewParagraph ) + if(isHitWhiteSpaceOrNewParagraph) { - if( isHitWhiteSpace ) + if(isHitWhiteSpace) { // Whether the current character is a white space. Note a new paragraph character is a white space as well but here is not wanted. - isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character ) && !Dali::TextAbstraction::IsNewParagraph( character ); + isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace(character) && !Dali::TextAbstraction::IsNewParagraph(character); } else { // Whether the current character is a new paragraph character. - isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsNewParagraph( character ); + isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsNewParagraph(character); } } else { // Whether the current character is a white space or a new paragraph character (note the new paragraph character is a white space as well). - isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace( character ); + isWhiteSpaceOrNewParagraph = Dali::TextAbstraction::IsWhiteSpace(character); } return isWhiteSpaceOrNewParagraph; } -void FindStartOfWord( FindWordData& data ) +void FindStartOfWord(FindWordData& data) { const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph; - for( data.foundIndex = data.hitCharacter; data.foundIndex > 0; --data.foundIndex ) + for(data.foundIndex = data.hitCharacter; data.foundIndex > 0; --data.foundIndex) { - const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex - 1u ); + const Dali::Toolkit::Text::Character character = *(data.textBuffer + data.foundIndex - 1u); - const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character, - data.isWhiteSpace, - isHitWhiteSpaceOrNewParagraph ); + const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph(character, + data.isWhiteSpace, + isHitWhiteSpaceOrNewParagraph); - if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph ) + if(isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph) { break; } } } -void FindEndOfWord( FindWordData& data ) +void FindEndOfWord(FindWordData& data) { const bool isHitWhiteSpaceOrNewParagraph = data.isWhiteSpace || data.isNewParagraph; - for( data.foundIndex = data.hitCharacter + 1u; data.foundIndex < data.totalNumberOfCharacters; ++data.foundIndex ) + for(data.foundIndex = data.hitCharacter + 1u; data.foundIndex < data.totalNumberOfCharacters; ++data.foundIndex) { - const Dali::Toolkit::Text::Character character = *( data.textBuffer + data.foundIndex ); + const Dali::Toolkit::Text::Character character = *(data.textBuffer + data.foundIndex); - const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph( character, - data.isWhiteSpace, - isHitWhiteSpaceOrNewParagraph ); + const bool isWhiteSpaceOrNewParagraph = IsWhiteSpaceOrNewParagraph(character, + data.isWhiteSpace, + isHitWhiteSpaceOrNewParagraph); - if( isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph ) + if(isHitWhiteSpaceOrNewParagraph != isWhiteSpaceOrNewParagraph) { break; } @@ -128,32 +129,29 @@ void FindEndOfWord( FindWordData& data ) namespace Dali { - namespace Toolkit { - namespace Text { - -LineIndex GetClosestLine( VisualModelPtr visualModel, - float visualY, - bool& matchedLine ) +LineIndex GetClosestLine(VisualModelPtr visualModel, + float visualY, + bool& matchedLine) { - float totalHeight = 0.f; - LineIndex lineIndex = 0; - matchedLine = false; + float totalHeight = 0.f; + LineIndex lineIndex = 0; + matchedLine = false; - if( visualY < 0.f ) + if(visualY < 0.f) { return 0; } const Vector& lines = visualModel->mLines; - for( Vector::ConstIterator it = lines.Begin(), - endIt = lines.End(); - it != endIt; - ++it, ++lineIndex ) + for(Vector::ConstIterator it = lines.Begin(), + endIt = lines.End(); + it != endIt; + ++it, ++lineIndex) { const LineRun& lineRun = *it; @@ -161,14 +159,14 @@ LineIndex GetClosestLine( VisualModelPtr visualModel, // However, the line descender has a negative value, hence the subtraction. totalHeight += lineRun.ascender - lineRun.descender; - if( visualY < totalHeight ) + if(visualY < totalHeight) { matchedLine = true; return lineIndex; } } - if( lineIndex == 0 ) + if(lineIndex == 0) { return 0; } @@ -176,15 +174,15 @@ LineIndex GetClosestLine( VisualModelPtr visualModel, return lineIndex - 1u; } -float CalculateLineOffset( const Vector& lines, - LineIndex lineIndex ) +float CalculateLineOffset(const Vector& lines, + LineIndex lineIndex) { float offset = 0.f; - for( Vector::ConstIterator it = lines.Begin(), - endIt = lines.Begin() + lineIndex; - it != endIt; - ++it ) + for(Vector::ConstIterator it = lines.Begin(), + endIt = lines.Begin() + lineIndex; + it != endIt; + ++it) { const LineRun& lineRun = *it; @@ -196,15 +194,15 @@ float CalculateLineOffset( const Vector& lines, return offset; } -CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, - LogicalModelPtr logicalModel, - MetricsPtr metrics, - float visualX, - float visualY, - CharacterHitTest::Mode mode, - bool& matchedCharacter ) +CharacterIndex GetClosestCursorIndex(VisualModelPtr visualModel, + LogicalModelPtr logicalModel, + MetricsPtr metrics, + float visualX, + float visualY, + CharacterHitTest::Mode mode, + bool& matchedCharacter) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GetClosestCursorIndex, closest visualX %f visualY %f\n", visualX, visualY); // Whether there is a hit on a glyph. matchedCharacter = false; @@ -213,8 +211,8 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count(); const Length totalNumberOfLines = visualModel->mLines.Count(); - if( ( 0 == totalNumberOfGlyphs ) || - ( 0 == totalNumberOfLines ) ) + if((0 == totalNumberOfGlyphs) || + (0 == totalNumberOfLines)) { return logicalIndex; } @@ -223,18 +221,18 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, bool matchedLine = false; // Find which line is closest. - const LineIndex lineIndex = Text::GetClosestLine( visualModel, - visualY, - matchedLine ); + const LineIndex lineIndex = Text::GetClosestLine(visualModel, + visualY, + matchedLine); - if( !matchedLine && ( CharacterHitTest::TAP == mode ) ) + if(!matchedLine && (CharacterHitTest::TAP == mode)) { // Return the first or the last character if the touch point doesn't hit a line. - return ( visualY < 0.f ) ? 0 : logicalModel->mText.Count(); + return (visualY < 0.f) ? 0 : logicalModel->mText.Count(); } // Convert from text's coords to line's coords. - const LineRun& line = *( visualModel->mLines.Begin() + lineIndex ); + const LineRun& line = *(visualModel->mLines.Begin() + lineIndex); // Transform the tap point from text's coords to line's coords. visualX -= line.alignmentOffset; @@ -256,10 +254,10 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, const CharacterIndex startCharacter = line.characterRun.characterIndex; const CharacterIndex endCharacter = line.characterRun.characterIndex + line.characterRun.numberOfCharacters; - DALI_ASSERT_DEBUG( endCharacter <= logicalModel->mText.Count() && "Invalid line info" ); + DALI_ASSERT_DEBUG(endCharacter <= logicalModel->mText.Count() && "Invalid line info"); // Whether this line is a bidirectional line. - const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo( startCharacter ); + const bool bidiLineFetched = logicalModel->FetchBidirectionalLineInfo(startCharacter); // The character's direction buffer. const CharacterDirection* const directionsBuffer = bidiLineFetched ? logicalModel->mCharacterDirections.Begin() : NULL; @@ -268,41 +266,41 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, bool isBeforeFirstGlyph = false; // Traverses glyphs in visual order. To do that use the visual to logical conversion table. - CharacterIndex visualIndex = startCharacter; - Length numberOfVisualCharacters = 0; - for( ; visualIndex < endCharacter; ++visualIndex ) + CharacterIndex visualIndex = startCharacter; + Length numberOfVisualCharacters = 0; + for(; visualIndex < endCharacter; ++visualIndex) { // The character in logical order. - const CharacterIndex characterLogicalOrderIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( visualIndex ) : visualIndex ); - const CharacterDirection direction = ( bidiLineFetched ? *( directionsBuffer + characterLogicalOrderIndex ) : LTR ); + const CharacterIndex characterLogicalOrderIndex = (bidiLineFetched ? logicalModel->GetLogicalCharacterIndex(visualIndex) : visualIndex); + const CharacterDirection direction = (bidiLineFetched ? *(directionsBuffer + characterLogicalOrderIndex) : LTR); // The number of glyphs for that character - const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterLogicalOrderIndex ); + const Length numberOfGlyphs = *(glyphsPerCharacterBuffer + characterLogicalOrderIndex); ++numberOfVisualCharacters; - if( 0 != numberOfGlyphs ) + if(0 != numberOfGlyphs) { // Get the first character/glyph of the group of glyphs. - const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfVisualCharacters; - const CharacterIndex firstLogicalCharacterIndex = ( bidiLineFetched ? logicalModel->GetLogicalCharacterIndex( firstVisualCharacterIndex ) : firstVisualCharacterIndex ); - const GlyphIndex firstLogicalGlyphIndex = *( charactersToGlyphBuffer + firstLogicalCharacterIndex ); + const CharacterIndex firstVisualCharacterIndex = 1u + visualIndex - numberOfVisualCharacters; + const CharacterIndex firstLogicalCharacterIndex = (bidiLineFetched ? logicalModel->GetLogicalCharacterIndex(firstVisualCharacterIndex) : firstVisualCharacterIndex); + const GlyphIndex firstLogicalGlyphIndex = *(charactersToGlyphBuffer + firstLogicalCharacterIndex); // Get the metrics for the group of glyphs. GlyphMetrics glyphMetrics; - GetGlyphsMetrics( firstLogicalGlyphIndex, - numberOfGlyphs, - glyphMetrics, - glyphInfoBuffer, - metrics ); + GetGlyphsMetrics(firstLogicalGlyphIndex, + numberOfGlyphs, + glyphMetrics, + glyphInfoBuffer, + metrics); // Get the position of the first glyph. - const Vector2& position = *( positionsBuffer + firstLogicalGlyphIndex ); + const Vector2& position = *(positionsBuffer + firstLogicalGlyphIndex); - if( startCharacter == visualIndex ) + if(startCharacter == visualIndex) { const float glyphPosition = -glyphMetrics.xBearing + position.x; - if( visualX < glyphPosition ) + if(visualX < glyphPosition) { isBeforeFirstGlyph = true; break; @@ -310,15 +308,15 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, } // Whether the glyph can be split, like Latin ligatures fi, ff or Arabic (ل + ا). - Length numberOfCharacters = *( charactersPerGlyphBuffer + firstLogicalGlyphIndex ); - if( direction != LTR ) + Length numberOfCharacters = *(charactersPerGlyphBuffer + firstLogicalGlyphIndex); + if(direction != LTR) { // As characters are being traversed in visual order, // for right to left ligatures, the character which contains the // number of glyphs in the table is found first. // Jump the number of characters to the next glyph is needed. - if( 0 == numberOfCharacters ) + if(0 == numberOfCharacters) { // TODO: This is a workaround to fix an issue with complex characters in the arabic // script like i.e. رّ or الأَبْجَدِيَّة العَرَبِيَّة @@ -331,14 +329,14 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, // to hang in an infinite loop. // Find the number of characters. - for( GlyphIndex index = firstLogicalGlyphIndex + 1u; - ( 0 == numberOfCharacters ) && ( index < totalNumberOfGlyphs ); - ++index ) + for(GlyphIndex index = firstLogicalGlyphIndex + 1u; + (0 == numberOfCharacters) && (index < totalNumberOfGlyphs); + ++index) { - numberOfCharacters = *( charactersPerGlyphBuffer + index ); + numberOfCharacters = *(charactersPerGlyphBuffer + index); } - if( 2u > numberOfCharacters ) + if(2u > numberOfCharacters) { continue; } @@ -350,26 +348,26 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, } // Get the script of the character. - const Script script = logicalModel->GetScript( characterLogicalOrderIndex ); + const Script script = logicalModel->GetScript(characterLogicalOrderIndex); - const bool isInterglyphIndex = ( numberOfCharacters > numberOfGlyphs ) && HasLigatureMustBreak( script ); - const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u; - const float glyphAdvance = glyphMetrics.advance / static_cast( numberOfBlocks ); + const bool isInterglyphIndex = (numberOfCharacters > numberOfGlyphs) && HasLigatureMustBreak(script); + const Length numberOfBlocks = isInterglyphIndex ? numberOfCharacters : 1u; + const float glyphAdvance = glyphMetrics.advance / static_cast(numberOfBlocks); CharacterIndex index = 0; - for( ; index < numberOfBlocks; ++index ) + for(; index < numberOfBlocks; ++index) { // Find the mid-point of the area containing the glyph - const float glyphCenter = -glyphMetrics.xBearing + position.x + ( static_cast( index ) + 0.5f ) * glyphAdvance; + const float glyphCenter = -glyphMetrics.xBearing + position.x + (static_cast(index) + 0.5f) * glyphAdvance; - if( visualX < glyphCenter ) + if(visualX < glyphCenter) { matchedCharacter = true; break; } } - if( matchedCharacter ) + if(matchedCharacter) { // If the glyph is shaped from more than one character, it matches the character of the glyph. visualIndex = firstVisualCharacterIndex + index; @@ -385,9 +383,9 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, // Return the logical position of the cursor in characters. - if( !matchedCharacter ) + if(!matchedCharacter) { - if( isBeforeFirstGlyph ) + if(isBeforeFirstGlyph) { // If no character is matched, then the first character (in visual order) of the line is used. visualIndex = startCharacter; @@ -402,15 +400,15 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, // Get the paragraph direction. const CharacterDirection paragraphDirection = line.direction; - if( totalNumberOfCharacters != visualIndex ) + if(totalNumberOfCharacters != visualIndex) { // The visual index is not at the end of the text. - if( LTR == paragraphDirection ) + if(LTR == paragraphDirection) { // The paragraph direction is left to right. - if( visualIndex == endCharacter ) + if(visualIndex == endCharacter) { // It places the cursor just before the last character in visual order. // i.e. it places the cursor just before the '\n' or before the last character @@ -426,8 +424,8 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, { // The paragraph direction is right to left. - if( ( lineIndex != totalNumberOfLines - 1u ) && // is not the last line. - ( visualIndex == startCharacter ) ) + if((lineIndex != totalNumberOfLines - 1u) && // is not the last line. + (visualIndex == startCharacter)) { // It places the cursor just after the first character in visual order. // i.e. it places the cursor just after the '\n' or after the last character @@ -447,28 +445,27 @@ CharacterIndex GetClosestCursorIndex( VisualModelPtr visualModel, // This branch checks if the closest line is the one with the last '\n'. If it is, it decrements the visual index to place // the cursor just before the last '\n'. - if( ( lineIndex != totalNumberOfLines - 1u ) && - TextAbstraction::IsNewParagraph( *( logicalModel->mText.Begin() + visualIndex - 1u ) ) ) + if((lineIndex != totalNumberOfLines - 1u) && + TextAbstraction::IsNewParagraph(*(logicalModel->mText.Begin() + visualIndex - 1u))) { --visualIndex; } } - logicalIndex = ( bidiLineFetched ? logicalModel->GetLogicalCursorIndex( visualIndex ) : visualIndex ); + logicalIndex = (bidiLineFetched ? logicalModel->GetLogicalCursorIndex(visualIndex) : visualIndex); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "closest visualIndex %d logicalIndex %d\n", visualIndex, logicalIndex); - DALI_ASSERT_DEBUG( ( logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0 ) && "GetClosestCursorIndex - Out of bounds index" ); + DALI_ASSERT_DEBUG((logicalIndex <= logicalModel->mText.Count() && logicalIndex >= 0) && "GetClosestCursorIndex - Out of bounds index"); return logicalIndex; } - -void GetCursorPosition( GetCursorPositionParameters& parameters, - CursorInfo& cursorInfo ) +void GetCursorPosition(GetCursorPositionParameters& parameters, + CursorInfo& cursorInfo) { const LineRun* const modelLines = parameters.visualModel->mLines.Begin(); - if( NULL == modelLines ) + if(NULL == modelLines) { // Nothing to do. return; @@ -478,25 +475,25 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, const bool isLastPosition = parameters.logicalModel->mText.Count() == parameters.logical; // Get the line where the character is laid-out. - const CharacterIndex characterOfLine = isLastPosition ? ( parameters.logical - 1u ) : parameters.logical; + const CharacterIndex characterOfLine = isLastPosition ? (parameters.logical - 1u) : parameters.logical; // Whether the cursor is in the last position and the last position is a new paragraph character. - const bool isLastNewParagraph = parameters.isMultiline && isLastPosition && TextAbstraction::IsNewParagraph( *( parameters.logicalModel->mText.Begin() + characterOfLine ) ); + const bool isLastNewParagraph = parameters.isMultiline && isLastPosition && TextAbstraction::IsNewParagraph(*(parameters.logicalModel->mText.Begin() + characterOfLine)); - const LineIndex lineIndex = parameters.visualModel->GetLineOfCharacter( characterOfLine ); - const LineRun& line = *( modelLines + lineIndex ); + const LineIndex lineIndex = parameters.visualModel->GetLineOfCharacter(characterOfLine); + const LineRun& line = *(modelLines + lineIndex); - if( isLastNewParagraph ) + if(isLastNewParagraph) { // The cursor is in a new line with no characters. Place the cursor in that line. const LineIndex newLineIndex = lineIndex + 1u; - const LineRun& newLine = *( modelLines + newLineIndex ); + const LineRun& newLine = *(modelLines + newLineIndex); cursorInfo.isSecondaryCursor = false; // Set the line offset and height. - cursorInfo.lineOffset = CalculateLineOffset( parameters.visualModel->mLines, - newLineIndex ); + cursorInfo.lineOffset = CalculateLineOffset(parameters.visualModel->mLines, + newLineIndex); // The line height is the addition of the line ascender and the line descender. // However, the line descender has a negative value, hence the subtraction. @@ -506,45 +503,45 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, cursorInfo.primaryCursorHeight = cursorInfo.lineHeight; // Set the primary cursor's position. - cursorInfo.primaryPosition.x = ( LTR == line.direction ) ? newLine.alignmentOffset : parameters.visualModel->mControlSize.width - newLine.alignmentOffset; + cursorInfo.primaryPosition.x = (LTR == line.direction) ? newLine.alignmentOffset : parameters.visualModel->mControlSize.width - newLine.alignmentOffset; cursorInfo.primaryPosition.y = cursorInfo.lineOffset; } else { // Whether this line is a bidirectional line. - const bool bidiLineFetched = parameters.logicalModel->FetchBidirectionalLineInfo( characterOfLine ); + const bool bidiLineFetched = parameters.logicalModel->FetchBidirectionalLineInfo(characterOfLine); // Check if the logical position is the first or the last one of the line. const bool isFirstPositionOfLine = line.characterRun.characterIndex == parameters.logical; - const bool isLastPositionOfLine = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == parameters.logical; + const bool isLastPositionOfLine = line.characterRun.characterIndex + line.characterRun.numberOfCharacters == parameters.logical; // 'logical' is the logical 'cursor' index. // Get the next and current logical 'character' index. - const CharacterIndex characterIndex = isFirstPositionOfLine ? parameters.logical : parameters.logical - 1u; + const CharacterIndex characterIndex = isFirstPositionOfLine ? parameters.logical : parameters.logical - 1u; const CharacterIndex nextCharacterIndex = isLastPositionOfLine ? characterIndex : parameters.logical; // The character's direction buffer. const CharacterDirection* const directionsBuffer = bidiLineFetched ? parameters.logicalModel->mCharacterDirections.Begin() : NULL; CharacterDirection isCurrentRightToLeft = false; - CharacterDirection isNextRightToLeft = false; - if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right. + CharacterDirection isNextRightToLeft = false; + if(bidiLineFetched) // If bidiLineFetched is false, it means the whole text is left to right. { - isCurrentRightToLeft = *( directionsBuffer + characterIndex ); - isNextRightToLeft = *( directionsBuffer + nextCharacterIndex ); + isCurrentRightToLeft = *(directionsBuffer + characterIndex); + isNextRightToLeft = *(directionsBuffer + nextCharacterIndex); } // Get the paragraph's direction. const CharacterDirection isRightToLeftParagraph = line.direction; // Check whether there is an alternative position: - cursorInfo.isSecondaryCursor = ( ( !isLastPositionOfLine && ( isCurrentRightToLeft != isNextRightToLeft ) ) || - ( isLastPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) || - ( isFirstPositionOfLine && ( isRightToLeftParagraph != isCurrentRightToLeft ) ) ); + cursorInfo.isSecondaryCursor = ((!isLastPositionOfLine && (isCurrentRightToLeft != isNextRightToLeft)) || + (isLastPositionOfLine && (isRightToLeftParagraph != isCurrentRightToLeft)) || + (isFirstPositionOfLine && (isRightToLeftParagraph != isCurrentRightToLeft))); // Set the line offset and height. - cursorInfo.lineOffset = CalculateLineOffset( parameters.visualModel->mLines, - lineIndex ); + cursorInfo.lineOffset = CalculateLineOffset(parameters.visualModel->mLines, + lineIndex); // The line height is the addition of the line ascender and the line descender. // However, the line descender has a negative value, hence the subtraction. @@ -553,11 +550,11 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, // Calculate the primary cursor. CharacterIndex index = characterIndex; - if( cursorInfo.isSecondaryCursor ) + if(cursorInfo.isSecondaryCursor) { // If there is a secondary position, the primary cursor may be in a different place than the logical index. - if( isLastPositionOfLine ) + if(isLastPositionOfLine) { // The position of the cursor after the last character needs special // care depending on its direction and the direction of the paragraph. @@ -566,44 +563,44 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, // i.e l0 l1 l2 r0 r1 should find r0. index = isRightToLeftParagraph ? line.characterRun.characterIndex : line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u; - if( bidiLineFetched ) + if(bidiLineFetched) { - index = parameters.logicalModel->GetLogicalCharacterIndex( index ); + index = parameters.logicalModel->GetLogicalCharacterIndex(index); } } - else if( isFirstPositionOfLine ) + else if(isFirstPositionOfLine) { index = isRightToLeftParagraph ? line.characterRun.characterIndex + line.characterRun.numberOfCharacters - 1u : line.characterRun.characterIndex; - if( bidiLineFetched ) + if(bidiLineFetched) { - index = parameters.logicalModel->GetLogicalCharacterIndex( index ); + index = parameters.logicalModel->GetLogicalCharacterIndex(index); } } else { - index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? characterIndex : nextCharacterIndex; + index = (isRightToLeftParagraph == isCurrentRightToLeft) ? characterIndex : nextCharacterIndex; } } - const GlyphIndex* const charactersToGlyphBuffer = parameters.visualModel->mCharactersToGlyph.Begin(); - const Length* const glyphsPerCharacterBuffer = parameters.visualModel->mGlyphsPerCharacter.Begin(); - const Length* const charactersPerGlyphBuffer = parameters.visualModel->mCharactersPerGlyph.Begin(); + const GlyphIndex* const charactersToGlyphBuffer = parameters.visualModel->mCharactersToGlyph.Begin(); + const Length* const glyphsPerCharacterBuffer = parameters.visualModel->mGlyphsPerCharacter.Begin(); + const Length* const charactersPerGlyphBuffer = parameters.visualModel->mCharactersPerGlyph.Begin(); const CharacterIndex* const glyphsToCharactersBuffer = parameters.visualModel->mGlyphsToCharacters.Begin(); - const Vector2* const glyphPositionsBuffer = parameters.visualModel->mGlyphPositions.Begin(); - const GlyphInfo* const glyphInfoBuffer = parameters.visualModel->mGlyphs.Begin(); + const Vector2* const glyphPositionsBuffer = parameters.visualModel->mGlyphPositions.Begin(); + const GlyphInfo* const glyphInfoBuffer = parameters.visualModel->mGlyphs.Begin(); // Convert the cursor position into the glyph position. - const GlyphIndex primaryGlyphIndex = *( charactersToGlyphBuffer + index ); - const Length primaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index ); - const Length primaryNumberOfCharacters = *( charactersPerGlyphBuffer + primaryGlyphIndex ); + const GlyphIndex primaryGlyphIndex = *(charactersToGlyphBuffer + index); + const Length primaryNumberOfGlyphs = *(glyphsPerCharacterBuffer + index); + const Length primaryNumberOfCharacters = *(charactersPerGlyphBuffer + primaryGlyphIndex); // Get the metrics for the group of glyphs. GlyphMetrics glyphMetrics; - GetGlyphsMetrics( primaryGlyphIndex, - primaryNumberOfGlyphs, - glyphMetrics, - glyphInfoBuffer, - parameters.metrics ); + GetGlyphsMetrics(primaryGlyphIndex, + primaryNumberOfGlyphs, + glyphMetrics, + glyphInfoBuffer, + parameters.metrics); // Whether to add the glyph's advance to the cursor position. // i.e if the paragraph is left to right and the logical cursor is zero, the position is the position of the first glyph and the advance is not added, @@ -635,34 +632,34 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, // P -> isRightToLeftParagraph // A -> Whether to add the glyph's advance. - const bool addGlyphAdvance = ( ( isLastPositionOfLine && !isRightToLeftParagraph ) || - ( isFirstPositionOfLine && isRightToLeftParagraph ) || - ( !isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft ) ); + const bool addGlyphAdvance = ((isLastPositionOfLine && !isRightToLeftParagraph) || + (isFirstPositionOfLine && isRightToLeftParagraph) || + (!isFirstPositionOfLine && !isLastPosition && !isCurrentRightToLeft)); float glyphAdvance = addGlyphAdvance ? glyphMetrics.advance : 0.f; - if( !isLastPositionOfLine && - ( primaryNumberOfCharacters > 1u ) ) + if(!isLastPositionOfLine && + (primaryNumberOfCharacters > 1u)) { - const CharacterIndex firstIndex = *( glyphsToCharactersBuffer + primaryGlyphIndex ); + const CharacterIndex firstIndex = *(glyphsToCharactersBuffer + primaryGlyphIndex); bool isCurrentRightToLeft = false; - if( bidiLineFetched ) // If bidiLineFetched is false, it means the whole text is left to right. + if(bidiLineFetched) // If bidiLineFetched is false, it means the whole text is left to right. { - isCurrentRightToLeft = *( directionsBuffer + index ); + isCurrentRightToLeft = *(directionsBuffer + index); } - Length numberOfGlyphAdvance = ( isFirstPositionOfLine ? 0 : 1u ) + characterIndex - firstIndex; - if( isCurrentRightToLeft ) + Length numberOfGlyphAdvance = (isFirstPositionOfLine ? 0 : 1u) + characterIndex - firstIndex; + if(isCurrentRightToLeft) { numberOfGlyphAdvance = primaryNumberOfCharacters - numberOfGlyphAdvance; } - glyphAdvance = static_cast( numberOfGlyphAdvance ) * glyphMetrics.advance / static_cast( primaryNumberOfCharacters ); + glyphAdvance = static_cast(numberOfGlyphAdvance) * glyphMetrics.advance / static_cast(primaryNumberOfCharacters); } // Get the glyph position and x bearing (in the line's coords). - const Vector2& primaryPosition = *( glyphPositionsBuffer + primaryGlyphIndex ); + const Vector2& primaryPosition = *(glyphPositionsBuffer + primaryGlyphIndex); // Set the primary cursor's height. cursorInfo.primaryCursorHeight = cursorInfo.isSecondaryCursor ? 0.5f * glyphMetrics.fontHeight : glyphMetrics.fontHeight; @@ -676,27 +673,27 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, cursorInfo.primaryPosition.x += line.alignmentOffset; // Calculate the secondary cursor. - if( cursorInfo.isSecondaryCursor ) + if(cursorInfo.isSecondaryCursor) { // Set the secondary cursor's height. cursorInfo.secondaryCursorHeight = 0.5f * glyphMetrics.fontHeight; CharacterIndex index = characterIndex; - if( !isLastPositionOfLine ) + if(!isLastPositionOfLine) { - index = ( isRightToLeftParagraph == isCurrentRightToLeft ) ? nextCharacterIndex : characterIndex; + index = (isRightToLeftParagraph == isCurrentRightToLeft) ? nextCharacterIndex : characterIndex; } - const GlyphIndex secondaryGlyphIndex = *( charactersToGlyphBuffer + index ); - const Length secondaryNumberOfGlyphs = *( glyphsPerCharacterBuffer + index ); + const GlyphIndex secondaryGlyphIndex = *(charactersToGlyphBuffer + index); + const Length secondaryNumberOfGlyphs = *(glyphsPerCharacterBuffer + index); - const Vector2& secondaryPosition = *( glyphPositionsBuffer + secondaryGlyphIndex ); + const Vector2& secondaryPosition = *(glyphPositionsBuffer + secondaryGlyphIndex); - GetGlyphsMetrics( secondaryGlyphIndex, - secondaryNumberOfGlyphs, - glyphMetrics, - glyphInfoBuffer, - parameters.metrics ); + GetGlyphsMetrics(secondaryGlyphIndex, + secondaryNumberOfGlyphs, + glyphMetrics, + glyphInfoBuffer, + parameters.metrics); // Set the secondary cursor's position. @@ -716,10 +713,10 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, // P -> isRightToLeftParagraph // A -> Whether to add the glyph's advance. - const bool addGlyphAdvance = ( ( !isFirstPositionOfLine && !isCurrentRightToLeft ) || - ( isFirstPositionOfLine && !isRightToLeftParagraph ) ); + const bool addGlyphAdvance = ((!isFirstPositionOfLine && !isCurrentRightToLeft) || + (isFirstPositionOfLine && !isRightToLeftParagraph)); - cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + ( addGlyphAdvance ? glyphMetrics.advance : 0.f ); + cursorInfo.secondaryPosition.x = -glyphMetrics.xBearing + secondaryPosition.x + (addGlyphAdvance ? glyphMetrics.advance : 0.f); cursorInfo.secondaryPosition.y = cursorInfo.lineOffset + cursorInfo.lineHeight - cursorInfo.secondaryCursorHeight; // Transform the cursor info from line's coords to text's coords. @@ -728,16 +725,16 @@ void GetCursorPosition( GetCursorPositionParameters& parameters, } } -bool FindSelectionIndices( VisualModelPtr visualModel, - LogicalModelPtr logicalModel, - MetricsPtr metrics, - float visualX, - float visualY, - CharacterIndex& startIndex, - CharacterIndex& endIndex, - CharacterIndex& noTextHitIndex ) +bool FindSelectionIndices(VisualModelPtr visualModel, + LogicalModelPtr logicalModel, + MetricsPtr metrics, + float visualX, + float visualY, + CharacterIndex& startIndex, + CharacterIndex& endIndex, + CharacterIndex& noTextHitIndex) { -/* + /* Hit character Select |-------------------------------------------------------|------------------------------------------| | On a word | The word | @@ -748,36 +745,36 @@ bool FindSelectionIndices( VisualModelPtr visualModel, |-------------------------------------------------------|------------------------------------------| */ const Length totalNumberOfCharacters = logicalModel->mText.Count(); - startIndex = 0; - endIndex = 0; - noTextHitIndex = 0; + startIndex = 0; + endIndex = 0; + noTextHitIndex = 0; - if( 0 == totalNumberOfCharacters ) + if(0 == totalNumberOfCharacters) { // Nothing to do if the model is empty. return false; } - bool matchedCharacter = false; - CharacterIndex hitCharacter = Text::GetClosestCursorIndex( visualModel, - logicalModel, - metrics, - visualX, - visualY, - CharacterHitTest::TAP, - matchedCharacter ); + bool matchedCharacter = false; + CharacterIndex hitCharacter = Text::GetClosestCursorIndex(visualModel, + logicalModel, + metrics, + visualX, + visualY, + CharacterHitTest::TAP, + matchedCharacter); - if( !matchedCharacter ) + if(!matchedCharacter) { noTextHitIndex = hitCharacter; } - DALI_ASSERT_DEBUG( ( hitCharacter <= totalNumberOfCharacters ) && "GetClosestCursorIndex returned out of bounds index" ); + DALI_ASSERT_DEBUG((hitCharacter <= totalNumberOfCharacters) && "GetClosestCursorIndex returned out of bounds index"); - if( hitCharacter >= totalNumberOfCharacters ) + if(hitCharacter >= totalNumberOfCharacters) { // Closest hit character is the last character. - if( hitCharacter == totalNumberOfCharacters ) + if(hitCharacter == totalNumberOfCharacters) { hitCharacter--; //Hit character index set to last character in logical model } @@ -791,69 +788,69 @@ bool FindSelectionIndices( VisualModelPtr visualModel, const Character* const textBuffer = logicalModel->mText.Begin(); startIndex = hitCharacter; - endIndex = hitCharacter; + endIndex = hitCharacter; // Whether the hit character is a new paragraph character. - const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + hitCharacter ) ); + const bool isHitCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + hitCharacter)); // Whether the hit character is a white space. Note a new paragraph character is a white space as well but here is not wanted. - const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + hitCharacter ) ) && !isHitCharacterNewParagraph; + const bool isHitCharacterWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + hitCharacter)) && !isHitCharacterNewParagraph; - FindWordData data( textBuffer, - totalNumberOfCharacters, - hitCharacter, - isHitCharacterWhiteSpace, - isHitCharacterNewParagraph ); + FindWordData data(textBuffer, + totalNumberOfCharacters, + hitCharacter, + isHitCharacterWhiteSpace, + isHitCharacterNewParagraph); - if( isHitCharacterNewParagraph ) + if(isHitCharacterNewParagraph) { // Find the first character before the hit one which is not a new paragraph character. - if( hitCharacter > 0 ) + if(hitCharacter > 0) { endIndex = hitCharacter - 1u; - for( ; endIndex > 0; --endIndex ) + for(; endIndex > 0; --endIndex) { - const Dali::Toolkit::Text::Character character = *( data.textBuffer + endIndex ); + const Dali::Toolkit::Text::Character character = *(data.textBuffer + endIndex); - if( !Dali::TextAbstraction::IsNewParagraph( character ) ) + if(!Dali::TextAbstraction::IsNewParagraph(character)) { break; } } } - data.hitCharacter = endIndex; + data.hitCharacter = endIndex; data.isNewParagraph = false; - data.isWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + data.hitCharacter ) ); + data.isWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + data.hitCharacter)); } // Find the start of the word. - FindStartOfWord( data ); + FindStartOfWord(data); startIndex = data.foundIndex; // Find the end of the word. - FindEndOfWord( data ); + FindEndOfWord(data); endIndex = data.foundIndex; - if( 1u == ( endIndex - startIndex ) ) + if(1u == (endIndex - startIndex)) { - if( isHitCharacterWhiteSpace ) + if(isHitCharacterWhiteSpace) { // Select the word before or after the white space - if( 0 == hitCharacter ) + if(0 == hitCharacter) { data.isWhiteSpace = false; - FindEndOfWord( data ); + FindEndOfWord(data); endIndex = data.foundIndex; } - else if( hitCharacter > 0 ) + else if(hitCharacter > 0) { // Find the start of the word. data.hitCharacter = hitCharacter - 1u; data.isWhiteSpace = false; - FindStartOfWord( data ); + FindStartOfWord(data); startIndex = data.foundIndex; --endIndex; diff --git a/dali-toolkit/internal/text/decorator/text-decorator.cpp b/dali-toolkit/internal/text/decorator/text-decorator.cpp index 648c17a..237649a 100644 --- a/dali-toolkit/internal/text/decorator/text-decorator.cpp +++ b/dali-toolkit/internal/text/decorator/text-decorator.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,22 @@ #include // EXTERNAL INCLUDES +#include +#include #include #include #include -#include -#include #include +#include #include #include #include -#include // INTERNAL INCLUDES -#include #include #include #include +#include #ifdef DEBUG_ENABLED #define DECORATOR_DEBUG @@ -48,31 +48,30 @@ namespace Internal namespace { #ifdef DECORATOR_DEBUG -Integration::Log::Filter* gLogFilter( Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR") ); +Integration::Log::Filter* gLogFilter(Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_TEXT_DECORATOR")); #endif -} -} -} - +} // namespace +} // namespace Internal +} // namespace Dali // Local Data namespace { -const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE( 1.25f, 1.5f, 1.0f ); -const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE( 1.25f, 1.5f, 1.0f ); -const Dali::Vector3 ACTIVE_LAYER_ANCHOR_POINT( 0.5f, 0.5f, 0.5f ); +const Dali::Vector3 DEFAULT_GRAB_HANDLE_RELATIVE_SIZE(1.25f, 1.5f, 1.0f); +const Dali::Vector3 DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE(1.25f, 1.5f, 1.0f); +const Dali::Vector3 ACTIVE_LAYER_ANCHOR_POINT(0.5f, 0.5f, 0.5f); -const Dali::Vector4 LIGHT_BLUE( 0.75f, 0.96f, 1.f, 1.f ); // The text highlight color. TODO: due some problems, maybe with the blending function in the text clipping, the color is fully opaque. +const Dali::Vector4 LIGHT_BLUE(0.75f, 0.96f, 1.f, 1.f); // The text highlight color. TODO: due some problems, maybe with the blending function in the text clipping, the color is fully opaque. -const Dali::Vector4 HANDLE_COLOR( 0.0f, (183.0f / 255.0f), (229.0f / 255.0f), 1.0f ); +const Dali::Vector4 HANDLE_COLOR(0.0f, (183.0f / 255.0f), (229.0f / 255.0f), 1.0f); -const unsigned int CURSOR_BLINK_INTERVAL = 500u; ///< Cursor blink interval in milliseconds. -const float TO_MILLISECONDS = 1000.f; ///< Converts from seconds to milliseconds. -const float TO_SECONDS = 1.f / TO_MILLISECONDS; ///< Converts from milliseconds to seconds. +const unsigned int CURSOR_BLINK_INTERVAL = 500u; ///< Cursor blink interval in milliseconds. +const float TO_MILLISECONDS = 1000.f; ///< Converts from seconds to milliseconds. +const float TO_SECONDS = 1.f / TO_MILLISECONDS; ///< Converts from milliseconds to seconds. -const unsigned int SCROLL_TICK_INTERVAL = 50u; ///< Scroll interval in milliseconds. -const float SCROLL_THRESHOLD = 10.f; ///< Threshold in pixels close to the edges of the decorator boundaries from where the scroll timer starts to emit signals. -const float SCROLL_SPEED = 300.f; ///< The scroll speed in pixels/second. +const unsigned int SCROLL_TICK_INTERVAL = 50u; ///< Scroll interval in milliseconds. +const float SCROLL_THRESHOLD = 10.f; ///< Threshold in pixels close to the edges of the decorator boundaries from where the scroll timer starts to emit signals. +const float SCROLL_SPEED = 300.f; ///< The scroll speed in pixels/second. const float SCROLL_DISTANCE = SCROLL_SPEED * SCROLL_TICK_INTERVAL * TO_SECONDS; ///< Distance in pixels scrolled in one second. @@ -87,7 +86,7 @@ typedef Dali::Vector QuadContainer; * @param[in] boundingRectangle local bounding * @param[out] Vector4 World coordinate bounding Box. */ -void LocalToWorldCoordinatesBoundingBox( const Dali::Rect& boundingRectangle, Dali::Vector4& boundingBox ) +void LocalToWorldCoordinatesBoundingBox(const Dali::Rect& boundingRectangle, Dali::Vector4& boundingBox) { // Convert to world coordinates and store as a Vector4 to be compatible with Property Notifications. Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize(); @@ -95,20 +94,20 @@ void LocalToWorldCoordinatesBoundingBox( const Dali::Rect& boundingRectangl const float originX = boundingRectangle.x - 0.5f * stageSize.width; const float originY = boundingRectangle.y - 0.5f * stageSize.height; - boundingBox = Dali::Vector4( originX, - originY, - originX + boundingRectangle.width, - originY + boundingRectangle.height ); + boundingBox = Dali::Vector4(originX, + originY, + originX + boundingRectangle.width, + originY + boundingRectangle.height); } -void WorldToLocalCoordinatesBoundingBox( const Dali::Vector4& boundingBox, Dali::Rect& boundingRectangle ) +void WorldToLocalCoordinatesBoundingBox(const Dali::Vector4& boundingBox, Dali::Rect& boundingRectangle) { // Convert to local coordinates and store as a Dali::Rect. Dali::Vector2 stageSize = Dali::Stage::GetCurrent().GetSize(); - boundingRectangle.x = boundingBox.x + 0.5f * stageSize.width; - boundingRectangle.y = boundingBox.y + 0.5f * stageSize.height; - boundingRectangle.width = boundingBox.z - boundingBox.x; + boundingRectangle.x = boundingBox.x + 0.5f * stageSize.width; + boundingRectangle.y = boundingBox.y + 0.5f * stageSize.height; + boundingRectangle.width = boundingBox.z - boundingBox.x; boundingRectangle.height = boundingBox.w - boundingBox.y; } @@ -116,13 +115,10 @@ void WorldToLocalCoordinatesBoundingBox( const Dali::Vector4& boundingBox, Dali: namespace Dali { - namespace Toolkit { - namespace Text { - struct Decorator::Impl : public ConnectionTracker { enum ScrollDirection @@ -137,19 +133,19 @@ struct Decorator::Impl : public ConnectionTracker struct CursorImpl { CursorImpl() - : color( Dali::Color::BLACK ), + : color(Dali::Color::BLACK), position(), - cursorHeight( 0.0f ), - lineHeight( 0.0f ), - glyphOffset( 0.0f ) + cursorHeight(0.0f), + lineHeight(0.0f), + glyphOffset(0.0f) { } Vector4 color; Vector2 position; - float cursorHeight; - float lineHeight; - float glyphOffset; + float cursorHeight; + float lineHeight; + float glyphOffset; }; struct HandleImpl @@ -158,38 +154,38 @@ struct Decorator::Impl : public ConnectionTracker : position(), globalPosition(), size(), - lineHeight( 0.0f ), - grabDisplacementX( 0.f ), - grabDisplacementY( 0.f ), - active( false ), - horizontallyVisible( false ), - verticallyVisible( false ), - pressed( false ), - verticallyFlippedPreferred( false ), - horizontallyFlipped( false ), - verticallyFlipped( false ), - verticallyFlippedOnTouch( false ) + lineHeight(0.0f), + grabDisplacementX(0.f), + grabDisplacementY(0.f), + active(false), + horizontallyVisible(false), + verticallyVisible(false), + pressed(false), + verticallyFlippedPreferred(false), + horizontallyFlipped(false), + verticallyFlipped(false), + verticallyFlippedOnTouch(false) { } ImageView actor; - Actor grabArea; + Actor grabArea; ImageView markerActor; Vector2 position; Vector2 globalPosition; Size size; - float lineHeight; ///< Not the handle height + float lineHeight; ///< Not the handle height float grabDisplacementX; float grabDisplacementY; - bool active : 1; - bool horizontallyVisible : 1; - bool verticallyVisible : 1; - bool pressed : 1; + bool active : 1; + bool horizontallyVisible : 1; + bool verticallyVisible : 1; + bool pressed : 1; bool verticallyFlippedPreferred : 1; ///< Whether the handle is preferred to be vertically flipped. - bool horizontallyFlipped : 1; ///< Whether the handle has been horizontally flipped. - bool verticallyFlipped : 1; ///< Whether the handle has been vertically flipped. - bool verticallyFlippedOnTouch : 1; ///< Whether the handle is vertically flipped on touch. + bool horizontallyFlipped : 1; ///< Whether the handle has been horizontally flipped. + bool verticallyFlipped : 1; ///< Whether the handle has been vertically flipped. + bool verticallyFlippedOnTouch : 1; ///< Whether the handle is vertically flipped on touch. }; struct PopupImpl @@ -200,53 +196,53 @@ struct Decorator::Impl : public ConnectionTracker } TextSelectionPopup actor; - Vector3 position; + Vector3 position; }; - Impl( ControllerInterface& controller, - TextSelectionPopupCallbackInterface& callbackInterface ) - : mController( controller ), - mEnabledPopupButtons( TextSelectionPopup::NONE ), - mTextSelectionPopupCallbackInterface( callbackInterface ), - mHandleColor( HANDLE_COLOR ), + Impl(ControllerInterface& controller, + TextSelectionPopupCallbackInterface& callbackInterface) + : mController(controller), + mEnabledPopupButtons(TextSelectionPopup::NONE), + mTextSelectionPopupCallbackInterface(callbackInterface), + mHandleColor(HANDLE_COLOR), mBoundingBox(), - mHighlightColor( LIGHT_BLUE ), - mHighlightPosition( Vector2::ZERO ), - mHighlightSize( Vector2::ZERO ), - mControlSize( Vector2::ZERO ), - mHighlightOutlineOffset( 0.f ), - mActiveCursor( ACTIVE_CURSOR_NONE ), - mCursorBlinkInterval( CURSOR_BLINK_INTERVAL ), - mCursorBlinkDuration( 0.0f ), - mCursorWidth( CURSOR_WIDTH ), - mHandleScrolling( HANDLE_TYPE_COUNT ), - mHandleReleased( HANDLE_TYPE_COUNT ), - mScrollDirection( SCROLL_NONE ), - mScrollThreshold( SCROLL_THRESHOLD ), - mScrollSpeed( SCROLL_SPEED ), - mScrollDistance( SCROLL_DISTANCE ), - mTextDepth( 0u ), - mActiveCopyPastePopup( false ), - mPopupSetNewPosition( true ), - mCursorBlinkStatus( true ), - mDelayCursorBlink( false ), - mPrimaryCursorVisible( false ), - mSecondaryCursorVisible( false ), - mFlipSelectionHandlesOnCross( false ), - mFlipLeftSelectionHandleDirection( false ), - mFlipRightSelectionHandleDirection( false ), - mIsHandlePanning( false ), - mIsHandleCurrentlyCrossed( false ), - mIsHandlePreviouslyCrossed( false ), - mNotifyEndOfScroll( false ), - mHorizontalScrollingEnabled( false ), - mVerticalScrollingEnabled( false ), - mSmoothHandlePanEnabled( false ), - mIsHighlightBoxActive( false ), - mHidePrimaryCursorAndGrabHandle( false ) + mHighlightColor(LIGHT_BLUE), + mHighlightPosition(Vector2::ZERO), + mHighlightSize(Vector2::ZERO), + mControlSize(Vector2::ZERO), + mHighlightOutlineOffset(0.f), + mActiveCursor(ACTIVE_CURSOR_NONE), + mCursorBlinkInterval(CURSOR_BLINK_INTERVAL), + mCursorBlinkDuration(0.0f), + mCursorWidth(CURSOR_WIDTH), + mHandleScrolling(HANDLE_TYPE_COUNT), + mHandleReleased(HANDLE_TYPE_COUNT), + mScrollDirection(SCROLL_NONE), + mScrollThreshold(SCROLL_THRESHOLD), + mScrollSpeed(SCROLL_SPEED), + mScrollDistance(SCROLL_DISTANCE), + mTextDepth(0u), + mActiveCopyPastePopup(false), + mPopupSetNewPosition(true), + mCursorBlinkStatus(true), + mDelayCursorBlink(false), + mPrimaryCursorVisible(false), + mSecondaryCursorVisible(false), + mFlipSelectionHandlesOnCross(false), + mFlipLeftSelectionHandleDirection(false), + mFlipRightSelectionHandleDirection(false), + mIsHandlePanning(false), + mIsHandleCurrentlyCrossed(false), + mIsHandlePreviouslyCrossed(false), + mNotifyEndOfScroll(false), + mHorizontalScrollingEnabled(false), + mVerticalScrollingEnabled(false), + mSmoothHandlePanEnabled(false), + mIsHighlightBoxActive(false), + mHidePrimaryCursorAndGrabHandle(false) { - mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2; - mHighlightShader = Shader::New( SHADER_TEXT_DECORATOR_SHADER_VERT, SHADER_TEXT_DECORATOR_SHADER_FRAG ); + mQuadVertexFormat["aPosition"] = Property::VECTOR2; + mHighlightShader = Shader::New(SHADER_TEXT_DECORATOR_SHADER_VERT, SHADER_TEXT_DECORATOR_SHADER_FRAG); SetupGestures(); } @@ -254,7 +250,7 @@ struct Decorator::Impl : public ConnectionTracker * Relayout of the decorations owned by the decorator. * @param[in] size The Size of the UI control the decorator is adding it's decorations to. */ - void Relayout( const Vector2& size ) + void Relayout(const Vector2& size) { mControlSize = size; @@ -264,51 +260,49 @@ struct Decorator::Impl : public ConnectionTracker // Show or hide the cursors CreateCursors(); - if( mPrimaryCursor ) + if(mPrimaryCursor) { const CursorImpl& cursor = mCursor[PRIMARY_CURSOR]; - mPrimaryCursorVisible = (!mHidePrimaryCursorAndGrabHandle) && ( ( mControlSize.width - ( cursor.position.x + mCursorWidth ) > -Math::MACHINE_EPSILON_1000 ) && - ( cursor.position.x > -Math::MACHINE_EPSILON_1000 ) && - ( mControlSize.height - ( cursor.position.y + cursor.cursorHeight ) > -Math::MACHINE_EPSILON_1000 ) && - ( cursor.position.y > -Math::MACHINE_EPSILON_1000 ) ); - if( mPrimaryCursorVisible ) + mPrimaryCursorVisible = (!mHidePrimaryCursorAndGrabHandle) && ((mControlSize.width - (cursor.position.x + mCursorWidth) > -Math::MACHINE_EPSILON_1000) && + (cursor.position.x > -Math::MACHINE_EPSILON_1000) && + (mControlSize.height - (cursor.position.y + cursor.cursorHeight) > -Math::MACHINE_EPSILON_1000) && + (cursor.position.y > -Math::MACHINE_EPSILON_1000)); + if(mPrimaryCursorVisible) { - mPrimaryCursor.SetProperty( Actor::Property::POSITION, Vector2( cursor.position.x, - cursor.position.y ) ); - mPrimaryCursor.SetProperty( Actor::Property::SIZE, Size( mCursorWidth, cursor.cursorHeight ) ); + mPrimaryCursor.SetProperty(Actor::Property::POSITION, Vector2(cursor.position.x, cursor.position.y)); + mPrimaryCursor.SetProperty(Actor::Property::SIZE, Size(mCursorWidth, cursor.cursorHeight)); } - mPrimaryCursor.SetProperty( Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus ); + mPrimaryCursor.SetProperty(Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus); } - if( mSecondaryCursor ) + if(mSecondaryCursor) { const CursorImpl& cursor = mCursor[SECONDARY_CURSOR]; - mSecondaryCursorVisible = ( ( mControlSize.width - ( cursor.position.x + mCursorWidth ) > -Math::MACHINE_EPSILON_1000 ) && - ( cursor.position.x > -Math::MACHINE_EPSILON_1000 ) && - ( mControlSize.height - ( cursor.position.y + cursor.cursorHeight ) > -Math::MACHINE_EPSILON_1000 ) && - ( cursor.position.y > -Math::MACHINE_EPSILON_1000 ) ); - if( mSecondaryCursorVisible ) + mSecondaryCursorVisible = ((mControlSize.width - (cursor.position.x + mCursorWidth) > -Math::MACHINE_EPSILON_1000) && + (cursor.position.x > -Math::MACHINE_EPSILON_1000) && + (mControlSize.height - (cursor.position.y + cursor.cursorHeight) > -Math::MACHINE_EPSILON_1000) && + (cursor.position.y > -Math::MACHINE_EPSILON_1000)); + if(mSecondaryCursorVisible) { - mSecondaryCursor.SetProperty( Actor::Property::POSITION, Vector2( cursor.position.x, - cursor.position.y ) ); - mSecondaryCursor.SetProperty( Actor::Property::SIZE, Size( mCursorWidth, cursor.cursorHeight ) ); + mSecondaryCursor.SetProperty(Actor::Property::POSITION, Vector2(cursor.position.x, cursor.position.y)); + mSecondaryCursor.SetProperty(Actor::Property::SIZE, Size(mCursorWidth, cursor.cursorHeight)); } - mSecondaryCursor.SetProperty( Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus ); + mSecondaryCursor.SetProperty(Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus); } // Show or hide the grab handle - HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - bool newGrabHandlePosition = false; - grabHandle.horizontallyVisible = false; - grabHandle.verticallyVisible = false; - if( grabHandle.active ) + HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; + bool newGrabHandlePosition = false; + grabHandle.horizontallyVisible = false; + grabHandle.verticallyVisible = false; + if(grabHandle.active) { - grabHandle.horizontallyVisible = ( ( mControlSize.width - ( grabHandle.position.x + floor( 0.5f * mCursorWidth ) ) > -Math::MACHINE_EPSILON_1000 ) && - ( grabHandle.position.x > -Math::MACHINE_EPSILON_1000 ) ); - grabHandle.verticallyVisible = ( ( ( mControlSize.height - grabHandle.lineHeight ) - grabHandle.position.y > -Math::MACHINE_EPSILON_1000 ) && - ( grabHandle.position.y > -Math::MACHINE_EPSILON_1000 ) ); + grabHandle.horizontallyVisible = ((mControlSize.width - (grabHandle.position.x + floor(0.5f * mCursorWidth)) > -Math::MACHINE_EPSILON_1000) && + (grabHandle.position.x > -Math::MACHINE_EPSILON_1000)); + grabHandle.verticallyVisible = (((mControlSize.height - grabHandle.lineHeight) - grabHandle.position.y > -Math::MACHINE_EPSILON_1000) && + (grabHandle.position.y > -Math::MACHINE_EPSILON_1000)); const bool isVisible = grabHandle.horizontallyVisible && grabHandle.verticallyVisible && (!mHidePrimaryCursorAndGrabHandle); - if( isVisible ) + if(isVisible) { CreateGrabHandle(); @@ -316,122 +310,121 @@ struct Decorator::Impl : public ConnectionTracker SetGrabHandlePosition(); // Sets the grab handle image according if it's pressed, flipped, etc. - SetHandleImage( GRAB_HANDLE ); + SetHandleImage(GRAB_HANDLE); newGrabHandlePosition = true; } - if( grabHandle.actor ) + if(grabHandle.actor) { - grabHandle.actor.SetProperty( Actor::Property::VISIBLE, isVisible ); + grabHandle.actor.SetProperty(Actor::Property::VISIBLE, isVisible); } } - else if( grabHandle.actor ) + else if(grabHandle.actor) { grabHandle.actor.Unparent(); } // Show or hide the selection handles/highlight - HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ]; - HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ]; - bool newPrimaryHandlePosition = false; - bool newSecondaryHandlePosition = false; - - primary.horizontallyVisible = ( ( mControlSize.width - primary.position.x > -Math::MACHINE_EPSILON_1000 ) && - ( primary.position.x > -Math::MACHINE_EPSILON_1000 ) ); - primary.verticallyVisible = ( ( ( mControlSize.height - primary.lineHeight ) - primary.position.y > -Math::MACHINE_EPSILON_1000 ) && - ( primary.position.y + ( primary.verticallyFlipped ? 0.f : primary.lineHeight ) > -Math::MACHINE_EPSILON_1000 ) ); - secondary.horizontallyVisible = ( ( mControlSize.width - secondary.position.x > -Math::MACHINE_EPSILON_1000 ) && - ( secondary.position.x > -Math::MACHINE_EPSILON_1000 ) ); - secondary.verticallyVisible = ( ( ( mControlSize.height - secondary.lineHeight ) - secondary.position.y > -Math::MACHINE_EPSILON_1000 ) && - ( secondary.position.y + ( secondary.verticallyFlipped ? 0.f : secondary.lineHeight ) > -Math::MACHINE_EPSILON_1000 ) ); - - const bool primaryVisible = primary.horizontallyVisible && primary.verticallyVisible; + HandleImpl& primary = mHandle[LEFT_SELECTION_HANDLE]; + HandleImpl& secondary = mHandle[RIGHT_SELECTION_HANDLE]; + bool newPrimaryHandlePosition = false; + bool newSecondaryHandlePosition = false; + + primary.horizontallyVisible = ((mControlSize.width - primary.position.x > -Math::MACHINE_EPSILON_1000) && + (primary.position.x > -Math::MACHINE_EPSILON_1000)); + primary.verticallyVisible = (((mControlSize.height - primary.lineHeight) - primary.position.y > -Math::MACHINE_EPSILON_1000) && + (primary.position.y + (primary.verticallyFlipped ? 0.f : primary.lineHeight) > -Math::MACHINE_EPSILON_1000)); + secondary.horizontallyVisible = ((mControlSize.width - secondary.position.x > -Math::MACHINE_EPSILON_1000) && + (secondary.position.x > -Math::MACHINE_EPSILON_1000)); + secondary.verticallyVisible = (((mControlSize.height - secondary.lineHeight) - secondary.position.y > -Math::MACHINE_EPSILON_1000) && + (secondary.position.y + (secondary.verticallyFlipped ? 0.f : secondary.lineHeight) > -Math::MACHINE_EPSILON_1000)); + + const bool primaryVisible = primary.horizontallyVisible && primary.verticallyVisible; const bool secondaryVisible = secondary.horizontallyVisible && secondary.verticallyVisible; - if( primary.active || secondary.active ) + if(primary.active || secondary.active) { - if( primaryVisible || secondaryVisible ) + if(primaryVisible || secondaryVisible) { CreateSelectionHandles(); - if( primaryVisible ) + if(primaryVisible) { - SetSelectionHandlePosition( LEFT_SELECTION_HANDLE ); + SetSelectionHandlePosition(LEFT_SELECTION_HANDLE); // Sets the primary handle image according if it's pressed, flipped, etc. - SetHandleImage( LEFT_SELECTION_HANDLE ); + SetHandleImage(LEFT_SELECTION_HANDLE); - SetSelectionHandleMarkerSize( primary ); + SetSelectionHandleMarkerSize(primary); newPrimaryHandlePosition = true; } - if( secondaryVisible ) + if(secondaryVisible) { - SetSelectionHandlePosition( RIGHT_SELECTION_HANDLE ); + SetSelectionHandlePosition(RIGHT_SELECTION_HANDLE); // Sets the secondary handle image according if it's pressed, flipped, etc. - SetHandleImage( RIGHT_SELECTION_HANDLE ); + SetHandleImage(RIGHT_SELECTION_HANDLE); - SetSelectionHandleMarkerSize( secondary ); + SetSelectionHandleMarkerSize(secondary); newSecondaryHandlePosition = true; } } - if( primary.actor ) + if(primary.actor) { - primary.actor.SetProperty( Actor::Property::VISIBLE, primaryVisible ); + primary.actor.SetProperty(Actor::Property::VISIBLE, primaryVisible); } - if( secondary.actor ) + if(secondary.actor) { - secondary.actor.SetProperty( Actor::Property::VISIBLE, secondaryVisible ); + secondary.actor.SetProperty(Actor::Property::VISIBLE, secondaryVisible); } - } else { - if( primary.actor ) + if(primary.actor) { primary.actor.Unparent(); } - if( secondary.actor ) + if(secondary.actor) { secondary.actor.Unparent(); } } - if( mIsHighlightBoxActive ) + if(mIsHighlightBoxActive) { CreateHighlight(); UpdateHighlight(); } else { - if( mHighlightActor ) + if(mHighlightActor) { mHighlightActor.Unparent(); } } - if( newGrabHandlePosition || - newPrimaryHandlePosition || - newSecondaryHandlePosition ) + if(newGrabHandlePosition || + newPrimaryHandlePosition || + newSecondaryHandlePosition) { // Setup property notifications to find whether the handles leave the boundaries of the current display. SetupActiveLayerPropertyNotifications(); } - if( mActiveCopyPastePopup && - ( primaryVisible || secondaryVisible ) ) + if(mActiveCopyPastePopup && + (primaryVisible || secondaryVisible)) { ShowPopup(); mPopupSetNewPosition = true; } else { - if( mCopyPastePopup.actor ) + if(mCopyPastePopup.actor) { mCopyPastePopup.actor.HidePopup(); mPopupSetNewPosition = true; @@ -439,63 +432,63 @@ struct Decorator::Impl : public ConnectionTracker } } - void UpdatePositions( const Vector2& scrollOffset ) + void UpdatePositions(const Vector2& scrollOffset) { mCursor[PRIMARY_CURSOR].position += scrollOffset; mCursor[SECONDARY_CURSOR].position += scrollOffset; - mHandle[ GRAB_HANDLE ].position += scrollOffset; - mHandle[ LEFT_SELECTION_HANDLE ].position += scrollOffset; - mHandle[ RIGHT_SELECTION_HANDLE ].position += scrollOffset; + mHandle[GRAB_HANDLE].position += scrollOffset; + mHandle[LEFT_SELECTION_HANDLE].position += scrollOffset; + mHandle[RIGHT_SELECTION_HANDLE].position += scrollOffset; mHighlightPosition += scrollOffset; } void ShowPopup() { - if( !mCopyPastePopup.actor ) + if(!mCopyPastePopup.actor) { return; } - if( !mCopyPastePopup.actor.GetParent() ) + if(!mCopyPastePopup.actor.GetParent()) { - mActiveLayer.Add( mCopyPastePopup.actor ); + mActiveLayer.Add(mCopyPastePopup.actor); } - mCopyPastePopup.actor.RaiseAbove( mActiveLayer ); + mCopyPastePopup.actor.RaiseAbove(mActiveLayer); mCopyPastePopup.actor.ShowPopup(); } - float CalculateVerticalPopUpPosition( float halfHeight, bool preferBelow ) + float CalculateVerticalPopUpPosition(float halfHeight, bool preferBelow) { float yPosition = 0.f; - const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; + const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE]; - const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; + const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - if( primaryHandle.active || secondaryHandle.active ) + if(primaryHandle.active || secondaryHandle.active) { // The origin of the decorator's coordinate system in world coords. - const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ) - mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * ACTIVE_LAYER_ANCHOR_POINT; + const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty(Actor::Property::WORLD_POSITION) - mActiveLayer.GetCurrentProperty(Actor::Property::SIZE) * ACTIVE_LAYER_ANCHOR_POINT; - if( preferBelow ) + if(preferBelow) { // Find out if there is enough space for the popup at the bottom. - const float primaryBelowY = primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height; + const float primaryBelowY = primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height; const float secondaryBelowY = secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height; - float maxY = std::max( primaryBelowY, secondaryBelowY ); + float maxY = std::max(primaryBelowY, secondaryBelowY); yPosition = halfHeight + maxY; - if( originWorldCoords.y + yPosition + halfHeight > mBoundingBox.w ) + if(originWorldCoords.y + yPosition + halfHeight > mBoundingBox.w) { // Does not fit below. // Try to fit first below the non active handle. Otherwise above the active handle. - if( RIGHT_SELECTION_HANDLE == mHandleReleased ) + if(RIGHT_SELECTION_HANDLE == mHandleReleased) { - if( primaryBelowY < secondaryBelowY ) + if(primaryBelowY < secondaryBelowY) { yPosition = halfHeight + primaryBelowY; } @@ -504,9 +497,9 @@ struct Decorator::Impl : public ConnectionTracker yPosition = primaryHandle.position.y - primaryHandle.size.height - halfHeight; } } - else if( LEFT_SELECTION_HANDLE == mHandleReleased ) + else if(LEFT_SELECTION_HANDLE == mHandleReleased) { - if( secondaryBelowY < primaryBelowY ) + if(secondaryBelowY < primaryBelowY) { yPosition = halfHeight + secondaryBelowY; } @@ -517,12 +510,12 @@ struct Decorator::Impl : public ConnectionTracker } // Check the handle is whithin the decoration box. - if( originWorldCoords.y + yPosition < mBoundingBox.y ) + if(originWorldCoords.y + yPosition < mBoundingBox.y) { yPosition = mBoundingBox.y - originWorldCoords.y + halfHeight; } - if( originWorldCoords.y + yPosition > mBoundingBox.w ) + if(originWorldCoords.y + yPosition > mBoundingBox.w) { yPosition = mBoundingBox.w - originWorldCoords.y - halfHeight; } @@ -531,17 +524,17 @@ struct Decorator::Impl : public ConnectionTracker else { // Find out if there is enough space for the popup at the top. - const float primaryTopY = primaryHandle.position.y - primaryHandle.size.height; + const float primaryTopY = primaryHandle.position.y - primaryHandle.size.height; const float secondaryTopY = secondaryHandle.position.y - secondaryHandle.size.height; - float minY = std::min( primaryTopY, secondaryTopY ); + float minY = std::min(primaryTopY, secondaryTopY); yPosition = -halfHeight + minY; } // !preferBelow - } // ( primaryHandle.active || secondaryHandle.active ) - else if( grabHandle.active ) + } // ( primaryHandle.active || secondaryHandle.active ) + else if(grabHandle.active) { - if( preferBelow ) + if(preferBelow) { yPosition = halfHeight + grabHandle.lineHeight + grabHandle.size.height + grabHandle.position.y; } @@ -554,102 +547,102 @@ struct Decorator::Impl : public ConnectionTracker return yPosition; } - void ConstrainPopupPosition( const Vector3& popupHalfSize ) + void ConstrainPopupPosition(const Vector3& popupHalfSize) { // Check if the popup is within the boundaries of the decoration box. // Check first the horizontal dimension. If is not within the boundaries, it calculates the offset. // The origin of the decorator's coordinate system in world coords. - const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ) - mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ) * ACTIVE_LAYER_ANCHOR_POINT; + const Vector3 originWorldCoords = mActiveLayer.GetCurrentProperty(Actor::Property::WORLD_POSITION) - mActiveLayer.GetCurrentProperty(Actor::Property::SIZE) * ACTIVE_LAYER_ANCHOR_POINT; // The popup's position in world coords. Vector3 popupPositionWorldCoords = originWorldCoords + mCopyPastePopup.position; - if( popupPositionWorldCoords.x - popupHalfSize.width < mBoundingBox.x ) + if(popupPositionWorldCoords.x - popupHalfSize.width < mBoundingBox.x) { - mCopyPastePopup.position.x += mBoundingBox.x - ( popupPositionWorldCoords.x - popupHalfSize.width ); + mCopyPastePopup.position.x += mBoundingBox.x - (popupPositionWorldCoords.x - popupHalfSize.width); } - else if( popupPositionWorldCoords.x + popupHalfSize.width > mBoundingBox.z ) + else if(popupPositionWorldCoords.x + popupHalfSize.width > mBoundingBox.z) { - mCopyPastePopup.position.x += mBoundingBox.z - ( popupPositionWorldCoords.x + popupHalfSize.width ); + mCopyPastePopup.position.x += mBoundingBox.z - (popupPositionWorldCoords.x + popupHalfSize.width); } // Check the vertical dimension. If the popup doesn't fit above the handles, it looks for a valid position below. - if( popupPositionWorldCoords.y - popupHalfSize.height < mBoundingBox.y ) + if(popupPositionWorldCoords.y - popupHalfSize.height < mBoundingBox.y) { - mCopyPastePopup.position.y = CalculateVerticalPopUpPosition( popupHalfSize.height, true ); // true -> prefer to set the popup's position below. + mCopyPastePopup.position.y = CalculateVerticalPopUpPosition(popupHalfSize.height, true); // true -> prefer to set the popup's position below. } } - void SetPopupPosition( Actor actor ) + void SetPopupPosition(Actor actor) { - if( !mActiveCopyPastePopup ) + if(!mActiveCopyPastePopup) { return; } // Retrieves the popup's size after relayout. - const Vector3 popupSize( mCopyPastePopup.actor.GetRelayoutSize( Dimension::WIDTH ), mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT ), 0.0f ); + const Vector3 popupSize(mCopyPastePopup.actor.GetRelayoutSize(Dimension::WIDTH), mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT), 0.0f); const Vector3 popupHalfSize = popupSize * 0.5f; - if( mPopupSetNewPosition ) + if(mPopupSetNewPosition) { - const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; + const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE]; - const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; + const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - if( primaryHandle.active || secondaryHandle.active ) + if(primaryHandle.active || secondaryHandle.active) { - const float minHandleXPosition = std::min( primaryHandle.position.x, secondaryHandle.position.x ); - const float maxHandleXPosition = std::max( primaryHandle.position.x, secondaryHandle.position.x ); + const float minHandleXPosition = std::min(primaryHandle.position.x, secondaryHandle.position.x); + const float maxHandleXPosition = std::max(primaryHandle.position.x, secondaryHandle.position.x); - mCopyPastePopup.position.x = minHandleXPosition + ( ( maxHandleXPosition - minHandleXPosition ) * 0.5f ); + mCopyPastePopup.position.x = minHandleXPosition + ((maxHandleXPosition - minHandleXPosition) * 0.5f); - const float primaryY = -popupHalfSize.height + primaryHandle.position.y - ( primaryHandle.verticallyFlipped ? primaryHandle.size.height : POPUP_PADDING ); - const float secondaryY = -popupHalfSize.height + secondaryHandle.position.y - ( secondaryHandle.verticallyFlipped ? secondaryHandle.size.height : POPUP_PADDING ); + const float primaryY = -popupHalfSize.height + primaryHandle.position.y - (primaryHandle.verticallyFlipped ? primaryHandle.size.height : POPUP_PADDING); + const float secondaryY = -popupHalfSize.height + secondaryHandle.position.y - (secondaryHandle.verticallyFlipped ? secondaryHandle.size.height : POPUP_PADDING); - mCopyPastePopup.position.y = std::min( primaryY, secondaryY ); + mCopyPastePopup.position.y = std::min(primaryY, secondaryY); } - else if( grabHandle.active ) + else if(grabHandle.active) { mCopyPastePopup.position.x = grabHandle.position.x; - mCopyPastePopup.position.y = -popupHalfSize.height + grabHandle.position.y - ( grabHandle.verticallyFlipped ? grabHandle.size.height : POPUP_PADDING ); + mCopyPastePopup.position.y = -popupHalfSize.height + grabHandle.position.y - (grabHandle.verticallyFlipped ? grabHandle.size.height : POPUP_PADDING); } } // mPopupSetNewPosition // It may change the popup's position to fit within the decoration box. - ConstrainPopupPosition( popupHalfSize ); + ConstrainPopupPosition(popupHalfSize); - SetUpPopupPositionNotifications( popupHalfSize ); + SetUpPopupPositionNotifications(popupHalfSize); // Prevent pixel mis-alignment by rounding down. - mCopyPastePopup.position.x = floorf( mCopyPastePopup.position.x ); - mCopyPastePopup.position.y = floorf( mCopyPastePopup.position.y ); + mCopyPastePopup.position.x = floorf(mCopyPastePopup.position.x); + mCopyPastePopup.position.y = floorf(mCopyPastePopup.position.y); - mCopyPastePopup.actor.SetProperty( Actor::Property::POSITION, mCopyPastePopup.position ); + mCopyPastePopup.actor.SetProperty(Actor::Property::POSITION, mCopyPastePopup.position); mPopupSetNewPosition = false; } - void CreateCursor( Control& cursor, const Vector4& color ) + void CreateCursor(Control& cursor, const Vector4& color) { cursor = Control::New(); - cursor.SetBackgroundColor( color ); - cursor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - cursor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); + cursor.SetBackgroundColor(color); + cursor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + cursor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); } // Add or Remove cursor(s) from parent void CreateCursors() { - if( mActiveCursor == ACTIVE_CURSOR_NONE ) + if(mActiveCursor == ACTIVE_CURSOR_NONE) { - if( mPrimaryCursor ) + if(mPrimaryCursor) { mPrimaryCursor.Unparent(); } - if( mSecondaryCursor ) + if(mSecondaryCursor) { mSecondaryCursor.Unparent(); } @@ -657,41 +650,41 @@ struct Decorator::Impl : public ConnectionTracker else { // Create Primary and or Secondary Cursor(s) if active and add to parent - if ( mActiveCursor == ACTIVE_CURSOR_PRIMARY || - mActiveCursor == ACTIVE_CURSOR_BOTH ) + if(mActiveCursor == ACTIVE_CURSOR_PRIMARY || + mActiveCursor == ACTIVE_CURSOR_BOTH) { - if ( !mPrimaryCursor ) + if(!mPrimaryCursor) { - CreateCursor( mPrimaryCursor, mCursor[PRIMARY_CURSOR].color ); + CreateCursor(mPrimaryCursor, mCursor[PRIMARY_CURSOR].color); #ifdef DECORATOR_DEBUG - mPrimaryCursor.SetProperty( Dali::Actor::Property::NAME, "PrimaryCursorActor" ); + mPrimaryCursor.SetProperty(Dali::Actor::Property::NAME, "PrimaryCursorActor"); #endif } - if( !mPrimaryCursor.GetParent() ) + if(!mPrimaryCursor.GetParent()) { - mActiveLayer.Add( mPrimaryCursor ); + mActiveLayer.Add(mPrimaryCursor); } } - if ( mActiveCursor == ACTIVE_CURSOR_BOTH ) + if(mActiveCursor == ACTIVE_CURSOR_BOTH) { - if ( !mSecondaryCursor ) + if(!mSecondaryCursor) { - CreateCursor( mSecondaryCursor, mCursor[SECONDARY_CURSOR].color ); + CreateCursor(mSecondaryCursor, mCursor[SECONDARY_CURSOR].color); #ifdef DECORATOR_DEBUG - mSecondaryCursor.SetProperty( Dali::Actor::Property::NAME, "SecondaryCursorActor" ); + mSecondaryCursor.SetProperty(Dali::Actor::Property::NAME, "SecondaryCursorActor"); #endif } - if( !mSecondaryCursor.GetParent() ) + if(!mSecondaryCursor.GetParent()) { - mActiveLayer.Add( mSecondaryCursor ); + mActiveLayer.Add(mSecondaryCursor); } } else { - if( mSecondaryCursor ) + if(mSecondaryCursor) { mSecondaryCursor.Unparent(); } @@ -701,16 +694,16 @@ struct Decorator::Impl : public ConnectionTracker bool OnCursorBlinkTimerTick() { - if( !mDelayCursorBlink ) + if(!mDelayCursorBlink) { // Cursor blinking - if ( mPrimaryCursor ) + if(mPrimaryCursor) { - mPrimaryCursor.SetProperty( Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus ); + mPrimaryCursor.SetProperty(Actor::Property::VISIBLE, mPrimaryCursorVisible && mCursorBlinkStatus); } - if ( mSecondaryCursor ) + if(mSecondaryCursor) { - mSecondaryCursor.SetProperty( Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus ); + mSecondaryCursor.SetProperty(Actor::Property::VISIBLE, mSecondaryCursorVisible && mCursorBlinkStatus); } mCursorBlinkStatus = !mCursorBlinkStatus; @@ -730,225 +723,225 @@ struct Decorator::Impl : public ConnectionTracker mTapDetector = TapGestureDetector::New(); // Will consume double tap gestures on handles. - mTapDetector.SetMaximumTapsRequired( 2u ); + mTapDetector.SetMaximumTapsRequired(2u); // Will consume long press gestures on handles. mLongPressDetector = LongPressGestureDetector::New(); // Detects pan gestures on handles. mPanDetector = PanGestureDetector::New(); - mPanDetector.DetectedSignal().Connect( this, &Decorator::Impl::OnPan ); + mPanDetector.DetectedSignal().Connect(this, &Decorator::Impl::OnPan); } void CreateActiveLayer() { - if( !mActiveLayer ) + if(!mActiveLayer) { mActiveLayer = Actor::New(); #ifdef DECORATOR_DEBUG - mActiveLayer.SetProperty( Actor::Property::NAME, "ActiveLayerActor" ); + mActiveLayer.SetProperty(Actor::Property::NAME, "ActiveLayerActor"); #endif - mActiveLayer.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mActiveLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); + mActiveLayer.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mActiveLayer.SetResizePolicy(ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS); // Add the active layer telling the controller it doesn't need clipping. - mController.AddDecoration( mActiveLayer, false ); + mController.AddDecoration(mActiveLayer, false); } mActiveLayer.RaiseToTop(); } - void SetSelectionHandleMarkerSize( HandleImpl& handle ) + void SetSelectionHandleMarkerSize(HandleImpl& handle) { - if( handle.markerActor ) + if(handle.markerActor) { - handle.markerActor.SetProperty( Actor::Property::SIZE, Vector2( 0, handle.lineHeight ) ); + handle.markerActor.SetProperty(Actor::Property::SIZE, Vector2(0, handle.lineHeight)); } } void CreateGrabHandle() { HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - if( !grabHandle.actor ) + if(!grabHandle.actor) { - if( mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED].size() ) + if(mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED].size()) { - grabHandle.actor = ImageView::New( mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED] ); - GetImpl( grabHandle.actor).SetDepthIndex( DepthIndex::DECORATION ); - grabHandle.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER ); + grabHandle.actor = ImageView::New(mHandleImages[GRAB_HANDLE][HANDLE_IMAGE_RELEASED]); + GetImpl(grabHandle.actor).SetDepthIndex(DepthIndex::DECORATION); + grabHandle.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER); // Area that Grab handle responds to, larger than actual handle so easier to move #ifdef DECORATOR_DEBUG - grabHandle.actor.SetProperty( Dali::Actor::Property::NAME, "GrabHandleActor" ); - if ( Dali::Internal::gLogFilter->IsEnabledFor( Debug::Verbose ) ) + grabHandle.actor.SetProperty(Dali::Actor::Property::NAME, "GrabHandleActor"); + if(Dali::Internal::gLogFilter->IsEnabledFor(Debug::Verbose)) { - grabHandle.grabArea = Control::New(); - Toolkit::Control control = Toolkit::Control::DownCast( grabHandle.grabArea ); - control.SetBackgroundColor( Vector4( 1.0f, 1.0f, 1.0f, 0.5f ) ); - grabHandle.grabArea.SetProperty( Dali::Actor::Property::NAME, "GrabArea" ); + grabHandle.grabArea = Control::New(); + Toolkit::Control control = Toolkit::Control::DownCast(grabHandle.grabArea); + control.SetBackgroundColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f)); + grabHandle.grabArea.SetProperty(Dali::Actor::Property::NAME, "GrabArea"); } else { grabHandle.grabArea = Actor::New(); - grabHandle.grabArea.SetProperty( Dali::Actor::Property::NAME, "GrabArea" ); + grabHandle.grabArea.SetProperty(Dali::Actor::Property::NAME, "GrabArea"); } #else grabHandle.grabArea = Actor::New(); #endif - grabHandle.grabArea.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); - grabHandle.grabArea.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER ); - grabHandle.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS ); - grabHandle.grabArea.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_GRAB_HANDLE_RELATIVE_SIZE ); - grabHandle.actor.Add( grabHandle.grabArea ); - grabHandle.actor.SetProperty( Actor::Property::COLOR, mHandleColor ); + grabHandle.grabArea.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER); + grabHandle.grabArea.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER); + grabHandle.grabArea.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS); + grabHandle.grabArea.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_GRAB_HANDLE_RELATIVE_SIZE); + grabHandle.actor.Add(grabHandle.grabArea); + grabHandle.actor.SetProperty(Actor::Property::COLOR, mHandleColor); - grabHandle.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnGrabHandleTouched ); + grabHandle.grabArea.TouchedSignal().Connect(this, &Decorator::Impl::OnGrabHandleTouched); // The grab handle's actor is attached to the tap and long press detectors in order to consume these events. // Note that no callbacks are connected to any signal emitted by the tap and long press detectors. - mTapDetector.Attach( grabHandle.actor ); - mLongPressDetector.Attach( grabHandle.actor ); + mTapDetector.Attach(grabHandle.actor); + mLongPressDetector.Attach(grabHandle.actor); // The grab handle's area is attached to the pan detector. // The OnPan() method is connected to the signals emitted by the pan detector. - mPanDetector.Attach( grabHandle.grabArea ); + mPanDetector.Attach(grabHandle.grabArea); - mActiveLayer.Add( grabHandle.actor ); + mActiveLayer.Add(grabHandle.actor); } } - if( grabHandle.actor && !grabHandle.actor.GetParent() ) + if(grabHandle.actor && !grabHandle.actor.GetParent()) { - mActiveLayer.Add( grabHandle.actor ); + mActiveLayer.Add(grabHandle.actor); } } - void CreateHandleMarker( HandleImpl& handle, const std::string& image, HandleType handleType ) + void CreateHandleMarker(HandleImpl& handle, const std::string& image, HandleType handleType) { - if( image.size() ) + if(image.size()) { - handle.markerActor = ImageView::New( image ); - handle.markerActor.SetProperty( Actor::Property::COLOR, mHandleColor ); - handle.actor.Add( handle.markerActor ); + handle.markerActor = ImageView::New(image); + handle.markerActor.SetProperty(Actor::Property::COLOR, mHandleColor); + handle.actor.Add(handle.markerActor); - handle.markerActor.SetResizePolicy ( ResizePolicy::FIXED, Dimension::HEIGHT ); + handle.markerActor.SetResizePolicy(ResizePolicy::FIXED, Dimension::HEIGHT); - if( LEFT_SELECTION_HANDLE == handleType ) + if(LEFT_SELECTION_HANDLE == handleType) { - handle.markerActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_RIGHT ); - handle.markerActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT ); + handle.markerActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_RIGHT); + handle.markerActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_RIGHT); } - else if( RIGHT_SELECTION_HANDLE == handleType ) + else if(RIGHT_SELECTION_HANDLE == handleType) { - handle.markerActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_LEFT ); - handle.markerActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); + handle.markerActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_LEFT); + handle.markerActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); } } } void CreateSelectionHandles() { - HandleImpl& primary = mHandle[ LEFT_SELECTION_HANDLE ]; - if( !primary.actor ) + HandleImpl& primary = mHandle[LEFT_SELECTION_HANDLE]; + if(!primary.actor) { - if( mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size() ) + if(mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size()) { - primary.actor = ImageView::New( mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] ); + primary.actor = ImageView::New(mHandleImages[LEFT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED]); #ifdef DECORATOR_DEBUG - primary.actor.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleOne"); + primary.actor.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleOne"); #endif - primary.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT ); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text. - GetImpl( primary.actor ).SetDepthIndex( DepthIndex::DECORATION ); - primary.actor.SetProperty( Actor::Property::COLOR, mHandleColor ); + primary.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_RIGHT); // Change to BOTTOM_RIGHT if Look'n'Feel requires handle above text. + GetImpl(primary.actor).SetDepthIndex(DepthIndex::DECORATION); + primary.actor.SetProperty(Actor::Property::COLOR, mHandleColor); primary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move #ifdef DECORATOR_DEBUG - primary.grabArea.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleOneGrabArea"); + primary.grabArea.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleOneGrabArea"); #endif - primary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS ); - primary.grabArea.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); - primary.grabArea.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER ); - primary.grabArea.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE ); + primary.grabArea.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS); + primary.grabArea.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER); + primary.grabArea.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER); + primary.grabArea.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE); - primary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleOneTouched ); + primary.grabArea.TouchedSignal().Connect(this, &Decorator::Impl::OnHandleOneTouched); // The handle's actor is attached to the tap and long press detectors in order to consume these events. // Note that no callbacks are connected to any signal emitted by the tap and long press detectors. - mTapDetector.Attach( primary.actor ); - mLongPressDetector.Attach( primary.actor ); + mTapDetector.Attach(primary.actor); + mLongPressDetector.Attach(primary.actor); // The handle's area is attached to the pan detector. // The OnPan() method is connected to the signals emitted by the pan detector. - mPanDetector.Attach( primary.grabArea ); + mPanDetector.Attach(primary.grabArea); - primary.actor.Add( primary.grabArea ); + primary.actor.Add(primary.grabArea); - CreateHandleMarker( primary, mHandleImages[LEFT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], LEFT_SELECTION_HANDLE ); + CreateHandleMarker(primary, mHandleImages[LEFT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], LEFT_SELECTION_HANDLE); } } - if( primary.actor && !primary.actor.GetParent() ) + if(primary.actor && !primary.actor.GetParent()) { - mActiveLayer.Add( primary.actor ); + mActiveLayer.Add(primary.actor); } - HandleImpl& secondary = mHandle[ RIGHT_SELECTION_HANDLE ]; - if( !secondary.actor ) + HandleImpl& secondary = mHandle[RIGHT_SELECTION_HANDLE]; + if(!secondary.actor) { - if( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size() ) + if(mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED].size()) { - secondary.actor = ImageView::New( mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED] ); + secondary.actor = ImageView::New(mHandleImages[RIGHT_SELECTION_HANDLE][HANDLE_IMAGE_RELEASED]); #ifdef DECORATOR_DEBUG - secondary.actor.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleTwo"); + secondary.actor.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleTwo"); #endif - secondary.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text. - GetImpl( secondary.actor ).SetDepthIndex( DepthIndex::DECORATION ); - secondary.actor.SetProperty( Actor::Property::COLOR, mHandleColor ); + secondary.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); // Change to BOTTOM_LEFT if Look'n'Feel requires handle above text. + GetImpl(secondary.actor).SetDepthIndex(DepthIndex::DECORATION); + secondary.actor.SetProperty(Actor::Property::COLOR, mHandleColor); secondary.grabArea = Actor::New(); // Area that Grab handle responds to, larger than actual handle so easier to move #ifdef DECORATOR_DEBUG - secondary.grabArea.SetProperty( Dali::Actor::Property::NAME,"SelectionHandleTwoGrabArea"); + secondary.grabArea.SetProperty(Dali::Actor::Property::NAME, "SelectionHandleTwoGrabArea"); #endif - secondary.grabArea.SetResizePolicy( ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS ); - secondary.grabArea.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); - secondary.grabArea.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER ); - secondary.grabArea.SetProperty( Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE ); + secondary.grabArea.SetResizePolicy(ResizePolicy::SIZE_RELATIVE_TO_PARENT, Dimension::ALL_DIMENSIONS); + secondary.grabArea.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER); + secondary.grabArea.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER); + secondary.grabArea.SetProperty(Actor::Property::SIZE_MODE_FACTOR, DEFAULT_SELECTION_HANDLE_RELATIVE_SIZE); - secondary.grabArea.TouchedSignal().Connect( this, &Decorator::Impl::OnHandleTwoTouched ); + secondary.grabArea.TouchedSignal().Connect(this, &Decorator::Impl::OnHandleTwoTouched); // The handle's actor is attached to the tap and long press detectors in order to consume these events. // Note that no callbacks are connected to any signal emitted by the tap and long press detectors. - mTapDetector.Attach( secondary.actor ); - mLongPressDetector.Attach( secondary.actor ); + mTapDetector.Attach(secondary.actor); + mLongPressDetector.Attach(secondary.actor); // The handle's area is attached to the pan detector. // The OnPan() method is connected to the signals emitted by the pan detector. - mPanDetector.Attach( secondary.grabArea ); + mPanDetector.Attach(secondary.grabArea); - secondary.actor.Add( secondary.grabArea ); + secondary.actor.Add(secondary.grabArea); - CreateHandleMarker( secondary, mHandleImages[RIGHT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], RIGHT_SELECTION_HANDLE ); + CreateHandleMarker(secondary, mHandleImages[RIGHT_SELECTION_HANDLE_MARKER][HANDLE_IMAGE_RELEASED], RIGHT_SELECTION_HANDLE); } } - if( secondary.actor && !secondary.actor.GetParent() ) + if(secondary.actor && !secondary.actor.GetParent()) { - mActiveLayer.Add( secondary.actor ); + mActiveLayer.Add(secondary.actor); } } - void CalculateHandleWorldCoordinates( HandleImpl& handle, Vector2& position ) + void CalculateHandleWorldCoordinates(HandleImpl& handle, Vector2& position) { // Gets the world position of the active layer. The active layer is where the handles are added. - const Vector3 parentWorldPosition = mActiveLayer.GetCurrentProperty< Vector3 >( Actor::Property::WORLD_POSITION ); + const Vector3 parentWorldPosition = mActiveLayer.GetCurrentProperty(Actor::Property::WORLD_POSITION); // The grab handle position in world coords. // The active layer's world position is the center of the active layer. The origin of the // coord system of the handles is the top left of the active layer. - position.x = parentWorldPosition.x - 0.5f * mControlSize.width + handle.position.x + ( mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f ); - position.y = parentWorldPosition.y - 0.5f * mControlSize.height + handle.position.y + ( mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f ); + position.x = parentWorldPosition.x - 0.5f * mControlSize.width + handle.position.x + (mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f); + position.y = parentWorldPosition.y - 0.5f * mControlSize.height + handle.position.y + (mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f); } void SetGrabHandlePosition() @@ -963,14 +956,14 @@ struct Decorator::Impl : public ConnectionTracker // retrieves the position of the center of the actor but the handle's position set // by the text controller is not the center of the actor. Vector2 grabHandleWorldPosition; - CalculateHandleWorldCoordinates( grabHandle, grabHandleWorldPosition ); + CalculateHandleWorldCoordinates(grabHandle, grabHandleWorldPosition); // Check if the grab handle exceeds the boundaries of the decoration box. // At the moment only the height is checked for the grab handle. - grabHandle.verticallyFlipped = ( grabHandle.verticallyFlippedPreferred && - ( ( grabHandleWorldPosition.y - grabHandle.size.height ) > mBoundingBox.y ) ) || - ( grabHandleWorldPosition.y + grabHandle.lineHeight + grabHandle.size.height > mBoundingBox.w ); + grabHandle.verticallyFlipped = (grabHandle.verticallyFlippedPreferred && + ((grabHandleWorldPosition.y - grabHandle.size.height) > mBoundingBox.y)) || + (grabHandleWorldPosition.y + grabHandle.lineHeight + grabHandle.size.height > mBoundingBox.w); // The grab handle 'y' position in local coords. // If the grab handle exceeds the bottom of the decoration box, @@ -978,14 +971,13 @@ struct Decorator::Impl : public ConnectionTracker // The SetGrabHandleImage() method will change the orientation. const float yLocalPosition = grabHandle.verticallyFlipped ? grabHandle.position.y : grabHandle.position.y + grabHandle.lineHeight; - if( grabHandle.actor ) + if(grabHandle.actor) { - grabHandle.actor.SetProperty( Actor::Property::POSITION, Vector2( grabHandle.position.x + floor( 0.5f * mCursorWidth ) + ( mSmoothHandlePanEnabled ? grabHandle.grabDisplacementX : 0.f ), - yLocalPosition + ( mSmoothHandlePanEnabled ? grabHandle.grabDisplacementY : 0.f ) ) ); + grabHandle.actor.SetProperty(Actor::Property::POSITION, Vector2(grabHandle.position.x + floor(0.5f * mCursorWidth) + (mSmoothHandlePanEnabled ? grabHandle.grabDisplacementX : 0.f), yLocalPosition + (mSmoothHandlePanEnabled ? grabHandle.grabDisplacementY : 0.f))); } } - void SetSelectionHandlePosition( HandleType type ) + void SetSelectionHandlePosition(HandleType type) { const bool isPrimaryHandle = LEFT_SELECTION_HANDLE == type; @@ -999,14 +991,14 @@ struct Decorator::Impl : public ConnectionTracker // retrieves the position of the center of the actor but the handle's position set // by the text controller is not the center of the actor. Vector2 handleWorldPosition; - CalculateHandleWorldCoordinates( handle, handleWorldPosition ); + CalculateHandleWorldCoordinates(handle, handleWorldPosition); // Whether to flip the handle (horizontally). bool flipHandle = isPrimaryHandle ? mFlipLeftSelectionHandleDirection : mFlipRightSelectionHandleDirection; // Whether to flip the handles if they are crossed. bool crossFlip = false; - if( mFlipSelectionHandlesOnCross || !mIsHandlePanning ) + if(mFlipSelectionHandlesOnCross || !mIsHandlePanning) { crossFlip = mIsHandleCurrentlyCrossed; } @@ -1015,14 +1007,14 @@ struct Decorator::Impl : public ConnectionTracker const bool isHandlePreviouslyCrossed = mFlipSelectionHandlesOnCross ? false : mIsHandlePreviouslyCrossed; // Does not flip if both conditions are true (double flip) - flipHandle = flipHandle != ( crossFlip || isHandlePreviouslyCrossed ); + flipHandle = flipHandle != (crossFlip || isHandlePreviouslyCrossed); // Will flip the handles vertically if the user prefers it. bool verticallyFlippedPreferred = handle.verticallyFlippedPreferred; - if( crossFlip || isHandlePreviouslyCrossed ) + if(crossFlip || isHandlePreviouslyCrossed) { - if( isPrimaryHandle ) + if(isPrimaryHandle) { verticallyFlippedPreferred = mHandle[RIGHT_SELECTION_HANDLE].verticallyFlippedPreferred; } @@ -1033,37 +1025,37 @@ struct Decorator::Impl : public ConnectionTracker } // Check if the selection handle exceeds the boundaries of the decoration box. - const bool exceedsLeftEdge = ( isPrimaryHandle ? !flipHandle : flipHandle ) && ( handleWorldPosition.x - handle.size.width < mBoundingBox.x ); - const bool exceedsRightEdge = ( isPrimaryHandle ? flipHandle : !flipHandle ) && ( handleWorldPosition.x + handle.size.width > mBoundingBox.z ); + const bool exceedsLeftEdge = (isPrimaryHandle ? !flipHandle : flipHandle) && (handleWorldPosition.x - handle.size.width < mBoundingBox.x); + const bool exceedsRightEdge = (isPrimaryHandle ? flipHandle : !flipHandle) && (handleWorldPosition.x + handle.size.width > mBoundingBox.z); // Does not flip if both conditions are true (double flip) - flipHandle = flipHandle != ( exceedsLeftEdge || exceedsRightEdge ); + flipHandle = flipHandle != (exceedsLeftEdge || exceedsRightEdge); - if( flipHandle ) + if(flipHandle) { - if( handle.actor && !handle.horizontallyFlipped ) + if(handle.actor && !handle.horizontallyFlipped) { // Change the anchor point to flip the image. - handle.actor.SetProperty( Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_LEFT : AnchorPoint::TOP_RIGHT ); + handle.actor.SetProperty(Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_LEFT : AnchorPoint::TOP_RIGHT); handle.horizontallyFlipped = true; } } else { - if( handle.actor && handle.horizontallyFlipped ) + if(handle.actor && handle.horizontallyFlipped) { // Reset the anchor point. - handle.actor.SetProperty( Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_RIGHT : AnchorPoint::TOP_LEFT ); + handle.actor.SetProperty(Actor::Property::ANCHOR_POINT, isPrimaryHandle ? AnchorPoint::TOP_RIGHT : AnchorPoint::TOP_LEFT); handle.horizontallyFlipped = false; } } // Whether to flip the handle vertically. - handle.verticallyFlipped = ( verticallyFlippedPreferred && - ( ( handleWorldPosition.y - handle.size.height ) > mBoundingBox.y ) ) || - ( handleWorldPosition.y + handle.lineHeight + handle.size.height > mBoundingBox.w ); + handle.verticallyFlipped = (verticallyFlippedPreferred && + ((handleWorldPosition.y - handle.size.height) > mBoundingBox.y)) || + (handleWorldPosition.y + handle.lineHeight + handle.size.height > mBoundingBox.w); // The primary selection handle 'y' position in local coords. // If the handle exceeds the bottom of the decoration box, @@ -1071,103 +1063,101 @@ struct Decorator::Impl : public ConnectionTracker // The SetHandleImage() method will change the orientation. const float yLocalPosition = handle.verticallyFlipped ? handle.position.y : handle.position.y + handle.lineHeight; - if( handle.actor ) + if(handle.actor) { - handle.actor.SetProperty( Actor::Property::POSITION, Vector2( handle.position.x + ( mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f ), - yLocalPosition + ( mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f ) ) ); + handle.actor.SetProperty(Actor::Property::POSITION, Vector2(handle.position.x + (mSmoothHandlePanEnabled ? handle.grabDisplacementX : 0.f), yLocalPosition + (mSmoothHandlePanEnabled ? handle.grabDisplacementY : 0.f))); } } - void SetHandleImage( HandleType type ) + void SetHandleImage(HandleType type) { HandleImpl& handle = mHandle[type]; HandleType markerType = HANDLE_TYPE_COUNT; // If the selection handle is flipped it chooses the image of the other selection handle. Does nothing for the grab handle. - if( LEFT_SELECTION_HANDLE == type ) + if(LEFT_SELECTION_HANDLE == type) { - type = handle.horizontallyFlipped ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE; + type = handle.horizontallyFlipped ? RIGHT_SELECTION_HANDLE : LEFT_SELECTION_HANDLE; markerType = handle.horizontallyFlipped ? RIGHT_SELECTION_HANDLE_MARKER : LEFT_SELECTION_HANDLE_MARKER; } - else if( RIGHT_SELECTION_HANDLE == type ) + else if(RIGHT_SELECTION_HANDLE == type) { - type = handle.horizontallyFlipped ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE; + type = handle.horizontallyFlipped ? LEFT_SELECTION_HANDLE : RIGHT_SELECTION_HANDLE; markerType = handle.horizontallyFlipped ? LEFT_SELECTION_HANDLE_MARKER : RIGHT_SELECTION_HANDLE_MARKER; } // Chooses between the released or pressed image. It checks whether the pressed image exists. - if( handle.actor ) + if(handle.actor) { - const HandleImageType imageType = ( handle.pressed ? ( mHandleImages[type][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED ) : HANDLE_IMAGE_RELEASED ); + const HandleImageType imageType = (handle.pressed ? (mHandleImages[type][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED) : HANDLE_IMAGE_RELEASED); - handle.actor.SetImage( mHandleImages[type][imageType] ); + handle.actor.SetImage(mHandleImages[type][imageType]); } - if( HANDLE_TYPE_COUNT != markerType ) + if(HANDLE_TYPE_COUNT != markerType) { - if( handle.markerActor ) + if(handle.markerActor) { - const HandleImageType markerImageType = ( handle.pressed ? ( mHandleImages[markerType][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED ) : HANDLE_IMAGE_RELEASED ); - handle.markerActor.SetImage( mHandleImages[markerType][markerImageType] ); + const HandleImageType markerImageType = (handle.pressed ? (mHandleImages[markerType][HANDLE_IMAGE_PRESSED].size() ? HANDLE_IMAGE_PRESSED : HANDLE_IMAGE_RELEASED) : HANDLE_IMAGE_RELEASED); + handle.markerActor.SetImage(mHandleImages[markerType][markerImageType]); } } // Whether to flip the handle vertically. - if( handle.actor ) + if(handle.actor) { - handle.actor.SetProperty( Actor::Property::ORIENTATION, Quaternion( handle.verticallyFlipped ? ANGLE_180 : ANGLE_0, Vector3::XAXIS ) ); + handle.actor.SetProperty(Actor::Property::ORIENTATION, Quaternion(handle.verticallyFlipped ? ANGLE_180 : ANGLE_0, Vector3::XAXIS)); } } void CreateHighlight() { - if( !mHighlightActor ) + if(!mHighlightActor) { mHighlightActor = Actor::New(); - mHighlightActor.SetProperty( Dali::Actor::Property::NAME, "HighlightActor" ); - mHighlightActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - mHighlightActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - mHighlightActor.SetProperty( Actor::Property::COLOR, mHighlightColor ); - mHighlightActor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_COLOR ); + mHighlightActor.SetProperty(Dali::Actor::Property::NAME, "HighlightActor"); + mHighlightActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + mHighlightActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mHighlightActor.SetProperty(Actor::Property::COLOR, mHighlightColor); + mHighlightActor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_COLOR); } // Add the highlight box telling the controller it needs clipping. - mController.AddDecoration( mHighlightActor, true ); + mController.AddDecoration(mHighlightActor, true); } void UpdateHighlight() { - if ( mHighlightActor ) + if(mHighlightActor) { // Sets the position of the highlight actor inside the decorator. - mHighlightActor.SetProperty( Actor::Property::POSITION, Vector2( mHighlightPosition.x + mHighlightOutlineOffset, - mHighlightPosition.y + mHighlightOutlineOffset ) ); + mHighlightActor.SetProperty(Actor::Property::POSITION, Vector2(mHighlightPosition.x + mHighlightOutlineOffset, mHighlightPosition.y + mHighlightOutlineOffset)); const unsigned int numberOfQuads = mHighlightQuadList.Count(); - if( 0u != numberOfQuads ) + if(0u != numberOfQuads) { // Set the size of the highlighted text to the actor. - mHighlightActor.SetProperty( Actor::Property::SIZE, mHighlightSize ); + mHighlightActor.SetProperty(Actor::Property::SIZE, mHighlightSize); // Used to translate the vertices given in decorator's coords to the mHighlightActor's local coords. const float offsetX = mHighlightPosition.x + 0.5f * mHighlightSize.width; const float offsetY = mHighlightPosition.y + 0.5f * mHighlightSize.height; - Vector vertices; + Vector vertices; Vector indices; - vertices.Reserve( 4u * numberOfQuads ); - indices.Reserve( 6u * numberOfQuads ); + vertices.Reserve(4u * numberOfQuads); + indices.Reserve(6u * numberOfQuads); // Index to the vertex. unsigned int v = 0u; // Traverse all quads. - for( Vector::ConstIterator it = mHighlightQuadList.Begin(), - endIt = mHighlightQuadList.End(); - it != endIt; - ++it, v += 4u ) + for(Vector::ConstIterator it = mHighlightQuadList.Begin(), + endIt = mHighlightQuadList.End(); + it != endIt; + ++it, v += 4u) { const Vector4& quad = *it; @@ -1176,68 +1166,68 @@ struct Decorator::Impl : public ConnectionTracker // top-left (v+0) vertex.x = quad.x - offsetX; vertex.y = quad.y - offsetY; - vertices.PushBack( vertex ); + vertices.PushBack(vertex); // top-right (v+1) vertex.x = quad.z - offsetX; vertex.y = quad.y - offsetY; - vertices.PushBack( vertex ); + vertices.PushBack(vertex); // bottom-left (v+2) vertex.x = quad.x - offsetX; vertex.y = quad.w - offsetY; - vertices.PushBack( vertex ); + vertices.PushBack(vertex); // bottom-right (v+3) vertex.x = quad.z - offsetX; vertex.y = quad.w - offsetY; - vertices.PushBack( vertex ); + vertices.PushBack(vertex); // triangle A (3, 1, 0) - indices.PushBack( v + 3 ); - indices.PushBack( v + 1 ); - indices.PushBack( v ); + indices.PushBack(v + 3); + indices.PushBack(v + 1); + indices.PushBack(v); // triangle B (0, 2, 3) - indices.PushBack( v ); - indices.PushBack( v + 2 ); - indices.PushBack( v + 3 ); + indices.PushBack(v); + indices.PushBack(v + 2); + indices.PushBack(v + 3); } - if( ! mQuadVertices ) + if(!mQuadVertices) { - mQuadVertices = VertexBuffer::New( mQuadVertexFormat ); + mQuadVertices = VertexBuffer::New(mQuadVertexFormat); } - mQuadVertices.SetData( &vertices[ 0 ], vertices.Size() ); + mQuadVertices.SetData(&vertices[0], vertices.Size()); - if( !mQuadGeometry ) + if(!mQuadGeometry) { mQuadGeometry = Geometry::New(); - mQuadGeometry.AddVertexBuffer( mQuadVertices ); + mQuadGeometry.AddVertexBuffer(mQuadVertices); } - mQuadGeometry.SetIndexBuffer( &indices[ 0 ], indices.Size() ); + mQuadGeometry.SetIndexBuffer(&indices[0], indices.Size()); - if( !mHighlightRenderer ) + if(!mHighlightRenderer) { - mHighlightRenderer = Dali::Renderer::New( mQuadGeometry, mHighlightShader ); - mHighlightActor.AddRenderer( mHighlightRenderer ); + mHighlightRenderer = Dali::Renderer::New(mQuadGeometry, mHighlightShader); + mHighlightActor.AddRenderer(mHighlightRenderer); } } mHighlightQuadList.Clear(); - if( mHighlightRenderer ) + if(mHighlightRenderer) { - mHighlightRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, mTextDepth - 2 ); // text is rendered at mTextDepth and text's shadow at mTextDepth -1u. + mHighlightRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, mTextDepth - 2); // text is rendered at mTextDepth and text's shadow at mTextDepth -1u. } } } - void DoPan( HandleImpl& handle, HandleType type, const PanGesture& gesture ) + void DoPan(HandleImpl& handle, HandleType type, const PanGesture& gesture) { GestureState state = gesture.GetState(); - if( GestureState::STARTED == state ) + if(GestureState::STARTED == state) { handle.grabDisplacementX = handle.grabDisplacementY = 0.f; @@ -1247,41 +1237,41 @@ struct Decorator::Impl : public ConnectionTracker const Vector2& displacement = gesture.GetDisplacement(); handle.grabDisplacementX += displacement.x; - handle.grabDisplacementY += ( handle.verticallyFlipped ? -displacement.y : displacement.y ); + handle.grabDisplacementY += (handle.verticallyFlipped ? -displacement.y : displacement.y); - const float x = handle.globalPosition.x + handle.grabDisplacementX; - const float y = handle.globalPosition.y + handle.grabDisplacementY + 0.5f * handle.lineHeight; - const float yVerticallyFlippedCorrected = y - ( handle.verticallyFlippedOnTouch ? handle.lineHeight : 0.f ); + const float x = handle.globalPosition.x + handle.grabDisplacementX; + const float y = handle.globalPosition.y + handle.grabDisplacementY + 0.5f * handle.lineHeight; + const float yVerticallyFlippedCorrected = y - (handle.verticallyFlippedOnTouch ? handle.lineHeight : 0.f); - if( ( GestureState::STARTED == state ) || - ( GestureState::CONTINUING == state ) ) + if((GestureState::STARTED == state) || + (GestureState::CONTINUING == state)) { Vector2 targetSize; - mController.GetTargetSize( targetSize ); + mController.GetTargetSize(targetSize); - if( mHorizontalScrollingEnabled && - ( x < mScrollThreshold ) ) + if(mHorizontalScrollingEnabled && + (x < mScrollThreshold)) { mScrollDirection = SCROLL_RIGHT; mHandleScrolling = type; StartScrollTimer(); } - else if( mHorizontalScrollingEnabled && - ( x > targetSize.width - mScrollThreshold ) ) + else if(mHorizontalScrollingEnabled && + (x > targetSize.width - mScrollThreshold)) { mScrollDirection = SCROLL_LEFT; mHandleScrolling = type; StartScrollTimer(); } - else if( mVerticalScrollingEnabled && - ( yVerticallyFlippedCorrected < mScrollThreshold ) ) + else if(mVerticalScrollingEnabled && + (yVerticallyFlippedCorrected < mScrollThreshold)) { mScrollDirection = SCROLL_TOP; mHandleScrolling = type; StartScrollTimer(); } - else if( mVerticalScrollingEnabled && - ( yVerticallyFlippedCorrected + handle.lineHeight > targetSize.height - mScrollThreshold ) ) + else if(mVerticalScrollingEnabled && + (yVerticallyFlippedCorrected + handle.lineHeight > targetSize.height - mScrollThreshold)) { mScrollDirection = SCROLL_BOTTOM; mHandleScrolling = type; @@ -1291,30 +1281,30 @@ struct Decorator::Impl : public ConnectionTracker { mHandleScrolling = HANDLE_TYPE_COUNT; StopScrollTimer(); - mController.DecorationEvent( type, HANDLE_PRESSED, x, y ); + mController.DecorationEvent(type, HANDLE_PRESSED, x, y); } mIsHandlePanning = true; } - else if( ( GestureState::FINISHED == state ) || - ( GestureState::CANCELLED == state ) ) + else if((GestureState::FINISHED == state) || + (GestureState::CANCELLED == state)) { - if( mScrollTimer && - ( mScrollTimer.IsRunning() || mNotifyEndOfScroll ) ) + if(mScrollTimer && + (mScrollTimer.IsRunning() || mNotifyEndOfScroll)) { mNotifyEndOfScroll = false; - mHandleScrolling = HANDLE_TYPE_COUNT; + mHandleScrolling = HANDLE_TYPE_COUNT; StopScrollTimer(); - mController.DecorationEvent( type, HANDLE_STOP_SCROLLING, x, y ); + mController.DecorationEvent(type, HANDLE_STOP_SCROLLING, x, y); } else { - mController.DecorationEvent( type, HANDLE_RELEASED, x, y ); + mController.DecorationEvent(type, HANDLE_RELEASED, x, y); } - if( handle.actor ) + if(handle.actor) { - handle.actor.SetImage( mHandleImages[type][HANDLE_IMAGE_RELEASED] ); + handle.actor.SetImage(mHandleImages[type][HANDLE_IMAGE_RELEASED]); } handle.pressed = false; @@ -1322,143 +1312,143 @@ struct Decorator::Impl : public ConnectionTracker } } - void OnPan( Actor actor, const PanGesture& gesture ) + void OnPan(Actor actor, const PanGesture& gesture) { - HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE]; + HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; + HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE]; HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE]; - if( actor == grabHandle.grabArea ) + if(actor == grabHandle.grabArea) { - DoPan( grabHandle, GRAB_HANDLE, gesture ); + DoPan(grabHandle, GRAB_HANDLE, gesture); } - else if( actor == primarySelectionHandle.grabArea ) + else if(actor == primarySelectionHandle.grabArea) { - DoPan( primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture ); + DoPan(primarySelectionHandle, LEFT_SELECTION_HANDLE, gesture); } - else if( actor == secondarySelectionHandle.grabArea ) + else if(actor == secondarySelectionHandle.grabArea) { - DoPan( secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture ); + DoPan(secondarySelectionHandle, RIGHT_SELECTION_HANDLE, gesture); } } - bool OnGrabHandleTouched( Actor actor, const TouchEvent& touch ) + bool OnGrabHandleTouched(Actor actor, const TouchEvent& touch) { HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; // Switch between pressed/release grab-handle images - if( touch.GetPointCount() > 0 && - grabHandle.actor ) + if(touch.GetPointCount() > 0 && + grabHandle.actor) { - const PointState::Type state = touch.GetState( 0 ); + const PointState::Type state = touch.GetState(0); - if( PointState::DOWN == state ) + if(PointState::DOWN == state) { grabHandle.pressed = true; } - else if( ( PointState::UP == state ) || - ( PointState::INTERRUPTED == state ) ) + else if((PointState::UP == state) || + (PointState::INTERRUPTED == state)) { grabHandle.pressed = false; } - SetHandleImage( GRAB_HANDLE ); + SetHandleImage(GRAB_HANDLE); } return false; } - bool OnHandleOneTouched( Actor actor, const TouchEvent& touch ) + bool OnHandleOneTouched(Actor actor, const TouchEvent& touch) { HandleImpl& primarySelectionHandle = mHandle[LEFT_SELECTION_HANDLE]; // Switch between pressed/release selection handle images - if( touch.GetPointCount() > 0 && - primarySelectionHandle.actor ) + if(touch.GetPointCount() > 0 && + primarySelectionHandle.actor) { - const PointState::Type state = touch.GetState( 0 ); + const PointState::Type state = touch.GetState(0); - if( PointState::DOWN == state ) + if(PointState::DOWN == state) { - primarySelectionHandle.pressed = true; + primarySelectionHandle.pressed = true; primarySelectionHandle.verticallyFlippedOnTouch = primarySelectionHandle.verticallyFlipped; } - else if( ( PointState::UP == state ) || - ( PointState::INTERRUPTED == state ) ) + else if((PointState::UP == state) || + (PointState::INTERRUPTED == state)) { primarySelectionHandle.pressed = false; - mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed; - mIsHandlePanning = false; - mHandleReleased = LEFT_SELECTION_HANDLE; + mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed; + mIsHandlePanning = false; + mHandleReleased = LEFT_SELECTION_HANDLE; } - SetHandleImage( LEFT_SELECTION_HANDLE ); + SetHandleImage(LEFT_SELECTION_HANDLE); } return false; } - bool OnHandleTwoTouched( Actor actor, const TouchEvent& touch ) + bool OnHandleTwoTouched(Actor actor, const TouchEvent& touch) { HandleImpl& secondarySelectionHandle = mHandle[RIGHT_SELECTION_HANDLE]; // Switch between pressed/release selection handle images - if( touch.GetPointCount() > 0 && - secondarySelectionHandle.actor ) + if(touch.GetPointCount() > 0 && + secondarySelectionHandle.actor) { - const PointState::Type state = touch.GetState( 0 ); + const PointState::Type state = touch.GetState(0); - if( PointState::DOWN == state ) + if(PointState::DOWN == state) { - secondarySelectionHandle.pressed = true; + secondarySelectionHandle.pressed = true; secondarySelectionHandle.verticallyFlippedOnTouch = secondarySelectionHandle.verticallyFlipped; } - else if( ( PointState::UP == state ) || - ( PointState::INTERRUPTED == state ) ) + else if((PointState::UP == state) || + (PointState::INTERRUPTED == state)) { secondarySelectionHandle.pressed = false; - mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed; - mIsHandlePanning = false; - mHandleReleased = RIGHT_SELECTION_HANDLE; + mIsHandlePreviouslyCrossed = mIsHandleCurrentlyCrossed; + mIsHandlePanning = false; + mHandleReleased = RIGHT_SELECTION_HANDLE; } - SetHandleImage( RIGHT_SELECTION_HANDLE ); + SetHandleImage(RIGHT_SELECTION_HANDLE); } return false; } - void HandleResetPosition( PropertyNotification& source ) + void HandleResetPosition(PropertyNotification& source) { const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - if( grabHandle.active ) + if(grabHandle.active) { // Sets the grab handle position and calculates if it needs to be vertically flipped if it exceeds the boundary box. SetGrabHandlePosition(); // Sets the grab handle image according if it's pressed, flipped, etc. - SetHandleImage( GRAB_HANDLE ); + SetHandleImage(GRAB_HANDLE); } else { // Sets the primary selection handle position and calculates if it needs to be vertically flipped if it exceeds the boundary box. - SetSelectionHandlePosition( LEFT_SELECTION_HANDLE ); + SetSelectionHandlePosition(LEFT_SELECTION_HANDLE); // Sets the primary handle image according if it's pressed, flipped, etc. - SetHandleImage( LEFT_SELECTION_HANDLE ); + SetHandleImage(LEFT_SELECTION_HANDLE); // Sets the secondary selection handle position and calculates if it needs to be vertically flipped if it exceeds the boundary box. - SetSelectionHandlePosition( RIGHT_SELECTION_HANDLE ); + SetSelectionHandlePosition(RIGHT_SELECTION_HANDLE); // Sets the secondary handle image according if it's pressed, flipped, etc. - SetHandleImage( RIGHT_SELECTION_HANDLE ); + SetHandleImage(RIGHT_SELECTION_HANDLE); } } void SetupActiveLayerPropertyNotifications() { - if( !mActiveLayer ) + if(!mActiveLayer) { return; } @@ -1466,25 +1456,25 @@ struct Decorator::Impl : public ConnectionTracker // Vertical notifications. // Disconnect any previous connected callback. - if( mHandleVerticalLessThanNotification ) + if(mHandleVerticalLessThanNotification) { - mHandleVerticalLessThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition ); - mActiveLayer.RemovePropertyNotification( mHandleVerticalLessThanNotification ); + mHandleVerticalLessThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition); + mActiveLayer.RemovePropertyNotification(mHandleVerticalLessThanNotification); } - if( mHandleVerticalGreaterThanNotification ) + if(mHandleVerticalGreaterThanNotification) { - mHandleVerticalGreaterThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition ); - mActiveLayer.RemovePropertyNotification( mHandleVerticalGreaterThanNotification ); + mHandleVerticalGreaterThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition); + mActiveLayer.RemovePropertyNotification(mHandleVerticalGreaterThanNotification); } - const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; + const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; + const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE]; - if( grabHandle.active ) + if(grabHandle.active) { - if( grabHandle.verticallyFlipped ) + if(grabHandle.verticallyFlipped) { // The grab handle is vertically flipped. Never is going to exceed the bottom edje of the display. mHandleVerticalGreaterThanNotification.Reset(); @@ -1492,14 +1482,14 @@ struct Decorator::Impl : public ConnectionTracker // The vertical distance from the center of the active layer to the top edje of the display. const float topHeight = 0.5f * mControlSize.height - grabHandle.position.y + grabHandle.size.height; - mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - LessThanCondition( mBoundingBox.y + topHeight ) ); + mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + LessThanCondition(mBoundingBox.y + topHeight)); // Notifies the change from false to true and from true to false. - mHandleVerticalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleVerticalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleVerticalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleVerticalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); } else { @@ -1509,239 +1499,235 @@ struct Decorator::Impl : public ConnectionTracker // The vertical distance from the center of the active layer to the bottom edje of the display. const float bottomHeight = -0.5f * mControlSize.height + grabHandle.position.y + grabHandle.lineHeight + grabHandle.size.height; - mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - GreaterThanCondition( mBoundingBox.w - bottomHeight ) ); + mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + GreaterThanCondition(mBoundingBox.w - bottomHeight)); // Notifies the change from false to true and from true to false. - mHandleVerticalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleVerticalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleVerticalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleVerticalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); } } else // The selection handles are active { - if( primaryHandle.verticallyFlipped && secondaryHandle.verticallyFlipped ) + if(primaryHandle.verticallyFlipped && secondaryHandle.verticallyFlipped) { // Both selection handles are vertically flipped. Never are going to exceed the bottom edje of the display. mHandleVerticalGreaterThanNotification.Reset(); // The vertical distance from the center of the active layer to the top edje of the display. - const float topHeight = 0.5f * mControlSize.height + std::max( -primaryHandle.position.y + primaryHandle.size.height, -secondaryHandle.position.y + secondaryHandle.size.height ); + const float topHeight = 0.5f * mControlSize.height + std::max(-primaryHandle.position.y + primaryHandle.size.height, -secondaryHandle.position.y + secondaryHandle.size.height); - mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - LessThanCondition( mBoundingBox.y + topHeight ) ); + mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + LessThanCondition(mBoundingBox.y + topHeight)); // Notifies the change from false to true and from true to false. - mHandleVerticalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleVerticalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleVerticalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleVerticalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); } - else if( !primaryHandle.verticallyFlipped && !secondaryHandle.verticallyFlipped ) + else if(!primaryHandle.verticallyFlipped && !secondaryHandle.verticallyFlipped) { // Both selection handles aren't vertically flipped. Never are going to exceed the top edje of the display. mHandleVerticalLessThanNotification.Reset(); // The vertical distance from the center of the active layer to the bottom edje of the display. - const float bottomHeight = -0.5f * mControlSize.height + std::max( primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height, - secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height ); + const float bottomHeight = -0.5f * mControlSize.height + std::max(primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height, + secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height); - mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - GreaterThanCondition( mBoundingBox.w - bottomHeight ) ); + mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + GreaterThanCondition(mBoundingBox.w - bottomHeight)); // Notifies the change from false to true and from true to false. - mHandleVerticalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleVerticalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleVerticalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleVerticalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); } else { // Only one of the selection handles is vertically flipped. Both vertical notifications are needed. // The vertical distance from the center of the active layer to the top edje of the display. - const float topHeight = 0.5f * mControlSize.height + ( primaryHandle.verticallyFlipped ? - -primaryHandle.position.y + primaryHandle.size.height : - -secondaryHandle.position.y + secondaryHandle.size.height ); + const float topHeight = 0.5f * mControlSize.height + (primaryHandle.verticallyFlipped ? -primaryHandle.position.y + primaryHandle.size.height : -secondaryHandle.position.y + secondaryHandle.size.height); - mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - LessThanCondition( mBoundingBox.y + topHeight ) ); + mHandleVerticalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + LessThanCondition(mBoundingBox.y + topHeight)); // Notifies the change from false to true and from true to false. - mHandleVerticalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleVerticalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleVerticalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleVerticalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); // The vertical distance from the center of the active layer to the bottom edje of the display. - const float bottomHeight = -0.5f * mControlSize.height + ( primaryHandle.verticallyFlipped ? - secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height : - primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height ); + const float bottomHeight = -0.5f * mControlSize.height + (primaryHandle.verticallyFlipped ? secondaryHandle.position.y + secondaryHandle.lineHeight + secondaryHandle.size.height : primaryHandle.position.y + primaryHandle.lineHeight + primaryHandle.size.height); - mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - GreaterThanCondition( mBoundingBox.w - bottomHeight ) ); + mHandleVerticalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + GreaterThanCondition(mBoundingBox.w - bottomHeight)); // Notifies the change from false to true and from true to false. - mHandleVerticalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleVerticalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleVerticalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleVerticalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); } } // Horizontal notifications. // Disconnect any previous connected callback. - if( mHandleHorizontalLessThanNotification ) + if(mHandleHorizontalLessThanNotification) { - mHandleHorizontalLessThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition ); - mActiveLayer.RemovePropertyNotification( mHandleHorizontalLessThanNotification ); + mHandleHorizontalLessThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition); + mActiveLayer.RemovePropertyNotification(mHandleHorizontalLessThanNotification); } - if( mHandleHorizontalGreaterThanNotification ) + if(mHandleHorizontalGreaterThanNotification) { - mHandleHorizontalGreaterThanNotification.NotifySignal().Disconnect( this, &Decorator::Impl::HandleResetPosition ); - mActiveLayer.RemovePropertyNotification( mHandleHorizontalGreaterThanNotification ); + mHandleHorizontalGreaterThanNotification.NotifySignal().Disconnect(this, &Decorator::Impl::HandleResetPosition); + mActiveLayer.RemovePropertyNotification(mHandleHorizontalGreaterThanNotification); } - if( primaryHandle.active || secondaryHandle.active ) + if(primaryHandle.active || secondaryHandle.active) { // The horizontal distance from the center of the active layer to the left edje of the display. - const float leftWidth = 0.5f * mControlSize.width + std::max( -primaryHandle.position.x + primaryHandle.size.width, - -secondaryHandle.position.x + secondaryHandle.size.width ); + const float leftWidth = 0.5f * mControlSize.width + std::max(-primaryHandle.position.x + primaryHandle.size.width, + -secondaryHandle.position.x + secondaryHandle.size.width); - mHandleHorizontalLessThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_X, - LessThanCondition( mBoundingBox.x + leftWidth ) ); + mHandleHorizontalLessThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_X, + LessThanCondition(mBoundingBox.x + leftWidth)); // Notifies the change from false to true and from true to false. - mHandleHorizontalLessThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleHorizontalLessThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleHorizontalLessThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleHorizontalLessThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); // The horizontal distance from the center of the active layer to the right edje of the display. - const float rightWidth = -0.5f * mControlSize.width + std::max( primaryHandle.position.x + primaryHandle.size.width, - secondaryHandle.position.x + secondaryHandle.size.width ); + const float rightWidth = -0.5f * mControlSize.width + std::max(primaryHandle.position.x + primaryHandle.size.width, + secondaryHandle.position.x + secondaryHandle.size.width); - mHandleHorizontalGreaterThanNotification = mActiveLayer.AddPropertyNotification( Actor::Property::WORLD_POSITION_X, - GreaterThanCondition( mBoundingBox.z - rightWidth ) ); + mHandleHorizontalGreaterThanNotification = mActiveLayer.AddPropertyNotification(Actor::Property::WORLD_POSITION_X, + GreaterThanCondition(mBoundingBox.z - rightWidth)); // Notifies the change from false to true and from true to false. - mHandleHorizontalGreaterThanNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mHandleHorizontalGreaterThanNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); // Connects the signals with the callbacks. - mHandleHorizontalGreaterThanNotification.NotifySignal().Connect( this, &Decorator::Impl::HandleResetPosition ); + mHandleHorizontalGreaterThanNotification.NotifySignal().Connect(this, &Decorator::Impl::HandleResetPosition); } } // Popup - float AlternatePopUpPositionRelativeToCursor( bool topBottom ) + float AlternatePopUpPositionRelativeToCursor(bool topBottom) { float alternativePosition = 0.0f; - const float halfPopupHeight = 0.5f * mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT ); + const float halfPopupHeight = 0.5f * mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT); - const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; + const HandleImpl& primaryHandle = mHandle[LEFT_SELECTION_HANDLE]; const HandleImpl& secondaryHandle = mHandle[RIGHT_SELECTION_HANDLE]; - const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; - const CursorImpl& cursor = mCursor[PRIMARY_CURSOR]; + const HandleImpl& grabHandle = mHandle[GRAB_HANDLE]; + const CursorImpl& cursor = mCursor[PRIMARY_CURSOR]; - if( primaryHandle.active || secondaryHandle.active ) + if(primaryHandle.active || secondaryHandle.active) { - float handleY = 0.f; + float handleY = 0.f; float maxHandleHeight = 0.f; - const bool primaryVisible = primaryHandle.horizontallyVisible && primaryHandle.verticallyVisible; + const bool primaryVisible = primaryHandle.horizontallyVisible && primaryHandle.verticallyVisible; const bool secondaryVisible = secondaryHandle.horizontallyVisible && secondaryHandle.verticallyVisible; - if( primaryVisible && secondaryVisible ) + if(primaryVisible && secondaryVisible) { - handleY = std::max( primaryHandle.position.y, secondaryHandle.position.y ); - maxHandleHeight = std::max( primaryHandle.size.height, secondaryHandle.size.height ); + handleY = std::max(primaryHandle.position.y, secondaryHandle.position.y); + maxHandleHeight = std::max(primaryHandle.size.height, secondaryHandle.size.height); } - else if( primaryVisible && !secondaryVisible ) + else if(primaryVisible && !secondaryVisible) { - handleY = primaryHandle.position.y; + handleY = primaryHandle.position.y; maxHandleHeight = primaryHandle.size.height; } - else if( !primaryVisible && secondaryVisible ) + else if(!primaryVisible && secondaryVisible) { - handleY = secondaryHandle.position.y; + handleY = secondaryHandle.position.y; maxHandleHeight = secondaryHandle.size.height; } - alternativePosition = handleY + ( topBottom ? halfPopupHeight + maxHandleHeight + cursor.lineHeight : -halfPopupHeight - maxHandleHeight ); + alternativePosition = handleY + (topBottom ? halfPopupHeight + maxHandleHeight + cursor.lineHeight : -halfPopupHeight - maxHandleHeight); } else { - alternativePosition = cursor.position.y + ( topBottom ? halfPopupHeight + grabHandle.size.height + cursor.lineHeight : -halfPopupHeight - grabHandle.size.height ); + alternativePosition = cursor.position.y + (topBottom ? halfPopupHeight + grabHandle.size.height + cursor.lineHeight : -halfPopupHeight - grabHandle.size.height); } return alternativePosition; } - void PopUpLeavesTopBoundary( PropertyNotification& source ) + void PopUpLeavesTopBoundary(PropertyNotification& source) { - const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT ); + const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT); // Sets the position of the popup below. - mCopyPastePopup.actor.SetProperty( Actor::Property::POSITION_Y, floorf( CalculateVerticalPopUpPosition( 0.5f * popupHeight, true ) ) ); + mCopyPastePopup.actor.SetProperty(Actor::Property::POSITION_Y, floorf(CalculateVerticalPopUpPosition(0.5f * popupHeight, true))); } - void PopUpLeavesBottomBoundary( PropertyNotification& source ) + void PopUpLeavesBottomBoundary(PropertyNotification& source) { - const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize( Dimension::HEIGHT ); + const float popupHeight = mCopyPastePopup.actor.GetRelayoutSize(Dimension::HEIGHT); // Sets the position of the popup above. - mCopyPastePopup.actor.SetProperty( Actor::Property::POSITION_Y, floorf( CalculateVerticalPopUpPosition( 0.5f * popupHeight, false ) ) ); + mCopyPastePopup.actor.SetProperty(Actor::Property::POSITION_Y, floorf(CalculateVerticalPopUpPosition(0.5f * popupHeight, false))); } - void SetUpPopupPositionNotifications( const Vector3& popupHalfSize ) + void SetUpPopupPositionNotifications(const Vector3& popupHalfSize) { // Disconnect any previous connected callback. - if( mPopupTopExceedNotification ) + if(mPopupTopExceedNotification) { - mPopupTopExceedNotification.NotifySignal().Disconnect( this, &Decorator::Impl::PopUpLeavesTopBoundary ); - mCopyPastePopup.actor.RemovePropertyNotification( mPopupTopExceedNotification ); + mPopupTopExceedNotification.NotifySignal().Disconnect(this, &Decorator::Impl::PopUpLeavesTopBoundary); + mCopyPastePopup.actor.RemovePropertyNotification(mPopupTopExceedNotification); } - if( mPopupBottomExceedNotification ) + if(mPopupBottomExceedNotification) { - mPopupBottomExceedNotification.NotifySignal().Disconnect( this, &Decorator::Impl::PopUpLeavesBottomBoundary ); - mCopyPastePopup.actor.RemovePropertyNotification( mPopupBottomExceedNotification ); + mPopupBottomExceedNotification.NotifySignal().Disconnect(this, &Decorator::Impl::PopUpLeavesBottomBoundary); + mCopyPastePopup.actor.RemovePropertyNotification(mPopupBottomExceedNotification); } // Note Property notifications ignore any set anchor point so conditions must allow for this. Default is Top Left. // Exceeding vertical boundary - mPopupTopExceedNotification = mCopyPastePopup.actor.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - LessThanCondition( mBoundingBox.y + popupHalfSize.height ) ); + mPopupTopExceedNotification = mCopyPastePopup.actor.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + LessThanCondition(mBoundingBox.y + popupHalfSize.height)); - mPopupBottomExceedNotification = mCopyPastePopup.actor.AddPropertyNotification( Actor::Property::WORLD_POSITION_Y, - GreaterThanCondition( mBoundingBox.w - popupHalfSize.height ) ); + mPopupBottomExceedNotification = mCopyPastePopup.actor.AddPropertyNotification(Actor::Property::WORLD_POSITION_Y, + GreaterThanCondition(mBoundingBox.w - popupHalfSize.height)); // Notifies the change from false to true and from true to false. - mPopupTopExceedNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); - mPopupBottomExceedNotification.SetNotifyMode( PropertyNotification::NOTIFY_ON_CHANGED ); + mPopupTopExceedNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); + mPopupBottomExceedNotification.SetNotifyMode(PropertyNotification::NOTIFY_ON_CHANGED); - mPopupTopExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesTopBoundary ); - mPopupBottomExceedNotification.NotifySignal().Connect( this, &Decorator::Impl::PopUpLeavesBottomBoundary ); + mPopupTopExceedNotification.NotifySignal().Connect(this, &Decorator::Impl::PopUpLeavesTopBoundary); + mPopupBottomExceedNotification.NotifySignal().Connect(this, &Decorator::Impl::PopUpLeavesBottomBoundary); } - void SetHandleImage( HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName ) + void SetHandleImage(HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName) { - ImageDimensions dimensions = Dali::GetOriginalImageSize( imageFileName ); + ImageDimensions dimensions = Dali::GetOriginalImageSize(imageFileName); HandleImpl& handle = mHandle[handleType]; - handle.size = Size( dimensions.GetWidth(), dimensions.GetHeight() ); + handle.size = Size(dimensions.GetWidth(), dimensions.GetHeight()); mHandleImages[handleType][handleImageType] = imageFileName; } - void SetScrollThreshold( float threshold ) + void SetScrollThreshold(float threshold) { mScrollThreshold = threshold; } @@ -1751,9 +1737,9 @@ struct Decorator::Impl : public ConnectionTracker return mScrollThreshold; } - void SetScrollSpeed( float speed ) + void SetScrollSpeed(float speed) { - mScrollSpeed = speed; + mScrollSpeed = speed; mScrollDistance = speed * SCROLL_TICK_INTERVAL * TO_SECONDS; } @@ -1766,7 +1752,7 @@ struct Decorator::Impl : public ConnectionTracker { StopScrollTimer(); - if( mScrollTimer ) + if(mScrollTimer) { mNotifyEndOfScroll = true; } @@ -1779,13 +1765,13 @@ struct Decorator::Impl : public ConnectionTracker */ void StartScrollTimer() { - if( !mScrollTimer ) + if(!mScrollTimer) { - mScrollTimer = Timer::New( SCROLL_TICK_INTERVAL ); - mScrollTimer.TickSignal().Connect( this, &Decorator::Impl::OnScrollTimerTick ); + mScrollTimer = Timer::New(SCROLL_TICK_INTERVAL); + mScrollTimer.TickSignal().Connect(this, &Decorator::Impl::OnScrollTimerTick); } - if( !mScrollTimer.IsRunning() ) + if(!mScrollTimer.IsRunning()) { mScrollTimer.Start(); } @@ -1796,7 +1782,7 @@ struct Decorator::Impl : public ConnectionTracker */ void StopScrollTimer() { - if( mScrollTimer ) + if(mScrollTimer) { mScrollTimer.Stop(); } @@ -1809,12 +1795,12 @@ struct Decorator::Impl : public ConnectionTracker */ bool OnScrollTimerTick() { - if( HANDLE_TYPE_COUNT != mHandleScrolling ) + if(HANDLE_TYPE_COUNT != mHandleScrolling) { float x = 0.f; float y = 0.f; - switch( mScrollDirection ) + switch(mScrollDirection) { case SCROLL_RIGHT: { @@ -1840,10 +1826,10 @@ struct Decorator::Impl : public ConnectionTracker break; } - mController.DecorationEvent( mHandleScrolling, - HANDLE_SCROLLING, - x, - y ); + mController.DecorationEvent(mHandleScrolling, + HANDLE_SCROLLING, + x, + y); } return true; @@ -1855,8 +1841,8 @@ struct Decorator::Impl : public ConnectionTracker PanGestureDetector mPanDetector; LongPressGestureDetector mLongPressDetector; - Timer mCursorBlinkTimer; ///< Timer to signal cursor to blink - Timer mScrollTimer; ///< Timer used to scroll the text when the grab handle is moved close to the edges. + Timer mCursorBlinkTimer; ///< Timer to signal cursor to blink + Timer mScrollTimer; ///< Timer used to scroll the text when the grab handle is moved close to the edges. Actor mActiveLayer; ///< Actor for active handles and alike that ensures they are above all else. PropertyNotification mHandleVerticalLessThanNotification; ///< Notifies when the 'y' coord of the active layer is less than a given value. @@ -1868,93 +1854,93 @@ struct Decorator::Impl : public ConnectionTracker Control mPrimaryCursor; Control mSecondaryCursor; - Actor mHighlightActor; ///< Actor to display highlight - Renderer mHighlightRenderer; - Shader mHighlightShader; ///< Shader used for highlight - Property::Map mQuadVertexFormat; - PopupImpl mCopyPastePopup; - TextSelectionPopup::Buttons mEnabledPopupButtons; /// Bit mask of currently enabled Popup buttons + Actor mHighlightActor; ///< Actor to display highlight + Renderer mHighlightRenderer; + Shader mHighlightShader; ///< Shader used for highlight + Property::Map mQuadVertexFormat; + PopupImpl mCopyPastePopup; + TextSelectionPopup::Buttons mEnabledPopupButtons; /// Bit mask of currently enabled Popup buttons TextSelectionPopupCallbackInterface& mTextSelectionPopupCallbackInterface; - std::string mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT]; - Vector4 mHandleColor; - - CursorImpl mCursor[CURSOR_COUNT]; - HandleImpl mHandle[HANDLE_TYPE_COUNT]; - - VertexBuffer mQuadVertices; - Geometry mQuadGeometry; - QuadContainer mHighlightQuadList; ///< Sub-selections that combine to create the complete selection highlight. - - Vector4 mBoundingBox; ///< The bounding box in world coords. - Vector4 mHighlightColor; ///< Color of the highlight - Vector2 mHighlightPosition; ///< The position of the highlight actor. - Size mHighlightSize; ///< The size of the highlighted text. - Size mControlSize; ///< The control's size. Set by the Relayout. - float mHighlightOutlineOffset; ///< The outline's offset. - - unsigned int mActiveCursor; - unsigned int mCursorBlinkInterval; - float mCursorBlinkDuration; - float mCursorWidth; ///< The width of the cursors in pixels. - HandleType mHandleScrolling; ///< The handle which is scrolling. - HandleType mHandleReleased; ///< The last handle released. - ScrollDirection mScrollDirection; ///< The direction of the scroll. - float mScrollThreshold; ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events. - float mScrollSpeed; ///< The scroll speed in pixels per second. - float mScrollDistance; ///< Distance the text scrolls during a scroll interval. - int mTextDepth; ///< The depth used to render the text. - - bool mActiveCopyPastePopup : 1; - bool mPopupSetNewPosition : 1; - bool mCursorBlinkStatus : 1; ///< Flag to switch between blink on and blink off. - bool mDelayCursorBlink : 1; ///< Used to avoid cursor blinking when entering text. - bool mPrimaryCursorVisible : 1; ///< Whether the primary cursor is visible. - bool mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible. - bool mFlipSelectionHandlesOnCross : 1; ///< Whether to flip the selection handles as soon as they cross. - bool mFlipLeftSelectionHandleDirection : 1; ///< Whether to flip the left selection handle image because of the character's direction. - bool mFlipRightSelectionHandleDirection : 1; ///< Whether to flip the right selection handle image because of the character's direction. - bool mIsHandlePanning : 1; ///< Whether any of the handles is moving. - bool mIsHandleCurrentlyCrossed : 1; ///< Whether the handles are crossed. - bool mIsHandlePreviouslyCrossed : 1; ///< Whether the handles where crossed at the last handle touch up. - bool mNotifyEndOfScroll : 1; ///< Whether to notify the end of the scroll. - bool mHorizontalScrollingEnabled : 1; ///< Whether the horizontal scrolling is enabled. - bool mVerticalScrollingEnabled : 1; ///< Whether the vertical scrolling is enabled. - bool mSmoothHandlePanEnabled : 1; ///< Whether to pan smoothly the handles. - bool mIsHighlightBoxActive : 1; ///< Whether the highlight box is active. - bool mHidePrimaryCursorAndGrabHandle : 1; ///< Whether the primary cursor and grab are hidden always. + std::string mHandleImages[HANDLE_TYPE_COUNT][HANDLE_IMAGE_TYPE_COUNT]; + Vector4 mHandleColor; + + CursorImpl mCursor[CURSOR_COUNT]; + HandleImpl mHandle[HANDLE_TYPE_COUNT]; + + VertexBuffer mQuadVertices; + Geometry mQuadGeometry; + QuadContainer mHighlightQuadList; ///< Sub-selections that combine to create the complete selection highlight. + + Vector4 mBoundingBox; ///< The bounding box in world coords. + Vector4 mHighlightColor; ///< Color of the highlight + Vector2 mHighlightPosition; ///< The position of the highlight actor. + Size mHighlightSize; ///< The size of the highlighted text. + Size mControlSize; ///< The control's size. Set by the Relayout. + float mHighlightOutlineOffset; ///< The outline's offset. + + unsigned int mActiveCursor; + unsigned int mCursorBlinkInterval; + float mCursorBlinkDuration; + float mCursorWidth; ///< The width of the cursors in pixels. + HandleType mHandleScrolling; ///< The handle which is scrolling. + HandleType mHandleReleased; ///< The last handle released. + ScrollDirection mScrollDirection; ///< The direction of the scroll. + float mScrollThreshold; ///< Defines a square area inside the control, close to the edge. A cursor entering this area will trigger scroll events. + float mScrollSpeed; ///< The scroll speed in pixels per second. + float mScrollDistance; ///< Distance the text scrolls during a scroll interval. + int mTextDepth; ///< The depth used to render the text. + + bool mActiveCopyPastePopup : 1; + bool mPopupSetNewPosition : 1; + bool mCursorBlinkStatus : 1; ///< Flag to switch between blink on and blink off. + bool mDelayCursorBlink : 1; ///< Used to avoid cursor blinking when entering text. + bool mPrimaryCursorVisible : 1; ///< Whether the primary cursor is visible. + bool mSecondaryCursorVisible : 1; ///< Whether the secondary cursor is visible. + bool mFlipSelectionHandlesOnCross : 1; ///< Whether to flip the selection handles as soon as they cross. + bool mFlipLeftSelectionHandleDirection : 1; ///< Whether to flip the left selection handle image because of the character's direction. + bool mFlipRightSelectionHandleDirection : 1; ///< Whether to flip the right selection handle image because of the character's direction. + bool mIsHandlePanning : 1; ///< Whether any of the handles is moving. + bool mIsHandleCurrentlyCrossed : 1; ///< Whether the handles are crossed. + bool mIsHandlePreviouslyCrossed : 1; ///< Whether the handles where crossed at the last handle touch up. + bool mNotifyEndOfScroll : 1; ///< Whether to notify the end of the scroll. + bool mHorizontalScrollingEnabled : 1; ///< Whether the horizontal scrolling is enabled. + bool mVerticalScrollingEnabled : 1; ///< Whether the vertical scrolling is enabled. + bool mSmoothHandlePanEnabled : 1; ///< Whether to pan smoothly the handles. + bool mIsHighlightBoxActive : 1; ///< Whether the highlight box is active. + bool mHidePrimaryCursorAndGrabHandle : 1; ///< Whether the primary cursor and grab are hidden always. }; -DecoratorPtr Decorator::New( ControllerInterface& controller, - TextSelectionPopupCallbackInterface& callbackInterface ) +DecoratorPtr Decorator::New(ControllerInterface& controller, + TextSelectionPopupCallbackInterface& callbackInterface) { - return DecoratorPtr( new Decorator( controller, - callbackInterface ) ); + return DecoratorPtr(new Decorator(controller, + callbackInterface)); } -void Decorator::SetBoundingBox( const Rect& boundingBox ) +void Decorator::SetBoundingBox(const Rect& boundingBox) { - LocalToWorldCoordinatesBoundingBox( boundingBox, mImpl->mBoundingBox ); + LocalToWorldCoordinatesBoundingBox(boundingBox, mImpl->mBoundingBox); } -void Decorator::GetBoundingBox( Rect& boundingBox ) const +void Decorator::GetBoundingBox(Rect& boundingBox) const { - WorldToLocalCoordinatesBoundingBox( mImpl->mBoundingBox, boundingBox ); + WorldToLocalCoordinatesBoundingBox(mImpl->mBoundingBox, boundingBox); } -void Decorator::Relayout( const Vector2& size ) +void Decorator::Relayout(const Vector2& size) { - mImpl->Relayout( size ); + mImpl->Relayout(size); } -void Decorator::UpdatePositions( const Vector2& scrollOffset ) +void Decorator::UpdatePositions(const Vector2& scrollOffset) { - mImpl->UpdatePositions( scrollOffset ); + mImpl->UpdatePositions(scrollOffset); } /** Cursor **/ -void Decorator::SetActiveCursor( ActiveCursor activeCursor ) +void Decorator::SetActiveCursor(ActiveCursor activeCursor) { mImpl->mActiveCursor = activeCursor; } @@ -1964,62 +1950,62 @@ unsigned int Decorator::GetActiveCursor() const return mImpl->mActiveCursor; } -void Decorator::SetPosition( Cursor cursor, float x, float y, float cursorHeight, float lineHeight ) +void Decorator::SetPosition(Cursor cursor, float x, float y, float cursorHeight, float lineHeight) { Impl::CursorImpl& cursorImpl = mImpl->mCursor[cursor]; - cursorImpl.position.x = x; - cursorImpl.position.y = y; + cursorImpl.position.x = x; + cursorImpl.position.y = y; cursorImpl.cursorHeight = cursorHeight; - cursorImpl.lineHeight = lineHeight; + cursorImpl.lineHeight = lineHeight; } -void Decorator::GetPosition( Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight ) const +void Decorator::GetPosition(Cursor cursor, float& x, float& y, float& cursorHeight, float& lineHeight) const { const Impl::CursorImpl& cursorImpl = mImpl->mCursor[cursor]; - x = cursorImpl.position.x; - y = cursorImpl.position.y; + x = cursorImpl.position.x; + y = cursorImpl.position.y; cursorHeight = cursorImpl.cursorHeight; - lineHeight = cursorImpl.lineHeight; + lineHeight = cursorImpl.lineHeight; } -const Vector2& Decorator::GetPosition( Cursor cursor ) const +const Vector2& Decorator::GetPosition(Cursor cursor) const { return mImpl->mCursor[cursor].position; } -void Decorator::SetGlyphOffset( Cursor cursor, float glyphOffset ) +void Decorator::SetGlyphOffset(Cursor cursor, float glyphOffset) { Impl::CursorImpl& cursorImpl = mImpl->mCursor[cursor]; cursorImpl.glyphOffset = glyphOffset; } -const float Decorator::GetGlyphOffset( Cursor cursor) const +const float Decorator::GetGlyphOffset(Cursor cursor) const { return mImpl->mCursor[cursor].glyphOffset; } -void Decorator::SetCursorColor( Cursor cursor, const Dali::Vector4& color ) +void Decorator::SetCursorColor(Cursor cursor, const Dali::Vector4& color) { mImpl->mCursor[cursor].color = color; } -const Dali::Vector4& Decorator::GetColor( Cursor cursor ) const +const Dali::Vector4& Decorator::GetColor(Cursor cursor) const { return mImpl->mCursor[cursor].color; } void Decorator::StartCursorBlink() { - if ( !mImpl->mCursorBlinkTimer ) + if(!mImpl->mCursorBlinkTimer) { - mImpl->mCursorBlinkTimer = Timer::New( mImpl->mCursorBlinkInterval ); - mImpl->mCursorBlinkTimer.TickSignal().Connect( mImpl, &Decorator::Impl::OnCursorBlinkTimerTick ); + mImpl->mCursorBlinkTimer = Timer::New(mImpl->mCursorBlinkInterval); + mImpl->mCursorBlinkTimer.TickSignal().Connect(mImpl, &Decorator::Impl::OnCursorBlinkTimerTick); } - if ( !mImpl->mCursorBlinkTimer.IsRunning() ) + if(!mImpl->mCursorBlinkTimer.IsRunning()) { mImpl->mCursorBlinkTimer.Start(); } @@ -2027,7 +2013,7 @@ void Decorator::StartCursorBlink() void Decorator::StopCursorBlink() { - if ( mImpl->mCursorBlinkTimer ) + if(mImpl->mCursorBlinkTimer) { mImpl->mCursorBlinkTimer.Stop(); } @@ -2038,20 +2024,20 @@ void Decorator::StopCursorBlink() void Decorator::DelayCursorBlink() { mImpl->mCursorBlinkStatus = true; // Show cursor for a bit longer - mImpl->mDelayCursorBlink = true; + mImpl->mDelayCursorBlink = true; } -void Decorator::SetCursorBlinkInterval( float seconds ) +void Decorator::SetCursorBlinkInterval(float seconds) { - mImpl->mCursorBlinkInterval = static_cast( seconds * TO_MILLISECONDS ); // Convert to milliseconds + mImpl->mCursorBlinkInterval = static_cast(seconds * TO_MILLISECONDS); // Convert to milliseconds } float Decorator::GetCursorBlinkInterval() const { - return static_cast( mImpl->mCursorBlinkInterval ) * TO_SECONDS; + return static_cast(mImpl->mCursorBlinkInterval) * TO_SECONDS; } -void Decorator::SetCursorBlinkDuration( float seconds ) +void Decorator::SetCursorBlinkDuration(float seconds) { mImpl->mCursorBlinkDuration = seconds; } @@ -2061,30 +2047,30 @@ float Decorator::GetCursorBlinkDuration() const return mImpl->mCursorBlinkDuration; } -void Decorator::SetCursorWidth( int width ) +void Decorator::SetCursorWidth(int width) { - mImpl->mCursorWidth = static_cast( width ); + mImpl->mCursorWidth = static_cast(width); } int Decorator::GetCursorWidth() const { - return static_cast( mImpl->mCursorWidth ); + return static_cast(mImpl->mCursorWidth); } -void Decorator::SetEditable( bool editable ) +void Decorator::SetEditable(bool editable) { mImpl->mHidePrimaryCursorAndGrabHandle = !editable; - mImpl->Relayout( mImpl->mControlSize ); + mImpl->Relayout(mImpl->mControlSize); } /** Handles **/ -void Decorator::SetHandleActive( HandleType handleType, bool active ) +void Decorator::SetHandleActive(HandleType handleType, bool active) { mImpl->mHandle[handleType].active = active; - if( !active ) + if(!active) { - if( ( LEFT_SELECTION_HANDLE == handleType ) || ( RIGHT_SELECTION_HANDLE == handleType ) ) + if((LEFT_SELECTION_HANDLE == handleType) || (RIGHT_SELECTION_HANDLE == handleType)) { mImpl->mIsHandlePreviouslyCrossed = false; } @@ -2093,32 +2079,31 @@ void Decorator::SetHandleActive( HandleType handleType, bool active ) // The problem is the handle actor does not receive the touch event with the Interrupt // state when the power button is pressed and the application goes to background. mImpl->mHandle[handleType].pressed = false; - const bool imageReleased = mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED].size(); - ImageView imageView = mImpl->mHandle[handleType].actor; - if( imageReleased && imageView ) + const bool imageReleased = mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED].size(); + ImageView imageView = mImpl->mHandle[handleType].actor; + if(imageReleased && imageView) { - imageView.SetImage( mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED] ); + imageView.SetImage(mImpl->mHandleImages[handleType][HANDLE_IMAGE_RELEASED]); } } - } -bool Decorator::IsHandleActive( HandleType handleType ) const +bool Decorator::IsHandleActive(HandleType handleType) const { - return mImpl->mHandle[handleType].active ; + return mImpl->mHandle[handleType].active; } -void Decorator::SetHandleImage( HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName ) +void Decorator::SetHandleImage(HandleType handleType, HandleImageType handleImageType, const std::string& imageFileName) { - mImpl->SetHandleImage( handleType, handleImageType, imageFileName ); + mImpl->SetHandleImage(handleType, handleImageType, imageFileName); } -const std::string& Decorator::GetHandleImage( HandleType handleType, HandleImageType handleImageType ) const +const std::string& Decorator::GetHandleImage(HandleType handleType, HandleImageType handleImageType) const { return mImpl->mHandleImages[handleType][handleImageType]; } -void Decorator::SetHandleColor( const Vector4& color ) +void Decorator::SetHandleColor(const Vector4& color) { mImpl->mHandleColor = color; } @@ -2128,7 +2113,7 @@ const Vector4& Decorator::GetHandleColor() const return mImpl->mHandleColor; } -void Decorator::SetPosition( HandleType handleType, float x, float y, float height ) +void Decorator::SetPosition(HandleType handleType, float x, float y, float height) { // Adjust handle's displacement Impl::HandleImpl& handle = mImpl->mHandle[handleType]; @@ -2137,74 +2122,74 @@ void Decorator::SetPosition( HandleType handleType, float x, float y, float heig handle.position.y = y; handle.lineHeight = height; - if( mImpl->mSmoothHandlePanEnabled ) + if(mImpl->mSmoothHandlePanEnabled) { handle.grabDisplacementX = 0.f; handle.grabDisplacementY = 0.f; } } -void Decorator::GetPosition( HandleType handleType, float& x, float& y, float& height ) const +void Decorator::GetPosition(HandleType handleType, float& x, float& y, float& height) const { Impl::HandleImpl& handle = mImpl->mHandle[handleType]; - x = handle.position.x; - y = handle.position.y; + x = handle.position.x; + y = handle.position.y; height = handle.lineHeight; } -const Vector2& Decorator::GetPosition( HandleType handleType ) const +const Vector2& Decorator::GetPosition(HandleType handleType) const { return mImpl->mHandle[handleType].position; } -void Decorator::FlipHandleVertically( HandleType handleType, bool flip ) +void Decorator::FlipHandleVertically(HandleType handleType, bool flip) { mImpl->mHandle[handleType].verticallyFlippedPreferred = flip; } -bool Decorator::IsHandleVerticallyFlipped( HandleType handleType ) const +bool Decorator::IsHandleVerticallyFlipped(HandleType handleType) const { return mImpl->mHandle[handleType].verticallyFlippedPreferred; } -void Decorator::FlipSelectionHandlesOnCrossEnabled( bool enable ) +void Decorator::FlipSelectionHandlesOnCrossEnabled(bool enable) { mImpl->mFlipSelectionHandlesOnCross = enable; } -void Decorator::SetSelectionHandleFlipState( bool indicesSwapped, bool left, bool right ) +void Decorator::SetSelectionHandleFlipState(bool indicesSwapped, bool left, bool right) { - mImpl->mIsHandleCurrentlyCrossed = indicesSwapped; - mImpl->mFlipLeftSelectionHandleDirection = left; + mImpl->mIsHandleCurrentlyCrossed = indicesSwapped; + mImpl->mFlipLeftSelectionHandleDirection = left; mImpl->mFlipRightSelectionHandleDirection = right; } -void Decorator::AddHighlight( unsigned int index, const Vector4& quad ) +void Decorator::AddHighlight(unsigned int index, const Vector4& quad) { - *( mImpl->mHighlightQuadList.Begin() + index ) = quad; + *(mImpl->mHighlightQuadList.Begin() + index) = quad; } -void Decorator::SetHighLightBox( const Vector2& position, const Size& size, float outlineOffset ) +void Decorator::SetHighLightBox(const Vector2& position, const Size& size, float outlineOffset) { - mImpl->mHighlightPosition = position; - mImpl->mHighlightSize = size; + mImpl->mHighlightPosition = position; + mImpl->mHighlightSize = size; mImpl->mHighlightOutlineOffset = outlineOffset; } void Decorator::ClearHighlights() { mImpl->mHighlightQuadList.Clear(); - mImpl->mHighlightPosition = Vector2::ZERO; + mImpl->mHighlightPosition = Vector2::ZERO; mImpl->mHighlightOutlineOffset = 0.f; } -void Decorator::ResizeHighlightQuads( unsigned int numberOfQuads ) +void Decorator::ResizeHighlightQuads(unsigned int numberOfQuads) { - mImpl->mHighlightQuadList.Resize( numberOfQuads ); + mImpl->mHighlightQuadList.Resize(numberOfQuads); } -void Decorator::SetHighlightColor( const Vector4& color ) +void Decorator::SetHighlightColor(const Vector4& color) { mImpl->mHighlightColor = color; } @@ -2214,7 +2199,7 @@ const Vector4& Decorator::GetHighlightColor() const return mImpl->mHighlightColor; } -void Decorator::SetHighlightActive( bool active ) +void Decorator::SetHighlightActive(bool active) { mImpl->mIsHighlightBoxActive = active; } @@ -2226,15 +2211,15 @@ bool Decorator::IsHighlightActive() const bool Decorator::IsHighlightVisible() const { - return ( mImpl->mHighlightActor && mImpl->mHighlightActor.GetParent() ); + return (mImpl->mHighlightActor && mImpl->mHighlightActor.GetParent()); } -void Decorator::SetTextDepth( int textDepth ) +void Decorator::SetTextDepth(int textDepth) { mImpl->mTextDepth = textDepth; } -void Decorator::SetPopupActive( bool active ) +void Decorator::SetPopupActive(bool active) { mImpl->mActiveCopyPastePopup = active; } @@ -2244,21 +2229,21 @@ bool Decorator::IsPopupActive() const return mImpl->mActiveCopyPastePopup; } -void Decorator::SetEnabledPopupButtons( TextSelectionPopup::Buttons& enabledButtonsBitMask ) +void Decorator::SetEnabledPopupButtons(TextSelectionPopup::Buttons& enabledButtonsBitMask) { mImpl->mEnabledPopupButtons = enabledButtonsBitMask; - if ( !mImpl->mCopyPastePopup.actor ) + if(!mImpl->mCopyPastePopup.actor) { - mImpl->mCopyPastePopup.actor = TextSelectionPopup::New( &mImpl->mTextSelectionPopupCallbackInterface ); + mImpl->mCopyPastePopup.actor = TextSelectionPopup::New(&mImpl->mTextSelectionPopupCallbackInterface); #ifdef DECORATOR_DEBUG - mImpl->mCopyPastePopup.actor.SetProperty( Dali::Actor::Property::NAME,"mCopyPastePopup"); + mImpl->mCopyPastePopup.actor.SetProperty(Dali::Actor::Property::NAME, "mCopyPastePopup"); #endif - mImpl->mCopyPastePopup.actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - mImpl->mCopyPastePopup.actor.OnRelayoutSignal().Connect( mImpl, &Decorator::Impl::SetPopupPosition ); // Position popup after size negotiation + mImpl->mCopyPastePopup.actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + mImpl->mCopyPastePopup.actor.OnRelayoutSignal().Connect(mImpl, &Decorator::Impl::SetPopupPosition); // Position popup after size negotiation } - mImpl->mCopyPastePopup.actor.EnableButtons( mImpl->mEnabledPopupButtons ); + mImpl->mCopyPastePopup.actor.EnableButtons(mImpl->mEnabledPopupButtons); } TextSelectionPopup::Buttons& Decorator::GetEnabledPopupButtons() @@ -2268,9 +2253,9 @@ TextSelectionPopup::Buttons& Decorator::GetEnabledPopupButtons() /** Scroll **/ -void Decorator::SetScrollThreshold( float threshold ) +void Decorator::SetScrollThreshold(float threshold) { - mImpl->SetScrollThreshold( threshold ); + mImpl->SetScrollThreshold(threshold); } float Decorator::GetScrollThreshold() const @@ -2278,9 +2263,9 @@ float Decorator::GetScrollThreshold() const return mImpl->GetScrollThreshold(); } -void Decorator::SetScrollSpeed( float speed ) +void Decorator::SetScrollSpeed(float speed) { - mImpl->SetScrollSpeed( speed ); + mImpl->SetScrollSpeed(speed); } float Decorator::GetScrollSpeed() const @@ -2293,7 +2278,7 @@ void Decorator::NotifyEndOfScroll() mImpl->NotifyEndOfScroll(); } -void Decorator::SetHorizontalScrollEnabled( bool enable ) +void Decorator::SetHorizontalScrollEnabled(bool enable) { mImpl->mHorizontalScrollingEnabled = enable; } @@ -2303,7 +2288,7 @@ bool Decorator::IsHorizontalScrollEnabled() const return mImpl->mHorizontalScrollingEnabled; } -void Decorator::SetVerticalScrollEnabled( bool enable ) +void Decorator::SetVerticalScrollEnabled(bool enable) { mImpl->mVerticalScrollingEnabled = enable; } @@ -2313,7 +2298,7 @@ bool Decorator::IsVerticalScrollEnabled() const return mImpl->mVerticalScrollingEnabled; } -void Decorator::SetSmoothHandlePanEnabled( bool enable ) +void Decorator::SetSmoothHandlePanEnabled(bool enable) { mImpl->mSmoothHandlePanEnabled = enable; } @@ -2328,11 +2313,11 @@ Decorator::~Decorator() delete mImpl; } -Decorator::Decorator( ControllerInterface& controller, - TextSelectionPopupCallbackInterface& callbackInterface ) -: mImpl( NULL ) +Decorator::Decorator(ControllerInterface& controller, + TextSelectionPopupCallbackInterface& callbackInterface) +: mImpl(NULL) { - mImpl = new Decorator::Impl( controller, callbackInterface ); + mImpl = new Decorator::Impl(controller, callbackInterface); } } // namespace Text diff --git a/dali-toolkit/internal/text/glyph-metrics-helper.cpp b/dali-toolkit/internal/text/glyph-metrics-helper.cpp old mode 100755 new mode 100644 index b47889e..1f27a84 --- a/dali-toolkit/internal/text/glyph-metrics-helper.cpp +++ b/dali-toolkit/internal/text/glyph-metrics-helper.cpp @@ -1,6 +1,6 @@ /* - * 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. @@ -21,22 +21,19 @@ namespace Dali { - namespace Toolkit { - namespace Text { - -Length GetNumberOfGlyphsOfGroup( GlyphIndex glyphIndex, - GlyphIndex lastGlyphPlusOne, - const Length* const charactersPerGlyphBuffer ) +Length GetNumberOfGlyphsOfGroup(GlyphIndex glyphIndex, + GlyphIndex lastGlyphPlusOne, + const Length* const charactersPerGlyphBuffer) { Length numberOfGLyphsInGroup = 1u; - for( GlyphIndex index = glyphIndex; index < lastGlyphPlusOne; ++index ) + for(GlyphIndex index = glyphIndex; index < lastGlyphPlusOne; ++index) { - if( 0u == *( charactersPerGlyphBuffer + index ) ) + if(0u == *(charactersPerGlyphBuffer + index)) { ++numberOfGLyphsInGroup; } @@ -49,50 +46,50 @@ Length GetNumberOfGlyphsOfGroup( GlyphIndex glyphIndex, return numberOfGLyphsInGroup; } -void GetGlyphsMetrics( GlyphIndex glyphIndex, - Length numberOfGlyphs, - GlyphMetrics& glyphMetrics, - const GlyphInfo* const glyphsBuffer, - MetricsPtr& metrics ) +void GetGlyphsMetrics(GlyphIndex glyphIndex, + Length numberOfGlyphs, + GlyphMetrics& glyphMetrics, + const GlyphInfo* const glyphsBuffer, + MetricsPtr& metrics) { - const GlyphInfo& firstGlyph = *( glyphsBuffer + glyphIndex ); + const GlyphInfo& firstGlyph = *(glyphsBuffer + glyphIndex); Text::FontMetrics fontMetrics; - if( 0u != firstGlyph.fontId ) + if(0u != firstGlyph.fontId) { - metrics->GetFontMetrics( firstGlyph.fontId, fontMetrics ); + metrics->GetFontMetrics(firstGlyph.fontId, fontMetrics); } - else if( 0u != firstGlyph.index ) + else if(0u != firstGlyph.index) { // It may be an embedded image. - fontMetrics.ascender = firstGlyph.height; + fontMetrics.ascender = firstGlyph.height; fontMetrics.descender = 0.f; - fontMetrics.height = fontMetrics.ascender; + fontMetrics.height = fontMetrics.ascender; } - const bool isItalicFont = metrics->HasItalicStyle( firstGlyph.fontId ); + const bool isItalicFont = metrics->HasItalicStyle(firstGlyph.fontId); - glyphMetrics.fontId = firstGlyph.fontId; + glyphMetrics.fontId = firstGlyph.fontId; glyphMetrics.fontHeight = fontMetrics.height; - glyphMetrics.width = firstGlyph.width; - glyphMetrics.advance = firstGlyph.advance; - glyphMetrics.ascender = fontMetrics.ascender; - glyphMetrics.xBearing = firstGlyph.xBearing; + glyphMetrics.width = firstGlyph.width; + glyphMetrics.advance = firstGlyph.advance; + glyphMetrics.ascender = fontMetrics.ascender; + glyphMetrics.xBearing = firstGlyph.xBearing; - if( 1u < numberOfGlyphs ) + if(1u < numberOfGlyphs) { - float maxWidthEdge = firstGlyph.xBearing + firstGlyph.width; + float maxWidthEdge = firstGlyph.xBearing + firstGlyph.width; - for( unsigned int i = 1u; i < numberOfGlyphs; ++i ) + for(unsigned int i = 1u; i < numberOfGlyphs; ++i) { - const GlyphInfo& glyphInfo = *( glyphsBuffer + glyphIndex + i ); + const GlyphInfo& glyphInfo = *(glyphsBuffer + glyphIndex + i); // update the initial xBearing if smaller. - glyphMetrics.xBearing = std::min( glyphMetrics.xBearing, glyphMetrics.advance + glyphInfo.xBearing ); + glyphMetrics.xBearing = std::min(glyphMetrics.xBearing, glyphMetrics.advance + glyphInfo.xBearing); // update the max width edge if bigger. const float currentMaxGlyphWidthEdge = glyphMetrics.advance + glyphInfo.xBearing + glyphInfo.width; - maxWidthEdge = std::max( maxWidthEdge, currentMaxGlyphWidthEdge ); + maxWidthEdge = std::max(maxWidthEdge, currentMaxGlyphWidthEdge); glyphMetrics.advance += glyphInfo.advance; } @@ -100,7 +97,7 @@ void GetGlyphsMetrics( GlyphIndex glyphIndex, glyphMetrics.width = maxWidthEdge - glyphMetrics.xBearing; } - glyphMetrics.width += ( firstGlyph.isItalicRequired && !isItalicFont ) ? TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE * firstGlyph.height : 0.f; + glyphMetrics.width += (firstGlyph.isItalicRequired && !isItalicFont) ? TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE * firstGlyph.height : 0.f; } } // namespace Text diff --git a/dali-toolkit/internal/text/hidden-text.cpp b/dali-toolkit/internal/text/hidden-text.cpp index 0dc8b9e..1adbe83 100644 --- a/dali-toolkit/internal/text/hidden-text.cpp +++ b/dali-toolkit/internal/text/hidden-text.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,119 +23,116 @@ using namespace Dali::Toolkit; -const uint32_t STAR = 0x2A; // Set default substitute character as '*' -const int DEFAULT_SHOW_DURATION = 1000; +const uint32_t STAR = 0x2A; // Set default substitute character as '*' +const int DEFAULT_SHOW_DURATION = 1000; namespace Dali { - namespace Toolkit { - namespace Text { - -const char * const PROPERTY_MODE = "mode"; -const char * const PROPERTY_SUBSTITUTE_CHARACTER = "substituteCharacter"; -const char * const PROPERTY_SUBSTITUTE_COUNT = "substituteCount"; -const char * const PROPERTY_SHOW_DURATION = "showDuration"; - -HiddenText::HiddenText( Observer* observer ) -: mObserver( observer ), - mHideMode( static_cast< int >( Toolkit::HiddenInput::Mode::HIDE_NONE ) ), - mSubstituteText( STAR ), - mDisplayDuration( DEFAULT_SHOW_DURATION ), - mSubstituteCount( 0 ), - mPreviousTextCount( 0 ) +const char* const PROPERTY_MODE = "mode"; +const char* const PROPERTY_SUBSTITUTE_CHARACTER = "substituteCharacter"; +const char* const PROPERTY_SUBSTITUTE_COUNT = "substituteCount"; +const char* const PROPERTY_SHOW_DURATION = "showDuration"; + +HiddenText::HiddenText(Observer* observer) +: mObserver(observer), + mHideMode(static_cast(Toolkit::HiddenInput::Mode::HIDE_NONE)), + mSubstituteText(STAR), + mDisplayDuration(DEFAULT_SHOW_DURATION), + mSubstituteCount(0), + mPreviousTextCount(0) { - mTimer = Timer::New( mDisplayDuration ); - mTimer.TickSignal().Connect( this, &HiddenText::OnTick ); + mTimer = Timer::New(mDisplayDuration); + mTimer.TickSignal().Connect(this, &HiddenText::OnTick); } -void HiddenText::SetProperties( const Property::Map& map ) +void HiddenText::SetProperties(const Property::Map& map) { - const Property::Map::SizeType count = map.Count(); + const Property::Map::SizeType count = map.Count(); - for ( Property::Map::SizeType position = 0; position < count; ++position ) - { - KeyValuePair keyValue = map.GetKeyValue( position ); - Property::Key& key = keyValue.first; - Property::Value& value = keyValue.second; + for(Property::Map::SizeType position = 0; position < count; ++position) + { + KeyValuePair keyValue = map.GetKeyValue(position); + Property::Key& key = keyValue.first; + Property::Value& value = keyValue.second; - if( key == Toolkit::HiddenInput::Property::MODE || key == PROPERTY_MODE ) - { - value.Get( mHideMode ); - } - else if( key == Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER || key == PROPERTY_SUBSTITUTE_CHARACTER ) - { - value.Get( mSubstituteText ); - } - else if( key == Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT || key == PROPERTY_SUBSTITUTE_COUNT ) - { - value.Get( mSubstituteCount ); - } - else if( key == Toolkit::HiddenInput::Property::SHOW_LAST_CHARACTER_DURATION || key == PROPERTY_SHOW_DURATION ) - { - value.Get( mDisplayDuration ); - } + if(key == Toolkit::HiddenInput::Property::MODE || key == PROPERTY_MODE) + { + value.Get(mHideMode); + } + else if(key == Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER || key == PROPERTY_SUBSTITUTE_CHARACTER) + { + value.Get(mSubstituteText); } + else if(key == Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT || key == PROPERTY_SUBSTITUTE_COUNT) + { + value.Get(mSubstituteCount); + } + else if(key == Toolkit::HiddenInput::Property::SHOW_LAST_CHARACTER_DURATION || key == PROPERTY_SHOW_DURATION) + { + value.Get(mDisplayDuration); + } + } } -void HiddenText::GetProperties( Property::Map& map ) +void HiddenText::GetProperties(Property::Map& map) { - map[Toolkit::HiddenInput::Property::MODE] = mHideMode; - map[Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER] = mSubstituteText; - map[Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT] = mSubstituteCount; + map[Toolkit::HiddenInput::Property::MODE] = mHideMode; + map[Toolkit::HiddenInput::Property::SUBSTITUTE_CHARACTER] = mSubstituteText; + map[Toolkit::HiddenInput::Property::SUBSTITUTE_COUNT] = mSubstituteCount; map[Toolkit::HiddenInput::Property::SHOW_LAST_CHARACTER_DURATION] = mDisplayDuration; } -void HiddenText::Substitute( const Vector& source, Vector& destination ) +void HiddenText::Substitute(const Vector& source, Vector& destination) { const Length characterCount = source.Count(); - destination.Resize( characterCount ); + destination.Resize(characterCount); - uint32_t* begin = destination.Begin(); - uint32_t* end = begin + characterCount; + uint32_t* begin = destination.Begin(); + uint32_t* end = begin + characterCount; uint32_t* hideStart = NULL; - uint32_t* hideEnd = NULL; + uint32_t* hideEnd = NULL; uint32_t* sourcePos = source.Begin(); - switch ( mHideMode ) + switch(mHideMode) { case Toolkit::HiddenInput::Mode::HIDE_NONE: { hideStart = NULL; - hideEnd = NULL; + hideEnd = NULL; break; } case Toolkit::HiddenInput::Mode::HIDE_ALL: { hideStart = begin; - hideEnd = end; + hideEnd = end; break; } case Toolkit::HiddenInput::Mode::HIDE_COUNT: { hideStart = begin; - hideEnd = begin + mSubstituteCount; + hideEnd = begin + mSubstituteCount; break; } case Toolkit::HiddenInput::Mode::SHOW_COUNT: { hideStart = begin + mSubstituteCount; - hideEnd = end; + hideEnd = end; break; } case Toolkit::HiddenInput::Mode::SHOW_LAST_CHARACTER: { - if (mPreviousTextCount < characterCount) + if(mPreviousTextCount < characterCount) { hideStart = begin; - hideEnd = end-1; - if ( mDisplayDuration > 0 ) + hideEnd = end - 1; + if(mDisplayDuration > 0) { - mTimer.SetInterval( mDisplayDuration ); + mTimer.SetInterval(mDisplayDuration); mTimer.Start(); } else @@ -146,14 +143,14 @@ void HiddenText::Substitute( const Vector& source, Vector& else { hideStart = begin; - hideEnd = end; + hideEnd = end; } break; } } - for (; begin < end; ++begin ) + for(; begin < end; ++begin) { - if (begin >= hideStart && begin < hideEnd) + if(begin >= hideStart && begin < hideEnd) { *begin = static_cast(mSubstituteText); sourcePos++; @@ -168,7 +165,7 @@ void HiddenText::Substitute( const Vector& source, Vector& bool HiddenText::OnTick() { - if( mObserver != NULL ) + if(mObserver != NULL) { mObserver->DisplayTimeExpired(); } diff --git a/dali-toolkit/internal/text/layouts/layout-engine.cpp b/dali-toolkit/internal/text/layouts/layout-engine.cpp old mode 100755 new mode 100644 index 89c01ca..fcf5f5e --- a/dali-toolkit/internal/text/layouts/layout-engine.cpp +++ b/dali-toolkit/internal/text/layouts/layout-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. @@ -19,10 +19,10 @@ #include // EXTERNAL INCLUDES -#include -#include -#include #include +#include +#include +#include // INTERNAL INCLUDES #include @@ -32,32 +32,27 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace Layout { - namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_LAYOUT"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_LAYOUT"); #endif -const float MAX_FLOAT = std::numeric_limits::max(); -const CharacterDirection LTR = false; -const CharacterDirection RTL = !LTR; -const float LINE_SPACING = 0.f; -const float MIN_LINE_SIZE = 0.f; +const float MAX_FLOAT = std::numeric_limits::max(); +const CharacterDirection LTR = false; +const CharacterDirection RTL = !LTR; +const float LINE_SPACING = 0.f; +const float MIN_LINE_SIZE = 0.f; -inline bool isEmptyLineAtLast( const Vector& lines, const Vector::Iterator& line ) +inline bool isEmptyLineAtLast(const Vector& lines, const Vector::Iterator& line) { - return ( (*line).characterRun.numberOfCharacters == 0 && line + 1u == lines.End() ); + return ((*line).characterRun.numberOfCharacters == 0 && line + 1u == lines.End()); } } //namespace @@ -68,32 +63,34 @@ inline bool isEmptyLineAtLast( const Vector& lines, const VectorGetFontMetrics( glyphMetrics.fontId, fontMetrics ); + mMetrics->GetFontMetrics(glyphMetrics.fontId, fontMetrics); } else { - fontMetrics.ascender = glyphMetrics.fontHeight; - fontMetrics.descender = 0.f; - fontMetrics.height = fontMetrics.ascender; - fontMetrics.underlinePosition = 0.f; + fontMetrics.ascender = glyphMetrics.fontHeight; + fontMetrics.descender = 0.f; + fontMetrics.height = fontMetrics.ascender; + fontMetrics.underlinePosition = 0.f; fontMetrics.underlineThickness = 1.f; } // Sets the maximum ascender. - lineLayout.ascender = std::max( lineLayout.ascender, fontMetrics.ascender ); + lineLayout.ascender = std::max(lineLayout.ascender, fontMetrics.ascender); // Sets the minimum descender. - lineLayout.descender = std::min( lineLayout.descender, fontMetrics.descender ); + lineLayout.descender = std::min(lineLayout.descender, fontMetrics.descender); // Sets the line size - lineLayout.lineSpacing = mDefaultLineSize - ( lineLayout.ascender + -lineLayout.descender ); + lineLayout.lineSpacing = mDefaultLineSize - (lineLayout.ascender + -lineLayout.descender); lineLayout.lineSpacing = lineLayout.lineSpacing < 0.f ? 0.f : lineLayout.lineSpacing; // Add the line spacing @@ -178,96 +175,96 @@ struct Engine::Impl * @param[in,out] lineLayout The line layout. * @param[in] tmpLineLayout A temporary line layout. */ - void MergeLineLayout( LineLayout& lineLayout, - const LineLayout& tmpLineLayout ) + void MergeLineLayout(LineLayout& lineLayout, + const LineLayout& tmpLineLayout) { lineLayout.numberOfCharacters += tmpLineLayout.numberOfCharacters; lineLayout.numberOfGlyphs += tmpLineLayout.numberOfGlyphs; - lineLayout.penX = tmpLineLayout.penX; + lineLayout.penX = tmpLineLayout.penX; lineLayout.previousAdvance = tmpLineLayout.previousAdvance; - lineLayout.length = tmpLineLayout.length; + lineLayout.length = tmpLineLayout.length; lineLayout.whiteSpaceLengthEndOfLine = tmpLineLayout.whiteSpaceLengthEndOfLine; // Sets the maximum ascender. - lineLayout.ascender = std::max( lineLayout.ascender, tmpLineLayout.ascender ); + lineLayout.ascender = std::max(lineLayout.ascender, tmpLineLayout.ascender); // Sets the minimum descender. - lineLayout.descender = std::min( lineLayout.descender, tmpLineLayout.descender ); + lineLayout.descender = std::min(lineLayout.descender, tmpLineLayout.descender); } - void LayoutRightToLeft( const Parameters& parameters, - const BidirectionalLineInfoRun& bidirectionalLineInfo, - float& length, - float& whiteSpaceLengthEndOfLine ) + void LayoutRightToLeft(const Parameters& parameters, + const BidirectionalLineInfoRun& bidirectionalLineInfo, + float& length, + float& whiteSpaceLengthEndOfLine) { - const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin(); - const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin(); - const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin(); + const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin(); + const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin(); + const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin(); const GlyphIndex* const charactersToGlyphsBuffer = parameters.textModel->mVisualModel->mCharactersToGlyph.Begin(); - const float outlineWidth = static_cast( parameters.textModel->GetOutlineWidth() ); + const float outlineWidth = static_cast(parameters.textModel->GetOutlineWidth()); const GlyphIndex lastGlyphOfParagraphPlusOne = parameters.startGlyphIndex + parameters.numberOfGlyphs; CharacterIndex characterLogicalIndex = 0u; - CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *( bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex ); + CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *(bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex); - if( RTL == bidirectionalLineInfo.direction ) + if(RTL == bidirectionalLineInfo.direction) { - while( TextAbstraction::IsWhiteSpace( *( textBuffer + characterVisualIndex ) ) ) + while(TextAbstraction::IsWhiteSpace(*(textBuffer + characterVisualIndex))) { - const GlyphInfo& glyphInfo = *( glyphsBuffer + *( charactersToGlyphsBuffer + characterVisualIndex ) ); + const GlyphInfo& glyphInfo = *(glyphsBuffer + *(charactersToGlyphsBuffer + characterVisualIndex)); whiteSpaceLengthEndOfLine += glyphInfo.advance; ++characterLogicalIndex; - characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *( bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex ); + characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *(bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex); } } - const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex ); + const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex); // Check whether the first glyph comes from a character that is shaped in multiple glyphs. - const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex, - lastGlyphOfParagraphPlusOne, - charactersPerGlyphBuffer ); + const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex, + lastGlyphOfParagraphPlusOne, + charactersPerGlyphBuffer); GlyphMetrics glyphMetrics; - GetGlyphsMetrics( glyphIndex, - numberOfGLyphsInGroup, - glyphMetrics, - glyphsBuffer, - mMetrics ); + GetGlyphsMetrics(glyphIndex, + numberOfGLyphsInGroup, + glyphMetrics, + glyphsBuffer, + mMetrics); float penX = -glyphMetrics.xBearing + mCursorWidth + outlineWidth; // Traverses the characters of the right to left paragraph. - for( ; characterLogicalIndex < bidirectionalLineInfo.characterRun.numberOfCharacters; ) + for(; characterLogicalIndex < bidirectionalLineInfo.characterRun.numberOfCharacters;) { // Convert the character in the logical order into the character in the visual order. - const CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *( bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex ); - const bool isWhiteSpace = TextAbstraction::IsWhiteSpace( *( textBuffer + characterVisualIndex ) ); + const CharacterIndex characterVisualIndex = bidirectionalLineInfo.characterRun.characterIndex + *(bidirectionalLineInfo.visualToLogicalMap + characterLogicalIndex); + const bool isWhiteSpace = TextAbstraction::IsWhiteSpace(*(textBuffer + characterVisualIndex)); - const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex ); + const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex); // Check whether this glyph comes from a character that is shaped in multiple glyphs. - const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex, - lastGlyphOfParagraphPlusOne, - charactersPerGlyphBuffer ); + const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex, + lastGlyphOfParagraphPlusOne, + charactersPerGlyphBuffer); - characterLogicalIndex += *( charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u ); + characterLogicalIndex += *(charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u); GlyphMetrics glyphMetrics; - GetGlyphsMetrics( glyphIndex, - numberOfGLyphsInGroup, - glyphMetrics, - glyphsBuffer, - mMetrics ); + GetGlyphsMetrics(glyphIndex, + numberOfGLyphsInGroup, + glyphMetrics, + glyphsBuffer, + mMetrics); - if( isWhiteSpace ) + if(isWhiteSpace) { - if( RTL == bidirectionalLineInfo.direction ) + if(RTL == bidirectionalLineInfo.direction) { length += glyphMetrics.advance; } @@ -279,21 +276,21 @@ struct Engine::Impl } else { - if( LTR == bidirectionalLineInfo.direction ) + if(LTR == bidirectionalLineInfo.direction) { whiteSpaceLengthEndOfLine = 0.f; } - length = std::max( length, penX + glyphMetrics.xBearing + glyphMetrics.width ); - penX += ( glyphMetrics.advance + parameters.interGlyphExtraAdvance ); + length = std::max(length, penX + glyphMetrics.xBearing + glyphMetrics.width); + penX += (glyphMetrics.advance + parameters.interGlyphExtraAdvance); } } } - void ReorderBiDiLayout( const Parameters& parameters, - LayoutBidiParameters& bidiParameters, - const LineLayout& currentLineLayout, - LineLayout& lineLayout, - bool breakInCharacters ) + void ReorderBiDiLayout(const Parameters& parameters, + LayoutBidiParameters& bidiParameters, + const LineLayout& currentLineLayout, + LineLayout& lineLayout, + bool breakInCharacters) { const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin(); @@ -303,65 +300,65 @@ struct Engine::Impl const Vector& bidirectionalParagraphsInfo = parameters.textModel->mLogicalModel->mBidirectionalParagraphInfo; const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo = bidirectionalParagraphsInfo[bidiParameters.bidiParagraphIndex]; - if( ( lineLayout.characterIndex >= bidirectionalParagraphInfo.characterRun.characterIndex ) && - ( lineLayout.characterIndex < bidirectionalParagraphInfo.characterRun.characterIndex + bidirectionalParagraphInfo.characterRun.numberOfCharacters ) ) + if((lineLayout.characterIndex >= bidirectionalParagraphInfo.characterRun.characterIndex) && + (lineLayout.characterIndex < bidirectionalParagraphInfo.characterRun.characterIndex + bidirectionalParagraphInfo.characterRun.numberOfCharacters)) { Vector& bidirectionalLinesInfo = parameters.textModel->mLogicalModel->mBidirectionalLineInfo; // Sets the visual to logical map tables needed to reorder the text. - ReorderLine( bidirectionalParagraphInfo, - bidirectionalLinesInfo, - bidiParameters.bidiLineIndex, - lineLayout.characterIndex, - lineLayout.numberOfCharacters, - bidiParameters.paragraphDirection ); + ReorderLine(bidirectionalParagraphInfo, + bidirectionalLinesInfo, + bidiParameters.bidiLineIndex, + lineLayout.characterIndex, + lineLayout.numberOfCharacters, + bidiParameters.paragraphDirection); // Recalculate the length of the line and update the layout. - const BidirectionalLineInfoRun& bidirectionalLineInfo = *( bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex ); + const BidirectionalLineInfoRun& bidirectionalLineInfo = *(bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex); - if( !bidirectionalLineInfo.isIdentity ) + if(!bidirectionalLineInfo.isIdentity) { - float length = 0.f; + float length = 0.f; float whiteSpaceLengthEndOfLine = 0.f; - LayoutRightToLeft( parameters, - bidirectionalLineInfo, - length, - whiteSpaceLengthEndOfLine ); + LayoutRightToLeft(parameters, + bidirectionalLineInfo, + length, + whiteSpaceLengthEndOfLine); lineLayout.whiteSpaceLengthEndOfLine = whiteSpaceLengthEndOfLine; - if( !Equals( length, lineLayout.length ) ) + if(!Equals(length, lineLayout.length)) { const bool isMultiline = mLayout == MULTI_LINE_BOX; - if( isMultiline && ( length > parameters.boundingBox.width ) ) + if(isMultiline && (length > parameters.boundingBox.width)) { - if( breakInCharacters || ( isMultiline && ( 0u == currentLineLayout.numberOfGlyphs ) ) ) + if(breakInCharacters || (isMultiline && (0u == currentLineLayout.numberOfGlyphs))) { // The word doesn't fit in one line. It has to be split by character. // Remove the last laid out glyph(s) as they doesn't fit. - for( GlyphIndex glyphIndex = lineLayout.glyphIndex + lineLayout.numberOfGlyphs - 1u; glyphIndex >= lineLayout.glyphIndex; ) + for(GlyphIndex glyphIndex = lineLayout.glyphIndex + lineLayout.numberOfGlyphs - 1u; glyphIndex >= lineLayout.glyphIndex;) { - const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex, - lastGlyphOfParagraphPlusOne, - charactersPerGlyphBuffer ); + const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex, + lastGlyphOfParagraphPlusOne, + charactersPerGlyphBuffer); - const Length numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u ); + const Length numberOfCharacters = *(charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u); lineLayout.numberOfGlyphs -= numberOfGLyphsInGroup; lineLayout.numberOfCharacters -= numberOfCharacters; - AdjustLayout( parameters, - bidiParameters, - bidirectionalParagraphInfo, - lineLayout ); + AdjustLayout(parameters, + bidiParameters, + bidirectionalParagraphInfo, + lineLayout); - if( lineLayout.length < parameters.boundingBox.width ) + if(lineLayout.length < parameters.boundingBox.width) { break; } - if( glyphIndex < numberOfGLyphsInGroup ) + if(glyphIndex < numberOfGLyphsInGroup) { // avoids go under zero for an unsigned int. break; @@ -372,51 +369,51 @@ struct Engine::Impl } else { - lineLayout = currentLineLayout; + lineLayout = currentLineLayout; - AdjustLayout( parameters, - bidiParameters, - bidirectionalParagraphInfo, - lineLayout ); + AdjustLayout(parameters, + bidiParameters, + bidirectionalParagraphInfo, + lineLayout); } } else { - lineLayout.length = std::max( length, lineLayout.length ); + lineLayout.length = std::max(length, lineLayout.length); } } } } } - void AdjustLayout( const Parameters& parameters, - LayoutBidiParameters& bidiParameters, - const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo, - LineLayout& lineLayout ) + void AdjustLayout(const Parameters& parameters, + LayoutBidiParameters& bidiParameters, + const BidirectionalParagraphInfoRun& bidirectionalParagraphInfo, + LineLayout& lineLayout) { Vector& bidirectionalLinesInfo = parameters.textModel->mLogicalModel->mBidirectionalLineInfo; // Remove current reordered line. - bidirectionalLinesInfo.Erase( bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex ); + bidirectionalLinesInfo.Erase(bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex); // Re-build the conversion table without the removed glyphs. - ReorderLine( bidirectionalParagraphInfo, - bidirectionalLinesInfo, - bidiParameters.bidiLineIndex, - lineLayout.characterIndex, - lineLayout.numberOfCharacters, - bidiParameters.paragraphDirection ); + ReorderLine(bidirectionalParagraphInfo, + bidirectionalLinesInfo, + bidiParameters.bidiLineIndex, + lineLayout.characterIndex, + lineLayout.numberOfCharacters, + bidiParameters.paragraphDirection); - const BidirectionalLineInfoRun& bidirectionalLineInfo = *( bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex ); + const BidirectionalLineInfoRun& bidirectionalLineInfo = *(bidirectionalLinesInfo.Begin() + bidiParameters.bidiLineIndex); - float length = 0.f; + float length = 0.f; float whiteSpaceLengthEndOfLine = 0.f; - LayoutRightToLeft( parameters, - bidirectionalLineInfo, - length, - whiteSpaceLengthEndOfLine ); + LayoutRightToLeft(parameters, + bidirectionalLineInfo, + length, + whiteSpaceLengthEndOfLine); - lineLayout.length = length; + lineLayout.length = length; lineLayout.whiteSpaceLengthEndOfLine = whiteSpaceLengthEndOfLine; } @@ -433,24 +430,24 @@ struct Engine::Impl * @param[out] lineLayout The line layout. * @param[in] completelyFill Whether to completely fill the line ( even if the last word exceeds the boundaries ). */ - void GetLineLayoutForBox( const Parameters& parameters, - LayoutBidiParameters& bidiParameters, - LineLayout& lineLayout, - bool completelyFill ) + void GetLineLayoutForBox(const Parameters& parameters, + LayoutBidiParameters& bidiParameters, + LineLayout& lineLayout, + bool completelyFill) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->GetLineLayoutForBox\n" ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " initial glyph index : %d\n", lineLayout.glyphIndex ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->GetLineLayoutForBox\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " initial glyph index : %d\n", lineLayout.glyphIndex); - const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin(); - const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin(); - const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin(); + const Character* const textBuffer = parameters.textModel->mLogicalModel->mText.Begin(); + const Length* const charactersPerGlyphBuffer = parameters.textModel->mVisualModel->mCharactersPerGlyph.Begin(); + const GlyphInfo* const glyphsBuffer = parameters.textModel->mVisualModel->mGlyphs.Begin(); const CharacterIndex* const glyphsToCharactersBuffer = parameters.textModel->mVisualModel->mGlyphsToCharacters.Begin(); - const LineBreakInfo* const lineBreakInfoBuffer = parameters.textModel->mLogicalModel->mLineBreakInfo.Begin(); + const LineBreakInfo* const lineBreakInfoBuffer = parameters.textModel->mLogicalModel->mLineBreakInfo.Begin(); - const float outlineWidth = static_cast( parameters.textModel->GetOutlineWidth() ); + const float outlineWidth = static_cast(parameters.textModel->GetOutlineWidth()); const Length totalNumberOfGlyphs = parameters.textModel->mVisualModel->mGlyphs.Count(); - const bool isMultiline = mLayout == MULTI_LINE_BOX; + const bool isMultiline = mLayout == MULTI_LINE_BOX; const bool isWordLaidOut = parameters.textModel->mLineWrapMode == Text::LineWrap::WORD; // The last glyph to be laid-out. @@ -461,19 +458,19 @@ struct Engine::Impl // the difference needs to be added to the line length. // Check whether the first glyph comes from a character that is shaped in multiple glyphs. - const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( lineLayout.glyphIndex, - lastGlyphOfParagraphPlusOne, - charactersPerGlyphBuffer ); + const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(lineLayout.glyphIndex, + lastGlyphOfParagraphPlusOne, + charactersPerGlyphBuffer); GlyphMetrics glyphMetrics; - GetGlyphsMetrics( lineLayout.glyphIndex, - numberOfGLyphsInGroup, - glyphMetrics, - glyphsBuffer, - mMetrics ); + GetGlyphsMetrics(lineLayout.glyphIndex, + numberOfGLyphsInGroup, + glyphMetrics, + glyphsBuffer, + mMetrics); // Set the direction of the first character of the line. - lineLayout.characterIndex = *( glyphsToCharactersBuffer + lineLayout.glyphIndex ); + lineLayout.characterIndex = *(glyphsToCharactersBuffer + lineLayout.glyphIndex); // Stores temporary line layout which has not been added to the final line layout. LineLayout tmpLineLayout; @@ -487,47 +484,47 @@ struct Engine::Impl // Calculate the line height if there is no characters. FontId lastFontId = glyphMetrics.fontId; - UpdateLineHeight( glyphMetrics, tmpLineLayout ); + UpdateLineHeight(glyphMetrics, tmpLineLayout); bool oneWordLaidOut = false; - for( GlyphIndex glyphIndex = lineLayout.glyphIndex; - glyphIndex < lastGlyphOfParagraphPlusOne; ) + for(GlyphIndex glyphIndex = lineLayout.glyphIndex; + glyphIndex < lastGlyphOfParagraphPlusOne;) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " glyph index : %d\n", glyphIndex ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " glyph index : %d\n", glyphIndex); // Check whether this glyph comes from a character that is shaped in multiple glyphs. - const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup( glyphIndex, - lastGlyphOfParagraphPlusOne, - charactersPerGlyphBuffer ); + const Length numberOfGLyphsInGroup = GetNumberOfGlyphsOfGroup(glyphIndex, + lastGlyphOfParagraphPlusOne, + charactersPerGlyphBuffer); GlyphMetrics glyphMetrics; - GetGlyphsMetrics( glyphIndex, - numberOfGLyphsInGroup, - glyphMetrics, - glyphsBuffer, - mMetrics ); + GetGlyphsMetrics(glyphIndex, + numberOfGLyphsInGroup, + glyphMetrics, + glyphsBuffer, + mMetrics); - const bool isLastGlyph = glyphIndex + numberOfGLyphsInGroup == totalNumberOfGlyphs; + const bool isLastGlyph = glyphIndex + numberOfGLyphsInGroup == totalNumberOfGlyphs; // Check if the font of the current glyph is the same of the previous one. // If it's different the ascender and descender need to be updated. - if( lastFontId != glyphMetrics.fontId ) + if(lastFontId != glyphMetrics.fontId) { - UpdateLineHeight( glyphMetrics, tmpLineLayout ); + UpdateLineHeight(glyphMetrics, tmpLineLayout); lastFontId = glyphMetrics.fontId; } // Get the character indices for the current glyph. The last character index is needed // because there are glyphs formed by more than one character but their break info is // given only for the last character. - const Length charactersPerGlyph = *( charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u ); - const bool hasCharacters = charactersPerGlyph > 0u; - const CharacterIndex characterFirstIndex = *( glyphsToCharactersBuffer + glyphIndex ); - const CharacterIndex characterLastIndex = characterFirstIndex + ( hasCharacters ? charactersPerGlyph - 1u : 0u ); + const Length charactersPerGlyph = *(charactersPerGlyphBuffer + glyphIndex + numberOfGLyphsInGroup - 1u); + const bool hasCharacters = charactersPerGlyph > 0u; + const CharacterIndex characterFirstIndex = *(glyphsToCharactersBuffer + glyphIndex); + const CharacterIndex characterLastIndex = characterFirstIndex + (hasCharacters ? charactersPerGlyph - 1u : 0u); // Get the line break info for the current character. - const LineBreakInfo lineBreakInfo = hasCharacters ? *( lineBreakInfoBuffer + characterLastIndex ) : TextAbstraction::LINE_NO_BREAK; + const LineBreakInfo lineBreakInfo = hasCharacters ? *(lineBreakInfoBuffer + characterLastIndex) : TextAbstraction::LINE_NO_BREAK; // Increase the number of characters. tmpLineLayout.numberOfCharacters += charactersPerGlyph; @@ -536,18 +533,18 @@ struct Engine::Impl tmpLineLayout.numberOfGlyphs += numberOfGLyphsInGroup; // Check whether is a white space. - const Character character = *( textBuffer + characterFirstIndex ); - const bool isWhiteSpace = TextAbstraction::IsWhiteSpace( character ); + const Character character = *(textBuffer + characterFirstIndex); + const bool isWhiteSpace = TextAbstraction::IsWhiteSpace(character); // Calculate the length of the line. // Used to restore the temporal line layout when a single word does not fit in the control's width and is split by character. - const float previousTmpPenX = tmpLineLayout.penX; - const float previousTmpAdvance = tmpLineLayout.previousAdvance; - const float previousTmpLength = tmpLineLayout.length; + const float previousTmpPenX = tmpLineLayout.penX; + const float previousTmpAdvance = tmpLineLayout.previousAdvance; + const float previousTmpLength = tmpLineLayout.length; const float previousTmpWhiteSpaceLengthEndOfLine = tmpLineLayout.whiteSpaceLengthEndOfLine; - if( isWhiteSpace ) + if(isWhiteSpace) { // Add the length to the length of white spaces at the end of the line. tmpLineLayout.whiteSpaceLengthEndOfLine += glyphMetrics.advance; // The advance is used as the width is always zero for the white spaces. @@ -555,91 +552,91 @@ struct Engine::Impl else { tmpLineLayout.penX += tmpLineLayout.previousAdvance + tmpLineLayout.whiteSpaceLengthEndOfLine; - tmpLineLayout.previousAdvance = ( glyphMetrics.advance + parameters.interGlyphExtraAdvance ); + tmpLineLayout.previousAdvance = (glyphMetrics.advance + parameters.interGlyphExtraAdvance); - tmpLineLayout.length = std::max( tmpLineLayout.length, tmpLineLayout.penX + glyphMetrics.xBearing + glyphMetrics.width ); + tmpLineLayout.length = std::max(tmpLineLayout.length, tmpLineLayout.penX + glyphMetrics.xBearing + glyphMetrics.width); // Clear the white space length at the end of the line. tmpLineLayout.whiteSpaceLengthEndOfLine = 0.f; } // Check if the accumulated length fits in the width of the box. - if( ( completelyFill || isMultiline ) && !isWhiteSpace && - ( tmpLineLayout.length > parameters.boundingBox.width ) ) + if((completelyFill || isMultiline) && !isWhiteSpace && + (tmpLineLayout.length > parameters.boundingBox.width)) { // Current word does not fit in the box's width. - if( !oneWordLaidOut || completelyFill ) + if(!oneWordLaidOut || completelyFill) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Break the word by character\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Break the word by character\n"); // The word doesn't fit in the control's width. It needs to be split by character. - if( tmpLineLayout.numberOfGlyphs > 0u ) + if(tmpLineLayout.numberOfGlyphs > 0u) { tmpLineLayout.numberOfCharacters -= charactersPerGlyph; tmpLineLayout.numberOfGlyphs -= numberOfGLyphsInGroup; - tmpLineLayout.penX = previousTmpPenX; - tmpLineLayout.previousAdvance = previousTmpAdvance; - tmpLineLayout.length = previousTmpLength; + tmpLineLayout.penX = previousTmpPenX; + tmpLineLayout.previousAdvance = previousTmpAdvance; + tmpLineLayout.length = previousTmpLength; tmpLineLayout.whiteSpaceLengthEndOfLine = previousTmpWhiteSpaceLengthEndOfLine; } // Add part of the word to the line layout. - MergeLineLayout( lineLayout, tmpLineLayout ); + MergeLineLayout(lineLayout, tmpLineLayout); } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Current word does not fit.\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Current word does not fit.\n"); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox.\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox.\n"); // Reorder the RTL line. - if( bidiParameters.isBidirectional ) + if(bidiParameters.isBidirectional) { - ReorderBiDiLayout( parameters, - bidiParameters, - lineLayout, - lineLayout, - true ); + ReorderBiDiLayout(parameters, + bidiParameters, + lineLayout, + lineLayout, + true); } return; } - if( ( isMultiline || isLastGlyph ) && - ( TextAbstraction::LINE_MUST_BREAK == lineBreakInfo ) ) + if((isMultiline || isLastGlyph) && + (TextAbstraction::LINE_MUST_BREAK == lineBreakInfo)) { LineLayout currentLineLayout = lineLayout; // Must break the line. Update the line layout and return. - MergeLineLayout( lineLayout, tmpLineLayout ); + MergeLineLayout(lineLayout, tmpLineLayout); - // Reorder the RTL line. - if( bidiParameters.isBidirectional ) + // Reorder the RTL line. + if(bidiParameters.isBidirectional) { - ReorderBiDiLayout( parameters, - bidiParameters, - currentLineLayout, - lineLayout, - false ); + ReorderBiDiLayout(parameters, + bidiParameters, + currentLineLayout, + lineLayout, + false); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Must break\n" ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Must break\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n"); return; } - if( isMultiline && - ( TextAbstraction::LINE_ALLOW_BREAK == lineBreakInfo ) ) + if(isMultiline && + (TextAbstraction::LINE_ALLOW_BREAK == lineBreakInfo)) { oneWordLaidOut = isWordLaidOut; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " One word laid-out\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " One word laid-out\n"); // Current glyph is the last one of the current word. // Add the temporal layout to the current one. - MergeLineLayout( lineLayout, tmpLineLayout ); + MergeLineLayout(lineLayout, tmpLineLayout); tmpLineLayout.Clear(); } @@ -647,14 +644,14 @@ struct Engine::Impl glyphIndex += numberOfGLyphsInGroup; } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--GetLineLayoutForBox\n"); } - void SetGlyphPositions( const GlyphInfo* const glyphsBuffer, - Length numberOfGlyphs, - float outlineWidth, - float interGlyphExtraAdvance, - Vector2* glyphPositionsBuffer ) + void SetGlyphPositions(const GlyphInfo* const glyphsBuffer, + Length numberOfGlyphs, + float outlineWidth, + float interGlyphExtraAdvance, + Vector2* glyphPositionsBuffer) { // Traverse the glyphs and set the positions. @@ -663,79 +660,79 @@ struct Engine::Impl // so the penX position needs to be moved to the right. const GlyphInfo& glyph = *glyphsBuffer; - float penX = -glyph.xBearing + mCursorWidth + outlineWidth; + float penX = -glyph.xBearing + mCursorWidth + outlineWidth; - for( GlyphIndex i = 0u; i < numberOfGlyphs; ++i ) + for(GlyphIndex i = 0u; i < numberOfGlyphs; ++i) { - const GlyphInfo& glyph = *( glyphsBuffer + i ); - Vector2& position = *( glyphPositionsBuffer + i ); + const GlyphInfo& glyph = *(glyphsBuffer + i); + Vector2& position = *(glyphPositionsBuffer + i); position.x = penX + glyph.xBearing; position.y = -glyph.yBearing; - penX += ( glyph.advance + interGlyphExtraAdvance ); + penX += (glyph.advance + interGlyphExtraAdvance); } } - void SetGlyphPositions( const Parameters& layoutParameters, - Vector2* glyphPositionsBuffer, - LayoutBidiParameters& layoutBidiParameters, - const LineLayout& layout ) + void SetGlyphPositions(const Parameters& layoutParameters, + Vector2* glyphPositionsBuffer, + LayoutBidiParameters& layoutBidiParameters, + const LineLayout& layout) { - const Character* const textBuffer = layoutParameters.textModel->mLogicalModel->mText.Begin(); - const BidirectionalLineInfoRun& bidiLine = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo[layoutBidiParameters.bidiLineIndex]; - const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin(); - const GlyphIndex* const charactersToGlyphsBuffer = layoutParameters.textModel->mVisualModel->mCharactersToGlyph.Begin(); - const Length* const glyphsPerCharacterBuffer = layoutParameters.textModel->mVisualModel->mGlyphsPerCharacter.Begin(); + const Character* const textBuffer = layoutParameters.textModel->mLogicalModel->mText.Begin(); + const BidirectionalLineInfoRun& bidiLine = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo[layoutBidiParameters.bidiLineIndex]; + const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin(); + const GlyphIndex* const charactersToGlyphsBuffer = layoutParameters.textModel->mVisualModel->mCharactersToGlyph.Begin(); + const Length* const glyphsPerCharacterBuffer = layoutParameters.textModel->mVisualModel->mGlyphsPerCharacter.Begin(); CharacterIndex characterLogicalIndex = 0u; - CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex ); + CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *(bidiLine.visualToLogicalMap + characterLogicalIndex); float penX = 0.f; - while( TextAbstraction::IsWhiteSpace( *( textBuffer + characterVisualIndex ) ) ) + while(TextAbstraction::IsWhiteSpace(*(textBuffer + characterVisualIndex))) { - const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex ); - const GlyphInfo& glyph = *( glyphsBuffer + glyphIndex ); + const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex); + const GlyphInfo& glyph = *(glyphsBuffer + glyphIndex); - Vector2& position = *( glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex ); - position.x = penX; - position.y = -glyph.yBearing; + Vector2& position = *(glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex); + position.x = penX; + position.y = -glyph.yBearing; penX += glyph.advance; ++characterLogicalIndex; - characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex ); + characterVisualIndex = bidiLine.characterRun.characterIndex + *(bidiLine.visualToLogicalMap + characterLogicalIndex); } - const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex ); - const GlyphInfo& glyph = *( glyphsBuffer + glyphIndex ); + const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex); + const GlyphInfo& glyph = *(glyphsBuffer + glyphIndex); penX += -glyph.xBearing; // Traverses the characters of the right to left paragraph. - for( ; characterLogicalIndex < bidiLine.characterRun.numberOfCharacters; - ++characterLogicalIndex ) + for(; characterLogicalIndex < bidiLine.characterRun.numberOfCharacters; + ++characterLogicalIndex) { // Convert the character in the logical order into the character in the visual order. - const CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *( bidiLine.visualToLogicalMap + characterLogicalIndex ); + const CharacterIndex characterVisualIndex = bidiLine.characterRun.characterIndex + *(bidiLine.visualToLogicalMap + characterLogicalIndex); // Get the number of glyphs of the character. - const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + characterVisualIndex ); + const Length numberOfGlyphs = *(glyphsPerCharacterBuffer + characterVisualIndex); - for( GlyphIndex index = 0u; index < numberOfGlyphs; ++index ) + for(GlyphIndex index = 0u; index < numberOfGlyphs; ++index) { // Convert the character in the visual order into the glyph in the visual order. - const GlyphIndex glyphIndex = *( charactersToGlyphsBuffer + characterVisualIndex ) + index; + const GlyphIndex glyphIndex = *(charactersToGlyphsBuffer + characterVisualIndex) + index; - DALI_ASSERT_DEBUG( glyphIndex < layoutParameters.textModel->mVisualModel->mGlyphs.Count() ); + DALI_ASSERT_DEBUG(glyphIndex < layoutParameters.textModel->mVisualModel->mGlyphs.Count()); - const GlyphInfo& glyph = *( glyphsBuffer + glyphIndex ); - Vector2& position = *( glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex ); + const GlyphInfo& glyph = *(glyphsBuffer + glyphIndex); + Vector2& position = *(glyphPositionsBuffer + glyphIndex - layoutParameters.startGlyphIndex); position.x = penX + glyph.xBearing; position.y = -glyph.yBearing; - penX += ( glyph.advance + layoutParameters.interGlyphExtraAdvance ); + penX += (glyph.advance + layoutParameters.interGlyphExtraAdvance); } } } @@ -750,22 +747,22 @@ struct Engine::Impl * * @return Pointer to either lines or newLines. */ - LineRun* ResizeLinesBuffer( Vector& lines, - Vector& newLines, - Length& linesCapacity, - bool updateCurrentBuffer ) + LineRun* ResizeLinesBuffer(Vector& lines, + Vector& newLines, + Length& linesCapacity, + bool updateCurrentBuffer) { LineRun* linesBuffer = nullptr; // Reserve more space for the next lines. linesCapacity *= 2u; - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newLines.Resize( linesCapacity ); + newLines.Resize(linesCapacity); linesBuffer = newLines.Begin(); } else { - lines.Resize( linesCapacity ); + lines.Resize(linesCapacity); linesBuffer = lines.Begin(); } @@ -787,22 +784,19 @@ struct Engine::Impl * * return Whether the line is ellipsized. */ - bool EllipsisLine( const Parameters& layoutParameters, - LayoutBidiParameters& layoutBidiParameters, - const LineLayout& layout, - Size& layoutSize, - LineRun* linesBuffer, - Vector2* glyphPositionsBuffer, - Length& numberOfLines, - float penY, - bool& isAutoScrollEnabled ) + bool EllipsisLine(const Parameters& layoutParameters, + LayoutBidiParameters& layoutBidiParameters, + const LineLayout& layout, + Size& layoutSize, + LineRun* linesBuffer, + Vector2* glyphPositionsBuffer, + Length& numberOfLines, + float penY, + bool& isAutoScrollEnabled) { - const bool ellipsis = isAutoScrollEnabled ? ( penY - layout.descender > layoutParameters.boundingBox.height ) : - ( ( penY - layout.descender > layoutParameters.boundingBox.height ) || - ( ( mLayout == SINGLE_LINE_BOX ) && - ( layout.length > layoutParameters.boundingBox.width ) ) ); + const bool ellipsis = isAutoScrollEnabled ? (penY - layout.descender > layoutParameters.boundingBox.height) : ((penY - layout.descender > layoutParameters.boundingBox.height) || ((mLayout == SINGLE_LINE_BOX) && (layout.length > layoutParameters.boundingBox.width))); - if( ellipsis ) + if(ellipsis) { isAutoScrollEnabled = false; // Do not layout more lines if ellipsis is enabled. @@ -810,12 +804,12 @@ struct Engine::Impl // The last line needs to be completely filled with characters. // Part of a word may be used. - LineRun* lineRun = nullptr; + LineRun* lineRun = nullptr; LineLayout ellipsisLayout; - if( 0u != numberOfLines ) + if(0u != numberOfLines) { // Get the last line and layout it again with the 'completelyFill' flag to true. - lineRun = linesBuffer + ( numberOfLines - 1u ); + lineRun = linesBuffer + (numberOfLines - 1u); penY -= layout.ascender - lineRun->descender + lineRun->lineSpacing; @@ -827,47 +821,47 @@ struct Engine::Impl lineRun = linesBuffer; lineRun->glyphRun.glyphIndex = 0u; - ellipsisLayout.glyphIndex = 0u; + ellipsisLayout.glyphIndex = 0u; ++numberOfLines; } - GetLineLayoutForBox( layoutParameters, - layoutBidiParameters, - ellipsisLayout, - true ); + GetLineLayoutForBox(layoutParameters, + layoutBidiParameters, + ellipsisLayout, + true); - lineRun->glyphRun.numberOfGlyphs = ellipsisLayout.numberOfGlyphs; - lineRun->characterRun.characterIndex = ellipsisLayout.characterIndex; + lineRun->glyphRun.numberOfGlyphs = ellipsisLayout.numberOfGlyphs; + lineRun->characterRun.characterIndex = ellipsisLayout.characterIndex; lineRun->characterRun.numberOfCharacters = ellipsisLayout.numberOfCharacters; - lineRun->width = ellipsisLayout.length; - lineRun->extraLength = std::ceil( ellipsisLayout.whiteSpaceLengthEndOfLine ); - lineRun->ascender = ellipsisLayout.ascender; - lineRun->descender = ellipsisLayout.descender; - lineRun->ellipsis = true; + lineRun->width = ellipsisLayout.length; + lineRun->extraLength = std::ceil(ellipsisLayout.whiteSpaceLengthEndOfLine); + lineRun->ascender = ellipsisLayout.ascender; + lineRun->descender = ellipsisLayout.descender; + lineRun->ellipsis = true; layoutSize.width = layoutParameters.boundingBox.width; - if( layoutSize.height < Math::MACHINE_EPSILON_1000 ) + if(layoutSize.height < Math::MACHINE_EPSILON_1000) { - layoutSize.height += ( lineRun->ascender + -lineRun->descender ) + lineRun->lineSpacing; + layoutSize.height += (lineRun->ascender + -lineRun->descender) + lineRun->lineSpacing; } const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin(); - const float outlineWidth = static_cast( layoutParameters.textModel->GetOutlineWidth() ); + const float outlineWidth = static_cast(layoutParameters.textModel->GetOutlineWidth()); const Vector& bidirectionalLinesInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo; - if( layoutBidiParameters.isBidirectional ) + if(layoutBidiParameters.isBidirectional) { layoutBidiParameters.bidiLineIndex = 0u; - for( Vector::ConstIterator it = bidirectionalLinesInfo.Begin(), - endIt = bidirectionalLinesInfo.End(); - it != endIt; - ++it, ++layoutBidiParameters.bidiLineIndex ) + for(Vector::ConstIterator it = bidirectionalLinesInfo.Begin(), + endIt = bidirectionalLinesInfo.End(); + it != endIt; + ++it, ++layoutBidiParameters.bidiLineIndex) { const BidirectionalLineInfoRun& run = *it; - if( ellipsisLayout.characterIndex == run.characterRun.characterIndex ) + if(ellipsisLayout.characterIndex == run.characterRun.characterIndex) { // Found where to insert the bidi line info. break; @@ -875,26 +869,26 @@ struct Engine::Impl } } - const BidirectionalLineInfoRun* const bidirectionalLineInfo = ( layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty() ) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr; + const BidirectionalLineInfoRun* const bidirectionalLineInfo = (layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty()) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr; - if( ( nullptr != bidirectionalLineInfo ) && - !bidirectionalLineInfo->isIdentity && - ( ellipsisLayout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex ) ) + if((nullptr != bidirectionalLineInfo) && + !bidirectionalLineInfo->isIdentity && + (ellipsisLayout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex)) { lineRun->direction = RTL; - SetGlyphPositions( layoutParameters, - glyphPositionsBuffer, - layoutBidiParameters, - ellipsisLayout ); + SetGlyphPositions(layoutParameters, + glyphPositionsBuffer, + layoutBidiParameters, + ellipsisLayout); } else { lineRun->direction = LTR; - SetGlyphPositions( glyphsBuffer + lineRun->glyphRun.glyphIndex, - ellipsisLayout.numberOfGlyphs, - outlineWidth, - layoutParameters.interGlyphExtraAdvance, - glyphPositionsBuffer + lineRun->glyphRun.glyphIndex - layoutParameters.startGlyphIndex ); + SetGlyphPositions(glyphsBuffer + lineRun->glyphRun.glyphIndex, + ellipsisLayout.numberOfGlyphs, + outlineWidth, + layoutParameters.interGlyphExtraAdvance, + glyphPositionsBuffer + lineRun->glyphRun.glyphIndex - layoutParameters.startGlyphIndex); } } @@ -912,46 +906,44 @@ struct Engine::Impl * @param[in,out] numberOfLines The number of laid-out lines. * @param[in] isLastLine Whether the laid-out line is the last one. */ - void UpdateTextLayout( const Parameters& layoutParameters, - const LineLayout& layout, - Size& layoutSize, - LineRun* linesBuffer, - GlyphIndex index, - Length& numberOfLines, - bool isLastLine ) + void UpdateTextLayout(const Parameters& layoutParameters, + const LineLayout& layout, + Size& layoutSize, + LineRun* linesBuffer, + GlyphIndex index, + Length& numberOfLines, + bool isLastLine) { - LineRun& lineRun = *( linesBuffer + numberOfLines ); + LineRun& lineRun = *(linesBuffer + numberOfLines); ++numberOfLines; - lineRun.glyphRun.glyphIndex = index; - lineRun.glyphRun.numberOfGlyphs = layout.numberOfGlyphs; - lineRun.characterRun.characterIndex = layout.characterIndex; + lineRun.glyphRun.glyphIndex = index; + lineRun.glyphRun.numberOfGlyphs = layout.numberOfGlyphs; + lineRun.characterRun.characterIndex = layout.characterIndex; lineRun.characterRun.numberOfCharacters = layout.numberOfCharacters; - lineRun.width = layout.length; - lineRun.extraLength = std::ceil( layout.whiteSpaceLengthEndOfLine ); - + lineRun.width = layout.length; + lineRun.extraLength = std::ceil(layout.whiteSpaceLengthEndOfLine); // Rounds upward to avoid a non integer size. - lineRun.width = std::ceil( lineRun.width ); + lineRun.width = std::ceil(lineRun.width); - lineRun.ascender = layout.ascender; + lineRun.ascender = layout.ascender; lineRun.descender = layout.descender; lineRun.direction = layout.direction; - lineRun.ellipsis = false; + lineRun.ellipsis = false; - lineRun.lineSpacing = mDefaultLineSize - ( lineRun.ascender + -lineRun.descender ); + lineRun.lineSpacing = mDefaultLineSize - (lineRun.ascender + -lineRun.descender); lineRun.lineSpacing = lineRun.lineSpacing < 0.f ? 0.f : lineRun.lineSpacing; lineRun.lineSpacing += mDefaultLineSpacing; - // Update the actual size. - if( lineRun.width > layoutSize.width ) + if(lineRun.width > layoutSize.width) { layoutSize.width = lineRun.width; } - layoutSize.height += ( lineRun.ascender + -lineRun.descender ) + lineRun.lineSpacing; + layoutSize.height += (lineRun.ascender + -lineRun.descender) + lineRun.lineSpacing; } /** @@ -964,12 +956,12 @@ struct Engine::Impl * @param[in,out] linesBuffer Pointer to the line's buffer. * @param[in,out] numberOfLines The number of laid-out lines. */ - void UpdateTextLayout( const Parameters& layoutParameters, - CharacterIndex characterIndex, - GlyphIndex glyphIndex, - Size& layoutSize, - LineRun* linesBuffer, - Length& numberOfLines ) + void UpdateTextLayout(const Parameters& layoutParameters, + CharacterIndex characterIndex, + GlyphIndex glyphIndex, + Size& layoutSize, + LineRun* linesBuffer, + Length& numberOfLines) { const Vector& glyphs = layoutParameters.textModel->mVisualModel->mGlyphs; @@ -977,32 +969,32 @@ struct Engine::Impl const GlyphInfo& glyphInfo = glyphs[glyphs.Count() - 1u]; Text::FontMetrics fontMetrics; - if( 0u != glyphInfo.fontId ) + if(0u != glyphInfo.fontId) { - mMetrics->GetFontMetrics( glyphInfo.fontId, fontMetrics ); + mMetrics->GetFontMetrics(glyphInfo.fontId, fontMetrics); } - LineRun& lineRun = *( linesBuffer + numberOfLines ); + LineRun& lineRun = *(linesBuffer + numberOfLines); ++numberOfLines; - lineRun.glyphRun.glyphIndex = glyphIndex; - lineRun.glyphRun.numberOfGlyphs = 0u; - lineRun.characterRun.characterIndex = characterIndex; + lineRun.glyphRun.glyphIndex = glyphIndex; + lineRun.glyphRun.numberOfGlyphs = 0u; + lineRun.characterRun.characterIndex = characterIndex; lineRun.characterRun.numberOfCharacters = 0u; - lineRun.width = 0.f; - lineRun.ascender = fontMetrics.ascender; - lineRun.descender = fontMetrics.descender; - lineRun.extraLength = 0.f; - lineRun.alignmentOffset = 0.f; - lineRun.direction = LTR; - lineRun.ellipsis = false; - - lineRun.lineSpacing = mDefaultLineSize - ( lineRun.ascender + -lineRun.descender ); + lineRun.width = 0.f; + lineRun.ascender = fontMetrics.ascender; + lineRun.descender = fontMetrics.descender; + lineRun.extraLength = 0.f; + lineRun.alignmentOffset = 0.f; + lineRun.direction = LTR; + lineRun.ellipsis = false; + + lineRun.lineSpacing = mDefaultLineSize - (lineRun.ascender + -lineRun.descender); lineRun.lineSpacing = lineRun.lineSpacing < 0.f ? 0.f : lineRun.lineSpacing; lineRun.lineSpacing += mDefaultLineSpacing; - layoutSize.height += ( lineRun.ascender + -lineRun.descender ) + lineRun.lineSpacing; + layoutSize.height += (lineRun.ascender + -lineRun.descender) + lineRun.lineSpacing; } /** @@ -1011,22 +1003,22 @@ struct Engine::Impl * @param[in] lines The vector of lines (before the new laid-out lines are inserted). * @param[in,out] layoutSize The text's layout size. */ - void UpdateLayoutSize( const Vector& lines, - Size& layoutSize ) + void UpdateLayoutSize(const Vector& lines, + Size& layoutSize) { - for( Vector::ConstIterator it = lines.Begin(), - endIt = lines.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = lines.Begin(), + endIt = lines.End(); + it != endIt; + ++it) { const LineRun& line = *it; - if( line.width > layoutSize.width ) + if(line.width > layoutSize.width) { layoutSize.width = line.width; } - layoutSize.height += ( line.ascender + -line.descender ) + line.lineSpacing; + layoutSize.height += (line.ascender + -line.descender) + line.lineSpacing; } } @@ -1038,20 +1030,20 @@ struct Engine::Impl * @param[in] characterOffset The offset to be added to the runs of characters. * @param[in] glyphOffset The offset to be added to the runs of glyphs. */ - void UpdateLineIndexOffsets( const Parameters& layoutParameters, - Vector& lines, - Length characterOffset, - Length glyphOffset ) + void UpdateLineIndexOffsets(const Parameters& layoutParameters, + Vector& lines, + Length characterOffset, + Length glyphOffset) { // Update the glyph and character runs. - for( Vector::Iterator it = lines.Begin() + layoutParameters.startLineIndex, - endIt = lines.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = lines.Begin() + layoutParameters.startLineIndex, + endIt = lines.End(); + it != endIt; + ++it) { LineRun& line = *it; - line.glyphRun.glyphIndex = glyphOffset; + line.glyphRun.glyphIndex = glyphOffset; line.characterRun.characterIndex = characterOffset; glyphOffset += line.glyphRun.numberOfGlyphs; @@ -1059,77 +1051,77 @@ struct Engine::Impl } } - bool LayoutText( Parameters& layoutParameters, - Size& layoutSize, - bool elideTextEnabled, - bool& isAutoScrollEnabled ) + bool LayoutText(Parameters& layoutParameters, + Size& layoutSize, + bool elideTextEnabled, + bool& isAutoScrollEnabled) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->LayoutText\n" ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " box size %f, %f\n", layoutParameters.boundingBox.width, layoutParameters.boundingBox.height ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->LayoutText\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " box size %f, %f\n", layoutParameters.boundingBox.width, layoutParameters.boundingBox.height); Vector& lines = layoutParameters.textModel->mVisualModel->mLines; - if( 0u == layoutParameters.numberOfGlyphs ) + if(0u == layoutParameters.numberOfGlyphs) { // Add an extra line if the last character is a new paragraph character and the last line doesn't have zero characters. - if( layoutParameters.isLastNewParagraph ) + if(layoutParameters.isLastNewParagraph) { Length numberOfLines = lines.Count(); - if( 0u != numberOfLines ) + if(0u != numberOfLines) { - const LineRun& lastLine = *( lines.End() - 1u ); + const LineRun& lastLine = *(lines.End() - 1u); - if( 0u != lastLine.characterRun.numberOfCharacters ) + if(0u != lastLine.characterRun.numberOfCharacters) { // Need to add a new line with no characters but with height to increase the layoutSize.height LineRun newLine; - Initialize( newLine ); - lines.PushBack( newLine ); - - UpdateTextLayout( layoutParameters, - lastLine.characterRun.characterIndex + lastLine.characterRun.numberOfCharacters, - lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs, - layoutSize, - lines.Begin(), - numberOfLines ); + Initialize(newLine); + lines.PushBack(newLine); + + UpdateTextLayout(layoutParameters, + lastLine.characterRun.characterIndex + lastLine.characterRun.numberOfCharacters, + lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs, + layoutSize, + lines.Begin(), + numberOfLines); } } } // Calculates the layout size. - UpdateLayoutSize( lines, - layoutSize ); + UpdateLayoutSize(lines, + layoutSize); // Rounds upward to avoid a non integer size. - layoutSize.height = std::ceil( layoutSize.height ); + layoutSize.height = std::ceil(layoutSize.height); // Nothing else do if there are no glyphs to layout. return false; } - const GlyphIndex lastGlyphPlusOne = layoutParameters.startGlyphIndex + layoutParameters.numberOfGlyphs; - const Length totalNumberOfGlyphs = layoutParameters.textModel->mVisualModel->mGlyphs.Count(); - Vector& glyphPositions = layoutParameters.textModel->mVisualModel->mGlyphPositions; + const GlyphIndex lastGlyphPlusOne = layoutParameters.startGlyphIndex + layoutParameters.numberOfGlyphs; + const Length totalNumberOfGlyphs = layoutParameters.textModel->mVisualModel->mGlyphs.Count(); + Vector& glyphPositions = layoutParameters.textModel->mVisualModel->mGlyphPositions; // In a previous layout, an extra line with no characters may have been added if the text ended with a new paragraph character. // This extra line needs to be removed. - if( 0u != lines.Count() ) + if(0u != lines.Count()) { Vector::Iterator lastLine = lines.End() - 1u; - if( ( 0u == lastLine->characterRun.numberOfCharacters ) && - ( lastGlyphPlusOne == totalNumberOfGlyphs ) ) + if((0u == lastLine->characterRun.numberOfCharacters) && + (lastGlyphPlusOne == totalNumberOfGlyphs)) { - lines.Remove( lastLine ); + lines.Remove(lastLine); } } // Retrieve BiDi info. const bool hasBidiParagraphs = !layoutParameters.textModel->mLogicalModel->mBidirectionalParagraphInfo.Empty(); - const CharacterIndex* const glyphsToCharactersBuffer = hasBidiParagraphs ? layoutParameters.textModel->mVisualModel->mGlyphsToCharacters.Begin() : nullptr; + const CharacterIndex* const glyphsToCharactersBuffer = hasBidiParagraphs ? layoutParameters.textModel->mVisualModel->mGlyphsToCharacters.Begin() : nullptr; const Vector& bidirectionalParagraphsInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalParagraphInfo; - const Vector& bidirectionalLinesInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo; + const Vector& bidirectionalLinesInfo = layoutParameters.textModel->mLogicalModel->mBidirectionalLineInfo; // Set the layout bidirectional paramters. LayoutBidiParameters layoutBidiParameters; @@ -1137,85 +1129,85 @@ struct Engine::Impl // Whether the layout is being updated or set from scratch. const bool updateCurrentBuffer = layoutParameters.numberOfGlyphs < totalNumberOfGlyphs; - Vector2* glyphPositionsBuffer = nullptr; + Vector2* glyphPositionsBuffer = nullptr; Vector newGlyphPositions; - LineRun* linesBuffer = nullptr; + LineRun* linesBuffer = nullptr; Vector newLines; // Estimate the number of lines. - Length linesCapacity = std::max( 1u, layoutParameters.estimatedNumberOfLines ); + Length linesCapacity = std::max(1u, layoutParameters.estimatedNumberOfLines); Length numberOfLines = 0u; - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newGlyphPositions.Resize( layoutParameters.numberOfGlyphs ); + newGlyphPositions.Resize(layoutParameters.numberOfGlyphs); glyphPositionsBuffer = newGlyphPositions.Begin(); - newLines.Resize( linesCapacity ); + newLines.Resize(linesCapacity); linesBuffer = newLines.Begin(); } else { glyphPositionsBuffer = glyphPositions.Begin(); - lines.Resize( linesCapacity ); + lines.Resize(linesCapacity); linesBuffer = lines.Begin(); } - float penY = CalculateLineOffset( lines, - layoutParameters.startLineIndex ); - for( GlyphIndex index = layoutParameters.startGlyphIndex; index < lastGlyphPlusOne; ) + float penY = CalculateLineOffset(lines, + layoutParameters.startLineIndex); + for(GlyphIndex index = layoutParameters.startGlyphIndex; index < lastGlyphPlusOne;) { layoutBidiParameters.Clear(); - if( hasBidiParagraphs ) + if(hasBidiParagraphs) { - const CharacterIndex startCharacterIndex = *( glyphsToCharactersBuffer + index ); + const CharacterIndex startCharacterIndex = *(glyphsToCharactersBuffer + index); - for( Vector::ConstIterator it = bidirectionalParagraphsInfo.Begin(), - endIt = bidirectionalParagraphsInfo.End(); - it != endIt; - ++it, ++layoutBidiParameters.bidiParagraphIndex ) + for(Vector::ConstIterator it = bidirectionalParagraphsInfo.Begin(), + endIt = bidirectionalParagraphsInfo.End(); + it != endIt; + ++it, ++layoutBidiParameters.bidiParagraphIndex) { const BidirectionalParagraphInfoRun& run = *it; const CharacterIndex lastCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters; - if( lastCharacterIndex <= startCharacterIndex ) + if(lastCharacterIndex <= startCharacterIndex) { // Do not process, the paragraph has already been processed. continue; } - if( startCharacterIndex >= run.characterRun.characterIndex && startCharacterIndex < lastCharacterIndex ) + if(startCharacterIndex >= run.characterRun.characterIndex && startCharacterIndex < lastCharacterIndex) { layoutBidiParameters.paragraphDirection = run.direction; - layoutBidiParameters.isBidirectional = true; + layoutBidiParameters.isBidirectional = true; } // Has already been found. break; } - if( layoutBidiParameters.isBidirectional ) + if(layoutBidiParameters.isBidirectional) { - for( Vector::ConstIterator it = bidirectionalLinesInfo.Begin(), - endIt = bidirectionalLinesInfo.End(); - it != endIt; - ++it, ++layoutBidiParameters.bidiLineIndex ) + for(Vector::ConstIterator it = bidirectionalLinesInfo.Begin(), + endIt = bidirectionalLinesInfo.End(); + it != endIt; + ++it, ++layoutBidiParameters.bidiLineIndex) { const BidirectionalLineInfoRun& run = *it; const CharacterIndex lastCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters; - if( lastCharacterIndex <= startCharacterIndex ) + if(lastCharacterIndex <= startCharacterIndex) { // skip continue; } - if( startCharacterIndex < lastCharacterIndex ) + if(startCharacterIndex < lastCharacterIndex) { // Found where to insert the bidi line info. break; @@ -1228,28 +1220,28 @@ struct Engine::Impl // Get the layout for the line. LineLayout layout; - layout.direction = layoutBidiParameters.paragraphDirection; + layout.direction = layoutBidiParameters.paragraphDirection; layout.glyphIndex = index; - GetLineLayoutForBox( layoutParameters, - layoutBidiParameters, - layout, - false ); - - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " glyph index %d\n", layout.glyphIndex ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " character index %d\n", layout.characterIndex ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of glyphs %d\n", layout.numberOfGlyphs ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " number of characters %d\n", layout.numberOfCharacters ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " length %f\n", layout.length ); - - if( 0u == layout.numberOfGlyphs ) + GetLineLayoutForBox(layoutParameters, + layoutBidiParameters, + layout, + false); + + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " glyph index %d\n", layout.glyphIndex); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " character index %d\n", layout.characterIndex); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of glyphs %d\n", layout.numberOfGlyphs); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " number of characters %d\n", layout.numberOfCharacters); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " length %f\n", layout.length); + + if(0u == layout.numberOfGlyphs) { // The width is too small and no characters are laid-out. - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--LayoutText width too small!\n\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--LayoutText width too small!\n\n"); - lines.Resize( numberOfLines ); + lines.Resize(numberOfLines); // Rounds upward to avoid a non integer size. - layoutSize.height = std::ceil( layoutSize.height ); + layoutSize.height = std::ceil(layoutSize.height); return false; } @@ -1258,26 +1250,26 @@ struct Engine::Impl // of the box. penY += layout.ascender; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " pen y %f\n", penY ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " pen y %f\n", penY); bool ellipsis = false; - if( elideTextEnabled ) + if(elideTextEnabled) { layoutBidiParameters.paragraphDirection = currentParagraphDirection; // Does the ellipsis of the last line. - ellipsis = EllipsisLine( layoutParameters, - layoutBidiParameters, - layout, - layoutSize, - linesBuffer, - glyphPositionsBuffer, - numberOfLines, - penY, - isAutoScrollEnabled ); + ellipsis = EllipsisLine(layoutParameters, + layoutBidiParameters, + layout, + layoutSize, + linesBuffer, + glyphPositionsBuffer, + numberOfLines, + penY, + isAutoScrollEnabled); } - if( ellipsis ) + if(ellipsis) { // No more lines to layout. break; @@ -1287,170 +1279,168 @@ struct Engine::Impl // Whether the last line has been laid-out. const bool isLastLine = index + layout.numberOfGlyphs == totalNumberOfGlyphs; - if( numberOfLines == linesCapacity ) + if(numberOfLines == linesCapacity) { - // Reserve more space for the next lines. - linesBuffer = ResizeLinesBuffer( lines, - newLines, - linesCapacity, - updateCurrentBuffer ); + linesBuffer = ResizeLinesBuffer(lines, + newLines, + linesCapacity, + updateCurrentBuffer); } // Updates the current text's layout with the line's layout. - UpdateTextLayout( layoutParameters, - layout, - layoutSize, - linesBuffer, - index, - numberOfLines, - isLastLine ); + UpdateTextLayout(layoutParameters, + layout, + layoutSize, + linesBuffer, + index, + numberOfLines, + isLastLine); const GlyphIndex nextIndex = index + layout.numberOfGlyphs; - if( ( nextIndex == totalNumberOfGlyphs ) && - layoutParameters.isLastNewParagraph && - ( mLayout == MULTI_LINE_BOX ) ) + if((nextIndex == totalNumberOfGlyphs) && + layoutParameters.isLastNewParagraph && + (mLayout == MULTI_LINE_BOX)) { // The last character of the text is a new paragraph character. // An extra line with no characters is added to increase the text's height // in order to place the cursor. - if( numberOfLines == linesCapacity ) + if(numberOfLines == linesCapacity) { // Reserve more space for the next lines. - linesBuffer = ResizeLinesBuffer( lines, - newLines, - linesCapacity, - updateCurrentBuffer ); + linesBuffer = ResizeLinesBuffer(lines, + newLines, + linesCapacity, + updateCurrentBuffer); } - UpdateTextLayout( layoutParameters, - layout.characterIndex + layout.numberOfCharacters, - index + layout.numberOfGlyphs, - layoutSize, - linesBuffer, - numberOfLines ); + UpdateTextLayout(layoutParameters, + layout.characterIndex + layout.numberOfCharacters, + index + layout.numberOfGlyphs, + layoutSize, + linesBuffer, + numberOfLines); } // whether to add a last line. const GlyphInfo* const glyphsBuffer = layoutParameters.textModel->mVisualModel->mGlyphs.Begin(); - const float outlineWidth = static_cast( layoutParameters.textModel->GetOutlineWidth() ); + const float outlineWidth = static_cast(layoutParameters.textModel->GetOutlineWidth()); - const BidirectionalLineInfoRun* const bidirectionalLineInfo = ( layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty() ) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr; + const BidirectionalLineInfoRun* const bidirectionalLineInfo = (layoutBidiParameters.isBidirectional && !bidirectionalLinesInfo.Empty()) ? &bidirectionalLinesInfo[layoutBidiParameters.bidiLineIndex] : nullptr; - if( ( nullptr != bidirectionalLineInfo ) && - !bidirectionalLineInfo->isIdentity && - ( layout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex ) ) + if((nullptr != bidirectionalLineInfo) && + !bidirectionalLineInfo->isIdentity && + (layout.characterIndex == bidirectionalLineInfo->characterRun.characterIndex)) { - SetGlyphPositions( layoutParameters, - glyphPositionsBuffer, - layoutBidiParameters, - layout ); + SetGlyphPositions(layoutParameters, + glyphPositionsBuffer, + layoutBidiParameters, + layout); } else { - // Sets the positions of the glyphs. - SetGlyphPositions( glyphsBuffer + index, - layout.numberOfGlyphs, - outlineWidth, - layoutParameters.interGlyphExtraAdvance, - glyphPositionsBuffer + index - layoutParameters.startGlyphIndex ); + SetGlyphPositions(glyphsBuffer + index, + layout.numberOfGlyphs, + outlineWidth, + layoutParameters.interGlyphExtraAdvance, + glyphPositionsBuffer + index - layoutParameters.startGlyphIndex); } // Updates the vertical pen's position. penY += -layout.descender + layout.lineSpacing + mDefaultLineSpacing; // If there is a defaultLineSize, updates the pen's position. - if( mDefaultLineSize > 0.f ) + if(mDefaultLineSize > 0.f) { - float lineSpacing = mDefaultLineSize - ( layout.ascender + -layout.descender ); - lineSpacing = lineSpacing < 0.f ? 0.f : lineSpacing; + float lineSpacing = mDefaultLineSize - (layout.ascender + -layout.descender); + lineSpacing = lineSpacing < 0.f ? 0.f : lineSpacing; penY += lineSpacing; } // Increase the glyph index. index = nextIndex; } // no ellipsis - } // end for() traversing glyphs. + } // end for() traversing glyphs. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - glyphPositions.Insert( glyphPositions.Begin() + layoutParameters.startGlyphIndex, - newGlyphPositions.Begin(), - newGlyphPositions.End() ); - glyphPositions.Resize( totalNumberOfGlyphs ); + glyphPositions.Insert(glyphPositions.Begin() + layoutParameters.startGlyphIndex, + newGlyphPositions.Begin(), + newGlyphPositions.End()); + glyphPositions.Resize(totalNumberOfGlyphs); - newLines.Resize( numberOfLines ); + newLines.Resize(numberOfLines); // Current text's layout size adds only the newly laid-out lines. // Updates the layout size with the previously laid-out lines. - UpdateLayoutSize( lines, - layoutSize ); + UpdateLayoutSize(lines, + layoutSize); - if( 0u != newLines.Count() ) + if(0u != newLines.Count()) { - const LineRun& lastLine = *( newLines.End() - 1u ); + const LineRun& lastLine = *(newLines.End() - 1u); const Length characterOffset = lastLine.characterRun.characterIndex + lastLine.characterRun.numberOfCharacters; - const Length glyphOffset = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs; + const Length glyphOffset = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs; // Update the indices of the runs before the new laid-out lines are inserted. - UpdateLineIndexOffsets( layoutParameters, - lines, - characterOffset, - glyphOffset ); + UpdateLineIndexOffsets(layoutParameters, + lines, + characterOffset, + glyphOffset); // Insert the lines. - lines.Insert( lines.Begin() + layoutParameters.startLineIndex, - newLines.Begin(), - newLines.End() ); + lines.Insert(lines.Begin() + layoutParameters.startLineIndex, + newLines.Begin(), + newLines.End()); } } else { - lines.Resize( numberOfLines ); + lines.Resize(numberOfLines); } // Rounds upward to avoid a non integer size. - layoutSize.height = std::ceil( layoutSize.height ); + layoutSize.height = std::ceil(layoutSize.height); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--LayoutText\n\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--LayoutText\n\n"); return true; } - void Align( const Size& size, - CharacterIndex startIndex, - Length numberOfCharacters, - Text::HorizontalAlignment::Type horizontalAlignment, - Vector& lines, - float& alignmentOffset, - Dali::LayoutDirection::Type layoutDirection, - bool matchSystemLanguageDirection ) + void Align(const Size& size, + CharacterIndex startIndex, + Length numberOfCharacters, + Text::HorizontalAlignment::Type horizontalAlignment, + Vector& lines, + float& alignmentOffset, + Dali::LayoutDirection::Type layoutDirection, + bool matchSystemLanguageDirection) { const CharacterIndex lastCharacterPlusOne = startIndex + numberOfCharacters; alignmentOffset = MAX_FLOAT; // Traverse all lines and align the glyphs. - for( Vector::Iterator it = lines.Begin(), endIt = lines.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = lines.Begin(), endIt = lines.End(); + it != endIt; + ++it) { LineRun& line = *it; - if( line.characterRun.characterIndex < startIndex ) + if(line.characterRun.characterIndex < startIndex) { // Do not align lines which have already been aligned. continue; } - if( line.characterRun.characterIndex > lastCharacterPlusOne ) + if(line.characterRun.characterIndex > lastCharacterPlusOne) { // Do not align lines beyond the last laid-out character. break; } - if( line.characterRun.characterIndex == lastCharacterPlusOne && !isEmptyLineAtLast( lines, it ) ) + if(line.characterRun.characterIndex == lastCharacterPlusOne && !isEmptyLineAtLast(lines, it)) { // Do not align lines beyond the last laid-out character unless the line is last and empty. break; @@ -1458,45 +1448,45 @@ struct Engine::Impl // Calculate the line's alignment offset accordingly with the align option, // the box width, line length, and the paragraph's direction. - CalculateHorizontalAlignment( size.width, - horizontalAlignment, - line, - layoutDirection, - matchSystemLanguageDirection ); + CalculateHorizontalAlignment(size.width, + horizontalAlignment, + line, + layoutDirection, + matchSystemLanguageDirection); // Updates the alignment offset. - alignmentOffset = std::min( alignmentOffset, line.alignmentOffset ); + alignmentOffset = std::min(alignmentOffset, line.alignmentOffset); } } - void CalculateHorizontalAlignment( float boxWidth, - HorizontalAlignment::Type horizontalAlignment, - LineRun& line, - Dali::LayoutDirection::Type layoutDirection, - bool matchSystemLanguageDirection ) + void CalculateHorizontalAlignment(float boxWidth, + HorizontalAlignment::Type horizontalAlignment, + LineRun& line, + Dali::LayoutDirection::Type layoutDirection, + bool matchSystemLanguageDirection) { line.alignmentOffset = 0.f; const bool isLineRTL = RTL == line.direction; // Whether to swap the alignment. // Swap if the line is RTL and is not required to match the direction of the system's language or if it's required to match the direction of the system's language and it's RTL. - bool isLayoutRTL = isLineRTL; - float lineLength = line.width; + bool isLayoutRTL = isLineRTL; + float lineLength = line.width; // match align for system language direction - if( matchSystemLanguageDirection ) + if(matchSystemLanguageDirection) { // Swap the alignment type if the line is right to left. isLayoutRTL = layoutDirection == LayoutDirection::RIGHT_TO_LEFT; } // Calculate the horizontal line offset. - switch( horizontalAlignment ) + switch(horizontalAlignment) { case HorizontalAlignment::BEGIN: { - if( isLayoutRTL ) + if(isLayoutRTL) { - if( isLineRTL ) + if(isLineRTL) { lineLength += line.extraLength; } @@ -1507,7 +1497,7 @@ struct Engine::Impl { line.alignmentOffset = 0.f; - if( isLineRTL ) + if(isLineRTL) { // 'Remove' the white spaces at the end of the line (which are at the beginning in visual order) line.alignmentOffset -= line.extraLength; @@ -1517,23 +1507,23 @@ struct Engine::Impl } case HorizontalAlignment::CENTER: { - line.alignmentOffset = 0.5f * ( boxWidth - lineLength ); + line.alignmentOffset = 0.5f * (boxWidth - lineLength); - if( isLineRTL ) + if(isLineRTL) { line.alignmentOffset -= line.extraLength; } - line.alignmentOffset = std::floor( line.alignmentOffset ); // floor() avoids pixel alignment issues. + line.alignmentOffset = std::floor(line.alignmentOffset); // floor() avoids pixel alignment issues. break; } case HorizontalAlignment::END: { - if( isLayoutRTL ) + if(isLayoutRTL) { line.alignmentOffset = 0.f; - if( isLineRTL ) + if(isLineRTL) { // 'Remove' the white spaces at the end of the line (which are at the beginning in visual order) line.alignmentOffset -= line.extraLength; @@ -1541,7 +1531,7 @@ struct Engine::Impl } else { - if( isLineRTL ) + if(isLineRTL) { lineLength += line.extraLength; } @@ -1553,23 +1543,23 @@ struct Engine::Impl } } - void Initialize( LineRun& line ) + void Initialize(LineRun& line) { - line.glyphRun.glyphIndex = 0u; - line.glyphRun.numberOfGlyphs = 0u; - line.characterRun.characterIndex = 0u; + line.glyphRun.glyphIndex = 0u; + line.glyphRun.numberOfGlyphs = 0u; + line.characterRun.characterIndex = 0u; line.characterRun.numberOfCharacters = 0u; - line.width = 0.f; - line.ascender = 0.f; - line.descender = 0.f; - line.extraLength = 0.f; - line.alignmentOffset = 0.f; - line.direction = LTR; - line.ellipsis = false; - line.lineSpacing = mDefaultLineSpacing; + line.width = 0.f; + line.ascender = 0.f; + line.descender = 0.f; + line.extraLength = 0.f; + line.alignmentOffset = 0.f; + line.direction = LTR; + line.ellipsis = false; + line.lineSpacing = mDefaultLineSpacing; } - Type mLayout; + Type mLayout; float mCursorWidth; float mDefaultLineSpacing; float mDefaultLineSize; @@ -1578,7 +1568,7 @@ struct Engine::Impl }; Engine::Engine() -: mImpl{ nullptr } +: mImpl{nullptr} { mImpl = new Engine::Impl(); } @@ -1588,63 +1578,63 @@ Engine::~Engine() delete mImpl; } -void Engine::SetMetrics( MetricsPtr& metrics ) +void Engine::SetMetrics(MetricsPtr& metrics) { mImpl->mMetrics = metrics; } -void Engine::SetLayout( Type layout ) +void Engine::SetLayout(Type layout) { mImpl->mLayout = layout; } Engine::Type Engine::GetLayout() const { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GetLayout[%d]\n", mImpl->mLayout); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GetLayout[%d]\n", mImpl->mLayout); return mImpl->mLayout; } -void Engine::SetCursorWidth( int width ) +void Engine::SetCursorWidth(int width) { - mImpl->mCursorWidth = static_cast( width ); + mImpl->mCursorWidth = static_cast(width); } int Engine::GetCursorWidth() const { - return static_cast( mImpl->mCursorWidth ); + return static_cast(mImpl->mCursorWidth); } -bool Engine::LayoutText( Parameters& layoutParameters, - Size& layoutSize, - bool elideTextEnabled, - bool& isAutoScrollEnabled ) +bool Engine::LayoutText(Parameters& layoutParameters, + Size& layoutSize, + bool elideTextEnabled, + bool& isAutoScrollEnabled) { - return mImpl->LayoutText( layoutParameters, - layoutSize, - elideTextEnabled, - isAutoScrollEnabled ); + return mImpl->LayoutText(layoutParameters, + layoutSize, + elideTextEnabled, + isAutoScrollEnabled); } -void Engine::Align( const Size& size, - CharacterIndex startIndex, - Length numberOfCharacters, - Text::HorizontalAlignment::Type horizontalAlignment, - Vector& lines, - float& alignmentOffset, - Dali::LayoutDirection::Type layoutDirection, - bool matchSystemLanguageDirection ) +void Engine::Align(const Size& size, + CharacterIndex startIndex, + Length numberOfCharacters, + Text::HorizontalAlignment::Type horizontalAlignment, + Vector& lines, + float& alignmentOffset, + Dali::LayoutDirection::Type layoutDirection, + bool matchSystemLanguageDirection) { - mImpl->Align( size, - startIndex, - numberOfCharacters, - horizontalAlignment, - lines, - alignmentOffset, - layoutDirection, - matchSystemLanguageDirection ); + mImpl->Align(size, + startIndex, + numberOfCharacters, + horizontalAlignment, + lines, + alignmentOffset, + layoutDirection, + matchSystemLanguageDirection); } -void Engine::SetDefaultLineSpacing( float lineSpacing ) +void Engine::SetDefaultLineSpacing(float lineSpacing) { mImpl->mDefaultLineSpacing = lineSpacing; } @@ -1654,7 +1644,7 @@ float Engine::GetDefaultLineSpacing() const return mImpl->mDefaultLineSpacing; } -void Engine::SetDefaultLineSize( float lineSize ) +void Engine::SetDefaultLineSize(float lineSize) { mImpl->mDefaultLineSize = lineSize; } diff --git a/dali-toolkit/internal/text/logical-model-impl.cpp b/dali-toolkit/internal/text/logical-model-impl.cpp old mode 100755 new mode 100644 index 3d9440e..8ecab1f --- a/dali-toolkit/internal/text/logical-model-impl.cpp +++ b/dali-toolkit/internal/text/logical-model-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. @@ -24,32 +24,29 @@ namespace Dali { - namespace Toolkit { - namespace Text { - -void FreeFontFamilyNames( Vector& fontDescriptionRuns ) +void FreeFontFamilyNames(Vector& fontDescriptionRuns) { - for( Vector::Iterator it = fontDescriptionRuns.Begin(), - endIt = fontDescriptionRuns.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = fontDescriptionRuns.Begin(), + endIt = fontDescriptionRuns.End(); + it != endIt; + ++it) { - delete[] (*it).familyName; + delete[](*it).familyName; } fontDescriptionRuns.Clear(); } -void FreeEmbeddedItems( Vector& embeddedItem ) +void FreeEmbeddedItems(Vector& embeddedItem) { - for( Vector::Iterator it = embeddedItem.Begin(), - endIt = embeddedItem.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = embeddedItem.Begin(), + endIt = embeddedItem.End(); + it != endIt; + ++it) { EmbeddedItem& item = *it; delete[] item.url; @@ -60,20 +57,20 @@ void FreeEmbeddedItems( Vector& embeddedItem ) LogicalModelPtr LogicalModel::New() { - return LogicalModelPtr( new LogicalModel() ); + return LogicalModelPtr(new LogicalModel()); } -Script LogicalModel::GetScript( CharacterIndex characterIndex ) const +Script LogicalModel::GetScript(CharacterIndex characterIndex) const { // If this operation is too slow, consider a binary search. const ScriptRun* const scriptRunBuffer = mScriptRuns.Begin(); - for( Length index = 0u, length = mScriptRuns.Count(); index < length; ++index ) + for(Length index = 0u, length = mScriptRuns.Count(); index < length; ++index) { const ScriptRun* const scriptRun = scriptRunBuffer + index; - if( ( scriptRun->characterRun.characterIndex <= characterIndex ) && - ( characterIndex < scriptRun->characterRun.characterIndex + scriptRun->characterRun.numberOfCharacters ) ) + if((scriptRun->characterRun.characterIndex <= characterIndex) && + (characterIndex < scriptRun->characterRun.characterIndex + scriptRun->characterRun.numberOfCharacters)) { return scriptRun->script; } @@ -82,18 +79,18 @@ Script LogicalModel::GetScript( CharacterIndex characterIndex ) const return TextAbstraction::UNKNOWN; } -CharacterDirection LogicalModel::GetCharacterDirection( CharacterIndex characterIndex ) const +CharacterDirection LogicalModel::GetCharacterDirection(CharacterIndex characterIndex) const { - if( characterIndex >= mCharacterDirections.Count() ) + if(characterIndex >= mCharacterDirections.Count()) { // The model has no right to left characters, so the vector of directions is void. return false; } - return *( mCharacterDirections.Begin() + characterIndex ); + return *(mCharacterDirections.Begin() + characterIndex); } -CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorIndex ) +CharacterIndex LogicalModel::GetLogicalCursorIndex(CharacterIndex visualCursorIndex) { // The character's directions buffer. const CharacterDirection* const modelCharacterDirections = mCharacterDirections.Begin(); @@ -109,9 +106,9 @@ CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorI CharacterIndex logicalCursorIndex = 0u; - if( bidirectionalLineInfo->characterRun.characterIndex == visualCursorIndex ) + if(bidirectionalLineInfo->characterRun.characterIndex == visualCursorIndex) { - if( isRightToLeftParagraph ) + if(isRightToLeftParagraph) { logicalCursorIndex = lastCharacterIndex; } @@ -120,9 +117,9 @@ CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorI logicalCursorIndex = bidirectionalLineInfo->characterRun.characterIndex; } } - else if( lastCharacterIndex == visualCursorIndex ) + else if(lastCharacterIndex == visualCursorIndex) { - if( isRightToLeftParagraph ) + if(isRightToLeftParagraph) { logicalCursorIndex = bidirectionalLineInfo->characterRun.characterIndex; } @@ -137,17 +134,17 @@ CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorI // and calculate the logical position according the directions of // both characters and the direction of the paragraph. - const CharacterIndex previousVisualCursorIndex = visualCursorIndex - 1u; - const CharacterIndex previousLogicalCursorIndex = *( bidirectionalLineInfo->visualToLogicalMap + previousVisualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex ) + bidirectionalLineInfo->characterRun.characterIndex; - const CharacterIndex currentLogicalCursorIndex = *( bidirectionalLineInfo->visualToLogicalMap + visualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex ) + bidirectionalLineInfo->characterRun.characterIndex; + const CharacterIndex previousVisualCursorIndex = visualCursorIndex - 1u; + const CharacterIndex previousLogicalCursorIndex = *(bidirectionalLineInfo->visualToLogicalMap + previousVisualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex; + const CharacterIndex currentLogicalCursorIndex = *(bidirectionalLineInfo->visualToLogicalMap + visualCursorIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex; - const CharacterDirection previousCharacterDirection = *( modelCharacterDirections + previousLogicalCursorIndex ); - const CharacterDirection currentCharacterDirection = *( modelCharacterDirections + currentLogicalCursorIndex ); + const CharacterDirection previousCharacterDirection = *(modelCharacterDirections + previousLogicalCursorIndex); + const CharacterDirection currentCharacterDirection = *(modelCharacterDirections + currentLogicalCursorIndex); - if( previousCharacterDirection == currentCharacterDirection ) + if(previousCharacterDirection == currentCharacterDirection) { // Both glyphs have the same direction. - if( previousCharacterDirection ) + if(previousCharacterDirection) { logicalCursorIndex = previousLogicalCursorIndex; } @@ -158,9 +155,9 @@ CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorI } else { - if( isRightToLeftParagraph ) + if(isRightToLeftParagraph) { - if( currentCharacterDirection ) + if(currentCharacterDirection) { logicalCursorIndex = currentLogicalCursorIndex + 1u; } @@ -171,7 +168,7 @@ CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorI } else { - if( previousCharacterDirection ) + if(previousCharacterDirection) { logicalCursorIndex = currentLogicalCursorIndex; } @@ -186,20 +183,20 @@ CharacterIndex LogicalModel::GetLogicalCursorIndex( CharacterIndex visualCursorI return logicalCursorIndex; } -CharacterIndex LogicalModel::GetLogicalCharacterIndex( CharacterIndex visualCharacterIndex ) +CharacterIndex LogicalModel::GetLogicalCharacterIndex(CharacterIndex visualCharacterIndex) { // The bidirectional line info. const BidirectionalLineInfoRun* const bidirectionalLineInfo = mBidirectionalLineInfo.Begin() + mBidirectionalLineIndex; - return *( bidirectionalLineInfo->visualToLogicalMap + visualCharacterIndex - bidirectionalLineInfo->characterRun.characterIndex ) + bidirectionalLineInfo->characterRun.characterIndex; + return *(bidirectionalLineInfo->visualToLogicalMap + visualCharacterIndex - bidirectionalLineInfo->characterRun.characterIndex) + bidirectionalLineInfo->characterRun.characterIndex; } -bool LogicalModel::FetchBidirectionalLineInfo( CharacterIndex characterIndex ) +bool LogicalModel::FetchBidirectionalLineInfo(CharacterIndex characterIndex) { // The number of bidirectional lines. const Length numberOfBidirectionalLines = mBidirectionalLineInfo.Count(); - if( 0u == numberOfBidirectionalLines ) + if(0u == numberOfBidirectionalLines) { // If there is no bidirectional info. return false; @@ -211,15 +208,15 @@ bool LogicalModel::FetchBidirectionalLineInfo( CharacterIndex characterIndex ) // Check first if the character is in the previously fetched line. - BidirectionalLineRunIndex bidiLineIndex = 0u; - CharacterIndex lastCharacterOfRightToLeftRun = 0u; - if( mBidirectionalLineIndex < numberOfBidirectionalLines ) + BidirectionalLineRunIndex bidiLineIndex = 0u; + CharacterIndex lastCharacterOfRightToLeftRun = 0u; + if(mBidirectionalLineIndex < numberOfBidirectionalLines) { - const BidirectionalLineInfoRun& bidiLineRun = *( bidirectionalLineInfoBuffer + mBidirectionalLineIndex ); + const BidirectionalLineInfoRun& bidiLineRun = *(bidirectionalLineInfoBuffer + mBidirectionalLineIndex); const CharacterIndex lastCharacterOfRunPlusOne = bidiLineRun.characterRun.characterIndex + bidiLineRun.characterRun.numberOfCharacters; - if( ( bidiLineRun.characterRun.characterIndex <= characterIndex ) && - ( characterIndex < lastCharacterOfRunPlusOne ) ) + if((bidiLineRun.characterRun.characterIndex <= characterIndex) && + (characterIndex < lastCharacterOfRunPlusOne)) { // The character is in the previously fetched bidi line. return true; @@ -229,7 +226,7 @@ bool LogicalModel::FetchBidirectionalLineInfo( CharacterIndex characterIndex ) // The character is not in the previously fetched line. // Set the bidi line index from where to start the fetch. - if( characterIndex < bidiLineRun.characterRun.characterIndex ) + if(characterIndex < bidiLineRun.characterRun.characterIndex) { // Start the fetch from the beginning. bidiLineIndex = 0u; @@ -237,31 +234,31 @@ bool LogicalModel::FetchBidirectionalLineInfo( CharacterIndex characterIndex ) else { // Start the fetch from the next line. - bidiLineIndex = mBidirectionalLineIndex + 1u; + bidiLineIndex = mBidirectionalLineIndex + 1u; lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u; } } } // The character has not been found in the previously fetched bidi line. - for( Vector::ConstIterator it = bidirectionalLineInfoBuffer + bidiLineIndex, - endIt = mBidirectionalLineInfo.End(); - it != endIt; - ++it, ++bidiLineIndex ) + for(Vector::ConstIterator it = bidirectionalLineInfoBuffer + bidiLineIndex, + endIt = mBidirectionalLineInfo.End(); + it != endIt; + ++it, ++bidiLineIndex) { const BidirectionalLineInfoRun& bidiLineRun = *it; - if( ( lastCharacterOfRightToLeftRun < characterIndex ) && - ( characterIndex < bidiLineRun.characterRun.characterIndex ) ) + if((lastCharacterOfRightToLeftRun < characterIndex) && + (characterIndex < bidiLineRun.characterRun.characterIndex)) { // The character is not inside a bidi line. return false; } const CharacterIndex lastCharacterOfRunPlusOne = bidiLineRun.characterRun.characterIndex + bidiLineRun.characterRun.numberOfCharacters; - lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u; - if( ( bidiLineRun.characterRun.characterIndex <= characterIndex ) && - ( characterIndex < lastCharacterOfRunPlusOne ) ) + lastCharacterOfRightToLeftRun = lastCharacterOfRunPlusOne - 1u; + if((bidiLineRun.characterRun.characterIndex <= characterIndex) && + (characterIndex < lastCharacterOfRunPlusOne)) { // Bidi line found. Fetch the line. mBidirectionalLineIndex = bidiLineIndex; @@ -277,65 +274,65 @@ BidirectionalLineRunIndex LogicalModel::GetBidirectionalLineInfo() const return mBidirectionalLineIndex; } -void LogicalModel::UpdateTextStyleRuns( CharacterIndex index, int numberOfCharacters ) +void LogicalModel::UpdateTextStyleRuns(CharacterIndex index, int numberOfCharacters) { const Length totalNumberOfCharacters = mText.Count(); // Process the color runs. Vector removedColorRuns; - UpdateCharacterRuns( index, - numberOfCharacters, - totalNumberOfCharacters, - mColorRuns, - removedColorRuns ); + UpdateCharacterRuns(index, + numberOfCharacters, + totalNumberOfCharacters, + mColorRuns, + removedColorRuns); // Process the background color runs. Vector removedBackgroundColorRuns; - UpdateCharacterRuns( index, - numberOfCharacters, - totalNumberOfCharacters, - mBackgroundColorRuns, - removedBackgroundColorRuns ); + UpdateCharacterRuns(index, + numberOfCharacters, + totalNumberOfCharacters, + mBackgroundColorRuns, + removedBackgroundColorRuns); // Process the font description runs. Vector removedFontDescriptionRuns; - UpdateCharacterRuns( index, - numberOfCharacters, - totalNumberOfCharacters, - mFontDescriptionRuns, - removedFontDescriptionRuns ); + UpdateCharacterRuns(index, + numberOfCharacters, + totalNumberOfCharacters, + mFontDescriptionRuns, + removedFontDescriptionRuns); // Free memory allocated for the font family name. - FreeFontFamilyNames( removedFontDescriptionRuns ); + FreeFontFamilyNames(removedFontDescriptionRuns); } -void LogicalModel::RetrieveStyle( CharacterIndex index, InputStyle& style ) +void LogicalModel::RetrieveStyle(CharacterIndex index, InputStyle& style) { unsigned int runIndex = 0u; // Set the text color. - bool colorOverriden = false; - unsigned int colorIndex = 0u; + bool colorOverriden = false; + unsigned int colorIndex = 0u; const ColorRun* const colorRunsBuffer = mColorRuns.Begin(); - for( Vector::ConstIterator it = colorRunsBuffer, - endIt = mColorRuns.End(); - it != endIt; - ++it, ++runIndex ) + for(Vector::ConstIterator it = colorRunsBuffer, + endIt = mColorRuns.End(); + it != endIt; + ++it, ++runIndex) { const ColorRun& colorRun = *it; - if( ( colorRun.characterRun.characterIndex <= index ) && - ( index < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters ) ) + if((colorRun.characterRun.characterIndex <= index) && + (index < colorRun.characterRun.characterIndex + colorRun.characterRun.numberOfCharacters)) { - colorIndex = runIndex; + colorIndex = runIndex; colorOverriden = true; } } // Set the text's color if it's overriden. - if( colorOverriden ) + if(colorOverriden) { - style.textColor = ( *( colorRunsBuffer + colorIndex ) ).color; + style.textColor = (*(colorRunsBuffer + colorIndex)).color; style.isDefaultColor = false; } @@ -343,125 +340,125 @@ void LogicalModel::RetrieveStyle( CharacterIndex index, InputStyle& style ) runIndex = 0u; // Set the font's parameters. - bool nameOverriden = false; - bool weightOverriden = false; - bool widthOverriden = false; - bool slantOverriden = false; - bool sizeOverriden = false; - unsigned int nameIndex = 0u; - unsigned int weightIndex = 0u; - unsigned int widthIndex = 0u; - unsigned int slantIndex = 0u; - unsigned int sizeIndex = 0u; + bool nameOverriden = false; + bool weightOverriden = false; + bool widthOverriden = false; + bool slantOverriden = false; + bool sizeOverriden = false; + unsigned int nameIndex = 0u; + unsigned int weightIndex = 0u; + unsigned int widthIndex = 0u; + unsigned int slantIndex = 0u; + unsigned int sizeIndex = 0u; const FontDescriptionRun* const fontDescriptionRunsBuffer = mFontDescriptionRuns.Begin(); - for( Vector::ConstIterator it = fontDescriptionRunsBuffer, - endIt = mFontDescriptionRuns.End(); - it != endIt; - ++it, ++runIndex ) + for(Vector::ConstIterator it = fontDescriptionRunsBuffer, + endIt = mFontDescriptionRuns.End(); + it != endIt; + ++it, ++runIndex) { const FontDescriptionRun& fontDescriptionRun = *it; - if( ( fontDescriptionRun.characterRun.characterIndex <= index ) && - ( index < fontDescriptionRun.characterRun.characterIndex + fontDescriptionRun.characterRun.numberOfCharacters ) ) + if((fontDescriptionRun.characterRun.characterIndex <= index) && + (index < fontDescriptionRun.characterRun.characterIndex + fontDescriptionRun.characterRun.numberOfCharacters)) { - if( fontDescriptionRun.familyDefined ) + if(fontDescriptionRun.familyDefined) { - nameIndex = runIndex; + nameIndex = runIndex; nameOverriden = true; } - if( fontDescriptionRun.weightDefined ) + if(fontDescriptionRun.weightDefined) { - weightIndex = runIndex; + weightIndex = runIndex; weightOverriden = true; } - if( fontDescriptionRun.widthDefined ) + if(fontDescriptionRun.widthDefined) { - widthIndex = runIndex; + widthIndex = runIndex; widthOverriden = true; } - if( fontDescriptionRun.slantDefined ) + if(fontDescriptionRun.slantDefined) { - slantIndex = runIndex; + slantIndex = runIndex; slantOverriden = true; } - if( fontDescriptionRun.sizeDefined ) + if(fontDescriptionRun.sizeDefined) { - sizeIndex = runIndex; + sizeIndex = runIndex; sizeOverriden = true; } } } // Set the font's family name if it's overriden. - if( nameOverriden ) + if(nameOverriden) { - const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + nameIndex ); + const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + nameIndex); - style.familyName = std::string( fontDescriptionRun.familyName, fontDescriptionRun.familyLength ); + style.familyName = std::string(fontDescriptionRun.familyName, fontDescriptionRun.familyLength); style.isFamilyDefined = true; } // Set the font's weight if it's overriden. - if( weightOverriden ) + if(weightOverriden) { - const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + weightIndex ); + const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + weightIndex); - style.weight = fontDescriptionRun.weight; + style.weight = fontDescriptionRun.weight; style.isWeightDefined = true; } // Set the font's width if it's overriden. - if( widthOverriden ) + if(widthOverriden) { - const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + widthIndex ); + const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + widthIndex); - style.width = fontDescriptionRun.width; + style.width = fontDescriptionRun.width; style.isWidthDefined = true; } // Set the font's slant if it's overriden. - if( slantOverriden ) + if(slantOverriden) { - const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + slantIndex ); + const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + slantIndex); - style.slant = fontDescriptionRun.slant; + style.slant = fontDescriptionRun.slant; style.isSlantDefined = true; } // Set the font's size if it's overriden. - if( sizeOverriden ) + if(sizeOverriden) { - const FontDescriptionRun& fontDescriptionRun = *( fontDescriptionRunsBuffer + sizeIndex ); + const FontDescriptionRun& fontDescriptionRun = *(fontDescriptionRunsBuffer + sizeIndex); - style.size = static_cast( fontDescriptionRun.size ) / 64.f; + style.size = static_cast(fontDescriptionRun.size) / 64.f; style.isSizeDefined = true; } } void LogicalModel::ClearFontDescriptionRuns() { - FreeFontFamilyNames( mFontDescriptionRuns ); + FreeFontFamilyNames(mFontDescriptionRuns); } -void LogicalModel::CreateParagraphInfo( CharacterIndex startIndex, - Length numberOfCharacters ) +void LogicalModel::CreateParagraphInfo(CharacterIndex startIndex, + Length numberOfCharacters) { const Length totalNumberOfCharacters = mLineBreakInfo.Count(); // Count the number of LINE_MUST_BREAK to reserve some space for the vector of paragraph's info. Vector paragraphs; - paragraphs.Reserve( numberOfCharacters ); - const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = mLineBreakInfo.Begin(); - const CharacterIndex lastCharacterIndexPlusOne = startIndex + numberOfCharacters; - for( Length index = startIndex; index < lastCharacterIndexPlusOne; ++index ) + paragraphs.Reserve(numberOfCharacters); + const TextAbstraction::LineBreakInfo* lineBreakInfoBuffer = mLineBreakInfo.Begin(); + const CharacterIndex lastCharacterIndexPlusOne = startIndex + numberOfCharacters; + for(Length index = startIndex; index < lastCharacterIndexPlusOne; ++index) { - if( TextAbstraction::LINE_MUST_BREAK == *( lineBreakInfoBuffer + index ) ) + if(TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + index)) { - paragraphs.PushBack( index ); + paragraphs.PushBack(index); } } @@ -469,16 +466,16 @@ void LogicalModel::CreateParagraphInfo( CharacterIndex startIndex, const bool updateCurrentParagraphs = numberOfCharacters < totalNumberOfCharacters; // Reserve space for current paragraphs plus new ones. - const Length numberOfNewParagraphs = paragraphs.Count(); + const Length numberOfNewParagraphs = paragraphs.Count(); const Length totalNumberOfParagraphs = mParagraphInfo.Count() + numberOfNewParagraphs; - mParagraphInfo.Resize( totalNumberOfParagraphs ); + mParagraphInfo.Resize(totalNumberOfParagraphs); - ParagraphRun* paragraphInfoBuffer = NULL; + ParagraphRun* paragraphInfoBuffer = NULL; Vector newParagraphs; - if( updateCurrentParagraphs ) + if(updateCurrentParagraphs) { - newParagraphs.Resize( numberOfNewParagraphs ); + newParagraphs.Resize(numberOfNewParagraphs); paragraphInfoBuffer = newParagraphs.Begin(); } else @@ -488,18 +485,18 @@ void LogicalModel::CreateParagraphInfo( CharacterIndex startIndex, // Find where to insert the new paragraphs. ParagraphRunIndex paragraphIndex = 0u; - CharacterIndex firstIndex = startIndex; + CharacterIndex firstIndex = startIndex; - if( updateCurrentParagraphs ) + if(updateCurrentParagraphs) { - for( Vector::ConstIterator it = mParagraphInfo.Begin(), - endIt = mParagraphInfo.Begin() + totalNumberOfParagraphs - numberOfNewParagraphs; - it != endIt; - ++it ) + for(Vector::ConstIterator it = mParagraphInfo.Begin(), + endIt = mParagraphInfo.Begin() + totalNumberOfParagraphs - numberOfNewParagraphs; + it != endIt; + ++it) { - const ParagraphRun& paragraph( *it ); + const ParagraphRun& paragraph(*it); - if( startIndex < paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters ) + if(startIndex < paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters) { firstIndex = paragraph.characterRun.characterIndex; break; @@ -511,70 +508,69 @@ void LogicalModel::CreateParagraphInfo( CharacterIndex startIndex, // Create the paragraph info. ParagraphRunIndex newParagraphIndex = 0u; - for( Vector::ConstIterator it = paragraphs.Begin(), - endIt = paragraphs.End(); - it != endIt; - ++it, ++newParagraphIndex ) + for(Vector::ConstIterator it = paragraphs.Begin(), + endIt = paragraphs.End(); + it != endIt; + ++it, ++newParagraphIndex) { const CharacterIndex index = *it; - ParagraphRun& paragraph = *( paragraphInfoBuffer + newParagraphIndex ); - paragraph.characterRun.characterIndex = firstIndex; + ParagraphRun& paragraph = *(paragraphInfoBuffer + newParagraphIndex); + paragraph.characterRun.characterIndex = firstIndex; paragraph.characterRun.numberOfCharacters = 1u + index - firstIndex; firstIndex += paragraph.characterRun.numberOfCharacters; } - // Insert the new paragraphs. - if( updateCurrentParagraphs ) + if(updateCurrentParagraphs) { - mParagraphInfo.Insert( mParagraphInfo.Begin() + paragraphIndex, - newParagraphs.Begin(), - newParagraphs.End() ); + mParagraphInfo.Insert(mParagraphInfo.Begin() + paragraphIndex, + newParagraphs.Begin(), + newParagraphs.End()); - mParagraphInfo.Resize( totalNumberOfParagraphs ); + mParagraphInfo.Resize(totalNumberOfParagraphs); // Update the next paragraph indices. - for( Vector::Iterator it = mParagraphInfo.Begin() + paragraphIndex + newParagraphs.Count(), - endIt = mParagraphInfo.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = mParagraphInfo.Begin() + paragraphIndex + newParagraphs.Count(), + endIt = mParagraphInfo.End(); + it != endIt; + ++it) { - ParagraphRun& paragraph( *it ); + ParagraphRun& paragraph(*it); paragraph.characterRun.characterIndex += numberOfCharacters; } } } -void LogicalModel::FindParagraphs( CharacterIndex index, - Length numberOfCharacters, - Vector& paragraphs ) +void LogicalModel::FindParagraphs(CharacterIndex index, + Length numberOfCharacters, + Vector& paragraphs) { // Reserve som space for the paragraph indices. - paragraphs.Reserve( mParagraphInfo.Count() ); + paragraphs.Reserve(mParagraphInfo.Count()); // Traverse the paragraphs to find which ones contain the given characters. ParagraphRunIndex paragraphIndex = 0u; - for( Vector::ConstIterator it = mParagraphInfo.Begin(), - endIt = mParagraphInfo.End(); - it != endIt; - ++it, ++paragraphIndex ) + for(Vector::ConstIterator it = mParagraphInfo.Begin(), + endIt = mParagraphInfo.End(); + it != endIt; + ++it, ++paragraphIndex) { - const ParagraphRun& paragraph( *it ); + const ParagraphRun& paragraph(*it); - if( ( paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters > index ) && - ( paragraph.characterRun.characterIndex < index + numberOfCharacters ) ) + if((paragraph.characterRun.characterIndex + paragraph.characterRun.numberOfCharacters > index) && + (paragraph.characterRun.characterIndex < index + numberOfCharacters)) { - paragraphs.PushBack( paragraphIndex ); + paragraphs.PushBack(paragraphIndex); } } } void LogicalModel::ClearEmbeddedImages() { - FreeEmbeddedItems( mEmbeddedItems ); + FreeEmbeddedItems(mEmbeddedItems); } LogicalModel::~LogicalModel() @@ -584,7 +580,7 @@ LogicalModel::~LogicalModel() } LogicalModel::LogicalModel() -: mBidirectionalLineIndex( 0u ) +: mBidirectionalLineIndex(0u) { } diff --git a/dali-toolkit/internal/text/markup-processor-color.cpp b/dali-toolkit/internal/text/markup-processor-color.cpp index 2fd826d..b66e37a 100644 --- a/dali-toolkit/internal/text/markup-processor-color.cpp +++ b/dali-toolkit/internal/text/markup-processor-color.cpp @@ -27,29 +27,26 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { const std::string XHTML_VALUE_ATTRIBUTE("value"); } -void ProcessColorTag( const Tag& tag, ColorRun& colorRun ) +void ProcessColorTag(const Tag& tag, ColorRun& colorRun) { - for( Vector::ConstIterator it = tag.attributes.Begin(), - endIt = tag.attributes.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = tag.attributes.Begin(), + endIt = tag.attributes.End(); + it != endIt; + ++it) { - const Attribute& attribute( *it ); - if( TokenComparison( XHTML_VALUE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + const Attribute& attribute(*it); + if(TokenComparison(XHTML_VALUE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { - ColorStringToVector4( attribute.valueBuffer, attribute.valueLength, colorRun.color ); + ColorStringToVector4(attribute.valueBuffer, attribute.valueLength, colorRun.color); } } } diff --git a/dali-toolkit/internal/text/markup-processor-embedded-item.cpp b/dali-toolkit/internal/text/markup-processor-embedded-item.cpp old mode 100755 new mode 100644 index 7751c01..1bfa3f4 --- a/dali-toolkit/internal/text/markup-processor-embedded-item.cpp +++ b/dali-toolkit/internal/text/markup-processor-embedded-item.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,13 +28,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { const std::string XHTML_URL_ATTRIBUTE("url"); @@ -44,40 +41,40 @@ const std::string XHTML_COLOR_BLENDING_ATTRIBUTE("color-blending"); const std::string NONE("none"); const std::string MULTIPLY("multiply"); -} +} // namespace -void ProcessEmbeddedItem( const Tag& tag, EmbeddedItem& embeddedItem ) +void ProcessEmbeddedItem(const Tag& tag, EmbeddedItem& embeddedItem) { - embeddedItem.url = nullptr; - embeddedItem.urlLength = 0u; - embeddedItem.width = 0u; - embeddedItem.height = 0u; + embeddedItem.url = nullptr; + embeddedItem.urlLength = 0u; + embeddedItem.width = 0u; + embeddedItem.height = 0u; embeddedItem.colorBlendingMode = ColorBlendingMode::NONE; - for( Vector::ConstIterator it = tag.attributes.Begin(), - endIt = tag.attributes.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = tag.attributes.Begin(), + endIt = tag.attributes.End(); + it != endIt; + ++it) { - const Attribute& attribute( *it ); - if( TokenComparison(XHTML_URL_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + const Attribute& attribute(*it); + if(TokenComparison(XHTML_URL_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { embeddedItem.urlLength = attribute.valueLength; - embeddedItem.url = new char[embeddedItem.urlLength]; + embeddedItem.url = new char[embeddedItem.urlLength]; memcpy(embeddedItem.url, attribute.valueBuffer, embeddedItem.urlLength); // The memory is freed when the font run is removed from the logical model. } - else if (TokenComparison(XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) + else if(TokenComparison(XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { embeddedItem.width = StringToUint(attribute.valueBuffer); } - else if (TokenComparison(XHTML_HEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) + else if(TokenComparison(XHTML_HEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { embeddedItem.height = StringToUint(attribute.valueBuffer); } - else if (TokenComparison(XHTML_COLOR_BLENDING_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) + else if(TokenComparison(XHTML_COLOR_BLENDING_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { - if (TokenComparison(MULTIPLY, attribute.valueBuffer, attribute.valueLength)) + if(TokenComparison(MULTIPLY, attribute.valueBuffer, attribute.valueLength)) { embeddedItem.colorBlendingMode = ColorBlendingMode::MULTIPLY; } diff --git a/dali-toolkit/internal/text/markup-processor-font.cpp b/dali-toolkit/internal/text/markup-processor-font.cpp index b745317..4ddcd61 100644 --- a/dali-toolkit/internal/text/markup-processor-font.cpp +++ b/dali-toolkit/internal/text/markup-processor-font.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. @@ -29,13 +29,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { const std::string XHTML_FAMILY_ATTRIBUTE("family"); @@ -45,61 +42,61 @@ const std::string XHTML_WIDTH_ATTRIBUTE("width"); const std::string XHTML_SLANT_ATTRIBUTE("slant"); const unsigned int MAX_FONT_ATTRIBUTE_SIZE = 15u; ///< The maximum length of any of the possible 'weight', 'width' or 'slant' values. -} +} // namespace -void ProcessFontTag( const Tag& tag, FontDescriptionRun& fontRun ) +void ProcessFontTag(const Tag& tag, FontDescriptionRun& fontRun) { - for( Vector::ConstIterator it = tag.attributes.Begin(), - endIt = tag.attributes.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = tag.attributes.Begin(), + endIt = tag.attributes.End(); + it != endIt; + ++it) { - const Attribute& attribute( *it ); - if( TokenComparison( XHTML_FAMILY_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + const Attribute& attribute(*it); + if(TokenComparison(XHTML_FAMILY_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { fontRun.familyDefined = true; - fontRun.familyLength = attribute.valueLength; - fontRun.familyName = new char[fontRun.familyLength]; - memcpy( fontRun.familyName, attribute.valueBuffer, fontRun.familyLength ); + fontRun.familyLength = attribute.valueLength; + fontRun.familyName = new char[fontRun.familyLength]; + memcpy(fontRun.familyName, attribute.valueBuffer, fontRun.familyLength); // The memory is freed when the font run is removed from the logical model. } - else if( TokenComparison( XHTML_SIZE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + else if(TokenComparison(XHTML_SIZE_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { // 64.f is used to convert from point size to 26.6 pixel format. - fontRun.size = static_cast( StringToFloat( attribute.valueBuffer ) * 64.f ); + fontRun.size = static_cast(StringToFloat(attribute.valueBuffer) * 64.f); fontRun.sizeDefined = true; } - else if( TokenComparison( XHTML_WEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + else if(TokenComparison(XHTML_WEIGHT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { // The StringToWeight() uses the Scripting::GetEnumeration() function which requires the input string to end with a '\0' char. - char value[MAX_FONT_ATTRIBUTE_SIZE+1u]; + char value[MAX_FONT_ATTRIBUTE_SIZE + 1u]; const Length length = attribute.valueLength > MAX_FONT_ATTRIBUTE_SIZE ? MAX_FONT_ATTRIBUTE_SIZE : attribute.valueLength; - memcpy( value, attribute.valueBuffer, length ); + memcpy(value, attribute.valueBuffer, length); value[length] = 0; - fontRun.weight = StringToWeight( value ); + fontRun.weight = StringToWeight(value); fontRun.weightDefined = true; } - else if( TokenComparison( XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + else if(TokenComparison(XHTML_WIDTH_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { // The StringToWidth() uses the Scripting::GetEnumeration() function which requires the input string to end with a '\0' char. - char value[MAX_FONT_ATTRIBUTE_SIZE+1u]; + char value[MAX_FONT_ATTRIBUTE_SIZE + 1u]; const Length length = attribute.valueLength > MAX_FONT_ATTRIBUTE_SIZE ? MAX_FONT_ATTRIBUTE_SIZE : attribute.valueLength; - memcpy( value, attribute.valueBuffer, length ); + memcpy(value, attribute.valueBuffer, length); value[length] = 0; - fontRun.width = StringToWidth( value ); + fontRun.width = StringToWidth(value); fontRun.widthDefined = true; } - else if( TokenComparison( XHTML_SLANT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength ) ) + else if(TokenComparison(XHTML_SLANT_ATTRIBUTE, attribute.nameBuffer, attribute.nameLength)) { // The StringToSlant() uses the Scripting::GetEnumeration() function which requires the input string to end with a '\0' char. - char value[MAX_FONT_ATTRIBUTE_SIZE+1u]; + char value[MAX_FONT_ATTRIBUTE_SIZE + 1u]; const Length length = attribute.valueLength > MAX_FONT_ATTRIBUTE_SIZE ? MAX_FONT_ATTRIBUTE_SIZE : attribute.valueLength; - memcpy( value, attribute.valueBuffer, length ); + memcpy(value, attribute.valueBuffer, length); value[length] = 0; - fontRun.slant = StringToSlant( value ); + fontRun.slant = StringToSlant(value); fontRun.slantDefined = true; } } diff --git a/dali-toolkit/internal/text/markup-processor-helper-functions.cpp b/dali-toolkit/internal/text/markup-processor-helper-functions.cpp old mode 100755 new mode 100644 index 6c133ae..ffa4cce --- a/dali-toolkit/internal/text/markup-processor-helper-functions.cpp +++ b/dali-toolkit/internal/text/markup-processor-helper-functions.cpp @@ -22,18 +22,15 @@ #include #include #include -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Text { - namespace { const char WHITE_SPACE = 0x20; // ASCII value of the white space. @@ -41,25 +38,25 @@ const char FIRST_UPPER_CASE = 0x41; // ASCII value of the one after the first up const char LAST_UPPER_CASE = 0x5b; // ASCII value of the one after the last upper case character (Z). const char TO_LOWER_CASE = 32; // Value to add to a upper case character to transform it into a lower case. -const char WEB_COLOR_TOKEN( '#' ); -const char* const HEX_COLOR_TOKEN( "0x" ); -const char* const ALPHA_ONE( "FF" ); - -const std::string BLACK_COLOR( "black" ); -const std::string WHITE_COLOR( "white" ); -const std::string RED_COLOR( "red" ); -const std::string GREEN_COLOR( "green" ); -const std::string BLUE_COLOR( "blue" ); -const std::string YELLOW_COLOR( "yellow" ); -const std::string MAGENTA_COLOR( "magenta" ); -const std::string CYAN_COLOR( "cyan" ); -const std::string TRANSPARENT_COLOR( "transparent" ); -} - -bool TokenComparison( const std::string& string1, const char* const stringBuffer2, Length length ) +const char WEB_COLOR_TOKEN('#'); +const char* const HEX_COLOR_TOKEN("0x"); +const char* const ALPHA_ONE("FF"); + +const std::string BLACK_COLOR("black"); +const std::string WHITE_COLOR("white"); +const std::string RED_COLOR("red"); +const std::string GREEN_COLOR("green"); +const std::string BLUE_COLOR("blue"); +const std::string YELLOW_COLOR("yellow"); +const std::string MAGENTA_COLOR("magenta"); +const std::string CYAN_COLOR("cyan"); +const std::string TRANSPARENT_COLOR("transparent"); +} // namespace + +bool TokenComparison(const std::string& string1, const char* const stringBuffer2, Length length) { const Length stringSize = string1.size(); - if( stringSize != length ) + if(stringSize != length) { // Early return. Strings have different sizes. return false; @@ -67,11 +64,11 @@ bool TokenComparison( const std::string& string1, const char* const stringBuffer const char* const stringBuffer1 = string1.c_str(); - for( std::size_t index = 0; index < stringSize; ++index ) + for(std::size_t index = 0; index < stringSize; ++index) { - const char character = *( stringBuffer2 + index ); - const bool toLower = ( character < LAST_UPPER_CASE ) && ( character >= FIRST_UPPER_CASE ); - if( *( stringBuffer1 + index ) != ( toLower ? character + TO_LOWER_CASE : character ) ) + const char character = *(stringBuffer2 + index); + const bool toLower = (character < LAST_UPPER_CASE) && (character >= FIRST_UPPER_CASE); + if(*(stringBuffer1 + index) != (toLower ? character + TO_LOWER_CASE : character)) { return false; } @@ -80,193 +77,195 @@ bool TokenComparison( const std::string& string1, const char* const stringBuffer return true; } -void SkipWhiteSpace( const char*& stringBuffer, - const char* const stringEndBuffer ) +void SkipWhiteSpace(const char*& stringBuffer, + const char* const stringEndBuffer) { - for( ; ( WHITE_SPACE >= *stringBuffer ) && ( stringBuffer < stringEndBuffer ); ++stringBuffer ); + for(; (WHITE_SPACE >= *stringBuffer) && (stringBuffer < stringEndBuffer); ++stringBuffer) + ; } -void JumpToWhiteSpace( const char*& stringBuffer, - const char* const stringEndBuffer ) +void JumpToWhiteSpace(const char*& stringBuffer, + const char* const stringEndBuffer) { - for( ; ( WHITE_SPACE != *stringBuffer ) && ( stringBuffer < stringEndBuffer ); ++stringBuffer ); + for(; (WHITE_SPACE != *stringBuffer) && (stringBuffer < stringEndBuffer); ++stringBuffer) + ; } -unsigned int StringToUint( const char* const uintStr ) +unsigned int StringToUint(const char* const uintStr) { - return static_cast( strtoul( uintStr, NULL, 10 ) ); + return static_cast(strtoul(uintStr, NULL, 10)); } -unsigned int StringToHex( const char* const uintStr ) +unsigned int StringToHex(const char* const uintStr) { - return static_cast( strtoul( uintStr, NULL, 16 ) ); + return static_cast(strtoul(uintStr, NULL, 16)); } -float StringToFloat( const char* const floatStr ) +float StringToFloat(const char* const floatStr) { - return static_cast( strtod( floatStr, NULL ) ); + return static_cast(strtod(floatStr, NULL)); } -void FloatToString( float value, std::string& floatStr ) +void FloatToString(float value, std::string& floatStr) { std::stringstream ss; ss << value; floatStr = ss.str(); } -void UintToString( unsigned int value, std::string& uIntStr ) +void UintToString(unsigned int value, std::string& uIntStr) { std::stringstream ss; ss << value; uIntStr = ss.str(); } -void UintColorToVector4( unsigned int color, Vector4& retColor ) +void UintColorToVector4(unsigned int color, Vector4& retColor) { - retColor.a = static_cast( ( color & 0xFF000000 ) >> 24u ) / 255.f; - retColor.r = static_cast( ( color & 0x00FF0000 ) >> 16u ) / 255.f; - retColor.g = static_cast( ( color & 0x0000FF00 ) >> 8u ) / 255.f; - retColor.b = static_cast( color & 0x000000FF ) / 255.f; + retColor.a = static_cast((color & 0xFF000000) >> 24u) / 255.f; + retColor.r = static_cast((color & 0x00FF0000) >> 16u) / 255.f; + retColor.g = static_cast((color & 0x0000FF00) >> 8u) / 255.f; + retColor.b = static_cast(color & 0x000000FF) / 255.f; } -void ColorStringToVector4( const char* const colorStr, Length length, Vector4& retColor ) +void ColorStringToVector4(const char* const colorStr, Length length, Vector4& retColor) { - if( WEB_COLOR_TOKEN == *colorStr ) + if(WEB_COLOR_TOKEN == *colorStr) { - std::string webColor( colorStr + 1u, length - 1u ); - if( 4u == length ) // 3 component web color #F00 (red) + std::string webColor(colorStr + 1u, length - 1u); + if(4u == length) // 3 component web color #F00 (red) { - webColor.insert( 2u, &( webColor[2] ), 1u ); - webColor.insert( 1u, &( webColor[1] ), 1u ); - webColor.insert( 0u, &( webColor[0] ), 1u ); - webColor.insert( 0u, ALPHA_ONE ); + webColor.insert(2u, &(webColor[2]), 1u); + webColor.insert(1u, &(webColor[1]), 1u); + webColor.insert(0u, &(webColor[0]), 1u); + webColor.insert(0u, ALPHA_ONE); } - else if( 7u == length ) // 6 component web color #FF0000 (red) + else if(7u == length) // 6 component web color #FF0000 (red) { - webColor.insert( 0u, ALPHA_ONE ); + webColor.insert(0u, ALPHA_ONE); } - UintColorToVector4( StringToHex( webColor.c_str() ), retColor ); + UintColorToVector4(StringToHex(webColor.c_str()), retColor); } - else if( TokenComparison( HEX_COLOR_TOKEN, colorStr, 2u ) ) + else if(TokenComparison(HEX_COLOR_TOKEN, colorStr, 2u)) { - UintColorToVector4( StringToHex( colorStr + 2u ), retColor ); + UintColorToVector4(StringToHex(colorStr + 2u), retColor); } - else if( TokenComparison( BLACK_COLOR, colorStr, length ) ) + else if(TokenComparison(BLACK_COLOR, colorStr, length)) { retColor = Color::BLACK; } - else if( TokenComparison( WHITE_COLOR, colorStr, length ) ) + else if(TokenComparison(WHITE_COLOR, colorStr, length)) { retColor = Color::WHITE; } - else if( TokenComparison( RED_COLOR, colorStr, length ) ) + else if(TokenComparison(RED_COLOR, colorStr, length)) { retColor = Color::RED; } - else if( TokenComparison( GREEN_COLOR, colorStr, length ) ) + else if(TokenComparison(GREEN_COLOR, colorStr, length)) { retColor = Color::GREEN; } - else if( TokenComparison( BLUE_COLOR, colorStr, length ) ) + else if(TokenComparison(BLUE_COLOR, colorStr, length)) { retColor = Color::BLUE; } - else if( TokenComparison( YELLOW_COLOR, colorStr, length ) ) + else if(TokenComparison(YELLOW_COLOR, colorStr, length)) { retColor = Color::YELLOW; } - else if( TokenComparison( MAGENTA_COLOR, colorStr, length ) ) + else if(TokenComparison(MAGENTA_COLOR, colorStr, length)) { retColor = Color::MAGENTA; } - else if( TokenComparison( CYAN_COLOR, colorStr, length ) ) + else if(TokenComparison(CYAN_COLOR, colorStr, length)) { retColor = Color::CYAN; } - else if( TokenComparison( TRANSPARENT_COLOR, colorStr, length ) ) + else if(TokenComparison(TRANSPARENT_COLOR, colorStr, length)) { retColor = Color::TRANSPARENT; } } -void Vector4ToColorString( const Vector4& value, std::string& vector2Str ) +void Vector4ToColorString(const Vector4& value, std::string& vector2Str) { - if( Color::BLACK == value ) + if(Color::BLACK == value) { vector2Str = BLACK_COLOR; return; } - if( Color::WHITE == value ) + if(Color::WHITE == value) { vector2Str = WHITE_COLOR; return; } - if( Color::RED == value ) + if(Color::RED == value) { vector2Str = RED_COLOR; return; } - if( Color::GREEN == value ) + if(Color::GREEN == value) { vector2Str = GREEN_COLOR; return; } - if( Color::BLUE == value ) + if(Color::BLUE == value) { vector2Str = BLUE_COLOR; return; } - if( Color::YELLOW == value ) + if(Color::YELLOW == value) { vector2Str = YELLOW_COLOR; return; } - if( Color::MAGENTA == value ) + if(Color::MAGENTA == value) { vector2Str = MAGENTA_COLOR; return; } - if( Color::CYAN == value ) + if(Color::CYAN == value) { vector2Str = CYAN_COLOR; return; } - if( Color::TRANSPARENT == value ) + if(Color::TRANSPARENT == value) { vector2Str = TRANSPARENT_COLOR; return; } - const unsigned int alpha = static_cast( 255.f * value.a ); - const unsigned int red = static_cast( 255.f * value.r ); - const unsigned int green = static_cast( 255.f * value.g ); - const unsigned int blue = static_cast( 255.f * value.b ); + const unsigned int alpha = static_cast(255.f * value.a); + const unsigned int red = static_cast(255.f * value.r); + const unsigned int green = static_cast(255.f * value.g); + const unsigned int blue = static_cast(255.f * value.b); - std::stringstream ss; - const unsigned int size = 2u * sizeof( unsigned char ); + std::stringstream ss; + const unsigned int size = 2u * sizeof(unsigned char); ss << "0x" - << std::setfill('0') << std::setw( size ) + << std::setfill('0') << std::setw(size) << std::hex << alpha - << std::setfill('0') << std::setw( size ) + << std::setfill('0') << std::setw(size) << std::hex << red - << std::setfill('0') << std::setw( size ) + << std::setfill('0') << std::setw(size) << std::hex << green - << std::setfill('0') << std::setw( size ) + << std::setfill('0') << std::setw(size) << std::hex << blue; vector2Str = ss.str(); } -void StringToVector2( const char* const vectorStr, Length length, Vector2& vector2 ) +void StringToVector2(const char* const vectorStr, Length length, Vector2& vector2) { // Points to the first character of the string. const char* strBuffer = vectorStr; @@ -275,23 +274,23 @@ void StringToVector2( const char* const vectorStr, Length length, Vector2& vecto const char* const xBuffer = strBuffer; // Jumps to the next white space. - JumpToWhiteSpace( strBuffer, strBuffer + length ); + JumpToWhiteSpace(strBuffer, strBuffer + length); // Points to the first character of the 'y' value. const char* const yBuffer = strBuffer; // Converts the shadow's offset to float. - vector2.x = StringToFloat( xBuffer ); - vector2.y = StringToFloat( yBuffer ); + vector2.x = StringToFloat(xBuffer); + vector2.y = StringToFloat(yBuffer); } -void Vector2ToString( const Vector2& value, std::string& vector2Str ) +void Vector2ToString(const Vector2& value, std::string& vector2Str) { - FloatToString( value.x, vector2Str ); + FloatToString(value.x, vector2Str); vector2Str += " "; std::string yStr; - FloatToString( value.y, yStr ); + FloatToString(value.y, yStr); vector2Str += yStr; } diff --git a/dali-toolkit/internal/text/markup-processor.cpp b/dali-toolkit/internal/text/markup-processor.cpp old mode 100755 new mode 100644 index 8e0b85b..20a5825 --- a/dali-toolkit/internal/text/markup-processor.cpp +++ b/dali-toolkit/internal/text/markup-processor.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 // for ULONG_MAX -#include #include +#include // for ULONG_MAX +#include // INTERNAL INCLUDES #include @@ -33,13 +33,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { // HTML-ISH tag and attribute constants. @@ -67,14 +64,14 @@ const char SEMI_COLON = ';'; const char CHAR_ARRAY_END = '\0'; const char HEX_CODE = 'x'; -const char WHITE_SPACE = 0x20; // ASCII value of the white space. +const char WHITE_SPACE = 0x20; // ASCII value of the white space. // Range 1 0x0u < XHTML_DECIMAL_ENTITY_RANGE <= 0xD7FFu // Range 2 0xE000u < XHTML_DECIMAL_ENTITY_RANGE <= 0xFFFDu // Range 3 0x10000u < XHTML_DECIMAL_ENTITY_RANGE <= 0x10FFFFu -const unsigned long XHTML_DECIMAL_ENTITY_RANGE[] = { 0x0u, 0xD7FFu, 0xE000u, 0xFFFDu, 0x10000u, 0x10FFFFu }; +const unsigned long XHTML_DECIMAL_ENTITY_RANGE[] = {0x0u, 0xD7FFu, 0xE000u, 0xFFFDu, 0x10000u, 0x10FFFFu}; -const unsigned int MAX_NUM_OF_ATTRIBUTES = 5u; ///< The font tag has the 'family', 'size' 'weight', 'width' and 'slant' attrubutes. +const unsigned int MAX_NUM_OF_ATTRIBUTES = 5u; ///< The font tag has the 'family', 'size' 'weight', 'width' and 'slant' attrubutes. const unsigned int DEFAULT_VECTOR_SIZE = 16u; ///< Default size of run vectors. #if defined(DEBUG_ENABLED) @@ -88,28 +85,28 @@ struct StyleStack { typedef VectorBase::SizeType RunIndex; - Vector stack; ///< Use a vector as a style stack. Stores the indices pointing where the run is stored inside the logical model. - unsigned int topIndex; ///< Points the top of the stack. + Vector stack; ///< Use a vector as a style stack. Stores the indices pointing where the run is stored inside the logical model. + unsigned int topIndex; ///< Points the top of the stack. StyleStack() : stack(), - topIndex( 0u ) + topIndex(0u) { - stack.Resize( DEFAULT_VECTOR_SIZE ); + stack.Resize(DEFAULT_VECTOR_SIZE); } - void Push( RunIndex index ) + void Push(RunIndex index) { // Check if there is space inside the style stack. const VectorBase::SizeType size = stack.Count(); - if( topIndex >= size ) + if(topIndex >= size) { // Resize the style stack. - stack.Resize( 2u * size ); + stack.Resize(2u * size); } // Set the run index in the top of the stack. - *( stack.Begin() + topIndex ) = index; + *(stack.Begin() + topIndex) = index; // Reposition the pointer to the top of the stack. ++topIndex; @@ -119,7 +116,7 @@ struct StyleStack { // Pop the top of the stack. --topIndex; - return *( stack.Begin() + topIndex ); + return *(stack.Begin() + topIndex); } }; @@ -128,21 +125,21 @@ struct StyleStack * * @param[in,out] fontRun The font description run to initialize. */ -void Initialize( FontDescriptionRun& fontRun ) +void Initialize(FontDescriptionRun& fontRun) { - fontRun.characterRun.characterIndex = 0u; + fontRun.characterRun.characterIndex = 0u; fontRun.characterRun.numberOfCharacters = 0u; - fontRun.familyName = NULL; - fontRun.familyLength = 0u; - fontRun.weight = TextAbstraction::FontWeight::NORMAL; - fontRun.width = TextAbstraction::FontWidth::NORMAL; - fontRun.slant = TextAbstraction::FontSlant::NORMAL; - fontRun.size = 0u; - fontRun.familyDefined = false; - fontRun.weightDefined = false; - fontRun.widthDefined = false; - fontRun.slantDefined = false; - fontRun.sizeDefined = false; + fontRun.familyName = NULL; + fontRun.familyLength = 0u; + fontRun.weight = TextAbstraction::FontWeight::NORMAL; + fontRun.width = TextAbstraction::FontWidth::NORMAL; + fontRun.slant = TextAbstraction::FontSlant::NORMAL; + fontRun.size = 0u; + fontRun.familyDefined = false; + fontRun.weightDefined = false; + fontRun.widthDefined = false; + fontRun.slantDefined = false; + fontRun.sizeDefined = false; } /** @@ -150,9 +147,9 @@ void Initialize( FontDescriptionRun& fontRun ) * * @param[in,out] colorRun The font description run to initialize. */ -void Initialize( ColorRun& colorRun ) +void Initialize(ColorRun& colorRun) { - colorRun.characterRun.characterIndex = 0u; + colorRun.characterRun.characterIndex = 0u; colorRun.characterRun.numberOfCharacters = 0u; } @@ -163,25 +160,25 @@ void Initialize( ColorRun& colorRun ) * * @param[in,out] tag The tag. */ -void ParseAttributes( Tag& tag ) +void ParseAttributes(Tag& tag) { - if( tag.buffer == NULL ) + if(tag.buffer == NULL) { return; } - tag.attributes.Resize( MAX_NUM_OF_ATTRIBUTES ); + tag.attributes.Resize(MAX_NUM_OF_ATTRIBUTES); // Find first the tag name. bool isQuotationOpen = false; - const char* tagBuffer = tag.buffer; + const char* tagBuffer = tag.buffer; const char* const tagEndBuffer = tagBuffer + tag.length; - tag.length = 0u; - for( ; tagBuffer < tagEndBuffer; ++tagBuffer ) + tag.length = 0u; + for(; tagBuffer < tagEndBuffer; ++tagBuffer) { const char character = *tagBuffer; - if( WHITE_SPACE < character ) + if(WHITE_SPACE < character) { ++tag.length; } @@ -192,70 +189,70 @@ void ParseAttributes( Tag& tag ) break; } } - SkipWhiteSpace( tagBuffer, tagEndBuffer ); + SkipWhiteSpace(tagBuffer, tagEndBuffer); // Find the attributes. unsigned int attributeIndex = 0u; - const char* nameBuffer = NULL; - const char* valueBuffer = NULL; - Length nameLength = 0u; - Length valueLength = 0u; + const char* nameBuffer = NULL; + const char* valueBuffer = NULL; + Length nameLength = 0u; + Length valueLength = 0u; - bool addToNameValue = true; + bool addToNameValue = true; Length numberOfWhiteSpace = 0u; - for( ; tagBuffer < tagEndBuffer; ++tagBuffer ) + for(; tagBuffer < tagEndBuffer; ++tagBuffer) { const char character = *tagBuffer; - if( ( WHITE_SPACE >= character ) && !isQuotationOpen ) + if((WHITE_SPACE >= character) && !isQuotationOpen) { - if( NULL != valueBuffer ) + if(NULL != valueBuffer) { // Remove white spaces at the end of the value. valueLength -= numberOfWhiteSpace; } - if( ( NULL != nameBuffer ) && ( NULL != valueBuffer ) ) + if((NULL != nameBuffer) && (NULL != valueBuffer)) { // Every time a white space is found, a new attribute is created and stored in the attributes vector. - Attribute& attribute = *( tag.attributes.Begin() + attributeIndex ); + Attribute& attribute = *(tag.attributes.Begin() + attributeIndex); ++attributeIndex; - attribute.nameBuffer = nameBuffer; + attribute.nameBuffer = nameBuffer; attribute.valueBuffer = valueBuffer; - attribute.nameLength = nameLength; + attribute.nameLength = nameLength; attribute.valueLength = valueLength; - nameBuffer = NULL; + nameBuffer = NULL; valueBuffer = NULL; - nameLength = 0u; + nameLength = 0u; valueLength = 0u; addToNameValue = true; // next read characters will be added to the name. } } - else if( EQUAL == character ) // '=' + else if(EQUAL == character) // '=' { addToNameValue = false; // next read characters will be added to the value. - SkipWhiteSpace( tagBuffer, tagEndBuffer ); + SkipWhiteSpace(tagBuffer, tagEndBuffer); } - else if( QUOTATION_MARK == character ) // '\'' + else if(QUOTATION_MARK == character) // '\'' { // Do not add quotation marks to neither name nor value. isQuotationOpen = !isQuotationOpen; - if( isQuotationOpen ) + if(isQuotationOpen) { ++tagBuffer; - SkipWhiteSpace( tagBuffer, tagEndBuffer ); + SkipWhiteSpace(tagBuffer, tagEndBuffer); --tagBuffer; } } else { // Adds characters to the name or the value. - if( addToNameValue ) + if(addToNameValue) { - if( NULL == nameBuffer ) + if(NULL == nameBuffer) { nameBuffer = tagBuffer; } @@ -263,9 +260,9 @@ void ParseAttributes( Tag& tag ) } else { - if( isQuotationOpen ) + if(isQuotationOpen) { - if( WHITE_SPACE >= character ) + if(WHITE_SPACE >= character) { ++numberOfWhiteSpace; } @@ -274,7 +271,7 @@ void ParseAttributes( Tag& tag ) numberOfWhiteSpace = 0u; } } - if( NULL == valueBuffer ) + if(NULL == valueBuffer) { valueBuffer = tagBuffer; } @@ -283,26 +280,26 @@ void ParseAttributes( Tag& tag ) } } - if( NULL != valueBuffer ) + if(NULL != valueBuffer) { // Remove white spaces at the end of the value. valueLength -= numberOfWhiteSpace; } - if( ( NULL != nameBuffer ) && ( NULL != valueBuffer ) ) + if((NULL != nameBuffer) && (NULL != valueBuffer)) { // Checks if the last attribute needs to be added. - Attribute& attribute = *( tag.attributes.Begin() + attributeIndex ); + Attribute& attribute = *(tag.attributes.Begin() + attributeIndex); ++attributeIndex; - attribute.nameBuffer = nameBuffer; + attribute.nameBuffer = nameBuffer; attribute.valueBuffer = valueBuffer; - attribute.nameLength = nameLength; + attribute.nameLength = nameLength; attribute.valueLength = valueLength; } // Resize the vector of attributes. - tag.attributes.Resize( attributeIndex ); + tag.attributes.Resize(attributeIndex); } /** @@ -314,37 +311,37 @@ void ParseAttributes( Tag& tag ) * * @return @e true if the iterator @e it is pointing a mark-up tag. Otherwise @e false. */ -bool IsTag( const char*& markupStringBuffer, - const char* const markupStringEndBuffer, - Tag& tag ) +bool IsTag(const char*& markupStringBuffer, + const char* const markupStringEndBuffer, + Tag& tag) { - bool isTag = false; - bool isQuotationOpen = false; - bool attributesFound = false; - tag.isEndTag = false; + bool isTag = false; + bool isQuotationOpen = false; + bool attributesFound = false; + tag.isEndTag = false; bool isPreviousLessThan = false; - bool isPreviousSlash = false; + bool isPreviousSlash = false; const char character = *markupStringBuffer; - if( LESS_THAN == character ) // '<' + if(LESS_THAN == character) // '<' { - tag.buffer = NULL; - tag.length = 0u; + tag.buffer = NULL; + tag.length = 0u; isPreviousLessThan = true; // if the iterator is pointing to a '<' character, then check if it's a mark-up tag is needed. ++markupStringBuffer; - if( markupStringBuffer < markupStringEndBuffer ) + if(markupStringBuffer < markupStringEndBuffer) { - SkipWhiteSpace( markupStringBuffer, markupStringEndBuffer ); + SkipWhiteSpace(markupStringBuffer, markupStringEndBuffer); - for( ; ( !isTag ) && ( markupStringBuffer < markupStringEndBuffer ); ++markupStringBuffer ) + for(; (!isTag) && (markupStringBuffer < markupStringEndBuffer); ++markupStringBuffer) { const char character = *markupStringBuffer; - if( !isQuotationOpen && ( SLASH == character ) ) // '/' + if(!isQuotationOpen && (SLASH == character)) // '/' { - if (isPreviousLessThan) + if(isPreviousLessThan) { tag.isEndTag = true; } @@ -355,36 +352,36 @@ bool IsTag( const char*& markupStringBuffer, } isPreviousLessThan = false; - if( ( markupStringBuffer + 1u < markupStringEndBuffer ) && ( WHITE_SPACE >= *( markupStringBuffer + 1u ) ) ) + if((markupStringBuffer + 1u < markupStringEndBuffer) && (WHITE_SPACE >= *(markupStringBuffer + 1u))) { ++markupStringBuffer; - SkipWhiteSpace( markupStringBuffer, markupStringEndBuffer ); + SkipWhiteSpace(markupStringBuffer, markupStringEndBuffer); --markupStringBuffer; } } - else if( GREATER_THAN == character ) // '>' + else if(GREATER_THAN == character) // '>' { isTag = true; - if (isPreviousSlash) + if(isPreviousSlash) { tag.isEndTag = true; } - isPreviousSlash = false; + isPreviousSlash = false; isPreviousLessThan = false; } - else if( QUOTATION_MARK == character ) + else if(QUOTATION_MARK == character) { isQuotationOpen = !isQuotationOpen; ++tag.length; - isPreviousSlash = false; + isPreviousSlash = false; isPreviousLessThan = false; } - else if( WHITE_SPACE >= character ) // ' ' + else if(WHITE_SPACE >= character) // ' ' { // If the tag contains white spaces then it may have attributes. - if( !isQuotationOpen ) + if(!isQuotationOpen) { attributesFound = true; } @@ -392,7 +389,7 @@ bool IsTag( const char*& markupStringBuffer, } else { - if( NULL == tag.buffer ) + if(NULL == tag.buffer) { tag.buffer = markupStringBuffer; } @@ -400,16 +397,16 @@ bool IsTag( const char*& markupStringBuffer, // If it's not any of the 'special' characters then just add it to the tag string. ++tag.length; - isPreviousSlash = false; + isPreviousSlash = false; isPreviousLessThan = false; } } } // If the tag string has white spaces, then parse the attributes is needed. - if( attributesFound ) + if(attributesFound) { - ParseAttributes( tag ); + ParseAttributes(tag); } } @@ -424,28 +421,28 @@ bool IsTag( const char*& markupStringBuffer, * * @return Length of markupText in case of XHTML entity otherwise return 0. */ -unsigned int GetXHTMLEntityLength( const char*& markupStringBuffer, - const char* const markupStringEndBuffer ) +unsigned int GetXHTMLEntityLength(const char*& markupStringBuffer, + const char* const markupStringEndBuffer) { char character = *markupStringBuffer; - if( AMPERSAND == character ) // '&' + if(AMPERSAND == character) // '&' { // if the iterator is pointing to a '&' character, then check for ';' to find end to XHTML entity. ++markupStringBuffer; - if( markupStringBuffer < markupStringEndBuffer ) + if(markupStringBuffer < markupStringEndBuffer) { unsigned int len = 1u; - for( ; markupStringBuffer < markupStringEndBuffer ; ++markupStringBuffer ) + for(; markupStringBuffer < markupStringEndBuffer; ++markupStringBuffer) { character = *markupStringBuffer; ++len; - if( SEMI_COLON == character ) // ';' + if(SEMI_COLON == character) // ';' { // found end of XHTML entity ++markupStringBuffer; return len; } - else if( ( AMPERSAND == character ) || ( BACK_SLASH == character ) || ( LESS_THAN == character )) + else if((AMPERSAND == character) || (BACK_SLASH == character) || (LESS_THAN == character)) { return 0; } @@ -463,36 +460,36 @@ unsigned int GetXHTMLEntityLength( const char*& markupStringBuffer, * * @return true if string is successfully parsed otherwise false */ -bool XHTMLNumericEntityToUtf8 ( const char* markupText, char* utf8 ) +bool XHTMLNumericEntityToUtf8(const char* markupText, char* utf8) { bool result = false; - if( NULL != markupText ) + if(NULL != markupText) { bool isHex = false; // check if hex or decimal entity - if( ( CHAR_ARRAY_END != *markupText ) && ( HEX_CODE == *markupText ) ) + if((CHAR_ARRAY_END != *markupText) && (HEX_CODE == *markupText)) { isHex = true; ++markupText; } - char* end = NULL; - unsigned long l = strtoul( markupText, &end, ( isHex ? 16 : 10 ) ); // l contains UTF-32 code in case of correct XHTML entity + char* end = NULL; + unsigned long l = strtoul(markupText, &end, (isHex ? 16 : 10)); // l contains UTF-32 code in case of correct XHTML entity // check for valid XHTML numeric entities (between '#' or "#x" and ';') - if( ( l > 0 ) && ( l < ULONG_MAX ) && ( *end == SEMI_COLON ) ) // in case wrong XHTML entity is set eg. "abcdefs;" in that case *end will be 'a' + if((l > 0) && (l < ULONG_MAX) && (*end == SEMI_COLON)) // in case wrong XHTML entity is set eg. "abcdefs;" in that case *end will be 'a' { /* characters XML 1.1 permits */ - if( ( ( XHTML_DECIMAL_ENTITY_RANGE[0] < l ) && ( l <= XHTML_DECIMAL_ENTITY_RANGE[1] ) ) || - ( ( XHTML_DECIMAL_ENTITY_RANGE[2] <= l ) && ( l <= XHTML_DECIMAL_ENTITY_RANGE[3] ) ) || - ( ( XHTML_DECIMAL_ENTITY_RANGE[4] <= l ) && ( l <= XHTML_DECIMAL_ENTITY_RANGE[5] ) ) ) + if(((XHTML_DECIMAL_ENTITY_RANGE[0] < l) && (l <= XHTML_DECIMAL_ENTITY_RANGE[1])) || + ((XHTML_DECIMAL_ENTITY_RANGE[2] <= l) && (l <= XHTML_DECIMAL_ENTITY_RANGE[3])) || + ((XHTML_DECIMAL_ENTITY_RANGE[4] <= l) && (l <= XHTML_DECIMAL_ENTITY_RANGE[5]))) { // Convert UTF32 code to UTF8 - Utf32ToUtf8( reinterpret_cast( &l ), 1, reinterpret_cast( utf8 ) ); + Utf32ToUtf8(reinterpret_cast(&l), 1, reinterpret_cast(utf8)); result = true; - } + } } } return result; @@ -511,17 +508,17 @@ bool XHTMLNumericEntityToUtf8 ( const char* markupText, char* utf8 ) * @param[in/out] tagReference The tagReference we should increment/decrement * @param[in] parameterSettingFunction This function will be called to set run specific parameters */ -template +template void ProcessTagForRun( - Vector& runsContainer, - StyleStack& styleStack, - const Tag& tag, - const CharacterIndex characterIndex, - StyleStack::RunIndex& runIndex, - int& tagReference, - std::function parameterSettingFunction) + Vector& runsContainer, + StyleStack& styleStack, + const Tag& tag, + const CharacterIndex characterIndex, + StyleStack::RunIndex& runIndex, + int& tagReference, + std::function parameterSettingFunction) { - if( !tag.isEndTag ) + if(!tag.isEndTag) { // Create a new run. RunType run; @@ -545,10 +542,10 @@ void ProcessTagForRun( } else { - if( tagReference > 0 ) + if(tagReference > 0) { // Pop the top of the stack and set the number of characters of the run. - RunType& run = *( runsContainer.Begin() + styleStack.Pop() ); + RunType& run = *(runsContainer.Begin() + styleStack.Pop()); run.characterRun.numberOfCharacters = characterIndex - run.characterRun.characterIndex; --tagReference; } @@ -563,11 +560,11 @@ void ProcessTagForRun( * @param[in/out] characterIndex The current character index */ void ProcessItemTag( - MarkupProcessData& markupProcessData, - const Tag tag, - CharacterIndex& characterIndex) + MarkupProcessData& markupProcessData, + const Tag tag, + CharacterIndex& characterIndex) { - if (tag.isEndTag) + if(tag.isEndTag) { // Create an embedded item instance. EmbeddedItem item; @@ -577,7 +574,7 @@ void ProcessItemTag( markupProcessData.items.PushBack(item); // Insert white space character that will be replaced by the item. - markupProcessData.markupProcessedText.append( 1u, WHITE_SPACE ); + markupProcessData.markupProcessedText.append(1u, WHITE_SPACE); ++characterIndex; } } @@ -591,14 +588,14 @@ void ProcessItemTag( */ void ResizeModelVectors(MarkupProcessData& markupProcessData, const StyleStack::RunIndex fontRunIndex, const StyleStack::RunIndex colorRunIndex) { - markupProcessData.fontRuns.Resize( fontRunIndex ); - markupProcessData.colorRuns.Resize( colorRunIndex ); + markupProcessData.fontRuns.Resize(fontRunIndex); + markupProcessData.colorRuns.Resize(colorRunIndex); #ifdef DEBUG_ENABLED - for( unsigned int i=0; i or & special character. - const unsigned char nextCharacter = *( markupStringBuffer + 1u ); - if( ( LESS_THAN == nextCharacter ) || ( GREATER_THAN == nextCharacter ) || ( AMPERSAND == nextCharacter ) ) + const unsigned char nextCharacter = *(markupStringBuffer + 1u); + if((LESS_THAN == nextCharacter) || (GREATER_THAN == nextCharacter) || (AMPERSAND == nextCharacter)) { character = nextCharacter; ++markupStringBuffer; - count = GetUtf8Length( character ); + count = GetUtf8Length(character); markupBuffer = markupStringBuffer; } } - else // checking if contains XHTML entity or not + else // checking if contains XHTML entity or not { - const unsigned int len = GetXHTMLEntityLength( markupStringBuffer, markupStringEndBuffer); + const unsigned int len = GetXHTMLEntityLength(markupStringBuffer, markupStringEndBuffer); // Parse markupStringTxt if it contains XHTML Entity between '&' and ';' - if( len > 0 ) + if(len > 0) { char* entityCode = NULL; - bool result = false; - count = 0; + bool result = false; + count = 0; // Checking if XHTML Numeric Entity - if( HASH == *( markupBuffer + 1u ) ) + if(HASH == *(markupBuffer + 1u)) { entityCode = &utf8[0]; // markupBuffer is currently pointing to '&'. By adding 2u to markupBuffer it will point to numeric string by skipping "&#' - result = XHTMLNumericEntityToUtf8( ( markupBuffer + 2u ), entityCode ); + result = XHTMLNumericEntityToUtf8((markupBuffer + 2u), entityCode); } - else // Checking if XHTML Named Entity + else // Checking if XHTML Named Entity { - entityCode = const_cast ( NamedEntityToUtf8( markupBuffer, len ) ); - result = ( entityCode != NULL ); + entityCode = const_cast(NamedEntityToUtf8(markupBuffer, len)); + result = (entityCode != NULL); } - if ( result ) + if(result) { markupBuffer = entityCode; //utf8 text assigned to markupBuffer - character = markupBuffer[0]; + character = markupBuffer[0]; } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Not valid XHTML entity : (%.*s) \n", len, markupBuffer ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Not valid XHTML entity : (%.*s) \n", len, markupBuffer); markupBuffer = NULL; } } - else // in case string conatins Start of XHTML Entity('&') but not its end character(';') + else // in case string conatins Start of XHTML Entity('&') but not its end character(';') { - if( character == AMPERSAND ) + if(character == AMPERSAND) { markupBuffer = NULL; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Not Well formed XHTML content \n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Not Well formed XHTML content \n"); } } } - if( markupBuffer != NULL ) + if(markupBuffer != NULL) { - const unsigned char numberOfBytes = GetUtf8Length( character ); - markupProcessData.markupProcessedText.push_back( character ); + const unsigned char numberOfBytes = GetUtf8Length(character); + markupProcessData.markupProcessedText.push_back(character); - for( unsigned char i = 1u; i < numberOfBytes; ++i ) + for(unsigned char i = 1u; i < numberOfBytes; ++i) { ++markupBuffer; - markupProcessData.markupProcessedText.push_back( *markupBuffer ); + markupProcessData.markupProcessedText.push_back(*markupBuffer); } ++characterIndex; @@ -697,102 +694,96 @@ void ProcessMarkupStringBuffer( } // namespace -void ProcessMarkupString( const std::string& markupString, MarkupProcessData& markupProcessData ) +void ProcessMarkupString(const std::string& markupString, MarkupProcessData& markupProcessData) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "markupString: %s\n", markupString.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "markupString: %s\n", markupString.c_str()); // Reserve space for the plain text. const Length markupStringSize = markupString.size(); - markupProcessData.markupProcessedText.reserve( markupStringSize ); + markupProcessData.markupProcessedText.reserve(markupStringSize); // Stores a struct with the index to the first character of the run, the type of run and its parameters. StyleStack styleStack; // Points the next free position in the vector of runs. StyleStack::RunIndex colorRunIndex = 0u; - StyleStack::RunIndex fontRunIndex = 0u; + StyleStack::RunIndex fontRunIndex = 0u; // check tag reference int colorTagReference = 0u; - int fontTagReference = 0u; - int iTagReference = 0u; - int bTagReference = 0u; + int fontTagReference = 0u; + int iTagReference = 0u; + int bTagReference = 0u; // Give an initial default value to the model's vectors. - markupProcessData.colorRuns.Reserve( DEFAULT_VECTOR_SIZE ); - markupProcessData.fontRuns.Reserve( DEFAULT_VECTOR_SIZE ); + markupProcessData.colorRuns.Reserve(DEFAULT_VECTOR_SIZE); + markupProcessData.fontRuns.Reserve(DEFAULT_VECTOR_SIZE); // Get the mark-up string buffer. - const char* markupStringBuffer = markupString.c_str(); + const char* markupStringBuffer = markupString.c_str(); const char* const markupStringEndBuffer = markupStringBuffer + markupStringSize; - Tag tag; + Tag tag; CharacterIndex characterIndex = 0u; - for( ; markupStringBuffer < markupStringEndBuffer; ) + for(; markupStringBuffer < markupStringEndBuffer;) { tag.attributes.Clear(); - if( IsTag( markupStringBuffer, - markupStringEndBuffer, - tag ) ) + if(IsTag(markupStringBuffer, + markupStringEndBuffer, + tag)) { - if( TokenComparison( XHTML_COLOR_TAG, tag.buffer, tag.length ) ) + if(TokenComparison(XHTML_COLOR_TAG, tag.buffer, tag.length)) { ProcessTagForRun( - markupProcessData.colorRuns, styleStack, tag, characterIndex, colorRunIndex, colorTagReference, - [] (const Tag& tag, ColorRun& run) { ProcessColorTag( tag, run ); }); + markupProcessData.colorRuns, styleStack, tag, characterIndex, colorRunIndex, colorTagReference, [](const Tag& tag, ColorRun& run) { ProcessColorTag(tag, run); }); } // - else if( TokenComparison( XHTML_I_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_I_TAG, tag.buffer, tag.length)) { ProcessTagForRun( - markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, iTagReference, - [] (const Tag&, FontDescriptionRun& fontRun) - { - fontRun.slant = TextAbstraction::FontSlant::ITALIC; - fontRun.slantDefined = true; - }); + markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, iTagReference, [](const Tag&, FontDescriptionRun& fontRun) { + fontRun.slant = TextAbstraction::FontSlant::ITALIC; + fontRun.slantDefined = true; + }); } // - else if( TokenComparison( XHTML_U_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_U_TAG, tag.buffer, tag.length)) { // TODO: If !tag.isEndTag, then create a new underline run. // else Pop the top of the stack and set the number of characters of the run. } // - else if( TokenComparison( XHTML_B_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_B_TAG, tag.buffer, tag.length)) { ProcessTagForRun( - markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, bTagReference, - [] (const Tag&, FontDescriptionRun& fontRun) - { - fontRun.weight = TextAbstraction::FontWeight::BOLD; - fontRun.weightDefined = true; - }); + markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, bTagReference, [](const Tag&, FontDescriptionRun& fontRun) { + fontRun.weight = TextAbstraction::FontWeight::BOLD; + fontRun.weightDefined = true; + }); } // - else if( TokenComparison( XHTML_FONT_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_FONT_TAG, tag.buffer, tag.length)) { ProcessTagForRun( - markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, fontTagReference, - [] (const Tag& tag, FontDescriptionRun& fontRun) { ProcessFontTag( tag, fontRun ); }); + markupProcessData.fontRuns, styleStack, tag, characterIndex, fontRunIndex, fontTagReference, [](const Tag& tag, FontDescriptionRun& fontRun) { ProcessFontTag(tag, fontRun); }); } // - else if( TokenComparison( XHTML_SHADOW_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_SHADOW_TAG, tag.buffer, tag.length)) { // TODO: If !tag.isEndTag, then create a new shadow run. // else Pop the top of the stack and set the number of characters of the run. } // - else if( TokenComparison( XHTML_GLOW_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_GLOW_TAG, tag.buffer, tag.length)) { // TODO: If !tag.isEndTag, then create a new glow run. // else Pop the top of the stack and set the number of characters of the run. } // - else if( TokenComparison( XHTML_OUTLINE_TAG, tag.buffer, tag.length ) ) + else if(TokenComparison(XHTML_OUTLINE_TAG, tag.buffer, tag.length)) { // TODO: If !tag.isEndTag, then create a new outline run. // else Pop the top of the stack and set the number of characters of the run. } // - else if (TokenComparison(XHTML_ITEM_TAG, tag.buffer, tag.length)) + else if(TokenComparison(XHTML_ITEM_TAG, tag.buffer, tag.length)) { ProcessItemTag(markupProcessData, tag, characterIndex); } - } // end if( IsTag() ) - else if( markupStringBuffer < markupStringEndBuffer ) + } // end if( IsTag() ) + else if(markupStringBuffer < markupStringEndBuffer) { ProcessMarkupStringBuffer(markupProcessData, markupStringBuffer, markupStringEndBuffer, characterIndex); } diff --git a/dali-toolkit/internal/text/multi-language-helper-functions.cpp b/dali-toolkit/internal/text/multi-language-helper-functions.cpp index 3fad598..f53bfef 100644 --- a/dali-toolkit/internal/text/multi-language-helper-functions.cpp +++ b/dali-toolkit/internal/text/multi-language-helper-functions.cpp @@ -23,20 +23,17 @@ namespace Dali { - namespace Toolkit { - namespace Text { - -void MergeFontDescriptions( const Vector& fontDescriptions, - const TextAbstraction::FontDescription& defaultFontDescription, - TextAbstraction::PointSize26Dot6 defaultPointSize, - CharacterIndex characterIndex, - TextAbstraction::FontDescription& fontDescription, - TextAbstraction::PointSize26Dot6& fontPointSize, - bool& isDefaultFont ) +void MergeFontDescriptions(const Vector& fontDescriptions, + const TextAbstraction::FontDescription& defaultFontDescription, + TextAbstraction::PointSize26Dot6 defaultPointSize, + CharacterIndex characterIndex, + TextAbstraction::FontDescription& fontDescription, + TextAbstraction::PointSize26Dot6& fontPointSize, + bool& isDefaultFont) { // Initialize with the default font's point size. fontPointSize = defaultPointSize; @@ -51,115 +48,115 @@ void MergeFontDescriptions( const Vector& fontDescriptions, Length familyIndex = 0u; Length weightIndex = 0u; - Length widthIndex = 0u; - Length slantIndex = 0u; - Length sizeIndex = 0u; + Length widthIndex = 0u; + Length slantIndex = 0u; + Length sizeIndex = 0u; bool familyOverriden = false; bool weightOverriden = false; - bool widthOverriden = false; - bool slantOverriden = false; - bool sizeOverriden = false; + bool widthOverriden = false; + bool slantOverriden = false; + bool sizeOverriden = false; // Traverse all the font descriptions. const FontDescriptionRun* const fontDescriptionsBuffer = fontDescriptions.Begin(); - for( Vector::ConstIterator it = fontDescriptionsBuffer, - endIt = fontDescriptions.End(); - it != endIt; - ++it, ++runIndex ) + for(Vector::ConstIterator it = fontDescriptionsBuffer, + endIt = fontDescriptions.End(); + it != endIt; + ++it, ++runIndex) { // Check whether the character's font is modified by the current font description. const FontDescriptionRun& fontRun = *it; - if( ( characterIndex >= fontRun.characterRun.characterIndex ) && - ( characterIndex < fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters ) ) + if((characterIndex >= fontRun.characterRun.characterIndex) && + (characterIndex < fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters)) { - if( fontRun.familyDefined ) + if(fontRun.familyDefined) { - isDefaultFont = false; + isDefaultFont = false; familyOverriden = true; - familyIndex = runIndex; + familyIndex = runIndex; } - if( fontRun.weightDefined ) + if(fontRun.weightDefined) { - isDefaultFont = false; + isDefaultFont = false; weightOverriden = true; - weightIndex = runIndex; + weightIndex = runIndex; } - if( fontRun.widthDefined ) + if(fontRun.widthDefined) { - isDefaultFont = false; + isDefaultFont = false; widthOverriden = true; - widthIndex = runIndex; + widthIndex = runIndex; } - if( fontRun.slantDefined ) + if(fontRun.slantDefined) { - isDefaultFont = false; + isDefaultFont = false; slantOverriden = true; - slantIndex = runIndex; + slantIndex = runIndex; } - if( fontRun.sizeDefined ) + if(fontRun.sizeDefined) { isDefaultFont = false; sizeOverriden = true; - sizeIndex = runIndex; + sizeIndex = runIndex; } } } // Get the font's description if is not the default font. - if( !isDefaultFont ) + if(!isDefaultFont) { - if( familyOverriden ) + if(familyOverriden) { - const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + familyIndex ); - fontDescription.family = std::string( fontRun.familyName, fontRun.familyLength ); + const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + familyIndex); + fontDescription.family = std::string(fontRun.familyName, fontRun.familyLength); } - if( weightOverriden ) + if(weightOverriden) { - const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + weightIndex ); - fontDescription.weight = fontRun.weight; + const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + weightIndex); + fontDescription.weight = fontRun.weight; } - if( widthOverriden ) + if(widthOverriden) { - const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + widthIndex ); - fontDescription.width = fontRun.width; + const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + widthIndex); + fontDescription.width = fontRun.width; } - if( slantOverriden ) + if(slantOverriden) { - const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + slantIndex ); - fontDescription.slant = fontRun.slant; + const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + slantIndex); + fontDescription.slant = fontRun.slant; } - if( sizeOverriden ) + if(sizeOverriden) { - const FontDescriptionRun& fontRun = *( fontDescriptionsBuffer + sizeIndex ); - fontPointSize = fontRun.size; + const FontDescriptionRun& fontRun = *(fontDescriptionsBuffer + sizeIndex); + fontPointSize = fontRun.size; } } } -Script GetScript( Length index, - Vector::ConstIterator& scriptRunIt, - const Vector::ConstIterator& scriptRunEndIt ) +Script GetScript(Length index, + Vector::ConstIterator& scriptRunIt, + const Vector::ConstIterator& scriptRunEndIt) { Script script = TextAbstraction::UNKNOWN; - while( scriptRunIt != scriptRunEndIt ) + while(scriptRunIt != scriptRunEndIt) { const ScriptRun& scriptRun = *scriptRunIt; - if( index >= scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters ) + if(index >= scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters) { ++scriptRunIt; } - else if( index >= scriptRun.characterRun.characterIndex ) + else if(index >= scriptRun.characterRun.characterIndex) { script = scriptRun.script; - if( index + 1u == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters ) + if(index + 1u == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters) { // All the characters of the current run have been traversed. Get the next one for the next iteration. ++scriptRunIt; diff --git a/dali-toolkit/internal/text/multi-language-support-impl.cpp b/dali-toolkit/internal/text/multi-language-support-impl.cpp old mode 100755 new mode 100644 index 99a969c..a0e6ae5 --- a/dali-toolkit/internal/text/multi-language-support-impl.cpp +++ b/dali-toolkit/internal/text/multi-language-support-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,19 +19,17 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - namespace { #if defined(DEBUG_ENABLED) @@ -39,22 +37,20 @@ Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_MULT #endif const Dali::Toolkit::Text::Character UTF32_A = 0x0041; -} +} // namespace namespace Text { - namespace Internal { - -bool ValidateFontsPerScript::IsValidFont( FontId fontId ) const +bool ValidateFontsPerScript::IsValidFont(FontId fontId) const { - for( Vector::ConstIterator it = mValidFonts.Begin(), - endIt = mValidFonts.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = mValidFonts.Begin(), + endIt = mValidFonts.End(); + it != endIt; + ++it) { - if( fontId == *it ) + if(fontId == *it) { return true; } @@ -63,22 +59,22 @@ bool ValidateFontsPerScript::IsValidFont( FontId fontId ) const return false; } -FontId DefaultFonts::FindFont( TextAbstraction::FontClient& fontClient, - const TextAbstraction::FontDescription& description, - PointSize26Dot6 size ) const +FontId DefaultFonts::FindFont(TextAbstraction::FontClient& fontClient, + const TextAbstraction::FontDescription& description, + PointSize26Dot6 size) const { - for( std::vector::const_iterator it = mFonts.begin(), - endIt = mFonts.end(); - it != endIt; - ++it ) + for(std::vector::const_iterator it = mFonts.begin(), + endIt = mFonts.end(); + it != endIt; + ++it) { const CacheItem& item = *it; - if( ( ( TextAbstraction::FontWeight::NONE == description.weight ) || ( description.weight == item.description.weight ) ) && - ( ( TextAbstraction::FontWidth::NONE == description.width ) || ( description.width == item.description.width ) ) && - ( ( TextAbstraction::FontSlant::NONE == description.slant ) || ( description.slant == item.description.slant ) ) && - ( size == fontClient.GetPointSize( item.fontId ) ) && - ( description.family.empty() || ( description.family == item.description.family ) ) ) + if(((TextAbstraction::FontWeight::NONE == description.weight) || (description.weight == item.description.weight)) && + ((TextAbstraction::FontWidth::NONE == description.width) || (description.width == item.description.width)) && + ((TextAbstraction::FontSlant::NONE == description.slant) || (description.slant == item.description.slant)) && + (size == fontClient.GetPointSize(item.fontId)) && + (description.family.empty() || (description.family == item.description.family))) { return item.fontId; } @@ -87,12 +83,12 @@ FontId DefaultFonts::FindFont( TextAbstraction::FontClient& fontClient, return 0u; } -void DefaultFonts::Cache( const TextAbstraction::FontDescription& description, FontId fontId ) +void DefaultFonts::Cache(const TextAbstraction::FontDescription& description, FontId fontId) { CacheItem item; item.description = description; - item.fontId = fontId; - mFonts.push_back( item ); + item.fontId = fontId; + mFonts.push_back(item); } MultilanguageSupport::MultilanguageSupport() @@ -101,29 +97,29 @@ MultilanguageSupport::MultilanguageSupport() { // Initializes the default font cache to zero (invalid font). // Reserves space to cache the default fonts and access them with the script as an index. - mDefaultFontPerScriptCache.Resize( TextAbstraction::UNKNOWN + 1, NULL ); + mDefaultFontPerScriptCache.Resize(TextAbstraction::UNKNOWN + 1, NULL); // Initializes the valid fonts cache to NULL (no valid fonts). // Reserves space to cache the valid fonts and access them with the script as an index. - mValidFontsPerScriptCache.Resize( TextAbstraction::UNKNOWN + 1, NULL ); + mValidFontsPerScriptCache.Resize(TextAbstraction::UNKNOWN + 1, NULL); } MultilanguageSupport::~MultilanguageSupport() { // Destroy the default font per script cache. - for( Vector::Iterator it = mDefaultFontPerScriptCache.Begin(), - endIt = mDefaultFontPerScriptCache.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = mDefaultFontPerScriptCache.Begin(), + endIt = mDefaultFontPerScriptCache.End(); + it != endIt; + ++it) { delete *it; } // Destroy the valid fonts per script cache. - for( Vector::Iterator it = mValidFontsPerScriptCache.Begin(), - endIt = mValidFontsPerScriptCache.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = mValidFontsPerScriptCache.Begin(), + endIt = mValidFontsPerScriptCache.End(); + it != endIt; + ++it) { delete *it; } @@ -133,33 +129,33 @@ Text::MultilanguageSupport MultilanguageSupport::Get() { Text::MultilanguageSupport multilanguageSupportHandle; - 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( Text::MultilanguageSupport ) ); - if( handle ) + Dali::BaseHandle handle = service.GetSingleton(typeid(Text::MultilanguageSupport)); + if(handle) { // If so, downcast the handle - MultilanguageSupport* impl = dynamic_cast< Internal::MultilanguageSupport* >( handle.GetObjectPtr() ); - multilanguageSupportHandle = Text::MultilanguageSupport( impl ); + MultilanguageSupport* impl = dynamic_cast(handle.GetObjectPtr()); + multilanguageSupportHandle = Text::MultilanguageSupport(impl); } else // create and register the object { - multilanguageSupportHandle = Text::MultilanguageSupport( new MultilanguageSupport ); - service.Register( typeid( multilanguageSupportHandle ), multilanguageSupportHandle ); + multilanguageSupportHandle = Text::MultilanguageSupport(new MultilanguageSupport); + service.Register(typeid(multilanguageSupportHandle), multilanguageSupportHandle); } } return multilanguageSupportHandle; } -void MultilanguageSupport::SetScripts( const Vector& text, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& scripts ) +void MultilanguageSupport::SetScripts(const Vector& text, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& scripts) { - if( 0u == numberOfCharacters ) + if(0u == numberOfCharacters) { // Nothing to do if there are no characters. return; @@ -167,15 +163,15 @@ void MultilanguageSupport::SetScripts( const Vector& text, // Find the first index where to insert the script. ScriptRunIndex scriptIndex = 0u; - if( 0u != startIndex ) + if(0u != startIndex) { - for( Vector::ConstIterator it = scripts.Begin(), - endIt = scripts.End(); - it != endIt; - ++it, ++scriptIndex ) + for(Vector::ConstIterator it = scripts.Begin(), + endIt = scripts.End(); + it != endIt; + ++it, ++scriptIndex) { const ScriptRun& run = *it; - if( startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters ) + if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters) { // Run found. break; @@ -185,12 +181,12 @@ void MultilanguageSupport::SetScripts( const Vector& text, // Stores the current script run. ScriptRun currentScriptRun; - currentScriptRun.characterRun.characterIndex = startIndex; + currentScriptRun.characterRun.characterIndex = startIndex; currentScriptRun.characterRun.numberOfCharacters = 0u; - currentScriptRun.script = TextAbstraction::UNKNOWN; + currentScriptRun.script = TextAbstraction::UNKNOWN; // Reserve some space to reduce the number of reallocations. - scripts.Reserve( text.Count() << 2u ); + scripts.Reserve(text.Count() << 2u); // Whether the first valid script needs to be set. bool isFirstScriptToBeSet = true; @@ -209,12 +205,12 @@ void MultilanguageSupport::SetScripts( const Vector& text, // Traverse all characters and set the scripts. const Length lastCharacter = startIndex + numberOfCharacters; - for( Length index = startIndex; index < lastCharacter; ++index ) + for(Length index = startIndex; index < lastCharacter; ++index) { - Character character = *( textBuffer + index ); + Character character = *(textBuffer + index); // Get the script of the character. - Script script = TextAbstraction::GetCharacterScript( character ); + Script script = TextAbstraction::GetCharacterScript(character); // Some characters (like white spaces) are valid for many scripts. The rules to set a script // for them are: @@ -226,29 +222,29 @@ void MultilanguageSupport::SetScripts( const Vector& text, // Skip those characters valid for many scripts like white spaces or '\n'. bool endOfText = index == lastCharacter; - while( !endOfText && - ( TextAbstraction::COMMON == script ) ) + while(!endOfText && + (TextAbstraction::COMMON == script)) { // Check if whether is right to left markup and Keeps true if the previous value was true. - currentScriptRun.isRightToLeft = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftMark( character ); + currentScriptRun.isRightToLeft = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftMark(character); - if( TextAbstraction::EMOJI == currentScriptRun.script ) + if(TextAbstraction::EMOJI == currentScriptRun.script) { // Emojis doesn't mix well with characters common to all scripts. Insert the emoji run. - scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun ); + scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun); ++scriptIndex; // Initialize the new one. - currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters; + currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters; currentScriptRun.characterRun.numberOfCharacters = 0u; - currentScriptRun.script = TextAbstraction::UNKNOWN; - numberOfAllScriptCharacters = 0u; + currentScriptRun.script = TextAbstraction::UNKNOWN; + numberOfAllScriptCharacters = 0u; } // Count all these characters to be added into a script. ++numberOfAllScriptCharacters; - if( TextAbstraction::IsNewParagraph( character ) ) + if(TextAbstraction::IsNewParagraph(character)) { // The character is a new paragraph. // To know when there is a new paragraph is needed because if there is a white space @@ -260,14 +256,14 @@ void MultilanguageSupport::SetScripts( const Vector& text, currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters; // Store the script run. - scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun ); + scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun); ++scriptIndex; // Initialize the new one. - currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters; + currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters; currentScriptRun.characterRun.numberOfCharacters = 0u; - currentScriptRun.script = TextAbstraction::UNKNOWN; - numberOfAllScriptCharacters = 0u; + currentScriptRun.script = TextAbstraction::UNKNOWN; + numberOfAllScriptCharacters = 0u; // Initialize whether is right to left direction currentScriptRun.isRightToLeft = false; } @@ -275,14 +271,14 @@ void MultilanguageSupport::SetScripts( const Vector& text, // Get the next character. ++index; endOfText = index == lastCharacter; - if( !endOfText ) + if(!endOfText) { - character = *( textBuffer + index ); - script = TextAbstraction::GetCharacterScript( character ); + character = *(textBuffer + index); + script = TextAbstraction::GetCharacterScript(character); } } // end while( !endOfText && ( TextAbstraction::COMMON == script ) ) - if( endOfText ) + if(endOfText) { // Last characters of the text are 'white spaces'. // There is nothing else to do. Just add the remaining characters to the last script after this bucle. @@ -290,62 +286,62 @@ void MultilanguageSupport::SetScripts( const Vector& text, } // Check if it is the first character of a paragraph. - if( isFirstScriptToBeSet && - ( TextAbstraction::UNKNOWN != script ) && - ( TextAbstraction::COMMON != script ) && - ( TextAbstraction::EMOJI != script ) ) + if(isFirstScriptToBeSet && + (TextAbstraction::UNKNOWN != script) && + (TextAbstraction::COMMON != script) && + (TextAbstraction::EMOJI != script)) { // Sets the direction of the first valid script. - isParagraphRTL = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftScript( script ); + isParagraphRTL = currentScriptRun.isRightToLeft || TextAbstraction::IsRightToLeftScript(script); isFirstScriptToBeSet = false; } - if( ( script != currentScriptRun.script ) && - ( TextAbstraction::COMMON != script ) ) + if((script != currentScriptRun.script) && + (TextAbstraction::COMMON != script)) { // Current run needs to be stored and a new one initialized. - if( ( isParagraphRTL == TextAbstraction::IsRightToLeftScript( currentScriptRun.script ) ) && - ( TextAbstraction::UNKNOWN != currentScriptRun.script ) ) + if((isParagraphRTL == TextAbstraction::IsRightToLeftScript(currentScriptRun.script)) && + (TextAbstraction::UNKNOWN != currentScriptRun.script)) { // Previous script has the same direction than the first script of the paragraph. // All the previously skipped characters need to be added to the previous script before it's stored. currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters; numberOfAllScriptCharacters = 0u; } - else if( ( TextAbstraction::IsRightToLeftScript( currentScriptRun.script ) == TextAbstraction::IsRightToLeftScript( script ) ) && - ( TextAbstraction::UNKNOWN != currentScriptRun.script ) ) + else if((TextAbstraction::IsRightToLeftScript(currentScriptRun.script) == TextAbstraction::IsRightToLeftScript(script)) && + (TextAbstraction::UNKNOWN != currentScriptRun.script)) { // Current script and previous one have the same direction. // All the previously skipped characters need to be added to the previous script before it's stored. currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters; numberOfAllScriptCharacters = 0u; } - else if( ( TextAbstraction::UNKNOWN == currentScriptRun.script ) && - ( TextAbstraction::EMOJI == script ) ) + else if((TextAbstraction::UNKNOWN == currentScriptRun.script) && + (TextAbstraction::EMOJI == script)) { currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters; numberOfAllScriptCharacters = 0u; } - if( 0u != currentScriptRun.characterRun.numberOfCharacters ) + if(0u != currentScriptRun.characterRun.numberOfCharacters) { // Store the script run. - scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun ); + scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun); ++scriptIndex; } // Initialize the new one. - currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters; + currentScriptRun.characterRun.characterIndex = currentScriptRun.characterRun.characterIndex + currentScriptRun.characterRun.numberOfCharacters; currentScriptRun.characterRun.numberOfCharacters = numberOfAllScriptCharacters + 1u; // Adds the white spaces which are at the begining of the script. - currentScriptRun.script = script; - numberOfAllScriptCharacters = 0u; + currentScriptRun.script = script; + numberOfAllScriptCharacters = 0u; // Check if whether is right to left script. - currentScriptRun.isRightToLeft = TextAbstraction::IsRightToLeftScript( currentScriptRun.script ); + currentScriptRun.isRightToLeft = TextAbstraction::IsRightToLeftScript(currentScriptRun.script); } else { - if( TextAbstraction::UNKNOWN != currentScriptRun.script ) + if(TextAbstraction::UNKNOWN != currentScriptRun.script) { // Adds white spaces between characters. currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters; @@ -360,60 +356,60 @@ void MultilanguageSupport::SetScripts( const Vector& text, // Add remaining characters into the last script. currentScriptRun.characterRun.numberOfCharacters += numberOfAllScriptCharacters; - if( 0u != currentScriptRun.characterRun.numberOfCharacters ) + if(0u != currentScriptRun.characterRun.numberOfCharacters) { // Store the last run. - scripts.Insert( scripts.Begin() + scriptIndex, currentScriptRun ); + scripts.Insert(scripts.Begin() + scriptIndex, currentScriptRun); ++scriptIndex; } - if( scriptIndex < scripts.Count() ) + if(scriptIndex < scripts.Count()) { // Update the indices of the next script runs. - const ScriptRun& run = *( scripts.Begin() + scriptIndex - 1u ); - CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters; + const ScriptRun& run = *(scripts.Begin() + scriptIndex - 1u); + CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters; - for( Vector::Iterator it = scripts.Begin() + scriptIndex, - endIt = scripts.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = scripts.Begin() + scriptIndex, + endIt = scripts.End(); + it != endIt; + ++it) { - ScriptRun& run = *it; + ScriptRun& run = *it; run.characterRun.characterIndex = nextCharacterIndex; nextCharacterIndex += run.characterRun.numberOfCharacters; } } } -void MultilanguageSupport::ValidateFonts( const Vector& text, - const Vector& scripts, - const Vector& fontDescriptions, - const TextAbstraction::FontDescription& defaultFontDescription, - TextAbstraction::PointSize26Dot6 defaultFontPointSize, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& fonts ) +void MultilanguageSupport::ValidateFonts(const Vector& text, + const Vector& scripts, + const Vector& fontDescriptions, + const TextAbstraction::FontDescription& defaultFontDescription, + TextAbstraction::PointSize26Dot6 defaultFontPointSize, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& fonts) { - DALI_LOG_INFO( gLogFilter, Debug::General, "-->MultilanguageSupport::ValidateFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "-->MultilanguageSupport::ValidateFonts\n"); - if( 0u == numberOfCharacters ) + if(0u == numberOfCharacters) { - DALI_LOG_INFO( gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n"); // Nothing to do if there are no characters. return; } // Find the first index where to insert the font run. FontRunIndex fontIndex = 0u; - if( 0u != startIndex ) + if(0u != startIndex) { - for( Vector::ConstIterator it = fonts.Begin(), - endIt = fonts.End(); - it != endIt; - ++it, ++fontIndex ) + for(Vector::ConstIterator it = fonts.Begin(), + endIt = fonts.End(); + it != endIt; + ++it, ++fontIndex) { const FontRun& run = *it; - if( startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters ) + if(startIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters) { // Run found. break; @@ -424,19 +420,19 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, // Traverse the characters and validate/set the fonts. // Get the caches. - DefaultFonts** defaultFontPerScriptCacheBuffer = mDefaultFontPerScriptCache.Begin(); - ValidateFontsPerScript** validFontsPerScriptCacheBuffer = mValidFontsPerScriptCache.Begin(); + DefaultFonts** defaultFontPerScriptCacheBuffer = mDefaultFontPerScriptCache.Begin(); + ValidateFontsPerScript** validFontsPerScriptCacheBuffer = mValidFontsPerScriptCache.Begin(); // Stores the validated font runs. - fonts.Reserve( fontDescriptions.Count() ); + fonts.Reserve(fontDescriptions.Count()); // Initializes a validated font run. FontRun currentFontRun; - currentFontRun.characterRun.characterIndex = startIndex; + currentFontRun.characterRun.characterIndex = startIndex; currentFontRun.characterRun.numberOfCharacters = 0u; - currentFontRun.fontId = 0u; - currentFontRun.isBoldRequired = false; - currentFontRun.isItalicRequired = false; + currentFontRun.fontId = 0u; + currentFontRun.isBoldRequired = false; + currentFontRun.isItalicRequired = false; // Get the font client. TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); @@ -444,51 +440,51 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, const Character* const textBuffer = text.Begin(); // Iterators of the script runs. - Vector::ConstIterator scriptRunIt = scripts.Begin(); - Vector::ConstIterator scriptRunEndIt = scripts.End(); - bool isNewParagraphCharacter = false; + Vector::ConstIterator scriptRunIt = scripts.Begin(); + Vector::ConstIterator scriptRunEndIt = scripts.End(); + bool isNewParagraphCharacter = false; bool isPreviousEmojiScript = false; CharacterIndex lastCharacter = startIndex + numberOfCharacters; - for( Length index = startIndex; index < lastCharacter; ++index ) + for(Length index = startIndex; index < lastCharacter; ++index) { // Get the current character. - const Character character = *( textBuffer + index ); - bool isItalicRequired = false; - bool isBoldRequired = false; + const Character character = *(textBuffer + index); + bool isItalicRequired = false; + bool isBoldRequired = false; // new description for current character TextAbstraction::FontDescription currentFontDescription; TextAbstraction::PointSize26Dot6 currentFontPointSize = defaultFontPointSize; - bool isDefaultFont = true; - MergeFontDescriptions( fontDescriptions, - defaultFontDescription, - defaultFontPointSize, - index, - currentFontDescription, - currentFontPointSize, - isDefaultFont ); + bool isDefaultFont = true; + MergeFontDescriptions(fontDescriptions, + defaultFontDescription, + defaultFontPointSize, + index, + currentFontDescription, + currentFontPointSize, + isDefaultFont); // Get the font for the current character. - FontId fontId = fontClient.GetFontId( currentFontDescription, currentFontPointSize ); + FontId fontId = fontClient.GetFontId(currentFontDescription, currentFontPointSize); // Get the script for the current character. - Script script = GetScript( index, - scriptRunIt, - scriptRunEndIt ); + Script script = GetScript(index, + scriptRunIt, + scriptRunEndIt); #ifdef DEBUG_ENABLED { Dali::TextAbstraction::FontDescription description; - fontClient.GetDescription( fontId, description ); - - DALI_LOG_INFO( gLogFilter, - Debug::Verbose, - " Initial font set\n Character : %x, Script : %s, Font : %s \n", - character, - Dali::TextAbstraction::ScriptName[script], - description.path.c_str() ); + fontClient.GetDescription(fontId, description); + + DALI_LOG_INFO(gLogFilter, + Debug::Verbose, + " Initial font set\n Character : %x, Script : %s, Font : %s \n", + character, + Dali::TextAbstraction::ScriptName[script], + description.path.c_str()); } #endif @@ -497,46 +493,46 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, // Check first in the cache of default fonts per script and size. - FontId cachedDefaultFontId = 0u; - DefaultFonts* defaultFonts = *( defaultFontPerScriptCacheBuffer + script ); - if( NULL != defaultFonts ) + FontId cachedDefaultFontId = 0u; + DefaultFonts* defaultFonts = *(defaultFontPerScriptCacheBuffer + script); + if(NULL != defaultFonts) { // This cache stores fall-back fonts. - cachedDefaultFontId = defaultFonts->FindFont( fontClient, - currentFontDescription, - currentFontPointSize ); + cachedDefaultFontId = defaultFonts->FindFont(fontClient, + currentFontDescription, + currentFontPointSize); } // Whether the cached default font is valid. const bool isValidCachedDefaultFont = 0u != cachedDefaultFontId; // The font is valid if it matches with the default one for the current script and size and it's different than zero. - isValidFont = isValidCachedDefaultFont && ( fontId == cachedDefaultFontId ); + isValidFont = isValidCachedDefaultFont && (fontId == cachedDefaultFontId); - if( isValidFont ) + if(isValidFont) { // Check if the font supports the character. - isValidFont = fontClient.IsCharacterSupportedByFont( fontId, character ); + isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character); } bool isCommonScript = false; - bool isEmojiScript = TextAbstraction::EMOJI == script; + bool isEmojiScript = TextAbstraction::EMOJI == script; - if( isEmojiScript && !isPreviousEmojiScript ) + if(isEmojiScript && !isPreviousEmojiScript) { - if( 0u != currentFontRun.characterRun.numberOfCharacters ) + if(0u != currentFontRun.characterRun.numberOfCharacters) { // Store the font run. - fonts.Insert( fonts.Begin() + fontIndex, currentFontRun ); + fonts.Insert(fonts.Begin() + fontIndex, currentFontRun); ++fontIndex; } // Initialize the new one. - currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters; + currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters; currentFontRun.characterRun.numberOfCharacters = 0u; - currentFontRun.fontId = fontId; - currentFontRun.isItalicRequired = false; - currentFontRun.isBoldRequired = false; + currentFontRun.fontId = fontId; + currentFontRun.isItalicRequired = false; + currentFontRun.isBoldRequired = false; } // If the given font is not valid, it means either: @@ -545,7 +541,7 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, // - the platform default font is different than the default font for the current script. // Need to check if the given font supports the current character. - if( !isValidFont ) // (1) + if(!isValidFont) // (1) { // Whether the current character is common for all scripts (i.e. white spaces, ...) @@ -559,57 +555,57 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, // // Many fonts support 'white spaces' so probably the font set by the user or the platform's default // supports the 'white space'. However, that font may not support the DEVANAGARI script. - isCommonScript = TextAbstraction::IsCommonScript( character ); + isCommonScript = TextAbstraction::IsCommonScript(character); // Check in the valid fonts cache. - ValidateFontsPerScript* validateFontsPerScript = *( validFontsPerScriptCacheBuffer + script ); + ValidateFontsPerScript* validateFontsPerScript = *(validFontsPerScriptCacheBuffer + script); - if( NULL != validateFontsPerScript ) + if(NULL != validateFontsPerScript) { // This cache stores valid fonts set by the user. - isValidFont = validateFontsPerScript->IsValidFont( fontId ); + isValidFont = validateFontsPerScript->IsValidFont(fontId); // It may happen that a validated font for a script doesn't have all the glyphs for that script. // i.e a font validated for the CJK script may contain glyphs for the chinese language but not for the Japanese. - if( isValidFont ) + if(isValidFont) { // Checks if the current character is supported by the font is needed. - isValidFont = fontClient.IsCharacterSupportedByFont( fontId, character ); + isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character); } } - if( !isValidFont ) // (2) + if(!isValidFont) // (2) { // The selected font is not stored in any cache. // Checks if the current character is supported by the selected font. - isValidFont = fontClient.IsCharacterSupportedByFont( fontId, character ); + isValidFont = fontClient.IsCharacterSupportedByFont(fontId, character); // If there is a valid font, cache it. - if( isValidFont && !isCommonScript ) + if(isValidFont && !isCommonScript) { - if( NULL == validateFontsPerScript ) + if(NULL == validateFontsPerScript) { validateFontsPerScript = new ValidateFontsPerScript(); - *( validFontsPerScriptCacheBuffer + script ) = validateFontsPerScript; + *(validFontsPerScriptCacheBuffer + script) = validateFontsPerScript; } - validateFontsPerScript->mValidFonts.PushBack( fontId ); + validateFontsPerScript->mValidFonts.PushBack(fontId); } - if( !isValidFont && ( fontId != cachedDefaultFontId ) && ( !TextAbstraction::IsNewParagraph( character ) )) // (3) + if(!isValidFont && (fontId != cachedDefaultFontId) && (!TextAbstraction::IsNewParagraph(character))) // (3) { // The selected font by the user or the platform's default font has failed to validate the character. // Checks if the previously discarted cached default font supports the character. bool isValidCachedFont = false; - if( isValidCachedDefaultFont ) + if(isValidCachedDefaultFont) { - isValidCachedFont = fontClient.IsCharacterSupportedByFont( cachedDefaultFontId, character ); + isValidCachedFont = fontClient.IsCharacterSupportedByFont(cachedDefaultFontId, character); } - if( isValidCachedFont ) + if(isValidCachedFont) { // Use the cached default font for the script if there is one. fontId = cachedDefaultFontId; @@ -621,103 +617,103 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, DefaultFonts* defaultFontsPerScript = NULL; // Find a fallback-font. - fontId = fontClient.FindFallbackFont( character, - currentFontDescription, - currentFontPointSize, - false ); + fontId = fontClient.FindFallbackFont(character, + currentFontDescription, + currentFontPointSize, + false); - if( 0u == fontId ) + if(0u == fontId) { - fontId = fontClient.FindDefaultFont( UTF32_A, currentFontPointSize ); + fontId = fontClient.FindDefaultFont(UTF32_A, currentFontPointSize); } - if ( !isCommonScript && (script != TextAbstraction::UNKNOWN) ) + if(!isCommonScript && (script != TextAbstraction::UNKNOWN)) { // Cache the font if it is not an unknown script - if( NULL == defaultFontsPerScript ) + if(NULL == defaultFontsPerScript) { - defaultFontsPerScript = *( defaultFontPerScriptCacheBuffer + script ); + defaultFontsPerScript = *(defaultFontPerScriptCacheBuffer + script); - if( NULL == defaultFontsPerScript ) + if(NULL == defaultFontsPerScript) { - defaultFontsPerScript = new DefaultFonts(); - *( defaultFontPerScriptCacheBuffer + script ) = defaultFontsPerScript; + defaultFontsPerScript = new DefaultFonts(); + *(defaultFontPerScriptCacheBuffer + script) = defaultFontsPerScript; } } - defaultFontsPerScript->Cache( currentFontDescription, fontId ); + defaultFontsPerScript->Cache(currentFontDescription, fontId); } } } // !isValidFont (3) - } // !isValidFont (2) - } // !isValidFont (1) + } // !isValidFont (2) + } // !isValidFont (1) #ifdef DEBUG_ENABLED { Dali::TextAbstraction::FontDescription description; - fontClient.GetDescription( fontId, description ); - DALI_LOG_INFO( gLogFilter, - Debug::Verbose, - " Validated font set\n Character : %x, Script : %s, Font : %s \n", - character, - Dali::TextAbstraction::ScriptName[script], - description.path.c_str() ); + fontClient.GetDescription(fontId, description); + DALI_LOG_INFO(gLogFilter, + Debug::Verbose, + " Validated font set\n Character : %x, Script : %s, Font : %s \n", + character, + Dali::TextAbstraction::ScriptName[script], + description.path.c_str()); } #endif // Whether bols style is required. - isBoldRequired = ( currentFontDescription.weight >= TextAbstraction::FontWeight::BOLD ); + isBoldRequired = (currentFontDescription.weight >= TextAbstraction::FontWeight::BOLD); // Whether italic style is required. - isItalicRequired = ( currentFontDescription.slant >= TextAbstraction::FontSlant::ITALIC ); + isItalicRequired = (currentFontDescription.slant >= TextAbstraction::FontSlant::ITALIC); // The font is now validated. - if( ( fontId != currentFontRun.fontId ) || - isNewParagraphCharacter || - // If font id is same as previous but style is diffrent, initialize new one - ( ( fontId == currentFontRun.fontId ) && ( ( isBoldRequired != currentFontRun.isBoldRequired ) || ( isItalicRequired != currentFontRun.isItalicRequired ) ) ) ) + if((fontId != currentFontRun.fontId) || + isNewParagraphCharacter || + // If font id is same as previous but style is diffrent, initialize new one + ((fontId == currentFontRun.fontId) && ((isBoldRequired != currentFontRun.isBoldRequired) || (isItalicRequired != currentFontRun.isItalicRequired)))) { // Current run needs to be stored and a new one initialized. - if( 0u != currentFontRun.characterRun.numberOfCharacters ) + if(0u != currentFontRun.characterRun.numberOfCharacters) { // Store the font run. - fonts.Insert( fonts.Begin() + fontIndex, currentFontRun ); + fonts.Insert(fonts.Begin() + fontIndex, currentFontRun); ++fontIndex; } // Initialize the new one. - currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters; + currentFontRun.characterRun.characterIndex = currentFontRun.characterRun.characterIndex + currentFontRun.characterRun.numberOfCharacters; currentFontRun.characterRun.numberOfCharacters = 0u; - currentFontRun.fontId = fontId; - currentFontRun.isBoldRequired = isBoldRequired; - currentFontRun.isItalicRequired = isItalicRequired; + currentFontRun.fontId = fontId; + currentFontRun.isBoldRequired = isBoldRequired; + currentFontRun.isItalicRequired = isItalicRequired; } // Add one more character to the run. ++currentFontRun.characterRun.numberOfCharacters; // Whether the current character is a new paragraph character. - isNewParagraphCharacter = TextAbstraction::IsNewParagraph( character ); - isPreviousEmojiScript = isEmojiScript; + isNewParagraphCharacter = TextAbstraction::IsNewParagraph(character); + isPreviousEmojiScript = isEmojiScript; } // end traverse characters. - if( 0u != currentFontRun.characterRun.numberOfCharacters ) + if(0u != currentFontRun.characterRun.numberOfCharacters) { // Store the last run. - fonts.Insert( fonts.Begin() + fontIndex, currentFontRun ); + fonts.Insert(fonts.Begin() + fontIndex, currentFontRun); ++fontIndex; } - if( fontIndex < fonts.Count() ) + if(fontIndex < fonts.Count()) { // Update the indices of the next font runs. - const FontRun& run = *( fonts.Begin() + fontIndex - 1u ); + const FontRun& run = *(fonts.Begin() + fontIndex - 1u); CharacterIndex nextCharacterIndex = run.characterRun.characterIndex + run.characterRun.numberOfCharacters; - for( Vector::Iterator it = fonts.Begin() + fontIndex, - endIt = fonts.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = fonts.Begin() + fontIndex, + endIt = fonts.End(); + it != endIt; + ++it) { FontRun& run = *it; @@ -726,7 +722,7 @@ void MultilanguageSupport::ValidateFonts( const Vector& text, } } - DALI_LOG_INFO( gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "<--MultilanguageSupport::ValidateFonts\n"); } } // namespace Internal diff --git a/dali-toolkit/internal/text/multi-language-support.cpp b/dali-toolkit/internal/text/multi-language-support.cpp index 795e7ae..11ba9c0 100644 --- a/dali-toolkit/internal/text/multi-language-support.cpp +++ b/dali-toolkit/internal/text/multi-language-support.cpp @@ -23,13 +23,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - MultilanguageSupport::MultilanguageSupport() { } @@ -38,8 +35,8 @@ MultilanguageSupport::~MultilanguageSupport() { } -MultilanguageSupport::MultilanguageSupport( Internal::MultilanguageSupport* implementation ) -: BaseHandle( implementation ) +MultilanguageSupport::MultilanguageSupport(Internal::MultilanguageSupport* implementation) +: BaseHandle(implementation) { } @@ -48,34 +45,34 @@ MultilanguageSupport MultilanguageSupport::Get() return Internal::MultilanguageSupport::Get(); } -void MultilanguageSupport::SetScripts( const Vector& text, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& scripts ) +void MultilanguageSupport::SetScripts(const Vector& text, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& scripts) { - GetImplementation( *this ).SetScripts( text, - startIndex, - numberOfCharacters, - scripts ); + GetImplementation(*this).SetScripts(text, + startIndex, + numberOfCharacters, + scripts); } -void MultilanguageSupport::ValidateFonts( const Vector& text, - const Vector& scripts, - const Vector& fontDescriptions, - const TextAbstraction::FontDescription& defaultFontDescription, - TextAbstraction::PointSize26Dot6 defaultFontPointSize, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& fonts ) +void MultilanguageSupport::ValidateFonts(const Vector& text, + const Vector& scripts, + const Vector& fontDescriptions, + const TextAbstraction::FontDescription& defaultFontDescription, + TextAbstraction::PointSize26Dot6 defaultFontPointSize, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& fonts) { - GetImplementation( *this ).ValidateFonts( text, - scripts, - fontDescriptions, - defaultFontDescription, - defaultFontPointSize, - startIndex, - numberOfCharacters, - fonts ); + GetImplementation(*this).ValidateFonts(text, + scripts, + fontDescriptions, + defaultFontDescription, + defaultFontPointSize, + startIndex, + numberOfCharacters, + fonts); } } // namespace Text diff --git a/dali-toolkit/internal/text/property-string-parser.cpp b/dali-toolkit/internal/text/property-string-parser.cpp index 2aa05e9..ec0fc94 100644 --- a/dali-toolkit/internal/text/property-string-parser.cpp +++ b/dali-toolkit/internal/text/property-string-parser.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. @@ -28,16 +28,13 @@ namespace Dali { - namespace Toolkit { - namespace Text { - -void CreatePropertyMap( const TreeNode* const node, Property::Map& map ) +void CreatePropertyMap(const TreeNode* const node, Property::Map& map) { - switch( node->GetType() ) + switch(node->GetType()) { case TreeNode::IS_NULL: case TreeNode::OBJECT: @@ -47,7 +44,7 @@ void CreatePropertyMap( const TreeNode* const node, Property::Map& map ) } case TreeNode::STRING: { - map.Insert( node->GetName(), Property::Value( node->GetString() ) ); + map.Insert(node->GetName(), Property::Value(node->GetString())); break; } case TreeNode::INTEGER: @@ -58,23 +55,23 @@ void CreatePropertyMap( const TreeNode* const node, Property::Map& map ) } } - for( TreeNode::ConstIterator it = node->CBegin(), endIt = node->CEnd(); it != endIt; ++it ) + for(TreeNode::ConstIterator it = node->CBegin(), endIt = node->CEnd(); it != endIt; ++it) { const TreeNode::KeyNodePair& pair = *it; - CreatePropertyMap( &pair.second, map ); + CreatePropertyMap(&pair.second, map); } } -void ParsePropertyString( const std::string& property, Property::Map& map ) +void ParsePropertyString(const std::string& property, Property::Map& map) { Toolkit::JsonParser parser = Toolkit::JsonParser::New(); - if( parser.Parse( property ) ) + if(parser.Parse(property)) { const TreeNode* const node = parser.GetRoot(); - if( node ) + if(node) { - CreatePropertyMap( node, map ); + CreatePropertyMap(node, map); } } } diff --git a/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager-impl.cpp b/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager-impl.cpp old mode 100755 new mode 100644 index a3f7efd..bc2a146 --- a/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager-impl.cpp +++ b/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager-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,109 +22,106 @@ namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); #endif } // unnamed namespace namespace Dali { - namespace Toolkit { - namespace Internal { - AtlasGlyphManager::AtlasGlyphManager() { mAtlasManager = Dali::Toolkit::AtlasManager::New(); - mSampler = Sampler::New(); - mSampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR ); + mSampler = Sampler::New(); + mSampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR); } -void AtlasGlyphManager::Add( const Text::GlyphInfo& glyph, - const Toolkit::AtlasGlyphManager::GlyphStyle& style, - const PixelData& bitmap, - Dali::Toolkit::AtlasManager::AtlasSlot& slot ) +void AtlasGlyphManager::Add(const Text::GlyphInfo& glyph, + const Toolkit::AtlasGlyphManager::GlyphStyle& style, + const PixelData& bitmap, + Dali::Toolkit::AtlasManager::AtlasSlot& slot) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Added glyph, font: %d index: %d\n", glyph.fontId, glyph.index ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Added glyph, font: %d index: %d\n", glyph.fontId, glyph.index); // If glyph added to an existing or new atlas then a new glyph record is required. // Check if an existing atlas will fit the image, create a new one if required. - if ( mAtlasManager.Add( bitmap, slot ) ) + if(mAtlasManager.Add(bitmap, slot)) { // A new atlas was created so set the texture set details for the atlas - Dali::Texture atlas = mAtlasManager.GetAtlasContainer( slot.mAtlasId ); - TextureSet textureSet = TextureSet::New(); - textureSet.SetTexture( 0u, atlas ); - textureSet.SetSampler( 0u, mSampler); - mAtlasManager.SetTextures( slot.mAtlasId, textureSet ); + Dali::Texture atlas = mAtlasManager.GetAtlasContainer(slot.mAtlasId); + TextureSet textureSet = TextureSet::New(); + textureSet.SetTexture(0u, atlas); + textureSet.SetSampler(0u, mSampler); + mAtlasManager.SetTextures(slot.mAtlasId, textureSet); } GlyphRecordEntry record; - record.mIndex = glyph.index; - record.mImageId = slot.mImageId; - record.mCount = 1; + record.mIndex = glyph.index; + record.mImageId = slot.mImageId; + record.mCount = 1; record.mOutlineWidth = style.outline; - record.isItalic = style.isItalic; - record.isBold = style.isBold; + record.isItalic = style.isItalic; + record.isBold = style.isBold; // Have glyph records been created for this fontId ? bool foundGlyph = false; - for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); - fontGlyphRecordIt != mFontGlyphRecords.end(); ++fontGlyphRecordIt ) + for(std::vector::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); + fontGlyphRecordIt != mFontGlyphRecords.end(); + ++fontGlyphRecordIt) { - if ( fontGlyphRecordIt->mFontId == glyph.fontId ) + if(fontGlyphRecordIt->mFontId == glyph.fontId) { - fontGlyphRecordIt->mGlyphRecords.PushBack( record ); + fontGlyphRecordIt->mGlyphRecords.PushBack(record); foundGlyph = true; break; } } - if ( !foundGlyph ) + if(!foundGlyph) { // We need to add a new font entry FontGlyphRecord fontGlyphRecord; fontGlyphRecord.mFontId = glyph.fontId; - fontGlyphRecord.mGlyphRecords.PushBack( record ); - mFontGlyphRecords.push_back( fontGlyphRecord ); + fontGlyphRecord.mGlyphRecords.PushBack(record); + mFontGlyphRecords.push_back(fontGlyphRecord); } } -void AtlasGlyphManager::GenerateMeshData( uint32_t imageId, - const Vector2& position, - Toolkit::AtlasManager::Mesh2D& mesh ) +void AtlasGlyphManager::GenerateMeshData(uint32_t imageId, + const Vector2& position, + Toolkit::AtlasManager::Mesh2D& mesh) { // Generate mesh data and tell Atlas Manager not to handle reference counting ( we'll do it ) - mAtlasManager.GenerateMeshData( imageId, position, mesh, false ); + mAtlasManager.GenerateMeshData(imageId, position, mesh, false); } -bool AtlasGlyphManager::IsCached( Text::FontId fontId, - Text::GlyphIndex index, - const Toolkit::AtlasGlyphManager::GlyphStyle& style, - Dali::Toolkit::AtlasManager::AtlasSlot& slot ) +bool AtlasGlyphManager::IsCached(Text::FontId fontId, + Text::GlyphIndex index, + const Toolkit::AtlasGlyphManager::GlyphStyle& style, + Dali::Toolkit::AtlasManager::AtlasSlot& slot) { - for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); - fontGlyphRecordIt != mFontGlyphRecords.end(); - ++fontGlyphRecordIt ) + for(std::vector::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); + fontGlyphRecordIt != mFontGlyphRecords.end(); + ++fontGlyphRecordIt) { - if ( fontGlyphRecordIt->mFontId == fontId ) + if(fontGlyphRecordIt->mFontId == fontId) { - for ( Vector< GlyphRecordEntry >::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin(); - glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End(); - ++glyphRecordIt ) + for(Vector::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin(); + glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End(); + ++glyphRecordIt) { - if ( ( glyphRecordIt->mIndex == index ) && - ( glyphRecordIt->mOutlineWidth == style.outline ) && - ( glyphRecordIt->isItalic == style.isItalic ) && - ( glyphRecordIt->isBold == style.isBold ) ) + if((glyphRecordIt->mIndex == index) && + (glyphRecordIt->mOutlineWidth == style.outline) && + (glyphRecordIt->isItalic == style.isItalic) && + (glyphRecordIt->isBold == style.isBold)) { slot.mImageId = glyphRecordIt->mImageId; - slot.mAtlasId = mAtlasManager.GetAtlas( slot.mImageId ); + slot.mAtlasId = mAtlasManager.GetAtlas(slot.mImageId); return true; } } @@ -134,25 +131,25 @@ bool AtlasGlyphManager::IsCached( Text::FontId fontId, return false; } -Vector2 AtlasGlyphManager::GetAtlasSize( uint32_t atlasId ) +Vector2 AtlasGlyphManager::GetAtlasSize(uint32_t atlasId) { - Toolkit::AtlasManager::AtlasSize size = mAtlasManager.GetAtlasSize( atlasId ); - return Vector2( static_cast< float >( size.mWidth ), static_cast< float >( size.mHeight ) ); + Toolkit::AtlasManager::AtlasSize size = mAtlasManager.GetAtlasSize(atlasId); + return Vector2(static_cast(size.mWidth), static_cast(size.mHeight)); } -void AtlasGlyphManager::SetNewAtlasSize( uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight ) +void AtlasGlyphManager::SetNewAtlasSize(uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight) { Toolkit::AtlasManager::AtlasSize size; - size.mWidth = width; - size.mHeight = height; - size.mBlockWidth = blockWidth; + size.mWidth = width; + size.mHeight = height; + size.mBlockWidth = blockWidth; size.mBlockHeight = blockHeight; - mAtlasManager.SetNewAtlasSize( size ); + mAtlasManager.SetNewAtlasSize(size); } -Pixel::Format AtlasGlyphManager::GetPixelFormat( uint32_t atlasId ) +Pixel::Format AtlasGlyphManager::GetPixelFormat(uint32_t atlasId) { - return mAtlasManager.GetPixelFormat( atlasId ); + return mAtlasManager.GetPixelFormat(atlasId); } const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics() @@ -160,16 +157,16 @@ const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics() std::ostringstream verboseMetrics; mMetrics.mGlyphCount = 0u; - for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); - fontGlyphRecordIt != mFontGlyphRecords.end(); - ++fontGlyphRecordIt ) + for(std::vector::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); + fontGlyphRecordIt != mFontGlyphRecords.end(); + ++fontGlyphRecordIt) { mMetrics.mGlyphCount += fontGlyphRecordIt->mGlyphRecords.Size(); verboseMetrics << "[FontId " << fontGlyphRecordIt->mFontId << " Glyph "; - for ( Vector< GlyphRecordEntry >::Iterator glyphRecordEntryIt = fontGlyphRecordIt->mGlyphRecords.Begin(); - glyphRecordEntryIt != fontGlyphRecordIt->mGlyphRecords.End(); - ++glyphRecordEntryIt ) + for(Vector::Iterator glyphRecordEntryIt = fontGlyphRecordIt->mGlyphRecords.Begin(); + glyphRecordEntryIt != fontGlyphRecordIt->mGlyphRecords.End(); + ++glyphRecordEntryIt) { verboseMetrics << glyphRecordEntryIt->mIndex << "(" << glyphRecordEntryIt->mCount << ") "; } @@ -177,39 +174,39 @@ const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics() } mMetrics.mVerboseGlyphCounts = verboseMetrics.str(); - mAtlasManager.GetMetrics( mMetrics.mAtlasMetrics ); + mAtlasManager.GetMetrics(mMetrics.mAtlasMetrics); return mMetrics; } -void AtlasGlyphManager::AdjustReferenceCount( Text::FontId fontId, Text::GlyphIndex index, const Toolkit::AtlasGlyphManager::GlyphStyle& style, int32_t delta ) +void AtlasGlyphManager::AdjustReferenceCount(Text::FontId fontId, Text::GlyphIndex index, const Toolkit::AtlasGlyphManager::GlyphStyle& style, int32_t delta) { - if( 0 != delta ) + if(0 != delta) { - DALI_LOG_INFO( gLogFilter, Debug::General, "AdjustReferenceCount %d, font: %d index: %d\n", delta, fontId, index ); + DALI_LOG_INFO(gLogFilter, Debug::General, "AdjustReferenceCount %d, font: %d index: %d\n", delta, fontId, index); - for ( std::vector< FontGlyphRecord >::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); - fontGlyphRecordIt != mFontGlyphRecords.end(); - ++fontGlyphRecordIt ) + for(std::vector::iterator fontGlyphRecordIt = mFontGlyphRecords.begin(); + fontGlyphRecordIt != mFontGlyphRecords.end(); + ++fontGlyphRecordIt) { - if ( fontGlyphRecordIt->mFontId == fontId ) + if(fontGlyphRecordIt->mFontId == fontId) { - for ( Vector< GlyphRecordEntry >::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin(); - glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End(); - ++glyphRecordIt ) + for(Vector::Iterator glyphRecordIt = fontGlyphRecordIt->mGlyphRecords.Begin(); + glyphRecordIt != fontGlyphRecordIt->mGlyphRecords.End(); + ++glyphRecordIt) { - if ( ( glyphRecordIt->mIndex == index ) && - ( glyphRecordIt->mOutlineWidth == style.outline ) && - ( glyphRecordIt->isItalic == style.isItalic ) && - ( glyphRecordIt->isBold == style.isBold ) ) + if((glyphRecordIt->mIndex == index) && + (glyphRecordIt->mOutlineWidth == style.outline) && + (glyphRecordIt->isItalic == style.isItalic) && + (glyphRecordIt->isBold == style.isBold)) { glyphRecordIt->mCount += delta; - DALI_ASSERT_DEBUG( glyphRecordIt->mCount >= 0 && "Glyph ref-count should not be negative" ); + DALI_ASSERT_DEBUG(glyphRecordIt->mCount >= 0 && "Glyph ref-count should not be negative"); - if ( !glyphRecordIt->mCount ) + if(!glyphRecordIt->mCount) { - mAtlasManager.Remove( glyphRecordIt->mImageId ); - fontGlyphRecordIt->mGlyphRecords.Remove( glyphRecordIt ); + mAtlasManager.Remove(glyphRecordIt->mImageId); + fontGlyphRecordIt->mGlyphRecords.Remove(glyphRecordIt); } return; } @@ -218,13 +215,13 @@ void AtlasGlyphManager::AdjustReferenceCount( Text::FontId fontId, Text::GlyphIn } // Should not arrive here - DALI_ASSERT_DEBUG( false && "Failed to adjust ref-count" ); + DALI_ASSERT_DEBUG(false && "Failed to adjust ref-count"); } } -TextureSet AtlasGlyphManager::GetTextures( uint32_t atlasId ) const +TextureSet AtlasGlyphManager::GetTextures(uint32_t atlasId) const { - return mAtlasManager.GetTextures( atlasId ); + return mAtlasManager.GetTextures(atlasId); } AtlasGlyphManager::~AtlasGlyphManager() diff --git a/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.cpp b/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.cpp index 4ce469e..a3059fe 100644 --- a/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.cpp +++ b/dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.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 Toolkit { - AtlasGlyphManager::AtlasGlyphManager() { } @@ -43,8 +41,8 @@ AtlasGlyphManager AtlasGlyphManager::Get() AtlasGlyphManager manager; // Check whether the AtlasGlyphManager is already created - SingletonService singletonService( SingletonService::Get() ); - if ( singletonService ) + SingletonService singletonService(SingletonService::Get()); + if(singletonService) { Dali::BaseHandle handle = singletonService.GetSingleton(typeid(AtlasGlyphManager)); if(handle) @@ -63,54 +61,54 @@ AtlasGlyphManager AtlasGlyphManager::Get() return manager; } -AtlasGlyphManager::AtlasGlyphManager(Internal::AtlasGlyphManager *impl) - : BaseHandle(impl) +AtlasGlyphManager::AtlasGlyphManager(Internal::AtlasGlyphManager* impl) +: BaseHandle(impl) { } -void AtlasGlyphManager::Add( const Text::GlyphInfo& glyph, - const GlyphStyle& style, - const PixelData& bitmap, - AtlasManager::AtlasSlot& slot ) +void AtlasGlyphManager::Add(const Text::GlyphInfo& glyph, + const GlyphStyle& style, + const PixelData& bitmap, + AtlasManager::AtlasSlot& slot) { - GetImplementation(*this).Add( glyph, style, bitmap, slot ); + GetImplementation(*this).Add(glyph, style, bitmap, slot); } -void AtlasGlyphManager::GenerateMeshData( uint32_t imageId, - const Vector2& position, - Toolkit::AtlasManager::Mesh2D& mesh ) +void AtlasGlyphManager::GenerateMeshData(uint32_t imageId, + const Vector2& position, + Toolkit::AtlasManager::Mesh2D& mesh) { - GetImplementation(*this).GenerateMeshData( imageId, - position, - mesh ); + GetImplementation(*this).GenerateMeshData(imageId, + position, + mesh); } -bool AtlasGlyphManager::IsCached( Text::FontId fontId, - Text::GlyphIndex index, - const GlyphStyle& style, - AtlasManager::AtlasSlot& slot ) +bool AtlasGlyphManager::IsCached(Text::FontId fontId, + Text::GlyphIndex index, + const GlyphStyle& style, + AtlasManager::AtlasSlot& slot) { - return GetImplementation(*this).IsCached( fontId, index, style, slot ); + return GetImplementation(*this).IsCached(fontId, index, style, slot); } -void AtlasGlyphManager::SetNewAtlasSize( uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight ) +void AtlasGlyphManager::SetNewAtlasSize(uint32_t width, uint32_t height, uint32_t blockWidth, uint32_t blockHeight) { - GetImplementation(*this).SetNewAtlasSize( width, height, blockWidth, blockHeight ); + GetImplementation(*this).SetNewAtlasSize(width, height, blockWidth, blockHeight); } -Vector2 AtlasGlyphManager::GetAtlasSize( uint32_t atlasId ) +Vector2 AtlasGlyphManager::GetAtlasSize(uint32_t atlasId) { - return GetImplementation(*this).GetAtlasSize( atlasId ); + return GetImplementation(*this).GetAtlasSize(atlasId); } -Pixel::Format AtlasGlyphManager::GetPixelFormat( uint32_t atlasId ) +Pixel::Format AtlasGlyphManager::GetPixelFormat(uint32_t atlasId) { - return GetImplementation(*this).GetPixelFormat( atlasId ); + return GetImplementation(*this).GetPixelFormat(atlasId); } -TextureSet AtlasGlyphManager::GetTextures( uint32_t atlasId ) const +TextureSet AtlasGlyphManager::GetTextures(uint32_t atlasId) const { - return GetImplementation(*this).GetTextures( atlasId ); + return GetImplementation(*this).GetTextures(atlasId); } const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics() @@ -118,9 +116,9 @@ const Toolkit::AtlasGlyphManager::Metrics& AtlasGlyphManager::GetMetrics() return GetImplementation(*this).GetMetrics(); } -void AtlasGlyphManager::AdjustReferenceCount( Text::FontId fontId, Text::GlyphIndex index, const GlyphStyle& style, int32_t delta ) +void AtlasGlyphManager::AdjustReferenceCount(Text::FontId fontId, Text::GlyphIndex index, const GlyphStyle& style, int32_t delta) { - GetImplementation(*this).AdjustReferenceCount( fontId, index, style, delta ); + GetImplementation(*this).AdjustReferenceCount(fontId, index, style, delta); } } // namespace Toolkit diff --git a/dali-toolkit/internal/text/rendering/atlas/atlas-manager-impl.cpp b/dali-toolkit/internal/text/rendering/atlas/atlas-manager-impl.cpp index ba07cef..8745db1 100644 --- a/dali-toolkit/internal/text/rendering/atlas/atlas-manager-impl.cpp +++ b/dali-toolkit/internal/text/rendering/atlas/atlas-manager-impl.cpp @@ -18,43 +18,40 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const uint32_t DEFAULT_ATLAS_WIDTH( 512u ); - const uint32_t DEFAULT_ATLAS_HEIGHT( 512u ); - const uint32_t DEFAULT_BLOCK_WIDTH( 16u ); - const uint32_t DEFAULT_BLOCK_HEIGHT( 16u ); - const uint32_t SINGLE_PIXEL_PADDING( 1u ); - const uint32_t DOUBLE_PIXEL_PADDING( SINGLE_PIXEL_PADDING << 1 ); - Toolkit::AtlasManager::AtlasSize EMPTY_SIZE; - - bool IsBlockSizeSufficient( uint32_t width, uint32_t height, uint32_t requiredBlockWidth, uint32_t requiredBlockHeight ) - { - return ( width + DOUBLE_PIXEL_PADDING <= requiredBlockWidth ) && ( height + DOUBLE_PIXEL_PADDING <= requiredBlockHeight ); - } +const uint32_t DEFAULT_ATLAS_WIDTH(512u); +const uint32_t DEFAULT_ATLAS_HEIGHT(512u); +const uint32_t DEFAULT_BLOCK_WIDTH(16u); +const uint32_t DEFAULT_BLOCK_HEIGHT(16u); +const uint32_t SINGLE_PIXEL_PADDING(1u); +const uint32_t DOUBLE_PIXEL_PADDING(SINGLE_PIXEL_PADDING << 1); +Toolkit::AtlasManager::AtlasSize EMPTY_SIZE; + +bool IsBlockSizeSufficient(uint32_t width, uint32_t height, uint32_t requiredBlockWidth, uint32_t requiredBlockHeight) +{ + return (width + DOUBLE_PIXEL_PADDING <= requiredBlockWidth) && (height + DOUBLE_PIXEL_PADDING <= requiredBlockHeight); } +} // namespace AtlasManager::AtlasManager() -: mAddFailPolicy( Toolkit::AtlasManager::FAIL_ON_ADD_CREATES ) +: mAddFailPolicy(Toolkit::AtlasManager::FAIL_ON_ADD_CREATES) { - mNewAtlasSize.mWidth = DEFAULT_ATLAS_WIDTH; - mNewAtlasSize.mHeight = DEFAULT_ATLAS_HEIGHT; - mNewAtlasSize.mBlockWidth = DEFAULT_BLOCK_WIDTH; + mNewAtlasSize.mWidth = DEFAULT_ATLAS_WIDTH; + mNewAtlasSize.mHeight = DEFAULT_ATLAS_HEIGHT; + mNewAtlasSize.mBlockWidth = DEFAULT_BLOCK_WIDTH; mNewAtlasSize.mBlockHeight = DEFAULT_BLOCK_HEIGHT; } @@ -68,103 +65,106 @@ AtlasManager::~AtlasManager() { } -Toolkit::AtlasManager::AtlasId AtlasManager::CreateAtlas( const Toolkit::AtlasManager::AtlasSize& size, Pixel::Format pixelformat ) +Toolkit::AtlasManager::AtlasId AtlasManager::CreateAtlas(const Toolkit::AtlasManager::AtlasSize& size, Pixel::Format pixelformat) { - SizeType width = size.mWidth; - SizeType height = size.mHeight; - SizeType blockWidth = size.mBlockWidth; + SizeType width = size.mWidth; + SizeType height = size.mHeight; + SizeType blockWidth = size.mBlockWidth; SizeType blockHeight = size.mBlockHeight; // Check to see if the atlas is large enough to hold a single block even ? - if ( blockWidth + DOUBLE_PIXEL_PADDING + 1u > width || blockHeight + DOUBLE_PIXEL_PADDING + 1u > height ) + if(blockWidth + DOUBLE_PIXEL_PADDING + 1u > width || blockHeight + DOUBLE_PIXEL_PADDING + 1u > height) { DALI_LOG_ERROR("Atlas %i x %i too small. Dimensions need to be at least %ix%i\n", - width, height, blockWidth + DOUBLE_PIXEL_PADDING + 1u, blockHeight + DOUBLE_PIXEL_PADDING + 1u ); + width, + height, + blockWidth + DOUBLE_PIXEL_PADDING + 1u, + blockHeight + DOUBLE_PIXEL_PADDING + 1u); return 0; } - Dali::Texture atlas = Dali::Texture::New( TextureType::TEXTURE_2D, pixelformat, width, height ); + Dali::Texture atlas = Dali::Texture::New(TextureType::TEXTURE_2D, pixelformat, width, height); // Clear the background - unsigned int bufferSize( width * height * Dali::Pixel::GetBytesPerPixel( pixelformat ) ); + unsigned int bufferSize(width * height * Dali::Pixel::GetBytesPerPixel(pixelformat)); unsigned char* background = new unsigned char[bufferSize]; - memset( background, 0, bufferSize ); - PixelData backgroundPixels = PixelData::New( background, bufferSize, width, height, pixelformat, PixelData::DELETE_ARRAY ); - atlas.Upload( backgroundPixels, 0u, 0u, 0u, 0u, width, height ); + memset(background, 0, bufferSize); + PixelData backgroundPixels = PixelData::New(background, bufferSize, width, height, pixelformat, PixelData::DELETE_ARRAY); + atlas.Upload(backgroundPixels, 0u, 0u, 0u, 0u, width, height); AtlasDescriptor atlasDescriptor; - atlasDescriptor.mAtlas = atlas; - atlasDescriptor.mSize = size; - atlasDescriptor.mPixelFormat = pixelformat; - atlasDescriptor.mTotalBlocks = ( ( width - 1u ) / blockWidth ) * ( ( height - 1u ) / blockHeight ); + atlasDescriptor.mAtlas = atlas; + atlasDescriptor.mSize = size; + atlasDescriptor.mPixelFormat = pixelformat; + atlasDescriptor.mTotalBlocks = ((width - 1u) / blockWidth) * ((height - 1u) / blockHeight); atlasDescriptor.mAvailableBlocks = atlasDescriptor.mTotalBlocks; - bufferSize = blockWidth * SINGLE_PIXEL_PADDING * Dali::Pixel::GetBytesPerPixel(pixelformat); + bufferSize = blockWidth * SINGLE_PIXEL_PADDING * Dali::Pixel::GetBytesPerPixel(pixelformat); unsigned char* bufferHorizontalStrip = new unsigned char[bufferSize]; - memset( bufferHorizontalStrip, 0, bufferSize ); - atlasDescriptor.mHorizontalStrip = PixelData::New( bufferHorizontalStrip, bufferSize, blockWidth, SINGLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY ); + memset(bufferHorizontalStrip, 0, bufferSize); + atlasDescriptor.mHorizontalStrip = PixelData::New(bufferHorizontalStrip, bufferSize, blockWidth, SINGLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY); - bufferSize = SINGLE_PIXEL_PADDING * (blockHeight - DOUBLE_PIXEL_PADDING) * Dali::Pixel::GetBytesPerPixel(pixelformat); + bufferSize = SINGLE_PIXEL_PADDING * (blockHeight - DOUBLE_PIXEL_PADDING) * Dali::Pixel::GetBytesPerPixel(pixelformat); unsigned char* bufferVerticalStrip = new unsigned char[bufferSize]; - memset( bufferVerticalStrip, 0, bufferSize ); - atlasDescriptor.mVerticalStrip = PixelData::New( bufferVerticalStrip, bufferSize, SINGLE_PIXEL_PADDING, blockHeight - DOUBLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY ); + memset(bufferVerticalStrip, 0, bufferSize); + atlasDescriptor.mVerticalStrip = PixelData::New(bufferVerticalStrip, bufferSize, SINGLE_PIXEL_PADDING, blockHeight - DOUBLE_PIXEL_PADDING, pixelformat, PixelData::DELETE_ARRAY); - bufferSize = Dali::Pixel::GetBytesPerPixel(pixelformat); + bufferSize = Dali::Pixel::GetBytesPerPixel(pixelformat); unsigned char* buffer = new unsigned char[bufferSize]; - memset( buffer, 0xFF, bufferSize ); - PixelData filledPixelImage = PixelData::New( buffer, bufferSize, 1u, 1u, pixelformat, PixelData::DELETE_ARRAY ); - atlas.Upload( filledPixelImage, 0u, 0u, 0u, 0u, 1u, 1u ); - mAtlasList.push_back( atlasDescriptor ); + memset(buffer, 0xFF, bufferSize); + PixelData filledPixelImage = PixelData::New(buffer, bufferSize, 1u, 1u, pixelformat, PixelData::DELETE_ARRAY); + atlas.Upload(filledPixelImage, 0u, 0u, 0u, 0u, 1u, 1u); + mAtlasList.push_back(atlasDescriptor); return mAtlasList.size(); } -void AtlasManager::SetAddPolicy( Toolkit::AtlasManager::AddFailPolicy policy ) +void AtlasManager::SetAddPolicy(Toolkit::AtlasManager::AddFailPolicy policy) { mAddFailPolicy = policy; } -bool AtlasManager::Add( const PixelData& image, - Toolkit::AtlasManager::AtlasSlot& slot, - Toolkit::AtlasManager::AtlasId atlas ) +bool AtlasManager::Add(const PixelData& image, + Toolkit::AtlasManager::AtlasSlot& slot, + Toolkit::AtlasManager::AtlasId atlas) { - bool created = false; + bool created = false; Pixel::Format pixelFormat = image.GetPixelFormat(); - SizeType width = image.GetWidth(); - SizeType height = image.GetHeight(); - SizeType foundAtlas = 0; - SizeType index = 0; - slot.mImageId = 0; + SizeType width = image.GetWidth(); + SizeType height = image.GetHeight(); + SizeType foundAtlas = 0; + SizeType index = 0; + slot.mImageId = 0; AtlasSlotDescriptor desc; // If there is a preferred atlas then check for room in that first - if ( atlas-- ) + if(atlas--) { - foundAtlas = CheckAtlas( atlas, width, height, pixelFormat ); + foundAtlas = CheckAtlas(atlas, width, height, pixelFormat); } // Search current atlases to see if there is a good match - while( ( 0u == foundAtlas ) && ( index < mAtlasList.size() ) ) + while((0u == foundAtlas) && (index < mAtlasList.size())) { - foundAtlas = CheckAtlas( index, width, height, pixelFormat ); + foundAtlas = CheckAtlas(index, width, height, pixelFormat); ++index; } // If we can't find a suitable atlas then check the policy to determine action - if ( 0u == foundAtlas ) + if(0u == foundAtlas) { - if ( Toolkit::AtlasManager::FAIL_ON_ADD_CREATES == mAddFailPolicy ) + if(Toolkit::AtlasManager::FAIL_ON_ADD_CREATES == mAddFailPolicy) { - if ( IsBlockSizeSufficient( width, height, mNewAtlasSize.mBlockWidth, mNewAtlasSize.mBlockHeight ) ) // Checks if image fits within the atlas blocks + if(IsBlockSizeSufficient(width, height, mNewAtlasSize.mBlockWidth, mNewAtlasSize.mBlockHeight)) // Checks if image fits within the atlas blocks { - foundAtlas = CreateAtlas( mNewAtlasSize, pixelFormat ); // Creating atlas with mNewAtlasSize, may not be the needed size! - if ( 0u == foundAtlas ) + foundAtlas = CreateAtlas(mNewAtlasSize, pixelFormat); // Creating atlas with mNewAtlasSize, may not be the needed size! + if(0u == foundAtlas) { DALI_LOG_ERROR("Failed to create an atlas of %i x %i blocksize: %i x %i.\n", mNewAtlasSize.mWidth, mNewAtlasSize.mHeight, mNewAtlasSize.mBlockWidth, - mNewAtlasSize.mBlockHeight ); + mNewAtlasSize.mBlockHeight); return false; } else @@ -174,7 +174,7 @@ bool AtlasManager::Add( const PixelData& image, } } - if ( ( 0u == foundAtlas ) || Toolkit::AtlasManager::FAIL_ON_ADD_FAILS == mAddFailPolicy ) + if((0u == foundAtlas) || Toolkit::AtlasManager::FAIL_ON_ADD_FAILS == mAddFailPolicy) { // Haven't found an atlas for this image ( may have failed to add image to atlas ) DALI_LOG_ERROR("Failed to create an atlas under current policy.\n"); @@ -186,63 +186,63 @@ bool AtlasManager::Add( const PixelData& image, // Work out which the block we're going to use // Is there currently a next free block available ? - if ( mAtlasList[ foundAtlas ].mAvailableBlocks ) + if(mAtlasList[foundAtlas].mAvailableBlocks) { // Yes, so select our next block - desc.mBlock = mAtlasList[ foundAtlas ].mTotalBlocks - mAtlasList[ foundAtlas ].mAvailableBlocks--; + desc.mBlock = mAtlasList[foundAtlas].mTotalBlocks - mAtlasList[foundAtlas].mAvailableBlocks--; } else { // Our next block must be from the free list, fetch from the start of the list - desc.mBlock = mAtlasList[ foundAtlas ].mFreeBlocksList[ 0 ]; - mAtlasList[ foundAtlas ].mFreeBlocksList.Remove( mAtlasList[ foundAtlas ].mFreeBlocksList.Begin() ); + desc.mBlock = mAtlasList[foundAtlas].mFreeBlocksList[0]; + mAtlasList[foundAtlas].mFreeBlocksList.Remove(mAtlasList[foundAtlas].mFreeBlocksList.Begin()); } - desc.mImageWidth = width; + desc.mImageWidth = width; desc.mImageHeight = height; - desc.mAtlasId = foundAtlas + 1u; // Ids start from 1 not the 0 index - desc.mCount = 1u; + desc.mAtlasId = foundAtlas + 1u; // Ids start from 1 not the 0 index + desc.mCount = 1u; // See if there's a previously freed image ID that we can assign to this new image uint32_t imageId = 0u; - for ( uint32_t i = 0u; i < mImageList.Size(); ++i ) + for(uint32_t i = 0u; i < mImageList.Size(); ++i) { - if ( !mImageList[ i ].mCount ) + if(!mImageList[i].mCount) { imageId = i + 1u; break; } } - if ( !imageId ) + if(!imageId) { - mImageList.PushBack( desc ); + mImageList.PushBack(desc); slot.mImageId = mImageList.Size(); } else { - mImageList[ imageId - 1u ] = desc; - slot.mImageId = imageId; + mImageList[imageId - 1u] = desc; + slot.mImageId = imageId; } slot.mAtlasId = foundAtlas + 1u; // Ids start from 1 not the 0 index // Upload the buffer image into the atlas - UploadImage( image, desc ); + UploadImage(image, desc); return created; } -AtlasManager::SizeType AtlasManager::CheckAtlas( SizeType atlas, - SizeType width, - SizeType height, - Pixel::Format pixelFormat ) +AtlasManager::SizeType AtlasManager::CheckAtlas(SizeType atlas, + SizeType width, + SizeType height, + Pixel::Format pixelFormat) { AtlasManager::SizeType result = 0u; - if ( pixelFormat == mAtlasList[ atlas ].mPixelFormat ) + if(pixelFormat == mAtlasList[atlas].mPixelFormat) { // Check to see if the image will fit in these blocks - const SizeType availableBlocks = mAtlasList[ atlas ].mAvailableBlocks + mAtlasList[ atlas ].mFreeBlocksList.Size(); + const SizeType availableBlocks = mAtlasList[atlas].mAvailableBlocks + mAtlasList[atlas].mFreeBlocksList.Size(); - if ( availableBlocks && IsBlockSizeSufficient( width, height,mAtlasList[ atlas ].mSize.mBlockWidth, mAtlasList[ atlas ].mSize.mBlockHeight ) ) + if(availableBlocks && IsBlockSizeSufficient(width, height, mAtlasList[atlas].mSize.mBlockWidth, mAtlasList[atlas].mSize.mBlockHeight)) { result = atlas + 1u; // Atlas ids start from 1 not 0 } @@ -250,111 +250,92 @@ AtlasManager::SizeType AtlasManager::CheckAtlas( SizeType atlas, return result; } -void AtlasManager::UploadImage( const PixelData& image, - const AtlasSlotDescriptor& desc ) +void AtlasManager::UploadImage(const PixelData& image, + const AtlasSlotDescriptor& desc) { // Get the atlas to upload the image to SizeType atlas = desc.mAtlasId - 1u; // Check to see that the pixel formats are compatible - if ( image.GetPixelFormat() != mAtlasList[ atlas ].mPixelFormat ) + if(image.GetPixelFormat() != mAtlasList[atlas].mPixelFormat) { DALI_LOG_ERROR("Cannot upload an image with a different PixelFormat to the Atlas.\n"); return; } - SizeType atlasBlockWidth = mAtlasList[ atlas ].mSize.mBlockWidth; - SizeType atlasBlockHeight = mAtlasList[ atlas ].mSize.mBlockHeight; - SizeType atlasWidthInBlocks = ( mAtlasList[ atlas ].mSize.mWidth - 1u ) / mAtlasList[ atlas ].mSize.mBlockWidth; + SizeType atlasBlockWidth = mAtlasList[atlas].mSize.mBlockWidth; + SizeType atlasBlockHeight = mAtlasList[atlas].mSize.mBlockHeight; + SizeType atlasWidthInBlocks = (mAtlasList[atlas].mSize.mWidth - 1u) / mAtlasList[atlas].mSize.mBlockWidth; - SizeType blockX = desc.mBlock % atlasWidthInBlocks; - SizeType blockY = desc.mBlock / atlasWidthInBlocks; - SizeType blockOffsetX = ( blockX * atlasBlockWidth ) + 1u; - SizeType blockOffsetY = ( blockY * atlasBlockHeight) + 1u; + SizeType blockX = desc.mBlock % atlasWidthInBlocks; + SizeType blockY = desc.mBlock / atlasWidthInBlocks; + SizeType blockOffsetX = (blockX * atlasBlockWidth) + 1u; + SizeType blockOffsetY = (blockY * atlasBlockHeight) + 1u; - SizeType width = image.GetWidth(); + SizeType width = image.GetWidth(); SizeType height = image.GetHeight(); // Blit image 1 pixel to the right and down into the block to compensate for texture filtering - if ( !mAtlasList[ atlas ].mAtlas.Upload( image, 0u, 0u, - blockOffsetX + SINGLE_PIXEL_PADDING, - blockOffsetY + SINGLE_PIXEL_PADDING, - width, height) ) + if(!mAtlasList[atlas].mAtlas.Upload(image, 0u, 0u, blockOffsetX + SINGLE_PIXEL_PADDING, blockOffsetY + SINGLE_PIXEL_PADDING, width, height)) { DALI_LOG_ERROR("Uploading image to Atlas Failed!.\n"); } // Blit top strip - if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mHorizontalStrip, 0u, 0u, - blockOffsetX, - blockOffsetY, - mAtlasList[ atlas ].mHorizontalStrip.GetWidth(), - mAtlasList[ atlas ].mHorizontalStrip.GetHeight()) ) + if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mHorizontalStrip, 0u, 0u, blockOffsetX, blockOffsetY, mAtlasList[atlas].mHorizontalStrip.GetWidth(), mAtlasList[atlas].mHorizontalStrip.GetHeight())) { DALI_LOG_ERROR("Uploading top strip to Atlas Failed!\n"); } // Blit left strip - if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mVerticalStrip, 0u, 0u, - blockOffsetX, - blockOffsetY + SINGLE_PIXEL_PADDING, - mAtlasList[ atlas ].mVerticalStrip.GetWidth(), - mAtlasList[ atlas ].mVerticalStrip.GetHeight() ) ) + if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mVerticalStrip, 0u, 0u, blockOffsetX, blockOffsetY + SINGLE_PIXEL_PADDING, mAtlasList[atlas].mVerticalStrip.GetWidth(), mAtlasList[atlas].mVerticalStrip.GetHeight())) { DALI_LOG_ERROR("Uploading left strip to Atlas Failed!\n"); } // Blit bottom strip - if ( blockOffsetY + height + DOUBLE_PIXEL_PADDING <= mAtlasList[ atlas ].mSize.mHeight ) + if(blockOffsetY + height + DOUBLE_PIXEL_PADDING <= mAtlasList[atlas].mSize.mHeight) { - if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mHorizontalStrip, 0u, 0u, - blockOffsetX, - blockOffsetY + height + SINGLE_PIXEL_PADDING, - mAtlasList[ atlas ].mHorizontalStrip.GetWidth(), - mAtlasList[ atlas ].mHorizontalStrip.GetHeight() ) ) + if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mHorizontalStrip, 0u, 0u, blockOffsetX, blockOffsetY + height + SINGLE_PIXEL_PADDING, mAtlasList[atlas].mHorizontalStrip.GetWidth(), mAtlasList[atlas].mHorizontalStrip.GetHeight())) { DALI_LOG_ERROR("Uploading bottom strip to Atlas Failed!.\n"); } } // Blit right strip - if ( blockOffsetX + width + DOUBLE_PIXEL_PADDING <= mAtlasList[ atlas ].mSize.mWidth ) + if(blockOffsetX + width + DOUBLE_PIXEL_PADDING <= mAtlasList[atlas].mSize.mWidth) { - if ( !mAtlasList[ atlas ].mAtlas.Upload( mAtlasList[ atlas ].mVerticalStrip, 0u, 0u, - blockOffsetX + width + SINGLE_PIXEL_PADDING, - blockOffsetY + SINGLE_PIXEL_PADDING, - mAtlasList[ atlas ].mVerticalStrip.GetWidth(), - mAtlasList[ atlas ].mVerticalStrip.GetHeight() ) ) + if(!mAtlasList[atlas].mAtlas.Upload(mAtlasList[atlas].mVerticalStrip, 0u, 0u, blockOffsetX + width + SINGLE_PIXEL_PADDING, blockOffsetY + SINGLE_PIXEL_PADDING, mAtlasList[atlas].mVerticalStrip.GetWidth(), mAtlasList[atlas].mVerticalStrip.GetHeight())) { DALI_LOG_ERROR("Uploading right strip to Atlas Failed!.\n"); } } } -void AtlasManager::GenerateMeshData( ImageId id, - const Vector2& position, - Toolkit::AtlasManager::Mesh2D& meshData, - bool addReference ) +void AtlasManager::GenerateMeshData(ImageId id, + const Vector2& position, + Toolkit::AtlasManager::Mesh2D& meshData, + bool addReference) { - if ( id ) + if(id) { // Read the atlas Id to use for this image SizeType imageId = id - 1u; - SizeType atlas = mImageList[ imageId ].mAtlasId - 1u; - SizeType width = mImageList[ imageId ].mImageWidth; - SizeType height = mImageList[ imageId ].mImageHeight; + SizeType atlas = mImageList[imageId].mAtlasId - 1u; + SizeType width = mImageList[imageId].mImageWidth; + SizeType height = mImageList[imageId].mImageHeight; - AtlasMeshFactory::CreateQuad( width, - height, - mImageList[ imageId ].mBlock, - mAtlasList[ atlas ].mSize, - position, - meshData ); + AtlasMeshFactory::CreateQuad(width, + height, + mImageList[imageId].mBlock, + mAtlasList[atlas].mSize, + position, + meshData); // Mesh created so increase the reference count, if we're asked to - if ( addReference ) + if(addReference) { - mImageList[ imageId ].mCount++; + mImageList[imageId].mCount++; } } else @@ -363,59 +344,59 @@ void AtlasManager::GenerateMeshData( ImageId id, } } -Dali::Texture AtlasManager::GetAtlasContainer( AtlasId atlas ) const +Dali::Texture AtlasManager::GetAtlasContainer(AtlasId atlas) const { - DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() ); + DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size()); Dali::Texture atlasContainer; - if ( atlas && atlas-- <= mAtlasList.size() ) + if(atlas && atlas-- <= mAtlasList.size()) { - atlasContainer = mAtlasList[ atlas ].mAtlas; + atlasContainer = mAtlasList[atlas].mAtlas; } return atlasContainer; } -bool AtlasManager::Remove( ImageId id ) +bool AtlasManager::Remove(ImageId id) { // Decrements the reference count of this image, and removes the blocks if zero. SizeType imageId = id - 1u; - bool removed = false; + bool removed = false; - if ( id > mImageList.Size() ) - { - DALI_LOG_ERROR("Atlas was asked to free an invalid imageID: %i\n", id ); + if(id > mImageList.Size()) + { + DALI_LOG_ERROR("Atlas was asked to free an invalid imageID: %i\n", id); return false; } // If we attempt to free an image that is already freed then do nothing, other than log - if ( !mImageList[ imageId ].mCount ) + if(!mImageList[imageId].mCount) { - DALI_LOG_ERROR("Atlas was asked to free an imageID: %i, that has already been freed!\n", id ); + DALI_LOG_ERROR("Atlas was asked to free an imageID: %i, that has already been freed!\n", id); return false; } - if ( 2u > --mImageList[ imageId ].mCount ) + if(2u > --mImageList[imageId].mCount) { // 'Remove the blocks' from this image and add to the atlas' freelist - removed = true; - mImageList[ imageId ].mCount = 0; - SizeType atlas = mImageList[ imageId ].mAtlasId - 1u; - mAtlasList[ atlas ].mFreeBlocksList.PushBack( mImageList[ imageId ].mBlock ); + removed = true; + mImageList[imageId].mCount = 0; + SizeType atlas = mImageList[imageId].mAtlasId - 1u; + mAtlasList[atlas].mFreeBlocksList.PushBack(mImageList[imageId].mBlock); } return removed; } -AtlasManager::AtlasId AtlasManager::GetAtlas( ImageId id ) const +AtlasManager::AtlasId AtlasManager::GetAtlas(ImageId id) const { - DALI_ASSERT_DEBUG( id && id <= mImageList.Size() ); + DALI_ASSERT_DEBUG(id && id <= mImageList.Size()); AtlasManager::AtlasId atlasId = 0u; - if ( id && id-- <= mImageList.Size() ) + if(id && id-- <= mImageList.Size()) { - atlasId = mImageList[ id ].mAtlasId; + atlasId = mImageList[id].mAtlasId; } return atlasId; } -void AtlasManager::SetNewAtlasSize( const Toolkit::AtlasManager::AtlasSize& size ) +void AtlasManager::SetNewAtlasSize(const Toolkit::AtlasManager::AtlasSize& size) { mNewAtlasSize = size; @@ -424,23 +405,23 @@ void AtlasManager::SetNewAtlasSize( const Toolkit::AtlasManager::AtlasSize& size mNewAtlasSize.mBlockHeight += DOUBLE_PIXEL_PADDING; } -const Toolkit::AtlasManager::AtlasSize& AtlasManager::GetAtlasSize( AtlasId atlas ) +const Toolkit::AtlasManager::AtlasSize& AtlasManager::GetAtlasSize(AtlasId atlas) { - DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() ); - if ( atlas && atlas-- <= mAtlasList.size() ) + DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size()); + if(atlas && atlas-- <= mAtlasList.size()) { - return mAtlasList[ atlas ].mSize; + return mAtlasList[atlas].mSize; } return EMPTY_SIZE; } -AtlasManager::SizeType AtlasManager::GetFreeBlocks( AtlasId atlas ) const +AtlasManager::SizeType AtlasManager::GetFreeBlocks(AtlasId atlas) const { - DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() ); + DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size()); AtlasManager::SizeType freeBlocks = 0u; - if ( atlas && atlas-- <= mAtlasList.size() ) + if(atlas && atlas-- <= mAtlasList.size()) { - freeBlocks = mAtlasList[ atlas ].mAvailableBlocks + mAtlasList[ atlas ].mFreeBlocksList.Size(); + freeBlocks = mAtlasList[atlas].mAvailableBlocks + mAtlasList[atlas].mFreeBlocksList.Size(); } return freeBlocks; } @@ -450,63 +431,62 @@ AtlasManager::SizeType AtlasManager::GetAtlasCount() const return mAtlasList.size(); } -Pixel::Format AtlasManager::GetPixelFormat( AtlasId atlas ) const +Pixel::Format AtlasManager::GetPixelFormat(AtlasId atlas) const { - DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() ); + DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size()); Pixel::Format pixelFormat = Pixel::RGBA8888; - if ( atlas && atlas-- <= mAtlasList.size() ) + if(atlas && atlas-- <= mAtlasList.size()) { - pixelFormat = mAtlasList[ atlas ].mPixelFormat; + pixelFormat = mAtlasList[atlas].mPixelFormat; } return pixelFormat; } -void AtlasManager::GetMetrics( Toolkit::AtlasManager::Metrics& metrics ) +void AtlasManager::GetMetrics(Toolkit::AtlasManager::Metrics& metrics) { Toolkit::AtlasManager::AtlasMetricsEntry entry; - uint32_t textureMemoryUsed = 0; - uint32_t atlasCount = mAtlasList.size(); - metrics.mAtlasCount = atlasCount; + uint32_t textureMemoryUsed = 0; + uint32_t atlasCount = mAtlasList.size(); + metrics.mAtlasCount = atlasCount; metrics.mAtlasMetrics.Resize(0); - for ( uint32_t i = 0; i < atlasCount; ++i ) + for(uint32_t i = 0; i < atlasCount; ++i) { - entry.mSize = mAtlasList[ i ].mSize; - entry.mTotalBlocks = mAtlasList[ i ].mTotalBlocks; - entry.mBlocksUsed = entry.mTotalBlocks - mAtlasList[ i ].mAvailableBlocks + mAtlasList[ i ].mFreeBlocksList.Size(); - entry.mPixelFormat = GetPixelFormat( i + 1 ); + entry.mSize = mAtlasList[i].mSize; + entry.mTotalBlocks = mAtlasList[i].mTotalBlocks; + entry.mBlocksUsed = entry.mTotalBlocks - mAtlasList[i].mAvailableBlocks + mAtlasList[i].mFreeBlocksList.Size(); + entry.mPixelFormat = GetPixelFormat(i + 1); - metrics.mAtlasMetrics.PushBack( entry ); + metrics.mAtlasMetrics.PushBack(entry); uint32_t size = entry.mSize.mWidth * entry.mSize.mHeight; - if ( entry.mPixelFormat == Pixel::BGRA8888 ) + if(entry.mPixelFormat == Pixel::BGRA8888) { size <<= 2; } textureMemoryUsed += size; - } metrics.mTextureMemoryUsed = textureMemoryUsed; } -TextureSet AtlasManager::GetTextures( AtlasId atlas ) const +TextureSet AtlasManager::GetTextures(AtlasId atlas) const { - DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() ); + DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size()); TextureSet textureSet; - if ( atlas && atlas-- <= mAtlasList.size() ) + if(atlas && atlas-- <= mAtlasList.size()) { - textureSet = mAtlasList[ atlas ].mTextureSet; + textureSet = mAtlasList[atlas].mTextureSet; } return textureSet; } -void AtlasManager::SetTextures( AtlasId atlas, TextureSet& textureSet ) +void AtlasManager::SetTextures(AtlasId atlas, TextureSet& textureSet) { - DALI_ASSERT_DEBUG( atlas && atlas <= mAtlasList.size() ); - if ( atlas && atlas-- <= mAtlasList.size() ) + DALI_ASSERT_DEBUG(atlas && atlas <= mAtlasList.size()); + if(atlas && atlas-- <= mAtlasList.size()) { - mAtlasList[ atlas ].mTextureSet = textureSet; + mAtlasList[atlas].mTextureSet = textureSet; } } @@ -515,5 +495,3 @@ void AtlasManager::SetTextures( AtlasId atlas, TextureSet& textureSet ) } // namespace Toolkit } // namespace Dali - - diff --git a/dali-toolkit/internal/text/rendering/atlas/atlas-manager.cpp b/dali-toolkit/internal/text/rendering/atlas/atlas-manager.cpp index 510da05..b883a8c 100644 --- a/dali-toolkit/internal/text/rendering/atlas/atlas-manager.cpp +++ b/dali-toolkit/internal/text/rendering/atlas/atlas-manager.cpp @@ -22,10 +22,8 @@ namespace Dali { - namespace Toolkit { - AtlasManager::AtlasManager() { } @@ -40,67 +38,67 @@ AtlasManager AtlasManager::New() return AtlasManager(internal.Get()); } -AtlasManager::AtlasManager(Internal::AtlasManager *impl) - : BaseHandle(impl) +AtlasManager::AtlasManager(Internal::AtlasManager* impl) +: BaseHandle(impl) { } -AtlasManager::AtlasId AtlasManager::CreateAtlas( const AtlasManager::AtlasSize& size, Pixel::Format pixelformat ) +AtlasManager::AtlasId AtlasManager::CreateAtlas(const AtlasManager::AtlasSize& size, Pixel::Format pixelformat) { - return GetImplementation(*this).CreateAtlas( size, pixelformat ); + return GetImplementation(*this).CreateAtlas(size, pixelformat); } -void AtlasManager::SetAddPolicy( AddFailPolicy policy ) +void AtlasManager::SetAddPolicy(AddFailPolicy policy) { - GetImplementation(*this).SetAddPolicy( policy ); + GetImplementation(*this).SetAddPolicy(policy); } -bool AtlasManager::Add( const PixelData& image, - AtlasManager::AtlasSlot& slot, - AtlasManager::AtlasId atlas ) +bool AtlasManager::Add(const PixelData& image, + AtlasManager::AtlasSlot& slot, + AtlasManager::AtlasId atlas) { - return GetImplementation(*this).Add( image, slot, atlas ); + return GetImplementation(*this).Add(image, slot, atlas); } -bool AtlasManager::Remove( ImageId id ) +bool AtlasManager::Remove(ImageId id) { - return GetImplementation(*this).Remove( id ); + return GetImplementation(*this).Remove(id); } -void AtlasManager::GenerateMeshData( ImageId id, - const Vector2& position, - Mesh2D& mesh, - bool addReference ) +void AtlasManager::GenerateMeshData(ImageId id, + const Vector2& position, + Mesh2D& mesh, + bool addReference) { - GetImplementation(*this).GenerateMeshData( id, - position, - mesh, - addReference ); + GetImplementation(*this).GenerateMeshData(id, + position, + mesh, + addReference); } -Dali::Texture AtlasManager::GetAtlasContainer( AtlasId atlas ) const +Dali::Texture AtlasManager::GetAtlasContainer(AtlasId atlas) const { - return GetImplementation(*this).GetAtlasContainer( atlas ); + return GetImplementation(*this).GetAtlasContainer(atlas); } -AtlasManager::AtlasId AtlasManager::GetAtlas( ImageId id ) +AtlasManager::AtlasId AtlasManager::GetAtlas(ImageId id) { - return GetImplementation(*this).GetAtlas( id ); + return GetImplementation(*this).GetAtlas(id); } -const AtlasManager::AtlasSize& AtlasManager::GetAtlasSize( AtlasId atlas ) +const AtlasManager::AtlasSize& AtlasManager::GetAtlasSize(AtlasId atlas) { - return GetImplementation(*this).GetAtlasSize( atlas ); + return GetImplementation(*this).GetAtlasSize(atlas); } -AtlasManager::SizeType AtlasManager::GetFreeBlocks( AtlasId atlas ) +AtlasManager::SizeType AtlasManager::GetFreeBlocks(AtlasId atlas) { - return GetImplementation(*this).GetFreeBlocks( atlas ); + return GetImplementation(*this).GetFreeBlocks(atlas); } -void AtlasManager::SetNewAtlasSize( const AtlasSize& size ) +void AtlasManager::SetNewAtlasSize(const AtlasSize& size) { - GetImplementation(*this).SetNewAtlasSize( size ); + GetImplementation(*this).SetNewAtlasSize(size); } AtlasManager::SizeType AtlasManager::GetAtlasCount() const @@ -108,24 +106,24 @@ AtlasManager::SizeType AtlasManager::GetAtlasCount() const return GetImplementation(*this).GetAtlasCount(); } -Pixel::Format AtlasManager::GetPixelFormat( AtlasId atlas ) const +Pixel::Format AtlasManager::GetPixelFormat(AtlasId atlas) const { - return GetImplementation(*this).GetPixelFormat( atlas ); + return GetImplementation(*this).GetPixelFormat(atlas); } -void AtlasManager::GetMetrics( Metrics& metrics ) +void AtlasManager::GetMetrics(Metrics& metrics) { - GetImplementation(*this).GetMetrics( metrics ); + GetImplementation(*this).GetMetrics(metrics); } -TextureSet AtlasManager::GetTextures( AtlasId atlas ) const +TextureSet AtlasManager::GetTextures(AtlasId atlas) const { - return GetImplementation(*this).GetTextures( atlas ); + return GetImplementation(*this).GetTextures(atlas); } -void AtlasManager::SetTextures( AtlasId atlas, TextureSet& textureSet ) +void AtlasManager::SetTextures(AtlasId atlas, TextureSet& textureSet) { - GetImplementation(*this).SetTextures( atlas, textureSet ); + GetImplementation(*this).SetTextures(atlas, textureSet); } } // namespace Toolkit diff --git a/dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.cpp b/dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.cpp index 4017f79..ac1c9bc 100644 --- a/dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.cpp +++ b/dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.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,142 +19,138 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace AtlasMeshFactory { - -void CreateQuad( SizeType imageWidth, - SizeType imageHeight, - SizeType block, - const Toolkit::AtlasManager::AtlasSize& atlasSize, - const Vector2& position, - Toolkit::AtlasManager::Mesh2D& mesh ) +void CreateQuad(SizeType imageWidth, + SizeType imageHeight, + SizeType block, + const Toolkit::AtlasManager::AtlasSize& atlasSize, + const Vector2& position, + Toolkit::AtlasManager::Mesh2D& mesh) { Toolkit::AtlasManager::Vertex2D vertex; - SizeType blockWidth = atlasSize.mBlockWidth; + SizeType blockWidth = atlasSize.mBlockWidth; SizeType blockHeight = atlasSize.mBlockHeight; - float vertexBlockWidth = static_cast< float >( blockWidth ); - float vertexBlockHeight = static_cast< float >( blockHeight ); + float vertexBlockWidth = static_cast(blockWidth); + float vertexBlockHeight = static_cast(blockHeight); - SizeType atlasWidth = atlasSize.mWidth; + SizeType atlasWidth = atlasSize.mWidth; SizeType atlasHeight = atlasSize.mHeight; - SizeType atlasWidthInBlocks = ( atlasWidth - 1u ) / blockWidth; + SizeType atlasWidthInBlocks = (atlasWidth - 1u) / blockWidth; // Get the normalized size of a texel in both directions - float texelX = 1.0f / static_cast< float >( atlasWidth ); - float texelY = 1.0f / static_cast< float >( atlasHeight ); + float texelX = 1.0f / static_cast(atlasWidth); + float texelY = 1.0f / static_cast(atlasHeight); - float oneAndAHalfTexelX = texelX + ( texelX * 0.5f ); - float oneAndAHalfTexelY = texelY + ( texelY * 0.5f ); + float oneAndAHalfTexelX = texelX + (texelX * 0.5f); + float oneAndAHalfTexelY = texelY + (texelY * 0.5f); - float texelBlockWidth = texelX * vertexBlockWidth; + float texelBlockWidth = texelX * vertexBlockWidth; float texelBlockHeight = texelY * vertexBlockHeight; uint32_t pixelsX = imageWidth % blockWidth; uint32_t pixelsY = imageHeight % blockHeight; - if ( !pixelsX ) + if(!pixelsX) { pixelsX = blockWidth; } - if ( !pixelsY ) + if(!pixelsY) { pixelsY = blockHeight; } - float vertexWidth = static_cast< float >( pixelsX ); - float vertexHeight = static_cast< float >( pixelsY ); - float texelWidth = texelX * vertexWidth; - float texelHeight = texelY * vertexHeight; + float vertexWidth = static_cast(pixelsX); + float vertexHeight = static_cast(pixelsY); + float texelWidth = texelX * vertexWidth; + float texelHeight = texelY * vertexHeight; // We're going to 'blit' half a pixel more on each edge vertexWidth++; vertexHeight++; // Move back half a pixel - Vector2 topLeft = Vector2( position.x - 0.5f, position.y - 0.5f ); + Vector2 topLeft = Vector2(position.x - 0.5f, position.y - 0.5f); - float fBlockX = texelBlockWidth * static_cast< float >( block % atlasWidthInBlocks ); + float fBlockX = texelBlockWidth * static_cast(block % atlasWidthInBlocks); // In the next expression, we have purposely made ( block / atlasWidthInBlocks ) yield an integer value and then convert to float as // we do not want the remainder in that expression to affect the value of fBlockY - float fBlockY = texelBlockHeight * static_cast< float >( block / atlasWidthInBlocks ); + float fBlockY = texelBlockHeight * static_cast(block / atlasWidthInBlocks); // Add on texture filtering compensation ( half a texel plus compensation for filled pixel in top left corner ) fBlockX += oneAndAHalfTexelX; fBlockY += oneAndAHalfTexelY; - float texelWidthOffset = texelWidth + texelX; + float texelWidthOffset = texelWidth + texelX; float texelHeightOffset = texelHeight + texelY; // Top left - vertex.mPosition.x = topLeft.x; - vertex.mPosition.y = topLeft.y; + vertex.mPosition.x = topLeft.x; + vertex.mPosition.y = topLeft.y; vertex.mTexCoords.x = fBlockX; vertex.mTexCoords.y = fBlockY; - mesh.mVertices.Reserve( 4u ); - mesh.mVertices.PushBack( vertex ); + mesh.mVertices.Reserve(4u); + mesh.mVertices.PushBack(vertex); // Top Right - vertex.mPosition.x = topLeft.x + vertexWidth; - vertex.mPosition.y = topLeft.y; + vertex.mPosition.x = topLeft.x + vertexWidth; + vertex.mPosition.y = topLeft.y; vertex.mTexCoords.x = fBlockX + texelWidthOffset; vertex.mTexCoords.y = fBlockY; - mesh.mVertices.PushBack( vertex ); + mesh.mVertices.PushBack(vertex); // Bottom Left - vertex.mPosition.x = topLeft.x; - vertex.mPosition.y = topLeft.y + vertexHeight; + vertex.mPosition.x = topLeft.x; + vertex.mPosition.y = topLeft.y + vertexHeight; vertex.mTexCoords.x = fBlockX; vertex.mTexCoords.y = fBlockY + texelHeightOffset; - mesh.mVertices.PushBack( vertex ); + mesh.mVertices.PushBack(vertex); // Bottom Right - vertex.mPosition.x = topLeft.x + vertexWidth; - vertex.mPosition.y = topLeft.y + vertexHeight; + vertex.mPosition.x = topLeft.x + vertexWidth; + vertex.mPosition.y = topLeft.y + vertexHeight; vertex.mTexCoords.x = fBlockX + texelWidthOffset; vertex.mTexCoords.y = fBlockY + texelHeightOffset; - mesh.mVertices.PushBack( vertex ); + mesh.mVertices.PushBack(vertex); // Six indices in counter clockwise winding - mesh.mIndices.Reserve( 6u ); - mesh.mIndices.PushBack( 1u ); - mesh.mIndices.PushBack( 0u ); - mesh.mIndices.PushBack( 2u ); - mesh.mIndices.PushBack( 2u ); - mesh.mIndices.PushBack( 3u ); - mesh.mIndices.PushBack( 1u ); + mesh.mIndices.Reserve(6u); + mesh.mIndices.PushBack(1u); + mesh.mIndices.PushBack(0u); + mesh.mIndices.PushBack(2u); + mesh.mIndices.PushBack(2u); + mesh.mIndices.PushBack(3u); + mesh.mIndices.PushBack(1u); } -void AppendMesh( Toolkit::AtlasManager::Mesh2D& first, - const Toolkit::AtlasManager::Mesh2D& second ) +void AppendMesh(Toolkit::AtlasManager::Mesh2D& first, + const Toolkit::AtlasManager::Mesh2D& second) { const uint32_t verticesCount = first.mVertices.Size(); - first.mVertices.Insert( first.mVertices.End(), - second.mVertices.Begin(), - second.mVertices.End() ); + first.mVertices.Insert(first.mVertices.End(), + second.mVertices.Begin(), + second.mVertices.End()); const uint32_t indicesCount = first.mIndices.Size(); - first.mIndices.Insert( first.mIndices.End(), - second.mIndices.Begin(), - second.mIndices.End() ); - - for( Vector::Iterator it = first.mIndices.Begin() + indicesCount, - endIt = first.mIndices.End(); - it != endIt; - ++it ) + first.mIndices.Insert(first.mIndices.End(), + second.mIndices.Begin(), + second.mIndices.End()); + + for(Vector::Iterator it = first.mIndices.Begin() + indicesCount, + endIt = first.mIndices.End(); + it != endIt; + ++it) { *it += verticesCount; } diff --git a/dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.cpp b/dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.cpp old mode 100755 new mode 100644 index 80a1111..6b1d82b --- a/dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.cpp +++ b/dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.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,19 +19,19 @@ #include // EXTERNAL INCLUDES -#include -#include #include #include #include +#include +#include // INTERNAL INCLUDES #include +#include #include #include #include #include -#include using namespace Dali; using namespace Dali::Toolkit; @@ -40,16 +40,16 @@ using namespace Dali::Toolkit::Text; namespace { #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_RENDERING"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_RENDERING"); #endif -const float ZERO( 0.0f ); -const float HALF( 0.5f ); -const float ONE( 1.0f ); -const uint32_t DEFAULT_ATLAS_WIDTH = 512u; +const float ZERO(0.0f); +const float HALF(0.5f); +const float ONE(1.0f); +const uint32_t DEFAULT_ATLAS_WIDTH = 512u; const uint32_t DEFAULT_ATLAS_HEIGHT = 512u; -const uint16_t NO_OUTLINE = 0u; -} +const uint16_t NO_OUTLINE = 0u; +} // namespace struct AtlasRenderer::Impl { @@ -62,11 +62,11 @@ struct AtlasRenderer::Impl struct MeshRecord { MeshRecord() - : mAtlasId( 0u ) + : mAtlasId(0u) { } - uint32_t mAtlasId; + uint32_t mAtlasId; AtlasManager::Mesh2D mMesh; }; @@ -77,33 +77,33 @@ struct AtlasRenderer::Impl struct Extent { Extent() - : mBaseLine( 0.0f ), - mLeft( 0.0f ), - mRight( 0.0f ), - mUnderlinePosition( 0.0f ), - mUnderlineThickness( 0.0f ), - mMeshRecordIndex( 0u ) + : mBaseLine(0.0f), + mLeft(0.0f), + mRight(0.0f), + mUnderlinePosition(0.0f), + mUnderlineThickness(0.0f), + mMeshRecordIndex(0u) { } - float mBaseLine; - float mLeft; - float mRight; - float mUnderlinePosition; - float mUnderlineThickness; + float mBaseLine; + float mLeft; + float mRight; + float mUnderlinePosition; + float mUnderlineThickness; uint32_t mMeshRecordIndex; }; struct MaxBlockSize { MaxBlockSize() - : mFontId( 0 ), - mNeededBlockWidth( 0 ), - mNeededBlockHeight( 0 ) + : mFontId(0), + mNeededBlockWidth(0), + mNeededBlockHeight(0) { } - FontId mFontId; + FontId mFontId; uint32_t mNeededBlockWidth; uint32_t mNeededBlockHeight; }; @@ -111,57 +111,57 @@ struct AtlasRenderer::Impl struct CheckEntry { CheckEntry() - : mFontId( 0 ), - mIndex( 0 ) + : mFontId(0), + mIndex(0) { } - FontId mFontId; + FontId mFontId; Text::GlyphIndex mIndex; }; struct TextCacheEntry { TextCacheEntry() - : mFontId{ 0u }, - mIndex{ 0u }, - mImageId{ 0u }, - mOutlineWidth{ 0u }, - isItalic{ false }, - isBold{ false } + : mFontId{0u}, + mIndex{0u}, + mImageId{0u}, + mOutlineWidth{0u}, + isItalic{false}, + isBold{false} { } - FontId mFontId; + FontId mFontId; Text::GlyphIndex mIndex; - uint32_t mImageId; - uint16_t mOutlineWidth; - bool isItalic:1; - bool isBold:1; + uint32_t mImageId; + uint16_t mOutlineWidth; + bool isItalic : 1; + bool isBold : 1; }; Impl() - : mDepth( 0 ) + : mDepth(0) { mGlyphManager = AtlasGlyphManager::Get(); - mFontClient = TextAbstraction::FontClient::Get(); + mFontClient = TextAbstraction::FontClient::Get(); - mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2; - mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2; - mQuadVertexFormat[ "aColor" ] = Property::VECTOR4; + mQuadVertexFormat["aPosition"] = Property::VECTOR2; + mQuadVertexFormat["aTexCoord"] = Property::VECTOR2; + mQuadVertexFormat["aColor"] = Property::VECTOR4; } - bool IsGlyphUnderlined( GlyphIndex index, - const Vector& underlineRuns ) + bool IsGlyphUnderlined(GlyphIndex index, + const Vector& underlineRuns) { - for( Vector::ConstIterator it = underlineRuns.Begin(), - endIt = underlineRuns.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = underlineRuns.Begin(), + endIt = underlineRuns.End(); + it != endIt; + ++it) { const GlyphRun& run = *it; - if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) ) + if((run.glyphIndex <= index) && (index < run.glyphIndex + run.numberOfGlyphs)) { return true; } @@ -170,28 +170,28 @@ struct AtlasRenderer::Impl return false; } - void CacheGlyph( const GlyphInfo& glyph, FontId lastFontId, const AtlasGlyphManager::GlyphStyle& style, AtlasManager::AtlasSlot& slot ) + void CacheGlyph(const GlyphInfo& glyph, FontId lastFontId, const AtlasGlyphManager::GlyphStyle& style, AtlasManager::AtlasSlot& slot) { - const bool glyphNotCached = !mGlyphManager.IsCached( glyph.fontId, glyph.index, style, slot ); // Check FontGlyphRecord vector for entry with glyph index and fontId + const bool glyphNotCached = !mGlyphManager.IsCached(glyph.fontId, glyph.index, style, slot); // Check FontGlyphRecord vector for entry with glyph index and fontId - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "AddGlyphs fontID[%u] glyphIndex[%u] [%s]\n", glyph.fontId, glyph.index, (glyphNotCached)?"not cached":"cached" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "AddGlyphs fontID[%u] glyphIndex[%u] [%s]\n", glyph.fontId, glyph.index, (glyphNotCached) ? "not cached" : "cached"); - if( glyphNotCached ) + if(glyphNotCached) { MaxBlockSize& blockSize = mBlockSizes[0u]; - if ( lastFontId != glyph.fontId ) + if(lastFontId != glyph.fontId) { uint32_t index = 0u; // Looks through all stored block sizes until finds the one which mataches required glyph font it. Ensures new atlas block size will match existing for same font id. // CalculateBlocksSize() above ensures a block size entry exists. - for( std::vector::const_iterator it = mBlockSizes.begin(), - endIt = mBlockSizes.end(); - it != endIt; - ++it, ++index ) + for(std::vector::const_iterator it = mBlockSizes.begin(), + endIt = mBlockSizes.end(); + it != endIt; + ++it, ++index) { const MaxBlockSize& blockSizeEntry = *it; - if( blockSizeEntry.mFontId == glyph.fontId ) + if(blockSizeEntry.mFontId == glyph.fontId) { blockSize = mBlockSizes[index]; } @@ -205,39 +205,39 @@ struct AtlasRenderer::Impl const bool isOutline = 0u != style.outline; // Whether the current glyph is a color one. - const bool isColorGlyph = mFontClient.IsColorGlyph( glyph.fontId, glyph.index ); + const bool isColorGlyph = mFontClient.IsColorGlyph(glyph.fontId, glyph.index); - if( !isOutline || ( isOutline && !isColorGlyph) ) + if(!isOutline || (isOutline && !isColorGlyph)) { // Retrieve the emoji's bitmap. TextAbstraction::FontClient::GlyphBufferData glyphBufferData; - glyphBufferData.width = isColorGlyph ? glyph.width : 0; // Desired width and height. + glyphBufferData.width = isColorGlyph ? glyph.width : 0; // Desired width and height. glyphBufferData.height = isColorGlyph ? glyph.height : 0; - mFontClient.CreateBitmap( glyph.fontId, - glyph.index, - glyph.isItalicRequired, - glyph.isBoldRequired, - glyphBufferData, - style.outline ); + mFontClient.CreateBitmap(glyph.fontId, + glyph.index, + glyph.isItalicRequired, + glyph.isBoldRequired, + glyphBufferData, + style.outline); // Create the pixel data. - bitmap = PixelData::New( glyphBufferData.buffer, - glyphBufferData.width * glyphBufferData.height * GetBytesPerPixel( glyphBufferData.format ), - glyphBufferData.width, - glyphBufferData.height, - glyphBufferData.format, - PixelData::DELETE_ARRAY ); - - if( bitmap ) + bitmap = PixelData::New(glyphBufferData.buffer, + glyphBufferData.width * glyphBufferData.height * GetBytesPerPixel(glyphBufferData.format), + glyphBufferData.width, + glyphBufferData.height, + glyphBufferData.format, + PixelData::DELETE_ARRAY); + + if(bitmap) { // Ensure that the next image will fit into the current block size - if( bitmap.GetWidth() > blockSize.mNeededBlockWidth ) + if(bitmap.GetWidth() > blockSize.mNeededBlockWidth) { blockSize.mNeededBlockWidth = bitmap.GetWidth(); } - if( bitmap.GetHeight() > blockSize.mNeededBlockHeight ) + if(bitmap.GetHeight() > blockSize.mNeededBlockHeight) { blockSize.mNeededBlockHeight = bitmap.GetHeight(); } @@ -245,146 +245,147 @@ struct AtlasRenderer::Impl // If CheckAtlas in AtlasManager::Add can't fit the bitmap in the current atlas it will create a new atlas // Setting the block size and size of new atlas does not mean a new one will be created. An existing atlas may still surffice. - mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH, - DEFAULT_ATLAS_HEIGHT, - blockSize.mNeededBlockWidth, - blockSize.mNeededBlockHeight ); + mGlyphManager.SetNewAtlasSize(DEFAULT_ATLAS_WIDTH, + DEFAULT_ATLAS_HEIGHT, + blockSize.mNeededBlockWidth, + blockSize.mNeededBlockHeight); // Locate a new slot for our glyph - mGlyphManager.Add( glyph, style, bitmap, slot ); // slot will be 0 is glyph not added + mGlyphManager.Add(glyph, style, bitmap, slot); // slot will be 0 is glyph not added } } } else { // We have 2+ copies of the same glyph - mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, style, 1 ); //increment + mGlyphManager.AdjustReferenceCount(glyph.fontId, glyph.index, style, 1); //increment } } - void GenerateMesh( const GlyphInfo& glyph, - const Vector2& position, - const Vector4& color, - uint16_t outline, - AtlasManager::AtlasSlot& slot, - bool underlineGlyph, - float currentUnderlinePosition, - float currentUnderlineThickness, - std::vector& meshContainer, - Vector& newTextCache, - Vector& extents ) + void GenerateMesh(const GlyphInfo& glyph, + const Vector2& position, + const Vector4& color, + uint16_t outline, + AtlasManager::AtlasSlot& slot, + bool underlineGlyph, + float currentUnderlinePosition, + float currentUnderlineThickness, + std::vector& meshContainer, + Vector& newTextCache, + Vector& extents) { // Generate mesh data for this quad, plugging in our supplied position AtlasManager::Mesh2D newMesh; - mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh ); + mGlyphManager.GenerateMeshData(slot.mImageId, position, newMesh); TextCacheEntry textCacheEntry; - textCacheEntry.mFontId = glyph.fontId; - textCacheEntry.mImageId = slot.mImageId; - textCacheEntry.mIndex = glyph.index; + textCacheEntry.mFontId = glyph.fontId; + textCacheEntry.mImageId = slot.mImageId; + textCacheEntry.mIndex = glyph.index; textCacheEntry.mOutlineWidth = outline; - textCacheEntry.isItalic = glyph.isItalicRequired; - textCacheEntry.isBold = glyph.isBoldRequired; + textCacheEntry.isItalic = glyph.isItalicRequired; + textCacheEntry.isBold = glyph.isBoldRequired; - newTextCache.PushBack( textCacheEntry ); + newTextCache.PushBack(textCacheEntry); AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin(); - for( unsigned int index = 0u, size = newMesh.mVertices.Count(); - index < size; - ++index ) + for(unsigned int index = 0u, size = newMesh.mVertices.Count(); + index < size; + ++index) { - AtlasManager::Vertex2D& vertex = *( verticesBuffer + index ); + AtlasManager::Vertex2D& vertex = *(verticesBuffer + index); // Set the color of the vertex. vertex.mColor = color; } // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas) - StitchTextMesh( meshContainer, - newMesh, - extents, - position.y + glyph.yBearing, - underlineGlyph, - currentUnderlinePosition, - currentUnderlineThickness, - slot ); + StitchTextMesh(meshContainer, + newMesh, + extents, + position.y + glyph.yBearing, + underlineGlyph, + currentUnderlinePosition, + currentUnderlineThickness, + slot); } - void CreateActors( const std::vector& meshContainer, - const Size& textSize, - const Vector4& color, - const Vector4& shadowColor, - const Vector2& shadowOffset, - Actor textControl, - Property::Index animatablePropertyIndex, - bool drawShadow ) + void CreateActors(const std::vector& meshContainer, + const Size& textSize, + const Vector4& color, + const Vector4& shadowColor, + const Vector2& shadowOffset, + Actor textControl, + Property::Index animatablePropertyIndex, + bool drawShadow) { - if( !mActor ) + if(!mActor) { // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues. mActor = Actor::New(); - mActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - mActor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - mActor.SetProperty( Actor::Property::SIZE, textSize ); - mActor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR ); + mActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + mActor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + mActor.SetProperty(Actor::Property::SIZE, textSize); + mActor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR); } - for( std::vector< MeshRecord >::const_iterator it = meshContainer.begin(), - endIt = meshContainer.end(); - it != endIt; ++it ) + for(std::vector::const_iterator it = meshContainer.begin(), + endIt = meshContainer.end(); + it != endIt; + ++it) { const MeshRecord& meshRecord = *it; - Actor actor = CreateMeshActor( textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_NORMAL ); + Actor actor = CreateMeshActor(textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_NORMAL); // Whether the actor has renderers. const bool hasRenderer = actor.GetRendererCount() > 0u; // Create an effect if necessary - if( hasRenderer && - drawShadow ) + if(hasRenderer && + drawShadow) { // Change the color of the vertices. - for( Vector::Iterator vIt = meshRecord.mMesh.mVertices.Begin(), - vEndIt = meshRecord.mMesh.mVertices.End(); - vIt != vEndIt; - ++vIt ) + for(Vector::Iterator vIt = meshRecord.mMesh.mVertices.Begin(), + vEndIt = meshRecord.mMesh.mVertices.End(); + vIt != vEndIt; + ++vIt) { AtlasManager::Vertex2D& vertex = *vIt; vertex.mColor = shadowColor; } - Actor shadowActor = CreateMeshActor(textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_DROP_SHADOW ); + Actor shadowActor = CreateMeshActor(textControl, animatablePropertyIndex, color, meshRecord, textSize, STYLE_DROP_SHADOW); #if defined(DEBUG_ENABLED) - shadowActor.SetProperty( Dali::Actor::Property::NAME, "Text Shadow renderable actor" ); + shadowActor.SetProperty(Dali::Actor::Property::NAME, "Text Shadow renderable actor"); #endif // Offset shadow in x and y - shadowActor.RegisterProperty("uOffset", shadowOffset ); - Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) ); - int depthIndex = renderer.GetProperty(Dali::Renderer::Property::DEPTH_INDEX); - renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 ); - mActor.Add( shadowActor ); + shadowActor.RegisterProperty("uOffset", shadowOffset); + Dali::Renderer renderer(shadowActor.GetRendererAt(0)); + int depthIndex = renderer.GetProperty(Dali::Renderer::Property::DEPTH_INDEX); + renderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1); + mActor.Add(shadowActor); } - if( hasRenderer ) + if(hasRenderer) { - mActor.Add( actor ); + mActor.Add(actor); } } } - void AddGlyphs( Text::ViewInterface& view, - Actor textControl, - Property::Index animatablePropertyIndex, - const Vector& positions, - const Vector& glyphs, - const Vector4& defaultColor, - const Vector4* const colorsBuffer, - const ColorIndex* const colorIndicesBuffer, - int depth, - float minLineOffset ) + void AddGlyphs(Text::ViewInterface& view, + Actor textControl, + Property::Index animatablePropertyIndex, + const Vector& positions, + const Vector& glyphs, + const Vector4& defaultColor, + const Vector4* const colorsBuffer, + const ColorIndex* const colorIndicesBuffer, + int depth, + float minLineOffset) { AtlasManager::AtlasSlot slot; slot.mImageId = 0u; @@ -394,93 +395,93 @@ struct AtlasRenderer::Impl slotOutline.mImageId = 0u; slotOutline.mAtlasId = 0u; - std::vector< MeshRecord > meshContainer; - std::vector< MeshRecord > meshContainerOutline; - Vector< Extent > extents; + std::vector meshContainer; + std::vector meshContainerOutline; + Vector extents; mDepth = depth; - const Vector2& textSize( view.GetLayoutSize() ); - const Vector2 halfTextSize( textSize * 0.5f ); - const Vector2& shadowOffset( view.GetShadowOffset() ); - const Vector4& shadowColor( view.GetShadowColor() ); - const bool underlineEnabled = view.IsUnderlineEnabled(); - const Vector4& underlineColor( view.GetUnderlineColor() ); - const float underlineHeight = view.GetUnderlineHeight(); - const uint16_t outlineWidth = view.GetOutlineWidth(); - const Vector4& outlineColor( view.GetOutlineColor() ); - const bool isOutline = 0u != outlineWidth; + const Vector2& textSize(view.GetLayoutSize()); + const Vector2 halfTextSize(textSize * 0.5f); + const Vector2& shadowOffset(view.GetShadowOffset()); + const Vector4& shadowColor(view.GetShadowColor()); + const bool underlineEnabled = view.IsUnderlineEnabled(); + const Vector4& underlineColor(view.GetUnderlineColor()); + const float underlineHeight = view.GetUnderlineHeight(); + const uint16_t outlineWidth = view.GetOutlineWidth(); + const Vector4& outlineColor(view.GetOutlineColor()); + const bool isOutline = 0u != outlineWidth; - const bool useDefaultColor = ( NULL == colorsBuffer ); + const bool useDefaultColor = (NULL == colorsBuffer); // Get the underline runs. - const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns(); + const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns(); Vector underlineRuns; - underlineRuns.Resize( numberOfUnderlineRuns ); - view.GetUnderlineRuns( underlineRuns.Begin(), - 0u, - numberOfUnderlineRuns ); + underlineRuns.Resize(numberOfUnderlineRuns); + view.GetUnderlineRuns(underlineRuns.Begin(), + 0u, + numberOfUnderlineRuns); bool thereAreUnderlinedGlyphs = false; - float currentUnderlinePosition = ZERO; - float currentUnderlineThickness = underlineHeight; - FontId lastFontId = 0; - FontId lastUnderlinedFontId = 0; - Style style = STYLE_NORMAL; + float currentUnderlinePosition = ZERO; + float currentUnderlineThickness = underlineHeight; + FontId lastFontId = 0; + FontId lastUnderlinedFontId = 0; + Style style = STYLE_NORMAL; - if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 ) + if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1) { style = STYLE_DROP_SHADOW; } - CalculateBlocksSize( glyphs ); + CalculateBlocksSize(glyphs); // Avoid emptying mTextCache (& removing references) until after incremented references for the new text - Vector< TextCacheEntry > newTextCache; - const GlyphInfo* const glyphsBuffer = glyphs.Begin(); - const Vector2* const positionsBuffer = positions.Begin(); - const Vector2 lineOffsetPosition( minLineOffset, 0.f ); + Vector newTextCache; + const GlyphInfo* const glyphsBuffer = glyphs.Begin(); + const Vector2* const positionsBuffer = positions.Begin(); + const Vector2 lineOffsetPosition(minLineOffset, 0.f); - for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i ) + for(uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i) { - const GlyphInfo& glyph = *( glyphsBuffer + i ); - const bool isGlyphUnderlined = underlineEnabled || IsGlyphUnderlined( i, underlineRuns ); - thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || isGlyphUnderlined; + const GlyphInfo& glyph = *(glyphsBuffer + i); + const bool isGlyphUnderlined = underlineEnabled || IsGlyphUnderlined(i, underlineRuns); + thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || isGlyphUnderlined; // No operation for white space - if( glyph.width && glyph.height ) + if(glyph.width && glyph.height) { // Are we still using the same fontId as previous - if( isGlyphUnderlined && ( glyph.fontId != lastUnderlinedFontId ) ) + if(isGlyphUnderlined && (glyph.fontId != lastUnderlinedFontId)) { // We need to fetch fresh font underline metrics FontMetrics fontMetrics; - mFontClient.GetFontMetrics( glyph.fontId, fontMetrics ); - currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) ); - const float descender = ceil( fabsf( fontMetrics.descender ) ); + mFontClient.GetFontMetrics(glyph.fontId, fontMetrics); + currentUnderlinePosition = ceil(fabsf(fontMetrics.underlinePosition)); + const float descender = ceil(fabsf(fontMetrics.descender)); - if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 ) + if(fabsf(underlineHeight) < Math::MACHINE_EPSILON_1000) { currentUnderlineThickness = fontMetrics.underlineThickness; // Ensure underline will be at least a pixel high - if ( currentUnderlineThickness < ONE ) + if(currentUnderlineThickness < ONE) { currentUnderlineThickness = ONE; } else { - currentUnderlineThickness = ceil( currentUnderlineThickness ); + currentUnderlineThickness = ceil(currentUnderlineThickness); } } // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font - if( currentUnderlinePosition > descender ) + if(currentUnderlinePosition > descender) { currentUnderlinePosition = descender; } - if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 ) + if(fabsf(currentUnderlinePosition) < Math::MACHINE_EPSILON_1000) { // Move offset down by one ( EFL behavior ) currentUnderlinePosition = ONE; @@ -491,256 +492,244 @@ struct AtlasRenderer::Impl AtlasGlyphManager::GlyphStyle style; style.isItalic = glyph.isItalicRequired; - style.isBold = glyph.isBoldRequired; + style.isBold = glyph.isBoldRequired; // Retrieves and caches the glyph's bitmap. - CacheGlyph( glyph, lastFontId, style, slot ); + CacheGlyph(glyph, lastFontId, style, slot); // Retrieves and caches the outline glyph's bitmap. - if( isOutline ) + if(isOutline) { style.outline = outlineWidth; - CacheGlyph( glyph, lastFontId, style, slotOutline ); + CacheGlyph(glyph, lastFontId, style, slotOutline); } // Move the origin (0,0) of the mesh to the center of the actor - const Vector2& temp = *( positionsBuffer + i ); - const Vector2 position = Vector2( roundf( temp.x ), temp.y ) - halfTextSize - lineOffsetPosition; // roundf() avoids pixel alignment issues. + const Vector2& temp = *(positionsBuffer + i); + const Vector2 position = Vector2(roundf(temp.x), temp.y) - halfTextSize - lineOffsetPosition; // roundf() avoids pixel alignment issues. - if ( 0u != slot.mImageId ) // invalid slot id, glyph has failed to be added to atlas + if(0u != slot.mImageId) // invalid slot id, glyph has failed to be added to atlas { Vector2 positionPlusOutlineOffset = position; - if( isOutline ) + if(isOutline) { // Add an offset to the text. - const float outlineWidthOffset = static_cast( outlineWidth ); - positionPlusOutlineOffset += Vector2( outlineWidthOffset, outlineWidthOffset ); + const float outlineWidthOffset = static_cast(outlineWidth); + positionPlusOutlineOffset += Vector2(outlineWidthOffset, outlineWidthOffset); } // Get the color of the character. - const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i ); - const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u ); - - GenerateMesh( glyph, - positionPlusOutlineOffset, - color, - NO_OUTLINE, - slot, - isGlyphUnderlined, - currentUnderlinePosition, - currentUnderlineThickness, - meshContainer, - newTextCache, - extents); + const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndicesBuffer + i); + const Vector4& color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + colorIndex - 1u); + + GenerateMesh(glyph, + positionPlusOutlineOffset, + color, + NO_OUTLINE, + slot, + isGlyphUnderlined, + currentUnderlinePosition, + currentUnderlineThickness, + meshContainer, + newTextCache, + extents); lastFontId = glyph.fontId; // Prevents searching for existing blocksizes when string of the same fontId. } - if( isOutline && ( 0u != slotOutline.mImageId ) ) // invalid slot id, glyph has failed to be added to atlas + if(isOutline && (0u != slotOutline.mImageId)) // invalid slot id, glyph has failed to be added to atlas { - GenerateMesh( glyph, - position, - outlineColor, - outlineWidth, - slotOutline, - false, - currentUnderlinePosition, - currentUnderlineThickness, - meshContainerOutline, - newTextCache, - extents); + GenerateMesh(glyph, + position, + outlineColor, + outlineWidth, + slotOutline, + false, + currentUnderlinePosition, + currentUnderlineThickness, + meshContainerOutline, + newTextCache, + extents); } } } // glyphs // Now remove references for the old text RemoveText(); - mTextCache.Swap( newTextCache ); + mTextCache.Swap(newTextCache); - if( thereAreUnderlinedGlyphs ) + if(thereAreUnderlinedGlyphs) { // Check to see if any of the text needs an underline - GenerateUnderlines( meshContainer, extents, underlineColor ); + GenerateUnderlines(meshContainer, extents, underlineColor); } // For each MeshData object, create a mesh actor and add to the renderable actor bool isShadowDrawn = false; - if( !meshContainerOutline.empty() ) + if(!meshContainerOutline.empty()) { const bool drawShadow = STYLE_DROP_SHADOW == style; - CreateActors( meshContainerOutline, - textSize, - outlineColor, - shadowColor, - shadowOffset, - textControl, - animatablePropertyIndex, - drawShadow ); + CreateActors(meshContainerOutline, + textSize, + outlineColor, + shadowColor, + shadowOffset, + textControl, + animatablePropertyIndex, + drawShadow); isShadowDrawn = drawShadow; } // For each MeshData object, create a mesh actor and add to the renderable actor - if( !meshContainer.empty() ) + if(!meshContainer.empty()) { - const bool drawShadow = !isShadowDrawn && ( STYLE_DROP_SHADOW == style ); - CreateActors( meshContainer, - textSize, - defaultColor, - shadowColor, - shadowOffset, - textControl, - animatablePropertyIndex, - drawShadow ); + const bool drawShadow = !isShadowDrawn && (STYLE_DROP_SHADOW == style); + CreateActors(meshContainer, + textSize, + defaultColor, + shadowColor, + shadowOffset, + textControl, + animatablePropertyIndex, + drawShadow); } #if defined(DEBUG_ENABLED) Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics(); - DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n", - metrics.mGlyphCount, - metrics.mAtlasMetrics.mAtlasCount, - metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 ); + DALI_LOG_INFO(gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n", metrics.mGlyphCount, metrics.mAtlasMetrics.mAtlasCount, metrics.mAtlasMetrics.mTextureMemoryUsed / 1024); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str()); - for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i ) + for(uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n", - i + 1, i > 8 ? "" : " ", - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA", - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth, - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight, - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth, - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight, - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed, - metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n", i + 1, i > 8 ? "" : " ", metrics.mAtlasMetrics.mAtlasMetrics[i].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA", metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mWidth, metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mHeight, metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mBlockWidth, metrics.mAtlasMetrics.mAtlasMetrics[i].mSize.mBlockHeight, metrics.mAtlasMetrics.mAtlasMetrics[i].mBlocksUsed, metrics.mAtlasMetrics.mAtlasMetrics[i].mTotalBlocks); } #endif } void RemoveText() { - for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter ) + for(Vector::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter) { AtlasGlyphManager::GlyphStyle style; - style.outline = oldTextIter->mOutlineWidth; + style.outline = oldTextIter->mOutlineWidth; style.isItalic = oldTextIter->isItalic; - style.isBold = oldTextIter->isBold; - mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, style, -1/*decrement*/ ); + style.isBold = oldTextIter->isBold; + mGlyphManager.AdjustReferenceCount(oldTextIter->mFontId, oldTextIter->mIndex, style, -1 /*decrement*/); } - mTextCache.Resize( 0 ); + mTextCache.Resize(0); } - Actor CreateMeshActor( Actor textControl, Property::Index animatablePropertyIndex, const Vector4& defaultColor, const MeshRecord& meshRecord, - const Vector2& actorSize, Style style ) + Actor CreateMeshActor(Actor textControl, Property::Index animatablePropertyIndex, const Vector4& defaultColor, const MeshRecord& meshRecord, const Vector2& actorSize, Style style) { - VertexBuffer quadVertices = VertexBuffer::New( mQuadVertexFormat ); - quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() ); + VertexBuffer quadVertices = VertexBuffer::New(mQuadVertexFormat); + quadVertices.SetData(const_cast(&meshRecord.mMesh.mVertices[0]), meshRecord.mMesh.mVertices.Size()); Geometry quadGeometry = Geometry::New(); - quadGeometry.AddVertexBuffer( quadVertices ); - quadGeometry.SetIndexBuffer( &meshRecord.mMesh.mIndices[0], meshRecord.mMesh.mIndices.Size() ); + quadGeometry.AddVertexBuffer(quadVertices); + quadGeometry.SetIndexBuffer(&meshRecord.mMesh.mIndices[0], meshRecord.mMesh.mIndices.Size()); - TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) ); + TextureSet textureSet(mGlyphManager.GetTextures(meshRecord.mAtlasId)); // Choose the shader to use. - const bool isColorShader = ( STYLE_DROP_SHADOW != style ) && ( Pixel::BGRA8888 == mGlyphManager.GetPixelFormat( meshRecord.mAtlasId ) ); - Shader shader; - if( isColorShader ) + const bool isColorShader = (STYLE_DROP_SHADOW != style) && (Pixel::BGRA8888 == mGlyphManager.GetPixelFormat(meshRecord.mAtlasId)); + Shader shader; + if(isColorShader) { // The glyph is an emoji and is not a shadow. - if( !mShaderRgba ) + if(!mShaderRgba) { - mShaderRgba = Shader::New( SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_RGBA_SHADER_FRAG ); + mShaderRgba = Shader::New(SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_RGBA_SHADER_FRAG); } shader = mShaderRgba; } else { // The glyph is text or a shadow. - if( !mShaderL8 ) + if(!mShaderL8) { - mShaderL8 = Shader::New( SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_L8_SHADER_FRAG ); + mShaderL8 = Shader::New(SHADER_TEXT_ATLAS_SHADER_VERT, SHADER_TEXT_ATLAS_L8_SHADER_FRAG); } shader = mShaderL8; } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "defaultColor[%f, %f, %f, %f ]\n", defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "defaultColor[%f, %f, %f, %f ]\n", defaultColor.r, defaultColor.g, defaultColor.b, defaultColor.a); - Dali::Property::Index shaderTextColorIndex = shader.RegisterProperty( "textColorAnimatable", defaultColor ); + Dali::Property::Index shaderTextColorIndex = shader.RegisterProperty("textColorAnimatable", defaultColor); - if ( animatablePropertyIndex != Property::INVALID_INDEX ) + if(animatablePropertyIndex != Property::INVALID_INDEX) { // create constraint for the animatable text's color Property with textColorAnimatable in the shader. - if( shaderTextColorIndex ) + if(shaderTextColorIndex) { - Constraint constraint = Constraint::New( shader, shaderTextColorIndex, EqualToConstraint() ); - constraint.AddSource( Source( textControl, animatablePropertyIndex ) ); + Constraint constraint = Constraint::New(shader, shaderTextColorIndex, EqualToConstraint()); + constraint.AddSource(Source(textControl, animatablePropertyIndex)); constraint.Apply(); } } else { // If not animating the text colour then set to 1's so shader uses the current vertex color - shader.RegisterProperty( "textColorAnimatable", Vector4(1.0, 1.0, 1.0, 1.0 ) ); + shader.RegisterProperty("textColorAnimatable", Vector4(1.0, 1.0, 1.0, 1.0)); } - Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader ); - renderer.SetTextures( textureSet ); - renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON ); - renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth ); + Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, shader); + renderer.SetTextures(textureSet); + renderer.SetProperty(Dali::Renderer::Property::BLEND_MODE, BlendMode::ON); + renderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth); Actor actor = Actor::New(); #if defined(DEBUG_ENABLED) - actor.SetProperty( Dali::Actor::Property::NAME, "Text renderable actor" ); + actor.SetProperty(Dali::Actor::Property::NAME, "Text renderable actor"); #endif - actor.AddRenderer( renderer ); + actor.AddRenderer(renderer); // Keep all of the origins aligned - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - actor.SetProperty( Actor::Property::SIZE, actorSize ); - actor.RegisterProperty("uOffset", Vector2::ZERO ); - actor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR ); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + actor.SetProperty(Actor::Property::SIZE, actorSize); + actor.RegisterProperty("uOffset", Vector2::ZERO); + actor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR); return actor; } - void StitchTextMesh( std::vector< MeshRecord >& meshContainer, - AtlasManager::Mesh2D& newMesh, - Vector< Extent >& extents, - float baseLine, - bool underlineGlyph, - float underlinePosition, - float underlineThickness, - AtlasManager::AtlasSlot& slot ) + void StitchTextMesh(std::vector& meshContainer, + AtlasManager::Mesh2D& newMesh, + Vector& extents, + float baseLine, + bool underlineGlyph, + float underlinePosition, + float underlineThickness, + AtlasManager::AtlasSlot& slot) { - if ( slot.mImageId ) + if(slot.mImageId) { - float left = newMesh.mVertices[ 0 ].mPosition.x; - float right = newMesh.mVertices[ 1 ].mPosition.x; + float left = newMesh.mVertices[0].mPosition.x; + float right = newMesh.mVertices[1].mPosition.x; // Check to see if there's a mesh data object that references the same atlas ? uint32_t index = 0; - for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(), - mEndIt = meshContainer.end(); - mIt != mEndIt; - ++mIt, ++index ) + for(std::vector::iterator mIt = meshContainer.begin(), + mEndIt = meshContainer.end(); + mIt != mEndIt; + ++mIt, ++index) { - if( slot.mAtlasId == mIt->mAtlasId ) + if(slot.mAtlasId == mIt->mAtlasId) { // Append the mesh to the existing mesh and adjust any extents - Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh ); + Toolkit::Internal::AtlasMeshFactory::AppendMesh(mIt->mMesh, newMesh); - if( underlineGlyph ) + if(underlineGlyph) { - AdjustExtents( extents, - meshContainer, - index, - left, - right, - baseLine, - underlinePosition, - underlineThickness ); + AdjustExtents(extents, + meshContainer, + index, + left, + right, + baseLine, + underlinePosition, + underlineThickness); } return; @@ -750,239 +739,239 @@ struct AtlasRenderer::Impl // No mesh data object currently exists that references this atlas, so create a new one MeshRecord meshRecord; meshRecord.mAtlasId = slot.mAtlasId; - meshRecord.mMesh = newMesh; - meshContainer.push_back( meshRecord ); + meshRecord.mMesh = newMesh; + meshContainer.push_back(meshRecord); - if( underlineGlyph ) + if(underlineGlyph) { // Adjust extents for this new meshrecord - AdjustExtents( extents, - meshContainer, - meshContainer.size() - 1u, - left, - right, - baseLine, - underlinePosition, - underlineThickness ); + AdjustExtents(extents, + meshContainer, + meshContainer.size() - 1u, + left, + right, + baseLine, + underlinePosition, + underlineThickness); } } } - void AdjustExtents( Vector< Extent >& extents, - std::vector< MeshRecord>& meshRecords, - uint32_t index, - float left, - float right, - float baseLine, - float underlinePosition, - float underlineThickness ) + void AdjustExtents(Vector& extents, + std::vector& meshRecords, + uint32_t index, + float left, + float right, + float baseLine, + float underlinePosition, + float underlineThickness) { bool foundExtent = false; - for ( Vector< Extent >::Iterator eIt = extents.Begin(), - eEndIt = extents.End(); - eIt != eEndIt; - ++eIt ) + for(Vector::Iterator eIt = extents.Begin(), + eEndIt = extents.End(); + eIt != eEndIt; + ++eIt) { - if ( Equals( baseLine, eIt->mBaseLine ) ) + if(Equals(baseLine, eIt->mBaseLine)) { foundExtent = true; - if ( left < eIt->mLeft ) + if(left < eIt->mLeft) { eIt->mLeft = left; } - if ( right > eIt->mRight ) + if(right > eIt->mRight) { eIt->mRight = right; } - if ( underlinePosition > eIt->mUnderlinePosition ) + if(underlinePosition > eIt->mUnderlinePosition) { eIt->mUnderlinePosition = underlinePosition; } - if ( underlineThickness > eIt->mUnderlineThickness ) + if(underlineThickness > eIt->mUnderlineThickness) { eIt->mUnderlineThickness = underlineThickness; } } } - if ( !foundExtent ) + if(!foundExtent) { Extent extent; - extent.mLeft = left; - extent.mRight = right; - extent.mBaseLine = baseLine; - extent.mUnderlinePosition = underlinePosition; + extent.mLeft = left; + extent.mRight = right; + extent.mBaseLine = baseLine; + extent.mUnderlinePosition = underlinePosition; extent.mUnderlineThickness = underlineThickness; - extent.mMeshRecordIndex = index; - extents.PushBack( extent ); + extent.mMeshRecordIndex = index; + extents.PushBack(extent); } } - void CalculateBlocksSize( const Vector& glyphs ) + void CalculateBlocksSize(const Vector& glyphs) { - for( Vector::ConstIterator glyphIt = glyphs.Begin(), - glyphEndIt = glyphs.End(); - glyphIt != glyphEndIt; - ++glyphIt ) + for(Vector::ConstIterator glyphIt = glyphs.Begin(), + glyphEndIt = glyphs.End(); + glyphIt != glyphEndIt; + ++glyphIt) { - const FontId fontId = (*glyphIt).fontId; - bool foundFont = false; + const FontId fontId = (*glyphIt).fontId; + bool foundFont = false; - for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(), - blockEndIt = mBlockSizes.end(); - blockIt != blockEndIt; - ++blockIt ) + for(std::vector::const_iterator blockIt = mBlockSizes.begin(), + blockEndIt = mBlockSizes.end(); + blockIt != blockEndIt; + ++blockIt) { - if( (*blockIt).mFontId == fontId ) // Different size fonts will have a different fontId + if((*blockIt).mFontId == fontId) // Different size fonts will have a different fontId { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize match found fontID(%u) glyphIndex(%u)\n", fontId, (*glyphIt).index ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize match found fontID(%u) glyphIndex(%u)\n", fontId, (*glyphIt).index); foundFont = true; break; } } - if ( !foundFont ) + if(!foundFont) { FontMetrics fontMetrics; - mFontClient.GetFontMetrics( fontId, fontMetrics ); + mFontClient.GetFontMetrics(fontId, fontMetrics); MaxBlockSize maxBlockSize; - maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height ); + maxBlockSize.mNeededBlockWidth = static_cast(fontMetrics.height); maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth; - maxBlockSize.mFontId = fontId; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize New font with no matched blocksize, setting blocksize[%u]\n", maxBlockSize.mNeededBlockWidth ); - mBlockSizes.push_back( maxBlockSize ); + maxBlockSize.mFontId = fontId; + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::AtlasRenderer::CalculateBlocksSize New font with no matched blocksize, setting blocksize[%u]\n", maxBlockSize.mNeededBlockWidth); + mBlockSizes.push_back(maxBlockSize); } } } - void GenerateUnderlines( std::vector< MeshRecord >& meshRecords, - Vector< Extent >& extents, - const Vector4& underlineColor ) + void GenerateUnderlines(std::vector& meshRecords, + Vector& extents, + const Vector4& underlineColor) { AtlasManager::Mesh2D newMesh; - unsigned short faceIndex = 0; - for ( Vector< Extent >::ConstIterator eIt = extents.Begin(), - eEndIt = extents.End(); - eIt != eEndIt; - ++eIt ) + unsigned short faceIndex = 0; + for(Vector::ConstIterator eIt = extents.Begin(), + eEndIt = extents.End(); + eIt != eEndIt; + ++eIt) { AtlasManager::Vertex2D vert; - uint32_t index = eIt->mMeshRecordIndex; - Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId ); + uint32_t index = eIt->mMeshRecordIndex; + Vector2 uv = mGlyphManager.GetAtlasSize(meshRecords[index].mAtlasId); // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas ) - float u = HALF / uv.x; - float v = HALF / uv.y; + float u = HALF / uv.x; + float v = HALF / uv.y; float thickness = eIt->mUnderlineThickness; - float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF ); - float tlx = eIt->mLeft; - float brx = eIt->mRight; + float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - (thickness * HALF); + float tlx = eIt->mLeft; + float brx = eIt->mRight; - vert.mPosition.x = tlx; - vert.mPosition.y = baseLine; + vert.mPosition.x = tlx; + vert.mPosition.y = baseLine; vert.mTexCoords.x = ZERO; vert.mTexCoords.y = ZERO; - vert.mColor = underlineColor; - newMesh.mVertices.PushBack( vert ); + vert.mColor = underlineColor; + newMesh.mVertices.PushBack(vert); - vert.mPosition.x = brx; - vert.mPosition.y = baseLine; + vert.mPosition.x = brx; + vert.mPosition.y = baseLine; vert.mTexCoords.x = u; - vert.mColor = underlineColor; - newMesh.mVertices.PushBack( vert ); + vert.mColor = underlineColor; + newMesh.mVertices.PushBack(vert); - vert.mPosition.x = tlx; - vert.mPosition.y = baseLine + thickness; + vert.mPosition.x = tlx; + vert.mPosition.y = baseLine + thickness; vert.mTexCoords.x = ZERO; vert.mTexCoords.y = v; - vert.mColor = underlineColor; - newMesh.mVertices.PushBack( vert ); + vert.mColor = underlineColor; + newMesh.mVertices.PushBack(vert); - vert.mPosition.x = brx; - vert.mPosition.y = baseLine + thickness; + vert.mPosition.x = brx; + vert.mPosition.y = baseLine + thickness; vert.mTexCoords.x = u; - vert.mColor = underlineColor; - newMesh.mVertices.PushBack( vert ); + vert.mColor = underlineColor; + newMesh.mVertices.PushBack(vert); // Six indices in counter clockwise winding - newMesh.mIndices.PushBack( faceIndex + 1u ); - newMesh.mIndices.PushBack( faceIndex ); - newMesh.mIndices.PushBack( faceIndex + 2u ); - newMesh.mIndices.PushBack( faceIndex + 2u ); - newMesh.mIndices.PushBack( faceIndex + 3u ); - newMesh.mIndices.PushBack( faceIndex + 1u ); + newMesh.mIndices.PushBack(faceIndex + 1u); + newMesh.mIndices.PushBack(faceIndex); + newMesh.mIndices.PushBack(faceIndex + 2u); + newMesh.mIndices.PushBack(faceIndex + 2u); + newMesh.mIndices.PushBack(faceIndex + 3u); + newMesh.mIndices.PushBack(faceIndex + 1u); faceIndex += 4; - Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh ); + Toolkit::Internal::AtlasMeshFactory::AppendMesh(meshRecords[index].mMesh, newMesh); } } - Actor mActor; ///< The actor parent which renders the text - AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching - TextAbstraction::FontClient mFontClient; ///< The font client used to supply glyph information - Shader mShaderL8; ///< The shader for glyphs and emoji's shadows. - Shader mShaderRgba; ///< The shader for emojis. - std::vector< MaxBlockSize > mBlockSizes; ///< Maximum size needed to contain a glyph in a block within a new atlas - Vector< TextCacheEntry > mTextCache; ///< Caches data from previous render - Property::Map mQuadVertexFormat; ///< Describes the vertex format for text - int mDepth; ///< DepthIndex passed by control when connect to stage + Actor mActor; ///< The actor parent which renders the text + AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching + TextAbstraction::FontClient mFontClient; ///< The font client used to supply glyph information + Shader mShaderL8; ///< The shader for glyphs and emoji's shadows. + Shader mShaderRgba; ///< The shader for emojis. + std::vector mBlockSizes; ///< Maximum size needed to contain a glyph in a block within a new atlas + Vector mTextCache; ///< Caches data from previous render + Property::Map mQuadVertexFormat; ///< Describes the vertex format for text + int mDepth; ///< DepthIndex passed by control when connect to stage }; Text::RendererPtr AtlasRenderer::New() { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n"); - return Text::RendererPtr( new AtlasRenderer() ); + return Text::RendererPtr(new AtlasRenderer()); } -Actor AtlasRenderer::Render( Text::ViewInterface& view, - Actor textControl, - Property::Index animatablePropertyIndex, - float& alignmentOffset, - int depth ) +Actor AtlasRenderer::Render(Text::ViewInterface& view, + Actor textControl, + Property::Index animatablePropertyIndex, + float& alignmentOffset, + int depth) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n"); - UnparentAndReset( mImpl->mActor ); + UnparentAndReset(mImpl->mActor); Length numberOfGlyphs = view.GetNumberOfGlyphs(); - if( numberOfGlyphs > 0u ) + if(numberOfGlyphs > 0u) { Vector glyphs; - glyphs.Resize( numberOfGlyphs ); + glyphs.Resize(numberOfGlyphs); Vector positions; - positions.Resize( numberOfGlyphs ); + positions.Resize(numberOfGlyphs); - numberOfGlyphs = view.GetGlyphs( glyphs.Begin(), - positions.Begin(), - alignmentOffset, - 0u, - numberOfGlyphs ); + numberOfGlyphs = view.GetGlyphs(glyphs.Begin(), + positions.Begin(), + alignmentOffset, + 0u, + numberOfGlyphs); - glyphs.Resize( numberOfGlyphs ); - positions.Resize( numberOfGlyphs ); + glyphs.Resize(numberOfGlyphs); + positions.Resize(numberOfGlyphs); - const Vector4* const colorsBuffer = view.GetColors(); + const Vector4* const colorsBuffer = view.GetColors(); const ColorIndex* const colorIndicesBuffer = view.GetColorIndices(); - const Vector4& defaultColor = view.GetTextColor(); - - mImpl->AddGlyphs( view, - textControl, - animatablePropertyIndex, - positions, - glyphs, - defaultColor, - colorsBuffer, - colorIndicesBuffer, - depth, - alignmentOffset ); + const Vector4& defaultColor = view.GetTextColor(); + + mImpl->AddGlyphs(view, + textControl, + animatablePropertyIndex, + positions, + glyphs, + defaultColor, + colorsBuffer, + colorIndicesBuffer, + depth, + alignmentOffset); /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */ /* This renderable actor is used to position the text, other "decorations" can rely on there always being an Actor regardless of it is whitespace or regular text. */ - if ( !mImpl->mActor ) + if(!mImpl->mActor) { mImpl->mActor = Actor::New(); } @@ -994,7 +983,6 @@ Actor AtlasRenderer::Render( Text::ViewInterface& view, AtlasRenderer::AtlasRenderer() { mImpl = new Impl(); - } AtlasRenderer::~AtlasRenderer() diff --git a/dali-toolkit/internal/text/rendering/text-backend-impl.cpp b/dali-toolkit/internal/text/rendering/text-backend-impl.cpp index 5214141..0e0d3a8 100644 --- a/dali-toolkit/internal/text/rendering/text-backend-impl.cpp +++ b/dali-toolkit/internal/text/rendering/text-backend-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,8 +19,8 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -31,23 +31,19 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace Internal { - struct Backend::Impl { int temp; // placeholder for future backend implemenations }; Backend::Backend() -: mImpl( NULL ) +: mImpl(NULL) { mImpl = new Impl(); } @@ -61,32 +57,32 @@ Dali::Toolkit::Text::Backend Backend::Get() { Dali::Toolkit::Text::Backend backendHandle; - 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::Toolkit::Text::Backend ) ); + Dali::BaseHandle handle = service.GetSingleton(typeid(Dali::Toolkit::Text::Backend)); if(handle) { // If so, downcast the handle - Backend* impl = dynamic_cast< Dali::Toolkit::Text::Internal::Backend* >( handle.GetObjectPtr() ); - backendHandle = Dali::Toolkit::Text::Backend( impl ); + Backend* impl = dynamic_cast(handle.GetObjectPtr()); + backendHandle = Dali::Toolkit::Text::Backend(impl); } else // create and register the object { - backendHandle = Dali::Toolkit::Text::Backend( new Backend ); - service.Register( typeid( backendHandle ), backendHandle ); + backendHandle = Dali::Toolkit::Text::Backend(new Backend); + service.Register(typeid(backendHandle), backendHandle); } } return backendHandle; } -RendererPtr Backend::NewRenderer( unsigned int renderingType ) +RendererPtr Backend::NewRenderer(unsigned int renderingType) { RendererPtr renderer; - switch( renderingType ) + switch(renderingType) { case Dali::Toolkit::DevelText::RENDERING_SHARED_ATLAS: { @@ -106,7 +102,7 @@ RendererPtr Backend::NewRenderer( unsigned int renderingType ) default: { - DALI_LOG_WARNING( "Unknown renderer type: %d\n", renderingType ); + DALI_LOG_WARNING("Unknown renderer type: %d\n", renderingType); break; } } diff --git a/dali-toolkit/internal/text/rendering/text-backend.cpp b/dali-toolkit/internal/text/rendering/text-backend.cpp index ee48026..1802b7b 100644 --- a/dali-toolkit/internal/text/rendering/text-backend.cpp +++ b/dali-toolkit/internal/text/rendering/text-backend.cpp @@ -23,21 +23,18 @@ namespace Dali { - namespace Toolkit { - namespace Text { - Backend Backend::Get() { return Internal::Backend::Get(); } -RendererPtr Backend::NewRenderer( unsigned int renderingType ) +RendererPtr Backend::NewRenderer(unsigned int renderingType) { - return GetImplementation(*this).NewRenderer( renderingType ); + return GetImplementation(*this).NewRenderer(renderingType); } Backend::Backend() @@ -48,19 +45,19 @@ Backend::~Backend() { } -Backend::Backend( const Backend& handle ) -: BaseHandle( handle ) +Backend::Backend(const Backend& handle) +: BaseHandle(handle) { } -Backend& Backend::operator=( const Backend& handle ) +Backend& Backend::operator=(const Backend& handle) { - BaseHandle::operator=( handle ); + BaseHandle::operator=(handle); return *this; } -Backend::Backend( Internal::Backend* internal ) -: BaseHandle( internal ) +Backend::Backend(Internal::Backend* internal) +: BaseHandle(internal) { } diff --git a/dali-toolkit/internal/text/rendering/text-renderer.cpp b/dali-toolkit/internal/text/rendering/text-renderer.cpp index 4d74934..727d9cb 100644 --- a/dali-toolkit/internal/text/rendering/text-renderer.cpp +++ b/dali-toolkit/internal/text/rendering/text-renderer.cpp @@ -20,13 +20,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - Renderer::Renderer() { } diff --git a/dali-toolkit/internal/text/rendering/text-typesetter.cpp b/dali-toolkit/internal/text/rendering/text-typesetter.cpp old mode 100755 new mode 100644 index 05b4a67..abf7325 --- a/dali-toolkit/internal/text/rendering/text-typesetter.cpp +++ b/dali-toolkit/internal/text/rendering/text-typesetter.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,22 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Text { - namespace { - /** * @brief Data struct used to set the buffer of the glyph's bitmap into the final bitmap's buffer. */ @@ -62,138 +58,138 @@ struct GlyphData * @param[in] style The style of the text. * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8). */ -void TypesetGlyph( GlyphData& data, - const Vector2* const position, - const Vector4* const color, - Typesetter::Style style, - Pixel::Format pixelFormat ) +void TypesetGlyph(GlyphData& data, + const Vector2* const position, + const Vector4* const color, + Typesetter::Style style, + Pixel::Format pixelFormat) { - if( ( 0u == data.glyphBitmap.width ) || ( 0u == data.glyphBitmap.height ) ) + if((0u == data.glyphBitmap.width) || (0u == data.glyphBitmap.height)) { // Nothing to do if the width or height of the buffer is zero. return; } - const int widthMinusOne = static_cast( data.width - 1u ); - const int heightMinusOne = static_cast( data.height - 1u ); + const int widthMinusOne = static_cast(data.width - 1u); + const int heightMinusOne = static_cast(data.height - 1u); - if ( Pixel::RGBA8888 == pixelFormat ) + if(Pixel::RGBA8888 == pixelFormat) { // Whether the given glyph is a color one. - const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap; - const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel( data.glyphBitmap.format ); - const uint32_t alphaIndex = glyphPixelSize - 1u; - const bool swapChannelsBR = Pixel::BGRA8888 == data.glyphBitmap.format; + const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap; + const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel(data.glyphBitmap.format); + const uint32_t alphaIndex = glyphPixelSize - 1u; + const bool swapChannelsBR = Pixel::BGRA8888 == data.glyphBitmap.format; // Pointer to the color glyph if there is one. - const uint32_t* const colorGlyphBuffer = isColorGlyph ? reinterpret_cast( data.glyphBitmap.buffer ) : NULL; + const uint32_t* const colorGlyphBuffer = isColorGlyph ? reinterpret_cast(data.glyphBitmap.buffer) : NULL; // Initial vertical offset. const int yOffset = data.verticalOffset + position->y; - uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( data.bitmapBuffer.GetBuffer() ); + uint32_t* bitmapBuffer = reinterpret_cast(data.bitmapBuffer.GetBuffer()); // Traverse the pixels of the glyph line per line. - for( int lineIndex = 0, glyphHeight = static_cast( data.glyphBitmap.height ); lineIndex < glyphHeight; ++lineIndex ) + for(int lineIndex = 0, glyphHeight = static_cast(data.glyphBitmap.height); lineIndex < glyphHeight; ++lineIndex) { const int yOffsetIndex = yOffset + lineIndex; - if( ( 0 > yOffsetIndex ) || ( yOffsetIndex > heightMinusOne ) ) + if((0 > yOffsetIndex) || (yOffsetIndex > heightMinusOne)) { // Do not write out of bounds. continue; } - const int verticalOffset = yOffsetIndex * data.width; - const int xOffset = data.horizontalOffset + position->x; - const int glyphBufferOffset = lineIndex * static_cast( data.glyphBitmap.width ); - for( int index = 0, glyphWidth = static_cast( data.glyphBitmap.width ); index < glyphWidth; ++index ) + const int verticalOffset = yOffsetIndex * data.width; + const int xOffset = data.horizontalOffset + position->x; + const int glyphBufferOffset = lineIndex * static_cast(data.glyphBitmap.width); + for(int index = 0, glyphWidth = static_cast(data.glyphBitmap.width); index < glyphWidth; ++index) { const int xOffsetIndex = xOffset + index; - if( ( 0 > xOffsetIndex ) || ( xOffsetIndex > widthMinusOne ) ) + if((0 > xOffsetIndex) || (xOffsetIndex > widthMinusOne)) { // Don't write out of bounds. continue; } - if( isColorGlyph ) + if(isColorGlyph) { // Retrieves the color from the color glyph. - uint32_t packedColorGlyph = *( colorGlyphBuffer + glyphBufferOffset + index ); - uint8_t* packedColorGlyphBuffer = reinterpret_cast( &packedColorGlyph ); + uint32_t packedColorGlyph = *(colorGlyphBuffer + glyphBufferOffset + index); + uint8_t* packedColorGlyphBuffer = reinterpret_cast(&packedColorGlyph); // Update the alpha channel. - if( Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style ) // Outline not shown for color glyph + if(Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style) // Outline not shown for color glyph { // Create an alpha mask for color glyph. - *( packedColorGlyphBuffer + 3u ) = 0u; - *( packedColorGlyphBuffer + 2u ) = 0u; - *( packedColorGlyphBuffer + 1u ) = 0u; - *packedColorGlyphBuffer = 0u; + *(packedColorGlyphBuffer + 3u) = 0u; + *(packedColorGlyphBuffer + 2u) = 0u; + *(packedColorGlyphBuffer + 1u) = 0u; + *packedColorGlyphBuffer = 0u; } else { - const uint8_t colorAlpha = static_cast( color->a * static_cast( *( packedColorGlyphBuffer + 3u ) ) ); - *( packedColorGlyphBuffer + 3u ) = colorAlpha; + const uint8_t colorAlpha = static_cast(color->a * static_cast(*(packedColorGlyphBuffer + 3u))); + *(packedColorGlyphBuffer + 3u) = colorAlpha; - if( Typesetter::STYLE_SHADOW == style ) + if(Typesetter::STYLE_SHADOW == style) { // The shadow of color glyph needs to have the shadow color. - *( packedColorGlyphBuffer + 2u ) = static_cast( color->b * colorAlpha ); - *( packedColorGlyphBuffer + 1u ) = static_cast( color->g * colorAlpha ); - *packedColorGlyphBuffer = static_cast( color->r * colorAlpha ); + *(packedColorGlyphBuffer + 2u) = static_cast(color->b * colorAlpha); + *(packedColorGlyphBuffer + 1u) = static_cast(color->g * colorAlpha); + *packedColorGlyphBuffer = static_cast(color->r * colorAlpha); } else { - if( swapChannelsBR ) + if(swapChannelsBR) { - std::swap( *packedColorGlyphBuffer, *( packedColorGlyphBuffer + 2u ) ); // Swap B and R. + std::swap(*packedColorGlyphBuffer, *(packedColorGlyphBuffer + 2u)); // Swap B and R. } - *( packedColorGlyphBuffer + 2u ) = ( *( packedColorGlyphBuffer + 2u ) * colorAlpha / 255 ); - *( packedColorGlyphBuffer + 1u ) = ( *( packedColorGlyphBuffer + 1u ) * colorAlpha / 255 ); - *packedColorGlyphBuffer = ( *( packedColorGlyphBuffer ) * colorAlpha / 255 ); + *(packedColorGlyphBuffer + 2u) = (*(packedColorGlyphBuffer + 2u) * colorAlpha / 255); + *(packedColorGlyphBuffer + 1u) = (*(packedColorGlyphBuffer + 1u) * colorAlpha / 255); + *packedColorGlyphBuffer = (*(packedColorGlyphBuffer)*colorAlpha / 255); - if( data.glyphBitmap.isColorBitmap ) + if(data.glyphBitmap.isColorBitmap) { - *( packedColorGlyphBuffer + 2u ) = static_cast( *( packedColorGlyphBuffer + 2u ) * color->b ); - *( packedColorGlyphBuffer + 1u ) = static_cast( *( packedColorGlyphBuffer + 1u ) * color->g ); - *packedColorGlyphBuffer = static_cast( *packedColorGlyphBuffer * color->r ); + *(packedColorGlyphBuffer + 2u) = static_cast(*(packedColorGlyphBuffer + 2u) * color->b); + *(packedColorGlyphBuffer + 1u) = static_cast(*(packedColorGlyphBuffer + 1u) * color->g); + *packedColorGlyphBuffer = static_cast(*packedColorGlyphBuffer * color->r); } } } // Set the color into the final pixel buffer. - *( bitmapBuffer + verticalOffset + xOffsetIndex ) = packedColorGlyph; + *(bitmapBuffer + verticalOffset + xOffsetIndex) = packedColorGlyph; } else { // Pack the given color into a 32bit buffer. The alpha channel will be updated later for each pixel. // The format is RGBA8888. - uint32_t packedColor = 0u; - uint8_t* packedColorBuffer = reinterpret_cast( &packedColor ); + uint32_t packedColor = 0u; + uint8_t* packedColorBuffer = reinterpret_cast(&packedColor); // Update the alpha channel. - const uint8_t alpha = *( data.glyphBitmap.buffer + glyphPixelSize * ( glyphBufferOffset + index ) + alphaIndex ); + const uint8_t alpha = *(data.glyphBitmap.buffer + glyphPixelSize * (glyphBufferOffset + index) + alphaIndex); // Copy non-transparent pixels only - if ( alpha > 0u ) + if(alpha > 0u) { // Check alpha of overlapped pixels - uint32_t& currentColor = *( bitmapBuffer + verticalOffset + xOffsetIndex ); - uint8_t* packedCurrentColorBuffer = reinterpret_cast( ¤tColor ); + uint32_t& currentColor = *(bitmapBuffer + verticalOffset + xOffsetIndex); + uint8_t* packedCurrentColorBuffer = reinterpret_cast(¤tColor); // For any pixel overlapped with the pixel in previous glyphs, make sure we don't // overwrite a previous bigger alpha with a smaller alpha (in order to avoid // semi-transparent gaps between joint glyphs with overlapped pixels, which could // happen, for example, in the RTL text when we copy glyphs from right to left). - uint8_t currentAlpha = *( packedCurrentColorBuffer + 3u ); - currentAlpha = std::max( currentAlpha, alpha ); + uint8_t currentAlpha = *(packedCurrentColorBuffer + 3u); + currentAlpha = std::max(currentAlpha, alpha); // Color is pre-muliplied with its alpha. - *( packedColorBuffer + 3u ) = static_cast( color->a * currentAlpha ); - *( packedColorBuffer + 2u ) = static_cast( color->b * currentAlpha ); - *( packedColorBuffer + 1u ) = static_cast( color->g * currentAlpha ); - *( packedColorBuffer ) = static_cast( color->r * currentAlpha ); + *(packedColorBuffer + 3u) = static_cast(color->a * currentAlpha); + *(packedColorBuffer + 2u) = static_cast(color->b * currentAlpha); + *(packedColorBuffer + 1u) = static_cast(color->g * currentAlpha); + *(packedColorBuffer) = static_cast(color->r * currentAlpha); // Set the color into the final pixel buffer. currentColor = packedColor; @@ -205,53 +201,53 @@ void TypesetGlyph( GlyphData& data, else { // Whether the given glyph is a color one. - const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap; - const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel( data.glyphBitmap.format ); - const uint32_t alphaIndex = glyphPixelSize - 1u; + const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap; + const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel(data.glyphBitmap.format); + const uint32_t alphaIndex = glyphPixelSize - 1u; // Initial vertical offset. const int yOffset = data.verticalOffset + position->y; - uint8_t* bitmapBuffer = reinterpret_cast< uint8_t* >( data.bitmapBuffer.GetBuffer() ); + uint8_t* bitmapBuffer = reinterpret_cast(data.bitmapBuffer.GetBuffer()); // Traverse the pixels of the glyph line per line. - for( int lineIndex = 0, glyphHeight = static_cast( data.glyphBitmap.height ); lineIndex < glyphHeight; ++lineIndex ) + for(int lineIndex = 0, glyphHeight = static_cast(data.glyphBitmap.height); lineIndex < glyphHeight; ++lineIndex) { const int yOffsetIndex = yOffset + lineIndex; - if( ( 0 > yOffsetIndex ) || ( yOffsetIndex > heightMinusOne ) ) + if((0 > yOffsetIndex) || (yOffsetIndex > heightMinusOne)) { // Do not write out of bounds. continue; } - const int verticalOffset = yOffsetIndex * data.width; - const int xOffset = data.horizontalOffset + position->x; - const int glyphBufferOffset = lineIndex * static_cast( data.glyphBitmap.width ); - for( int index = 0, glyphWidth = static_cast( data.glyphBitmap.width ); index < glyphWidth; ++index ) + const int verticalOffset = yOffsetIndex * data.width; + const int xOffset = data.horizontalOffset + position->x; + const int glyphBufferOffset = lineIndex * static_cast(data.glyphBitmap.width); + for(int index = 0, glyphWidth = static_cast(data.glyphBitmap.width); index < glyphWidth; ++index) { const int xOffsetIndex = xOffset + index; - if( ( 0 > xOffsetIndex ) || ( xOffsetIndex > widthMinusOne ) ) + if((0 > xOffsetIndex) || (xOffsetIndex > widthMinusOne)) { // Don't write out of bounds. continue; } - if ( !isColorGlyph ) + if(!isColorGlyph) { // Update the alpha channel. - const uint8_t alpha = *( data.glyphBitmap.buffer + glyphPixelSize * ( glyphBufferOffset + index ) + alphaIndex ); + const uint8_t alpha = *(data.glyphBitmap.buffer + glyphPixelSize * (glyphBufferOffset + index) + alphaIndex); // Copy non-transparent pixels only - if ( alpha > 0u ) + if(alpha > 0u) { // Check alpha of overlapped pixels - uint8_t& currentAlpha = *( bitmapBuffer + verticalOffset + xOffsetIndex ); + uint8_t& currentAlpha = *(bitmapBuffer + verticalOffset + xOffsetIndex); // For any pixel overlapped with the pixel in previous glyphs, make sure we don't // overwrite a previous bigger alpha with a smaller alpha (in order to avoid // semi-transparent gaps between joint glyphs with overlapped pixels, which could // happen, for example, in the RTL text when we copy glyphs from right to left). - currentAlpha = std::max( currentAlpha, alpha ); + currentAlpha = std::max(currentAlpha, alpha); } } } @@ -259,17 +255,17 @@ void TypesetGlyph( GlyphData& data, } } -bool IsGlyphUnderlined( GlyphIndex index, - const Vector& underlineRuns ) +bool IsGlyphUnderlined(GlyphIndex index, + const Vector& underlineRuns) { - for( Vector::ConstIterator it = underlineRuns.Begin(), - endIt = underlineRuns.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = underlineRuns.Begin(), + endIt = underlineRuns.End(); + it != endIt; + ++it) { const GlyphRun& run = *it; - if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) ) + if((run.glyphIndex <= index) && (index < run.glyphIndex + run.numberOfGlyphs)) { return true; } @@ -280,47 +276,47 @@ bool IsGlyphUnderlined( GlyphIndex index, /// Helper method to fetch the underline metrics for the specified font glyph void FetchFontUnderlineMetrics( - TextAbstraction::FontClient& fontClient, - const GlyphInfo* const glyphInfo, - float& currentUnderlinePosition, - const float underlineHeight, - float& currentUnderlineThickness, - float& maxUnderlineThickness, - FontId& lastUnderlinedFontId) + TextAbstraction::FontClient& fontClient, + const GlyphInfo* const glyphInfo, + float& currentUnderlinePosition, + const float underlineHeight, + float& currentUnderlineThickness, + float& maxUnderlineThickness, + FontId& lastUnderlinedFontId) { FontMetrics fontMetrics; - fontClient.GetFontMetrics( glyphInfo->fontId, fontMetrics ); - currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) ); - const float descender = ceil( fabsf( fontMetrics.descender ) ); + fontClient.GetFontMetrics(glyphInfo->fontId, fontMetrics); + currentUnderlinePosition = ceil(fabsf(fontMetrics.underlinePosition)); + const float descender = ceil(fabsf(fontMetrics.descender)); - if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 ) + if(fabsf(underlineHeight) < Math::MACHINE_EPSILON_1000) { currentUnderlineThickness = fontMetrics.underlineThickness; // Ensure underline will be at least a pixel high - if ( currentUnderlineThickness < 1.0f ) + if(currentUnderlineThickness < 1.0f) { currentUnderlineThickness = 1.0f; } else { - currentUnderlineThickness = ceil( currentUnderlineThickness ); + currentUnderlineThickness = ceil(currentUnderlineThickness); } } // The underline thickness should be the max underline thickness of all glyphs of the line. - if ( currentUnderlineThickness > maxUnderlineThickness ) + if(currentUnderlineThickness > maxUnderlineThickness) { maxUnderlineThickness = currentUnderlineThickness; } // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font - if( currentUnderlinePosition > descender ) + if(currentUnderlinePosition > descender) { currentUnderlinePosition = descender; } - if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 ) + if(fabsf(currentUnderlinePosition) < Math::MACHINE_EPSILON_1000) { // Move offset down by one ( EFL behavior ) currentUnderlinePosition = 1.0f; @@ -331,52 +327,52 @@ void FetchFontUnderlineMetrics( /// Draws the specified color to the pixel buffer void WriteColorToPixelBuffer( - GlyphData& glyphData, - uint32_t* bitmapBuffer, - const Vector4& color, - const unsigned int x, - const unsigned int y) + GlyphData& glyphData, + uint32_t* bitmapBuffer, + const Vector4& color, + const unsigned int x, + const unsigned int y) { // Always RGBA image for text with styles - uint32_t pixel = *( bitmapBuffer + y * glyphData.width + x ); - uint8_t* pixelBuffer = reinterpret_cast( &pixel ); + uint32_t pixel = *(bitmapBuffer + y * glyphData.width + x); + uint8_t* pixelBuffer = reinterpret_cast(&pixel); // Write the color to the pixel buffer - uint8_t colorAlpha = static_cast< uint8_t >( color.a * 255.f ); - *( pixelBuffer + 3u ) = colorAlpha; - *( pixelBuffer + 2u ) = static_cast< uint8_t >( color.b * colorAlpha ); - *( pixelBuffer + 1u ) = static_cast< uint8_t >( color.g * colorAlpha ); - *( pixelBuffer ) = static_cast< uint8_t >( color.r * colorAlpha ); + uint8_t colorAlpha = static_cast(color.a * 255.f); + *(pixelBuffer + 3u) = colorAlpha; + *(pixelBuffer + 2u) = static_cast(color.b * colorAlpha); + *(pixelBuffer + 1u) = static_cast(color.g * colorAlpha); + *(pixelBuffer) = static_cast(color.r * colorAlpha); - *( bitmapBuffer + y * glyphData.width + x ) = pixel; + *(bitmapBuffer + y * glyphData.width + x) = pixel; } /// Draws the specified underline color to the buffer void DrawUnderline( - const Vector4& underlineColor, - const unsigned int bufferWidth, - const unsigned int bufferHeight, - GlyphData& glyphData, - const float baseline, - const float currentUnderlinePosition, - const float maxUnderlineThickness, - const float lineExtentLeft, - const float lineExtentRight) + const Vector4& underlineColor, + const unsigned int bufferWidth, + const unsigned int bufferHeight, + GlyphData& glyphData, + const float baseline, + const float currentUnderlinePosition, + const float maxUnderlineThickness, + const float lineExtentLeft, + const float lineExtentRight) { - int underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition; - uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() ); + int underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition; + uint32_t* bitmapBuffer = reinterpret_cast(glyphData.bitmapBuffer.GetBuffer()); - for( unsigned int y = underlineYOffset; y < underlineYOffset + maxUnderlineThickness; y++ ) + for(unsigned int y = underlineYOffset; y < underlineYOffset + maxUnderlineThickness; y++) { - if( y > bufferHeight - 1 ) + if(y > bufferHeight - 1) { // Do not write out of bounds. break; } - for( unsigned int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ ) + for(unsigned int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++) { - if( x > bufferWidth - 1 ) + if(x > bufferWidth - 1) { // Do not write out of bounds. break; @@ -389,28 +385,28 @@ void DrawUnderline( /// Draws the background color to the buffer void DrawBackgroundColor( - Vector4 backgroundColor, - const unsigned int bufferWidth, - const unsigned int bufferHeight, - GlyphData& glyphData, - const float baseline, - const LineRun& line, - const float lineExtentLeft, - const float lineExtentRight) + Vector4 backgroundColor, + const unsigned int bufferWidth, + const unsigned int bufferHeight, + GlyphData& glyphData, + const float baseline, + const LineRun& line, + const float lineExtentLeft, + const float lineExtentRight) { - uint32_t* bitmapBuffer = reinterpret_cast< uint32_t* >( glyphData.bitmapBuffer.GetBuffer() ); + uint32_t* bitmapBuffer = reinterpret_cast(glyphData.bitmapBuffer.GetBuffer()); - for( int y = glyphData.verticalOffset + baseline - line.ascender; y < glyphData.verticalOffset + baseline - line.descender; y++ ) + for(int y = glyphData.verticalOffset + baseline - line.ascender; y < glyphData.verticalOffset + baseline - line.descender; y++) { - if( ( y < 0 ) || ( y > static_cast(bufferHeight - 1) ) ) + if((y < 0) || (y > static_cast(bufferHeight - 1))) { // Do not write out of bounds. continue; } - for( int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++ ) + for(int x = glyphData.horizontalOffset + lineExtentLeft; x <= glyphData.horizontalOffset + lineExtentRight; x++) { - if( ( x < 0 ) || ( x > static_cast(bufferWidth - 1) ) ) + if((x < 0) || (x > static_cast(bufferWidth - 1))) { // Do not write out of bounds. continue; @@ -423,9 +419,9 @@ void DrawBackgroundColor( } // namespace -TypesetterPtr Typesetter::New( const ModelInterface* const model ) +TypesetterPtr Typesetter::New(const ModelInterface* const model) { - return TypesetterPtr( new Typesetter( model ) ); + return TypesetterPtr(new Typesetter(model)); } ViewModel* Typesetter::GetViewModel() @@ -433,7 +429,7 @@ ViewModel* Typesetter::GetViewModel() return mModel; } -PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirection::Type textDirection, RenderBehaviour behaviour, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat ) +PixelData Typesetter::Render(const Vector2& size, Toolkit::DevelText::TextDirection::Type textDirection, RenderBehaviour behaviour, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat) { // @todo. This initial implementation for a TextLabel has only one visible page. @@ -443,12 +439,12 @@ PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirec // Retrieves the layout size. const Size& layoutSize = mModel->GetLayoutSize(); - const int outlineWidth = static_cast( mModel->GetOutlineWidth() ); + const int outlineWidth = static_cast(mModel->GetOutlineWidth()); // Set the offset for the horizontal alignment according to the text direction and outline width. int penX = 0; - switch( mModel->GetHorizontalAlignment() ) + switch(mModel->GetHorizontalAlignment()) { case HorizontalAlignment::BEGIN: { @@ -457,12 +453,12 @@ PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirec } case HorizontalAlignment::CENTER: { - penX += ( textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT ) ? -outlineWidth : outlineWidth; + penX += (textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT) ? -outlineWidth : outlineWidth; break; } case HorizontalAlignment::END: { - penX += ( textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT ) ? -outlineWidth * 2 : outlineWidth * 2; + penX += (textDirection == Toolkit::DevelText::TextDirection::LEFT_TO_RIGHT) ? -outlineWidth * 2 : outlineWidth * 2; break; } } @@ -470,7 +466,7 @@ PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirec // Set the offset for the vertical alignment. int penY = 0u; - switch( mModel->GetVerticalAlignment() ) + switch(mModel->GetVerticalAlignment()) { case VerticalAlignment::TOP: { @@ -479,19 +475,19 @@ PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirec } case VerticalAlignment::CENTER: { - penY = static_cast( 0.5f * ( size.height - layoutSize.height ) ); + penY = static_cast(0.5f * (size.height - layoutSize.height)); penY = penY < 0.f ? 0.f : penY; break; } case VerticalAlignment::BOTTOM: { - penY = static_cast( size.height - layoutSize.height ); + penY = static_cast(size.height - layoutSize.height); break; } } // Calculate vertical line alignment - switch( mModel->GetVerticalLineAlignment() ) + switch(mModel->GetVerticalLineAlignment()) { case DevelText::VerticalLineAlignment::TOP: { @@ -501,13 +497,13 @@ PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirec { const auto& line = *mModel->GetLines(); penY -= line.descender; - penY += static_cast(line.lineSpacing*0.5f + line.descender); + penY += static_cast(line.lineSpacing * 0.5f + line.descender); break; } case DevelText::VerticalLineAlignment::BOTTOM: { - const auto& line = *mModel->GetLines(); - const auto lineHeight = line.ascender + (-line.descender) + line.lineSpacing; + const auto& line = *mModel->GetLines(); + const auto lineHeight = line.ascender + (-line.descender) + line.lineSpacing; penY += static_cast(lineHeight - (line.ascender - line.descender)); break; } @@ -518,202 +514,201 @@ PixelData Typesetter::Render( const Vector2& size, Toolkit::DevelText::TextDirec // do all of these in CPU only, so that once the final texture is generated, // no calculation is needed in GPU during each frame. - const unsigned int bufferWidth = static_cast( size.width ); - const unsigned int bufferHeight = static_cast( size.height ); + const unsigned int bufferWidth = static_cast(size.width); + const unsigned int bufferHeight = static_cast(size.height); - const unsigned int bufferSizeInt = bufferWidth * bufferHeight; + const unsigned int bufferSizeInt = bufferWidth * bufferHeight; const unsigned int bufferSizeChar = 4u * bufferSizeInt; Length numberOfGlyphs = mModel->GetNumberOfGlyphs(); Devel::PixelBuffer imageBuffer; - if( RENDER_MASK == behaviour ) + if(RENDER_MASK == behaviour) { // Generate the image buffer as an alpha mask for color glyphs. - imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 ); + imageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1); } - else if( RENDER_NO_TEXT == behaviour ) + else if(RENDER_NO_TEXT == behaviour) { // Generate an empty image buffer so that it can been combined with the image buffers for styles - imageBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 ); - memset( imageBuffer.GetBuffer(), 0u, bufferSizeChar ); + imageBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888); + memset(imageBuffer.GetBuffer(), 0u, bufferSizeChar); } else { // Generate the image buffer for the text with no style. - imageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 ); + imageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1); } - if ( ( RENDER_NO_STYLES != behaviour ) && ( RENDER_MASK != behaviour ) ) + if((RENDER_NO_STYLES != behaviour) && (RENDER_MASK != behaviour)) { - // Generate the outline if enabled const uint16_t outlineWidth = mModel->GetOutlineWidth(); - if ( outlineWidth != 0u ) + if(outlineWidth != 0u) { // Create the image buffer for outline - Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 ); + Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1); // Combine the two buffers - imageBuffer = CombineImageBuffer( imageBuffer, outlineImageBuffer, bufferWidth, bufferHeight ); + imageBuffer = CombineImageBuffer(imageBuffer, outlineImageBuffer, bufferWidth, bufferHeight); } // @todo. Support shadow and underline for partial text later on. // Generate the shadow if enabled const Vector2& shadowOffset = mModel->GetShadowOffset(); - if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 ) + if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1) { // Create the image buffer for shadow - Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 ); + Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1); // Check whether it will be a soft shadow const float& blurRadius = mModel->GetShadowBlurRadius(); - if ( blurRadius > Math::MACHINE_EPSILON_1 ) + if(blurRadius > Math::MACHINE_EPSILON_1) { - shadowImageBuffer.ApplyGaussianBlur( blurRadius ); + shadowImageBuffer.ApplyGaussianBlur(blurRadius); } // Combine the two buffers - imageBuffer = CombineImageBuffer( imageBuffer, shadowImageBuffer, bufferWidth, bufferHeight ); + imageBuffer = CombineImageBuffer(imageBuffer, shadowImageBuffer, bufferWidth, bufferHeight); } // Generate the underline if enabled const bool underlineEnabled = mModel->IsUnderlineEnabled(); - if ( underlineEnabled ) + if(underlineEnabled) { // Create the image buffer for underline - Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1 ); + Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1); // Combine the two buffers - imageBuffer = CombineImageBuffer( imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight ); + imageBuffer = CombineImageBuffer(imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight); } // Generate the background if enabled const bool backgroundEnabled = mModel->IsBackgroundEnabled(); - if ( backgroundEnabled ) + if(backgroundEnabled) { - Devel::PixelBuffer backgroundImageBuffer = CreateImageBuffer( bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs -1 ); + Devel::PixelBuffer backgroundImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, numberOfGlyphs - 1); // Combine the two buffers - imageBuffer = CombineImageBuffer( imageBuffer, backgroundImageBuffer, bufferWidth, bufferHeight ); + imageBuffer = CombineImageBuffer(imageBuffer, backgroundImageBuffer, bufferWidth, bufferHeight); } } // Create the final PixelData for the combined image buffer - PixelData pixelData = Devel::PixelBuffer::Convert( imageBuffer ); + PixelData pixelData = Devel::PixelBuffer::Convert(imageBuffer); return pixelData; } -Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth, const unsigned int bufferHeight, Typesetter::Style style, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat, int horizontalOffset, int verticalOffset, GlyphIndex fromGlyphIndex, GlyphIndex toGlyphIndex ) +Devel::PixelBuffer Typesetter::CreateImageBuffer(const unsigned int bufferWidth, const unsigned int bufferHeight, Typesetter::Style style, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat, int horizontalOffset, int verticalOffset, GlyphIndex fromGlyphIndex, GlyphIndex toGlyphIndex) { // Retrieve lines, glyphs, positions and colors from the view model. - const Length modelNumberOfLines = mModel->GetNumberOfLines(); - const LineRun* const modelLinesBuffer = mModel->GetLines(); - const Length numberOfGlyphs = mModel->GetNumberOfGlyphs(); - const GlyphInfo* const glyphsBuffer = mModel->GetGlyphs(); - const Vector2* const positionBuffer = mModel->GetLayout(); - const Vector4* const colorsBuffer = mModel->GetColors(); - const ColorIndex* const colorIndexBuffer = mModel->GetColorIndices(); + const Length modelNumberOfLines = mModel->GetNumberOfLines(); + const LineRun* const modelLinesBuffer = mModel->GetLines(); + const Length numberOfGlyphs = mModel->GetNumberOfGlyphs(); + const GlyphInfo* const glyphsBuffer = mModel->GetGlyphs(); + const Vector2* const positionBuffer = mModel->GetLayout(); + const Vector4* const colorsBuffer = mModel->GetColors(); + const ColorIndex* const colorIndexBuffer = mModel->GetColorIndices(); // Whether to use the default color. - const bool useDefaultColor = ( NULL == colorsBuffer ); - const Vector4& defaultColor = mModel->GetDefaultColor(); + const bool useDefaultColor = (NULL == colorsBuffer); + const Vector4& defaultColor = mModel->GetDefaultColor(); // Create and initialize the pixel buffer. GlyphData glyphData; - glyphData.verticalOffset = verticalOffset; - glyphData.width = bufferWidth; - glyphData.height = bufferHeight; - glyphData.bitmapBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, pixelFormat ); + glyphData.verticalOffset = verticalOffset; + glyphData.width = bufferWidth; + glyphData.height = bufferHeight; + glyphData.bitmapBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat); glyphData.horizontalOffset = 0; - if ( Pixel::RGBA8888 == pixelFormat ) + if(Pixel::RGBA8888 == pixelFormat) { - const unsigned int bufferSizeInt = bufferWidth * bufferHeight; + const unsigned int bufferSizeInt = bufferWidth * bufferHeight; const unsigned int bufferSizeChar = 4u * bufferSizeInt; - memset( glyphData.bitmapBuffer.GetBuffer(), 0u, bufferSizeChar ); + memset(glyphData.bitmapBuffer.GetBuffer(), 0u, bufferSizeChar); } else { - memset( glyphData.bitmapBuffer.GetBuffer(), 0, bufferWidth * bufferHeight ); + memset(glyphData.bitmapBuffer.GetBuffer(), 0, bufferWidth * bufferHeight); } // Get a handle of the font client. Used to retrieve the bitmaps of the glyphs. TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); // Traverses the lines of the text. - for( LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex ) + for(LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex) { - const LineRun& line = *( modelLinesBuffer + lineIndex ); + const LineRun& line = *(modelLinesBuffer + lineIndex); // Sets the horizontal offset of the line. - glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast( line.alignmentOffset ); + glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast(line.alignmentOffset); glyphData.horizontalOffset += horizontalOffset; // Increases the vertical offset with the line's ascender. - glyphData.verticalOffset += static_cast( line.ascender ); + glyphData.verticalOffset += static_cast(line.ascender); // Include line spacing after first line - if( lineIndex > 0u ) + if(lineIndex > 0u) { - glyphData.verticalOffset += static_cast( line.lineSpacing ); + glyphData.verticalOffset += static_cast(line.lineSpacing); } // Retrieves the glyph's outline width - float outlineWidth = static_cast( mModel->GetOutlineWidth() ); + float outlineWidth = static_cast(mModel->GetOutlineWidth()); - if( style == Typesetter::STYLE_OUTLINE ) + if(style == Typesetter::STYLE_OUTLINE) { glyphData.horizontalOffset -= outlineWidth; - if( lineIndex == 0u ) + if(lineIndex == 0u) { // Only need to add the vertical outline offset for the first line glyphData.verticalOffset -= outlineWidth; } } - else if ( style == Typesetter::STYLE_SHADOW ) + else if(style == Typesetter::STYLE_SHADOW) { const Vector2& shadowOffset = mModel->GetShadowOffset(); glyphData.horizontalOffset += shadowOffset.x - outlineWidth; // if outline enabled then shadow should offset from outline - if ( lineIndex == 0u ) + if(lineIndex == 0u) { // Only need to add the vertical shadow offset for first line glyphData.verticalOffset += shadowOffset.y - outlineWidth; } } - const bool underlineEnabled = mModel->IsUnderlineEnabled(); - const Vector4& underlineColor = mModel->GetUnderlineColor(); - const float underlineHeight = mModel->GetUnderlineHeight(); + const bool underlineEnabled = mModel->IsUnderlineEnabled(); + const Vector4& underlineColor = mModel->GetUnderlineColor(); + const float underlineHeight = mModel->GetUnderlineHeight(); // Get the underline runs. - const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns(); + const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns(); Vector underlineRuns; - underlineRuns.Resize( numberOfUnderlineRuns ); - mModel->GetUnderlineRuns( underlineRuns.Begin(), 0u, numberOfUnderlineRuns ); + underlineRuns.Resize(numberOfUnderlineRuns); + mModel->GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns); bool thereAreUnderlinedGlyphs = false; - float currentUnderlinePosition = 0.0f; + float currentUnderlinePosition = 0.0f; float currentUnderlineThickness = underlineHeight; - float maxUnderlineThickness = currentUnderlineThickness; + float maxUnderlineThickness = currentUnderlineThickness; FontId lastUnderlinedFontId = 0; - float lineExtentLeft = bufferWidth; + float lineExtentLeft = bufferWidth; float lineExtentRight = 0.0f; - float baseline = 0.0f; + float baseline = 0.0f; // Traverses the glyphs of the line. - const GlyphIndex endGlyphIndex = std::min( numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs ); - for( GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex ) + const GlyphIndex endGlyphIndex = std::min(numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs); + for(GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex) { - if ( glyphIndex < fromGlyphIndex || glyphIndex > toGlyphIndex ) + if(glyphIndex < fromGlyphIndex || glyphIndex > toGlyphIndex) { // Ignore any glyph that out of the specified range continue; @@ -722,18 +717,18 @@ Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth // Retrieve the glyph's info. const GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex; - if( ( glyphInfo->width < Math::MACHINE_EPSILON_1000 ) || - ( glyphInfo->height < Math::MACHINE_EPSILON_1000 ) ) + if((glyphInfo->width < Math::MACHINE_EPSILON_1000) || + (glyphInfo->height < Math::MACHINE_EPSILON_1000)) { // Nothing to do if the glyph's width or height is zero. continue; } - const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( glyphIndex, underlineRuns ); - thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph; + const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined(glyphIndex, underlineRuns); + thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph; // Are we still using the same fontId as previous - if( underlineGlyph && ( glyphInfo->fontId != lastUnderlinedFontId ) ) + if(underlineGlyph && (glyphInfo->fontId != lastUnderlinedFontId)) { // We need to fetch fresh font underline metrics FetchFontUnderlineMetrics(fontClient, glyphInfo, currentUnderlinePosition, underlineHeight, currentUnderlineThickness, maxUnderlineThickness, lastUnderlinedFontId); @@ -741,37 +736,37 @@ Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth // Retrieves the glyph's position. const Vector2* const position = positionBuffer + glyphIndex; - if ( baseline < position->y + glyphInfo->yBearing ) + if(baseline < position->y + glyphInfo->yBearing) { baseline = position->y + glyphInfo->yBearing; } // Calculate the positions of leftmost and rightmost glyphs in the current line - if ( position->x < lineExtentLeft) + if(position->x < lineExtentLeft) { lineExtentLeft = position->x; } - if ( position->x + glyphInfo->width > lineExtentRight) + if(position->x + glyphInfo->width > lineExtentRight) { lineExtentRight = position->x + glyphInfo->width; } // Retrieves the glyph's color. - const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndexBuffer + glyphIndex ); + const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndexBuffer + glyphIndex); Vector4 color; - if ( style == Typesetter::STYLE_SHADOW ) + if(style == Typesetter::STYLE_SHADOW) { color = mModel->GetShadowColor(); } - else if ( style == Typesetter::STYLE_OUTLINE ) + else if(style == Typesetter::STYLE_OUTLINE) { color = mModel->GetOutlineColor(); } else { - color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + ( colorIndex - 1u ) ); + color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + (colorIndex - 1u)); } // Premultiply alpha @@ -781,29 +776,29 @@ Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth // Retrieves the glyph's bitmap. glyphData.glyphBitmap.buffer = NULL; - glyphData.glyphBitmap.width = glyphInfo->width; // Desired width and height. + glyphData.glyphBitmap.width = glyphInfo->width; // Desired width and height. glyphData.glyphBitmap.height = glyphInfo->height; - if( style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW ) + if(style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW) { // Don't render outline for other styles outlineWidth = 0.0f; } - if( style != Typesetter::STYLE_UNDERLINE ) + if(style != Typesetter::STYLE_UNDERLINE) { - fontClient.CreateBitmap( glyphInfo->fontId, - glyphInfo->index, - glyphInfo->isItalicRequired, - glyphInfo->isBoldRequired, - glyphData.glyphBitmap, - static_cast( outlineWidth ) ); + fontClient.CreateBitmap(glyphInfo->fontId, + glyphInfo->index, + glyphInfo->isItalicRequired, + glyphInfo->isBoldRequired, + glyphData.glyphBitmap, + static_cast(outlineWidth)); } // Sets the glyph's bitmap into the bitmap of the whole text. - if( NULL != glyphData.glyphBitmap.buffer ) + if(NULL != glyphData.glyphBitmap.buffer) { - if ( style == Typesetter::STYLE_OUTLINE ) + if(style == Typesetter::STYLE_OUTLINE) { // Set the position offset for the current glyph glyphData.horizontalOffset -= glyphData.glyphBitmap.outlineOffsetX; @@ -811,13 +806,13 @@ Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth } // Set the buffer of the glyph's bitmap into the final bitmap's buffer - TypesetGlyph( glyphData, - position, - &color, - style, - pixelFormat); + TypesetGlyph(glyphData, + position, + &color, + style, + pixelFormat); - if ( style == Typesetter::STYLE_OUTLINE ) + if(style == Typesetter::STYLE_OUTLINE) { // Reset the position offset for the next glyph glyphData.horizontalOffset += glyphData.glyphBitmap.outlineOffsetX; @@ -825,94 +820,94 @@ Devel::PixelBuffer Typesetter::CreateImageBuffer( const unsigned int bufferWidth } // delete the glyphBitmap.buffer as it is now copied into glyphData.bitmapBuffer - delete []glyphData.glyphBitmap.buffer; + delete[] glyphData.glyphBitmap.buffer; glyphData.glyphBitmap.buffer = NULL; } } // Draw the underline from the leftmost glyph to the rightmost glyph - if ( thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE ) + if(thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE) { DrawUnderline(underlineColor, bufferWidth, bufferHeight, glyphData, baseline, currentUnderlinePosition, maxUnderlineThickness, lineExtentLeft, lineExtentRight); } // Draw the background color from the leftmost glyph to the rightmost glyph - if ( style == Typesetter::STYLE_BACKGROUND ) + if(style == Typesetter::STYLE_BACKGROUND) { DrawBackgroundColor(mModel->GetBackgroundColor(), bufferWidth, bufferHeight, glyphData, baseline, line, lineExtentLeft, lineExtentRight); } // Increases the vertical offset with the line's descender. - glyphData.verticalOffset += static_cast( -line.descender ); + glyphData.verticalOffset += static_cast(-line.descender); } return glyphData.bitmapBuffer; } -Devel::PixelBuffer Typesetter::CombineImageBuffer( Devel::PixelBuffer topPixelBuffer, Devel::PixelBuffer bottomPixelBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight ) +Devel::PixelBuffer Typesetter::CombineImageBuffer(Devel::PixelBuffer topPixelBuffer, Devel::PixelBuffer bottomPixelBuffer, const unsigned int bufferWidth, const unsigned int bufferHeight) { - unsigned char* topBuffer = topPixelBuffer.GetBuffer(); + unsigned char* topBuffer = topPixelBuffer.GetBuffer(); unsigned char* bottomBuffer = bottomPixelBuffer.GetBuffer(); Devel::PixelBuffer combinedPixelBuffer; - if ( topBuffer == NULL && bottomBuffer == NULL ) + if(topBuffer == NULL && bottomBuffer == NULL) { // Nothing to do if both buffers are empty. return combinedPixelBuffer; } - if ( topBuffer == NULL ) + if(topBuffer == NULL) { // Nothing to do if topBuffer is empty. return bottomPixelBuffer; } - if ( bottomBuffer == NULL ) + if(bottomBuffer == NULL) { // Nothing to do if bottomBuffer is empty. return topPixelBuffer; } // Always combine two RGBA images - const unsigned int bufferSizeInt = bufferWidth * bufferHeight; + const unsigned int bufferSizeInt = bufferWidth * bufferHeight; const unsigned int bufferSizeChar = 4u * bufferSizeInt; - combinedPixelBuffer = Devel::PixelBuffer::New( bufferWidth, bufferHeight, Pixel::RGBA8888 ); - uint8_t* combinedBuffer = reinterpret_cast< uint8_t* >( combinedPixelBuffer.GetBuffer() ); - memset( combinedBuffer, 0u, bufferSizeChar ); + combinedPixelBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888); + uint8_t* combinedBuffer = reinterpret_cast(combinedPixelBuffer.GetBuffer()); + memset(combinedBuffer, 0u, bufferSizeChar); - for (unsigned int pixelIndex = 0; pixelIndex < bufferSizeInt; pixelIndex++) + for(unsigned int pixelIndex = 0; pixelIndex < bufferSizeInt; pixelIndex++) { // If the alpha of the pixel in either buffer is not fully opaque, blend the two pixels. // Otherwise, copy pixel from topBuffer to combinedBuffer. - unsigned int alphaBuffer1 = topBuffer[pixelIndex*4+3]; + unsigned int alphaBuffer1 = topBuffer[pixelIndex * 4 + 3]; - if ( alphaBuffer1 != 255 ) + if(alphaBuffer1 != 255) { // At least one pixel is not fully opaque // "Over" blend the the pixel from topBuffer with the pixel in bottomBuffer - combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4] + ( bottomBuffer[pixelIndex*4] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 ); - combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1] + ( bottomBuffer[pixelIndex*4+1] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 ); - combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2] + ( bottomBuffer[pixelIndex*4+2] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 ); - combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3] + ( bottomBuffer[pixelIndex*4+3] * ( 255 - topBuffer[pixelIndex*4+3] ) / 255 ); + combinedBuffer[pixelIndex * 4] = topBuffer[pixelIndex * 4] + (bottomBuffer[pixelIndex * 4] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255); + combinedBuffer[pixelIndex * 4 + 1] = topBuffer[pixelIndex * 4 + 1] + (bottomBuffer[pixelIndex * 4 + 1] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255); + combinedBuffer[pixelIndex * 4 + 2] = topBuffer[pixelIndex * 4 + 2] + (bottomBuffer[pixelIndex * 4 + 2] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255); + combinedBuffer[pixelIndex * 4 + 3] = topBuffer[pixelIndex * 4 + 3] + (bottomBuffer[pixelIndex * 4 + 3] * (255 - topBuffer[pixelIndex * 4 + 3]) / 255); } else { // Copy the pixel from topBuffer to combinedBuffer - combinedBuffer[pixelIndex*4] = topBuffer[pixelIndex*4]; - combinedBuffer[pixelIndex*4+1] = topBuffer[pixelIndex*4+1]; - combinedBuffer[pixelIndex*4+2] = topBuffer[pixelIndex*4+2]; - combinedBuffer[pixelIndex*4+3] = topBuffer[pixelIndex*4+3]; + combinedBuffer[pixelIndex * 4] = topBuffer[pixelIndex * 4]; + combinedBuffer[pixelIndex * 4 + 1] = topBuffer[pixelIndex * 4 + 1]; + combinedBuffer[pixelIndex * 4 + 2] = topBuffer[pixelIndex * 4 + 2]; + combinedBuffer[pixelIndex * 4 + 3] = topBuffer[pixelIndex * 4 + 3]; } } return combinedPixelBuffer; } -Typesetter::Typesetter( const ModelInterface* const model ) -: mModel( new ViewModel( model ) ) +Typesetter::Typesetter(const ModelInterface* const model) +: mModel(new ViewModel(model)) { } diff --git a/dali-toolkit/internal/text/rendering/vector-based/glyphy-shader/glyphy-shader.cpp b/dali-toolkit/internal/text/rendering/vector-based/glyphy-shader/glyphy-shader.cpp index 71d3f19..4be2524 100644 --- a/dali-toolkit/internal/text/rendering/vector-based/glyphy-shader/glyphy-shader.cpp +++ b/dali-toolkit/internal/text/rendering/vector-based/glyphy-shader/glyphy-shader.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. @@ -29,175 +29,168 @@ using namespace Dali; namespace { - const char* const ENABLE_EXTENSION_PREFIX = -"#extension GL_OES_standard_derivatives : enable\n" -"precision highp float;\n" -"precision highp int;\n"; + "#extension GL_OES_standard_derivatives : enable\n" + "precision highp float;\n" + "precision highp int;\n"; const char* const VERTEX_SHADER_MAIN = -"uniform mediump mat4 uProjection;\n" -"uniform mediump mat4 uModelView;\n" -"uniform mediump mat4 uMvpMatrix;\n" -"uniform bool uTextureMapped;\n" -"uniform mediump vec4 uCustomTextureCoords;\n" -"attribute highp vec2 aTexCoord;\n" -"varying mediump vec2 vTexCoord;\n" -"uniform mat3 uModelViewIT;\n" -"attribute mediump vec3 aNormal;\n" -"varying mediump vec3 vNormal;\n" -"attribute mediump vec2 aPosition;\n" -"varying mediump vec4 vVertex;\n" -"attribute mediump vec4 aColor;\n" -"varying mediump vec4 vColor;\n" -"varying vec4 v_glyph;\n" -"\n" -"vec4\n" -"glyph_vertex_transcode (vec2 v)\n" -"{\n" -" ivec2 g = ivec2 (v);\n" -" ivec2 corner = ivec2 (mod (v, 2.));\n" -" g /= 2;\n" -" ivec2 nominal_size = ivec2 (mod (vec2(g), 64.));\n" -" return vec4 (corner * nominal_size, g * 4);\n" -"}\n" -"\n" -"void\n" -"main()\n" -"{\n" -" gl_Position = uMvpMatrix * vec4 (aPosition, 0.0, 1.0);\n" -" v_glyph = glyph_vertex_transcode (aTexCoord);\n" -" vColor = aColor;\n" -"}\n" -; + "uniform mediump mat4 uProjection;\n" + "uniform mediump mat4 uModelView;\n" + "uniform mediump mat4 uMvpMatrix;\n" + "uniform bool uTextureMapped;\n" + "uniform mediump vec4 uCustomTextureCoords;\n" + "attribute highp vec2 aTexCoord;\n" + "varying mediump vec2 vTexCoord;\n" + "uniform mat3 uModelViewIT;\n" + "attribute mediump vec3 aNormal;\n" + "varying mediump vec3 vNormal;\n" + "attribute mediump vec2 aPosition;\n" + "varying mediump vec4 vVertex;\n" + "attribute mediump vec4 aColor;\n" + "varying mediump vec4 vColor;\n" + "varying vec4 v_glyph;\n" + "\n" + "vec4\n" + "glyph_vertex_transcode (vec2 v)\n" + "{\n" + " ivec2 g = ivec2 (v);\n" + " ivec2 corner = ivec2 (mod (v, 2.));\n" + " g /= 2;\n" + " ivec2 nominal_size = ivec2 (mod (vec2(g), 64.));\n" + " return vec4 (corner * nominal_size, g * 4);\n" + "}\n" + "\n" + "void\n" + "main()\n" + "{\n" + " gl_Position = uMvpMatrix * vec4 (aPosition, 0.0, 1.0);\n" + " v_glyph = glyph_vertex_transcode (aTexCoord);\n" + " vColor = aColor;\n" + "}\n"; const char* const FRAGMENT_SHADER_PREFIX = -"struct Material\n" -"{\n" -" mediump float mOpacity;\n" -" mediump float mShininess;\n" -" lowp vec4 mAmbient;\n" -" lowp vec4 mDiffuse;\n" -" lowp vec4 mSpecular;\n" -" lowp vec4 mEmissive;\n" -"};\n" -"uniform sampler2D sTexture;\n" -"uniform sampler2D sOpacityTexture;\n" -"uniform sampler2D sNormalMapTexture;\n" -"uniform sampler2D sEffect;\n" -"varying mediump vec2 vTexCoord;\n" -"uniform Material uMaterial;\n" -"uniform lowp vec4 uColor;\n" -"varying highp vec4 vVertex;\n" -"varying highp vec3 vNormal;\n" -"varying mediump vec4 vColor;\n" -"uniform vec4 u_atlas_info;\n" -"\n" -"#define GLYPHY_TEXTURE1D_EXTRA_DECLS , sampler2D _tex, ivec4 _atlas_info, ivec2 _atlas_pos\n" -"#define GLYPHY_TEXTURE1D_EXTRA_ARGS , _tex, _atlas_info, _atlas_pos\n" -"#define GLYPHY_DEMO_EXTRA_ARGS , sTexture, uu_atlas_info, gi.atlas_pos\n" -"\n" -"vec4\n" -"glyphy_texture1D_func (int offset GLYPHY_TEXTURE1D_EXTRA_DECLS)\n" -"{\n" -" ivec2 item_geom = _atlas_info.zw;\n" -" vec2 pos = (vec2 (_atlas_pos.xy * item_geom +\n" -" ivec2 (mod (float (offset), float (item_geom.x)), offset / item_geom.x)) +\n" -" + vec2 (.5, .5)) / vec2(_atlas_info.xy);\n" -" return texture2D (_tex, pos);\n" -"}\n" -; + "struct Material\n" + "{\n" + " mediump float mOpacity;\n" + " mediump float mShininess;\n" + " lowp vec4 mAmbient;\n" + " lowp vec4 mDiffuse;\n" + " lowp vec4 mSpecular;\n" + " lowp vec4 mEmissive;\n" + "};\n" + "uniform sampler2D sTexture;\n" + "uniform sampler2D sOpacityTexture;\n" + "uniform sampler2D sNormalMapTexture;\n" + "uniform sampler2D sEffect;\n" + "varying mediump vec2 vTexCoord;\n" + "uniform Material uMaterial;\n" + "uniform lowp vec4 uColor;\n" + "varying highp vec4 vVertex;\n" + "varying highp vec3 vNormal;\n" + "varying mediump vec4 vColor;\n" + "uniform vec4 u_atlas_info;\n" + "\n" + "#define GLYPHY_TEXTURE1D_EXTRA_DECLS , sampler2D _tex, ivec4 _atlas_info, ivec2 _atlas_pos\n" + "#define GLYPHY_TEXTURE1D_EXTRA_ARGS , _tex, _atlas_info, _atlas_pos\n" + "#define GLYPHY_DEMO_EXTRA_ARGS , sTexture, uu_atlas_info, gi.atlas_pos\n" + "\n" + "vec4\n" + "glyphy_texture1D_func (int offset GLYPHY_TEXTURE1D_EXTRA_DECLS)\n" + "{\n" + " ivec2 item_geom = _atlas_info.zw;\n" + " vec2 pos = (vec2 (_atlas_pos.xy * item_geom +\n" + " ivec2 (mod (float (offset), float (item_geom.x)), offset / item_geom.x)) +\n" + " + vec2 (.5, .5)) / vec2(_atlas_info.xy);\n" + " return texture2D (_tex, pos);\n" + "}\n"; static const char* FRAGMENT_SHADER_MAIN = -"uniform float u_contrast;\n" -"uniform float u_gamma_adjust;\n" -"uniform float u_outline_thickness;\n" -"uniform float u_outline;\n" -"uniform float u_boldness;\n" -"\n" -"varying vec4 v_glyph;\n" -"\n" -"\n" -"#define SQRT2_2 0.70711 /* 1 / sqrt(2.) */\n" -"#define SQRT2 1.41421\n" -"\n" -"struct glyph_info_t {\n" -" ivec2 nominal_size;\n" -" ivec2 atlas_pos;\n" -"};\n" -"\n" -"glyph_info_t\n" -"glyph_info_decode (vec4 v)\n" -"{\n" -" glyph_info_t gi;\n" -" gi.nominal_size = (ivec2 (mod (v.zw, 256.)) + 2) / 4;\n" -" gi.atlas_pos = ivec2 (v_glyph.zw) / 256;\n" -" return gi;\n" -"}\n" -"\n" -"\n" -"float\n" -"antialias (float d)\n" -"{\n" -" return smoothstep (-.75, +.75, d);\n" -"}\n" -"\n" -"vec4\n" -"source_over (const vec4 src, const vec4 dst)\n" -"{\n" -" // http://dev.w3.org/fxtf/compositing-1/#porterduffcompositingoperators_srcover\n" -" float alpha = src.a + (dst.a * (1. - src.a));\n" -" return vec4 (((src.rgb * src.a) + (dst.rgb * dst.a * (1. - src.a))) / alpha, alpha);\n" -"}\n" -"\n" -"void\n" -"main()\n" -"{\n" -" vec2 p = v_glyph.xy;\n" -" glyph_info_t gi = glyph_info_decode (v_glyph);\n" -"\n" -" /* isotropic antialiasing */\n" -" vec2 dpdx = dFdx (p);\n" -" vec2 dpdy = dFdy (p);\n" -" float m = length (vec2 (length (dpdx), length (dpdy))) * SQRT2_2;\n" -"\n" -" vec4 color = vec4( vColor.rgb * uColor.rgb, vColor.a * uColor.a );\n" -"\n" -" ivec4 uu_atlas_info = ivec4( u_atlas_info );" -" float gsdist = glyphy_sdf (p, gi.nominal_size GLYPHY_DEMO_EXTRA_ARGS);\n" -" float sdist = gsdist / m * u_contrast;\n" -"\n" -" sdist -= u_boldness * 10.;\n" -" if ( glyphy_iszero( u_outline ) )\n" -" sdist = abs (sdist) - u_outline_thickness * .5;\n" -" if (sdist > 1.)\n" -" discard;\n" -" float alpha = antialias (-sdist);\n" -" if (u_gamma_adjust != 1.)\n" -" alpha = pow (alpha, 1./u_gamma_adjust);\n" -" color = vec4 (color.rgb,color.a * alpha);\n" -"\n" -" gl_FragColor = color;\n" -"}\n" -; + "uniform float u_contrast;\n" + "uniform float u_gamma_adjust;\n" + "uniform float u_outline_thickness;\n" + "uniform float u_outline;\n" + "uniform float u_boldness;\n" + "\n" + "varying vec4 v_glyph;\n" + "\n" + "\n" + "#define SQRT2_2 0.70711 /* 1 / sqrt(2.) */\n" + "#define SQRT2 1.41421\n" + "\n" + "struct glyph_info_t {\n" + " ivec2 nominal_size;\n" + " ivec2 atlas_pos;\n" + "};\n" + "\n" + "glyph_info_t\n" + "glyph_info_decode (vec4 v)\n" + "{\n" + " glyph_info_t gi;\n" + " gi.nominal_size = (ivec2 (mod (v.zw, 256.)) + 2) / 4;\n" + " gi.atlas_pos = ivec2 (v_glyph.zw) / 256;\n" + " return gi;\n" + "}\n" + "\n" + "\n" + "float\n" + "antialias (float d)\n" + "{\n" + " return smoothstep (-.75, +.75, d);\n" + "}\n" + "\n" + "vec4\n" + "source_over (const vec4 src, const vec4 dst)\n" + "{\n" + " // http://dev.w3.org/fxtf/compositing-1/#porterduffcompositingoperators_srcover\n" + " float alpha = src.a + (dst.a * (1. - src.a));\n" + " return vec4 (((src.rgb * src.a) + (dst.rgb * dst.a * (1. - src.a))) / alpha, alpha);\n" + "}\n" + "\n" + "void\n" + "main()\n" + "{\n" + " vec2 p = v_glyph.xy;\n" + " glyph_info_t gi = glyph_info_decode (v_glyph);\n" + "\n" + " /* isotropic antialiasing */\n" + " vec2 dpdx = dFdx (p);\n" + " vec2 dpdy = dFdy (p);\n" + " float m = length (vec2 (length (dpdx), length (dpdy))) * SQRT2_2;\n" + "\n" + " vec4 color = vec4( vColor.rgb * uColor.rgb, vColor.a * uColor.a );\n" + "\n" + " ivec4 uu_atlas_info = ivec4( u_atlas_info );" + " float gsdist = glyphy_sdf (p, gi.nominal_size GLYPHY_DEMO_EXTRA_ARGS);\n" + " float sdist = gsdist / m * u_contrast;\n" + "\n" + " sdist -= u_boldness * 10.;\n" + " if ( glyphy_iszero( u_outline ) )\n" + " sdist = abs (sdist) - u_outline_thickness * .5;\n" + " if (sdist > 1.)\n" + " discard;\n" + " float alpha = antialias (-sdist);\n" + " if (u_gamma_adjust != 1.)\n" + " alpha = pow (alpha, 1./u_gamma_adjust);\n" + " color = vec4 (color.rgb,color.a * alpha);\n" + "\n" + " gl_FragColor = color;\n" + "}\n"; } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - GlyphyShader::GlyphyShader() { } -GlyphyShader::GlyphyShader( Shader handle ) -: Shader( handle ) +GlyphyShader::GlyphyShader(Shader handle) +: Shader(handle) { } @@ -205,7 +198,7 @@ GlyphyShader::~GlyphyShader() { } -GlyphyShader GlyphyShader::New( const Dali::Vector4& atlasInfo ) +GlyphyShader GlyphyShader::New(const Dali::Vector4& atlasInfo) { std::ostringstream vertexShaderStringStream; std::ostringstream fragmentShaderStringStream; @@ -219,18 +212,18 @@ GlyphyShader GlyphyShader::New( const Dali::Vector4& atlasInfo ) << glyphy_sdf_glsl << FRAGMENT_SHADER_MAIN; - Shader shaderEffectCustom = Shader::New( vertexShaderStringStream.str(), - fragmentShaderStringStream.str(), - Shader::Hint::OUTPUT_IS_TRANSPARENT ); + Shader shaderEffectCustom = Shader::New(vertexShaderStringStream.str(), + fragmentShaderStringStream.str(), + Shader::Hint::OUTPUT_IS_TRANSPARENT); - GlyphyShader handle( shaderEffectCustom ); + GlyphyShader handle(shaderEffectCustom); - handle.RegisterProperty( "u_atlas_info", atlasInfo ); - handle.RegisterProperty( "u_contrast", 1.f ); - handle.RegisterProperty( "u_gamma_adjust", 1.f ); - handle.RegisterProperty( "u_outline_thickness", 1.f ); - handle.RegisterProperty( "u_outline", 1.f ); - handle.RegisterProperty( "u_boldness", 0.f ); + handle.RegisterProperty("u_atlas_info", atlasInfo); + handle.RegisterProperty("u_contrast", 1.f); + handle.RegisterProperty("u_gamma_adjust", 1.f); + handle.RegisterProperty("u_outline_thickness", 1.f); + handle.RegisterProperty("u_outline", 1.f); + handle.RegisterProperty("u_boldness", 0.f); return handle; } diff --git a/dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.cpp b/dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.cpp index d7b245d..76f8c85 100644 --- a/dali-toolkit/internal/text/rendering/vector-based/vector-based-renderer.cpp +++ b/dali-toolkit/internal/text/rendering/vector-based/vector-based-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,17 +19,17 @@ #include // EXTERNAL INCLUDES -#include -#include #include #include +#include +#include // INTERNAL INCLUDES #include -#include #include -#include #include +#include +#include using namespace Dali; using namespace Dali::Toolkit; @@ -37,79 +37,78 @@ using namespace Dali::Toolkit::Text; namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); #endif const float DEFAULT_POINT_SIZE = 13.f; struct Vertex2D { - float x; - float y; - float u; - float v; + float x; + float y; + float u; + float v; Vector4 color; }; -void AddVertex( Vector& vertices, float x, float y, float u, float v, const Vector4& color ) +void AddVertex(Vector& vertices, float x, float y, float u, float v, const Vector4& color) { Vertex2D meshVertex; - meshVertex.x = x; - meshVertex.y = y; - meshVertex.u = u; - meshVertex.v = v; + meshVertex.x = x; + meshVertex.y = y; + meshVertex.u = u; + meshVertex.v = v; meshVertex.color = color; - vertices.PushBack( meshVertex ); + vertices.PushBack(meshVertex); } -void AddTriangle( Vector& indices, unsigned int v0, unsigned int v1, unsigned int v2 ) +void AddTriangle(Vector& indices, unsigned int v0, unsigned int v1, unsigned int v2) { - indices.PushBack( v0 ); - indices.PushBack( v1 ); - indices.PushBack( v2 ); + indices.PushBack(v0); + indices.PushBack(v1); + indices.PushBack(v2); } -bool CreateGeometry( const Vector& glyphs, - unsigned int numberOfGlyphs, - const Vector& positions, - float xOffset, - float yOffset, - VectorBlobAtlas& atlas, - Dali::TextAbstraction::FontClient& fontClient, - Vector< Vertex2D >& vertices, - Vector< unsigned short >& indices, - const Vector4* const colorsBuffer, - const ColorIndex* const colorIndicesBuffer, - const Vector4& defaultColor ) +bool CreateGeometry(const Vector& glyphs, + unsigned int numberOfGlyphs, + const Vector& positions, + float xOffset, + float yOffset, + VectorBlobAtlas& atlas, + Dali::TextAbstraction::FontClient& fontClient, + Vector& vertices, + Vector& indices, + const Vector4* const colorsBuffer, + const ColorIndex* const colorIndicesBuffer, + const Vector4& defaultColor) { // Whether the default color is used. - const bool useDefaultColor = ( NULL == colorsBuffer ); + const bool useDefaultColor = (NULL == colorsBuffer); - bool atlasFull( false ); + bool atlasFull(false); - for( unsigned int i=0, idx=0; i 0 && - glyphs[i].height > 0 ) + if(glyphs[i].width > 0 && + glyphs[i].height > 0) { - bool foundBlob( true ); + bool foundBlob(true); BlobCoordinate blobCoords[4]; - if( ! atlas.FindGlyph( glyphs[i].fontId, glyphs[i].index, blobCoords ) ) + if(!atlas.FindGlyph(glyphs[i].fontId, glyphs[i].index, blobCoords)) { // Add blob to atlas - VectorBlob* blob( NULL ); - unsigned int blobLength( 0 ); - unsigned int nominalWidth( 0 ); - unsigned int nominalHeight( 0 ); - fontClient.CreateVectorBlob( glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight ); + VectorBlob* blob(NULL); + unsigned int blobLength(0); + unsigned int nominalWidth(0); + unsigned int nominalHeight(0); + fontClient.CreateVectorBlob(glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight); - if( 0 != blobLength ) + if(0 != blobLength) { - bool glyphAdded = atlas.AddGlyph( glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight, blobCoords ); + bool glyphAdded = atlas.AddGlyph(glyphs[i].fontId, glyphs[i].index, blob, blobLength, nominalWidth, nominalHeight, blobCoords); foundBlob = glyphAdded; atlasFull = !glyphAdded; @@ -120,28 +119,28 @@ bool CreateGeometry( const Vector& glyphs, } } - if( foundBlob ) + if(foundBlob) { // Get the color of the character. - const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i ); - const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u ); - - const float x1( xOffset + positions[i].x ); - const float x2( xOffset + positions[i].x + glyphs[i].width ); - const float y1( yOffset + positions[i].y ); - const float y2( yOffset + positions[i].y + glyphs[i].height ); - - AddVertex( vertices, x1, y2, blobCoords[0].u, blobCoords[0].v, color ); - AddVertex( vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color ); - AddVertex( vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color ); - AddTriangle( indices, idx, idx+1, idx+2 ); - idx+=3; - - AddVertex( vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color ); - AddVertex( vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color ); - AddVertex( vertices, x2, y1, blobCoords[3].u, blobCoords[3].v, color ); - AddTriangle( indices, idx, idx+1, idx+2 ); - idx+=3; + const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndicesBuffer + i); + const Vector4& color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + colorIndex - 1u); + + const float x1(xOffset + positions[i].x); + const float x2(xOffset + positions[i].x + glyphs[i].width); + const float y1(yOffset + positions[i].y); + const float y2(yOffset + positions[i].y + glyphs[i].height); + + AddVertex(vertices, x1, y2, blobCoords[0].u, blobCoords[0].v, color); + AddVertex(vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color); + AddVertex(vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color); + AddTriangle(indices, idx, idx + 1, idx + 2); + idx += 3; + + AddVertex(vertices, x1, y1, blobCoords[1].u, blobCoords[1].v, color); + AddVertex(vertices, x2, y2, blobCoords[2].u, blobCoords[2].v, color); + AddVertex(vertices, x2, y1, blobCoords[3].u, blobCoords[3].v, color); + AddTriangle(indices, idx, idx + 1, idx + 2); + idx += 3; } } } @@ -158,16 +157,16 @@ struct VectorBasedRenderer::Impl { mFontClient = TextAbstraction::FontClient::Get(); - mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2; - mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2; - mQuadVertexFormat[ "aColor" ] = Property::VECTOR4; + mQuadVertexFormat["aPosition"] = Property::VECTOR2; + mQuadVertexFormat["aTexCoord"] = Property::VECTOR2; + mQuadVertexFormat["aColor"] = Property::VECTOR4; } - Actor mActor; ///< The actor parent which renders the text + Actor mActor; ///< The actor parent which renders the text TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information - Property::Map mQuadVertexFormat; ///> Describes the vertex format for text + Property::Map mQuadVertexFormat; ///> Describes the vertex format for text Shader mShaderEffect; @@ -176,79 +175,79 @@ struct VectorBasedRenderer::Impl Text::RendererPtr VectorBasedRenderer::New() { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::VectorBasedRenderer::New()\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Text::VectorBasedRenderer::New()\n"); - return Text::RendererPtr( new VectorBasedRenderer() ); + return Text::RendererPtr(new VectorBasedRenderer()); } -Actor VectorBasedRenderer::Render( Text::ViewInterface& view, - Actor textControl, - Property::Index animatablePropertyIndex, - float& alignmentOffset, - int /*depth*/ ) +Actor VectorBasedRenderer::Render(Text::ViewInterface& view, + Actor textControl, + Property::Index animatablePropertyIndex, + float& alignmentOffset, + int /*depth*/) { - UnparentAndReset( mImpl->mActor ); + UnparentAndReset(mImpl->mActor); mImpl->mActor = Actor::New(); - mImpl->mActor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mImpl->mActor.SetProperty( Actor::Property::SIZE, Vector2( view.GetControlSize() ) ); - mImpl->mActor.SetProperty( Actor::Property::COLOR, Color::WHITE ); + mImpl->mActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mImpl->mActor.SetProperty(Actor::Property::SIZE, Vector2(view.GetControlSize())); + mImpl->mActor.SetProperty(Actor::Property::COLOR, Color::WHITE); #if defined(DEBUG_ENABLED) - mImpl->mActor.SetProperty( Dali::Actor::Property::NAME, "Text renderable actor" ); + mImpl->mActor.SetProperty(Dali::Actor::Property::NAME, "Text renderable actor"); #endif Length numberOfGlyphs = view.GetNumberOfGlyphs(); - if( numberOfGlyphs > 0u ) + if(numberOfGlyphs > 0u) { Vector glyphs; - glyphs.Resize( numberOfGlyphs ); + glyphs.Resize(numberOfGlyphs); Vector positions; - positions.Resize( numberOfGlyphs ); + positions.Resize(numberOfGlyphs); - numberOfGlyphs = view.GetGlyphs( glyphs.Begin(), - positions.Begin(), - alignmentOffset, - 0u, - numberOfGlyphs ); + numberOfGlyphs = view.GetGlyphs(glyphs.Begin(), + positions.Begin(), + alignmentOffset, + 0u, + numberOfGlyphs); - glyphs.Resize( numberOfGlyphs ); - positions.Resize( numberOfGlyphs ); + glyphs.Resize(numberOfGlyphs); + positions.Resize(numberOfGlyphs); - const Vector4* const colorsBuffer = view.GetColors(); + const Vector4* const colorsBuffer = view.GetColors(); const ColorIndex* const colorIndicesBuffer = view.GetColorIndices(); - const Vector4& defaultColor = view.GetTextColor(); + const Vector4& defaultColor = view.GetTextColor(); - Vector< Vertex2D > vertices; - Vector< unsigned short > indices; + Vector vertices; + Vector indices; const Vector2& controlSize = view.GetControlSize(); - float xOffset = -alignmentOffset + controlSize.width * -0.5f; - float yOffset = controlSize.height * -0.5f; + float xOffset = -alignmentOffset + controlSize.width * -0.5f; + float yOffset = controlSize.height * -0.5f; - if( ! mImpl->mAtlas || - mImpl->mAtlas->IsFull() ) + if(!mImpl->mAtlas || + mImpl->mAtlas->IsFull()) { VectorBlobAtlasShare atlasShare = VectorBlobAtlasShare::Get(); - mImpl->mAtlas = atlasShare.GetCurrentAtlas(); + mImpl->mAtlas = atlasShare.GetCurrentAtlas(); } // First try adding the glyphs to the previous shared atlas - bool allGlyphsAdded = CreateGeometry( glyphs, - numberOfGlyphs, - positions, - xOffset, - yOffset, - *mImpl->mAtlas, - mImpl->mFontClient, - vertices, - indices, - colorsBuffer, - colorIndicesBuffer, - defaultColor ); - - if( ! allGlyphsAdded ) + bool allGlyphsAdded = CreateGeometry(glyphs, + numberOfGlyphs, + positions, + xOffset, + yOffset, + *mImpl->mAtlas, + mImpl->mFontClient, + vertices, + indices, + colorsBuffer, + colorIndicesBuffer, + defaultColor); + + if(!allGlyphsAdded) { // The current atlas is full, abandon it and use a new one mImpl->mAtlas.Reset(); @@ -256,42 +255,41 @@ Actor VectorBasedRenderer::Render( Text::ViewInterface& view, indices.Clear(); VectorBlobAtlasShare atlasShare = VectorBlobAtlasShare::Get(); - mImpl->mAtlas = atlasShare.GetNewAtlas(); - - CreateGeometry( glyphs, - numberOfGlyphs, - positions, - xOffset, - yOffset, - *mImpl->mAtlas, - mImpl->mFontClient, - vertices, - indices, - colorsBuffer, - colorIndicesBuffer, - defaultColor ); + mImpl->mAtlas = atlasShare.GetNewAtlas(); + + CreateGeometry(glyphs, + numberOfGlyphs, + positions, + xOffset, + yOffset, + *mImpl->mAtlas, + mImpl->mFontClient, + vertices, + indices, + colorsBuffer, + colorIndicesBuffer, + defaultColor); // Return value ignored; using more than an entire new atlas is not supported } - if( 0 != vertices.Count() ) + if(0 != vertices.Count()) { - VertexBuffer quadVertices = VertexBuffer::New( mImpl->mQuadVertexFormat ); - - quadVertices.SetData( &vertices[ 0 ], vertices.Size() ); + VertexBuffer quadVertices = VertexBuffer::New(mImpl->mQuadVertexFormat); + quadVertices.SetData(&vertices[0], vertices.Size()); Geometry quadGeometry = Geometry::New(); - quadGeometry.AddVertexBuffer( quadVertices ); - quadGeometry.SetIndexBuffer( &indices[ 0 ], indices.Size() ); + quadGeometry.AddVertexBuffer(quadVertices); + quadGeometry.SetIndexBuffer(&indices[0], indices.Size()); TextureSet texture = mImpl->mAtlas->GetTextureSet(); const Vector4 atlasInfo = mImpl->mAtlas->GetInfo(); - mImpl->mShaderEffect = GlyphyShader::New( atlasInfo ); + mImpl->mShaderEffect = GlyphyShader::New(atlasInfo); - Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, mImpl->mShaderEffect ); - renderer.SetTextures( texture ); - mImpl->mActor.AddRenderer( renderer ); + Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, mImpl->mShaderEffect); + renderer.SetTextures(texture); + mImpl->mActor.AddRenderer(renderer); } } diff --git a/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.cpp b/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.cpp index 98c94a8..a1db81e 100644 --- a/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.cpp +++ b/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas-share.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,36 +19,31 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace { - -const int INITIAL_VECTOR_BLOB_ATLAS_WIDTH = 512; +const int INITIAL_VECTOR_BLOB_ATLAS_WIDTH = 512; const int INITIAL_VECTOR_BLOB_ATLAS_HEIGHT = 512; -const int NEW_VECTOR_BLOB_ATLAS_WIDTH = 1024; +const int NEW_VECTOR_BLOB_ATLAS_WIDTH = 1024; const int NEW_VECTOR_BLOB_ATLAS_HEIGHT = 1024; -const int VECTOR_BLOB_ATLAS_ITEM_WIDTH = 64; +const int VECTOR_BLOB_ATLAS_ITEM_WIDTH = 64; const int VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM = 8; } // unnamed namespace namespace Dali { - namespace Toolkit { - namespace Text { - class VectorBlobAtlasShare::Impl : public Dali::BaseObject { public: - /** * @brief Constructor */ @@ -58,9 +53,9 @@ public: VectorBlobAtlas* GetCurrentAtlas() { - if( ! mCurrentAtlas ) + if(!mCurrentAtlas) { - mCurrentAtlas = new VectorBlobAtlas( INITIAL_VECTOR_BLOB_ATLAS_WIDTH, INITIAL_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM ); + mCurrentAtlas = new VectorBlobAtlas(INITIAL_VECTOR_BLOB_ATLAS_WIDTH, INITIAL_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM); } return mCurrentAtlas.Get(); @@ -69,15 +64,14 @@ public: VectorBlobAtlas* GetNewAtlas() { // The current atlas should have been filled, before asking for a new one - DALI_ASSERT_DEBUG( mCurrentAtlas->IsFull() && "Current atlas is not full yet" ); + DALI_ASSERT_DEBUG(mCurrentAtlas->IsFull() && "Current atlas is not full yet"); - mCurrentAtlas = new VectorBlobAtlas( NEW_VECTOR_BLOB_ATLAS_WIDTH, NEW_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM ); + mCurrentAtlas = new VectorBlobAtlas(NEW_VECTOR_BLOB_ATLAS_WIDTH, NEW_VECTOR_BLOB_ATLAS_HEIGHT, VECTOR_BLOB_ATLAS_ITEM_WIDTH, VECTOR_BLOB_ATLAS_HEIGHT_QUANTUM); return mCurrentAtlas.Get(); } protected: - /** * A reference counted object may only be deleted by calling Unreference() */ @@ -86,7 +80,6 @@ protected: } private: - IntrusivePtr mCurrentAtlas; }; @@ -103,42 +96,42 @@ VectorBlobAtlasShare VectorBlobAtlasShare::Get() VectorBlobAtlasShare manager; // Check whether the VectorBlobAtlasShare is already created - SingletonService singletonService( SingletonService::Get() ); - if ( singletonService ) + SingletonService singletonService(SingletonService::Get()); + if(singletonService) { - Dali::BaseHandle handle = singletonService.GetSingleton( typeid( VectorBlobAtlasShare ) ); - if( handle ) + Dali::BaseHandle handle = singletonService.GetSingleton(typeid(VectorBlobAtlasShare)); + if(handle) { // If so, downcast the handle of singleton to VectorBlobAtlasShare - manager = VectorBlobAtlasShare( dynamic_cast( handle.GetObjectPtr() ) ); + manager = VectorBlobAtlasShare(dynamic_cast(handle.GetObjectPtr())); } - if( !manager ) + if(!manager) { // If not, create the VectorBlobAtlasShare and register it as a singleton - manager = VectorBlobAtlasShare( new VectorBlobAtlasShare::Impl() ); - singletonService.Register( typeid( manager ), manager ); + manager = VectorBlobAtlasShare(new VectorBlobAtlasShare::Impl()); + singletonService.Register(typeid(manager), manager); } } return manager; } -VectorBlobAtlasShare::VectorBlobAtlasShare( VectorBlobAtlasShare::Impl* impl ) -: BaseHandle( impl ) +VectorBlobAtlasShare::VectorBlobAtlasShare(VectorBlobAtlasShare::Impl* impl) +: BaseHandle(impl) { } VectorBlobAtlas* VectorBlobAtlasShare::GetCurrentAtlas() { - VectorBlobAtlasShare::Impl& impl = static_cast( GetBaseObject() ); + VectorBlobAtlasShare::Impl& impl = static_cast(GetBaseObject()); return impl.GetCurrentAtlas(); } VectorBlobAtlas* VectorBlobAtlasShare::GetNewAtlas() { - VectorBlobAtlasShare::Impl& impl = static_cast( GetBaseObject() ); + VectorBlobAtlasShare::Impl& impl = static_cast(GetBaseObject()); return impl.GetNewAtlas(); } diff --git a/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.cpp b/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.cpp index b17400c..3b4270d 100644 --- a/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.cpp +++ b/dali-toolkit/internal/text/rendering/vector-based/vector-blob-atlas.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,27 +23,20 @@ namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING"); #endif -} +} // namespace namespace Dali { - namespace Toolkit { - namespace Text { - static void -EncodeBlobCoordinate( unsigned int cornerX, unsigned int cornerY, - unsigned int atlasX, unsigned int atlasY, - unsigned int nominalWidth, unsigned int nominalHeight, - BlobCoordinate* v ) +EncodeBlobCoordinate(unsigned int cornerX, unsigned int cornerY, unsigned int atlasX, unsigned int atlasY, unsigned int nominalWidth, unsigned int nominalHeight, BlobCoordinate* v) { DALI_ASSERT_DEBUG(0 == (atlasX & ~0x7F)); DALI_ASSERT_DEBUG(0 == (atlasY & ~0x7F)); @@ -52,7 +45,7 @@ EncodeBlobCoordinate( unsigned int cornerX, unsigned int cornerY, DALI_ASSERT_DEBUG(0 == (nominalWidth & ~0x3F)); DALI_ASSERT_DEBUG(0 == (nominalHeight & ~0x3F)); - unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX; + unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX; unsigned int y = (((atlasY << 6) | nominalHeight) << 1) | cornerY; unsigned int encoded = (x << 16) | y; @@ -61,21 +54,21 @@ EncodeBlobCoordinate( unsigned int cornerX, unsigned int cornerY, v->v = encoded & 0xFFFF; } -VectorBlobAtlas::VectorBlobAtlas( unsigned int textureWidth, - unsigned int textureHeight, - unsigned int itemWidth, - unsigned int itemHeightQuantum ) -: mTextureWidth( textureWidth ), - mTextureHeight( textureHeight ), - mItemWidth( itemWidth ), - mItemHeightQuantum( itemHeightQuantum ), - mCursorX( 0 ), - mCursorY( 0 ), - mIsFull( false ) +VectorBlobAtlas::VectorBlobAtlas(unsigned int textureWidth, + unsigned int textureHeight, + unsigned int itemWidth, + unsigned int itemHeightQuantum) +: mTextureWidth(textureWidth), + mTextureHeight(textureHeight), + mItemWidth(itemWidth), + mItemHeightQuantum(itemHeightQuantum), + mCursorX(0), + mCursorY(0), + mIsFull(false) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Blob atlas %p size %dx%d, item width %d, height quantum %d\n", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p size %dx%d, item width %d, height quantum %d\n", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum); - mAtlasTexture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight ); + mAtlasTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight); mTextureSet = TextureSet::New(); mTextureSet.SetTexture(0, mAtlasTexture); @@ -86,18 +79,18 @@ bool VectorBlobAtlas::IsFull() const return mIsFull; } -bool VectorBlobAtlas::FindGlyph( FontId fontId, - GlyphIndex glyphIndex, - BlobCoordinate* coords ) +bool VectorBlobAtlas::FindGlyph(FontId fontId, + GlyphIndex glyphIndex, + BlobCoordinate* coords) { - const unsigned int size( mItemLookup.size() ); + const unsigned int size(mItemLookup.size()); - for( unsigned int i=0; i mTextureHeight ) + if(mCursorY + h > mTextureHeight) { // Go to next column mCursorX += mItemWidth; mCursorY = 0; } - if( mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight ) + if(mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight) { x = mCursorX; y = mCursorY; @@ -144,46 +137,42 @@ bool VectorBlobAtlas::AddGlyph( unsigned int fontId, } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "Blob atlas %p is now FULL\n", this ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p is now FULL\n", this); // The atlas is now considered to be full mIsFull = true; return false; } - if (w * h == length) + if(w * h == length) { - TexSubImage( x, y, w, h, blob ); + TexSubImage(x, y, w, h, blob); } else { - TexSubImage( x, y, w, h-1, blob ); + TexSubImage(x, y, w, h - 1, blob); // Upload the last row separately - TexSubImage( x, y + h - 1, length - (w * (h - 1)), 1 , blob + w * (h - 1)); + TexSubImage(x, y + h - 1, length - (w * (h - 1)), 1, blob + w * (h - 1)); } - DALI_LOG_INFO( gLogFilter, Debug::General, "Blob atlas %p capacity %d filled %d %f\%\n", - this, - mTextureWidth*mTextureHeight, - mCursorY*mItemWidth + mCursorX*mTextureHeight, - 100.0f * (float)(mCursorY*mItemWidth + mCursorX*mTextureHeight) / (float)(mTextureWidth*mTextureHeight) ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Blob atlas %p capacity %d filled %d %f\%\n", this, mTextureWidth * mTextureHeight, mCursorY * mItemWidth + mCursorX * mTextureHeight, 100.0f * (float)(mCursorY * mItemWidth + mCursorX * mTextureHeight) / (float)(mTextureWidth * mTextureHeight)); Key key; - key.fontId = fontId; + key.fontId = fontId; key.glyphIndex = glyphIndex; key.cacheIndex = mItemCache.size(); - mItemLookup.push_back( key ); + mItemLookup.push_back(key); x /= mItemWidth; y /= mItemHeightQuantum; Item item; - EncodeBlobCoordinate( 0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0] ); // BOTTOM_LEFT - EncodeBlobCoordinate( 0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1] ); // TOP_LEFT - EncodeBlobCoordinate( 1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2] ); // BOTTOM_RIGHT - EncodeBlobCoordinate( 1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3] ); // TOP_RIGHT - mItemCache.push_back( item ); + EncodeBlobCoordinate(0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0]); // BOTTOM_LEFT + EncodeBlobCoordinate(0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1]); // TOP_LEFT + EncodeBlobCoordinate(1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2]); // BOTTOM_RIGHT + EncodeBlobCoordinate(1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3]); // TOP_RIGHT + mItemCache.push_back(item); coords[0] = item.coords[0]; coords[1] = item.coords[1]; @@ -193,26 +182,26 @@ bool VectorBlobAtlas::AddGlyph( unsigned int fontId, return true; } -void VectorBlobAtlas::TexSubImage( unsigned int offsetX, - unsigned int offsetY, - unsigned int width, - unsigned int height, - VectorBlob* blob ) +void VectorBlobAtlas::TexSubImage(unsigned int offsetX, + unsigned int offsetY, + unsigned int width, + unsigned int height, + VectorBlob* blob) { - const size_t size = width * height * 4; - uint8_t* pixbuf = new uint8_t[size]; + const size_t size = width * height * 4; + uint8_t* pixbuf = new uint8_t[size]; size_t pos; size_t dataIndex = 0; - for( size_t y = 0; y < height; y++ ) + for(size_t y = 0; y < height; y++) { pos = y * mTextureWidth * 4; - for( size_t x = 0; x < width; x++ ) + for(size_t x = 0; x < width; x++) { - pixbuf[pos+x*4] = 0xFF & blob[dataIndex].r; - pixbuf[pos+x*4+1] = 0xFF & blob[dataIndex].g; - pixbuf[pos+x*4+2] = 0xFF & blob[dataIndex].b; - pixbuf[pos+x*4+3] = 0xFF & blob[dataIndex].a; + pixbuf[pos + x * 4] = 0xFF & blob[dataIndex].r; + pixbuf[pos + x * 4 + 1] = 0xFF & blob[dataIndex].g; + pixbuf[pos + x * 4 + 2] = 0xFF & blob[dataIndex].b; + pixbuf[pos + x * 4 + 3] = 0xFF & blob[dataIndex].a; dataIndex++; } } diff --git a/dali-toolkit/internal/text/rendering/view-model.cpp b/dali-toolkit/internal/text/rendering/view-model.cpp old mode 100755 new mode 100644 index 0e8dc61..e7b40a5 --- a/dali-toolkit/internal/text/rendering/view-model.cpp +++ b/dali-toolkit/internal/text/rendering/view-model.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,26 +19,23 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - namespace Text { - -ViewModel::ViewModel( const ModelInterface* const model ) -: mModel( model ), +ViewModel::ViewModel(const ModelInterface* const model) +: mModel(model), mElidedGlyphs(), mElidedLayout(), - mIsTextElided( false ) + mIsTextElided(false) { } @@ -103,9 +100,9 @@ const ScriptRun* const ViewModel::GetScriptRuns() const Length ViewModel::GetNumberOfGlyphs() const { - if( mIsTextElided && mModel->IsTextElideEnabled() ) + if(mIsTextElided && mModel->IsTextElideEnabled()) { - return mElidedGlyphs.Count(); + return mElidedGlyphs.Count(); } else { @@ -117,7 +114,7 @@ Length ViewModel::GetNumberOfGlyphs() const const GlyphInfo* const ViewModel::GetGlyphs() const { - if( mIsTextElided && mModel->IsTextElideEnabled() ) + if(mIsTextElided && mModel->IsTextElideEnabled()) { return mElidedGlyphs.Begin(); } @@ -131,7 +128,7 @@ const GlyphInfo* const ViewModel::GetGlyphs() const const Vector2* const ViewModel::GetLayout() const { - if( mIsTextElided && mModel->IsTextElideEnabled() ) + if(mIsTextElided && mModel->IsTextElideEnabled()) { return mElidedLayout.Begin(); } @@ -203,9 +200,9 @@ Length ViewModel::GetNumberOfUnderlineRuns() const return mModel->GetNumberOfUnderlineRuns(); } -void ViewModel::GetUnderlineRuns( GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns ) const +void ViewModel::GetUnderlineRuns(GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns) const { - mModel->GetUnderlineRuns( underlineRuns, index, numberOfRuns ); + mModel->GetUnderlineRuns(underlineRuns, index, numberOfRuns); } const Vector4& ViewModel::GetOutlineColor() const @@ -232,42 +229,42 @@ void ViewModel::ElideGlyphs() { mIsTextElided = false; - if( mModel->IsTextElideEnabled() ) + if(mModel->IsTextElideEnabled()) { const Length numberOfLines = mModel->GetNumberOfLines(); - if( 0u != numberOfLines ) + if(0u != numberOfLines) { const LineRun* const lines = mModel->GetLines(); - const LineRun& lastLine = *( lines + ( numberOfLines - 1u ) ); - const Length numberOfLaidOutGlyphs = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs; + const LineRun& lastLine = *(lines + (numberOfLines - 1u)); + const Length numberOfLaidOutGlyphs = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs; - if( lastLine.ellipsis && ( 0u != numberOfLaidOutGlyphs ) ) + if(lastLine.ellipsis && (0u != numberOfLaidOutGlyphs)) { - mIsTextElided = true; + mIsTextElided = true; TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - const GlyphInfo* const glyphs = mModel->GetGlyphs(); - const Vector2* const positions = mModel->GetLayout(); + const GlyphInfo* const glyphs = mModel->GetGlyphs(); + const Vector2* const positions = mModel->GetLayout(); // Copy the glyphs to be elided. - mElidedGlyphs.Resize( numberOfLaidOutGlyphs ); - mElidedLayout.Resize( numberOfLaidOutGlyphs ); + mElidedGlyphs.Resize(numberOfLaidOutGlyphs); + mElidedLayout.Resize(numberOfLaidOutGlyphs); - GlyphInfo* elidedGlyphsBuffer = mElidedGlyphs.Begin(); - Vector2* elidedPositionsBuffer = mElidedLayout.Begin(); + GlyphInfo* elidedGlyphsBuffer = mElidedGlyphs.Begin(); + Vector2* elidedPositionsBuffer = mElidedLayout.Begin(); - memcpy( elidedGlyphsBuffer, glyphs, numberOfLaidOutGlyphs * sizeof( GlyphInfo ) ); - memcpy( elidedPositionsBuffer, positions, numberOfLaidOutGlyphs * sizeof( Vector2 ) ); + memcpy(elidedGlyphsBuffer, glyphs, numberOfLaidOutGlyphs * sizeof(GlyphInfo)); + memcpy(elidedPositionsBuffer, positions, numberOfLaidOutGlyphs * sizeof(Vector2)); const Size& controlSize = mModel->GetControlSize(); - if( ( 1u == numberOfLines ) && - ( lastLine.ascender - lastLine.descender > controlSize.height ) ) + if((1u == numberOfLines) && + (lastLine.ascender - lastLine.descender > controlSize.height)) { // Get the first glyph which is going to be replaced and the ellipsis glyph. - GlyphInfo& glyphToRemove = *elidedGlyphsBuffer; - const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph( fontClient.GetPointSize( glyphToRemove.fontId ) ); + GlyphInfo& glyphToRemove = *elidedGlyphsBuffer; + const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph(fontClient.GetPointSize(glyphToRemove.fontId)); // Change the 'x' and 'y' position of the ellipsis glyph. Vector2& position = *elidedPositionsBuffer; @@ -278,45 +275,45 @@ void ViewModel::ElideGlyphs() // Replace the glyph by the ellipsis glyph and resize the buffers. glyphToRemove = ellipsisGlyph; - mElidedGlyphs.Resize( 1u ); - mElidedLayout.Resize( 1u ); + mElidedGlyphs.Resize(1u); + mElidedLayout.Resize(1u); return; } // firstPenX, penY and firstPenSet are used to position the ellipsis glyph if needed. - float firstPenX = 0.f; // Used if rtl text is elided. - float penY = 0.f; - bool firstPenSet = false; + float firstPenX = 0.f; // Used if rtl text is elided. + float penY = 0.f; + bool firstPenSet = false; // Add the ellipsis glyph. - bool inserted = false; - float removedGlypsWidth = 0.f; - Length numberOfRemovedGlyphs = 0u; - GlyphIndex index = numberOfLaidOutGlyphs - 1u; + bool inserted = false; + float removedGlypsWidth = 0.f; + Length numberOfRemovedGlyphs = 0u; + GlyphIndex index = numberOfLaidOutGlyphs - 1u; // The ellipsis glyph has to fit in the place where the last glyph(s) is(are) removed. - while( !inserted ) + while(!inserted) { - const GlyphInfo& glyphToRemove = *( elidedGlyphsBuffer + index ); + const GlyphInfo& glyphToRemove = *(elidedGlyphsBuffer + index); - if( 0u != glyphToRemove.fontId ) + if(0u != glyphToRemove.fontId) { // i.e. The font id of the glyph shaped from the '\n' character is zero. // Need to reshape the glyph as the font may be different in size. - const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph( fontClient.GetPointSize( glyphToRemove.fontId ) ); + const GlyphInfo& ellipsisGlyph = fontClient.GetEllipsisGlyph(fontClient.GetPointSize(glyphToRemove.fontId)); - if( !firstPenSet || EqualsZero( glyphToRemove.advance ) ) + if(!firstPenSet || EqualsZero(glyphToRemove.advance)) { - const Vector2& position = *( elidedPositionsBuffer + index ); + const Vector2& position = *(elidedPositionsBuffer + index); // Calculates the penY of the current line. It will be used to position the ellipsis glyph. penY = position.y + glyphToRemove.yBearing; // Calculates the first penX which will be used if rtl text is elided. firstPenX = position.x - glyphToRemove.xBearing; - if( firstPenX < -ellipsisGlyph.xBearing ) + if(firstPenX < -ellipsisGlyph.xBearing) { // Avoids to exceed the bounding box when rtl text is elided. firstPenX = -ellipsisGlyph.xBearing; @@ -324,32 +321,32 @@ void ViewModel::ElideGlyphs() removedGlypsWidth = -ellipsisGlyph.xBearing; - if( !EqualsZero( firstPenX ) ) + if(!EqualsZero(firstPenX)) { firstPenSet = true; } } - removedGlypsWidth += std::min( glyphToRemove.advance, ( glyphToRemove.xBearing + glyphToRemove.width ) ); + removedGlypsWidth += std::min(glyphToRemove.advance, (glyphToRemove.xBearing + glyphToRemove.width)); // Calculate the width of the ellipsis glyph and check if it fits. const float ellipsisGlyphWidth = ellipsisGlyph.width + ellipsisGlyph.xBearing; // If it is the last glyph to remove, add the ellipsis glyph without checking its width. - if( ( ellipsisGlyphWidth < removedGlypsWidth ) || ( index == 0u ) ) + if((ellipsisGlyphWidth < removedGlypsWidth) || (index == 0u)) { - GlyphInfo& glyphInfo = *( elidedGlyphsBuffer + index ); - Vector2& position = *( elidedPositionsBuffer + index ); - position.x -= ( 0.f > glyphInfo.xBearing ) ? glyphInfo.xBearing : 0.f; + GlyphInfo& glyphInfo = *(elidedGlyphsBuffer + index); + Vector2& position = *(elidedPositionsBuffer + index); + position.x -= (0.f > glyphInfo.xBearing) ? glyphInfo.xBearing : 0.f; // Replace the glyph by the ellipsis glyph. glyphInfo = ellipsisGlyph; // Change the 'x' and 'y' position of the ellipsis glyph. - if( position.x > firstPenX ) + if(position.x > firstPenX) { position.x = firstPenX; - if (ellipsisGlyphWidth < removedGlypsWidth) + if(ellipsisGlyphWidth < removedGlypsWidth) { position.x += removedGlypsWidth - ellipsisGlyphWidth; } @@ -362,9 +359,9 @@ void ViewModel::ElideGlyphs() } } - if( !inserted ) + if(!inserted) { - if( index > 0u ) + if(index > 0u) { --index; } @@ -377,10 +374,10 @@ void ViewModel::ElideGlyphs() } } // while( !inserted ) - // 'Removes' all the glyphs after the ellipsis glyph. + // 'Removes' all the glyphs after the ellipsis glyph. const Length numberOfGlyphs = numberOfLaidOutGlyphs - numberOfRemovedGlyphs; - mElidedGlyphs.Resize( numberOfGlyphs ); - mElidedLayout.Resize( numberOfGlyphs ); + mElidedGlyphs.Resize(numberOfGlyphs); + mElidedLayout.Resize(numberOfGlyphs); } } } diff --git a/dali-toolkit/internal/text/segmentation.cpp b/dali-toolkit/internal/text/segmentation.cpp index 61afef1..f52710c 100644 --- a/dali-toolkit/internal/text/segmentation.cpp +++ b/dali-toolkit/internal/text/segmentation.cpp @@ -21,8 +21,8 @@ // EXTERNAL INCLUDES #include #ifdef DEBUG_ENABLED -#include #include +#include #endif // INTERNAL INCLUDES @@ -32,48 +32,43 @@ namespace { - #if defined(DEBUG_ENABLED) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_SEGMENTATION"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_SEGMENTATION"); #endif } // namespace - namespace Dali { - namespace Toolkit { - namespace Text { - -void SetLineBreakInfo( const Vector& text, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& lineBreakInfo ) +void SetLineBreakInfo(const Vector& text, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& lineBreakInfo) { const Length totalNumberOfCharacters = text.Count(); - if( 0u == totalNumberOfCharacters ) + if(0u == totalNumberOfCharacters) { // Nothing to do if there are no characters. return; } // Retrieve the line break info. - lineBreakInfo.Resize( totalNumberOfCharacters ); + lineBreakInfo.Resize(totalNumberOfCharacters); // Whether the current buffer is being updated or is set from scratch. const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters; - LineBreakInfo* lineBreakInfoBuffer = NULL; + LineBreakInfo* lineBreakInfoBuffer = NULL; Vector newLineBreakInfo; - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newLineBreakInfo.Resize( numberOfCharacters ); + newLineBreakInfo.Resize(numberOfCharacters); lineBreakInfoBuffer = newLineBreakInfo.Begin(); } else @@ -82,63 +77,63 @@ void SetLineBreakInfo( const Vector& text, } // Retrieve the line break info. - TextAbstraction::Segmentation::Get().GetLineBreakPositions( text.Begin() + startIndex, - numberOfCharacters, - lineBreakInfoBuffer ); + TextAbstraction::Segmentation::Get().GetLineBreakPositions(text.Begin() + startIndex, + numberOfCharacters, + lineBreakInfoBuffer); // If the line break info is updated, it needs to be inserted in the model. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - lineBreakInfo.Insert( lineBreakInfo.Begin() + startIndex, - newLineBreakInfo.Begin(), - newLineBreakInfo.End() ); - lineBreakInfo.Resize( totalNumberOfCharacters ); + lineBreakInfo.Insert(lineBreakInfo.Begin() + startIndex, + newLineBreakInfo.Begin(), + newLineBreakInfo.End()); + lineBreakInfo.Resize(totalNumberOfCharacters); } #ifdef DEBUG_ENABLED - if( gLogFilter->IsEnabledFor(Debug::Verbose) ) + if(gLogFilter->IsEnabledFor(Debug::Verbose)) { std::string utf8; - Utf32ToUtf8( text.Begin(), numberOfCharacters, utf8 ); + Utf32ToUtf8(text.Begin(), numberOfCharacters, utf8); std::string info; - info.reserve( numberOfCharacters ); - for( unsigned int i=0; i('0' + lineBreakInfo[i]) ); + info.push_back(static_cast('0' + lineBreakInfo[i])); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetLineBreakInfo Characters: %s\n", utf8.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetLineBreakInfo Break info: %s\n", info.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetLineBreakInfo Characters: %s\n", utf8.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetLineBreakInfo Break info: %s\n", info.c_str()); } #endif } -void SetWordBreakInfo( const Vector& text, - CharacterIndex startIndex, - Length numberOfCharacters, - Vector& wordBreakInfo ) +void SetWordBreakInfo(const Vector& text, + CharacterIndex startIndex, + Length numberOfCharacters, + Vector& wordBreakInfo) { const Length totalNumberOfCharacters = text.Count(); - if( 0u == totalNumberOfCharacters ) + if(0u == totalNumberOfCharacters) { // Nothing to do if there are no characters. return; } // Resize the vector. - wordBreakInfo.Resize( totalNumberOfCharacters ); + wordBreakInfo.Resize(totalNumberOfCharacters); // Whether the current buffer is being updated or is set from scratch. const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters; - WordBreakInfo* wordBreakInfoBuffer = NULL; + WordBreakInfo* wordBreakInfoBuffer = NULL; Vector newWordBreakInfo; - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newWordBreakInfo.Resize( numberOfCharacters ); + newWordBreakInfo.Resize(numberOfCharacters); wordBreakInfoBuffer = newWordBreakInfo.Begin(); } else @@ -147,34 +142,34 @@ void SetWordBreakInfo( const Vector& text, } // Retrieve the word break info. - TextAbstraction::Segmentation::Get().GetWordBreakPositions( text.Begin() + startIndex, - numberOfCharacters, - wordBreakInfoBuffer ); + TextAbstraction::Segmentation::Get().GetWordBreakPositions(text.Begin() + startIndex, + numberOfCharacters, + wordBreakInfoBuffer); // If the word break info is updated, it needs to be inserted in the model. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - wordBreakInfo.Insert( wordBreakInfo.Begin() + startIndex, - newWordBreakInfo.Begin(), - newWordBreakInfo.End() ); - wordBreakInfo.Resize( totalNumberOfCharacters ); + wordBreakInfo.Insert(wordBreakInfo.Begin() + startIndex, + newWordBreakInfo.Begin(), + newWordBreakInfo.End()); + wordBreakInfo.Resize(totalNumberOfCharacters); } #ifdef DEBUG_ENABLED - if( gLogFilter->IsEnabledFor(Debug::Verbose) ) + if(gLogFilter->IsEnabledFor(Debug::Verbose)) { std::string utf8; - Utf32ToUtf8( text.Begin(), totalNumberOfCharacters, utf8 ); + Utf32ToUtf8(text.Begin(), totalNumberOfCharacters, utf8); std::string info; - info.reserve( totalNumberOfCharacters ); - for( unsigned int i=0; i('0' + wordBreakInfo[i]) ); + info.push_back(static_cast('0' + wordBreakInfo[i])); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetWordBreakInfo Characters: %s\n", utf8.c_str() ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "SetWordBreakInfo Break info: %s\n", info.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetWordBreakInfo Characters: %s\n", utf8.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "SetWordBreakInfo Break info: %s\n", info.c_str()); } #endif } diff --git a/dali-toolkit/internal/text/shaper.cpp b/dali-toolkit/internal/text/shaper.cpp old mode 100755 new mode 100644 index de41d0e..9d9fc1b --- a/dali-toolkit/internal/text/shaper.cpp +++ b/dali-toolkit/internal/text/shaper.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,50 +23,47 @@ namespace Dali { - namespace Toolkit { - namespace Text { - -CharacterIndex min( CharacterIndex index0, - CharacterIndex index1 ) +CharacterIndex min(CharacterIndex index0, + CharacterIndex index1) { - return ( index0 < index1 ) ? index0 : index1; + return (index0 < index1) ? index0 : index1; } -void ShapeText( const Vector& text, - const Vector& lineBreakInfo, - const Vector& scripts, - const Vector& fonts, - CharacterIndex startCharacterIndex, - GlyphIndex startGlyphIndex, - Length numberOfCharacters, - Vector& glyphs, - Vector& glyphToCharacterMap, - Vector& charactersPerGlyph, - Vector& newParagraphGlyphs ) +void ShapeText(const Vector& text, + const Vector& lineBreakInfo, + const Vector& scripts, + const Vector& fonts, + CharacterIndex startCharacterIndex, + GlyphIndex startGlyphIndex, + Length numberOfCharacters, + Vector& glyphs, + Vector& glyphToCharacterMap, + Vector& charactersPerGlyph, + Vector& newParagraphGlyphs) { - if( 0u == numberOfCharacters ) + if(0u == numberOfCharacters) { // Nothing to do if there are no characters. return; } #ifdef DEBUG_ENABLED - const Length numberOfFontRuns = fonts.Count(); - const Length numberOfScriptRuns = scripts.Count(); + const Length numberOfFontRuns = fonts.Count(); + const Length numberOfScriptRuns = scripts.Count(); const Length totalNumberOfCharacters = text.Count(); #endif - DALI_ASSERT_DEBUG( ( 0u != numberOfFontRuns ) && - ( totalNumberOfCharacters == fonts[numberOfFontRuns - 1u].characterRun.characterIndex + fonts[numberOfFontRuns - 1u].characterRun.numberOfCharacters ) && - "Toolkit::Text::ShapeText. All characters must have a font set." ); + DALI_ASSERT_DEBUG((0u != numberOfFontRuns) && + (totalNumberOfCharacters == fonts[numberOfFontRuns - 1u].characterRun.characterIndex + fonts[numberOfFontRuns - 1u].characterRun.numberOfCharacters) && + "Toolkit::Text::ShapeText. All characters must have a font set."); - DALI_ASSERT_DEBUG( ( 0u != numberOfScriptRuns ) && - ( totalNumberOfCharacters == scripts[numberOfScriptRuns - 1u].characterRun.characterIndex + scripts[numberOfScriptRuns - 1u].characterRun.numberOfCharacters ) && - "Toolkit::Text::ShapeText. All characters must have a script set." ); + DALI_ASSERT_DEBUG((0u != numberOfScriptRuns) && + (totalNumberOfCharacters == scripts[numberOfScriptRuns - 1u].characterRun.characterIndex + scripts[numberOfScriptRuns - 1u].characterRun.numberOfCharacters) && + "Toolkit::Text::ShapeText. All characters must have a script set."); // The text needs to be split in chunks of consecutive characters. // Each chunk must contain characters with the same font id and script set. @@ -78,10 +75,10 @@ void ShapeText( const Vector& text, // Get the font run containing the startCharacterIndex character. Vector::ConstIterator fontRunIt = fonts.Begin(); - for( Vector::ConstIterator endIt = fonts.End(); fontRunIt < endIt; ++fontRunIt ) + for(Vector::ConstIterator endIt = fonts.End(); fontRunIt < endIt; ++fontRunIt) { const FontRun& run = *fontRunIt; - if( startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters ) + if(startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters) { // Found. break; @@ -90,10 +87,10 @@ void ShapeText( const Vector& text, // Get the script run containing the startCharacterIndex character. Vector::ConstIterator scriptRunIt = scripts.Begin(); - for( Vector::ConstIterator endIt = scripts.End(); scriptRunIt < endIt; ++scriptRunIt ) + for(Vector::ConstIterator endIt = scripts.End(); scriptRunIt < endIt; ++scriptRunIt) { const ScriptRun& run = *scriptRunIt; - if( startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters ) + if(startCharacterIndex < run.characterRun.characterIndex + run.characterRun.numberOfCharacters) { // Found. break; @@ -113,40 +110,40 @@ void ShapeText( const Vector& text, GlyphInfo glyphInfo; glyphInfo.isItalicRequired = false; - glyphInfo.isBoldRequired = false; + glyphInfo.isBoldRequired = false; - const Length currentNumberOfGlyphs = glyphs.Count(); - const Length numberOfGlyphsReserved = static_cast( numberOfCharacters * 1.3f ); - glyphs.Reserve( currentNumberOfGlyphs + numberOfGlyphsReserved ); - glyphToCharacterMap.Reserve( currentNumberOfGlyphs + numberOfGlyphsReserved ); + const Length currentNumberOfGlyphs = glyphs.Count(); + const Length numberOfGlyphsReserved = static_cast(numberOfCharacters * 1.3f); + glyphs.Reserve(currentNumberOfGlyphs + numberOfGlyphsReserved); + glyphToCharacterMap.Reserve(currentNumberOfGlyphs + numberOfGlyphsReserved); // The actual number of glyphs. Length totalNumberOfGlyphs = currentNumberOfGlyphs; // The number of new glyphs. Length numberOfNewGlyphs = 0u; - const Character* const textBuffer = text.Begin(); - const LineBreakInfo* const lineBreakInfoBuffer = lineBreakInfo.Begin(); - CharacterIndex* glyphToCharacterMapBuffer = glyphToCharacterMap.Begin(); + const Character* const textBuffer = text.Begin(); + const LineBreakInfo* const lineBreakInfoBuffer = lineBreakInfo.Begin(); + CharacterIndex* glyphToCharacterMapBuffer = glyphToCharacterMap.Begin(); Length glyphIndex = startGlyphIndex; // Traverse the characters and shape the text. const CharacterIndex lastCharacter = startCharacterIndex + numberOfCharacters; - for( previousIndex = startCharacterIndex; previousIndex < lastCharacter; ) + for(previousIndex = startCharacterIndex; previousIndex < lastCharacter;) { // Get the font id and the script. - const FontRun& fontRun = *fontRunIt; + const FontRun& fontRun = *fontRunIt; const ScriptRun& scriptRun = *scriptRunIt; - currentFontId = fontRun.fontId; - currentScript = scriptRun.script; + currentFontId = fontRun.fontId; + currentScript = scriptRun.script; const bool isItalicRequired = fontRun.isItalicRequired; - const bool isBoldRequired = fontRun.isBoldRequired; + const bool isBoldRequired = fontRun.isBoldRequired; // Get the min index to the last character of both runs. - CharacterIndex currentIndex = min( fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters, - scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters ); + CharacterIndex currentIndex = min(fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters, + scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters); // Check if there is a line must break. bool mustBreak = false; @@ -156,43 +153,43 @@ void ShapeText( const Vector& text, // However, the metrics need to be changed in order to not to draw a square. bool isNewParagraph = false; - for( CharacterIndex index = previousIndex; index < currentIndex; ++index ) + for(CharacterIndex index = previousIndex; index < currentIndex; ++index) { - mustBreak = TextAbstraction::LINE_MUST_BREAK == *( lineBreakInfoBuffer + index ); - if( mustBreak ) + mustBreak = TextAbstraction::LINE_MUST_BREAK == *(lineBreakInfoBuffer + index); + if(mustBreak) { - isNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + index ) ); - currentIndex = index + 1u; + isNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + index)); + currentIndex = index + 1u; break; } } // Shape the text for the current chunk. - const Length numberOfGlyphs = shaping.Shape( textBuffer + previousIndex, - ( currentIndex - previousIndex ), // The number of characters to shape. - currentFontId, - currentScript ); + const Length numberOfGlyphs = shaping.Shape(textBuffer + previousIndex, + (currentIndex - previousIndex), // The number of characters to shape. + currentFontId, + currentScript); // Retrieve the glyphs and the glyph to character conversion map. - Vector tmpGlyphs; + Vector tmpGlyphs; Vector tmpGlyphToCharacterMap; GlyphInfo glyphInfo; glyphInfo.isItalicRequired = isItalicRequired; - glyphInfo.isBoldRequired = isBoldRequired; + glyphInfo.isBoldRequired = isBoldRequired; - tmpGlyphs.Resize( numberOfGlyphs, glyphInfo ); - tmpGlyphToCharacterMap.Resize( numberOfGlyphs ); - shaping.GetGlyphs( tmpGlyphs.Begin(), - tmpGlyphToCharacterMap.Begin() ); + tmpGlyphs.Resize(numberOfGlyphs, glyphInfo); + tmpGlyphToCharacterMap.Resize(numberOfGlyphs); + shaping.GetGlyphs(tmpGlyphs.Begin(), + tmpGlyphToCharacterMap.Begin()); // Update the new indices of the glyph to character map. - if( 0u != totalNumberOfGlyphs ) + if(0u != totalNumberOfGlyphs) { - for( Vector::Iterator it = tmpGlyphToCharacterMap.Begin(), - endIt = tmpGlyphToCharacterMap.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = tmpGlyphToCharacterMap.Begin(), + endIt = tmpGlyphToCharacterMap.End(); + it != endIt; + ++it) { *it += previousIndex; } @@ -201,26 +198,26 @@ void ShapeText( const Vector& text, totalNumberOfGlyphs += numberOfGlyphs; numberOfNewGlyphs += numberOfGlyphs; - glyphs.Insert( glyphs.Begin() + glyphIndex, tmpGlyphs.Begin(), tmpGlyphs.End() ); - glyphToCharacterMap.Insert( glyphToCharacterMap.Begin() + glyphIndex, tmpGlyphToCharacterMap.Begin(), tmpGlyphToCharacterMap.End() ); + glyphs.Insert(glyphs.Begin() + glyphIndex, tmpGlyphs.Begin(), tmpGlyphs.End()); + glyphToCharacterMap.Insert(glyphToCharacterMap.Begin() + glyphIndex, tmpGlyphToCharacterMap.Begin(), tmpGlyphToCharacterMap.End()); glyphIndex += numberOfGlyphs; // Set the buffer pointers again. glyphToCharacterMapBuffer = glyphToCharacterMap.Begin(); - if( isNewParagraph ) + if(isNewParagraph) { // Add the index of the new paragraph glyph to a vector. // Their metrics will be updated in a following step. - newParagraphGlyphs.PushBack( glyphIndex - 1u ); + newParagraphGlyphs.PushBack(glyphIndex - 1u); } // Update the iterators to get the next font or script run. - if( currentIndex == fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters ) + if(currentIndex == fontRun.characterRun.characterIndex + fontRun.characterRun.numberOfCharacters) { ++fontRunIt; } - if( currentIndex == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters ) + if(currentIndex == scriptRun.characterRun.characterIndex + scriptRun.characterRun.numberOfCharacters) { ++scriptRunIt; } @@ -230,31 +227,31 @@ void ShapeText( const Vector& text, } // Update indices. - for( Length index = startGlyphIndex + numberOfNewGlyphs; index < totalNumberOfGlyphs; ++index ) + for(Length index = startGlyphIndex + numberOfNewGlyphs; index < totalNumberOfGlyphs; ++index) { - CharacterIndex& characterIndex = *( glyphToCharacterMapBuffer + index ); + CharacterIndex& characterIndex = *(glyphToCharacterMapBuffer + index); characterIndex += numberOfCharacters; } // Add the number of characters per glyph. - charactersPerGlyph.Reserve( totalNumberOfGlyphs ); + charactersPerGlyph.Reserve(totalNumberOfGlyphs); Length* charactersPerGlyphBuffer = charactersPerGlyph.Begin(); const GlyphIndex lastGlyph = startGlyphIndex + numberOfNewGlyphs; - previousIndex = startCharacterIndex; - for( Length index = startGlyphIndex + 1u; index < lastGlyph; ++index ) + previousIndex = startCharacterIndex; + for(Length index = startGlyphIndex + 1u; index < lastGlyph; ++index) { - const CharacterIndex characterIndex = *( glyphToCharacterMapBuffer + index ); + const CharacterIndex characterIndex = *(glyphToCharacterMapBuffer + index); - charactersPerGlyph.Insert( charactersPerGlyphBuffer + index - 1u, characterIndex - previousIndex ); + charactersPerGlyph.Insert(charactersPerGlyphBuffer + index - 1u, characterIndex - previousIndex); previousIndex = characterIndex; } - charactersPerGlyph.Insert( charactersPerGlyphBuffer + lastGlyph - 1u, numberOfCharacters + startCharacterIndex - previousIndex ); + charactersPerGlyph.Insert(charactersPerGlyphBuffer + lastGlyph - 1u, numberOfCharacters + startCharacterIndex - previousIndex); // Resize the vectors to set the right number of items. - glyphs.Resize( totalNumberOfGlyphs ); - glyphToCharacterMap.Resize( totalNumberOfGlyphs ); + glyphs.Resize(totalNumberOfGlyphs); + glyphToCharacterMap.Resize(totalNumberOfGlyphs); } } // namespace Text diff --git a/dali-toolkit/internal/text/text-controller-event-handler.cpp b/dali-toolkit/internal/text/text-controller-event-handler.cpp index 89ff0f9..c6fbe87 100644 --- a/dali-toolkit/internal/text/text-controller-event-handler.cpp +++ b/dali-toolkit/internal/text/text-controller-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,9 +19,9 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include // INTERNAL INCLUDES #include @@ -29,44 +29,40 @@ namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif -const std::string KEY_C_NAME = "c"; -const std::string KEY_V_NAME = "v"; -const std::string KEY_X_NAME = "x"; -const std::string KEY_A_NAME = "a"; +const std::string KEY_C_NAME = "c"; +const std::string KEY_V_NAME = "v"; +const std::string KEY_X_NAME = "x"; +const std::string KEY_A_NAME = "a"; const std::string KEY_INSERT_NAME = "Insert"; } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - void Controller::EventHandler::KeyboardFocusGainEvent(Controller& controller) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected KeyboardFocusGainEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected KeyboardFocusGainEvent"); - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( ( EventData::INACTIVE == controller.mImpl->mEventData->mState ) || - ( EventData::INTERRUPTED == controller.mImpl->mEventData->mState ) ) + if((EventData::INACTIVE == controller.mImpl->mEventData->mState) || + (EventData::INTERRUPTED == controller.mImpl->mEventData->mState)) { - controller.mImpl->ChangeState( EventData::EDITING ); - controller.mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered. - controller.mImpl->mEventData->mUpdateInputStyle = true; + controller.mImpl->ChangeState(EventData::EDITING); + controller.mImpl->mEventData->mUpdateCursorPosition = true; //If editing started without tap event, cursor update must be triggered. + controller.mImpl->mEventData->mUpdateInputStyle = true; controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; } controller.mImpl->NotifyInputMethodContextMultiLineStatus(); - if( controller.mImpl->IsShowingPlaceholderText() ) + if(controller.mImpl->IsShowingPlaceholderText()) { // Show alternative placeholder-text when editing controller.ShowPlaceholderText(); @@ -78,15 +74,15 @@ void Controller::EventHandler::KeyboardFocusGainEvent(Controller& controller) void Controller::EventHandler::KeyboardFocusLostEvent(Controller& controller) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected KeyboardFocusLostEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected KeyboardFocusLostEvent"); - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( EventData::INTERRUPTED != controller.mImpl->mEventData->mState ) + if(EventData::INTERRUPTED != controller.mImpl->mEventData->mState) { - controller.mImpl->ChangeState( EventData::INACTIVE ); + controller.mImpl->ChangeState(EventData::INACTIVE); - if( !controller.mImpl->IsShowingRealText() ) + if(!controller.mImpl->IsShowingRealText()) { // Revert to regular placeholder-text when not editing controller.ShowPlaceholderText(); @@ -98,83 +94,83 @@ void Controller::EventHandler::KeyboardFocusLostEvent(Controller& controller) bool Controller::EventHandler::KeyEvent(Controller& controller, const Dali::KeyEvent& keyEvent) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected KeyEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected KeyEvent"); - bool textChanged = false; + bool textChanged = false; bool relayoutNeeded = false; - if( ( NULL != controller.mImpl->mEventData ) && - ( keyEvent.GetState() == KeyEvent::DOWN ) ) + if((NULL != controller.mImpl->mEventData) && + (keyEvent.GetState() == KeyEvent::DOWN)) { - int keyCode = keyEvent.GetKeyCode(); + int keyCode = keyEvent.GetKeyCode(); const std::string& keyString = keyEvent.GetKeyString(); - const std::string keyName = keyEvent.GetKeyName(); + const std::string keyName = keyEvent.GetKeyName(); // Key will produce same logical-key value when ctrl // is down, regardless of language layout const std::string logicalKey = keyEvent.GetLogicalKey(); - const bool isNullKey = ( 0 == keyCode ) && ( keyString.empty() ); + const bool isNullKey = (0 == keyCode) && (keyString.empty()); // Pre-process to separate modifying events from non-modifying input events. - if( isNullKey ) + if(isNullKey) { // In some platforms arrive key events with no key code. // Do nothing. return false; } - else if( Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode || Dali::DALI_KEY_SEARCH == keyCode ) + else if(Dali::DALI_KEY_ESCAPE == keyCode || Dali::DALI_KEY_BACK == keyCode || Dali::DALI_KEY_SEARCH == keyCode) { // Do nothing return false; } - else if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode ) || - ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) || - ( Dali::DALI_KEY_CURSOR_UP == keyCode ) || - ( Dali::DALI_KEY_CURSOR_DOWN == keyCode ) ) + else if((Dali::DALI_KEY_CURSOR_LEFT == keyCode) || + (Dali::DALI_KEY_CURSOR_RIGHT == keyCode) || + (Dali::DALI_KEY_CURSOR_UP == keyCode) || + (Dali::DALI_KEY_CURSOR_DOWN == keyCode)) { // If don't have any text, do nothing. - if( !controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters ) + if(!controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters) { return false; } - uint32_t cursorPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; + uint32_t cursorPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; uint32_t numberOfCharacters = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - uint32_t cursorLine = controller.mImpl->mModel->mVisualModel->GetLineOfCharacter( cursorPosition ); - uint32_t numberOfLines = controller.mImpl->mModel->GetNumberOfLines(); + uint32_t cursorLine = controller.mImpl->mModel->mVisualModel->GetLineOfCharacter(cursorPosition); + uint32_t numberOfLines = controller.mImpl->mModel->GetNumberOfLines(); // Logic to determine whether this text control will lose focus or not. - if( ( Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier() ) || - ( Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier() ) || - ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines -1 ) || - ( Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine -1 == numberOfLines -1 ) || - ( Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0 ) || - ( Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1 ) ) + if((Dali::DALI_KEY_CURSOR_LEFT == keyCode && 0 == cursorPosition && !keyEvent.IsShiftModifier()) || + (Dali::DALI_KEY_CURSOR_RIGHT == keyCode && numberOfCharacters == cursorPosition && !keyEvent.IsShiftModifier()) || + (Dali::DALI_KEY_CURSOR_DOWN == keyCode && cursorLine == numberOfLines - 1) || + (Dali::DALI_KEY_CURSOR_DOWN == keyCode && numberOfCharacters == cursorPosition && cursorLine - 1 == numberOfLines - 1) || + (Dali::DALI_KEY_CURSOR_UP == keyCode && cursorLine == 0) || + (Dali::DALI_KEY_CURSOR_UP == keyCode && numberOfCharacters == cursorPosition && cursorLine == 1)) { // Release the active highlight. - if( controller.mImpl->mEventData->mState == EventData::SELECTING ) + if(controller.mImpl->mEventData->mState == EventData::SELECTING) { - controller.mImpl->ChangeState( EventData::EDITING ); + controller.mImpl->ChangeState(EventData::EDITING); // Update selection position. - controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; + controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; controller.mImpl->mEventData->mRightSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; - controller.mImpl->mEventData->mUpdateCursorPosition = true; + controller.mImpl->mEventData->mUpdateCursorPosition = true; controller.mImpl->RequestRelayout(); } return false; } controller.mImpl->mEventData->mCheckScrollAmount = true; - Event event( Event::CURSOR_KEY_EVENT ); - event.p1.mInt = keyCode; + Event event(Event::CURSOR_KEY_EVENT); + event.p1.mInt = keyCode; event.p2.mBool = keyEvent.IsShiftModifier(); - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); // Will request for relayout. relayoutNeeded = true; } - else if ( Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode ) + else if(Dali::DevelKey::DALI_KEY_CONTROL_LEFT == keyCode || Dali::DevelKey::DALI_KEY_CONTROL_RIGHT == keyCode) { // Left or Right Control key event is received before Ctrl-C/V/X key event is received // If not handle it here, any selected text will be deleted @@ -182,56 +178,56 @@ bool Controller::EventHandler::KeyEvent(Controller& controller, const Dali::KeyE // Do nothing return false; } - else if ( keyEvent.IsCtrlModifier() && !keyEvent.IsShiftModifier()) + else if(keyEvent.IsCtrlModifier() && !keyEvent.IsShiftModifier()) { bool consumed = false; - if (keyName == KEY_C_NAME || keyName == KEY_INSERT_NAME || logicalKey == KEY_C_NAME || logicalKey == KEY_INSERT_NAME) + if(keyName == KEY_C_NAME || keyName == KEY_INSERT_NAME || logicalKey == KEY_C_NAME || logicalKey == KEY_INSERT_NAME) { // Ctrl-C or Ctrl+Insert to copy the selected text - controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::COPY ); + controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::COPY); consumed = true; } - else if (keyName == KEY_V_NAME || logicalKey == KEY_V_NAME) + else if(keyName == KEY_V_NAME || logicalKey == KEY_V_NAME) { // Ctrl-V to paste the copied text - controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::PASTE ); + controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::PASTE); consumed = true; } - else if (keyName == KEY_X_NAME || logicalKey == KEY_X_NAME) + else if(keyName == KEY_X_NAME || logicalKey == KEY_X_NAME) { // Ctrl-X to cut the selected text - controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::CUT ); + controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::CUT); consumed = true; } - else if (keyName == KEY_A_NAME || logicalKey == KEY_A_NAME) + else if(keyName == KEY_A_NAME || logicalKey == KEY_A_NAME) { // Ctrl-A to select All the text - controller.TextPopupButtonTouched( Toolkit::TextSelectionPopup::SELECT_ALL ); + controller.TextPopupButtonTouched(Toolkit::TextSelectionPopup::SELECT_ALL); consumed = true; } return consumed; } - else if( ( Dali::DALI_KEY_BACKSPACE == keyCode ) || - ( Dali::DevelKey::DALI_KEY_DELETE == keyCode ) ) + else if((Dali::DALI_KEY_BACKSPACE == keyCode) || + (Dali::DevelKey::DALI_KEY_DELETE == keyCode)) { - textChanged = controller.DeleteEvent( keyCode ); + textChanged = controller.DeleteEvent(keyCode); // Will request for relayout. relayoutNeeded = true; } - else if( IsKey( keyEvent, Dali::DALI_KEY_POWER ) || - IsKey( keyEvent, Dali::DALI_KEY_MENU ) || - IsKey( keyEvent, Dali::DALI_KEY_HOME ) ) + else if(IsKey(keyEvent, Dali::DALI_KEY_POWER) || + IsKey(keyEvent, Dali::DALI_KEY_MENU) || + IsKey(keyEvent, Dali::DALI_KEY_HOME)) { // Power key/Menu/Home key behaviour does not allow edit mode to resume. - controller.mImpl->ChangeState( EventData::INACTIVE ); + controller.mImpl->ChangeState(EventData::INACTIVE); // Will request for relayout. relayoutNeeded = true; // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text. } - else if( ( Dali::DALI_KEY_SHIFT_LEFT == keyCode ) || ( Dali::DALI_KEY_SHIFT_RIGHT == keyCode ) ) + else if((Dali::DALI_KEY_SHIFT_LEFT == keyCode) || (Dali::DALI_KEY_SHIFT_RIGHT == keyCode)) { // DALI_KEY_SHIFT_LEFT or DALI_KEY_SHIFT_RIGHT is the key code for Shift. It's sent (by the InputMethodContext?) when the predictive text is enabled // and a character is typed after the type of a upper case latin character. @@ -239,7 +235,7 @@ bool Controller::EventHandler::KeyEvent(Controller& controller, const Dali::KeyE // Do nothing. return false; } - else if( ( Dali::DALI_KEY_VOLUME_UP == keyCode ) || ( Dali::DALI_KEY_VOLUME_DOWN == keyCode ) ) + else if((Dali::DALI_KEY_VOLUME_UP == keyCode) || (Dali::DALI_KEY_VOLUME_DOWN == keyCode)) { // This branch avoids calling the InsertText() method of the 'else' branch which can delete selected text. // Do nothing. @@ -247,49 +243,48 @@ bool Controller::EventHandler::KeyEvent(Controller& controller, const Dali::KeyE } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", &controller, keyString.c_str() ); - if (!controller.IsEditable()) return false; + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::KeyEvent %p keyString %s\n", &controller, keyString.c_str()); + if(!controller.IsEditable()) return false; - if( !keyString.empty() ) + if(!keyString.empty()) { // InputMethodContext is no longer handling key-events controller.mImpl->ClearPreEditFlag(); - controller.InsertText( keyString, COMMIT ); + controller.InsertText(keyString, COMMIT); textChanged = true; // Will request for relayout. relayoutNeeded = true; } - } - if ( ( controller.mImpl->mEventData->mState != EventData::INTERRUPTED ) && - ( controller.mImpl->mEventData->mState != EventData::INACTIVE ) && - ( !isNullKey ) && - ( Dali::DALI_KEY_SHIFT_LEFT != keyCode ) && - ( Dali::DALI_KEY_SHIFT_RIGHT != keyCode ) && - ( Dali::DALI_KEY_VOLUME_UP != keyCode ) && - ( Dali::DALI_KEY_VOLUME_DOWN != keyCode ) ) + if((controller.mImpl->mEventData->mState != EventData::INTERRUPTED) && + (controller.mImpl->mEventData->mState != EventData::INACTIVE) && + (!isNullKey) && + (Dali::DALI_KEY_SHIFT_LEFT != keyCode) && + (Dali::DALI_KEY_SHIFT_RIGHT != keyCode) && + (Dali::DALI_KEY_VOLUME_UP != keyCode) && + (Dali::DALI_KEY_VOLUME_DOWN != keyCode)) { // Should not change the state if the key is the shift send by the InputMethodContext. // Otherwise, when the state is SELECTING the text controller can't send the right // surrounding info to the InputMethodContext. - controller.mImpl->ChangeState( EventData::EDITING ); + controller.mImpl->ChangeState(EventData::EDITING); // Will request for relayout. relayoutNeeded = true; } - if( relayoutNeeded ) + if(relayoutNeeded) { controller.mImpl->RequestRelayout(); } } - if( textChanged && - ( NULL != controller.mImpl->mEditableControlInterface ) ) + if(textChanged && + (NULL != controller.mImpl->mEditableControlInterface)) { // Do this last since it provides callbacks into application code controller.mImpl->mEditableControlInterface->TextChanged(); @@ -300,72 +295,72 @@ bool Controller::EventHandler::KeyEvent(Controller& controller, const Dali::KeyE void Controller::EventHandler::TapEvent(Controller& controller, unsigned int tapCount, float x, float y) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected TapEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected TapEvent"); - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - DALI_LOG_INFO( gLogFilter, Debug::Concise, "TapEvent state:%d \n", controller.mImpl->mEventData->mState ); - EventData::State state( controller.mImpl->mEventData->mState ); - bool relayoutNeeded( false ); // to avoid unnecessary relayouts when tapping an empty text-field + DALI_LOG_INFO(gLogFilter, Debug::Concise, "TapEvent state:%d \n", controller.mImpl->mEventData->mState); + EventData::State state(controller.mImpl->mEventData->mState); + bool relayoutNeeded(false); // to avoid unnecessary relayouts when tapping an empty text-field - if( controller.mImpl->IsClipboardVisible() ) + if(controller.mImpl->IsClipboardVisible()) { - if( EventData::INACTIVE == state || EventData::EDITING == state) + if(EventData::INACTIVE == state || EventData::EDITING == state) { - controller.mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE ); + controller.mImpl->ChangeState(EventData::EDITING_WITH_GRAB_HANDLE); } relayoutNeeded = true; } - else if( 1u == tapCount ) + else if(1u == tapCount) { - if( EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state ) + if(EventData::EDITING_WITH_POPUP == state || EventData::EDITING_WITH_PASTE_POPUP == state) { - controller.mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE ); // If Popup shown hide it here so can be shown again if required. + controller.mImpl->ChangeState(EventData::EDITING_WITH_GRAB_HANDLE); // If Popup shown hide it here so can be shown again if required. } - if( controller.mImpl->IsShowingRealText() && ( EventData::INACTIVE != state ) ) + if(controller.mImpl->IsShowingRealText() && (EventData::INACTIVE != state)) { - controller.mImpl->ChangeState( EventData::EDITING_WITH_GRAB_HANDLE ); + controller.mImpl->ChangeState(EventData::EDITING_WITH_GRAB_HANDLE); relayoutNeeded = true; } else { - if( controller.mImpl->IsShowingPlaceholderText() && !controller.mImpl->IsFocusedPlaceholderAvailable() ) + if(controller.mImpl->IsShowingPlaceholderText() && !controller.mImpl->IsFocusedPlaceholderAvailable()) { // Hide placeholder text controller.ResetText(); } - if( EventData::INACTIVE == state ) + if(EventData::INACTIVE == state) { - controller.mImpl->ChangeState( EventData::EDITING ); + controller.mImpl->ChangeState(EventData::EDITING); } - else if( !controller.mImpl->IsClipboardEmpty() ) + else if(!controller.mImpl->IsClipboardEmpty()) { - controller.mImpl->ChangeState( EventData::EDITING_WITH_POPUP ); + controller.mImpl->ChangeState(EventData::EDITING_WITH_POPUP); } relayoutNeeded = true; } } - else if( 2u == tapCount ) + else if(2u == tapCount) { - if( controller.mImpl->mEventData->mSelectionEnabled && - controller.mImpl->IsShowingRealText() ) + if(controller.mImpl->mEventData->mSelectionEnabled && + controller.mImpl->IsShowingRealText()) { - relayoutNeeded = true; - controller.mImpl->mEventData->mIsLeftHandleSelected = true; + relayoutNeeded = true; + controller.mImpl->mEventData->mIsLeftHandleSelected = true; controller.mImpl->mEventData->mIsRightHandleSelected = true; } } // Handles & cursors must be repositioned after Relayout() i.e. after the Model has been updated - if( relayoutNeeded ) + if(relayoutNeeded) { - Event event( Event::TAP_EVENT ); - event.p1.mUint = tapCount; + Event event(Event::TAP_EVENT); + event.p1.mUint = tapCount; event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); controller.mImpl->RequestRelayout(); } @@ -377,15 +372,15 @@ void Controller::EventHandler::TapEvent(Controller& controller, unsigned int tap void Controller::EventHandler::PanEvent(Controller& controller, GestureState state, const Vector2& displacement) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected PanEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected PanEvent"); - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - Event event( Event::PAN_EVENT ); - event.p1.mInt = static_cast( state ); + Event event(Event::PAN_EVENT); + event.p1.mInt = static_cast(state); event.p2.mFloat = displacement.x; event.p3.mFloat = displacement.y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); controller.mImpl->RequestRelayout(); } @@ -393,46 +388,46 @@ void Controller::EventHandler::PanEvent(Controller& controller, GestureState sta void Controller::EventHandler::LongPressEvent(Controller& controller, GestureState state, float x, float y) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected LongPressEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected LongPressEvent"); - if( ( state == GestureState::STARTED ) && - ( NULL != controller.mImpl->mEventData ) ) + if((state == GestureState::STARTED) && + (NULL != controller.mImpl->mEventData)) { // The 1st long-press on inactive text-field is treated as tap - if( EventData::INACTIVE == controller.mImpl->mEventData->mState ) + if(EventData::INACTIVE == controller.mImpl->mEventData->mState) { - controller.mImpl->ChangeState( EventData::EDITING ); + controller.mImpl->ChangeState(EventData::EDITING); - Event event( Event::TAP_EVENT ); - event.p1.mUint = 1; + Event event(Event::TAP_EVENT); + event.p1.mUint = 1; event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); controller.mImpl->RequestRelayout(); } - else if( !controller.mImpl->IsShowingRealText() ) + else if(!controller.mImpl->IsShowingRealText()) { - Event event( Event::LONG_PRESS_EVENT ); - event.p1.mInt = static_cast( state ); + Event event(Event::LONG_PRESS_EVENT); + event.p1.mInt = static_cast(state); event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); controller.mImpl->RequestRelayout(); } - else if( !controller.mImpl->IsClipboardVisible() ) + else if(!controller.mImpl->IsClipboardVisible()) { // Reset the InputMethodContext to commit the pre-edit before selecting the text. controller.mImpl->ResetInputMethodContext(); - Event event( Event::LONG_PRESS_EVENT ); - event.p1.mInt = static_cast( state ); + Event event(Event::LONG_PRESS_EVENT); + event.p1.mInt = static_cast(state); event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); controller.mImpl->RequestRelayout(); - controller.mImpl->mEventData->mIsLeftHandleSelected = true; + controller.mImpl->mEventData->mIsLeftHandleSelected = true; controller.mImpl->mEventData->mIsRightHandleSelected = true; } } @@ -440,30 +435,30 @@ void Controller::EventHandler::LongPressEvent(Controller& controller, GestureSta void Controller::EventHandler::SelectEvent(Controller& controller, float x, float y, SelectionType selectType) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SelectEvent\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SelectEvent\n"); - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( selectType == SelectionType::ALL ) + if(selectType == SelectionType::ALL) { - Event event( Event::SELECT_ALL ); - controller.mImpl->mEventData->mEventQueue.push_back( event ); + Event event(Event::SELECT_ALL); + controller.mImpl->mEventData->mEventQueue.push_back(event); } - else if( selectType == SelectionType::NONE ) + else if(selectType == SelectionType::NONE) { - Event event( Event::SELECT_NONE ); - controller.mImpl->mEventData->mEventQueue.push_back( event ); + Event event(Event::SELECT_NONE); + controller.mImpl->mEventData->mEventQueue.push_back(event); } else { - Event event( Event::SELECT ); + Event event(Event::SELECT); event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); } - controller.mImpl->mEventData->mCheckScrollAmount = true; - controller.mImpl->mEventData->mIsLeftHandleSelected = true; + controller.mImpl->mEventData->mCheckScrollAmount = true; + controller.mImpl->mEventData->mIsLeftHandleSelected = true; controller.mImpl->mEventData->mIsRightHandleSelected = true; controller.mImpl->RequestRelayout(); } @@ -473,47 +468,47 @@ void Controller::EventHandler::ProcessModifyEvents(Controller& controller) { Vector& events = controller.mImpl->mModifyEvents; - if( 0u == events.Count() ) + if(0u == events.Count()) { // Nothing to do. return; } - for( Vector::ConstIterator it = events.Begin(), - endIt = events.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = events.Begin(), + endIt = events.End(); + it != endIt; + ++it) { const ModifyEvent& event = *it; - if( ModifyEvent::TEXT_REPLACED == event.type ) + if(ModifyEvent::TEXT_REPLACED == event.type) { // A (single) replace event should come first, otherwise we wasted time processing NOOP events - DALI_ASSERT_DEBUG( it == events.Begin() && "Unexpected TEXT_REPLACED event" ); + DALI_ASSERT_DEBUG(it == events.Begin() && "Unexpected TEXT_REPLACED event"); controller.TextReplacedEvent(); } - else if( ModifyEvent::TEXT_INSERTED == event.type ) + else if(ModifyEvent::TEXT_INSERTED == event.type) { controller.TextInsertedEvent(); } - else if( ModifyEvent::TEXT_DELETED == event.type ) + else if(ModifyEvent::TEXT_DELETED == event.type) { // Placeholder-text cannot be deleted - if( !controller.mImpl->IsShowingPlaceholderText() ) + if(!controller.mImpl->IsShowingPlaceholderText()) { controller.TextDeletedEvent(); } } } - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { // When the text is being modified, delay cursor blinking controller.mImpl->mEventData->mDecorator->DelayCursorBlink(); // Update selection position after modifying the text - controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; + controller.mImpl->mEventData->mLeftSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; controller.mImpl->mEventData->mRightSelectionPosition = controller.mImpl->mEventData->mPrimaryCursorPosition; } @@ -535,9 +530,9 @@ void Controller::EventHandler::TextReplacedEvent(Controller& controller) void Controller::EventHandler::TextInsertedEvent(Controller& controller) { - DALI_ASSERT_DEBUG( NULL != controller.mImpl->mEventData && "Unexpected TextInsertedEvent" ); + DALI_ASSERT_DEBUG(NULL != controller.mImpl->mEventData && "Unexpected TextInsertedEvent"); - if( NULL == controller.mImpl->mEventData ) + if(NULL == controller.mImpl->mEventData) { return; } @@ -556,14 +551,14 @@ void Controller::EventHandler::TextInsertedEvent(Controller& controller) void Controller::EventHandler::TextDeletedEvent(Controller& controller) { - DALI_ASSERT_DEBUG( NULL != controller.mImpl->mEventData && "Unexpected TextDeletedEvent" ); + DALI_ASSERT_DEBUG(NULL != controller.mImpl->mEventData && "Unexpected TextDeletedEvent"); - if( NULL == controller.mImpl->mEventData ) + if(NULL == controller.mImpl->mEventData) { return; } - if (!controller.IsEditable()) return; + if(!controller.IsEditable()) return; controller.mImpl->mEventData->mCheckScrollAmount = true; @@ -579,52 +574,52 @@ void Controller::EventHandler::TextDeletedEvent(Controller& controller) bool Controller::EventHandler::DeleteEvent(Controller& controller, int keyCode) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", &controller, keyCode ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::KeyEvent %p KeyCode : %d \n", &controller, keyCode); bool removed = false; - if( NULL == controller.mImpl->mEventData ) + if(NULL == controller.mImpl->mEventData) { return removed; } - if (!controller.IsEditable()) return false; + if(!controller.IsEditable()) return false; // InputMethodContext is no longer handling key-events controller.mImpl->ClearPreEditFlag(); - if( EventData::SELECTING == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState) { removed = controller.RemoveSelectedText(); } - else if( ( controller.mImpl->mEventData->mPrimaryCursorPosition > 0 ) && ( keyCode == Dali::DALI_KEY_BACKSPACE) ) + else if((controller.mImpl->mEventData->mPrimaryCursorPosition > 0) && (keyCode == Dali::DALI_KEY_BACKSPACE)) { // Remove the character before the current cursor position - removed = controller.RemoveText( -1, - 1, - UPDATE_INPUT_STYLE ); + removed = controller.RemoveText(-1, + 1, + UPDATE_INPUT_STYLE); } - else if( keyCode == Dali::DevelKey::DALI_KEY_DELETE ) + else if(keyCode == Dali::DevelKey::DALI_KEY_DELETE) { // Remove the character after the current cursor position - removed = controller.RemoveText( 0, - 1, - UPDATE_INPUT_STYLE ); + removed = controller.RemoveText(0, + 1, + UPDATE_INPUT_STYLE); } - if( removed ) + if(removed) { - if( ( 0u != controller.mImpl->mModel->mLogicalModel->mText.Count() ) || - !controller.mImpl->IsPlaceholderAvailable() ) + if((0u != controller.mImpl->mModel->mLogicalModel->mText.Count()) || + !controller.mImpl->IsPlaceholderAvailable()) { - controller.mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED ); + controller.mImpl->QueueModifyEvent(ModifyEvent::TEXT_DELETED); } else { controller.ShowPlaceholderText(); } controller.mImpl->mEventData->mUpdateCursorPosition = true; - controller.mImpl->mEventData->mScrollAfterDelete = true; + controller.mImpl->mEventData->mScrollAfterDelete = true; } return removed; @@ -636,44 +631,44 @@ InputMethodContext::CallbackData Controller::EventHandler::OnInputMethodContextE bool requestRelayout = false; // Whether to retrieve the text and cursor position to be sent to the InputMethodContext. - bool retrieveText = false; + bool retrieveText = false; bool retrieveCursor = false; - switch( inputMethodContextEvent.eventName ) + switch(inputMethodContextEvent.eventName) { case InputMethodContext::COMMIT: { - controller.InsertText( inputMethodContextEvent.predictiveString, Text::Controller::COMMIT ); + controller.InsertText(inputMethodContextEvent.predictiveString, Text::Controller::COMMIT); requestRelayout = true; - retrieveCursor = true; + retrieveCursor = true; break; } case InputMethodContext::PRE_EDIT: { - controller.InsertText( inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT ); + controller.InsertText(inputMethodContextEvent.predictiveString, Text::Controller::PRE_EDIT); requestRelayout = true; - retrieveCursor = true; + retrieveCursor = true; break; } case InputMethodContext::DELETE_SURROUNDING: { - const bool textDeleted = controller.RemoveText( inputMethodContextEvent.cursorOffset, - inputMethodContextEvent.numberOfChars, - DONT_UPDATE_INPUT_STYLE ); + const bool textDeleted = controller.RemoveText(inputMethodContextEvent.cursorOffset, + inputMethodContextEvent.numberOfChars, + DONT_UPDATE_INPUT_STYLE); - if( textDeleted ) + if(textDeleted) { - if( ( 0u != controller.mImpl->mModel->mLogicalModel->mText.Count() ) || - !controller.mImpl->IsPlaceholderAvailable() ) + if((0u != controller.mImpl->mModel->mLogicalModel->mText.Count()) || + !controller.mImpl->IsPlaceholderAvailable()) { - controller.mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED ); + controller.mImpl->QueueModifyEvent(ModifyEvent::TEXT_DELETED); } else { controller.ShowPlaceholderText(); } controller.mImpl->mEventData->mUpdateCursorPosition = true; - controller.mImpl->mEventData->mScrollAfterDelete = true; + controller.mImpl->mEventData->mScrollAfterDelete = true; requestRelayout = true; } @@ -681,14 +676,14 @@ InputMethodContext::CallbackData Controller::EventHandler::OnInputMethodContextE } case InputMethodContext::GET_SURROUNDING: { - retrieveText = true; + retrieveText = true; retrieveCursor = true; break; } case InputMethodContext::PRIVATE_COMMAND: { // PRIVATECOMMAND event is just for getting the private command message - retrieveText = true; + retrieveText = true; retrieveCursor = true; break; } @@ -699,23 +694,23 @@ InputMethodContext::CallbackData Controller::EventHandler::OnInputMethodContextE } } // end switch - if( requestRelayout ) + if(requestRelayout) { controller.mImpl->mOperationsPending = ALL_OPERATIONS; controller.mImpl->RequestRelayout(); } - std::string text; - CharacterIndex cursorPosition = 0u; - Length numberOfWhiteSpaces = 0u; + std::string text; + CharacterIndex cursorPosition = 0u; + Length numberOfWhiteSpaces = 0u; - if( retrieveCursor ) + if(retrieveCursor) { - numberOfWhiteSpaces = controller.mImpl->GetNumberOfWhiteSpaces( 0u ); + numberOfWhiteSpaces = controller.mImpl->GetNumberOfWhiteSpaces(0u); cursorPosition = controller.mImpl->GetLogicalCursorPosition(); - if( cursorPosition < numberOfWhiteSpaces ) + if(cursorPosition < numberOfWhiteSpaces) { cursorPosition = 0u; } @@ -725,12 +720,12 @@ InputMethodContext::CallbackData Controller::EventHandler::OnInputMethodContextE } } - if( retrieveText ) + if(retrieveText) { - if( !controller.mImpl->IsShowingPlaceholderText() ) + if(!controller.mImpl->IsShowingPlaceholderText()) { // Retrieves the normal text string. - controller.mImpl->GetText( numberOfWhiteSpaces, text ); + controller.mImpl->GetText(numberOfWhiteSpaces, text); } else { @@ -740,10 +735,10 @@ InputMethodContext::CallbackData Controller::EventHandler::OnInputMethodContextE } } - InputMethodContext::CallbackData callbackData( ( retrieveText || retrieveCursor ), cursorPosition, text, false ); + InputMethodContext::CallbackData callbackData((retrieveText || retrieveCursor), cursorPosition, text, false); - if( requestRelayout && - ( NULL != controller.mImpl->mEditableControlInterface ) ) + if(requestRelayout && + (NULL != controller.mImpl->mEditableControlInterface)) { // Do this last since it provides callbacks into application code controller.mImpl->mEditableControlInterface->TextChanged(); @@ -755,57 +750,57 @@ InputMethodContext::CallbackData Controller::EventHandler::OnInputMethodContextE void Controller::EventHandler::PasteClipboardItemEvent(Controller& controller) { // Retrieve the clipboard contents first - ClipboardEventNotifier notifier( ClipboardEventNotifier::Get() ); - std::string stringToPaste( notifier.GetContent() ); + ClipboardEventNotifier notifier(ClipboardEventNotifier::Get()); + std::string stringToPaste(notifier.GetContent()); // Commit the current pre-edit text; the contents of the clipboard should be appended controller.mImpl->ResetInputMethodContext(); // Temporary disable hiding clipboard - controller.mImpl->SetClipboardHideEnable( false ); + controller.mImpl->SetClipboardHideEnable(false); // Paste - controller.PasteText( stringToPaste ); + controller.PasteText(stringToPaste); - controller.mImpl->SetClipboardHideEnable( true ); + controller.mImpl->SetClipboardHideEnable(true); } void Controller::EventHandler::DecorationEvent(Controller& controller, HandleType handleType, HandleState state, float x, float y) { - DALI_ASSERT_DEBUG( controller.mImpl->mEventData && "Unexpected DecorationEvent" ); + DALI_ASSERT_DEBUG(controller.mImpl->mEventData && "Unexpected DecorationEvent"); - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - switch( handleType ) + switch(handleType) { case GRAB_HANDLE: { - Event event( Event::GRAB_HANDLE_EVENT ); + Event event(Event::GRAB_HANDLE_EVENT); event.p1.mUint = state; event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); break; } case LEFT_SELECTION_HANDLE: { - Event event( Event::LEFT_SELECTION_HANDLE_EVENT ); + Event event(Event::LEFT_SELECTION_HANDLE_EVENT); event.p1.mUint = state; event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); break; } case RIGHT_SELECTION_HANDLE: { - Event event( Event::RIGHT_SELECTION_HANDLE_EVENT ); + Event event(Event::RIGHT_SELECTION_HANDLE_EVENT); event.p1.mUint = state; event.p2.mFloat = x; event.p3.mFloat = y; - controller.mImpl->mEventData->mEventQueue.push_back( event ); + controller.mImpl->mEventData->mEventQueue.push_back(event); break; } case LEFT_SELECTION_HANDLE_MARKER: @@ -816,7 +811,7 @@ void Controller::EventHandler::DecorationEvent(Controller& controller, HandleTyp } case HANDLE_TYPE_COUNT: { - DALI_ASSERT_DEBUG( !"Controller::HandleEvent. Unexpected handle type" ); + DALI_ASSERT_DEBUG(!"Controller::HandleEvent. Unexpected handle type"); } } @@ -826,23 +821,23 @@ void Controller::EventHandler::DecorationEvent(Controller& controller, HandleTyp void Controller::EventHandler::TextPopupButtonTouched(Controller& controller, Dali::Toolkit::TextSelectionPopup::Buttons button) { - if( NULL == controller.mImpl->mEventData ) + if(NULL == controller.mImpl->mEventData) { return; } - switch( button ) + switch(button) { case Toolkit::TextSelectionPopup::CUT: { - if (!controller.IsEditable()) return; - controller.mImpl->SendSelectionToClipboard( true ); // Synchronous call to modify text + if(!controller.IsEditable()) return; + controller.mImpl->SendSelectionToClipboard(true); // Synchronous call to modify text controller.mImpl->mOperationsPending = ALL_OPERATIONS; - if( ( 0u != controller.mImpl->mModel->mLogicalModel->mText.Count() ) || - !controller.mImpl->IsPlaceholderAvailable() ) + if((0u != controller.mImpl->mModel->mLogicalModel->mText.Count()) || + !controller.mImpl->IsPlaceholderAvailable()) { - controller.mImpl->QueueModifyEvent( ModifyEvent::TEXT_DELETED ); + controller.mImpl->QueueModifyEvent(ModifyEvent::TEXT_DELETED); } else { @@ -850,11 +845,11 @@ void Controller::EventHandler::TextPopupButtonTouched(Controller& controller, Da } controller.mImpl->mEventData->mUpdateCursorPosition = true; - controller.mImpl->mEventData->mScrollAfterDelete = true; + controller.mImpl->mEventData->mScrollAfterDelete = true; controller.mImpl->RequestRelayout(); - if( NULL != controller.mImpl->mEditableControlInterface ) + if(NULL != controller.mImpl->mEditableControlInterface) { controller.mImpl->mEditableControlInterface->TextChanged(); } @@ -862,7 +857,7 @@ void Controller::EventHandler::TextPopupButtonTouched(Controller& controller, Da } case Toolkit::TextSelectionPopup::COPY: { - controller.mImpl->SendSelectionToClipboard( false ); // Text not modified + controller.mImpl->SendSelectionToClipboard(false); // Text not modified controller.mImpl->mEventData->mUpdateCursorPosition = true; @@ -876,19 +871,19 @@ void Controller::EventHandler::TextPopupButtonTouched(Controller& controller, Da } case Toolkit::TextSelectionPopup::SELECT: { - const Vector2& currentCursorPosition = controller.mImpl->mEventData->mDecorator->GetPosition( PRIMARY_CURSOR ); + const Vector2& currentCursorPosition = controller.mImpl->mEventData->mDecorator->GetPosition(PRIMARY_CURSOR); - if( controller.mImpl->mEventData->mSelectionEnabled ) + if(controller.mImpl->mEventData->mSelectionEnabled) { // Creates a SELECT event. - controller.SelectEvent( currentCursorPosition.x, currentCursorPosition.y, SelectionType::INTERACTIVE ); + controller.SelectEvent(currentCursorPosition.x, currentCursorPosition.y, SelectionType::INTERACTIVE); } break; } case Toolkit::TextSelectionPopup::SELECT_ALL: { // Creates a SELECT_ALL event - controller.SelectEvent( 0.f, 0.f, SelectionType::ALL ); + controller.SelectEvent(0.f, 0.f, SelectionType::ALL); break; } case Toolkit::TextSelectionPopup::CLIPBOARD: diff --git a/dali-toolkit/internal/text/text-controller-impl-event-handler.cpp b/dali-toolkit/internal/text/text-controller-impl-event-handler.cpp index 475f3fc..22525db 100644 --- a/dali-toolkit/internal/text/text-controller-impl-event-handler.cpp +++ b/dali-toolkit/internal/text/text-controller-impl-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,8 +19,8 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include @@ -30,7 +30,6 @@ using namespace Dali; namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif @@ -39,32 +38,29 @@ Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT namespace Dali { - namespace Toolkit { - namespace Text { - bool ControllerImplEventHandler::ProcessInputEvents(Controller::Impl& impl) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::ProcessInputEvents\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::ProcessInputEvents\n"); EventData*& eventData = impl.mEventData; - if( NULL == eventData ) + if(NULL == eventData) { // Nothing to do if there is no text input. - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents no event data\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents no event data\n"); return false; } - if( eventData->mDecorator ) + if(eventData->mDecorator) { - for( std::vector::iterator iter = eventData->mEventQueue.begin(); - iter != eventData->mEventQueue.end(); - ++iter ) + for(std::vector::iterator iter = eventData->mEventQueue.begin(); + iter != eventData->mEventQueue.end(); + ++iter) { - switch( iter->type ) + switch(iter->type) { case Event::CURSOR_KEY_EVENT: { @@ -112,14 +108,14 @@ bool ControllerImplEventHandler::ProcessInputEvents(Controller::Impl& impl) } } - if( eventData->mUpdateCursorPosition || - eventData->mUpdateHighlightBox ) + if(eventData->mUpdateCursorPosition || + eventData->mUpdateHighlightBox) { impl.NotifyInputMethodContext(); } // The cursor must also be repositioned after inserts into the model - if( eventData->mUpdateCursorPosition ) + if(eventData->mUpdateCursorPosition) { // Updates the cursor position and scrolls the text to make it visible. CursorInfo cursorInfo; @@ -128,35 +124,35 @@ bool ControllerImplEventHandler::ProcessInputEvents(Controller::Impl& impl) if(nullptr != impl.mEditableControlInterface) { - impl.mEditableControlInterface->CaretMoved( eventData->mPrimaryCursorPosition ); + impl.mEditableControlInterface->CaretMoved(eventData->mPrimaryCursorPosition); } - if( eventData->mUpdateCursorHookPosition ) + if(eventData->mUpdateCursorHookPosition) { // Update the cursor hook position. Used to move the cursor with the keys 'up' and 'down'. - eventData->mCursorHookPositionX = cursorInfo.primaryPosition.x; + eventData->mCursorHookPositionX = cursorInfo.primaryPosition.x; eventData->mUpdateCursorHookPosition = false; } // Scroll first the text after delete ... - if( eventData->mScrollAfterDelete ) + if(eventData->mScrollAfterDelete) { impl.ScrollTextToMatchCursor(cursorInfo); } // ... then, text can be scrolled to make the cursor visible. - if( eventData->mScrollAfterUpdatePosition ) + if(eventData->mScrollAfterUpdatePosition) { - const Vector2 currentCursorPosition( cursorInfo.primaryPosition.x, cursorInfo.lineOffset ); - impl.ScrollToMakePositionVisible( currentCursorPosition, cursorInfo.lineHeight ); + const Vector2 currentCursorPosition(cursorInfo.primaryPosition.x, cursorInfo.lineOffset); + impl.ScrollToMakePositionVisible(currentCursorPosition, cursorInfo.lineHeight); } eventData->mScrollAfterUpdatePosition = false; - eventData->mScrollAfterDelete = false; + eventData->mScrollAfterDelete = false; - impl.UpdateCursorPosition( cursorInfo ); + impl.UpdateCursorPosition(cursorInfo); - eventData->mDecoratorUpdated = true; - eventData->mUpdateCursorPosition = false; + eventData->mDecoratorUpdated = true; + eventData->mUpdateCursorPosition = false; eventData->mUpdateGrabHandlePosition = false; } else @@ -164,91 +160,91 @@ bool ControllerImplEventHandler::ProcessInputEvents(Controller::Impl& impl) CursorInfo leftHandleInfo; CursorInfo rightHandleInfo; - if( eventData->mUpdateHighlightBox ) + if(eventData->mUpdateHighlightBox) { impl.GetCursorPosition(eventData->mLeftSelectionPosition, leftHandleInfo); impl.GetCursorPosition(eventData->mRightSelectionPosition, rightHandleInfo); - if( eventData->mScrollAfterUpdatePosition && ( eventData->mIsLeftHandleSelected ? eventData->mUpdateLeftSelectionPosition : eventData->mUpdateRightSelectionPosition ) ) + if(eventData->mScrollAfterUpdatePosition && (eventData->mIsLeftHandleSelected ? eventData->mUpdateLeftSelectionPosition : eventData->mUpdateRightSelectionPosition)) { - if( eventData->mIsLeftHandleSelected && eventData->mIsRightHandleSelected ) + if(eventData->mIsLeftHandleSelected && eventData->mIsRightHandleSelected) { CursorInfo& infoLeft = leftHandleInfo; - const Vector2 currentCursorPositionLeft( infoLeft.primaryPosition.x, infoLeft.lineOffset ); - impl.ScrollToMakePositionVisible( currentCursorPositionLeft, infoLeft.lineHeight ); + const Vector2 currentCursorPositionLeft(infoLeft.primaryPosition.x, infoLeft.lineOffset); + impl.ScrollToMakePositionVisible(currentCursorPositionLeft, infoLeft.lineHeight); CursorInfo& infoRight = rightHandleInfo; - const Vector2 currentCursorPositionRight( infoRight.primaryPosition.x, infoRight.lineOffset ); - impl.ScrollToMakePositionVisible( currentCursorPositionRight, infoRight.lineHeight ); + const Vector2 currentCursorPositionRight(infoRight.primaryPosition.x, infoRight.lineOffset); + impl.ScrollToMakePositionVisible(currentCursorPositionRight, infoRight.lineHeight); } else { CursorInfo& info = eventData->mIsLeftHandleSelected ? leftHandleInfo : rightHandleInfo; - const Vector2 currentCursorPosition( info.primaryPosition.x, info.lineOffset ); - impl. ScrollToMakePositionVisible( currentCursorPosition, info.lineHeight ); + const Vector2 currentCursorPosition(info.primaryPosition.x, info.lineOffset); + impl.ScrollToMakePositionVisible(currentCursorPosition, info.lineHeight); } } } - if( eventData->mUpdateLeftSelectionPosition ) + if(eventData->mUpdateLeftSelectionPosition) { impl.UpdateSelectionHandle(LEFT_SELECTION_HANDLE, leftHandleInfo); impl.SetPopupButtons(); - eventData->mDecoratorUpdated = true; + eventData->mDecoratorUpdated = true; eventData->mUpdateLeftSelectionPosition = false; } - if( eventData->mUpdateRightSelectionPosition ) + if(eventData->mUpdateRightSelectionPosition) { impl.UpdateSelectionHandle(RIGHT_SELECTION_HANDLE, rightHandleInfo); impl.SetPopupButtons(); - eventData->mDecoratorUpdated = true; + eventData->mDecoratorUpdated = true; eventData->mUpdateRightSelectionPosition = false; } - if( eventData->mUpdateHighlightBox ) + if(eventData->mUpdateHighlightBox) { impl.RepositionSelectionHandles(); - eventData->mUpdateLeftSelectionPosition = false; + eventData->mUpdateLeftSelectionPosition = false; eventData->mUpdateRightSelectionPosition = false; - eventData->mUpdateHighlightBox = false; - eventData->mIsLeftHandleSelected = false; - eventData->mIsRightHandleSelected = false; + eventData->mUpdateHighlightBox = false; + eventData->mIsLeftHandleSelected = false; + eventData->mIsRightHandleSelected = false; } eventData->mScrollAfterUpdatePosition = false; } - if( eventData->mUpdateInputStyle ) + if(eventData->mUpdateInputStyle) { // Keep a copy of the current input style. InputStyle currentInputStyle; - currentInputStyle.Copy( eventData->mInputStyle ); + currentInputStyle.Copy(eventData->mInputStyle); // Set the default style first. - impl.RetrieveDefaultInputStyle( eventData->mInputStyle ); + impl.RetrieveDefaultInputStyle(eventData->mInputStyle); // Get the character index from the cursor index. - const CharacterIndex styleIndex = ( eventData->mPrimaryCursorPosition > 0u ) ? eventData->mPrimaryCursorPosition - 1u : 0u; + const CharacterIndex styleIndex = (eventData->mPrimaryCursorPosition > 0u) ? eventData->mPrimaryCursorPosition - 1u : 0u; // Retrieve the style from the style runs stored in the logical model. - impl.mModel->mLogicalModel->RetrieveStyle( styleIndex, eventData->mInputStyle ); + impl.mModel->mLogicalModel->RetrieveStyle(styleIndex, eventData->mInputStyle); // Compare if the input style has changed. - const bool hasInputStyleChanged = !currentInputStyle.Equal( eventData->mInputStyle ); + const bool hasInputStyleChanged = !currentInputStyle.Equal(eventData->mInputStyle); - if( hasInputStyleChanged ) + if(hasInputStyleChanged) { - const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( eventData->mInputStyle ); + const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(eventData->mInputStyle); // Queue the input style changed signal. - eventData->mInputStyleChangedQueue.PushBack( styleChangedMask ); + eventData->mInputStyleChangedQueue.PushBack(styleChangedMask); } eventData->mUpdateInputStyle = false; @@ -256,210 +252,209 @@ bool ControllerImplEventHandler::ProcessInputEvents(Controller::Impl& impl) eventData->mEventQueue.clear(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::ProcessInputEvents\n"); - const bool decoratorUpdated = eventData->mDecoratorUpdated; + const bool decoratorUpdated = eventData->mDecoratorUpdated; eventData->mDecoratorUpdated = false; return decoratorUpdated; } - void ControllerImplEventHandler::OnCursorKeyEvent(Controller::Impl& impl, const Event& event) { - if( NULL == impl.mEventData || !impl.IsShowingRealText() ) + if(NULL == impl.mEventData || !impl.IsShowingRealText()) { // Nothing to do if there is no text input. return; } - int keyCode = event.p1.mInt; - bool isShiftModifier = event.p2.mBool; - EventData& eventData = *impl.mEventData; - ModelPtr& model = impl.mModel; - LogicalModelPtr& logicalModel = model->mLogicalModel; - VisualModelPtr& visualModel = model->mVisualModel; + int keyCode = event.p1.mInt; + bool isShiftModifier = event.p2.mBool; + EventData& eventData = *impl.mEventData; + ModelPtr& model = impl.mModel; + LogicalModelPtr& logicalModel = model->mLogicalModel; + VisualModelPtr& visualModel = model->mVisualModel; - CharacterIndex& primaryCursorPosition = eventData.mPrimaryCursorPosition; - CharacterIndex previousPrimaryCursorPosition = primaryCursorPosition; + CharacterIndex& primaryCursorPosition = eventData.mPrimaryCursorPosition; + CharacterIndex previousPrimaryCursorPosition = primaryCursorPosition; - if( Dali::DALI_KEY_CURSOR_LEFT == keyCode ) + if(Dali::DALI_KEY_CURSOR_LEFT == keyCode) { - if( primaryCursorPosition > 0u ) + if(primaryCursorPosition > 0u) { - if ( !isShiftModifier && eventData.mDecorator->IsHighlightVisible() ) + if(!isShiftModifier && eventData.mDecorator->IsHighlightVisible()) { primaryCursorPosition = std::min(eventData.mLeftSelectionPosition, eventData.mRightSelectionPosition); } else { - primaryCursorPosition = impl.CalculateNewCursorIndex( primaryCursorPosition - 1u ); + primaryCursorPosition = impl.CalculateNewCursorIndex(primaryCursorPosition - 1u); } } } - else if( Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) + else if(Dali::DALI_KEY_CURSOR_RIGHT == keyCode) { - if( logicalModel->mText.Count() > primaryCursorPosition ) + if(logicalModel->mText.Count() > primaryCursorPosition) { - if ( !isShiftModifier && eventData.mDecorator->IsHighlightVisible() ) + if(!isShiftModifier && eventData.mDecorator->IsHighlightVisible()) { primaryCursorPosition = std::max(eventData.mLeftSelectionPosition, eventData.mRightSelectionPosition); } else { - primaryCursorPosition = impl.CalculateNewCursorIndex( primaryCursorPosition ); + primaryCursorPosition = impl.CalculateNewCursorIndex(primaryCursorPosition); } } } - else if( Dali::DALI_KEY_CURSOR_UP == keyCode && !isShiftModifier ) + else if(Dali::DALI_KEY_CURSOR_UP == keyCode && !isShiftModifier) { // Ignore Shift-Up for text selection for now. // Get first the line index of the current cursor position index. CharacterIndex characterIndex = 0u; - if( primaryCursorPosition > 0u ) + if(primaryCursorPosition > 0u) { characterIndex = primaryCursorPosition - 1u; } - const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterIndex ); - const LineIndex previousLineIndex = ( lineIndex > 0 ? lineIndex - 1u : lineIndex ); + const LineIndex lineIndex = visualModel->GetLineOfCharacter(characterIndex); + const LineIndex previousLineIndex = (lineIndex > 0 ? lineIndex - 1u : lineIndex); // Retrieve the cursor position info. CursorInfo cursorInfo; - impl.GetCursorPosition( primaryCursorPosition, - cursorInfo ); + impl.GetCursorPosition(primaryCursorPosition, + cursorInfo); // Get the line above. - const LineRun& line = *( visualModel->mLines.Begin() + previousLineIndex ); + const LineRun& line = *(visualModel->mLines.Begin() + previousLineIndex); // Get the next hit 'y' point. - const float hitPointY = cursorInfo.lineOffset - 0.5f * ( line.ascender - line.descender ); + const float hitPointY = cursorInfo.lineOffset - 0.5f * (line.ascender - line.descender); // Use the cursor hook position 'x' and the next hit 'y' position to calculate the new cursor index. bool matchedCharacter = false; - primaryCursorPosition = Text::GetClosestCursorIndex( visualModel, - logicalModel, - impl.mMetrics, - eventData.mCursorHookPositionX, - hitPointY, - CharacterHitTest::TAP, - matchedCharacter ); + primaryCursorPosition = Text::GetClosestCursorIndex(visualModel, + logicalModel, + impl.mMetrics, + eventData.mCursorHookPositionX, + hitPointY, + CharacterHitTest::TAP, + matchedCharacter); } - else if( Dali::DALI_KEY_CURSOR_DOWN == keyCode && !isShiftModifier ) + else if(Dali::DALI_KEY_CURSOR_DOWN == keyCode && !isShiftModifier) { // Ignore Shift-Down for text selection for now. // Get first the line index of the current cursor position index. CharacterIndex characterIndex = 0u; - if( primaryCursorPosition > 0u ) + if(primaryCursorPosition > 0u) { characterIndex = primaryCursorPosition - 1u; } - const LineIndex lineIndex = visualModel->GetLineOfCharacter( characterIndex ); + const LineIndex lineIndex = visualModel->GetLineOfCharacter(characterIndex); - if( lineIndex + 1u < visualModel->mLines.Count() ) + if(lineIndex + 1u < visualModel->mLines.Count()) { // Retrieve the cursor position info. CursorInfo cursorInfo; - impl.GetCursorPosition( primaryCursorPosition, cursorInfo ); + impl.GetCursorPosition(primaryCursorPosition, cursorInfo); // Get the line below. - const LineRun& line = *( visualModel->mLines.Begin() + lineIndex + 1u ); + const LineRun& line = *(visualModel->mLines.Begin() + lineIndex + 1u); // Get the next hit 'y' point. - const float hitPointY = cursorInfo.lineOffset + cursorInfo.lineHeight + 0.5f * ( line.ascender - line.descender ); + const float hitPointY = cursorInfo.lineOffset + cursorInfo.lineHeight + 0.5f * (line.ascender - line.descender); // Use the cursor hook position 'x' and the next hit 'y' position to calculate the new cursor index. bool matchedCharacter = false; - primaryCursorPosition = Text::GetClosestCursorIndex( visualModel, - logicalModel, - impl.mMetrics, - eventData.mCursorHookPositionX, - hitPointY, - CharacterHitTest::TAP, - matchedCharacter ); + primaryCursorPosition = Text::GetClosestCursorIndex(visualModel, + logicalModel, + impl.mMetrics, + eventData.mCursorHookPositionX, + hitPointY, + CharacterHitTest::TAP, + matchedCharacter); } } - if ( !isShiftModifier && eventData.mState != EventData::SELECTING ) + if(!isShiftModifier && eventData.mState != EventData::SELECTING) { // Update selection position after moving the cursor - eventData.mLeftSelectionPosition = primaryCursorPosition; + eventData.mLeftSelectionPosition = primaryCursorPosition; eventData.mRightSelectionPosition = primaryCursorPosition; } - if ( isShiftModifier && impl.IsShowingRealText() && eventData.mShiftSelectionFlag ) + if(isShiftModifier && impl.IsShowingRealText() && eventData.mShiftSelectionFlag) { // Handle text selection bool selecting = false; - if ( Dali::DALI_KEY_CURSOR_LEFT == keyCode || Dali::DALI_KEY_CURSOR_RIGHT == keyCode ) + if(Dali::DALI_KEY_CURSOR_LEFT == keyCode || Dali::DALI_KEY_CURSOR_RIGHT == keyCode) { // Shift-Left/Right to select the text int cursorPositionDelta = primaryCursorPosition - previousPrimaryCursorPosition; - if ( cursorPositionDelta > 0 || eventData.mRightSelectionPosition > 0u ) // Check the boundary + if(cursorPositionDelta > 0 || eventData.mRightSelectionPosition > 0u) // Check the boundary { eventData.mRightSelectionPosition += cursorPositionDelta; } selecting = true; } - else if ( eventData.mLeftSelectionPosition != eventData.mRightSelectionPosition ) + else if(eventData.mLeftSelectionPosition != eventData.mRightSelectionPosition) { // Show no grab handles and text highlight if Shift-Up/Down pressed but no selected text selecting = true; } - if ( selecting ) + if(selecting) { // Notify the cursor position to the InputMethodContext. - if( eventData.mInputMethodContext ) + if(eventData.mInputMethodContext) { - eventData.mInputMethodContext.SetCursorPosition( primaryCursorPosition ); + eventData.mInputMethodContext.SetCursorPosition(primaryCursorPosition); eventData.mInputMethodContext.NotifyCursorPosition(); } - impl.ChangeState( EventData::SELECTING ); + impl.ChangeState(EventData::SELECTING); - eventData.mUpdateLeftSelectionPosition = true; + eventData.mUpdateLeftSelectionPosition = true; eventData.mUpdateRightSelectionPosition = true; - eventData.mUpdateGrabHandlePosition = true; - eventData.mUpdateHighlightBox = true; + eventData.mUpdateGrabHandlePosition = true; + eventData.mUpdateHighlightBox = true; // Hide the text selection popup if select the text using keyboard instead of moving grab handles - if( eventData.mGrabHandlePopupEnabled ) + if(eventData.mGrabHandlePopupEnabled) { - eventData.mDecorator->SetPopupActive( false ); + eventData.mDecorator->SetPopupActive(false); } } } else { // Handle normal cursor move - impl.ChangeState( EventData::EDITING ); + impl.ChangeState(EventData::EDITING); eventData.mUpdateCursorPosition = true; } - eventData.mUpdateInputStyle = true; + eventData.mUpdateInputStyle = true; eventData.mScrollAfterUpdatePosition = true; } void ControllerImplEventHandler::OnTapEvent(Controller::Impl& impl, const Event& event) { - if( impl.mEventData ) + if(impl.mEventData) { - const unsigned int tapCount = event.p1.mUint; - EventData& eventData = *impl.mEventData; - ModelPtr& model = impl.mModel; - LogicalModelPtr& logicalModel = model->mLogicalModel; - VisualModelPtr& visualModel = model->mVisualModel; + const unsigned int tapCount = event.p1.mUint; + EventData& eventData = *impl.mEventData; + ModelPtr& model = impl.mModel; + LogicalModelPtr& logicalModel = model->mLogicalModel; + VisualModelPtr& visualModel = model->mVisualModel; - if( 1u == tapCount ) + if(1u == tapCount) { - if( impl.IsShowingRealText() ) + if(impl.IsShowingRealText()) { // Convert from control's coords to text's coords. const float xPosition = event.p2.mFloat - model->mScrollPosition.x; @@ -469,14 +464,14 @@ void ControllerImplEventHandler::OnTapEvent(Controller::Impl& impl, const Event& eventData.mCursorHookPositionX = xPosition; // Whether to touch point hits on a glyph. - bool matchedCharacter = false; - eventData.mPrimaryCursorPosition = Text::GetClosestCursorIndex( visualModel, - logicalModel, - impl.mMetrics, - xPosition, - yPosition, - CharacterHitTest::TAP, - matchedCharacter ); + bool matchedCharacter = false; + eventData.mPrimaryCursorPosition = Text::GetClosestCursorIndex(visualModel, + logicalModel, + impl.mMetrics, + xPosition, + yPosition, + CharacterHitTest::TAP, + matchedCharacter); // When the cursor position is changing, delay cursor blinking eventData.mDecorator->DelayCursorBlink(); @@ -487,31 +482,31 @@ void ControllerImplEventHandler::OnTapEvent(Controller::Impl& impl, const Event& } // Update selection position after tapping - eventData.mLeftSelectionPosition = eventData.mPrimaryCursorPosition; + eventData.mLeftSelectionPosition = eventData.mPrimaryCursorPosition; eventData.mRightSelectionPosition = eventData.mPrimaryCursorPosition; - eventData.mUpdateCursorPosition = true; - eventData.mUpdateGrabHandlePosition = true; + eventData.mUpdateCursorPosition = true; + eventData.mUpdateGrabHandlePosition = true; eventData.mScrollAfterUpdatePosition = true; - eventData.mUpdateInputStyle = true; + eventData.mUpdateInputStyle = true; // Notify the cursor position to the InputMethodContext. - if( eventData.mInputMethodContext ) + if(eventData.mInputMethodContext) { - eventData.mInputMethodContext.SetCursorPosition( eventData.mPrimaryCursorPosition ); + eventData.mInputMethodContext.SetCursorPosition(eventData.mPrimaryCursorPosition); eventData.mInputMethodContext.NotifyCursorPosition(); } } - else if( 2u == tapCount ) + else if(2u == tapCount) { - if( eventData.mSelectionEnabled ) + if(eventData.mSelectionEnabled) { // Convert from control's coords to text's coords. const float xPosition = event.p2.mFloat - model->mScrollPosition.x; const float yPosition = event.p3.mFloat - model->mScrollPosition.y; // Calculates the logical position from the x,y coords. - impl.RepositionSelectionHandles( xPosition, yPosition, eventData.mDoubleTapAction ); + impl.RepositionSelectionHandles(xPosition, yPosition, eventData.mDoubleTapAction); } } } @@ -519,61 +514,61 @@ void ControllerImplEventHandler::OnTapEvent(Controller::Impl& impl, const Event& void ControllerImplEventHandler::OnPanEvent(Controller::Impl& impl, const Event& event) { - if( impl.mEventData ) + if(impl.mEventData) { - EventData& eventData = *impl.mEventData; + EventData& eventData = *impl.mEventData; DecoratorPtr& decorator = eventData.mDecorator; const bool isHorizontalScrollEnabled = decorator->IsHorizontalScrollEnabled(); - const bool isVerticalScrollEnabled = decorator->IsVerticalScrollEnabled(); + const bool isVerticalScrollEnabled = decorator->IsVerticalScrollEnabled(); - if( !isHorizontalScrollEnabled && !isVerticalScrollEnabled ) + if(!isHorizontalScrollEnabled && !isVerticalScrollEnabled) { // Nothing to do if scrolling is not enabled. return; } - const GestureState state = static_cast( event.p1.mInt ); - switch( state ) + const GestureState state = static_cast(event.p1.mInt); + switch(state) { case GestureState::STARTED: { // Will remove the cursor, handles or text's popup, ... - impl.ChangeState( EventData::TEXT_PANNING ); + impl.ChangeState(EventData::TEXT_PANNING); break; } case GestureState::CONTINUING: { ModelPtr& model = impl.mModel; - const Vector2& layoutSize = model->mVisualModel->GetLayoutSize(); - Vector2& scrollPosition = model->mScrollPosition; - const Vector2 currentScroll = scrollPosition; + const Vector2& layoutSize = model->mVisualModel->GetLayoutSize(); + Vector2& scrollPosition = model->mScrollPosition; + const Vector2 currentScroll = scrollPosition; - if( isHorizontalScrollEnabled ) + if(isHorizontalScrollEnabled) { const float displacementX = event.p2.mFloat; scrollPosition.x += displacementX; - impl.ClampHorizontalScroll( layoutSize ); + impl.ClampHorizontalScroll(layoutSize); } - if( isVerticalScrollEnabled ) + if(isVerticalScrollEnabled) { const float displacementY = event.p3.mFloat; scrollPosition.y += displacementY; - impl.ClampVerticalScroll( layoutSize ); + impl.ClampVerticalScroll(layoutSize); } - decorator->UpdatePositions( scrollPosition - currentScroll ); + decorator->UpdatePositions(scrollPosition - currentScroll); break; } case GestureState::FINISHED: case GestureState::CANCELLED: // FALLTHROUGH { // Will go back to the previous state to show the cursor, handles, the text's popup, ... - impl.ChangeState( eventData.mPreviousState ); + impl.ChangeState(eventData.mPreviousState); break; } default: @@ -584,21 +579,21 @@ void ControllerImplEventHandler::OnPanEvent(Controller::Impl& impl, const Event& void ControllerImplEventHandler::OnLongPressEvent(Controller::Impl& impl, const Event& event) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::OnLongPressEvent\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::OnLongPressEvent\n"); - if( impl.mEventData ) + if(impl.mEventData) { EventData& eventData = *impl.mEventData; - if( !impl.IsShowingRealText() && ( EventData::EDITING == eventData.mState ) ) + if(!impl.IsShowingRealText() && (EventData::EDITING == eventData.mState)) { - impl.ChangeState( EventData::EDITING_WITH_POPUP ); + impl.ChangeState(EventData::EDITING_WITH_POPUP); eventData.mDecoratorUpdated = true; eventData.mUpdateInputStyle = true; } else { - if( eventData.mSelectionEnabled ) + if(eventData.mSelectionEnabled) { ModelPtr& model = impl.mModel; @@ -607,7 +602,7 @@ void ControllerImplEventHandler::OnLongPressEvent(Controller::Impl& impl, const const float yPosition = event.p3.mFloat - model->mScrollPosition.y; // Calculates the logical position from the x,y coords. - impl.RepositionSelectionHandles( xPosition, yPosition, eventData.mLongPressAction ); + impl.RepositionSelectionHandles(xPosition, yPosition, eventData.mLongPressAction); } } } @@ -615,33 +610,33 @@ void ControllerImplEventHandler::OnLongPressEvent(Controller::Impl& impl, const void ControllerImplEventHandler::OnHandleEvent(Controller::Impl& impl, const Event& event) { - if( impl.mEventData ) + if(impl.mEventData) { - const unsigned int state = event.p1.mUint; - const bool handleStopScrolling = ( HANDLE_STOP_SCROLLING == state ); - const bool isSmoothHandlePanEnabled = impl.mEventData->mDecorator->IsSmoothHandlePanEnabled(); + const unsigned int state = event.p1.mUint; + const bool handleStopScrolling = (HANDLE_STOP_SCROLLING == state); + const bool isSmoothHandlePanEnabled = impl.mEventData->mDecorator->IsSmoothHandlePanEnabled(); - if( HANDLE_PRESSED == state ) + if(HANDLE_PRESSED == state) { OnHandlePressed(impl, event, isSmoothHandlePanEnabled); } // end ( HANDLE_PRESSED == state ) - else if( ( HANDLE_RELEASED == state ) || - handleStopScrolling ) + else if((HANDLE_RELEASED == state) || + handleStopScrolling) { OnHandleReleased(impl, event, isSmoothHandlePanEnabled, handleStopScrolling); } // end ( ( HANDLE_RELEASED == state ) || ( HANDLE_STOP_SCROLLING == state ) ) - else if( HANDLE_SCROLLING == state ) + else if(HANDLE_SCROLLING == state) { OnHandleScrolling(impl, event, isSmoothHandlePanEnabled); } // end ( HANDLE_SCROLLING == state ) } } -void ControllerImplEventHandler::OnSelectEvent(Controller::Impl& impl, const Event& event ) +void ControllerImplEventHandler::OnSelectEvent(Controller::Impl& impl, const Event& event) { - if( impl.mEventData && impl.mEventData->mSelectionEnabled ) + if(impl.mEventData && impl.mEventData->mSelectionEnabled) { - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; const Vector2& scrollPosition = model->mScrollPosition; // Convert from control's coords to text's coords. @@ -649,28 +644,28 @@ void ControllerImplEventHandler::OnSelectEvent(Controller::Impl& impl, const Eve const float yPosition = event.p3.mFloat - scrollPosition.y; // Calculates the logical position from the x,y coords. - impl.RepositionSelectionHandles( xPosition, yPosition, Controller::NoTextTap::HIGHLIGHT ); + impl.RepositionSelectionHandles(xPosition, yPosition, Controller::NoTextTap::HIGHLIGHT); } } void ControllerImplEventHandler::OnSelectAllEvent(Controller::Impl& impl) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "OnSelectAllEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled?"true":"false"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "OnSelectAllEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled ? "true" : "false"); - if( impl.mEventData ) + if(impl.mEventData) { EventData& eventData = *impl.mEventData; - if( eventData.mSelectionEnabled ) + if(eventData.mSelectionEnabled) { - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; const Vector2& scrollPosition = model->mScrollPosition; // Calculates the logical position from the start. - impl.RepositionSelectionHandles( 0.f - scrollPosition.x, - 0.f - scrollPosition.y, - Controller::NoTextTap::HIGHLIGHT ); + impl.RepositionSelectionHandles(0.f - scrollPosition.x, + 0.f - scrollPosition.y, + Controller::NoTextTap::HIGHLIGHT); - eventData.mLeftSelectionPosition = 0u; + eventData.mLeftSelectionPosition = 0u; eventData.mRightSelectionPosition = model->mLogicalModel->mText.Count(); } } @@ -678,18 +673,18 @@ void ControllerImplEventHandler::OnSelectAllEvent(Controller::Impl& impl) void ControllerImplEventHandler::OnSelectNoneEvent(Controller::Impl& impl) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "OnSelectNoneEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled?"true":"false"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "OnSelectNoneEvent mEventData->mSelectionEnabled%s \n", impl.mEventData->mSelectionEnabled ? "true" : "false"); - if( impl.mEventData ) + if(impl.mEventData) { EventData& eventData = *impl.mEventData; - if( eventData.mSelectionEnabled && eventData.mState == EventData::SELECTING) + if(eventData.mSelectionEnabled && eventData.mState == EventData::SELECTING) { eventData.mPrimaryCursorPosition = 0u; eventData.mLeftSelectionPosition = eventData.mRightSelectionPosition = eventData.mPrimaryCursorPosition; - impl.ChangeState( EventData::INACTIVE ); - eventData.mUpdateCursorPosition = true; - eventData.mUpdateInputStyle = true; + impl.ChangeState(EventData::INACTIVE); + eventData.mUpdateCursorPosition = true; + eventData.mUpdateInputStyle = true; eventData.mScrollAfterUpdatePosition = true; } } @@ -697,7 +692,7 @@ void ControllerImplEventHandler::OnSelectNoneEvent(Controller::Impl& impl) void ControllerImplEventHandler::OnHandlePressed(Controller::Impl& impl, const Event& event, const bool isSmoothHandlePanEnabled) { - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; const Vector2& scrollPosition = model->mScrollPosition; // Convert from decorator's coords to text's coords. @@ -705,73 +700,73 @@ void ControllerImplEventHandler::OnHandlePressed(Controller::Impl& impl, const E const float yPosition = event.p3.mFloat - scrollPosition.y; // Need to calculate the handle's new position. - bool matchedCharacter = false; - const CharacterIndex handleNewPosition = Text::GetClosestCursorIndex( model->mVisualModel, - model->mLogicalModel, - impl.mMetrics, - xPosition, - yPosition, - CharacterHitTest::SCROLL, - matchedCharacter ); + bool matchedCharacter = false; + const CharacterIndex handleNewPosition = Text::GetClosestCursorIndex(model->mVisualModel, + model->mLogicalModel, + impl.mMetrics, + xPosition, + yPosition, + CharacterHitTest::SCROLL, + matchedCharacter); EventData& eventData = *impl.mEventData; - if( Event::GRAB_HANDLE_EVENT == event.type ) + if(Event::GRAB_HANDLE_EVENT == event.type) { - impl.ChangeState ( EventData::GRAB_HANDLE_PANNING ); + impl.ChangeState(EventData::GRAB_HANDLE_PANNING); - if( handleNewPosition != eventData.mPrimaryCursorPosition ) + if(handleNewPosition != eventData.mPrimaryCursorPosition) { // Updates the cursor position if the handle's new position is different than the current one. eventData.mUpdateCursorPosition = true; // Does not update the grab handle position if the smooth panning is enabled. (The decorator does it smooth). eventData.mUpdateGrabHandlePosition = !isSmoothHandlePanEnabled; - eventData.mPrimaryCursorPosition = handleNewPosition; + eventData.mPrimaryCursorPosition = handleNewPosition; } // Updates the decorator if the soft handle panning is enabled. It triggers a relayout in the decorator and the new position of the handle is set. eventData.mDecoratorUpdated = isSmoothHandlePanEnabled; } - else if( Event::LEFT_SELECTION_HANDLE_EVENT == event.type ) + else if(Event::LEFT_SELECTION_HANDLE_EVENT == event.type) { - impl.ChangeState ( EventData::SELECTION_HANDLE_PANNING ); + impl.ChangeState(EventData::SELECTION_HANDLE_PANNING); - if( ( handleNewPosition != eventData.mLeftSelectionPosition ) && - ( handleNewPosition != eventData.mRightSelectionPosition ) ) + if((handleNewPosition != eventData.mLeftSelectionPosition) && + (handleNewPosition != eventData.mRightSelectionPosition)) { // Updates the highlight box if the handle's new position is different than the current one. eventData.mUpdateHighlightBox = true; // Does not update the selection handle position if the smooth panning is enabled. (The decorator does it smooth). eventData.mUpdateLeftSelectionPosition = !isSmoothHandlePanEnabled; - eventData.mLeftSelectionPosition = handleNewPosition; + eventData.mLeftSelectionPosition = handleNewPosition; } // Updates the decorator if the soft handle panning is enabled. It triggers a relayout in the decorator and the new position of the handle is set. eventData.mDecoratorUpdated = isSmoothHandlePanEnabled; // Will define the order to scroll the text to match the handle position. - eventData.mIsLeftHandleSelected = true; + eventData.mIsLeftHandleSelected = true; eventData.mIsRightHandleSelected = false; } - else if( Event::RIGHT_SELECTION_HANDLE_EVENT == event.type ) + else if(Event::RIGHT_SELECTION_HANDLE_EVENT == event.type) { - impl.ChangeState ( EventData::SELECTION_HANDLE_PANNING ); + impl.ChangeState(EventData::SELECTION_HANDLE_PANNING); - if( ( handleNewPosition != eventData.mRightSelectionPosition ) && - ( handleNewPosition != eventData.mLeftSelectionPosition ) ) + if((handleNewPosition != eventData.mRightSelectionPosition) && + (handleNewPosition != eventData.mLeftSelectionPosition)) { // Updates the highlight box if the handle's new position is different than the current one. eventData.mUpdateHighlightBox = true; // Does not update the selection handle position if the smooth panning is enabled. (The decorator does it smooth). eventData.mUpdateRightSelectionPosition = !isSmoothHandlePanEnabled; - eventData.mRightSelectionPosition = handleNewPosition; + eventData.mRightSelectionPosition = handleNewPosition; } // Updates the decorator if the soft handle panning is enabled. It triggers a relayout in the decorator and the new position of the handle is set. eventData.mDecoratorUpdated = isSmoothHandlePanEnabled; // Will define the order to scroll the text to match the handle position. - eventData.mIsLeftHandleSelected = false; + eventData.mIsLeftHandleSelected = false; eventData.mIsRightHandleSelected = true; } } @@ -779,9 +774,9 @@ void ControllerImplEventHandler::OnHandlePressed(Controller::Impl& impl, const E void ControllerImplEventHandler::OnHandleReleased(Controller::Impl& impl, const Event& event, const bool isSmoothHandlePanEnabled, const bool handleStopScrolling) { CharacterIndex handlePosition = 0u; - if( handleStopScrolling || isSmoothHandlePanEnabled ) + if(handleStopScrolling || isSmoothHandlePanEnabled) { - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; const Vector2& scrollPosition = model->mScrollPosition; // Convert from decorator's coords to text's coords. @@ -789,66 +784,66 @@ void ControllerImplEventHandler::OnHandleReleased(Controller::Impl& impl, const const float yPosition = event.p3.mFloat - scrollPosition.y; bool matchedCharacter = false; - handlePosition = Text::GetClosestCursorIndex( model->mVisualModel, - model->mLogicalModel, - impl.mMetrics, - xPosition, - yPosition, - CharacterHitTest::SCROLL, - matchedCharacter ); + handlePosition = Text::GetClosestCursorIndex(model->mVisualModel, + model->mLogicalModel, + impl.mMetrics, + xPosition, + yPosition, + CharacterHitTest::SCROLL, + matchedCharacter); } EventData& eventData = *impl.mEventData; - if( Event::GRAB_HANDLE_EVENT == event.type ) + if(Event::GRAB_HANDLE_EVENT == event.type) { - eventData.mUpdateCursorPosition = true; + eventData.mUpdateCursorPosition = true; eventData.mUpdateGrabHandlePosition = true; - eventData.mUpdateInputStyle = true; + eventData.mUpdateInputStyle = true; - if( !impl.IsClipboardEmpty() ) + if(!impl.IsClipboardEmpty()) { - impl.ChangeState( EventData::EDITING_WITH_PASTE_POPUP ); // Moving grabhandle will show Paste Popup + impl.ChangeState(EventData::EDITING_WITH_PASTE_POPUP); // Moving grabhandle will show Paste Popup } - if( handleStopScrolling || isSmoothHandlePanEnabled ) + if(handleStopScrolling || isSmoothHandlePanEnabled) { eventData.mScrollAfterUpdatePosition = true; - eventData.mPrimaryCursorPosition = handlePosition; + eventData.mPrimaryCursorPosition = handlePosition; } } - else if( Event::LEFT_SELECTION_HANDLE_EVENT == event.type ) + else if(Event::LEFT_SELECTION_HANDLE_EVENT == event.type) { - impl.ChangeState( EventData::SELECTING ); + impl.ChangeState(EventData::SELECTING); - eventData.mUpdateHighlightBox = true; - eventData.mUpdateLeftSelectionPosition = true; + eventData.mUpdateHighlightBox = true; + eventData.mUpdateLeftSelectionPosition = true; eventData.mUpdateRightSelectionPosition = true; - if( handleStopScrolling || isSmoothHandlePanEnabled ) + if(handleStopScrolling || isSmoothHandlePanEnabled) { eventData.mScrollAfterUpdatePosition = true; - if( ( handlePosition != eventData.mRightSelectionPosition ) && - ( handlePosition != eventData.mLeftSelectionPosition ) ) + if((handlePosition != eventData.mRightSelectionPosition) && + (handlePosition != eventData.mLeftSelectionPosition)) { eventData.mLeftSelectionPosition = handlePosition; } } } - else if( Event::RIGHT_SELECTION_HANDLE_EVENT == event.type ) + else if(Event::RIGHT_SELECTION_HANDLE_EVENT == event.type) { - impl.ChangeState( EventData::SELECTING ); + impl.ChangeState(EventData::SELECTING); - eventData.mUpdateHighlightBox = true; + eventData.mUpdateHighlightBox = true; eventData.mUpdateRightSelectionPosition = true; - eventData.mUpdateLeftSelectionPosition = true; + eventData.mUpdateLeftSelectionPosition = true; - if( handleStopScrolling || isSmoothHandlePanEnabled ) + if(handleStopScrolling || isSmoothHandlePanEnabled) { eventData.mScrollAfterUpdatePosition = true; - if( ( handlePosition != eventData.mRightSelectionPosition ) && - ( handlePosition != eventData.mLeftSelectionPosition ) ) + if((handlePosition != eventData.mRightSelectionPosition) && + (handlePosition != eventData.mLeftSelectionPosition)) { eventData.mRightSelectionPosition = handlePosition; } @@ -860,26 +855,26 @@ void ControllerImplEventHandler::OnHandleReleased(Controller::Impl& impl, const void ControllerImplEventHandler::OnHandleScrolling(Controller::Impl& impl, const Event& event, const bool isSmoothHandlePanEnabled) { - ModelPtr& model = impl.mModel; - Vector2& scrollPosition = model->mScrollPosition; - VisualModelPtr& visualModel = model->mVisualModel; + ModelPtr& model = impl.mModel; + Vector2& scrollPosition = model->mScrollPosition; + VisualModelPtr& visualModel = model->mVisualModel; - const float xSpeed = event.p2.mFloat; - const float ySpeed = event.p3.mFloat; - const Vector2& layoutSize = visualModel->GetLayoutSize(); - const Vector2 currentScrollPosition = scrollPosition; + const float xSpeed = event.p2.mFloat; + const float ySpeed = event.p3.mFloat; + const Vector2& layoutSize = visualModel->GetLayoutSize(); + const Vector2 currentScrollPosition = scrollPosition; scrollPosition.x += xSpeed; scrollPosition.y += ySpeed; - impl.ClampHorizontalScroll( layoutSize ); - impl.ClampVerticalScroll( layoutSize ); + impl.ClampHorizontalScroll(layoutSize); + impl.ClampVerticalScroll(layoutSize); - EventData& eventData = *impl.mEventData; + EventData& eventData = *impl.mEventData; DecoratorPtr& decorator = eventData.mDecorator; bool endOfScroll = false; - if( Vector2::ZERO == ( currentScrollPosition - scrollPosition ) ) + if(Vector2::ZERO == (currentScrollPosition - scrollPosition)) { // Notify the decorator there is no more text to scroll. // The decorator won't send more scroll events. @@ -889,25 +884,25 @@ void ControllerImplEventHandler::OnHandleScrolling(Controller::Impl& impl, const } // Set the position of the handle. - const bool scrollRightDirection = xSpeed > 0.f; - const bool scrollBottomDirection = ySpeed > 0.f; - const bool leftSelectionHandleEvent = Event::LEFT_SELECTION_HANDLE_EVENT == event.type; + const bool scrollRightDirection = xSpeed > 0.f; + const bool scrollBottomDirection = ySpeed > 0.f; + const bool leftSelectionHandleEvent = Event::LEFT_SELECTION_HANDLE_EVENT == event.type; const bool rightSelectionHandleEvent = Event::RIGHT_SELECTION_HANDLE_EVENT == event.type; - if( Event::GRAB_HANDLE_EVENT == event.type ) + if(Event::GRAB_HANDLE_EVENT == event.type) { - impl.ChangeState( EventData::GRAB_HANDLE_PANNING ); + impl.ChangeState(EventData::GRAB_HANDLE_PANNING); // Get the grab handle position in decorator coords. - Vector2 position = decorator->GetPosition( GRAB_HANDLE ); + Vector2 position = decorator->GetPosition(GRAB_HANDLE); - if( decorator->IsHorizontalScrollEnabled() ) + if(decorator->IsHorizontalScrollEnabled()) { // Position the grag handle close to either the left or right edge. position.x = scrollRightDirection ? 0.f : visualModel->mControlSize.width; } - if( decorator->IsVerticalScrollEnabled() ) + if(decorator->IsVerticalScrollEnabled()) { position.x = eventData.mCursorHookPositionX; @@ -917,41 +912,41 @@ void ControllerImplEventHandler::OnHandleScrolling(Controller::Impl& impl, const // Get the new handle position. // The grab handle's position is in decorator's coords. Need to transforms to text's coords. - bool matchedCharacter = false; - const CharacterIndex handlePosition = Text::GetClosestCursorIndex( visualModel, - impl.mModel->mLogicalModel, - impl.mMetrics, - position.x - scrollPosition.x, - position.y - scrollPosition.y, - CharacterHitTest::SCROLL, - matchedCharacter ); - - if( eventData.mPrimaryCursorPosition != handlePosition ) - { - eventData.mUpdateCursorPosition = true; - eventData.mUpdateGrabHandlePosition = !isSmoothHandlePanEnabled; + bool matchedCharacter = false; + const CharacterIndex handlePosition = Text::GetClosestCursorIndex(visualModel, + impl.mModel->mLogicalModel, + impl.mMetrics, + position.x - scrollPosition.x, + position.y - scrollPosition.y, + CharacterHitTest::SCROLL, + matchedCharacter); + + if(eventData.mPrimaryCursorPosition != handlePosition) + { + eventData.mUpdateCursorPosition = true; + eventData.mUpdateGrabHandlePosition = !isSmoothHandlePanEnabled; eventData.mScrollAfterUpdatePosition = true; - eventData.mPrimaryCursorPosition = handlePosition; + eventData.mPrimaryCursorPosition = handlePosition; } eventData.mUpdateInputStyle = eventData.mUpdateCursorPosition; // Updates the decorator if the soft handle panning is enabled. eventData.mDecoratorUpdated = isSmoothHandlePanEnabled; } - else if( leftSelectionHandleEvent || rightSelectionHandleEvent ) + else if(leftSelectionHandleEvent || rightSelectionHandleEvent) { - impl.ChangeState( EventData::SELECTION_HANDLE_PANNING ); + impl.ChangeState(EventData::SELECTION_HANDLE_PANNING); // Get the selection handle position in decorator coords. - Vector2 position = decorator->GetPosition( leftSelectionHandleEvent ? Text::LEFT_SELECTION_HANDLE : Text::RIGHT_SELECTION_HANDLE ); + Vector2 position = decorator->GetPosition(leftSelectionHandleEvent ? Text::LEFT_SELECTION_HANDLE : Text::RIGHT_SELECTION_HANDLE); - if( decorator->IsHorizontalScrollEnabled() ) + if(decorator->IsHorizontalScrollEnabled()) { // Position the selection handle close to either the left or right edge. position.x = scrollRightDirection ? 0.f : visualModel->mControlSize.width; } - if( decorator->IsVerticalScrollEnabled() ) + if(decorator->IsVerticalScrollEnabled()) { position.x = eventData.mCursorHookPositionX; @@ -961,40 +956,40 @@ void ControllerImplEventHandler::OnHandleScrolling(Controller::Impl& impl, const // Get the new handle position. // The selection handle's position is in decorator's coords. Need to transform to text's coords. - bool matchedCharacter = false; - const CharacterIndex handlePosition = Text::GetClosestCursorIndex( visualModel, - impl.mModel->mLogicalModel, - impl.mMetrics, - position.x - scrollPosition.x, - position.y - scrollPosition.y, - CharacterHitTest::SCROLL, - matchedCharacter ); + bool matchedCharacter = false; + const CharacterIndex handlePosition = Text::GetClosestCursorIndex(visualModel, + impl.mModel->mLogicalModel, + impl.mMetrics, + position.x - scrollPosition.x, + position.y - scrollPosition.y, + CharacterHitTest::SCROLL, + matchedCharacter); - if( leftSelectionHandleEvent ) + if(leftSelectionHandleEvent) { - const bool differentHandles = ( eventData.mLeftSelectionPosition != handlePosition ) && ( eventData.mRightSelectionPosition != handlePosition ); + const bool differentHandles = (eventData.mLeftSelectionPosition != handlePosition) && (eventData.mRightSelectionPosition != handlePosition); - if( differentHandles || endOfScroll ) + if(differentHandles || endOfScroll) { - eventData.mUpdateHighlightBox = true; - eventData.mUpdateLeftSelectionPosition = !isSmoothHandlePanEnabled; + eventData.mUpdateHighlightBox = true; + eventData.mUpdateLeftSelectionPosition = !isSmoothHandlePanEnabled; eventData.mUpdateRightSelectionPosition = isSmoothHandlePanEnabled; - eventData.mLeftSelectionPosition = handlePosition; + eventData.mLeftSelectionPosition = handlePosition; } } else { - const bool differentHandles = ( eventData.mRightSelectionPosition != handlePosition ) && ( eventData.mLeftSelectionPosition != handlePosition ); - if( differentHandles || endOfScroll ) + const bool differentHandles = (eventData.mRightSelectionPosition != handlePosition) && (eventData.mLeftSelectionPosition != handlePosition); + if(differentHandles || endOfScroll) { - eventData.mUpdateHighlightBox = true; + eventData.mUpdateHighlightBox = true; eventData.mUpdateRightSelectionPosition = !isSmoothHandlePanEnabled; - eventData.mUpdateLeftSelectionPosition = isSmoothHandlePanEnabled; - eventData.mRightSelectionPosition = handlePosition; + eventData.mUpdateLeftSelectionPosition = isSmoothHandlePanEnabled; + eventData.mRightSelectionPosition = handlePosition; } } - if( eventData.mUpdateLeftSelectionPosition || eventData.mUpdateRightSelectionPosition ) + if(eventData.mUpdateLeftSelectionPosition || eventData.mUpdateRightSelectionPosition) { impl.RepositionSelectionHandles(); diff --git a/dali-toolkit/internal/text/text-controller-impl.cpp b/dali-toolkit/internal/text/text-controller-impl.cpp index da5e2e7..ec00903 100644 --- a/dali-toolkit/internal/text/text-controller-impl.cpp +++ b/dali-toolkit/internal/text/text-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. @@ -19,11 +19,12 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include +#include #include #include #include @@ -35,92 +36,87 @@ #include #include #include -#include using namespace Dali; namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif struct BackgroundVertex { - Vector2 mPosition; ///< Vertex posiiton - Vector4 mColor; ///< Vertex color + Vector2 mPosition; ///< Vertex posiiton + Vector4 mColor; ///< Vertex color }; struct BackgroundMesh { - Vector< BackgroundVertex > mVertices; ///< container of vertices - Vector< unsigned short > mIndices; ///< container of indices + Vector mVertices; ///< container of vertices + Vector mIndices; ///< container of indices }; -const Dali::Vector4 LIGHT_BLUE( 0.75f, 0.96f, 1.f, 1.f ); -const Dali::Vector4 BACKGROUND_SUB4( 0.58f, 0.87f, 0.96f, 1.f ); -const Dali::Vector4 BACKGROUND_SUB5( 0.83f, 0.94f, 0.98f, 1.f ); -const Dali::Vector4 BACKGROUND_SUB6( 1.f, 0.5f, 0.5f, 1.f ); -const Dali::Vector4 BACKGROUND_SUB7( 1.f, 0.8f, 0.8f, 1.f ); +const Dali::Vector4 LIGHT_BLUE(0.75f, 0.96f, 1.f, 1.f); +const Dali::Vector4 BACKGROUND_SUB4(0.58f, 0.87f, 0.96f, 1.f); +const Dali::Vector4 BACKGROUND_SUB5(0.83f, 0.94f, 0.98f, 1.f); +const Dali::Vector4 BACKGROUND_SUB6(1.f, 0.5f, 0.5f, 1.f); +const Dali::Vector4 BACKGROUND_SUB7(1.f, 0.8f, 0.8f, 1.f); } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - -EventData::EventData( DecoratorPtr decorator, InputMethodContext& inputMethodContext ) -: mDecorator( decorator ), - mInputMethodContext( inputMethodContext ), - mPlaceholderFont( NULL ), +EventData::EventData(DecoratorPtr decorator, InputMethodContext& inputMethodContext) +: mDecorator(decorator), + mInputMethodContext(inputMethodContext), + mPlaceholderFont(NULL), mPlaceholderTextActive(), mPlaceholderTextInactive(), - mPlaceholderTextColor( 0.8f, 0.8f, 0.8f, 0.8f ), // This color has been published in the Public API (placeholder-properties.h). + mPlaceholderTextColor(0.8f, 0.8f, 0.8f, 0.8f), // This color has been published in the Public API (placeholder-properties.h). mEventQueue(), mInputStyleChangedQueue(), - mPreviousState( INACTIVE ), - mState( INACTIVE ), - mPrimaryCursorPosition( 0u ), - mLeftSelectionPosition( 0u ), - mRightSelectionPosition( 0u ), - mPreEditStartPosition( 0u ), - mPreEditLength( 0u ), - mCursorHookPositionX( 0.f ), - mDoubleTapAction( Controller::NoTextTap::NO_ACTION ), - mLongPressAction( Controller::NoTextTap::SHOW_SELECTION_POPUP ), - mIsShowingPlaceholderText( false ), - mPreEditFlag( false ), - mDecoratorUpdated( false ), - mCursorBlinkEnabled( true ), - mGrabHandleEnabled( true ), - mGrabHandlePopupEnabled( true ), - mSelectionEnabled( true ), - mUpdateCursorHookPosition( false ), - mUpdateCursorPosition( false ), - mUpdateGrabHandlePosition( false ), - mUpdateLeftSelectionPosition( false ), - mUpdateRightSelectionPosition( false ), - mIsLeftHandleSelected( false ), - mIsRightHandleSelected( false ), - mUpdateHighlightBox( false ), - mScrollAfterUpdatePosition( false ), - mScrollAfterDelete( false ), - mAllTextSelected( false ), - mUpdateInputStyle( false ), - mPasswordInput( false ), - mCheckScrollAmount( false ), - mIsPlaceholderPixelSize( false ), - mIsPlaceholderElideEnabled( false ), - mPlaceholderEllipsisFlag( false ), - mShiftSelectionFlag( true ), - mUpdateAlignment( false ), - mEditingEnabled( true ) + mPreviousState(INACTIVE), + mState(INACTIVE), + mPrimaryCursorPosition(0u), + mLeftSelectionPosition(0u), + mRightSelectionPosition(0u), + mPreEditStartPosition(0u), + mPreEditLength(0u), + mCursorHookPositionX(0.f), + mDoubleTapAction(Controller::NoTextTap::NO_ACTION), + mLongPressAction(Controller::NoTextTap::SHOW_SELECTION_POPUP), + mIsShowingPlaceholderText(false), + mPreEditFlag(false), + mDecoratorUpdated(false), + mCursorBlinkEnabled(true), + mGrabHandleEnabled(true), + mGrabHandlePopupEnabled(true), + mSelectionEnabled(true), + mUpdateCursorHookPosition(false), + mUpdateCursorPosition(false), + mUpdateGrabHandlePosition(false), + mUpdateLeftSelectionPosition(false), + mUpdateRightSelectionPosition(false), + mIsLeftHandleSelected(false), + mIsRightHandleSelected(false), + mUpdateHighlightBox(false), + mScrollAfterUpdatePosition(false), + mScrollAfterDelete(false), + mAllTextSelected(false), + mUpdateInputStyle(false), + mPasswordInput(false), + mCheckScrollAmount(false), + mIsPlaceholderPixelSize(false), + mIsPlaceholderElideEnabled(false), + mPlaceholderEllipsisFlag(false), + mShiftSelectionFlag(true), + mUpdateAlignment(false), + mEditingEnabled(true) { } @@ -131,14 +127,14 @@ bool Controller::Impl::ProcessInputEvents() void Controller::Impl::NotifyInputMethodContext() { - if( mEventData && mEventData->mInputMethodContext ) + if(mEventData && mEventData->mInputMethodContext) { CharacterIndex cursorPosition = GetLogicalCursorPosition(); - const Length numberOfWhiteSpaces = GetNumberOfWhiteSpaces( 0u ); + const Length numberOfWhiteSpaces = GetNumberOfWhiteSpaces(0u); // Update the cursor position by removing the initial white spaces. - if( cursorPosition < numberOfWhiteSpaces ) + if(cursorPosition < numberOfWhiteSpaces) { cursorPosition = 0u; } @@ -147,17 +143,17 @@ void Controller::Impl::NotifyInputMethodContext() cursorPosition -= numberOfWhiteSpaces; } - mEventData->mInputMethodContext.SetCursorPosition( cursorPosition ); + mEventData->mInputMethodContext.SetCursorPosition(cursorPosition); mEventData->mInputMethodContext.NotifyCursorPosition(); } } void Controller::Impl::NotifyInputMethodContextMultiLineStatus() { - if ( mEventData && mEventData->mInputMethodContext ) + if(mEventData && mEventData->mInputMethodContext) { Text::Layout::Engine::Type layout = mLayoutEngine.GetLayout(); - mEventData->mInputMethodContext.NotifyTextInputMultiLine( layout == Text::Layout::Engine::MULTI_LINE_BOX ); + mEventData->mInputMethodContext.NotifyTextInputMultiLine(layout == Text::Layout::Engine::MULTI_LINE_BOX); } } @@ -165,12 +161,12 @@ CharacterIndex Controller::Impl::GetLogicalCursorPosition() const { CharacterIndex cursorPosition = 0u; - if( mEventData ) + if(mEventData) { - if( ( EventData::SELECTING == mEventData->mState ) || - ( EventData::SELECTION_HANDLE_PANNING == mEventData->mState ) ) + if((EventData::SELECTING == mEventData->mState) || + (EventData::SELECTION_HANDLE_PANNING == mEventData->mState)) { - cursorPosition = std::min( mEventData->mRightSelectionPosition, mEventData->mLeftSelectionPosition ); + cursorPosition = std::min(mEventData->mRightSelectionPosition, mEventData->mLeftSelectionPosition); } else { @@ -181,7 +177,7 @@ CharacterIndex Controller::Impl::GetLogicalCursorPosition() const return cursorPosition; } -Length Controller::Impl::GetNumberOfWhiteSpaces( CharacterIndex index ) const +Length Controller::Impl::GetNumberOfWhiteSpaces(CharacterIndex index) const { Length numberOfWhiteSpaces = 0u; @@ -189,9 +185,9 @@ Length Controller::Impl::GetNumberOfWhiteSpaces( CharacterIndex index ) const Character* utf32CharacterBuffer = mModel->mLogicalModel->mText.Begin(); const Length totalNumberOfCharacters = mModel->mLogicalModel->mText.Count(); - for( ; index < totalNumberOfCharacters; ++index, ++numberOfWhiteSpaces ) + for(; index < totalNumberOfCharacters; ++index, ++numberOfWhiteSpaces) { - if( !TextAbstraction::IsWhiteSpace( *( utf32CharacterBuffer + index ) ) ) + if(!TextAbstraction::IsWhiteSpace(*(utf32CharacterBuffer + index))) { break; } @@ -200,30 +196,30 @@ Length Controller::Impl::GetNumberOfWhiteSpaces( CharacterIndex index ) const return numberOfWhiteSpaces; } -void Controller::Impl::GetText( CharacterIndex index, std::string& text ) const +void Controller::Impl::GetText(CharacterIndex index, std::string& text) const { // Get the total number of characters. Length numberOfCharacters = mModel->mLogicalModel->mText.Count(); // Retrieve the text. - if( 0u != numberOfCharacters ) + if(0u != numberOfCharacters) { - Utf32ToUtf8( mModel->mLogicalModel->mText.Begin() + index, numberOfCharacters - index, text ); + Utf32ToUtf8(mModel->mLogicalModel->mText.Begin() + index, numberOfCharacters - index, text); } } -void Controller::Impl::CalculateTextUpdateIndices( Length& numberOfCharacters ) +void Controller::Impl::CalculateTextUpdateIndices(Length& numberOfCharacters) { mTextUpdateInfo.mParagraphCharacterIndex = 0u; - mTextUpdateInfo.mStartGlyphIndex = 0u; - mTextUpdateInfo.mStartLineIndex = 0u; - numberOfCharacters = 0u; + mTextUpdateInfo.mStartGlyphIndex = 0u; + mTextUpdateInfo.mStartLineIndex = 0u; + numberOfCharacters = 0u; const Length numberOfParagraphs = mModel->mLogicalModel->mParagraphInfo.Count(); - if( 0u == numberOfParagraphs ) + if(0u == numberOfParagraphs) { mTextUpdateInfo.mParagraphCharacterIndex = 0u; - numberOfCharacters = 0u; + numberOfCharacters = 0u; mTextUpdateInfo.mRequestedNumberOfCharacters = mTextUpdateInfo.mNumberOfCharactersToAdd - mTextUpdateInfo.mNumberOfCharactersToRemove; @@ -233,57 +229,57 @@ void Controller::Impl::CalculateTextUpdateIndices( Length& numberOfCharacters ) // Find the paragraphs to be updated. Vector paragraphsToBeUpdated; - if( mTextUpdateInfo.mCharacterIndex >= mTextUpdateInfo.mPreviousNumberOfCharacters ) + if(mTextUpdateInfo.mCharacterIndex >= mTextUpdateInfo.mPreviousNumberOfCharacters) { // Text is being added at the end of the current text. - if( mTextUpdateInfo.mIsLastCharacterNewParagraph ) + if(mTextUpdateInfo.mIsLastCharacterNewParagraph) { // Text is being added in a new paragraph after the last character of the text. - mTextUpdateInfo.mParagraphCharacterIndex = mTextUpdateInfo.mPreviousNumberOfCharacters; - numberOfCharacters = 0u; + mTextUpdateInfo.mParagraphCharacterIndex = mTextUpdateInfo.mPreviousNumberOfCharacters; + numberOfCharacters = 0u; mTextUpdateInfo.mRequestedNumberOfCharacters = mTextUpdateInfo.mNumberOfCharactersToAdd - mTextUpdateInfo.mNumberOfCharactersToRemove; mTextUpdateInfo.mStartGlyphIndex = mModel->mVisualModel->mGlyphs.Count(); - mTextUpdateInfo.mStartLineIndex = mModel->mVisualModel->mLines.Count() - 1u; + mTextUpdateInfo.mStartLineIndex = mModel->mVisualModel->mLines.Count() - 1u; // Nothing else to do; return; } - paragraphsToBeUpdated.PushBack( numberOfParagraphs - 1u ); + paragraphsToBeUpdated.PushBack(numberOfParagraphs - 1u); } else { Length numberOfCharactersToUpdate = 0u; - if( mTextUpdateInfo.mFullRelayoutNeeded ) + if(mTextUpdateInfo.mFullRelayoutNeeded) { numberOfCharactersToUpdate = mTextUpdateInfo.mPreviousNumberOfCharacters; } else { - numberOfCharactersToUpdate = ( mTextUpdateInfo.mNumberOfCharactersToRemove > 0u ) ? mTextUpdateInfo.mNumberOfCharactersToRemove : 1u; + numberOfCharactersToUpdate = (mTextUpdateInfo.mNumberOfCharactersToRemove > 0u) ? mTextUpdateInfo.mNumberOfCharactersToRemove : 1u; } - mModel->mLogicalModel->FindParagraphs( mTextUpdateInfo.mCharacterIndex, - numberOfCharactersToUpdate, - paragraphsToBeUpdated ); + mModel->mLogicalModel->FindParagraphs(mTextUpdateInfo.mCharacterIndex, + numberOfCharactersToUpdate, + paragraphsToBeUpdated); } - if( 0u != paragraphsToBeUpdated.Count() ) + if(0u != paragraphsToBeUpdated.Count()) { - const ParagraphRunIndex firstParagraphIndex = *( paragraphsToBeUpdated.Begin() ); - const ParagraphRun& firstParagraph = *( mModel->mLogicalModel->mParagraphInfo.Begin() + firstParagraphIndex ); - mTextUpdateInfo.mParagraphCharacterIndex = firstParagraph.characterRun.characterIndex; + const ParagraphRunIndex firstParagraphIndex = *(paragraphsToBeUpdated.Begin()); + const ParagraphRun& firstParagraph = *(mModel->mLogicalModel->mParagraphInfo.Begin() + firstParagraphIndex); + mTextUpdateInfo.mParagraphCharacterIndex = firstParagraph.characterRun.characterIndex; - ParagraphRunIndex lastParagraphIndex = *( paragraphsToBeUpdated.End() - 1u ); - const ParagraphRun& lastParagraph = *( mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex ); + ParagraphRunIndex lastParagraphIndex = *(paragraphsToBeUpdated.End() - 1u); + const ParagraphRun& lastParagraph = *(mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex); - if( ( mTextUpdateInfo.mNumberOfCharactersToRemove > 0u ) && // Some character are removed. - ( lastParagraphIndex < numberOfParagraphs - 1u ) && // There is a next paragraph. - ( ( lastParagraph.characterRun.characterIndex + lastParagraph.characterRun.numberOfCharacters ) == // The last removed character is the new paragraph character. - ( mTextUpdateInfo.mCharacterIndex + mTextUpdateInfo.mNumberOfCharactersToRemove ) ) ) + if((mTextUpdateInfo.mNumberOfCharactersToRemove > 0u) && // Some character are removed. + (lastParagraphIndex < numberOfParagraphs - 1u) && // There is a next paragraph. + ((lastParagraph.characterRun.characterIndex + lastParagraph.characterRun.numberOfCharacters) == // The last removed character is the new paragraph character. + (mTextUpdateInfo.mCharacterIndex + mTextUpdateInfo.mNumberOfCharactersToRemove))) { // The new paragraph character of the last updated paragraph has been removed so is going to be merged with the next one. - const ParagraphRun& lastParagraph = *( mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex + 1u ); + const ParagraphRun& lastParagraph = *(mModel->mLogicalModel->mParagraphInfo.Begin() + lastParagraphIndex + 1u); numberOfCharacters = lastParagraph.characterRun.characterIndex + lastParagraph.characterRun.numberOfCharacters - mTextUpdateInfo.mParagraphCharacterIndex; } @@ -294,53 +290,53 @@ void Controller::Impl::CalculateTextUpdateIndices( Length& numberOfCharacters ) } mTextUpdateInfo.mRequestedNumberOfCharacters = numberOfCharacters + mTextUpdateInfo.mNumberOfCharactersToAdd - mTextUpdateInfo.mNumberOfCharactersToRemove; - mTextUpdateInfo.mStartGlyphIndex = *( mModel->mVisualModel->mCharactersToGlyph.Begin() + mTextUpdateInfo.mParagraphCharacterIndex ); + mTextUpdateInfo.mStartGlyphIndex = *(mModel->mVisualModel->mCharactersToGlyph.Begin() + mTextUpdateInfo.mParagraphCharacterIndex); } -void Controller::Impl::ClearFullModelData( OperationsMask operations ) +void Controller::Impl::ClearFullModelData(OperationsMask operations) { - if( NO_OPERATION != ( GET_LINE_BREAKS & operations ) ) + if(NO_OPERATION != (GET_LINE_BREAKS & operations)) { mModel->mLogicalModel->mLineBreakInfo.Clear(); mModel->mLogicalModel->mParagraphInfo.Clear(); } - if( NO_OPERATION != ( GET_SCRIPTS & operations ) ) + if(NO_OPERATION != (GET_SCRIPTS & operations)) { mModel->mLogicalModel->mScriptRuns.Clear(); } - if( NO_OPERATION != ( VALIDATE_FONTS & operations ) ) + if(NO_OPERATION != (VALIDATE_FONTS & operations)) { mModel->mLogicalModel->mFontRuns.Clear(); } - if( 0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count() ) + if(0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count()) { - if( NO_OPERATION != ( BIDI_INFO & operations ) ) + if(NO_OPERATION != (BIDI_INFO & operations)) { mModel->mLogicalModel->mBidirectionalParagraphInfo.Clear(); mModel->mLogicalModel->mCharacterDirections.Clear(); } - if( NO_OPERATION != ( REORDER & operations ) ) + if(NO_OPERATION != (REORDER & operations)) { // Free the allocated memory used to store the conversion table in the bidirectional line info run. - for( Vector::Iterator it = mModel->mLogicalModel->mBidirectionalLineInfo.Begin(), - endIt = mModel->mLogicalModel->mBidirectionalLineInfo.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = mModel->mLogicalModel->mBidirectionalLineInfo.Begin(), + endIt = mModel->mLogicalModel->mBidirectionalLineInfo.End(); + it != endIt; + ++it) { BidirectionalLineInfoRun& bidiLineInfo = *it; - free( bidiLineInfo.visualToLogicalMap ); + free(bidiLineInfo.visualToLogicalMap); bidiLineInfo.visualToLogicalMap = NULL; } mModel->mLogicalModel->mBidirectionalLineInfo.Clear(); } } - if( NO_OPERATION != ( SHAPE_TEXT & operations ) ) + if(NO_OPERATION != (SHAPE_TEXT & operations)) { mModel->mVisualModel->mGlyphs.Clear(); mModel->mVisualModel->mGlyphsToCharacters.Clear(); @@ -350,298 +346,298 @@ void Controller::Impl::ClearFullModelData( OperationsMask operations ) mModel->mVisualModel->mGlyphPositions.Clear(); } - if( NO_OPERATION != ( LAYOUT & operations ) ) + if(NO_OPERATION != (LAYOUT & operations)) { mModel->mVisualModel->mLines.Clear(); } - if( NO_OPERATION != ( COLOR & operations ) ) + if(NO_OPERATION != (COLOR & operations)) { mModel->mVisualModel->mColorIndices.Clear(); mModel->mVisualModel->mBackgroundColorIndices.Clear(); } } -void Controller::Impl::ClearCharacterModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations ) +void Controller::Impl::ClearCharacterModelData(CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations) { const CharacterIndex endIndexPlusOne = endIndex + 1u; - if( NO_OPERATION != ( GET_LINE_BREAKS & operations ) ) + if(NO_OPERATION != (GET_LINE_BREAKS & operations)) { // Clear the line break info. LineBreakInfo* lineBreakInfoBuffer = mModel->mLogicalModel->mLineBreakInfo.Begin(); - mModel->mLogicalModel->mLineBreakInfo.Erase( lineBreakInfoBuffer + startIndex, - lineBreakInfoBuffer + endIndexPlusOne ); + mModel->mLogicalModel->mLineBreakInfo.Erase(lineBreakInfoBuffer + startIndex, + lineBreakInfoBuffer + endIndexPlusOne); // Clear the paragraphs. - ClearCharacterRuns( startIndex, - endIndex, - mModel->mLogicalModel->mParagraphInfo ); + ClearCharacterRuns(startIndex, + endIndex, + mModel->mLogicalModel->mParagraphInfo); } - if( NO_OPERATION != ( GET_SCRIPTS & operations ) ) + if(NO_OPERATION != (GET_SCRIPTS & operations)) { // Clear the scripts. - ClearCharacterRuns( startIndex, - endIndex, - mModel->mLogicalModel->mScriptRuns ); + ClearCharacterRuns(startIndex, + endIndex, + mModel->mLogicalModel->mScriptRuns); } - if( NO_OPERATION != ( VALIDATE_FONTS & operations ) ) + if(NO_OPERATION != (VALIDATE_FONTS & operations)) { // Clear the fonts. - ClearCharacterRuns( startIndex, - endIndex, - mModel->mLogicalModel->mFontRuns ); + ClearCharacterRuns(startIndex, + endIndex, + mModel->mLogicalModel->mFontRuns); } - if( 0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count() ) + if(0u != mModel->mLogicalModel->mBidirectionalParagraphInfo.Count()) { - if( NO_OPERATION != ( BIDI_INFO & operations ) ) + if(NO_OPERATION != (BIDI_INFO & operations)) { // Clear the bidirectional paragraph info. - ClearCharacterRuns( startIndex, - endIndex, - mModel->mLogicalModel->mBidirectionalParagraphInfo ); + ClearCharacterRuns(startIndex, + endIndex, + mModel->mLogicalModel->mBidirectionalParagraphInfo); // Clear the character's directions. CharacterDirection* characterDirectionsBuffer = mModel->mLogicalModel->mCharacterDirections.Begin(); - mModel->mLogicalModel->mCharacterDirections.Erase( characterDirectionsBuffer + startIndex, - characterDirectionsBuffer + endIndexPlusOne ); + mModel->mLogicalModel->mCharacterDirections.Erase(characterDirectionsBuffer + startIndex, + characterDirectionsBuffer + endIndexPlusOne); } - if( NO_OPERATION != ( REORDER & operations ) ) + if(NO_OPERATION != (REORDER & operations)) { uint32_t startRemoveIndex = mModel->mLogicalModel->mBidirectionalLineInfo.Count(); - uint32_t endRemoveIndex = startRemoveIndex; - ClearCharacterRuns( startIndex, - endIndex, - mModel->mLogicalModel->mBidirectionalLineInfo, - startRemoveIndex, - endRemoveIndex ); + uint32_t endRemoveIndex = startRemoveIndex; + ClearCharacterRuns(startIndex, + endIndex, + mModel->mLogicalModel->mBidirectionalLineInfo, + startRemoveIndex, + endRemoveIndex); BidirectionalLineInfoRun* bidirectionalLineInfoBuffer = mModel->mLogicalModel->mBidirectionalLineInfo.Begin(); // Free the allocated memory used to store the conversion table in the bidirectional line info run. - for( Vector::Iterator it = bidirectionalLineInfoBuffer + startRemoveIndex, - endIt = bidirectionalLineInfoBuffer + endRemoveIndex; - it != endIt; - ++it ) + for(Vector::Iterator it = bidirectionalLineInfoBuffer + startRemoveIndex, + endIt = bidirectionalLineInfoBuffer + endRemoveIndex; + it != endIt; + ++it) { BidirectionalLineInfoRun& bidiLineInfo = *it; - free( bidiLineInfo.visualToLogicalMap ); + free(bidiLineInfo.visualToLogicalMap); bidiLineInfo.visualToLogicalMap = NULL; } - mModel->mLogicalModel->mBidirectionalLineInfo.Erase( bidirectionalLineInfoBuffer + startRemoveIndex, - bidirectionalLineInfoBuffer + endRemoveIndex ); + mModel->mLogicalModel->mBidirectionalLineInfo.Erase(bidirectionalLineInfoBuffer + startRemoveIndex, + bidirectionalLineInfoBuffer + endRemoveIndex); } } } -void Controller::Impl::ClearGlyphModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations ) +void Controller::Impl::ClearGlyphModelData(CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations) { - const CharacterIndex endIndexPlusOne = endIndex + 1u; - const Length numberOfCharactersRemoved = endIndexPlusOne - startIndex; + const CharacterIndex endIndexPlusOne = endIndex + 1u; + const Length numberOfCharactersRemoved = endIndexPlusOne - startIndex; // Convert the character index to glyph index before deleting the character to glyph and the glyphs per character buffers. - GlyphIndex* charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin(); - Length* glyphsPerCharacterBuffer = mModel->mVisualModel->mGlyphsPerCharacter.Begin(); + GlyphIndex* charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin(); + Length* glyphsPerCharacterBuffer = mModel->mVisualModel->mGlyphsPerCharacter.Begin(); - const GlyphIndex endGlyphIndexPlusOne = *( charactersToGlyphBuffer + endIndex ) + *( glyphsPerCharacterBuffer + endIndex ); - const Length numberOfGlyphsRemoved = endGlyphIndexPlusOne - mTextUpdateInfo.mStartGlyphIndex; + const GlyphIndex endGlyphIndexPlusOne = *(charactersToGlyphBuffer + endIndex) + *(glyphsPerCharacterBuffer + endIndex); + const Length numberOfGlyphsRemoved = endGlyphIndexPlusOne - mTextUpdateInfo.mStartGlyphIndex; - if( NO_OPERATION != ( SHAPE_TEXT & operations ) ) + if(NO_OPERATION != (SHAPE_TEXT & operations)) { // Update the character to glyph indices. - for( Vector::Iterator it = charactersToGlyphBuffer + endIndexPlusOne, - endIt = charactersToGlyphBuffer + mModel->mVisualModel->mCharactersToGlyph.Count(); - it != endIt; - ++it ) + for(Vector::Iterator it = charactersToGlyphBuffer + endIndexPlusOne, + endIt = charactersToGlyphBuffer + mModel->mVisualModel->mCharactersToGlyph.Count(); + it != endIt; + ++it) { CharacterIndex& index = *it; index -= numberOfGlyphsRemoved; } // Clear the character to glyph conversion table. - mModel->mVisualModel->mCharactersToGlyph.Erase( charactersToGlyphBuffer + startIndex, - charactersToGlyphBuffer + endIndexPlusOne ); + mModel->mVisualModel->mCharactersToGlyph.Erase(charactersToGlyphBuffer + startIndex, + charactersToGlyphBuffer + endIndexPlusOne); // Clear the glyphs per character table. - mModel->mVisualModel->mGlyphsPerCharacter.Erase( glyphsPerCharacterBuffer + startIndex, - glyphsPerCharacterBuffer + endIndexPlusOne ); + mModel->mVisualModel->mGlyphsPerCharacter.Erase(glyphsPerCharacterBuffer + startIndex, + glyphsPerCharacterBuffer + endIndexPlusOne); // Clear the glyphs buffer. GlyphInfo* glyphsBuffer = mModel->mVisualModel->mGlyphs.Begin(); - mModel->mVisualModel->mGlyphs.Erase( glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex, - glyphsBuffer + endGlyphIndexPlusOne ); + mModel->mVisualModel->mGlyphs.Erase(glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex, + glyphsBuffer + endGlyphIndexPlusOne); CharacterIndex* glyphsToCharactersBuffer = mModel->mVisualModel->mGlyphsToCharacters.Begin(); // Update the glyph to character indices. - for( Vector::Iterator it = glyphsToCharactersBuffer + endGlyphIndexPlusOne, - endIt = glyphsToCharactersBuffer + mModel->mVisualModel->mGlyphsToCharacters.Count(); - it != endIt; - ++it ) + for(Vector::Iterator it = glyphsToCharactersBuffer + endGlyphIndexPlusOne, + endIt = glyphsToCharactersBuffer + mModel->mVisualModel->mGlyphsToCharacters.Count(); + it != endIt; + ++it) { CharacterIndex& index = *it; index -= numberOfCharactersRemoved; } // Clear the glyphs to characters buffer. - mModel->mVisualModel->mGlyphsToCharacters.Erase( glyphsToCharactersBuffer + mTextUpdateInfo.mStartGlyphIndex, - glyphsToCharactersBuffer + endGlyphIndexPlusOne ); + mModel->mVisualModel->mGlyphsToCharacters.Erase(glyphsToCharactersBuffer + mTextUpdateInfo.mStartGlyphIndex, + glyphsToCharactersBuffer + endGlyphIndexPlusOne); // Clear the characters per glyph buffer. Length* charactersPerGlyphBuffer = mModel->mVisualModel->mCharactersPerGlyph.Begin(); - mModel->mVisualModel->mCharactersPerGlyph.Erase( charactersPerGlyphBuffer + mTextUpdateInfo.mStartGlyphIndex, - charactersPerGlyphBuffer + endGlyphIndexPlusOne ); + mModel->mVisualModel->mCharactersPerGlyph.Erase(charactersPerGlyphBuffer + mTextUpdateInfo.mStartGlyphIndex, + charactersPerGlyphBuffer + endGlyphIndexPlusOne); // Clear the positions buffer. Vector2* positionsBuffer = mModel->mVisualModel->mGlyphPositions.Begin(); - mModel->mVisualModel->mGlyphPositions.Erase( positionsBuffer + mTextUpdateInfo.mStartGlyphIndex, - positionsBuffer + endGlyphIndexPlusOne ); + mModel->mVisualModel->mGlyphPositions.Erase(positionsBuffer + mTextUpdateInfo.mStartGlyphIndex, + positionsBuffer + endGlyphIndexPlusOne); } - if( NO_OPERATION != ( LAYOUT & operations ) ) + if(NO_OPERATION != (LAYOUT & operations)) { // Clear the lines. uint32_t startRemoveIndex = mModel->mVisualModel->mLines.Count(); - uint32_t endRemoveIndex = startRemoveIndex; - ClearCharacterRuns( startIndex, - endIndex, - mModel->mVisualModel->mLines, - startRemoveIndex, - endRemoveIndex ); + uint32_t endRemoveIndex = startRemoveIndex; + ClearCharacterRuns(startIndex, + endIndex, + mModel->mVisualModel->mLines, + startRemoveIndex, + endRemoveIndex); // Will update the glyph runs. startRemoveIndex = mModel->mVisualModel->mLines.Count(); - endRemoveIndex = startRemoveIndex; - ClearGlyphRuns( mTextUpdateInfo.mStartGlyphIndex, - endGlyphIndexPlusOne - 1u, - mModel->mVisualModel->mLines, - startRemoveIndex, - endRemoveIndex ); + endRemoveIndex = startRemoveIndex; + ClearGlyphRuns(mTextUpdateInfo.mStartGlyphIndex, + endGlyphIndexPlusOne - 1u, + mModel->mVisualModel->mLines, + startRemoveIndex, + endRemoveIndex); // Set the line index from where to insert the new laid-out lines. mTextUpdateInfo.mStartLineIndex = startRemoveIndex; LineRun* linesBuffer = mModel->mVisualModel->mLines.Begin(); - mModel->mVisualModel->mLines.Erase( linesBuffer + startRemoveIndex, - linesBuffer + endRemoveIndex ); + mModel->mVisualModel->mLines.Erase(linesBuffer + startRemoveIndex, + linesBuffer + endRemoveIndex); } - if( NO_OPERATION != ( COLOR & operations ) ) + if(NO_OPERATION != (COLOR & operations)) { - if( 0u != mModel->mVisualModel->mColorIndices.Count() ) + if(0u != mModel->mVisualModel->mColorIndices.Count()) { ColorIndex* colorIndexBuffer = mModel->mVisualModel->mColorIndices.Begin(); - mModel->mVisualModel->mColorIndices.Erase( colorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex, - colorIndexBuffer + endGlyphIndexPlusOne ); + mModel->mVisualModel->mColorIndices.Erase(colorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex, + colorIndexBuffer + endGlyphIndexPlusOne); } - if( 0u != mModel->mVisualModel->mBackgroundColorIndices.Count() ) + if(0u != mModel->mVisualModel->mBackgroundColorIndices.Count()) { ColorIndex* backgroundColorIndexBuffer = mModel->mVisualModel->mBackgroundColorIndices.Begin(); - mModel->mVisualModel->mBackgroundColorIndices.Erase( backgroundColorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex, - backgroundColorIndexBuffer + endGlyphIndexPlusOne ); + mModel->mVisualModel->mBackgroundColorIndices.Erase(backgroundColorIndexBuffer + mTextUpdateInfo.mStartGlyphIndex, + backgroundColorIndexBuffer + endGlyphIndexPlusOne); } } } -void Controller::Impl::ClearModelData( CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations ) +void Controller::Impl::ClearModelData(CharacterIndex startIndex, CharacterIndex endIndex, OperationsMask operations) { - if( mTextUpdateInfo.mClearAll || - ( ( 0u == startIndex ) && - ( mTextUpdateInfo.mPreviousNumberOfCharacters == endIndex + 1u ) ) ) + if(mTextUpdateInfo.mClearAll || + ((0u == startIndex) && + (mTextUpdateInfo.mPreviousNumberOfCharacters == endIndex + 1u))) { - ClearFullModelData( operations ); + ClearFullModelData(operations); } else { // Clear the model data related with characters. - ClearCharacterModelData( startIndex, endIndex, operations ); + ClearCharacterModelData(startIndex, endIndex, operations); // Clear the model data related with glyphs. - ClearGlyphModelData( startIndex, endIndex, operations ); + ClearGlyphModelData(startIndex, endIndex, operations); } // The estimated number of lines. Used to avoid reallocations when layouting. - mTextUpdateInfo.mEstimatedNumberOfLines = std::max( mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count() ); + mTextUpdateInfo.mEstimatedNumberOfLines = std::max(mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count()); mModel->mVisualModel->ClearCaches(); } -bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) +bool Controller::Impl::UpdateModel(OperationsMask operationsRequired) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::UpdateModel\n" ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::UpdateModel\n"); // Calculate the operations to be done. - const OperationsMask operations = static_cast( mOperationsPending & operationsRequired ); + const OperationsMask operations = static_cast(mOperationsPending & operationsRequired); - if( NO_OPERATION == operations ) + if(NO_OPERATION == operations) { // Nothing to do if no operations are pending and required. return false; } Vector& srcCharacters = mModel->mLogicalModel->mText; - Vector displayCharacters; - bool useHiddenText = false; - if ( mHiddenInput && mEventData != NULL && !mEventData->mIsShowingPlaceholderText) + Vector displayCharacters; + bool useHiddenText = false; + if(mHiddenInput && mEventData != NULL && !mEventData->mIsShowingPlaceholderText) { - mHiddenInput->Substitute( srcCharacters,displayCharacters ); + mHiddenInput->Substitute(srcCharacters, displayCharacters); useHiddenText = true; } - Vector& utf32Characters = useHiddenText ? displayCharacters : srcCharacters; - const Length numberOfCharacters = utf32Characters.Count(); + Vector& utf32Characters = useHiddenText ? displayCharacters : srcCharacters; + const Length numberOfCharacters = utf32Characters.Count(); // Index to the first character of the first paragraph to be updated. CharacterIndex startIndex = 0u; // Number of characters of the paragraphs to be removed. Length paragraphCharacters = 0u; - CalculateTextUpdateIndices( paragraphCharacters ); + CalculateTextUpdateIndices(paragraphCharacters); // Check whether the indices for updating the text is valid - if ( numberOfCharacters > 0u && - ( mTextUpdateInfo.mParagraphCharacterIndex > numberOfCharacters || - mTextUpdateInfo.mRequestedNumberOfCharacters > numberOfCharacters ) ) + if(numberOfCharacters > 0u && + (mTextUpdateInfo.mParagraphCharacterIndex > numberOfCharacters || + mTextUpdateInfo.mRequestedNumberOfCharacters > numberOfCharacters)) { std::string currentText; - Utf32ToUtf8( mModel->mLogicalModel->mText.Begin(), numberOfCharacters, currentText ); + Utf32ToUtf8(mModel->mLogicalModel->mText.Begin(), numberOfCharacters, currentText); - DALI_LOG_ERROR( "Controller::Impl::UpdateModel: mTextUpdateInfo has invalid indices\n" ); - DALI_LOG_ERROR( "Number of characters: %d, current text is: %s\n", numberOfCharacters, currentText.c_str() ); + DALI_LOG_ERROR("Controller::Impl::UpdateModel: mTextUpdateInfo has invalid indices\n"); + DALI_LOG_ERROR("Number of characters: %d, current text is: %s\n", numberOfCharacters, currentText.c_str()); // Dump mTextUpdateInfo - DALI_LOG_ERROR( "Dump mTextUpdateInfo:\n" ); - DALI_LOG_ERROR( " mTextUpdateInfo.mCharacterIndex = %u\n", mTextUpdateInfo.mCharacterIndex ); - DALI_LOG_ERROR( " mTextUpdateInfo.mNumberOfCharactersToRemove = %u\n", mTextUpdateInfo.mNumberOfCharactersToRemove ); - DALI_LOG_ERROR( " mTextUpdateInfo.mNumberOfCharactersToAdd = %u\n", mTextUpdateInfo.mNumberOfCharactersToAdd ); - DALI_LOG_ERROR( " mTextUpdateInfo.mPreviousNumberOfCharacters = %u\n", mTextUpdateInfo.mPreviousNumberOfCharacters ); - DALI_LOG_ERROR( " mTextUpdateInfo.mParagraphCharacterIndex = %u\n", mTextUpdateInfo.mParagraphCharacterIndex ); - DALI_LOG_ERROR( " mTextUpdateInfo.mRequestedNumberOfCharacters = %u\n", mTextUpdateInfo.mRequestedNumberOfCharacters ); - DALI_LOG_ERROR( " mTextUpdateInfo.mStartGlyphIndex = %u\n", mTextUpdateInfo.mStartGlyphIndex ); - DALI_LOG_ERROR( " mTextUpdateInfo.mStartLineIndex = %u\n", mTextUpdateInfo.mStartLineIndex ); - DALI_LOG_ERROR( " mTextUpdateInfo.mEstimatedNumberOfLines = %u\n", mTextUpdateInfo.mEstimatedNumberOfLines ); - DALI_LOG_ERROR( " mTextUpdateInfo.mClearAll = %d\n", mTextUpdateInfo.mClearAll ); - DALI_LOG_ERROR( " mTextUpdateInfo.mFullRelayoutNeeded = %d\n", mTextUpdateInfo.mFullRelayoutNeeded ); - DALI_LOG_ERROR( " mTextUpdateInfo.mIsLastCharacterNewParagraph = %d\n", mTextUpdateInfo.mIsLastCharacterNewParagraph ); + DALI_LOG_ERROR("Dump mTextUpdateInfo:\n"); + DALI_LOG_ERROR(" mTextUpdateInfo.mCharacterIndex = %u\n", mTextUpdateInfo.mCharacterIndex); + DALI_LOG_ERROR(" mTextUpdateInfo.mNumberOfCharactersToRemove = %u\n", mTextUpdateInfo.mNumberOfCharactersToRemove); + DALI_LOG_ERROR(" mTextUpdateInfo.mNumberOfCharactersToAdd = %u\n", mTextUpdateInfo.mNumberOfCharactersToAdd); + DALI_LOG_ERROR(" mTextUpdateInfo.mPreviousNumberOfCharacters = %u\n", mTextUpdateInfo.mPreviousNumberOfCharacters); + DALI_LOG_ERROR(" mTextUpdateInfo.mParagraphCharacterIndex = %u\n", mTextUpdateInfo.mParagraphCharacterIndex); + DALI_LOG_ERROR(" mTextUpdateInfo.mRequestedNumberOfCharacters = %u\n", mTextUpdateInfo.mRequestedNumberOfCharacters); + DALI_LOG_ERROR(" mTextUpdateInfo.mStartGlyphIndex = %u\n", mTextUpdateInfo.mStartGlyphIndex); + DALI_LOG_ERROR(" mTextUpdateInfo.mStartLineIndex = %u\n", mTextUpdateInfo.mStartLineIndex); + DALI_LOG_ERROR(" mTextUpdateInfo.mEstimatedNumberOfLines = %u\n", mTextUpdateInfo.mEstimatedNumberOfLines); + DALI_LOG_ERROR(" mTextUpdateInfo.mClearAll = %d\n", mTextUpdateInfo.mClearAll); + DALI_LOG_ERROR(" mTextUpdateInfo.mFullRelayoutNeeded = %d\n", mTextUpdateInfo.mFullRelayoutNeeded); + DALI_LOG_ERROR(" mTextUpdateInfo.mIsLastCharacterNewParagraph = %d\n", mTextUpdateInfo.mIsLastCharacterNewParagraph); return false; } startIndex = mTextUpdateInfo.mParagraphCharacterIndex; - if( mTextUpdateInfo.mClearAll || - ( 0u != paragraphCharacters ) ) + if(mTextUpdateInfo.mClearAll || + (0u != paragraphCharacters)) { - ClearModelData( startIndex, startIndex + ( ( paragraphCharacters > 0u ) ? paragraphCharacters - 1u : 0u ), operations ); + ClearModelData(startIndex, startIndex + ((paragraphCharacters > 0u) ? paragraphCharacters - 1u : 0u), operations); } mTextUpdateInfo.mClearAll = false; @@ -649,50 +645,50 @@ bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) // Whether the model is updated. bool updated = false; - Vector& lineBreakInfo = mModel->mLogicalModel->mLineBreakInfo; - const Length requestedNumberOfCharacters = mTextUpdateInfo.mRequestedNumberOfCharacters; + Vector& lineBreakInfo = mModel->mLogicalModel->mLineBreakInfo; + const Length requestedNumberOfCharacters = mTextUpdateInfo.mRequestedNumberOfCharacters; - if( NO_OPERATION != ( GET_LINE_BREAKS & operations ) ) + if(NO_OPERATION != (GET_LINE_BREAKS & operations)) { // Retrieves the line break info. The line break info is used to split the text in 'paragraphs' to // calculate the bidirectional info for each 'paragraph'. // It's also used to layout the text (where it should be a new line) or to shape the text (text in different lines // is not shaped together). - lineBreakInfo.Resize( numberOfCharacters, TextAbstraction::LINE_NO_BREAK ); + lineBreakInfo.Resize(numberOfCharacters, TextAbstraction::LINE_NO_BREAK); - SetLineBreakInfo( utf32Characters, - startIndex, - requestedNumberOfCharacters, - lineBreakInfo ); + SetLineBreakInfo(utf32Characters, + startIndex, + requestedNumberOfCharacters, + lineBreakInfo); // Create the paragraph info. - mModel->mLogicalModel->CreateParagraphInfo( startIndex, - requestedNumberOfCharacters ); + mModel->mLogicalModel->CreateParagraphInfo(startIndex, + requestedNumberOfCharacters); updated = true; } - const bool getScripts = NO_OPERATION != ( GET_SCRIPTS & operations ); - const bool validateFonts = NO_OPERATION != ( VALIDATE_FONTS & operations ); + const bool getScripts = NO_OPERATION != (GET_SCRIPTS & operations); + const bool validateFonts = NO_OPERATION != (VALIDATE_FONTS & operations); - Vector& scripts = mModel->mLogicalModel->mScriptRuns; - Vector& validFonts = mModel->mLogicalModel->mFontRuns; + Vector& scripts = mModel->mLogicalModel->mScriptRuns; + Vector& validFonts = mModel->mLogicalModel->mFontRuns; - if( getScripts || validateFonts ) + if(getScripts || validateFonts) { // Validates the fonts assigned by the application or assigns default ones. // It makes sure all the characters are going to be rendered by the correct font. MultilanguageSupport multilanguageSupport = MultilanguageSupport::Get(); - if( getScripts ) + if(getScripts) { // Retrieves the scripts used in the text. - multilanguageSupport.SetScripts( utf32Characters, - startIndex, - requestedNumberOfCharacters, - scripts ); + multilanguageSupport.SetScripts(utf32Characters, + startIndex, + requestedNumberOfCharacters, + scripts); } - if( validateFonts ) + if(validateFonts) { // Validate the fonts set through the mark-up string. Vector& fontDescriptionRuns = mModel->mLogicalModel->mFontDescriptionRuns; @@ -701,21 +697,21 @@ bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) TextAbstraction::FontDescription defaultFontDescription; TextAbstraction::PointSize26Dot6 defaultPointSize = TextAbstraction::FontClient::DEFAULT_POINT_SIZE * mFontSizeScale; - if( IsShowingPlaceholderText() && mEventData && ( NULL != mEventData->mPlaceholderFont ) ) + if(IsShowingPlaceholderText() && mEventData && (NULL != mEventData->mPlaceholderFont)) { // If the placeholder font is set specifically, only placeholder font is changed. defaultFontDescription = mEventData->mPlaceholderFont->mFontDescription; - if( mEventData->mPlaceholderFont->sizeDefined ) + if(mEventData->mPlaceholderFont->sizeDefined) { defaultPointSize = mEventData->mPlaceholderFont->mDefaultPointSize * mFontSizeScale * 64u; } } - else if( NULL != mFontDefaults ) + else if(NULL != mFontDefaults) { // Set the normal font and the placeholder font. defaultFontDescription = mFontDefaults->mFontDescription; - if( mTextFitEnabled ) + if(mTextFitEnabled) { defaultPointSize = mFontDefaults->mFitPointSize * 64u; } @@ -727,55 +723,55 @@ bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) // Validates the fonts. If there is a character with no assigned font it sets a default one. // After this call, fonts are validated. - multilanguageSupport.ValidateFonts( utf32Characters, - scripts, - fontDescriptionRuns, - defaultFontDescription, - defaultPointSize, - startIndex, - requestedNumberOfCharacters, - validFonts ); + multilanguageSupport.ValidateFonts(utf32Characters, + scripts, + fontDescriptionRuns, + defaultFontDescription, + defaultPointSize, + startIndex, + requestedNumberOfCharacters, + validFonts); } updated = true; } Vector mirroredUtf32Characters; - bool textMirrored = false; - const Length numberOfParagraphs = mModel->mLogicalModel->mParagraphInfo.Count(); - if( NO_OPERATION != ( BIDI_INFO & operations ) ) + bool textMirrored = false; + const Length numberOfParagraphs = mModel->mLogicalModel->mParagraphInfo.Count(); + if(NO_OPERATION != (BIDI_INFO & operations)) { Vector& bidirectionalInfo = mModel->mLogicalModel->mBidirectionalParagraphInfo; - bidirectionalInfo.Reserve( numberOfParagraphs ); + bidirectionalInfo.Reserve(numberOfParagraphs); // Calculates the bidirectional info for the whole paragraph if it contains right to left scripts. - SetBidirectionalInfo( utf32Characters, - scripts, - lineBreakInfo, - startIndex, - requestedNumberOfCharacters, - bidirectionalInfo, - mModel->mMatchSystemLanguageDirection, - mLayoutDirection ); - - if( 0u != bidirectionalInfo.Count() ) + SetBidirectionalInfo(utf32Characters, + scripts, + lineBreakInfo, + startIndex, + requestedNumberOfCharacters, + bidirectionalInfo, + mModel->mMatchSystemLanguageDirection, + mLayoutDirection); + + if(0u != bidirectionalInfo.Count()) { // Only set the character directions if there is right to left characters. Vector& directions = mModel->mLogicalModel->mCharacterDirections; - GetCharactersDirection( bidirectionalInfo, - numberOfCharacters, - startIndex, - requestedNumberOfCharacters, - directions ); + GetCharactersDirection(bidirectionalInfo, + numberOfCharacters, + startIndex, + requestedNumberOfCharacters, + directions); // This paragraph has right to left text. Some characters may need to be mirrored. // TODO: consider if the mirrored string can be stored as well. - textMirrored = GetMirroredText( utf32Characters, - directions, - bidirectionalInfo, - startIndex, - requestedNumberOfCharacters, - mirroredUtf32Characters ); + textMirrored = GetMirroredText(utf32Characters, + directions, + bidirectionalInfo, + startIndex, + requestedNumberOfCharacters, + mirroredUtf32Characters); } else { @@ -785,172 +781,172 @@ bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) updated = true; } - Vector& glyphs = mModel->mVisualModel->mGlyphs; + Vector& glyphs = mModel->mVisualModel->mGlyphs; Vector& glyphsToCharactersMap = mModel->mVisualModel->mGlyphsToCharacters; - Vector& charactersPerGlyph = mModel->mVisualModel->mCharactersPerGlyph; - Vector newParagraphGlyphs; - newParagraphGlyphs.Reserve( numberOfParagraphs ); + Vector& charactersPerGlyph = mModel->mVisualModel->mCharactersPerGlyph; + Vector newParagraphGlyphs; + newParagraphGlyphs.Reserve(numberOfParagraphs); const Length currentNumberOfGlyphs = glyphs.Count(); - if( NO_OPERATION != ( SHAPE_TEXT & operations ) ) + if(NO_OPERATION != (SHAPE_TEXT & operations)) { const Vector& textToShape = textMirrored ? mirroredUtf32Characters : utf32Characters; // Shapes the text. - ShapeText( textToShape, - lineBreakInfo, - scripts, - validFonts, - startIndex, - mTextUpdateInfo.mStartGlyphIndex, - requestedNumberOfCharacters, - glyphs, - glyphsToCharactersMap, - charactersPerGlyph, - newParagraphGlyphs ); + ShapeText(textToShape, + lineBreakInfo, + scripts, + validFonts, + startIndex, + mTextUpdateInfo.mStartGlyphIndex, + requestedNumberOfCharacters, + glyphs, + glyphsToCharactersMap, + charactersPerGlyph, + newParagraphGlyphs); // Create the 'number of glyphs' per character and the glyph to character conversion tables. - mModel->mVisualModel->CreateGlyphsPerCharacterTable( startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters ); - mModel->mVisualModel->CreateCharacterToGlyphTable( startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters ); + mModel->mVisualModel->CreateGlyphsPerCharacterTable(startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters); + mModel->mVisualModel->CreateCharacterToGlyphTable(startIndex, mTextUpdateInfo.mStartGlyphIndex, requestedNumberOfCharacters); updated = true; } const Length numberOfGlyphs = glyphs.Count() - currentNumberOfGlyphs; - if( NO_OPERATION != ( GET_GLYPH_METRICS & operations ) ) + if(NO_OPERATION != (GET_GLYPH_METRICS & operations)) { GlyphInfo* glyphsBuffer = glyphs.Begin(); - mMetrics->GetGlyphMetrics( glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex, numberOfGlyphs ); + mMetrics->GetGlyphMetrics(glyphsBuffer + mTextUpdateInfo.mStartGlyphIndex, numberOfGlyphs); // Update the width and advance of all new paragraph characters. - for( Vector::ConstIterator it = newParagraphGlyphs.Begin(), endIt = newParagraphGlyphs.End(); it != endIt; ++it ) + for(Vector::ConstIterator it = newParagraphGlyphs.Begin(), endIt = newParagraphGlyphs.End(); it != endIt; ++it) { const GlyphIndex index = *it; - GlyphInfo& glyph = *( glyphsBuffer + index ); + GlyphInfo& glyph = *(glyphsBuffer + index); glyph.xBearing = 0.f; - glyph.width = 0.f; - glyph.advance = 0.f; + glyph.width = 0.f; + glyph.advance = 0.f; } updated = true; } - if( ( NULL != mEventData ) && - mEventData->mPreEditFlag && - ( 0u != mModel->mVisualModel->mCharactersToGlyph.Count() ) ) + if((NULL != mEventData) && + mEventData->mPreEditFlag && + (0u != mModel->mVisualModel->mCharactersToGlyph.Count())) { Dali::InputMethodContext::PreEditAttributeDataContainer attrs; - mEventData->mInputMethodContext.GetPreeditStyle( attrs ); + mEventData->mInputMethodContext.GetPreeditStyle(attrs); Dali::InputMethodContext::PreeditStyle type = Dali::InputMethodContext::PreeditStyle::NONE; // Check the type of preedit and run it. - for( Dali::InputMethodContext::PreEditAttributeDataContainer::Iterator it = attrs.Begin(), endIt = attrs.End(); it != endIt; it++ ) + for(Dali::InputMethodContext::PreEditAttributeDataContainer::Iterator it = attrs.Begin(), endIt = attrs.End(); it != endIt; it++) { Dali::InputMethodContext::PreeditAttributeData attrData = *it; - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::UpdateModel PreeditStyle type : %d start %d end %d \n", attrData.preeditType, attrData.startIndex, attrData.endIndex ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::UpdateModel PreeditStyle type : %d start %d end %d \n", attrData.preeditType, attrData.startIndex, attrData.endIndex); type = attrData.preeditType; // Check the number of commit characters for the start position. - unsigned int numberOfCommit = mEventData->mPrimaryCursorPosition - mEventData->mPreEditLength; - Length numberOfIndices = attrData.endIndex - attrData.startIndex; + unsigned int numberOfCommit = mEventData->mPrimaryCursorPosition - mEventData->mPreEditLength; + Length numberOfIndices = attrData.endIndex - attrData.startIndex; - switch( type ) + switch(type) { case Dali::InputMethodContext::PreeditStyle::UNDERLINE: { // Add the underline for the pre-edit text. GlyphRun underlineRun; - underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; + underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; underlineRun.numberOfGlyphs = numberOfIndices; - mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun ); + mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun); break; } case Dali::InputMethodContext::PreeditStyle::REVERSE: { - Vector4 textColor = mModel->mVisualModel->GetTextColor(); + Vector4 textColor = mModel->mVisualModel->GetTextColor(); ColorRun backgroundColorRun; - backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices; - backgroundColorRun.color = textColor; - mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun ); - - Vector4 backgroundColor = mModel->mVisualModel->GetBackgroundColor(); - Vector colorRuns; - colorRuns.Resize( 1u ); - ColorRun& colorRun = *( colorRuns.Begin() ); - colorRun.color = backgroundColor; - colorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.color = textColor; + mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun); + + Vector4 backgroundColor = mModel->mVisualModel->GetBackgroundColor(); + Vector colorRuns; + colorRuns.Resize(1u); + ColorRun& colorRun = *(colorRuns.Begin()); + colorRun.color = backgroundColor; + colorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; colorRun.characterRun.numberOfCharacters = numberOfIndices; - mModel->mLogicalModel->mColorRuns.PushBack( colorRun ); + mModel->mLogicalModel->mColorRuns.PushBack(colorRun); break; } case Dali::InputMethodContext::PreeditStyle::HIGHLIGHT: { ColorRun backgroundColorRun; - backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices; - backgroundColorRun.color = LIGHT_BLUE; - mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun ); + backgroundColorRun.color = LIGHT_BLUE; + mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun); break; } case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_1: { // CUSTOM_PLATFORM_STYLE_1 should be drawn with background and underline together. ColorRun backgroundColorRun; - backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices; - backgroundColorRun.color = BACKGROUND_SUB4; - mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun ); + backgroundColorRun.color = BACKGROUND_SUB4; + mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun); GlyphRun underlineRun; - underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; + underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; underlineRun.numberOfGlyphs = numberOfIndices; - mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun ); + mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun); break; } case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_2: { // CUSTOM_PLATFORM_STYLE_2 should be drawn with background and underline together. ColorRun backgroundColorRun; - backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices; - backgroundColorRun.color = BACKGROUND_SUB5; - mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun ); + backgroundColorRun.color = BACKGROUND_SUB5; + mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun); GlyphRun underlineRun; - underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; + underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; underlineRun.numberOfGlyphs = numberOfIndices; - mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun ); + mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun); break; } case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_3: { // CUSTOM_PLATFORM_STYLE_3 should be drawn with background and underline together. ColorRun backgroundColorRun; - backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices; - backgroundColorRun.color = BACKGROUND_SUB6; - mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun ); + backgroundColorRun.color = BACKGROUND_SUB6; + mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun); GlyphRun underlineRun; - underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; + underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; underlineRun.numberOfGlyphs = numberOfIndices; - mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun ); + mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun); break; } case Dali::InputMethodContext::PreeditStyle::CUSTOM_PLATFORM_STYLE_4: { // CUSTOM_PLATFORM_STYLE_4 should be drawn with background and underline together. ColorRun backgroundColorRun; - backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; + backgroundColorRun.characterRun.characterIndex = attrData.startIndex + numberOfCommit; backgroundColorRun.characterRun.numberOfCharacters = numberOfIndices; - backgroundColorRun.color = BACKGROUND_SUB7; - mModel->mLogicalModel->mBackgroundColorRuns.PushBack( backgroundColorRun ); + backgroundColorRun.color = BACKGROUND_SUB7; + mModel->mLogicalModel->mBackgroundColorRuns.PushBack(backgroundColorRun); GlyphRun underlineRun; - underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; + underlineRun.glyphIndex = attrData.startIndex + numberOfCommit; underlineRun.numberOfGlyphs = numberOfIndices; - mModel->mVisualModel->mUnderlineRuns.PushBack( underlineRun ); + mModel->mVisualModel->mUnderlineRuns.PushBack(underlineRun); break; } case Dali::InputMethodContext::PreeditStyle::NONE: @@ -964,34 +960,33 @@ bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) updated = true; } - if( NO_OPERATION != ( COLOR & operations ) ) + if(NO_OPERATION != (COLOR & operations)) { // Set the color runs in glyphs. - SetColorSegmentationInfo( mModel->mLogicalModel->mColorRuns, - mModel->mVisualModel->mCharactersToGlyph, - mModel->mVisualModel->mGlyphsPerCharacter, - startIndex, - mTextUpdateInfo.mStartGlyphIndex, - requestedNumberOfCharacters, - mModel->mVisualModel->mColors, - mModel->mVisualModel->mColorIndices ); + SetColorSegmentationInfo(mModel->mLogicalModel->mColorRuns, + mModel->mVisualModel->mCharactersToGlyph, + mModel->mVisualModel->mGlyphsPerCharacter, + startIndex, + mTextUpdateInfo.mStartGlyphIndex, + requestedNumberOfCharacters, + mModel->mVisualModel->mColors, + mModel->mVisualModel->mColorIndices); // Set the background color runs in glyphs. - SetColorSegmentationInfo( mModel->mLogicalModel->mBackgroundColorRuns, - mModel->mVisualModel->mCharactersToGlyph, - mModel->mVisualModel->mGlyphsPerCharacter, - startIndex, - mTextUpdateInfo.mStartGlyphIndex, - requestedNumberOfCharacters, - mModel->mVisualModel->mBackgroundColors, - mModel->mVisualModel->mBackgroundColorIndices ); + SetColorSegmentationInfo(mModel->mLogicalModel->mBackgroundColorRuns, + mModel->mVisualModel->mCharactersToGlyph, + mModel->mVisualModel->mGlyphsPerCharacter, + startIndex, + mTextUpdateInfo.mStartGlyphIndex, + requestedNumberOfCharacters, + mModel->mVisualModel->mBackgroundColors, + mModel->mVisualModel->mBackgroundColorIndices); updated = true; } - // The estimated number of lines. Used to avoid reallocations when layouting. - mTextUpdateInfo.mEstimatedNumberOfLines = std::max( mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count() ); + mTextUpdateInfo.mEstimatedNumberOfLines = std::max(mModel->mVisualModel->mLines.Count(), mModel->mLogicalModel->mParagraphInfo.Count()); // Set the previous number of characters for the next time the text is updated. mTextUpdateInfo.mPreviousNumberOfCharacters = numberOfCharacters; @@ -999,17 +994,17 @@ bool Controller::Impl::UpdateModel( OperationsMask operationsRequired ) return updated; } -void Controller::Impl::RetrieveDefaultInputStyle( InputStyle& inputStyle ) +void Controller::Impl::RetrieveDefaultInputStyle(InputStyle& inputStyle) { // Sets the default text's color. - inputStyle.textColor = mTextColor; + inputStyle.textColor = mTextColor; inputStyle.isDefaultColor = true; inputStyle.familyName.clear(); inputStyle.weight = TextAbstraction::FontWeight::NORMAL; - inputStyle.width = TextAbstraction::FontWidth::NORMAL; - inputStyle.slant = TextAbstraction::FontSlant::NORMAL; - inputStyle.size = 0.f; + inputStyle.width = TextAbstraction::FontWidth::NORMAL; + inputStyle.slant = TextAbstraction::FontSlant::NORMAL; + inputStyle.size = 0.f; inputStyle.lineSpacing = 0.f; @@ -1020,47 +1015,47 @@ void Controller::Impl::RetrieveDefaultInputStyle( InputStyle& inputStyle ) inputStyle.isFamilyDefined = false; inputStyle.isWeightDefined = false; - inputStyle.isWidthDefined = false; - inputStyle.isSlantDefined = false; - inputStyle.isSizeDefined = false; + inputStyle.isWidthDefined = false; + inputStyle.isSlantDefined = false; + inputStyle.isSizeDefined = false; inputStyle.isLineSpacingDefined = false; inputStyle.isUnderlineDefined = false; - inputStyle.isShadowDefined = false; - inputStyle.isEmbossDefined = false; - inputStyle.isOutlineDefined = false; + inputStyle.isShadowDefined = false; + inputStyle.isEmbossDefined = false; + inputStyle.isOutlineDefined = false; // Sets the default font's family name, weight, width, slant and size. - if( mFontDefaults ) + if(mFontDefaults) { - if( mFontDefaults->familyDefined ) + if(mFontDefaults->familyDefined) { - inputStyle.familyName = mFontDefaults->mFontDescription.family; + inputStyle.familyName = mFontDefaults->mFontDescription.family; inputStyle.isFamilyDefined = true; } - if( mFontDefaults->weightDefined ) + if(mFontDefaults->weightDefined) { - inputStyle.weight = mFontDefaults->mFontDescription.weight; + inputStyle.weight = mFontDefaults->mFontDescription.weight; inputStyle.isWeightDefined = true; } - if( mFontDefaults->widthDefined ) + if(mFontDefaults->widthDefined) { - inputStyle.width = mFontDefaults->mFontDescription.width; + inputStyle.width = mFontDefaults->mFontDescription.width; inputStyle.isWidthDefined = true; } - if( mFontDefaults->slantDefined ) + if(mFontDefaults->slantDefined) { - inputStyle.slant = mFontDefaults->mFontDescription.slant; + inputStyle.slant = mFontDefaults->mFontDescription.slant; inputStyle.isSlantDefined = true; } - if( mFontDefaults->sizeDefined ) + if(mFontDefaults->sizeDefined) { - inputStyle.size = mFontDefaults->mDefaultPointSize; + inputStyle.size = mFontDefaults->mDefaultPointSize; inputStyle.isSizeDefined = true; } } @@ -1069,54 +1064,54 @@ void Controller::Impl::RetrieveDefaultInputStyle( InputStyle& inputStyle ) float Controller::Impl::GetDefaultFontLineHeight() { FontId defaultFontId = 0u; - if( NULL == mFontDefaults ) + if(NULL == mFontDefaults) { TextAbstraction::FontDescription fontDescription; - defaultFontId = mFontClient.GetFontId( fontDescription, TextAbstraction::FontClient::DEFAULT_POINT_SIZE * mFontSizeScale ); + defaultFontId = mFontClient.GetFontId(fontDescription, TextAbstraction::FontClient::DEFAULT_POINT_SIZE * mFontSizeScale); } else { - defaultFontId = mFontDefaults->GetFontId( mFontClient, mFontDefaults->mDefaultPointSize * mFontSizeScale ); + defaultFontId = mFontDefaults->GetFontId(mFontClient, mFontDefaults->mDefaultPointSize * mFontSizeScale); } Text::FontMetrics fontMetrics; - mMetrics->GetFontMetrics( defaultFontId, fontMetrics ); + mMetrics->GetFontMetrics(defaultFontId, fontMetrics); - return( fontMetrics.ascender - fontMetrics.descender ); + return (fontMetrics.ascender - fontMetrics.descender); } -void Controller::Impl::SetTextSelectionRange(const uint32_t *pStart, const uint32_t *pEnd) +void Controller::Impl::SetTextSelectionRange(const uint32_t* pStart, const uint32_t* pEnd) { - if( nullptr == mEventData ) + if(nullptr == mEventData) { // Nothing to do if there is no text. return; } - if( mEventData->mSelectionEnabled && (pStart || pEnd)) + if(mEventData->mSelectionEnabled && (pStart || pEnd)) { uint32_t length = static_cast(mModel->mLogicalModel->mText.Count()); - if (pStart) + if(pStart) { mEventData->mLeftSelectionPosition = std::min(*pStart, length); } - if (pEnd) + if(pEnd) { mEventData->mRightSelectionPosition = std::min(*pEnd, length); } - if (mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition) + if(mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition) { - ChangeState( EventData::EDITING ); + ChangeState(EventData::EDITING); mEventData->mPrimaryCursorPosition = mEventData->mLeftSelectionPosition = mEventData->mRightSelectionPosition; - mEventData->mUpdateCursorPosition = true; + mEventData->mUpdateCursorPosition = true; } else { - ChangeState( EventData::SELECTING ); - mEventData->mUpdateHighlightBox = true; - mEventData->mUpdateLeftSelectionPosition = true; + ChangeState(EventData::SELECTING); + mEventData->mUpdateHighlightBox = true; + mEventData->mUpdateLeftSelectionPosition = true; mEventData->mUpdateRightSelectionPosition = true; } } @@ -1124,32 +1119,32 @@ void Controller::Impl::SetTextSelectionRange(const uint32_t *pStart, const uint3 CharacterIndex Controller::Impl::GetPrimaryCursorPosition() const { - if( nullptr == mEventData ) + if(nullptr == mEventData) { return 0; } return mEventData->mPrimaryCursorPosition; } -bool Controller::Impl::SetPrimaryCursorPosition( CharacterIndex index ) +bool Controller::Impl::SetPrimaryCursorPosition(CharacterIndex index) { - if( nullptr == mEventData ) + if(nullptr == mEventData) { // Nothing to do if there is no text. return false; } - if( mEventData->mPrimaryCursorPosition == index ) + if(mEventData->mPrimaryCursorPosition == index) { // Nothing for same cursor position. return false; } - uint32_t length = static_cast(mModel->mLogicalModel->mText.Count()); + uint32_t length = static_cast(mModel->mLogicalModel->mText.Count()); mEventData->mPrimaryCursorPosition = std::min(index, length); - ChangeState( EventData::EDITING ); + ChangeState(EventData::EDITING); mEventData->mLeftSelectionPosition = mEventData->mRightSelectionPosition = mEventData->mPrimaryCursorPosition; - mEventData->mUpdateCursorPosition = true; + mEventData->mUpdateCursorPosition = true; ScrollTextToMatchCursor(); return true; } @@ -1158,9 +1153,9 @@ Uint32Pair Controller::Impl::GetTextSelectionRange() const { Uint32Pair range; - if( mEventData ) + if(mEventData) { - range.first = mEventData->mLeftSelectionPosition; + range.first = mEventData->mLeftSelectionPosition; range.second = mEventData->mRightSelectionPosition; } @@ -1172,17 +1167,17 @@ bool Controller::Impl::IsEditable() const return mEventData && mEventData->mEditingEnabled; } -void Controller::Impl::SetEditable( bool editable ) +void Controller::Impl::SetEditable(bool editable) { - if( mEventData) + if(mEventData) { mEventData->mEditingEnabled = editable; } } -void Controller::Impl::RetrieveSelection( std::string& selectedText, bool deleteAfterRetrieval ) +void Controller::Impl::RetrieveSelection(std::string& selectedText, bool deleteAfterRetrieval) { - if( mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition ) + if(mEventData->mLeftSelectionPosition == mEventData->mRightSelectionPosition) { // Nothing to select if handles are in the same place. selectedText.clear(); @@ -1192,57 +1187,57 @@ void Controller::Impl::RetrieveSelection( std::string& selectedText, bool delete const bool handlesCrossed = mEventData->mLeftSelectionPosition > mEventData->mRightSelectionPosition; //Get start and end position of selection - const CharacterIndex startOfSelectedText = handlesCrossed ? mEventData->mRightSelectionPosition : mEventData->mLeftSelectionPosition; - const Length lengthOfSelectedText = ( handlesCrossed ? mEventData->mLeftSelectionPosition : mEventData->mRightSelectionPosition ) - startOfSelectedText; + const CharacterIndex startOfSelectedText = handlesCrossed ? mEventData->mRightSelectionPosition : mEventData->mLeftSelectionPosition; + const Length lengthOfSelectedText = (handlesCrossed ? mEventData->mLeftSelectionPosition : mEventData->mRightSelectionPosition) - startOfSelectedText; - Vector& utf32Characters = mModel->mLogicalModel->mText; - const Length numberOfCharacters = utf32Characters.Count(); + Vector& utf32Characters = mModel->mLogicalModel->mText; + const Length numberOfCharacters = utf32Characters.Count(); // Validate the start and end selection points - if( ( startOfSelectedText + lengthOfSelectedText ) <= numberOfCharacters ) + if((startOfSelectedText + lengthOfSelectedText) <= numberOfCharacters) { //Get text as a UTF8 string - Utf32ToUtf8( &utf32Characters[startOfSelectedText], lengthOfSelectedText, selectedText ); + Utf32ToUtf8(&utf32Characters[startOfSelectedText], lengthOfSelectedText, selectedText); - if( deleteAfterRetrieval ) // Only delete text if copied successfully + if(deleteAfterRetrieval) // Only delete text if copied successfully { // Keep a copy of the current input style. InputStyle currentInputStyle; - currentInputStyle.Copy( mEventData->mInputStyle ); + currentInputStyle.Copy(mEventData->mInputStyle); // Set as input style the style of the first deleted character. - mModel->mLogicalModel->RetrieveStyle( startOfSelectedText, mEventData->mInputStyle ); + mModel->mLogicalModel->RetrieveStyle(startOfSelectedText, mEventData->mInputStyle); // Compare if the input style has changed. - const bool hasInputStyleChanged = !currentInputStyle.Equal( mEventData->mInputStyle ); + const bool hasInputStyleChanged = !currentInputStyle.Equal(mEventData->mInputStyle); - if( hasInputStyleChanged ) + if(hasInputStyleChanged) { - const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( mEventData->mInputStyle ); + const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(mEventData->mInputStyle); // Queue the input style changed signal. - mEventData->mInputStyleChangedQueue.PushBack( styleChangedMask ); + mEventData->mInputStyleChangedQueue.PushBack(styleChangedMask); } - mModel->mLogicalModel->UpdateTextStyleRuns( startOfSelectedText, -static_cast( lengthOfSelectedText ) ); + mModel->mLogicalModel->UpdateTextStyleRuns(startOfSelectedText, -static_cast(lengthOfSelectedText)); // Mark the paragraphs to be updated. - if( Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout() ) + if(Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout()) { - mTextUpdateInfo.mCharacterIndex = 0; + mTextUpdateInfo.mCharacterIndex = 0; mTextUpdateInfo.mNumberOfCharactersToRemove = mTextUpdateInfo.mPreviousNumberOfCharacters; - mTextUpdateInfo.mNumberOfCharactersToAdd = mTextUpdateInfo.mPreviousNumberOfCharacters - lengthOfSelectedText; - mTextUpdateInfo.mClearAll = true; + mTextUpdateInfo.mNumberOfCharactersToAdd = mTextUpdateInfo.mPreviousNumberOfCharacters - lengthOfSelectedText; + mTextUpdateInfo.mClearAll = true; } else { - mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + mTextUpdateInfo.mCharacterIndex = startOfSelectedText; mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; } // Delete text between handles Vector::Iterator first = utf32Characters.Begin() + startOfSelectedText; Vector::Iterator last = first + lengthOfSelectedText; - utf32Characters.Erase( first, last ); + utf32Characters.Erase(first, last); // Will show the cursor at the first character of the selection. mEventData->mPrimaryCursorPosition = handlesCrossed ? mEventData->mRightSelectionPosition : mEventData->mLeftSelectionPosition; @@ -1257,21 +1252,21 @@ void Controller::Impl::RetrieveSelection( std::string& selectedText, bool delete } } -void Controller::Impl::SetSelection( int start, int end ) +void Controller::Impl::SetSelection(int start, int end) { - mEventData->mLeftSelectionPosition = start; + mEventData->mLeftSelectionPosition = start; mEventData->mRightSelectionPosition = end; - mEventData->mUpdateCursorPosition = true; + mEventData->mUpdateCursorPosition = true; } -std::pair< int, int > Controller::Impl::GetSelectionIndexes() const +std::pair Controller::Impl::GetSelectionIndexes() const { - return { mEventData->mLeftSelectionPosition, mEventData->mRightSelectionPosition }; + return {mEventData->mLeftSelectionPosition, mEventData->mRightSelectionPosition}; } void Controller::Impl::ShowClipboard() { - if( mClipboard ) + if(mClipboard) { mClipboard.ShowClipboard(); } @@ -1279,7 +1274,7 @@ void Controller::Impl::ShowClipboard() void Controller::Impl::HideClipboard() { - if( mClipboard && mClipboardHideEnabled ) + if(mClipboard && mClipboardHideEnabled) { mClipboard.HideClipboard(); } @@ -1290,23 +1285,23 @@ void Controller::Impl::SetClipboardHideEnable(bool enable) mClipboardHideEnabled = enable; } -bool Controller::Impl::CopyStringToClipboard( const std::string& source ) +bool Controller::Impl::CopyStringToClipboard(const std::string& source) { //Send string to clipboard - return ( mClipboard && mClipboard.SetItem( source ) ); + return (mClipboard && mClipboard.SetItem(source)); } -void Controller::Impl::SendSelectionToClipboard( bool deleteAfterSending ) +void Controller::Impl::SendSelectionToClipboard(bool deleteAfterSending) { std::string selectedText; - RetrieveSelection( selectedText, deleteAfterSending ); - CopyStringToClipboard( selectedText ); - ChangeState( EventData::EDITING ); + RetrieveSelection(selectedText, deleteAfterSending); + CopyStringToClipboard(selectedText); + ChangeState(EventData::EDITING); } void Controller::Impl::RequestGetTextFromClipboard() { - if ( mClipboard ) + if(mClipboard) { mClipboard.RequestItem(); } @@ -1316,7 +1311,7 @@ void Controller::Impl::RepositionSelectionHandles() { SelectionHandleController::Reposition(*this); } -void Controller::Impl::RepositionSelectionHandles( float visualX, float visualY, Controller::NoTextTap::Action action ) +void Controller::Impl::RepositionSelectionHandles(float visualX, float visualY, Controller::NoTextTap::Action action) { SelectionHandleController::Reposition(*this, visualX, visualY, action); } @@ -1331,273 +1326,273 @@ void Controller::Impl::SetPopupButtons() * If EDITING_WITH_POPUP : SELECT & SELECT_ALL */ - bool isEditable = IsEditable(); + bool isEditable = IsEditable(); TextSelectionPopup::Buttons buttonsToShow = TextSelectionPopup::NONE; - if( EventData::SELECTING == mEventData->mState ) + if(EventData::SELECTING == mEventData->mState) { - buttonsToShow = TextSelectionPopup::Buttons( TextSelectionPopup::COPY ); + buttonsToShow = TextSelectionPopup::Buttons(TextSelectionPopup::COPY); if(isEditable) { - buttonsToShow = TextSelectionPopup::Buttons( buttonsToShow | TextSelectionPopup::CUT ); + buttonsToShow = TextSelectionPopup::Buttons(buttonsToShow | TextSelectionPopup::CUT); } - if( !IsClipboardEmpty() ) + if(!IsClipboardEmpty()) { if(isEditable) { - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::PASTE ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::PASTE)); } - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::CLIPBOARD ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::CLIPBOARD)); } - if( !mEventData->mAllTextSelected ) + if(!mEventData->mAllTextSelected) { - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::SELECT_ALL ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::SELECT_ALL)); } } - else if( EventData::EDITING_WITH_POPUP == mEventData->mState ) + else if(EventData::EDITING_WITH_POPUP == mEventData->mState) { - if( mModel->mLogicalModel->mText.Count() && !IsShowingPlaceholderText() ) + if(mModel->mLogicalModel->mText.Count() && !IsShowingPlaceholderText()) { - buttonsToShow = TextSelectionPopup::Buttons( TextSelectionPopup::SELECT | TextSelectionPopup::SELECT_ALL ); + buttonsToShow = TextSelectionPopup::Buttons(TextSelectionPopup::SELECT | TextSelectionPopup::SELECT_ALL); } - if( !IsClipboardEmpty() ) + if(!IsClipboardEmpty()) { if(isEditable) { - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::PASTE ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::PASTE)); } - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::CLIPBOARD ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::CLIPBOARD)); } } - else if( EventData::EDITING_WITH_PASTE_POPUP == mEventData->mState ) + else if(EventData::EDITING_WITH_PASTE_POPUP == mEventData->mState) { - if ( !IsClipboardEmpty() ) + if(!IsClipboardEmpty()) { if(isEditable) { - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::PASTE ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::PASTE)); } - buttonsToShow = TextSelectionPopup::Buttons ( ( buttonsToShow | TextSelectionPopup::CLIPBOARD ) ); + buttonsToShow = TextSelectionPopup::Buttons((buttonsToShow | TextSelectionPopup::CLIPBOARD)); } } - mEventData->mDecorator->SetEnabledPopupButtons( buttonsToShow ); + mEventData->mDecorator->SetEnabledPopupButtons(buttonsToShow); } -void Controller::Impl::ChangeState( EventData::State newState ) +void Controller::Impl::ChangeState(EventData::State newState) { - if( NULL == mEventData ) + if(NULL == mEventData) { // Nothing to do if there is no text input. return; } - DALI_LOG_INFO( gLogFilter, Debug::General, "ChangeState state:%d newstate:%d\n", mEventData->mState, newState ); + DALI_LOG_INFO(gLogFilter, Debug::General, "ChangeState state:%d newstate:%d\n", mEventData->mState, newState); - if( mEventData->mState != newState ) + if(mEventData->mState != newState) { mEventData->mPreviousState = mEventData->mState; - mEventData->mState = newState; + mEventData->mState = newState; - switch( mEventData->mState ) + switch(mEventData->mState) { case EventData::INACTIVE: { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE); mEventData->mDecorator->StopCursorBlink(); - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); + mEventData->mDecorator->SetPopupActive(false); mEventData->mDecoratorUpdated = true; break; } case EventData::INTERRUPTED: { - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); + mEventData->mDecorator->SetPopupActive(false); mEventData->mDecoratorUpdated = true; break; } case EventData::SELECTING: { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE); mEventData->mDecorator->StopCursorBlink(); - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); - if ( mEventData->mGrabHandleEnabled ) + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false); + if(mEventData->mGrabHandleEnabled) { - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, true ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, true ); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, true); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, true); } - mEventData->mDecorator->SetHighlightActive( true ); - if( mEventData->mGrabHandlePopupEnabled ) + mEventData->mDecorator->SetHighlightActive(true); + if(mEventData->mGrabHandlePopupEnabled) { SetPopupButtons(); - mEventData->mDecorator->SetPopupActive( true ); + mEventData->mDecorator->SetPopupActive(true); } mEventData->mDecoratorUpdated = true; break; } case EventData::EDITING: { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mEventData->mCursorBlinkEnabled ) + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY); + if(mEventData->mCursorBlinkEnabled) { mEventData->mDecorator->StartCursorBlink(); } // Grab handle is not shown until a tap is received whilst EDITING - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); - if( mEventData->mGrabHandlePopupEnabled ) + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); + if(mEventData->mGrabHandlePopupEnabled) { - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetPopupActive(false); } mEventData->mDecoratorUpdated = true; break; } case EventData::EDITING_WITH_POPUP: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "EDITING_WITH_POPUP \n", newState ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "EDITING_WITH_POPUP \n", newState); - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mEventData->mCursorBlinkEnabled ) + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY); + if(mEventData->mCursorBlinkEnabled) { mEventData->mDecorator->StartCursorBlink(); } - if( mEventData->mSelectionEnabled ) + if(mEventData->mSelectionEnabled) { - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); } - else if ( mEventData->mGrabHandleEnabled ) + else if(mEventData->mGrabHandleEnabled) { - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true ); + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true); } - if( mEventData->mGrabHandlePopupEnabled ) + if(mEventData->mGrabHandlePopupEnabled) { SetPopupButtons(); - mEventData->mDecorator->SetPopupActive( true ); + mEventData->mDecorator->SetPopupActive(true); } mEventData->mDecoratorUpdated = true; break; } case EventData::EDITING_WITH_GRAB_HANDLE: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "EDITING_WITH_GRAB_HANDLE \n", newState ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "EDITING_WITH_GRAB_HANDLE \n", newState); - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mEventData->mCursorBlinkEnabled ) + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY); + if(mEventData->mCursorBlinkEnabled) { mEventData->mDecorator->StartCursorBlink(); } // Grab handle is not shown until a tap is received whilst EDITING - if ( mEventData->mGrabHandleEnabled ) + if(mEventData->mGrabHandleEnabled) { - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true ); + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true); } - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); - if( mEventData->mGrabHandlePopupEnabled ) + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); + if(mEventData->mGrabHandlePopupEnabled) { - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetPopupActive(false); } mEventData->mDecoratorUpdated = true; break; } case EventData::SELECTION_HANDLE_PANNING: { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE); mEventData->mDecorator->StopCursorBlink(); - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); - if ( mEventData->mGrabHandleEnabled ) + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false); + if(mEventData->mGrabHandleEnabled) { - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, true ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, true ); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, true); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, true); } - mEventData->mDecorator->SetHighlightActive( true ); - if( mEventData->mGrabHandlePopupEnabled ) + mEventData->mDecorator->SetHighlightActive(true); + if(mEventData->mGrabHandlePopupEnabled) { - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetPopupActive(false); } mEventData->mDecoratorUpdated = true; break; } case EventData::GRAB_HANDLE_PANNING: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "GRAB_HANDLE_PANNING \n", newState ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "GRAB_HANDLE_PANNING \n", newState); - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mEventData->mCursorBlinkEnabled ) + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY); + if(mEventData->mCursorBlinkEnabled) { mEventData->mDecorator->StartCursorBlink(); } - if ( mEventData->mGrabHandleEnabled ) + if(mEventData->mGrabHandleEnabled) { - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true ); + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true); } - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); - if( mEventData->mGrabHandlePopupEnabled ) + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); + if(mEventData->mGrabHandlePopupEnabled) { - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetPopupActive(false); } mEventData->mDecoratorUpdated = true; break; } case EventData::EDITING_WITH_PASTE_POPUP: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "EDITING_WITH_PASTE_POPUP \n", newState ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "EDITING_WITH_PASTE_POPUP \n", newState); - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); - if( mEventData->mCursorBlinkEnabled ) + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY); + if(mEventData->mCursorBlinkEnabled) { mEventData->mDecorator->StartCursorBlink(); } - if ( mEventData->mGrabHandleEnabled ) + if(mEventData->mGrabHandleEnabled) { - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, true ); + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, true); } - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( false ); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(false); - if( mEventData->mGrabHandlePopupEnabled ) + if(mEventData->mGrabHandlePopupEnabled) { SetPopupButtons(); - mEventData->mDecorator->SetPopupActive( true ); + mEventData->mDecorator->SetPopupActive(true); } mEventData->mDecoratorUpdated = true; break; } case EventData::TEXT_PANNING: { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE); mEventData->mDecorator->StopCursorBlink(); - mEventData->mDecorator->SetHandleActive( GRAB_HANDLE, false ); - if( mEventData->mDecorator->IsHandleActive( LEFT_SELECTION_HANDLE ) || - mEventData->mDecorator->IsHandleActive( RIGHT_SELECTION_HANDLE ) ) + mEventData->mDecorator->SetHandleActive(GRAB_HANDLE, false); + if(mEventData->mDecorator->IsHandleActive(LEFT_SELECTION_HANDLE) || + mEventData->mDecorator->IsHandleActive(RIGHT_SELECTION_HANDLE)) { - mEventData->mDecorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); - mEventData->mDecorator->SetHighlightActive( true ); + mEventData->mDecorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); + mEventData->mDecorator->SetHighlightActive(true); } - if( mEventData->mGrabHandlePopupEnabled ) + if(mEventData->mGrabHandlePopupEnabled) { - mEventData->mDecorator->SetPopupActive( false ); + mEventData->mDecorator->SetPopupActive(false); } mEventData->mDecoratorUpdated = true; @@ -1607,10 +1602,10 @@ void Controller::Impl::ChangeState( EventData::State newState ) } } -void Controller::Impl::GetCursorPosition( CharacterIndex logical, - CursorInfo& cursorInfo ) +void Controller::Impl::GetCursorPosition(CharacterIndex logical, + CursorInfo& cursorInfo) { - if( !IsShowingRealText() ) + if(!IsShowingRealText()) { // Do not want to use the place-holder text to set the cursor position. @@ -1618,21 +1613,21 @@ void Controller::Impl::GetCursorPosition( CharacterIndex logical, // If there is no font's family set, use the default font. // Use the current alignment to place the cursor at the beginning, center or end of the box. - cursorInfo.lineOffset = 0.f; - cursorInfo.lineHeight = GetDefaultFontLineHeight(); + cursorInfo.lineOffset = 0.f; + cursorInfo.lineHeight = GetDefaultFontLineHeight(); cursorInfo.primaryCursorHeight = cursorInfo.lineHeight; bool isRTL = false; - if( mModel->mMatchSystemLanguageDirection ) + if(mModel->mMatchSystemLanguageDirection) { isRTL = mLayoutDirection == LayoutDirection::RIGHT_TO_LEFT; } - switch( mModel->mHorizontalAlignment ) + switch(mModel->mHorizontalAlignment) { - case Text::HorizontalAlignment::BEGIN : + case Text::HorizontalAlignment::BEGIN: { - if( isRTL ) + if(isRTL) { cursorInfo.primaryPosition.x = mModel->mVisualModel->mControlSize.width - mEventData->mDecorator->GetCursorWidth(); } @@ -1644,12 +1639,12 @@ void Controller::Impl::GetCursorPosition( CharacterIndex logical, } case Text::HorizontalAlignment::CENTER: { - cursorInfo.primaryPosition.x = floorf( 0.5f * mModel->mVisualModel->mControlSize.width ); + cursorInfo.primaryPosition.x = floorf(0.5f * mModel->mVisualModel->mControlSize.width); break; } case Text::HorizontalAlignment::END: { - if( isRTL ) + if(isRTL) { cursorInfo.primaryPosition.x = 0.f; } @@ -1665,47 +1660,47 @@ void Controller::Impl::GetCursorPosition( CharacterIndex logical, return; } - const bool isMultiLine = ( Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout() ); + const bool isMultiLine = (Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout()); GetCursorPositionParameters parameters; - parameters.visualModel = mModel->mVisualModel; + parameters.visualModel = mModel->mVisualModel; parameters.logicalModel = mModel->mLogicalModel; - parameters.metrics = mMetrics; - parameters.logical = logical; - parameters.isMultiline = isMultiLine; + parameters.metrics = mMetrics; + parameters.logical = logical; + parameters.isMultiline = isMultiLine; - Text::GetCursorPosition( parameters, - cursorInfo ); + Text::GetCursorPosition(parameters, + cursorInfo); // Adds Outline offset. - const float outlineWidth = static_cast( mModel->GetOutlineWidth() ); + const float outlineWidth = static_cast(mModel->GetOutlineWidth()); cursorInfo.primaryPosition.x += outlineWidth; cursorInfo.primaryPosition.y += outlineWidth; cursorInfo.secondaryPosition.x += outlineWidth; cursorInfo.secondaryPosition.y += outlineWidth; - if( isMultiLine ) + if(isMultiLine) { // If the text is editable and multi-line, the cursor position after a white space shouldn't exceed the boundaries of the text control. // Note the white spaces laid-out at the end of the line might exceed the boundaries of the control. // The reason is a wrapped line must not start with a white space so they are laid-out at the end of the line. - if( 0.f > cursorInfo.primaryPosition.x ) + if(0.f > cursorInfo.primaryPosition.x) { cursorInfo.primaryPosition.x = 0.f; } - const float edgeWidth = mModel->mVisualModel->mControlSize.width - static_cast( mEventData->mDecorator->GetCursorWidth() ); - if( cursorInfo.primaryPosition.x > edgeWidth ) + const float edgeWidth = mModel->mVisualModel->mControlSize.width - static_cast(mEventData->mDecorator->GetCursorWidth()); + if(cursorInfo.primaryPosition.x > edgeWidth) { cursorInfo.primaryPosition.x = edgeWidth; } } } -CharacterIndex Controller::Impl::CalculateNewCursorIndex( CharacterIndex index ) const +CharacterIndex Controller::Impl::CalculateNewCursorIndex(CharacterIndex index) const { - if( NULL == mEventData ) + if(NULL == mEventData) { // Nothing to do if there is no text input. return 0u; @@ -1713,16 +1708,16 @@ CharacterIndex Controller::Impl::CalculateNewCursorIndex( CharacterIndex index ) CharacterIndex cursorIndex = mEventData->mPrimaryCursorPosition; - const GlyphIndex* const charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin(); - const Length* const charactersPerGlyphBuffer = mModel->mVisualModel->mCharactersPerGlyph.Begin(); + const GlyphIndex* const charactersToGlyphBuffer = mModel->mVisualModel->mCharactersToGlyph.Begin(); + const Length* const charactersPerGlyphBuffer = mModel->mVisualModel->mCharactersPerGlyph.Begin(); - GlyphIndex glyphIndex = *( charactersToGlyphBuffer + index ); - Length numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex ); + GlyphIndex glyphIndex = *(charactersToGlyphBuffer + index); + Length numberOfCharacters = *(charactersPerGlyphBuffer + glyphIndex); - if( numberOfCharacters > 1u ) + if(numberOfCharacters > 1u) { - const Script script = mModel->mLogicalModel->GetScript( index ); - if( HasLigatureMustBreak( script ) ) + const Script script = mModel->mLogicalModel->GetScript(index); + if(HasLigatureMustBreak(script)) { // Prevents to jump the whole Latin ligatures like fi, ff, or Arabic ï»», ... numberOfCharacters = 1u; @@ -1730,14 +1725,14 @@ CharacterIndex Controller::Impl::CalculateNewCursorIndex( CharacterIndex index ) } else { - while( 0u == numberOfCharacters ) + while(0u == numberOfCharacters) { ++glyphIndex; - numberOfCharacters = *( charactersPerGlyphBuffer + glyphIndex ); + numberOfCharacters = *(charactersPerGlyphBuffer + glyphIndex); } } - if( index < mEventData->mPrimaryCursorPosition ) + if(index < mEventData->mPrimaryCursorPosition) { cursorIndex -= numberOfCharacters; } @@ -1752,82 +1747,82 @@ CharacterIndex Controller::Impl::CalculateNewCursorIndex( CharacterIndex index ) return cursorIndex; } -void Controller::Impl::UpdateCursorPosition( const CursorInfo& cursorInfo ) +void Controller::Impl::UpdateCursorPosition(const CursorInfo& cursorInfo) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::UpdateCursorPosition %p\n", this ); - if( NULL == mEventData ) + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::UpdateCursorPosition %p\n", this); + if(NULL == mEventData) { // Nothing to do if there is no text input. - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition no event data\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition no event data\n"); return; } const Vector2 cursorPosition = cursorInfo.primaryPosition + mModel->mScrollPosition; - mEventData->mDecorator->SetGlyphOffset( PRIMARY_CURSOR, cursorInfo.glyphOffset ); + mEventData->mDecorator->SetGlyphOffset(PRIMARY_CURSOR, cursorInfo.glyphOffset); // Sets the cursor position. - mEventData->mDecorator->SetPosition( PRIMARY_CURSOR, - cursorPosition.x, - cursorPosition.y, - cursorInfo.primaryCursorHeight, - cursorInfo.lineHeight ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Primary cursor position: %f,%f\n", cursorPosition.x, cursorPosition.y ); + mEventData->mDecorator->SetPosition(PRIMARY_CURSOR, + cursorPosition.x, + cursorPosition.y, + cursorInfo.primaryCursorHeight, + cursorInfo.lineHeight); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Primary cursor position: %f,%f\n", cursorPosition.x, cursorPosition.y); - if( mEventData->mUpdateGrabHandlePosition ) + if(mEventData->mUpdateGrabHandlePosition) { // Sets the grab handle position. - mEventData->mDecorator->SetPosition( GRAB_HANDLE, - cursorPosition.x, - cursorInfo.lineOffset + mModel->mScrollPosition.y, - cursorInfo.lineHeight ); + mEventData->mDecorator->SetPosition(GRAB_HANDLE, + cursorPosition.x, + cursorInfo.lineOffset + mModel->mScrollPosition.y, + cursorInfo.lineHeight); } - if( cursorInfo.isSecondaryCursor ) + if(cursorInfo.isSecondaryCursor) { - mEventData->mDecorator->SetPosition( SECONDARY_CURSOR, - cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x, - cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y, - cursorInfo.secondaryCursorHeight, - cursorInfo.lineHeight ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Secondary cursor position: %f,%f\n", cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x, cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y ); + mEventData->mDecorator->SetPosition(SECONDARY_CURSOR, + cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x, + cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y, + cursorInfo.secondaryCursorHeight, + cursorInfo.lineHeight); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Secondary cursor position: %f,%f\n", cursorInfo.secondaryPosition.x + mModel->mScrollPosition.x, cursorInfo.secondaryPosition.y + mModel->mScrollPosition.y); } // Set which cursors are active according the state. - if( EventData::IsEditingState( mEventData->mState ) || ( EventData::GRAB_HANDLE_PANNING == mEventData->mState ) ) + if(EventData::IsEditingState(mEventData->mState) || (EventData::GRAB_HANDLE_PANNING == mEventData->mState)) { - if( cursorInfo.isSecondaryCursor ) + if(cursorInfo.isSecondaryCursor) { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_BOTH ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_BOTH); } else { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_PRIMARY ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_PRIMARY); } } else { - mEventData->mDecorator->SetActiveCursor( ACTIVE_CURSOR_NONE ); + mEventData->mDecorator->SetActiveCursor(ACTIVE_CURSOR_NONE); } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::UpdateCursorPosition\n"); } -void Controller::Impl::UpdateSelectionHandle( HandleType handleType, - const CursorInfo& cursorInfo ) +void Controller::Impl::UpdateSelectionHandle(HandleType handleType, + const CursorInfo& cursorInfo) { SelectionHandleController::Update(*this, handleType, cursorInfo); } -void Controller::Impl::ClampHorizontalScroll( const Vector2& layoutSize ) +void Controller::Impl::ClampHorizontalScroll(const Vector2& layoutSize) { // Clamp between -space & -alignment offset. - if( layoutSize.width > mModel->mVisualModel->mControlSize.width ) + if(layoutSize.width > mModel->mVisualModel->mControlSize.width) { - const float space = ( layoutSize.width - mModel->mVisualModel->mControlSize.width ) + mModel->mAlignmentOffset; - mModel->mScrollPosition.x = ( mModel->mScrollPosition.x < -space ) ? -space : mModel->mScrollPosition.x; - mModel->mScrollPosition.x = ( mModel->mScrollPosition.x > -mModel->mAlignmentOffset ) ? -mModel->mAlignmentOffset : mModel->mScrollPosition.x; + const float space = (layoutSize.width - mModel->mVisualModel->mControlSize.width) + mModel->mAlignmentOffset; + mModel->mScrollPosition.x = (mModel->mScrollPosition.x < -space) ? -space : mModel->mScrollPosition.x; + mModel->mScrollPosition.x = (mModel->mScrollPosition.x > -mModel->mAlignmentOffset) ? -mModel->mAlignmentOffset : mModel->mScrollPosition.x; mEventData->mDecoratorUpdated = true; } @@ -1837,20 +1832,20 @@ void Controller::Impl::ClampHorizontalScroll( const Vector2& layoutSize ) } } -void Controller::Impl::ClampVerticalScroll( const Vector2& layoutSize ) +void Controller::Impl::ClampVerticalScroll(const Vector2& layoutSize) { - if( Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout() ) + if(Layout::Engine::SINGLE_LINE_BOX == mLayoutEngine.GetLayout()) { // Nothing to do if the text is single line. return; } // Clamp between -space & 0. - if( layoutSize.height > mModel->mVisualModel->mControlSize.height ) + if(layoutSize.height > mModel->mVisualModel->mControlSize.height) { - const float space = ( layoutSize.height - mModel->mVisualModel->mControlSize.height ); - mModel->mScrollPosition.y = ( mModel->mScrollPosition.y < -space ) ? -space : mModel->mScrollPosition.y; - mModel->mScrollPosition.y = ( mModel->mScrollPosition.y > 0.f ) ? 0.f : mModel->mScrollPosition.y; + const float space = (layoutSize.height - mModel->mVisualModel->mControlSize.height); + mModel->mScrollPosition.y = (mModel->mScrollPosition.y < -space) ? -space : mModel->mScrollPosition.y; + mModel->mScrollPosition.y = (mModel->mScrollPosition.y > 0.f) ? 0.f : mModel->mScrollPosition.y; mEventData->mDecoratorUpdated = true; } @@ -1860,9 +1855,9 @@ void Controller::Impl::ClampVerticalScroll( const Vector2& layoutSize ) } } -void Controller::Impl::ScrollToMakePositionVisible( const Vector2& position, float lineHeight ) +void Controller::Impl::ScrollToMakePositionVisible(const Vector2& position, float lineHeight) { - const float cursorWidth = mEventData->mDecorator ? static_cast( mEventData->mDecorator->GetCursorWidth() ) : 0.f; + const float cursorWidth = mEventData->mDecorator ? static_cast(mEventData->mDecorator->GetCursorWidth()) : 0.f; // position is in actor's coords. const float positionEndX = position.x + cursorWidth; @@ -1870,70 +1865,67 @@ void Controller::Impl::ScrollToMakePositionVisible( const Vector2& position, flo // Transform the position to decorator coords. const float decoratorPositionBeginX = position.x + mModel->mScrollPosition.x; - const float decoratorPositionEndX = positionEndX + mModel->mScrollPosition.x; + const float decoratorPositionEndX = positionEndX + mModel->mScrollPosition.x; const float decoratorPositionBeginY = position.y + mModel->mScrollPosition.y; - const float decoratorPositionEndY = positionEndY + mModel->mScrollPosition.y; + const float decoratorPositionEndY = positionEndY + mModel->mScrollPosition.y; - if( decoratorPositionBeginX < 0.f ) + if(decoratorPositionBeginX < 0.f) { mModel->mScrollPosition.x = -position.x; } - else if( decoratorPositionEndX > mModel->mVisualModel->mControlSize.width ) + else if(decoratorPositionEndX > mModel->mVisualModel->mControlSize.width) { mModel->mScrollPosition.x = mModel->mVisualModel->mControlSize.width - positionEndX; } - if( Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout() ) + if(Layout::Engine::MULTI_LINE_BOX == mLayoutEngine.GetLayout()) { - if( decoratorPositionBeginY < 0.f ) + if(decoratorPositionBeginY < 0.f) { mModel->mScrollPosition.y = -position.y; } - else if( decoratorPositionEndY > mModel->mVisualModel->mControlSize.height ) + else if(decoratorPositionEndY > mModel->mVisualModel->mControlSize.height) { mModel->mScrollPosition.y = mModel->mVisualModel->mControlSize.height - positionEndY; } } } -void Controller::Impl::ScrollTextToMatchCursor( const CursorInfo& cursorInfo ) +void Controller::Impl::ScrollTextToMatchCursor(const CursorInfo& cursorInfo) { // Get the current cursor position in decorator coords. - const Vector2& currentCursorPosition = mEventData->mDecorator->GetPosition( PRIMARY_CURSOR ); - - const LineIndex lineIndex = mModel->mVisualModel->GetLineOfCharacter( mEventData->mPrimaryCursorPosition ); - + const Vector2& currentCursorPosition = mEventData->mDecorator->GetPosition(PRIMARY_CURSOR); + const LineIndex lineIndex = mModel->mVisualModel->GetLineOfCharacter(mEventData->mPrimaryCursorPosition); // Calculate the offset to match the cursor position before the character was deleted. mModel->mScrollPosition.x = currentCursorPosition.x - cursorInfo.primaryPosition.x; //If text control has more than two lines and current line index is not last, calculate scrollpositionY - if( mModel->mVisualModel->mLines.Count() > 1u && lineIndex != mModel->mVisualModel->mLines.Count() -1u ) + if(mModel->mVisualModel->mLines.Count() > 1u && lineIndex != mModel->mVisualModel->mLines.Count() - 1u) { - const float currentCursorGlyphOffset = mEventData->mDecorator->GetGlyphOffset( PRIMARY_CURSOR ); - mModel->mScrollPosition.y = currentCursorPosition.y - cursorInfo.lineOffset - currentCursorGlyphOffset; + const float currentCursorGlyphOffset = mEventData->mDecorator->GetGlyphOffset(PRIMARY_CURSOR); + mModel->mScrollPosition.y = currentCursorPosition.y - cursorInfo.lineOffset - currentCursorGlyphOffset; } - - ClampHorizontalScroll( mModel->mVisualModel->GetLayoutSize() ); - ClampVerticalScroll( mModel->mVisualModel->GetLayoutSize() ); + ClampHorizontalScroll(mModel->mVisualModel->GetLayoutSize()); + ClampVerticalScroll(mModel->mVisualModel->GetLayoutSize()); // Makes the new cursor position visible if needed. - ScrollToMakePositionVisible( cursorInfo.primaryPosition, cursorInfo.lineHeight ); + ScrollToMakePositionVisible(cursorInfo.primaryPosition, cursorInfo.lineHeight); } void Controller::Impl::ScrollTextToMatchCursor() { CursorInfo cursorInfo; - GetCursorPosition( mEventData->mPrimaryCursorPosition, cursorInfo ); + GetCursorPosition(mEventData->mPrimaryCursorPosition, cursorInfo); ScrollTextToMatchCursor(cursorInfo); } void Controller::Impl::RequestRelayout() { - if( NULL != mControlInterface ) + if(NULL != mControlInterface) { mControlInterface->RequestTextRelayout(); } @@ -1947,78 +1939,78 @@ Actor Controller::Impl::CreateBackgroundActor() Actor actor; Length numberOfGlyphs = mView.GetNumberOfGlyphs(); - if( numberOfGlyphs > 0u ) + if(numberOfGlyphs > 0u) { Vector glyphs; - glyphs.Resize( numberOfGlyphs ); + glyphs.Resize(numberOfGlyphs); Vector positions; - positions.Resize( numberOfGlyphs ); + positions.Resize(numberOfGlyphs); // Get the line where the glyphs are laid-out. - const LineRun* lineRun = mModel->mVisualModel->mLines.Begin(); - float alignmentOffset = lineRun->alignmentOffset; - numberOfGlyphs = mView.GetGlyphs( glyphs.Begin(), - positions.Begin(), - alignmentOffset, - 0u, - numberOfGlyphs ); + const LineRun* lineRun = mModel->mVisualModel->mLines.Begin(); + float alignmentOffset = lineRun->alignmentOffset; + numberOfGlyphs = mView.GetGlyphs(glyphs.Begin(), + positions.Begin(), + alignmentOffset, + 0u, + numberOfGlyphs); - glyphs.Resize( numberOfGlyphs ); - positions.Resize( numberOfGlyphs ); + glyphs.Resize(numberOfGlyphs); + positions.Resize(numberOfGlyphs); - const GlyphInfo* const glyphsBuffer = glyphs.Begin(); - const Vector2* const positionsBuffer = positions.Begin(); + const GlyphInfo* const glyphsBuffer = glyphs.Begin(); + const Vector2* const positionsBuffer = positions.Begin(); BackgroundMesh mesh; - mesh.mVertices.Reserve( 4u * glyphs.Size() ); - mesh.mIndices.Reserve( 6u * glyphs.Size() ); + mesh.mVertices.Reserve(4u * glyphs.Size()); + mesh.mIndices.Reserve(6u * glyphs.Size()); const Vector2 textSize = mView.GetLayoutSize(); const float offsetX = textSize.width * 0.5f; const float offsetY = textSize.height * 0.5f; - const Vector4* const backgroundColorsBuffer = mView.GetBackgroundColors(); + const Vector4* const backgroundColorsBuffer = mView.GetBackgroundColors(); const ColorIndex* const backgroundColorIndicesBuffer = mView.GetBackgroundColorIndices(); - const Vector4& defaultBackgroundColor = mModel->mVisualModel->IsBackgroundEnabled() ? mModel->mVisualModel->GetBackgroundColor() : Color::TRANSPARENT; + const Vector4& defaultBackgroundColor = mModel->mVisualModel->IsBackgroundEnabled() ? mModel->mVisualModel->GetBackgroundColor() : Color::TRANSPARENT; - Vector4 quad; + Vector4 quad; uint32_t numberOfQuads = 0u; - for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i ) + for(uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i) { - const GlyphInfo& glyph = *( glyphsBuffer + i ); + const GlyphInfo& glyph = *(glyphsBuffer + i); // Get the background color of the character. // The color index zero is reserved for the default background color (i.e. Color::TRANSPARENT) - const ColorIndex backgroundColorIndex = ( nullptr == backgroundColorsBuffer ) ? 0u : *( backgroundColorIndicesBuffer + i ); - const Vector4& backgroundColor = ( 0u == backgroundColorIndex ) ? defaultBackgroundColor : *( backgroundColorsBuffer + backgroundColorIndex - 1u ); + const ColorIndex backgroundColorIndex = (nullptr == backgroundColorsBuffer) ? 0u : *(backgroundColorIndicesBuffer + i); + const Vector4& backgroundColor = (0u == backgroundColorIndex) ? defaultBackgroundColor : *(backgroundColorsBuffer + backgroundColorIndex - 1u); // Only create quads for glyphs with a background color - if ( backgroundColor != Color::TRANSPARENT ) + if(backgroundColor != Color::TRANSPARENT) { - const Vector2 position = *( positionsBuffer + i ); + const Vector2 position = *(positionsBuffer + i); - if ( i == 0u && glyphSize == 1u ) // Only one glyph in the whole text + if(i == 0u && glyphSize == 1u) // Only one glyph in the whole text { quad.x = position.x; quad.y = 0.0f; - quad.z = quad.x + std::max( glyph.advance, glyph.xBearing + glyph.width ); + quad.z = quad.x + std::max(glyph.advance, glyph.xBearing + glyph.width); quad.w = textSize.height; } - else if ( i == 0u ) // The first glyph in the whole text + else if(i == 0u) // The first glyph in the whole text { quad.x = position.x; quad.y = 0.0f; quad.z = quad.x - glyph.xBearing + glyph.advance; quad.w = textSize.height; } - else if ( i == glyphSize - 1u ) // The last glyph in the whole text + else if(i == glyphSize - 1u) // The last glyph in the whole text { quad.x = position.x - glyph.xBearing; quad.y = 0.0f; - quad.z = quad.x + std::max( glyph.advance, glyph.xBearing + glyph.width ); + quad.z = quad.x + std::max(glyph.advance, glyph.xBearing + glyph.width); quad.w = textSize.height; } else // The glyph in the middle of the text @@ -2034,69 +2026,69 @@ Actor Controller::Impl::CreateBackgroundActor() // Top left vertex.mPosition.x = quad.x - offsetX; vertex.mPosition.y = quad.y - offsetY; - vertex.mColor = backgroundColor; - mesh.mVertices.PushBack( vertex ); + vertex.mColor = backgroundColor; + mesh.mVertices.PushBack(vertex); // Top right vertex.mPosition.x = quad.z - offsetX; vertex.mPosition.y = quad.y - offsetY; - vertex.mColor = backgroundColor; - mesh.mVertices.PushBack( vertex ); + vertex.mColor = backgroundColor; + mesh.mVertices.PushBack(vertex); // Bottom left vertex.mPosition.x = quad.x - offsetX; vertex.mPosition.y = quad.w - offsetY; - vertex.mColor = backgroundColor; - mesh.mVertices.PushBack( vertex ); + vertex.mColor = backgroundColor; + mesh.mVertices.PushBack(vertex); // Bottom right vertex.mPosition.x = quad.z - offsetX; vertex.mPosition.y = quad.w - offsetY; - vertex.mColor = backgroundColor; - mesh.mVertices.PushBack( vertex ); + vertex.mColor = backgroundColor; + mesh.mVertices.PushBack(vertex); // Six indices in counter clockwise winding - mesh.mIndices.PushBack( 1u + 4 * numberOfQuads ); - mesh.mIndices.PushBack( 0u + 4 * numberOfQuads ); - mesh.mIndices.PushBack( 2u + 4 * numberOfQuads ); - mesh.mIndices.PushBack( 2u + 4 * numberOfQuads ); - mesh.mIndices.PushBack( 3u + 4 * numberOfQuads ); - mesh.mIndices.PushBack( 1u + 4 * numberOfQuads ); + mesh.mIndices.PushBack(1u + 4 * numberOfQuads); + mesh.mIndices.PushBack(0u + 4 * numberOfQuads); + mesh.mIndices.PushBack(2u + 4 * numberOfQuads); + mesh.mIndices.PushBack(2u + 4 * numberOfQuads); + mesh.mIndices.PushBack(3u + 4 * numberOfQuads); + mesh.mIndices.PushBack(1u + 4 * numberOfQuads); numberOfQuads++; } } // Only create the background actor if there are glyphs with background color - if ( mesh.mVertices.Count() > 0u ) + if(mesh.mVertices.Count() > 0u) { Property::Map quadVertexFormat; - quadVertexFormat[ "aPosition" ] = Property::VECTOR2; - quadVertexFormat[ "aColor" ] = Property::VECTOR4; + quadVertexFormat["aPosition"] = Property::VECTOR2; + quadVertexFormat["aColor"] = Property::VECTOR4; - VertexBuffer quadVertices = VertexBuffer::New( quadVertexFormat ); - quadVertices.SetData( &mesh.mVertices[ 0 ], mesh.mVertices.Size() ); + VertexBuffer quadVertices = VertexBuffer::New(quadVertexFormat); + quadVertices.SetData(&mesh.mVertices[0], mesh.mVertices.Size()); Geometry quadGeometry = Geometry::New(); - quadGeometry.AddVertexBuffer( quadVertices ); - quadGeometry.SetIndexBuffer( &mesh.mIndices[ 0 ], mesh.mIndices.Size() ); + quadGeometry.AddVertexBuffer(quadVertices); + quadGeometry.SetIndexBuffer(&mesh.mIndices[0], mesh.mIndices.Size()); - if( !mShaderBackground ) + if(!mShaderBackground) { - mShaderBackground = Shader::New( SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_VERT, SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_FRAG ); + mShaderBackground = Shader::New(SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_VERT, SHADER_TEXT_CONTROLLER_BACKGROUND_SHADER_FRAG); } - Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, mShaderBackground ); - renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON ); - renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT ); + Dali::Renderer renderer = Dali::Renderer::New(quadGeometry, mShaderBackground); + renderer.SetProperty(Dali::Renderer::Property::BLEND_MODE, BlendMode::ON); + renderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT); actor = Actor::New(); - actor.SetProperty( Dali::Actor::Property::NAME, "TextBackgroundColorActor" ); - actor.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT ); - actor.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT ); - actor.SetProperty( Actor::Property::SIZE, textSize ); - actor.SetProperty( Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR ); - actor.AddRenderer( renderer ); + actor.SetProperty(Dali::Actor::Property::NAME, "TextBackgroundColorActor"); + actor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_LEFT); + actor.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_LEFT); + actor.SetProperty(Actor::Property::SIZE, textSize); + actor.SetProperty(Actor::Property::COLOR_MODE, USE_OWN_MULTIPLY_PARENT_COLOR); + actor.AddRenderer(renderer); } } diff --git a/dali-toolkit/internal/text/text-controller-input-font-handler.cpp b/dali-toolkit/internal/text/text-controller-input-font-handler.cpp index 3eb74a1..8a3ac3e 100644 --- a/dali-toolkit/internal/text/text-controller-input-font-handler.cpp +++ b/dali-toolkit/internal/text/text-controller-input-font-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. @@ -26,16 +26,12 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { - /** * @brief Adds a new font description run for the selected text. * @@ -46,30 +42,30 @@ namespace * @param[out] startOfSelectedText Index to the first selected character. * @param[out] lengthOfSelectedText Number of selected characters. */ -FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData, - LogicalModelPtr logicalModel, - CharacterIndex& startOfSelectedText, - Length& lengthOfSelectedText ) +FontDescriptionRun& UpdateSelectionFontStyleRun(EventData* eventData, + LogicalModelPtr logicalModel, + CharacterIndex& startOfSelectedText, + Length& lengthOfSelectedText) { const bool handlesCrossed = eventData->mLeftSelectionPosition > eventData->mRightSelectionPosition; // Get start and end position of selection - startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition; - lengthOfSelectedText = ( handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition ) - startOfSelectedText; + startOfSelectedText = handlesCrossed ? eventData->mRightSelectionPosition : eventData->mLeftSelectionPosition; + lengthOfSelectedText = (handlesCrossed ? eventData->mLeftSelectionPosition : eventData->mRightSelectionPosition) - startOfSelectedText; // Add the font run. const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count(); - logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u ); + logicalModel->mFontDescriptionRuns.Resize(numberOfRuns + 1u); - FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns ); + FontDescriptionRun& fontDescriptionRun = *(logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns); - fontDescriptionRun.characterRun.characterIndex = startOfSelectedText; + fontDescriptionRun.characterRun.characterIndex = startOfSelectedText; fontDescriptionRun.characterRun.numberOfCharacters = lengthOfSelectedText; // Recalculate the selection highlight as the metrics may have changed. - eventData->mUpdateLeftSelectionPosition = true; + eventData->mUpdateLeftSelectionPosition = true; eventData->mUpdateRightSelectionPosition = true; - eventData->mUpdateHighlightBox = true; + eventData->mUpdateHighlightBox = true; return fontDescriptionRun; } @@ -78,66 +74,66 @@ FontDescriptionRun& UpdateSelectionFontStyleRun( EventData* eventData, void Controller::InputFontHandler::SetInputFontFamily(Controller& controller, const std::string& fontFamily) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - controller.mImpl->mEventData->mInputStyle.familyName = fontFamily; + controller.mImpl->mEventData->mInputStyle.familyName = fontFamily; controller.mImpl->mEventData->mInputStyle.isFamilyDefined = true; - if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState) { - CharacterIndex startOfSelectedText = 0u; - Length lengthOfSelectedText = 0u; + CharacterIndex startOfSelectedText = 0u; + Length lengthOfSelectedText = 0u; - if( EventData::SELECTING == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState) { // Update a font description run for the selecting state. - FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData, - controller.mImpl->mModel->mLogicalModel, - startOfSelectedText, - lengthOfSelectedText ); + FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData, + controller.mImpl->mModel->mLogicalModel, + startOfSelectedText, + lengthOfSelectedText); fontDescriptionRun.familyLength = fontFamily.size(); - fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength]; - memcpy( fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength ); + fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength]; + memcpy(fontDescriptionRun.familyName, fontFamily.c_str(), fontDescriptionRun.familyLength); fontDescriptionRun.familyDefined = true; // The memory allocated for the font family name is freed when the font description is removed from the logical model. - controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; } else { - controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); } // Request to relayout. - controller.mImpl->mOperationsPending = static_cast( controller.mImpl->mOperationsPending | - VALIDATE_FONTS | - SHAPE_TEXT | - GET_GLYPH_METRICS | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER | - ALIGN ); + controller.mImpl->mOperationsPending = static_cast(controller.mImpl->mOperationsPending | + VALIDATE_FONTS | + SHAPE_TEXT | + GET_GLYPH_METRICS | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER | + ALIGN); controller.mImpl->mRecalculateNaturalSize = true; controller.mImpl->RequestRelayout(); // As the font changes, recalculate the handle positions is needed. - controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; + controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; controller.mImpl->mEventData->mUpdateRightSelectionPosition = true; - controller.mImpl->mEventData->mUpdateHighlightBox = true; - controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; + controller.mImpl->mEventData->mUpdateHighlightBox = true; + controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; } } } const std::string& Controller::InputFontHandler::GetInputFontFamily(const Controller& controller) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { return controller.mImpl->mEventData->mInputStyle.familyName; } @@ -148,55 +144,55 @@ const std::string& Controller::InputFontHandler::GetInputFontFamily(const Contro void Controller::InputFontHandler::SetInputFontWeight(const Controller& controller, FontWeight weight) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - controller.mImpl->mEventData->mInputStyle.weight = weight; + controller.mImpl->mEventData->mInputStyle.weight = weight; controller.mImpl->mEventData->mInputStyle.isWeightDefined = true; - if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState) { - CharacterIndex startOfSelectedText = 0u; - Length lengthOfSelectedText = 0u; + CharacterIndex startOfSelectedText = 0u; + Length lengthOfSelectedText = 0u; - if( EventData::SELECTING == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState) { // Update a font description run for the selecting state. - FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData, - controller.mImpl->mModel->mLogicalModel, - startOfSelectedText, - lengthOfSelectedText ); + FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData, + controller.mImpl->mModel->mLogicalModel, + startOfSelectedText, + lengthOfSelectedText); - fontDescriptionRun.weight = weight; + fontDescriptionRun.weight = weight; fontDescriptionRun.weightDefined = true; - controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; } else { - controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); } // Request to relayout. - controller.mImpl->mOperationsPending = static_cast( controller.mImpl->mOperationsPending | - VALIDATE_FONTS | - SHAPE_TEXT | - GET_GLYPH_METRICS | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER | - ALIGN ); + controller.mImpl->mOperationsPending = static_cast(controller.mImpl->mOperationsPending | + VALIDATE_FONTS | + SHAPE_TEXT | + GET_GLYPH_METRICS | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER | + ALIGN); controller.mImpl->mRecalculateNaturalSize = true; controller.mImpl->RequestRelayout(); // As the font might change, recalculate the handle positions is needed. - controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; + controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; controller.mImpl->mEventData->mUpdateRightSelectionPosition = true; - controller.mImpl->mEventData->mUpdateHighlightBox = true; - controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; + controller.mImpl->mEventData->mUpdateHighlightBox = true; + controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; } } } @@ -205,7 +201,7 @@ bool Controller::InputFontHandler::IsInputFontWeightDefined(const Controller& co { bool defined = false; - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { defined = controller.mImpl->mEventData->mInputStyle.isWeightDefined; } @@ -215,7 +211,7 @@ bool Controller::InputFontHandler::IsInputFontWeightDefined(const Controller& co FontWeight Controller::InputFontHandler::GetInputFontWeight(const Controller& controller) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { return controller.mImpl->mEventData->mInputStyle.weight; } @@ -225,55 +221,55 @@ FontWeight Controller::InputFontHandler::GetInputFontWeight(const Controller& co void Controller::InputFontHandler::SetInputFontWidth(Controller& controller, FontWidth width) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - controller.mImpl->mEventData->mInputStyle.width = width; + controller.mImpl->mEventData->mInputStyle.width = width; controller.mImpl->mEventData->mInputStyle.isWidthDefined = true; - if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState) { - CharacterIndex startOfSelectedText = 0u; - Length lengthOfSelectedText = 0u; + CharacterIndex startOfSelectedText = 0u; + Length lengthOfSelectedText = 0u; - if( EventData::SELECTING == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState) { // Update a font description run for the selecting state. - FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData, - controller.mImpl->mModel->mLogicalModel, - startOfSelectedText, - lengthOfSelectedText ); + FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData, + controller.mImpl->mModel->mLogicalModel, + startOfSelectedText, + lengthOfSelectedText); - fontDescriptionRun.width = width; + fontDescriptionRun.width = width; fontDescriptionRun.widthDefined = true; - controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; } else { - controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); } // Request to relayout. - controller.mImpl->mOperationsPending = static_cast( controller.mImpl->mOperationsPending | - VALIDATE_FONTS | - SHAPE_TEXT | - GET_GLYPH_METRICS | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER | - ALIGN ); + controller.mImpl->mOperationsPending = static_cast(controller.mImpl->mOperationsPending | + VALIDATE_FONTS | + SHAPE_TEXT | + GET_GLYPH_METRICS | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER | + ALIGN); controller.mImpl->mRecalculateNaturalSize = true; controller.mImpl->RequestRelayout(); // As the font might change, recalculate the handle positions is needed. - controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; + controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; controller.mImpl->mEventData->mUpdateRightSelectionPosition = true; - controller.mImpl->mEventData->mUpdateHighlightBox = true; - controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; + controller.mImpl->mEventData->mUpdateHighlightBox = true; + controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; } } } @@ -282,7 +278,7 @@ bool Controller::InputFontHandler::IsInputFontWidthDefined(const Controller& con { bool defined = false; - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { defined = controller.mImpl->mEventData->mInputStyle.isWidthDefined; } @@ -292,7 +288,7 @@ bool Controller::InputFontHandler::IsInputFontWidthDefined(const Controller& con FontWidth Controller::InputFontHandler::GetInputFontWidth(const Controller& controller) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { return controller.mImpl->mEventData->mInputStyle.width; } @@ -302,55 +298,55 @@ FontWidth Controller::InputFontHandler::GetInputFontWidth(const Controller& cont void Controller::InputFontHandler::SetInputFontSlant(Controller& controller, FontSlant slant) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - controller.mImpl->mEventData->mInputStyle.slant = slant; + controller.mImpl->mEventData->mInputStyle.slant = slant; controller.mImpl->mEventData->mInputStyle.isSlantDefined = true; - if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState) { - CharacterIndex startOfSelectedText = 0u; - Length lengthOfSelectedText = 0u; + CharacterIndex startOfSelectedText = 0u; + Length lengthOfSelectedText = 0u; - if( EventData::SELECTING == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState) { // Update a font description run for the selecting state. - FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData, - controller.mImpl->mModel->mLogicalModel, - startOfSelectedText, - lengthOfSelectedText ); + FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData, + controller.mImpl->mModel->mLogicalModel, + startOfSelectedText, + lengthOfSelectedText); - fontDescriptionRun.slant = slant; + fontDescriptionRun.slant = slant; fontDescriptionRun.slantDefined = true; - controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; } else { - controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); } // Request to relayout. - controller.mImpl->mOperationsPending = static_cast( controller.mImpl->mOperationsPending | - VALIDATE_FONTS | - SHAPE_TEXT | - GET_GLYPH_METRICS | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER | - ALIGN ); + controller.mImpl->mOperationsPending = static_cast(controller.mImpl->mOperationsPending | + VALIDATE_FONTS | + SHAPE_TEXT | + GET_GLYPH_METRICS | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER | + ALIGN); controller.mImpl->mRecalculateNaturalSize = true; controller.mImpl->RequestRelayout(); // As the font might change, recalculate the handle positions is needed. - controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; + controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; controller.mImpl->mEventData->mUpdateRightSelectionPosition = true; - controller.mImpl->mEventData->mUpdateHighlightBox = true; - controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; + controller.mImpl->mEventData->mUpdateHighlightBox = true; + controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; } } } @@ -359,7 +355,7 @@ bool Controller::InputFontHandler::IsInputFontSlantDefined(const Controller& con { bool defined = false; - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { defined = controller.mImpl->mEventData->mInputStyle.isSlantDefined; } @@ -369,7 +365,7 @@ bool Controller::InputFontHandler::IsInputFontSlantDefined(const Controller& con FontSlant Controller::InputFontHandler::GetInputFontSlant(const Controller& controller) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { return controller.mImpl->mEventData->mInputStyle.slant; } @@ -379,68 +375,68 @@ FontSlant Controller::InputFontHandler::GetInputFontSlant(const Controller& cont void Controller::InputFontHandler::SetInputFontPointSize(Controller& controller, float size) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - controller.mImpl->mEventData->mInputStyle.size = size; + controller.mImpl->mEventData->mInputStyle.size = size; controller.mImpl->mEventData->mInputStyle.isSizeDefined = true; - if( EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState || EventData::EDITING == controller.mImpl->mEventData->mState || EventData::INACTIVE == controller.mImpl->mEventData->mState) { - CharacterIndex startOfSelectedText = 0u; - Length lengthOfSelectedText = 0u; + CharacterIndex startOfSelectedText = 0u; + Length lengthOfSelectedText = 0u; - if( EventData::SELECTING == controller.mImpl->mEventData->mState ) + if(EventData::SELECTING == controller.mImpl->mEventData->mState) { // Update a font description run for the selecting state. - FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun( controller.mImpl->mEventData, - controller.mImpl->mModel->mLogicalModel, - startOfSelectedText, - lengthOfSelectedText ); + FontDescriptionRun& fontDescriptionRun = UpdateSelectionFontStyleRun(controller.mImpl->mEventData, + controller.mImpl->mModel->mLogicalModel, + startOfSelectedText, + lengthOfSelectedText); - fontDescriptionRun.size = static_cast( size * controller.mImpl->mFontSizeScale * 64.f ); + fontDescriptionRun.size = static_cast(size * controller.mImpl->mFontSizeScale * 64.f); fontDescriptionRun.sizeDefined = true; - controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; } else { - controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; + controller.mImpl->mTextUpdateInfo.mCharacterIndex = 0; controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = controller.mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); + controller.mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = controller.mImpl->mModel->mLogicalModel->mText.Count(); } // Request to relayout. - controller.mImpl->mOperationsPending = static_cast( controller.mImpl->mOperationsPending | - VALIDATE_FONTS | - SHAPE_TEXT | - GET_GLYPH_METRICS | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER | - ALIGN ); + controller.mImpl->mOperationsPending = static_cast(controller.mImpl->mOperationsPending | + VALIDATE_FONTS | + SHAPE_TEXT | + GET_GLYPH_METRICS | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER | + ALIGN); controller.mImpl->mRecalculateNaturalSize = true; controller.mImpl->RequestRelayout(); // As the font might change, recalculate the handle positions is needed. - controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; + controller.mImpl->mEventData->mUpdateLeftSelectionPosition = true; controller.mImpl->mEventData->mUpdateRightSelectionPosition = true; - controller.mImpl->mEventData->mUpdateHighlightBox = true; - controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; + controller.mImpl->mEventData->mUpdateHighlightBox = true; + controller.mImpl->mEventData->mScrollAfterUpdatePosition = true; } } } float Controller::InputFontHandler::GetInputFontPointSize(const Controller& controller) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { return controller.mImpl->mEventData->mInputStyle.size; } // Return the default font's point size if there is no EventData. - return controller.GetDefaultFontSize( Text::Controller::POINT_SIZE ); + return controller.GetDefaultFontSize(Text::Controller::POINT_SIZE); } } // namespace Text diff --git a/dali-toolkit/internal/text/text-controller-placeholder-handler.cpp b/dali-toolkit/internal/text/text-controller-placeholder-handler.cpp index 793a3e6..81d491a 100644 --- a/dali-toolkit/internal/text/text-controller-placeholder-handler.cpp +++ b/dali-toolkit/internal/text/text-controller-placeholder-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. @@ -22,48 +22,44 @@ #include // INTERNAL INCLUDES -#include #include #include #include +#include namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif const std::string EMPTY_STRING(""); -const char * const PLACEHOLDER_TEXT = "text"; -const char * const PLACEHOLDER_TEXT_FOCUSED = "textFocused"; -const char * const PLACEHOLDER_COLOR = "color"; -const char * const PLACEHOLDER_FONT_FAMILY = "fontFamily"; -const char * const PLACEHOLDER_FONT_STYLE = "fontStyle"; -const char * const PLACEHOLDER_POINT_SIZE = "pointSize"; -const char * const PLACEHOLDER_PIXEL_SIZE = "pixelSize"; -const char * const PLACEHOLDER_ELLIPSIS = "ellipsis"; +const char* const PLACEHOLDER_TEXT = "text"; +const char* const PLACEHOLDER_TEXT_FOCUSED = "textFocused"; +const char* const PLACEHOLDER_COLOR = "color"; +const char* const PLACEHOLDER_FONT_FAMILY = "fontFamily"; +const char* const PLACEHOLDER_FONT_STYLE = "fontStyle"; +const char* const PLACEHOLDER_POINT_SIZE = "pointSize"; +const char* const PLACEHOLDER_PIXEL_SIZE = "pixelSize"; +const char* const PLACEHOLDER_ELLIPSIS = "ellipsis"; } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - void Controller::PlaceholderHandler::SetPlaceholderTextElideEnabled(Controller& controller, bool enabled) { controller.mImpl->mEventData->mIsPlaceholderElideEnabled = enabled; - controller.mImpl->mEventData->mPlaceholderEllipsisFlag = true; + controller.mImpl->mEventData->mPlaceholderEllipsisFlag = true; // Update placeholder if there is no text - if( controller.mImpl->IsShowingPlaceholderText() || - ( 0u == controller.mImpl->mModel->mLogicalModel->mText.Count() ) ) + if(controller.mImpl->IsShowingPlaceholderText() || + (0u == controller.mImpl->mModel->mLogicalModel->mText.Count())) { controller.ShowPlaceholderText(); } @@ -76,9 +72,9 @@ bool Controller::PlaceholderHandler::IsPlaceholderTextElideEnabled(const Control void Controller::PlaceholderHandler::SetPlaceholderText(Controller& controller, PlaceholderType type, const std::string& text) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( PLACEHOLDER_TYPE_INACTIVE == type ) + if(PLACEHOLDER_TYPE_INACTIVE == type) { controller.mImpl->mEventData->mPlaceholderTextInactive = text; } @@ -88,8 +84,8 @@ void Controller::PlaceholderHandler::SetPlaceholderText(Controller& controller, } // Update placeholder if there is no text - if( controller.mImpl->IsShowingPlaceholderText() || - ( 0u == controller.mImpl->mModel->mLogicalModel->mText.Count() ) ) + if(controller.mImpl->IsShowingPlaceholderText() || + (0u == controller.mImpl->mModel->mLogicalModel->mText.Count())) { controller.ShowPlaceholderText(); } @@ -98,9 +94,9 @@ void Controller::PlaceholderHandler::SetPlaceholderText(Controller& controller, void Controller::PlaceholderHandler::GetPlaceholderText(const Controller& controller, PlaceholderType type, std::string& text) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( PLACEHOLDER_TYPE_INACTIVE == type ) + if(PLACEHOLDER_TYPE_INACTIVE == type) { text = controller.mImpl->mEventData->mPlaceholderTextInactive; } @@ -113,15 +109,15 @@ void Controller::PlaceholderHandler::GetPlaceholderText(const Controller& contro void Controller::PlaceholderHandler::SetPlaceholderFontFamily(Controller& controller, const std::string& placeholderTextFontFamily) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( NULL == controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL == controller.mImpl->mEventData->mPlaceholderFont) { controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults(); } controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.family = placeholderTextFontFamily; - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetPlaceholderFontFamily %s\n", placeholderTextFontFamily.c_str()); controller.mImpl->mEventData->mPlaceholderFont->familyDefined = !placeholderTextFontFamily.empty(); controller.mImpl->RequestRelayout(); @@ -130,7 +126,7 @@ void Controller::PlaceholderHandler::SetPlaceholderFontFamily(Controller& contro const std::string& Controller::PlaceholderHandler::GetPlaceholderFontFamily(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.family; } @@ -140,15 +136,15 @@ const std::string& Controller::PlaceholderHandler::GetPlaceholderFontFamily(cons void Controller::PlaceholderHandler::SetPlaceholderTextFontWeight(Controller& controller, FontWeight weight) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( NULL == controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL == controller.mImpl->mEventData->mPlaceholderFont) { controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults(); } controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.weight = weight; - controller.mImpl->mEventData->mPlaceholderFont->weightDefined = true; + controller.mImpl->mEventData->mPlaceholderFont->weightDefined = true; controller.mImpl->RequestRelayout(); } @@ -156,7 +152,7 @@ void Controller::PlaceholderHandler::SetPlaceholderTextFontWeight(Controller& co bool Controller::PlaceholderHandler::IsPlaceholderTextFontWeightDefined(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->weightDefined; } @@ -165,7 +161,7 @@ bool Controller::PlaceholderHandler::IsPlaceholderTextFontWeightDefined(const Co FontWeight Controller::PlaceholderHandler::GetPlaceholderTextFontWeight(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.weight; } @@ -175,15 +171,15 @@ FontWeight Controller::PlaceholderHandler::GetPlaceholderTextFontWeight(const Co void Controller::PlaceholderHandler::SetPlaceholderTextFontWidth(Controller& controller, FontWidth width) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( NULL == controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL == controller.mImpl->mEventData->mPlaceholderFont) { controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults(); } controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.width = width; - controller.mImpl->mEventData->mPlaceholderFont->widthDefined = true; + controller.mImpl->mEventData->mPlaceholderFont->widthDefined = true; controller.mImpl->RequestRelayout(); } @@ -191,7 +187,7 @@ void Controller::PlaceholderHandler::SetPlaceholderTextFontWidth(Controller& con bool Controller::PlaceholderHandler::IsPlaceholderTextFontWidthDefined(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->widthDefined; } @@ -200,7 +196,7 @@ bool Controller::PlaceholderHandler::IsPlaceholderTextFontWidthDefined(const Con FontWidth Controller::PlaceholderHandler::GetPlaceholderTextFontWidth(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.width; } @@ -210,15 +206,15 @@ FontWidth Controller::PlaceholderHandler::GetPlaceholderTextFontWidth(const Cont void Controller::PlaceholderHandler::SetPlaceholderTextFontSlant(Controller& controller, FontSlant slant) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( NULL == controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL == controller.mImpl->mEventData->mPlaceholderFont) { controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults(); } controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.slant = slant; - controller.mImpl->mEventData->mPlaceholderFont->slantDefined = true; + controller.mImpl->mEventData->mPlaceholderFont->slantDefined = true; controller.mImpl->RequestRelayout(); } @@ -226,7 +222,7 @@ void Controller::PlaceholderHandler::SetPlaceholderTextFontSlant(Controller& con bool Controller::PlaceholderHandler::IsPlaceholderTextFontSlantDefined(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->slantDefined; } @@ -235,7 +231,7 @@ bool Controller::PlaceholderHandler::IsPlaceholderTextFontSlantDefined(const Con FontSlant Controller::PlaceholderHandler::GetPlaceholderTextFontSlant(const Controller& controller) { - if( ( NULL != controller.mImpl->mEventData ) && ( NULL != controller.mImpl->mEventData->mPlaceholderFont ) ) + if((NULL != controller.mImpl->mEventData) && (NULL != controller.mImpl->mEventData->mPlaceholderFont)) { return controller.mImpl->mEventData->mPlaceholderFont->mFontDescription.slant; } @@ -245,33 +241,33 @@ FontSlant Controller::PlaceholderHandler::GetPlaceholderTextFontSlant(const Cont void Controller::PlaceholderHandler::SetPlaceholderTextFontSize(Controller& controller, float fontSize, FontSizeType type) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( NULL == controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL == controller.mImpl->mEventData->mPlaceholderFont) { controller.mImpl->mEventData->mPlaceholderFont = new FontDefaults(); } - switch( type ) + switch(type) { case POINT_SIZE: { controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = fontSize; - controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true; - controller.mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag + controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true; + controller.mImpl->mEventData->mIsPlaceholderPixelSize = false; // Font size flag break; } case PIXEL_SIZE: { // Point size = Pixel size * 72.f / DPI - unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - fontClient.GetDpi( horizontalDpi, verticalDpi ); - - controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi ); - controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true; - controller.mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag + unsigned int horizontalDpi = 0u; + unsigned int verticalDpi = 0u; + TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); + fontClient.GetDpi(horizontalDpi, verticalDpi); + + controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize = (fontSize * 72.f) / static_cast(horizontalDpi); + controller.mImpl->mEventData->mPlaceholderFont->sizeDefined = true; + controller.mImpl->mEventData->mIsPlaceholderPixelSize = true; // Font size flag break; } } @@ -280,42 +276,42 @@ void Controller::PlaceholderHandler::SetPlaceholderTextFontSize(Controller& cont } } -float Controller::PlaceholderHandler::GetPlaceholderTextFontSize(const Controller& controller, FontSizeType type ) +float Controller::PlaceholderHandler::GetPlaceholderTextFontSize(const Controller& controller, FontSizeType type) { float value = 0.0f; - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - switch( type ) + switch(type) { case POINT_SIZE: { - if( NULL != controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL != controller.mImpl->mEventData->mPlaceholderFont) { value = controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize; } else { // If the placeholder text font size is not set, then return the default font size. - value = controller.GetDefaultFontSize( POINT_SIZE ); + value = controller.GetDefaultFontSize(POINT_SIZE); } break; } case PIXEL_SIZE: { - if( NULL != controller.mImpl->mEventData->mPlaceholderFont ) + if(NULL != controller.mImpl->mEventData->mPlaceholderFont) { // Pixel size = Point size * DPI / 72.f - unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - fontClient.GetDpi( horizontalDpi, verticalDpi ); + unsigned int horizontalDpi = 0u; + unsigned int verticalDpi = 0u; + TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); + fontClient.GetDpi(horizontalDpi, verticalDpi); - value = controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f; + value = controller.mImpl->mEventData->mPlaceholderFont->mDefaultPointSize * static_cast(horizontalDpi) / 72.f; } else { // If the placeholder text font size is not set, then return the default font size. - value = controller.GetDefaultFontSize( PIXEL_SIZE ); + value = controller.GetDefaultFontSize(PIXEL_SIZE); } break; } @@ -326,23 +322,23 @@ float Controller::PlaceholderHandler::GetPlaceholderTextFontSize(const Controlle return value; } -void Controller::PlaceholderHandler::SetPlaceholderTextColor(Controller& controller, const Vector4& textColor ) +void Controller::PlaceholderHandler::SetPlaceholderTextColor(Controller& controller, const Vector4& textColor) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { controller.mImpl->mEventData->mPlaceholderTextColor = textColor; } - if( controller.mImpl->IsShowingPlaceholderText() ) + if(controller.mImpl->IsShowingPlaceholderText()) { - controller.mImpl->mModel->mVisualModel->SetTextColor( textColor ); + controller.mImpl->mModel->mVisualModel->SetTextColor(textColor); controller.mImpl->RequestRelayout(); } } const Vector4& Controller::PlaceholderHandler::GetPlaceholderTextColor(const Controller& controller) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { return controller.mImpl->mEventData->mPlaceholderTextColor; } @@ -350,69 +346,69 @@ const Vector4& Controller::PlaceholderHandler::GetPlaceholderTextColor(const Con return Color::BLACK; } -void Controller::PlaceholderHandler::SetPlaceholderProperty(Controller& controller, const Property::Map& map ) +void Controller::PlaceholderHandler::SetPlaceholderProperty(Controller& controller, const Property::Map& map) { const Property::Map::SizeType count = map.Count(); - for( Property::Map::SizeType position = 0; position < count; ++position ) + for(Property::Map::SizeType position = 0; position < count; ++position) { - KeyValuePair keyValue = map.GetKeyValue( position ); - Property::Key& key = keyValue.first; - Property::Value& value = keyValue.second; + KeyValuePair keyValue = map.GetKeyValue(position); + Property::Key& key = keyValue.first; + Property::Value& value = keyValue.second; - if( key == Toolkit::Text::PlaceHolder::Property::TEXT || key == PLACEHOLDER_TEXT ) + if(key == Toolkit::Text::PlaceHolder::Property::TEXT || key == PLACEHOLDER_TEXT) { std::string text = ""; - value.Get( text ); + value.Get(text); SetPlaceholderText(controller, Controller::PLACEHOLDER_TYPE_INACTIVE, text); } - else if( key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED ) + else if(key == Toolkit::Text::PlaceHolder::Property::TEXT_FOCUSED || key == PLACEHOLDER_TEXT_FOCUSED) { std::string text = ""; - value.Get( text ); + value.Get(text); SetPlaceholderText(controller, Controller::PLACEHOLDER_TYPE_ACTIVE, text); } - else if( key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR ) + else if(key == Toolkit::Text::PlaceHolder::Property::COLOR || key == PLACEHOLDER_COLOR) { Vector4 textColor; - value.Get( textColor ); - if( GetPlaceholderTextColor(controller) != textColor ) + value.Get(textColor); + if(GetPlaceholderTextColor(controller) != textColor) { SetPlaceholderTextColor(controller, textColor); } } - else if( key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY ) + else if(key == Toolkit::Text::PlaceHolder::Property::FONT_FAMILY || key == PLACEHOLDER_FONT_FAMILY) { std::string fontFamily = ""; - value.Get( fontFamily ); + value.Get(fontFamily); SetPlaceholderFontFamily(controller, fontFamily); } - else if( key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE ) + else if(key == Toolkit::Text::PlaceHolder::Property::FONT_STYLE || key == PLACEHOLDER_FONT_STYLE) { - SetFontStyleProperty( &controller, value, Text::FontStyle::PLACEHOLDER ); + SetFontStyleProperty(&controller, value, Text::FontStyle::PLACEHOLDER); } - else if( key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE ) + else if(key == Toolkit::Text::PlaceHolder::Property::POINT_SIZE || key == PLACEHOLDER_POINT_SIZE) { float pointSize; - value.Get( pointSize ); - if( !Equals(GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE), pointSize) ) + value.Get(pointSize); + if(!Equals(GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE), pointSize)) { SetPlaceholderTextFontSize(controller, pointSize, Text::Controller::POINT_SIZE); } } - else if( key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE ) + else if(key == Toolkit::Text::PlaceHolder::Property::PIXEL_SIZE || key == PLACEHOLDER_PIXEL_SIZE) { float pixelSize; - value.Get( pixelSize ); - if( !Equals(GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE), pixelSize) ) + value.Get(pixelSize); + if(!Equals(GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE), pixelSize)) { SetPlaceholderTextFontSize(controller, pixelSize, Text::Controller::PIXEL_SIZE); } } - else if( key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS ) + else if(key == Toolkit::Text::PlaceHolder::Property::ELLIPSIS || key == PLACEHOLDER_ELLIPSIS) { bool ellipsis; - value.Get( ellipsis ); + value.Get(ellipsis); SetPlaceholderTextElideEnabled(controller, ellipsis); } } @@ -420,37 +416,37 @@ void Controller::PlaceholderHandler::SetPlaceholderProperty(Controller& controll void Controller::PlaceholderHandler::GetPlaceholderProperty(Controller& controller, Property::Map& map) { - if( NULL != controller.mImpl->mEventData ) + if(NULL != controller.mImpl->mEventData) { - if( !controller.mImpl->mEventData->mPlaceholderTextActive.empty() ) + if(!controller.mImpl->mEventData->mPlaceholderTextActive.empty()) { - map[ Text::PlaceHolder::Property::TEXT_FOCUSED ] = controller.mImpl->mEventData->mPlaceholderTextActive; + map[Text::PlaceHolder::Property::TEXT_FOCUSED] = controller.mImpl->mEventData->mPlaceholderTextActive; } - if( !controller.mImpl->mEventData->mPlaceholderTextInactive.empty() ) + if(!controller.mImpl->mEventData->mPlaceholderTextInactive.empty()) { - map[ Text::PlaceHolder::Property::TEXT ] = controller.mImpl->mEventData->mPlaceholderTextInactive; + map[Text::PlaceHolder::Property::TEXT] = controller.mImpl->mEventData->mPlaceholderTextInactive; } - map[ Text::PlaceHolder::Property::COLOR ] = controller.mImpl->mEventData->mPlaceholderTextColor; - map[ Text::PlaceHolder::Property::FONT_FAMILY ] = GetPlaceholderFontFamily(controller); + map[Text::PlaceHolder::Property::COLOR] = controller.mImpl->mEventData->mPlaceholderTextColor; + map[Text::PlaceHolder::Property::FONT_FAMILY] = GetPlaceholderFontFamily(controller); Property::Value fontStyleMapGet; - GetFontStyleProperty( &controller, fontStyleMapGet, Text::FontStyle::PLACEHOLDER ); - map[ Text::PlaceHolder::Property::FONT_STYLE ] = fontStyleMapGet; + GetFontStyleProperty(&controller, fontStyleMapGet, Text::FontStyle::PLACEHOLDER); + map[Text::PlaceHolder::Property::FONT_STYLE] = fontStyleMapGet; // Choose font size : POINT_SIZE or PIXEL_SIZE - if( !controller.mImpl->mEventData->mIsPlaceholderPixelSize ) + if(!controller.mImpl->mEventData->mIsPlaceholderPixelSize) { - map[ Text::PlaceHolder::Property::POINT_SIZE ] = GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE); + map[Text::PlaceHolder::Property::POINT_SIZE] = GetPlaceholderTextFontSize(controller, Text::Controller::POINT_SIZE); } else { - map[ Text::PlaceHolder::Property::PIXEL_SIZE ] = GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE); + map[Text::PlaceHolder::Property::PIXEL_SIZE] = GetPlaceholderTextFontSize(controller, Text::Controller::PIXEL_SIZE); } - if( controller.mImpl->mEventData->mPlaceholderEllipsisFlag ) + if(controller.mImpl->mEventData->mPlaceholderEllipsisFlag) { - map[ Text::PlaceHolder::Property::ELLIPSIS ] = IsPlaceholderTextElideEnabled(controller); + map[Text::PlaceHolder::Property::ELLIPSIS] = IsPlaceholderTextElideEnabled(controller); } } } @@ -459,12 +455,12 @@ void Controller::PlaceholderHandler::ShowPlaceholderText(Controller& controller) { Controller::Impl& impl = *controller.mImpl; - if( impl.IsPlaceholderAvailable() ) + if(impl.IsPlaceholderAvailable()) { EventData*& eventData = impl.mEventData; - DALI_ASSERT_DEBUG( eventData && "No placeholder text available" ); + DALI_ASSERT_DEBUG(eventData && "No placeholder text available"); - if( NULL == eventData ) + if(NULL == eventData) { return; } @@ -473,17 +469,17 @@ void Controller::PlaceholderHandler::ShowPlaceholderText(Controller& controller) // Disable handles when showing place-holder text DecoratorPtr& decorator = eventData->mDecorator; - decorator->SetHandleActive( GRAB_HANDLE, false ); - decorator->SetHandleActive( LEFT_SELECTION_HANDLE, false ); - decorator->SetHandleActive( RIGHT_SELECTION_HANDLE, false ); + decorator->SetHandleActive(GRAB_HANDLE, false); + decorator->SetHandleActive(LEFT_SELECTION_HANDLE, false); + decorator->SetHandleActive(RIGHT_SELECTION_HANDLE, false); - const char* text( NULL ); - size_t size( 0 ); + const char* text(NULL); + size_t size(0); // TODO - Switch Placeholder text when changing state std::string& placeholderTextActive = eventData->mPlaceholderTextActive; - if( ( EventData::INACTIVE != eventData->mState ) && - ( 0u != placeholderTextActive.c_str() ) ) + if((EventData::INACTIVE != eventData->mState) && + (0u != placeholderTextActive.c_str())) { text = placeholderTextActive.c_str(); size = placeholderTextActive.size(); @@ -491,31 +487,31 @@ void Controller::PlaceholderHandler::ShowPlaceholderText(Controller& controller) else { std::string& placeholderTextInactive = eventData->mPlaceholderTextInactive; - text = placeholderTextInactive.c_str(); - size = placeholderTextInactive.size(); + text = placeholderTextInactive.c_str(); + size = placeholderTextInactive.size(); } - TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; - textUpdateInfo.mCharacterIndex = 0u; + TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; + textUpdateInfo.mCharacterIndex = 0u; textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters; // Reset model for showing placeholder. - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; LogicalModelPtr& logicalModel = model->mLogicalModel; logicalModel->mText.Clear(); - model->mVisualModel->SetTextColor( eventData->mPlaceholderTextColor ); + model->mVisualModel->SetTextColor(eventData->mPlaceholderTextColor); // Convert text into UTF-32 Vector& utf32Characters = logicalModel->mText; - utf32Characters.Resize( size ); + utf32Characters.Resize(size); // This is a bit horrible but std::string returns a (signed) char* - const uint8_t* utf8 = reinterpret_cast( text ); + const uint8_t* utf8 = reinterpret_cast(text); // Transform a text array encoded in utf8 into an array encoded in utf32. // It returns the actual number of characters. - const Length characterCount = Utf8ToUtf32( utf8, size, utf32Characters.Begin() ); - utf32Characters.Resize( characterCount ); + const Length characterCount = Utf8ToUtf32(utf8, size, utf32Characters.Begin()); + utf32Characters.Resize(characterCount); // The characters to be added. textUpdateInfo.mNumberOfCharactersToAdd = characterCount; @@ -533,11 +529,10 @@ void Controller::PlaceholderHandler::ShowPlaceholderText(Controller& controller) impl.mOperationsPending = ALL_OPERATIONS; // Update the rest of the model during size negotiation - impl.QueueModifyEvent( ModifyEvent::TEXT_REPLACED ); + impl.QueueModifyEvent(ModifyEvent::TEXT_REPLACED); } } - } // namespace Text } // namespace Toolkit diff --git a/dali-toolkit/internal/text/text-controller-relayouter.cpp b/dali-toolkit/internal/text/text-controller-relayouter.cpp index fa71759..2b362c0 100644 --- a/dali-toolkit/internal/text/text-controller-relayouter.cpp +++ b/dali-toolkit/internal/text/text-controller-relayouter.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 @@ -28,87 +28,83 @@ namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif constexpr float MAX_FLOAT = std::numeric_limits::max(); -float ConvertToEven( float value ) +float ConvertToEven(float value) { - int intValue(static_cast( value )); - return static_cast( intValue + ( intValue & 1 ) ); + int intValue(static_cast(value)); + return static_cast(intValue + (intValue & 1)); } } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetNaturalSize\n"); Vector3 naturalSize; // Make sure the model is up-to-date before layouting controller.ProcessModifyEvents(); - Controller::Impl& impl = *controller.mImpl; - ModelPtr& model = impl.mModel; - VisualModelPtr& visualModel = model->mVisualModel; - if( impl.mRecalculateNaturalSize ) + Controller::Impl& impl = *controller.mImpl; + ModelPtr& model = impl.mModel; + VisualModelPtr& visualModel = model->mVisualModel; + if(impl.mRecalculateNaturalSize) { // Operations that can be done only once until the text changes. - const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | - GET_SCRIPTS | - VALIDATE_FONTS | - GET_LINE_BREAKS | - BIDI_INFO | - SHAPE_TEXT | - GET_GLYPH_METRICS ); + const OperationsMask onlyOnceOperations = static_cast(CONVERT_TO_UTF32 | + GET_SCRIPTS | + VALIDATE_FONTS | + GET_LINE_BREAKS | + BIDI_INFO | + SHAPE_TEXT | + GET_GLYPH_METRICS); // Set the update info to relayout the whole text. - TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; - textUpdateInfo.mParagraphCharacterIndex = 0u; + TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; + textUpdateInfo.mParagraphCharacterIndex = 0u; textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count(); // Make sure the model is up-to-date before layouting - impl.UpdateModel( onlyOnceOperations ); + impl.UpdateModel(onlyOnceOperations); // Get a reference to the pending operations member OperationsMask& operationsPending = impl.mOperationsPending; // Layout the text for the new width. - operationsPending = static_cast( operationsPending | LAYOUT | REORDER ); + operationsPending = static_cast(operationsPending | LAYOUT | REORDER); // Store the actual control's size to restore later. const Size actualControlSize = visualModel->mControlSize; - DoRelayout( controller, - Size( MAX_FLOAT, MAX_FLOAT ), - static_cast( onlyOnceOperations | - LAYOUT | REORDER ), - naturalSize.GetVectorXY() ); + DoRelayout(controller, + Size(MAX_FLOAT, MAX_FLOAT), + static_cast(onlyOnceOperations | + LAYOUT | REORDER), + naturalSize.GetVectorXY()); // Do not do again the only once operations. - operationsPending = static_cast( operationsPending & ~onlyOnceOperations ); + operationsPending = static_cast(operationsPending & ~onlyOnceOperations); // Do the size related operations again. - const OperationsMask sizeOperations = static_cast( LAYOUT | - ALIGN | - REORDER ); - operationsPending = static_cast( operationsPending | sizeOperations ); + const OperationsMask sizeOperations = static_cast(LAYOUT | + ALIGN | + REORDER); + operationsPending = static_cast(operationsPending | sizeOperations); // Stores the natural size to avoid recalculate it again // unless the text/style changes. - visualModel->SetNaturalSize( naturalSize.GetVectorXY() ); + visualModel->SetNaturalSize(naturalSize.GetVectorXY()); impl.mRecalculateNaturalSize = false; @@ -119,55 +115,55 @@ Vector3 Controller::Relayouter::GetNaturalSize(Controller& controller) // Restore the actual control's size. visualModel->mControlSize = actualControlSize; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize calculated %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z); } else { naturalSize = visualModel->GetNaturalSize(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetNaturalSize cached %f,%f,%f\n", naturalSize.x, naturalSize.y, naturalSize.z); } - naturalSize.x = ConvertToEven( naturalSize.x ); - naturalSize.y = ConvertToEven( naturalSize.y ); + naturalSize.x = ConvertToEven(naturalSize.x); + naturalSize.y = ConvertToEven(naturalSize.y); return naturalSize; } bool Controller::Relayouter::CheckForTextFit(Controller& controller, float pointSize, const Size& layoutSize) { - Size textSize; - Controller::Impl& impl = *controller.mImpl; - TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; + Size textSize; + Controller::Impl& impl = *controller.mImpl; + TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; impl.mFontDefaults->mFitPointSize = pointSize; - impl.mFontDefaults->sizeDefined = true; + impl.mFontDefaults->sizeDefined = true; controller.ClearFontData(); // Operations that can be done only once until the text changes. - const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | - GET_SCRIPTS | - VALIDATE_FONTS | - GET_LINE_BREAKS | - BIDI_INFO | - SHAPE_TEXT| - GET_GLYPH_METRICS ); - - textUpdateInfo.mParagraphCharacterIndex = 0u; + const OperationsMask onlyOnceOperations = static_cast(CONVERT_TO_UTF32 | + GET_SCRIPTS | + VALIDATE_FONTS | + GET_LINE_BREAKS | + BIDI_INFO | + SHAPE_TEXT | + GET_GLYPH_METRICS); + + textUpdateInfo.mParagraphCharacterIndex = 0u; textUpdateInfo.mRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count(); // Make sure the model is up-to-date before layouting - impl.UpdateModel( onlyOnceOperations ); + impl.UpdateModel(onlyOnceOperations); - DoRelayout( controller, - Size( layoutSize.width, MAX_FLOAT ), - static_cast( onlyOnceOperations | LAYOUT), - textSize); + DoRelayout(controller, + Size(layoutSize.width, MAX_FLOAT), + static_cast(onlyOnceOperations | LAYOUT), + textSize); // Clear the update info. This info will be set the next time the text is updated. textUpdateInfo.Clear(); textUpdateInfo.mClearAll = true; - if( textSize.width > layoutSize.width || textSize.height > layoutSize.height ) + if(textSize.width > layoutSize.width || textSize.height > layoutSize.height) { return false; } @@ -178,116 +174,116 @@ void Controller::Relayouter::FitPointSizeforLayout(Controller& controller, const { Controller::Impl& impl = *controller.mImpl; - const OperationsMask operations = impl.mOperationsPending; - if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) || impl.mTextFitContentSize != layoutSize ) + const OperationsMask operations = impl.mOperationsPending; + if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations) || impl.mTextFitContentSize != layoutSize) { ModelPtr& model = impl.mModel; - bool actualellipsis = model->mElideEnabled; - float minPointSize = impl.mTextFitMinSize; - float maxPointSize = impl.mTextFitMaxSize; - float pointInterval = impl.mTextFitStepSize; + bool actualellipsis = model->mElideEnabled; + float minPointSize = impl.mTextFitMinSize; + float maxPointSize = impl.mTextFitMaxSize; + float pointInterval = impl.mTextFitStepSize; model->mElideEnabled = false; Vector pointSizeArray; // check zero value - if( pointInterval < 1.f ) + if(pointInterval < 1.f) { impl.mTextFitStepSize = pointInterval = 1.0f; } - pointSizeArray.Reserve( static_cast< unsigned int >( ceil( ( maxPointSize - minPointSize ) / pointInterval ) ) ); + pointSizeArray.Reserve(static_cast(ceil((maxPointSize - minPointSize) / pointInterval))); - for( float i = minPointSize; i < maxPointSize; i += pointInterval ) + for(float i = minPointSize; i < maxPointSize; i += pointInterval) { - pointSizeArray.PushBack( i ); + pointSizeArray.PushBack(i); } - pointSizeArray.PushBack( maxPointSize ); + pointSizeArray.PushBack(maxPointSize); int bestSizeIndex = 0; - int min = bestSizeIndex + 1; - int max = pointSizeArray.Size() - 1; - while( min <= max ) + int min = bestSizeIndex + 1; + int max = pointSizeArray.Size() - 1; + while(min <= max) { - int destI = ( min + max ) / 2; + int destI = (min + max) / 2; - if( CheckForTextFit( controller, pointSizeArray[destI], layoutSize ) ) + if(CheckForTextFit(controller, pointSizeArray[destI], layoutSize)) { bestSizeIndex = min; - min = destI + 1; + min = destI + 1; } else { - max = destI - 1; + max = destI - 1; bestSizeIndex = max; } } - model->mElideEnabled = actualellipsis; + model->mElideEnabled = actualellipsis; impl.mFontDefaults->mFitPointSize = pointSizeArray[bestSizeIndex]; - impl.mFontDefaults->sizeDefined = true; + impl.mFontDefaults->sizeDefined = true; controller.ClearFontData(); } } float Controller::Relayouter::GetHeightForWidth(Controller& controller, float width) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::GetHeightForWidth %p width %f\n", &controller, width); // Make sure the model is up-to-date before layouting controller.ProcessModifyEvents(); - Controller::Impl& impl = *controller.mImpl; - ModelPtr& model = impl.mModel; - VisualModelPtr& visualModel = model->mVisualModel; - TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; + Controller::Impl& impl = *controller.mImpl; + ModelPtr& model = impl.mModel; + VisualModelPtr& visualModel = model->mVisualModel; + TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; Size layoutSize; - if( fabsf( width - visualModel->mControlSize.width ) > Math::MACHINE_EPSILON_1000 || - textUpdateInfo.mFullRelayoutNeeded || - textUpdateInfo.mClearAll ) + if(fabsf(width - visualModel->mControlSize.width) > Math::MACHINE_EPSILON_1000 || + textUpdateInfo.mFullRelayoutNeeded || + textUpdateInfo.mClearAll) { // Operations that can be done only once until the text changes. - const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | - GET_SCRIPTS | - VALIDATE_FONTS | - GET_LINE_BREAKS | - BIDI_INFO | - SHAPE_TEXT | - GET_GLYPH_METRICS ); + const OperationsMask onlyOnceOperations = static_cast(CONVERT_TO_UTF32 | + GET_SCRIPTS | + VALIDATE_FONTS | + GET_LINE_BREAKS | + BIDI_INFO | + SHAPE_TEXT | + GET_GLYPH_METRICS); // Set the update info to relayout the whole text. - textUpdateInfo.mParagraphCharacterIndex = 0u; + textUpdateInfo.mParagraphCharacterIndex = 0u; textUpdateInfo.mRequestedNumberOfCharacters = model->mLogicalModel->mText.Count(); // Make sure the model is up-to-date before layouting - impl.UpdateModel( onlyOnceOperations ); + impl.UpdateModel(onlyOnceOperations); // Get a reference to the pending operations member OperationsMask& operationsPending = impl.mOperationsPending; // Layout the text for the new width. - operationsPending = static_cast( operationsPending | LAYOUT ); + operationsPending = static_cast(operationsPending | LAYOUT); // Store the actual control's width. const float actualControlWidth = visualModel->mControlSize.width; - DoRelayout( controller, - Size( width, MAX_FLOAT ), - static_cast( onlyOnceOperations | - LAYOUT ), - layoutSize ); + DoRelayout(controller, + Size(width, MAX_FLOAT), + static_cast(onlyOnceOperations | + LAYOUT), + layoutSize); // Do not do again the only once operations. - operationsPending = static_cast( operationsPending & ~onlyOnceOperations ); + operationsPending = static_cast(operationsPending & ~onlyOnceOperations); // Do the size related operations again. - const OperationsMask sizeOperations = static_cast( LAYOUT | - ALIGN | - REORDER ); + const OperationsMask sizeOperations = static_cast(LAYOUT | + ALIGN | + REORDER); - operationsPending = static_cast( operationsPending | sizeOperations ); + operationsPending = static_cast(operationsPending | sizeOperations); // Clear the update info. This info will be set the next time the text is updated. textUpdateInfo.Clear(); @@ -296,12 +292,12 @@ float Controller::Relayouter::GetHeightForWidth(Controller& controller, float wi // Restore the actual control's width. visualModel->mControlSize.width = actualControlWidth; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth calculated %f\n", layoutSize.height); } else { layoutSize = visualModel->GetLayoutSize(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::GetHeightForWidth cached %f\n", layoutSize.height); } return layoutSize.height; @@ -309,18 +305,18 @@ float Controller::Relayouter::GetHeightForWidth(Controller& controller, float wi Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controller, const Size& size, Dali::LayoutDirection::Type layoutDirection) { - Controller::Impl& impl = *controller.mImpl; - ModelPtr& model = impl.mModel; - VisualModelPtr& visualModel = model->mVisualModel; - TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; + Controller::Impl& impl = *controller.mImpl; + ModelPtr& model = impl.mModel; + VisualModelPtr& visualModel = model->mVisualModel; + TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ?"true":"false" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::Relayout %p size %f,%f, autoScroll[%s]\n", &controller, size.width, size.height, impl.mIsAutoScrollEnabled ? "true" : "false"); UpdateTextType updateTextType = NONE_UPDATED; - if( ( size.width < Math::MACHINE_EPSILON_1000 ) || ( size.height < Math::MACHINE_EPSILON_1000 ) ) + if((size.width < Math::MACHINE_EPSILON_1000) || (size.height < Math::MACHINE_EPSILON_1000)) { - if( 0u != visualModel->mGlyphPositions.Count() ) + if(0u != visualModel->mGlyphPositions.Count()) { visualModel->mGlyphPositions.Clear(); updateTextType = MODEL_UPDATED; @@ -330,95 +326,94 @@ Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controll textUpdateInfo.Clear(); // Not worth to relayout if width or height is equal to zero. - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout (skipped)\n"); return updateTextType; } // Whether a new size has been set. - const bool newSize = ( size != visualModel->mControlSize ); + const bool newSize = (size != visualModel->mControlSize); // Get a reference to the pending operations member OperationsMask& operationsPending = impl.mOperationsPending; - if( newSize ) + if(newSize) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "new size (previous size %f,%f)\n", visualModel->mControlSize.width, visualModel->mControlSize.height); - if( ( 0 == textUpdateInfo.mNumberOfCharactersToAdd ) && - ( 0 == textUpdateInfo.mPreviousNumberOfCharacters ) && - ( ( visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000 ) || ( visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000 ) ) ) + if((0 == textUpdateInfo.mNumberOfCharactersToAdd) && + (0 == textUpdateInfo.mPreviousNumberOfCharacters) && + ((visualModel->mControlSize.width < Math::MACHINE_EPSILON_1000) || (visualModel->mControlSize.height < Math::MACHINE_EPSILON_1000))) { textUpdateInfo.mNumberOfCharactersToAdd = model->mLogicalModel->mText.Count(); } // Layout operations that need to be done if the size changes. - operationsPending = static_cast( operationsPending | - LAYOUT | - ALIGN | - UPDATE_LAYOUT_SIZE | - REORDER ); + operationsPending = static_cast(operationsPending | + LAYOUT | + ALIGN | + UPDATE_LAYOUT_SIZE | + REORDER); // Set the update info to relayout the whole text. textUpdateInfo.mFullRelayoutNeeded = true; - textUpdateInfo.mCharacterIndex = 0u; + textUpdateInfo.mCharacterIndex = 0u; // Store the size used to layout the text. visualModel->mControlSize = size; } // Whether there are modify events. - if( 0u != impl.mModifyEvents.Count() ) + if(0u != impl.mModifyEvents.Count()) { // Style operations that need to be done if the text is modified. - operationsPending = static_cast( operationsPending | COLOR ); + operationsPending = static_cast(operationsPending | COLOR); } // Set the update info to elide the text. - if( model->mElideEnabled || - ( ( NULL != impl.mEventData ) && impl.mEventData->mIsPlaceholderElideEnabled ) ) + if(model->mElideEnabled || + ((NULL != impl.mEventData) && impl.mEventData->mIsPlaceholderElideEnabled)) { // Update Text layout for applying elided - operationsPending = static_cast( operationsPending | - ALIGN | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER ); + operationsPending = static_cast(operationsPending | + ALIGN | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER); textUpdateInfo.mFullRelayoutNeeded = true; - textUpdateInfo.mCharacterIndex = 0u; + textUpdateInfo.mCharacterIndex = 0u; } - if( model->mMatchSystemLanguageDirection && impl.mLayoutDirection != layoutDirection ) + if(model->mMatchSystemLanguageDirection && impl.mLayoutDirection != layoutDirection) { // Clear the update info. This info will be set the next time the text is updated. textUpdateInfo.mClearAll = true; // Apply modifications to the model // Shape the text again is needed because characters like '()[]{}' have to be mirrored and the glyphs generated again. - operationsPending = static_cast( operationsPending | - GET_GLYPH_METRICS | - SHAPE_TEXT | - UPDATE_DIRECTION | - LAYOUT | - BIDI_INFO | - REORDER ); + operationsPending = static_cast(operationsPending | + GET_GLYPH_METRICS | + SHAPE_TEXT | + UPDATE_DIRECTION | + LAYOUT | + BIDI_INFO | + REORDER); impl.mLayoutDirection = layoutDirection; } // Make sure the model is up-to-date before layouting. controller.ProcessModifyEvents(); - bool updated = impl.UpdateModel( operationsPending ); + bool updated = impl.UpdateModel(operationsPending); // Layout the text. Size layoutSize; - updated = DoRelayout( controller, size, operationsPending, layoutSize ) || updated; + updated = DoRelayout(controller, size, operationsPending, layoutSize) || updated; - - if( updated ) + if(updated) { updateTextType = MODEL_UPDATED; } // Do not re-do any operation until something changes. - operationsPending = NO_OPERATION; + operationsPending = NO_OPERATION; model->mScrollPositionLast = model->mScrollPosition; // Whether the text control is editable @@ -426,142 +421,142 @@ Controller::UpdateTextType Controller::Relayouter::Relayout(Controller& controll // Keep the current offset as it will be used to update the decorator's positions (if the size changes). Vector2 offset; - if( newSize && isEditable ) + if(newSize && isEditable) { offset = model->mScrollPosition; } - if( !isEditable || !controller.IsMultiLineEnabled() ) + if(!isEditable || !controller.IsMultiLineEnabled()) { // After doing the text layout, the vertical offset to place the actor in the desired position can be calculated. - controller.CalculateVerticalOffset( size ); + controller.CalculateVerticalOffset(size); } - if( isEditable ) + if(isEditable) { - if( newSize ) + if(newSize) { // If there is a new size, the scroll position needs to be clamped. - impl.ClampHorizontalScroll( layoutSize ); + impl.ClampHorizontalScroll(layoutSize); // Update the decorator's positions is needed if there is a new size. - impl.mEventData->mDecorator->UpdatePositions( model->mScrollPosition - offset ); + impl.mEventData->mDecorator->UpdatePositions(model->mScrollPosition - offset); } // Move the cursor, grab handle etc. - if( impl.ProcessInputEvents() ) + if(impl.ProcessInputEvents()) { - updateTextType = static_cast( updateTextType | DECORATOR_UPDATED ); + updateTextType = static_cast(updateTextType | DECORATOR_UPDATED); } } // Clear the update info. This info will be set the next time the text is updated. textUpdateInfo.Clear(); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::Relayout\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::Relayout\n"); return updateTextType; } -bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize ) +bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size, OperationsMask operationsRequired, Size& layoutSize) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height ); - bool viewUpdated( false ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout %p size %f,%f\n", &controller, size.width, size.height); + bool viewUpdated(false); Controller::Impl& impl = *controller.mImpl; // Calculate the operations to be done. - const OperationsMask operations = static_cast( impl.mOperationsPending & operationsRequired ); + const OperationsMask operations = static_cast(impl.mOperationsPending & operationsRequired); - TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; - const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex; - const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters; + TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; + const CharacterIndex startIndex = textUpdateInfo.mParagraphCharacterIndex; + const Length requestedNumberOfCharacters = textUpdateInfo.mRequestedNumberOfCharacters; // Get the current layout size. VisualModelPtr& visualModel = impl.mModel->mVisualModel; - layoutSize = visualModel->GetLayoutSize(); + layoutSize = visualModel->GetLayoutSize(); - if( NO_OPERATION != ( LAYOUT & operations ) ) + if(NO_OPERATION != (LAYOUT & operations)) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "-->Controller::DoRelayout LAYOUT & operations\n"); // Some vectors with data needed to layout and reorder may be void // after the first time the text has been laid out. // Fill the vectors again. // Calculate the number of glyphs to layout. - const Vector& charactersToGlyph = visualModel->mCharactersToGlyph; - const Vector& glyphsPerCharacter = visualModel->mGlyphsPerCharacter; - const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin(); - const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin(); + const Vector& charactersToGlyph = visualModel->mCharactersToGlyph; + const Vector& glyphsPerCharacter = visualModel->mGlyphsPerCharacter; + const GlyphIndex* const charactersToGlyphBuffer = charactersToGlyph.Begin(); + const Length* const glyphsPerCharacterBuffer = glyphsPerCharacter.Begin(); - const CharacterIndex lastIndex = startIndex + ( ( requestedNumberOfCharacters > 0u ) ? requestedNumberOfCharacters - 1u : 0u ); - const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex; + const CharacterIndex lastIndex = startIndex + ((requestedNumberOfCharacters > 0u) ? requestedNumberOfCharacters - 1u : 0u); + const GlyphIndex startGlyphIndex = textUpdateInfo.mStartGlyphIndex; // Make sure the index is not out of bound - if ( charactersToGlyph.Count() != glyphsPerCharacter.Count() || - requestedNumberOfCharacters > charactersToGlyph.Count() || - ( lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u ) ) + if(charactersToGlyph.Count() != glyphsPerCharacter.Count() || + requestedNumberOfCharacters > charactersToGlyph.Count() || + (lastIndex > charactersToGlyph.Count() && charactersToGlyph.Count() > 0u)) { std::string currentText; - controller.GetText( currentText ); + controller.GetText(currentText); - DALI_LOG_ERROR( "Controller::DoRelayout: Attempting to access invalid buffer\n" ); - DALI_LOG_ERROR( "Current text is: %s\n", currentText.c_str() ); - DALI_LOG_ERROR( "startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count()); + DALI_LOG_ERROR("Controller::DoRelayout: Attempting to access invalid buffer\n"); + DALI_LOG_ERROR("Current text is: %s\n", currentText.c_str()); + DALI_LOG_ERROR("startIndex: %u, lastIndex: %u, requestedNumberOfCharacters: %u, charactersToGlyph.Count = %lu, glyphsPerCharacter.Count = %lu\n", startIndex, lastIndex, requestedNumberOfCharacters, charactersToGlyph.Count(), glyphsPerCharacter.Count()); return false; } - const Length numberOfGlyphs = ( requestedNumberOfCharacters > 0u ) ? *( charactersToGlyphBuffer + lastIndex ) + *( glyphsPerCharacterBuffer + lastIndex ) - startGlyphIndex : 0u; + const Length numberOfGlyphs = (requestedNumberOfCharacters > 0u) ? *(charactersToGlyphBuffer + lastIndex) + *(glyphsPerCharacterBuffer + lastIndex) - startGlyphIndex : 0u; const Length totalNumberOfGlyphs = visualModel->mGlyphs.Count(); - if( 0u == totalNumberOfGlyphs ) + if(0u == totalNumberOfGlyphs) { - if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) ) + if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations)) { - visualModel->SetLayoutSize( Size::ZERO ); + visualModel->SetLayoutSize(Size::ZERO); } // Nothing else to do if there is no glyphs. - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout no glyphs, view updated true\n"); return true; } // Set the layout parameters. - Layout::Parameters layoutParameters( size, impl.mModel); + Layout::Parameters layoutParameters(size, impl.mModel); // Resize the vector of positions to have the same size than the vector of glyphs. Vector& glyphPositions = visualModel->mGlyphPositions; - glyphPositions.Resize( totalNumberOfGlyphs ); + glyphPositions.Resize(totalNumberOfGlyphs); // Whether the last character is a new paragraph character. - const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin(); - textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph( *( textBuffer + ( impl.mModel->mLogicalModel->mText.Count() - 1u ) ) ); - layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph; + const Character* const textBuffer = impl.mModel->mLogicalModel->mText.Begin(); + textUpdateInfo.mIsLastCharacterNewParagraph = TextAbstraction::IsNewParagraph(*(textBuffer + (impl.mModel->mLogicalModel->mText.Count() - 1u))); + layoutParameters.isLastNewParagraph = textUpdateInfo.mIsLastCharacterNewParagraph; // The initial glyph and the number of glyphs to layout. - layoutParameters.startGlyphIndex = startGlyphIndex; - layoutParameters.numberOfGlyphs = numberOfGlyphs; - layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex; + layoutParameters.startGlyphIndex = startGlyphIndex; + layoutParameters.numberOfGlyphs = numberOfGlyphs; + layoutParameters.startLineIndex = textUpdateInfo.mStartLineIndex; layoutParameters.estimatedNumberOfLines = textUpdateInfo.mEstimatedNumberOfLines; // Update the ellipsis bool elideTextEnabled = impl.mModel->mElideEnabled; - if( NULL != impl.mEventData ) + if(NULL != impl.mEventData) { - if( impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText() ) + if(impl.mEventData->mPlaceholderEllipsisFlag && impl.IsShowingPlaceholderText()) { elideTextEnabled = impl.mEventData->mIsPlaceholderElideEnabled; } - else if( EventData::INACTIVE != impl.mEventData->mState ) + else if(EventData::INACTIVE != impl.mEventData->mState) { // Disable ellipsis when editing elideTextEnabled = false; } // Reset the scroll position in inactive state - if( elideTextEnabled && ( impl.mEventData->mState == EventData::INACTIVE ) ) + if(elideTextEnabled && (impl.mEventData->mState == EventData::INACTIVE)) { controller.ResetScrollPosition(); } @@ -570,88 +565,88 @@ bool Controller::Relayouter::DoRelayout(Controller& controller, const Size& size // Update the visual model. bool isAutoScrollEnabled = impl.mIsAutoScrollEnabled; Size newLayoutSize; - viewUpdated = impl.mLayoutEngine.LayoutText( layoutParameters, - newLayoutSize, - elideTextEnabled, - isAutoScrollEnabled ); + viewUpdated = impl.mLayoutEngine.LayoutText(layoutParameters, + newLayoutSize, + elideTextEnabled, + isAutoScrollEnabled); impl.mIsAutoScrollEnabled = isAutoScrollEnabled; - viewUpdated = viewUpdated || ( newLayoutSize != layoutSize ); + viewUpdated = viewUpdated || (newLayoutSize != layoutSize); - if( viewUpdated ) + if(viewUpdated) { layoutSize = newLayoutSize; - if( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) + if(NO_OPERATION != (UPDATE_DIRECTION & operations)) { impl.mIsTextDirectionRTL = false; } - if ( ( NO_OPERATION != ( UPDATE_DIRECTION & operations ) ) && !visualModel->mLines.Empty() ) + if((NO_OPERATION != (UPDATE_DIRECTION & operations)) && !visualModel->mLines.Empty()) { impl.mIsTextDirectionRTL = visualModel->mLines[0u].direction; } // Sets the layout size. - if( NO_OPERATION != ( UPDATE_LAYOUT_SIZE & operations ) ) + if(NO_OPERATION != (UPDATE_LAYOUT_SIZE & operations)) { - visualModel->SetLayoutSize( layoutSize ); + visualModel->SetLayoutSize(layoutSize); } } // view updated } - if( NO_OPERATION != ( ALIGN & operations ) ) + if(NO_OPERATION != (ALIGN & operations)) { // The laid-out lines. Vector& lines = visualModel->mLines; - CharacterIndex alignStartIndex = startIndex; - Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters; + CharacterIndex alignStartIndex = startIndex; + Length alignRequestedNumberOfCharacters = requestedNumberOfCharacters; // the whole text needs to be full aligned. // If you do not do a full aligned, only the last line of the multiline input is aligned. - if( impl.mEventData && impl.mEventData->mUpdateAlignment ) + if(impl.mEventData && impl.mEventData->mUpdateAlignment) { - alignStartIndex = 0u; - alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count(); + alignStartIndex = 0u; + alignRequestedNumberOfCharacters = impl.mModel->mLogicalModel->mText.Count(); impl.mEventData->mUpdateAlignment = false; } // Need to align with the control's size as the text may contain lines // starting either with left to right text or right to left. - impl.mLayoutEngine.Align( size, - alignStartIndex, - alignRequestedNumberOfCharacters, - impl.mModel->mHorizontalAlignment, - lines, - impl.mModel->mAlignmentOffset, - impl.mLayoutDirection, - impl.mModel->mMatchSystemLanguageDirection ); + impl.mLayoutEngine.Align(size, + alignStartIndex, + alignRequestedNumberOfCharacters, + impl.mModel->mHorizontalAlignment, + lines, + impl.mModel->mAlignmentOffset, + impl.mLayoutDirection, + impl.mModel->mMatchSystemLanguageDirection); viewUpdated = true; } #if defined(DEBUG_ENABLED) std::string currentText; - controller.GetText( currentText ); - DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL)?"true":"false", currentText.c_str() ); + controller.GetText(currentText); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::DoRelayout [%p] mImpl->mIsTextDirectionRTL[%s] [%s]\n", &controller, (impl.mIsTextDirectionRTL) ? "true" : "false", currentText.c_str()); #endif - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", ( viewUpdated ? "true" : "false" ) ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "<--Controller::DoRelayout, view updated %s\n", (viewUpdated ? "true" : "false")); return viewUpdated; } void Controller::Relayouter::CalculateVerticalOffset(Controller& controller, const Size& controlSize) { - Controller::Impl& impl = *controller.mImpl; - ModelPtr& model = impl.mModel; - Size layoutSize = model->mVisualModel->GetLayoutSize(); + Controller::Impl& impl = *controller.mImpl; + ModelPtr& model = impl.mModel; + Size layoutSize = model->mVisualModel->GetLayoutSize(); - if( fabsf( layoutSize.height ) < Math::MACHINE_EPSILON_1000 ) + if(fabsf(layoutSize.height) < Math::MACHINE_EPSILON_1000) { // Get the line height of the default font. layoutSize.height = impl.GetDefaultFontLineHeight(); } - switch( model->mVerticalAlignment ) + switch(model->mVerticalAlignment) { case VerticalAlignment::TOP: { @@ -660,7 +655,7 @@ void Controller::Relayouter::CalculateVerticalOffset(Controller& controller, con } case VerticalAlignment::CENTER: { - model->mScrollPosition.y = floorf( 0.5f * ( controlSize.height - layoutSize.height ) ); // try to avoid pixel alignment. + model->mScrollPosition.y = floorf(0.5f * (controlSize.height - layoutSize.height)); // try to avoid pixel alignment. break; } case VerticalAlignment::BOTTOM: diff --git a/dali-toolkit/internal/text/text-controller-text-updater.cpp b/dali-toolkit/internal/text/text-controller-text-updater.cpp index cd3f755..c22e207 100644 --- a/dali-toolkit/internal/text/text-controller-text-updater.cpp +++ b/dali-toolkit/internal/text/text-controller-text-updater.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 @@ -30,7 +30,6 @@ namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif @@ -39,16 +38,13 @@ Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT namespace Dali { - namespace Toolkit { - namespace Text { - void Controller::TextUpdater::SetText(Controller& controller, const std::string& text) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SetText\n"); Controller::Impl& impl = *controller.mImpl; @@ -65,57 +61,57 @@ void Controller::TextUpdater::SetText(Controller& controller, const std::string& EventData*& eventData = impl.mEventData; - if( nullptr != eventData ) + if(nullptr != eventData) { // If popup shown then hide it by switching to Editing state - if( ( EventData::SELECTING == eventData->mState ) || - ( EventData::EDITING_WITH_POPUP == eventData->mState ) || - ( EventData::EDITING_WITH_GRAB_HANDLE == eventData->mState ) || - ( EventData::EDITING_WITH_PASTE_POPUP == eventData->mState ) ) + if((EventData::SELECTING == eventData->mState) || + (EventData::EDITING_WITH_POPUP == eventData->mState) || + (EventData::EDITING_WITH_GRAB_HANDLE == eventData->mState) || + (EventData::EDITING_WITH_PASTE_POPUP == eventData->mState)) { - impl.ChangeState( EventData::EDITING ); + impl.ChangeState(EventData::EDITING); } } - if( !text.empty() ) + if(!text.empty()) { - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; LogicalModelPtr& logicalModel = model->mLogicalModel; - model->mVisualModel->SetTextColor( impl.mTextColor ); + model->mVisualModel->SetTextColor(impl.mTextColor); - MarkupProcessData markupProcessData( logicalModel->mColorRuns, - logicalModel->mFontDescriptionRuns, - logicalModel->mEmbeddedItems ); + MarkupProcessData markupProcessData(logicalModel->mColorRuns, + logicalModel->mFontDescriptionRuns, + logicalModel->mEmbeddedItems); - Length textSize = 0u; - const uint8_t* utf8 = NULL; - if( impl.mMarkupProcessorEnabled ) + Length textSize = 0u; + const uint8_t* utf8 = NULL; + if(impl.mMarkupProcessorEnabled) { - ProcessMarkupString( text, markupProcessData ); + ProcessMarkupString(text, markupProcessData); textSize = markupProcessData.markupProcessedText.size(); // This is a bit horrible but std::string returns a (signed) char* - utf8 = reinterpret_cast( markupProcessData.markupProcessedText.c_str() ); + utf8 = reinterpret_cast(markupProcessData.markupProcessedText.c_str()); } else { textSize = text.size(); // This is a bit horrible but std::string returns a (signed) char* - utf8 = reinterpret_cast( text.c_str() ); + utf8 = reinterpret_cast(text.c_str()); } // Convert text into UTF-32 Vector& utf32Characters = logicalModel->mText; - utf32Characters.Resize( textSize ); + utf32Characters.Resize(textSize); // Transform a text array encoded in utf8 into an array encoded in utf32. // It returns the actual number of characters. - Length characterCount = Utf8ToUtf32( utf8, textSize, utf32Characters.Begin() ); - utf32Characters.Resize( characterCount ); + Length characterCount = Utf8ToUtf32(utf8, textSize, utf32Characters.Begin()); + utf32Characters.Resize(characterCount); - DALI_ASSERT_DEBUG( textSize >= characterCount && "Invalid UTF32 conversion length" ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", &controller, textSize, logicalModel->mText.Count() ); + DALI_ASSERT_DEBUG(textSize >= characterCount && "Invalid UTF32 conversion length"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::SetText %p UTF8 size %d, UTF32 size %d\n", &controller, textSize, logicalModel->mText.Count()); // The characters to be added. impl.mTextUpdateInfo.mNumberOfCharactersToAdd = logicalModel->mText.Count(); @@ -124,7 +120,7 @@ void Controller::TextUpdater::SetText(Controller& controller, const std::string& lastCursorIndex = characterCount; // Update the rest of the model during size negotiation - impl.QueueModifyEvent( ModifyEvent::TEXT_REPLACED ); + impl.QueueModifyEvent(ModifyEvent::TEXT_REPLACED); // The natural size needs to be re-calculated. impl.mRecalculateNaturalSize = true; @@ -141,21 +137,21 @@ void Controller::TextUpdater::SetText(Controller& controller, const std::string& } // Resets the cursor position. - controller.ResetCursorPosition( lastCursorIndex ); + controller.ResetCursorPosition(lastCursorIndex); // Scrolls the text to make the cursor visible. controller.ResetScrollPosition(); impl.RequestRelayout(); - if( nullptr != eventData ) + if(nullptr != eventData) { // Cancel previously queued events eventData->mEventQueue.clear(); } // Do this last since it provides callbacks into application code. - if( NULL != impl.mEditableControlInterface ) + if(NULL != impl.mEditableControlInterface) { impl.mEditableControlInterface->TextChanged(); } @@ -163,105 +159,102 @@ void Controller::TextUpdater::SetText(Controller& controller, const std::string& void Controller::TextUpdater::InsertText(Controller& controller, const std::string& text, Controller::InsertType type) { - Controller::Impl& impl = *controller.mImpl; - EventData*& eventData = impl.mEventData; + Controller::Impl& impl = *controller.mImpl; + EventData*& eventData = impl.mEventData; - DALI_ASSERT_DEBUG( nullptr != eventData && "Unexpected InsertText" ) + DALI_ASSERT_DEBUG(nullptr != eventData && "Unexpected InsertText") - if( NULL == eventData ) + if(NULL == eventData) { return; } - bool removedPrevious = false; - bool removedSelected = false; + bool removedPrevious = false; + bool removedSelected = false; bool maxLengthReached = false; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n", - &controller, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"), - eventData->mPrimaryCursorPosition, eventData->mPreEditFlag, eventData->mPreEditStartPosition, eventData->mPreEditLength ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::InsertText %p %s (%s) mPrimaryCursorPosition %d mPreEditFlag %d mPreEditStartPosition %d mPreEditLength %d\n", &controller, text.c_str(), (COMMIT == type ? "COMMIT" : "PRE_EDIT"), eventData->mPrimaryCursorPosition, eventData->mPreEditFlag, eventData->mPreEditStartPosition, eventData->mPreEditLength); - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; LogicalModelPtr& logicalModel = model->mLogicalModel; // TODO: At the moment the underline runs are only for pre-edit. model->mVisualModel->mUnderlineRuns.Clear(); // Remove the previous InputMethodContext pre-edit. - if( eventData->mPreEditFlag && ( 0u != eventData->mPreEditLength ) ) + if(eventData->mPreEditFlag && (0u != eventData->mPreEditLength)) { - removedPrevious = RemoveText( controller, - -static_cast( eventData->mPrimaryCursorPosition - eventData->mPreEditStartPosition ), - eventData->mPreEditLength, - DONT_UPDATE_INPUT_STYLE ); + removedPrevious = RemoveText(controller, + -static_cast(eventData->mPrimaryCursorPosition - eventData->mPreEditStartPosition), + eventData->mPreEditLength, + DONT_UPDATE_INPUT_STYLE); eventData->mPrimaryCursorPosition = eventData->mPreEditStartPosition; - eventData->mPreEditLength = 0u; + eventData->mPreEditLength = 0u; } else { // Remove the previous Selection. removedSelected = RemoveSelectedText(controller); - } Vector utf32Characters; - Length characterCount = 0u; + Length characterCount = 0u; - if( !text.empty() ) + if(!text.empty()) { // Convert text into UTF-32 - utf32Characters.Resize( text.size() ); + utf32Characters.Resize(text.size()); // This is a bit horrible but std::string returns a (signed) char* - const uint8_t* utf8 = reinterpret_cast( text.c_str() ); + const uint8_t* utf8 = reinterpret_cast(text.c_str()); // Transform a text array encoded in utf8 into an array encoded in utf32. // It returns the actual number of characters. - characterCount = Utf8ToUtf32( utf8, text.size(), utf32Characters.Begin() ); - utf32Characters.Resize( characterCount ); + characterCount = Utf8ToUtf32(utf8, text.size(), utf32Characters.Begin()); + utf32Characters.Resize(characterCount); - DALI_ASSERT_DEBUG( text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length" ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count() ); + DALI_ASSERT_DEBUG(text.size() >= utf32Characters.Count() && "Invalid UTF32 conversion length"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "UTF8 size %d, UTF32 size %d\n", text.size(), utf32Characters.Count()); } - if( 0u != utf32Characters.Count() ) // Check if Utf8ToUtf32 conversion succeeded + if(0u != utf32Characters.Count()) // Check if Utf8ToUtf32 conversion succeeded { // The placeholder text is no longer needed - if( impl.IsShowingPlaceholderText() ) + if(impl.IsShowingPlaceholderText()) { ResetText(controller); } - impl.ChangeState( EventData::EDITING ); + impl.ChangeState(EventData::EDITING); // Handle the InputMethodContext (predicitive text) state changes - if( COMMIT == type ) + if(COMMIT == type) { // InputMethodContext is no longer handling key-events impl.ClearPreEditFlag(); } else // PRE_EDIT { - if( !eventData->mPreEditFlag ) + if(!eventData->mPreEditFlag) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Entered PreEdit state\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Entered PreEdit state\n"); // Record the start of the pre-edit text eventData->mPreEditStartPosition = eventData->mPrimaryCursorPosition; } eventData->mPreEditLength = utf32Characters.Count(); - eventData->mPreEditFlag = true; + eventData->mPreEditFlag = true; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", eventData->mPreEditStartPosition, eventData->mPreEditLength ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "mPreEditStartPosition %d mPreEditLength %d\n", eventData->mPreEditStartPosition, eventData->mPreEditLength); } const Length numberOfCharactersInModel = logicalModel->mText.Count(); // Restrict new text to fit within Maximum characters setting. - Length maxSizeOfNewText = std::min( ( impl.mMaximumNumberOfCharacters - numberOfCharactersInModel ), characterCount ); - maxLengthReached = ( characterCount > maxSizeOfNewText ); + Length maxSizeOfNewText = std::min((impl.mMaximumNumberOfCharacters - numberOfCharactersInModel), characterCount); + maxLengthReached = (characterCount > maxSizeOfNewText); // The cursor position. CharacterIndex& cursorIndex = eventData->mPrimaryCursorPosition; @@ -269,86 +262,86 @@ void Controller::TextUpdater::InsertText(Controller& controller, const std::stri // Update the text's style. // Updates the text style runs by adding characters. - logicalModel->UpdateTextStyleRuns( cursorIndex, maxSizeOfNewText ); + logicalModel->UpdateTextStyleRuns(cursorIndex, maxSizeOfNewText); // Get the character index from the cursor index. - const CharacterIndex styleIndex = ( cursorIndex > 0u ) ? cursorIndex - 1u : 0u; + const CharacterIndex styleIndex = (cursorIndex > 0u) ? cursorIndex - 1u : 0u; // Retrieve the text's style for the given index. InputStyle style; - impl.RetrieveDefaultInputStyle( style ); - logicalModel->RetrieveStyle( styleIndex, style ); + impl.RetrieveDefaultInputStyle(style); + logicalModel->RetrieveStyle(styleIndex, style); InputStyle& inputStyle = eventData->mInputStyle; // Whether to add a new text color run. - const bool addColorRun = ( style.textColor != inputStyle.textColor ) && !inputStyle.isDefaultColor; + const bool addColorRun = (style.textColor != inputStyle.textColor) && !inputStyle.isDefaultColor; // Whether to add a new font run. - const bool addFontNameRun = ( style.familyName != inputStyle.familyName ) && inputStyle.isFamilyDefined; - const bool addFontWeightRun = ( style.weight != inputStyle.weight ) && inputStyle.isWeightDefined; - const bool addFontWidthRun = ( style.width != inputStyle.width ) && inputStyle.isWidthDefined; - const bool addFontSlantRun = ( style.slant != inputStyle.slant ) && inputStyle.isSlantDefined; - const bool addFontSizeRun = ( style.size != inputStyle.size ) && inputStyle.isSizeDefined ; + const bool addFontNameRun = (style.familyName != inputStyle.familyName) && inputStyle.isFamilyDefined; + const bool addFontWeightRun = (style.weight != inputStyle.weight) && inputStyle.isWeightDefined; + const bool addFontWidthRun = (style.width != inputStyle.width) && inputStyle.isWidthDefined; + const bool addFontSlantRun = (style.slant != inputStyle.slant) && inputStyle.isSlantDefined; + const bool addFontSizeRun = (style.size != inputStyle.size) && inputStyle.isSizeDefined; // Add style runs. - if( addColorRun ) + if(addColorRun) { const VectorBase::SizeType numberOfRuns = logicalModel->mColorRuns.Count(); - logicalModel->mColorRuns.Resize( numberOfRuns + 1u ); + logicalModel->mColorRuns.Resize(numberOfRuns + 1u); - ColorRun& colorRun = *( logicalModel->mColorRuns.Begin() + numberOfRuns ); - colorRun.color = inputStyle.textColor; - colorRun.characterRun.characterIndex = cursorIndex; + ColorRun& colorRun = *(logicalModel->mColorRuns.Begin() + numberOfRuns); + colorRun.color = inputStyle.textColor; + colorRun.characterRun.characterIndex = cursorIndex; colorRun.characterRun.numberOfCharacters = maxSizeOfNewText; } - if( addFontNameRun || - addFontWeightRun || - addFontWidthRun || - addFontSlantRun || - addFontSizeRun ) + if(addFontNameRun || + addFontWeightRun || + addFontWidthRun || + addFontSlantRun || + addFontSizeRun) { const VectorBase::SizeType numberOfRuns = logicalModel->mFontDescriptionRuns.Count(); - logicalModel->mFontDescriptionRuns.Resize( numberOfRuns + 1u ); + logicalModel->mFontDescriptionRuns.Resize(numberOfRuns + 1u); - FontDescriptionRun& fontDescriptionRun = *( logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns ); + FontDescriptionRun& fontDescriptionRun = *(logicalModel->mFontDescriptionRuns.Begin() + numberOfRuns); - if( addFontNameRun ) + if(addFontNameRun) { fontDescriptionRun.familyLength = inputStyle.familyName.size(); - fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength]; - memcpy( fontDescriptionRun.familyName, inputStyle.familyName.c_str(), fontDescriptionRun.familyLength ); + fontDescriptionRun.familyName = new char[fontDescriptionRun.familyLength]; + memcpy(fontDescriptionRun.familyName, inputStyle.familyName.c_str(), fontDescriptionRun.familyLength); fontDescriptionRun.familyDefined = true; // The memory allocated for the font family name is freed when the font description is removed from the logical model. } - if( addFontWeightRun ) + if(addFontWeightRun) { - fontDescriptionRun.weight = inputStyle.weight; + fontDescriptionRun.weight = inputStyle.weight; fontDescriptionRun.weightDefined = true; } - if( addFontWidthRun ) + if(addFontWidthRun) { - fontDescriptionRun.width = inputStyle.width; + fontDescriptionRun.width = inputStyle.width; fontDescriptionRun.widthDefined = true; } - if( addFontSlantRun ) + if(addFontSlantRun) { - fontDescriptionRun.slant = inputStyle.slant; + fontDescriptionRun.slant = inputStyle.slant; fontDescriptionRun.slantDefined = true; } - if( addFontSizeRun ) + if(addFontSizeRun) { - fontDescriptionRun.size = static_cast( inputStyle.size * impl.mFontSizeScale * 64.f ); + fontDescriptionRun.size = static_cast(inputStyle.size * impl.mFontSizeScale * 64.f); fontDescriptionRun.sizeDefined = true; } - fontDescriptionRun.characterRun.characterIndex = cursorIndex; + fontDescriptionRun.characterRun.characterIndex = cursorIndex; fontDescriptionRun.characterRun.numberOfCharacters = maxSizeOfNewText; } @@ -356,57 +349,57 @@ void Controller::TextUpdater::InsertText(Controller& controller, const std::stri Vector& modifyText = logicalModel->mText; auto pos = modifyText.End(); - if( cursorIndex < numberOfCharactersInModel ) + if(cursorIndex < numberOfCharactersInModel) { pos = modifyText.Begin() + cursorIndex; } unsigned int realPos = pos - modifyText.Begin(); - modifyText.Insert( pos, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText ); + modifyText.Insert(pos, utf32Characters.Begin(), utf32Characters.Begin() + maxSizeOfNewText); - if( NULL != impl.mEditableControlInterface ) + if(NULL != impl.mEditableControlInterface) { - impl.mEditableControlInterface->TextInserted( realPos, maxSizeOfNewText, text ); + impl.mEditableControlInterface->TextInserted(realPos, maxSizeOfNewText, text); } TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; // Mark the first paragraph to be updated. - if( Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout() ) + if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) { - textUpdateInfo.mCharacterIndex = 0; + textUpdateInfo.mCharacterIndex = 0; textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters; - textUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText; - textUpdateInfo.mClearAll = true; + textUpdateInfo.mNumberOfCharactersToAdd = numberOfCharactersInModel + maxSizeOfNewText; + textUpdateInfo.mClearAll = true; } else { - textUpdateInfo.mCharacterIndex = std::min( cursorIndex, textUpdateInfo.mCharacterIndex ); + textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex); textUpdateInfo.mNumberOfCharactersToAdd += maxSizeOfNewText; } // Update the cursor index. cursorIndex += maxSizeOfNewText; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Inserted %d characters, new size %d new cursor %d\n", maxSizeOfNewText, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition); } - if( ( 0u == logicalModel->mText.Count() ) && - impl.IsPlaceholderAvailable() ) + if((0u == logicalModel->mText.Count()) && + impl.IsPlaceholderAvailable()) { // Show place-holder if empty after removing the pre-edit text controller.ShowPlaceholderText(); eventData->mUpdateCursorPosition = true; impl.ClearPreEditFlag(); } - else if( removedPrevious || - removedSelected || - ( 0 != utf32Characters.Count() ) ) + else if(removedPrevious || + removedSelected || + (0 != utf32Characters.Count())) { // Queue an inserted event - impl.QueueModifyEvent( ModifyEvent::TEXT_INSERTED ); + impl.QueueModifyEvent(ModifyEvent::TEXT_INSERTED); eventData->mUpdateCursorPosition = true; - if( removedSelected ) + if(removedSelected) { eventData->mScrollAfterDelete = true; } @@ -416,13 +409,13 @@ void Controller::TextUpdater::InsertText(Controller& controller, const std::stri } } - if( maxLengthReached ) + if(maxLengthReached) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", logicalModel->mText.Count() ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "MaxLengthReached (%d)\n", logicalModel->mText.Count()); impl.ResetInputMethodContext(); - if( NULL != impl.mEditableControlInterface ) + if(NULL != impl.mEditableControlInterface) { // Do this last since it provides callbacks into application code impl.mEditableControlInterface->MaxLengthReached(); @@ -432,12 +425,12 @@ void Controller::TextUpdater::InsertText(Controller& controller, const std::stri void Controller::TextUpdater::PasteText(Controller& controller, const std::string& stringToPaste) { - InsertText( controller, stringToPaste, Text::Controller::COMMIT ); + InsertText(controller, stringToPaste, Text::Controller::COMMIT); Controller::Impl& impl = *controller.mImpl; - impl.ChangeState( EventData::EDITING ); + impl.ChangeState(EventData::EDITING); impl.RequestRelayout(); - if( NULL != impl.mEditableControlInterface ) + if(NULL != impl.mEditableControlInterface) { // Do this last since it provides callbacks into application code impl.mEditableControlInterface->TextChanged(); @@ -445,127 +438,126 @@ void Controller::TextUpdater::PasteText(Controller& controller, const std::strin } bool Controller::TextUpdater::RemoveText( - Controller& controller, - int cursorOffset, - int numberOfCharacters, - UpdateInputStyleType type ) + Controller& controller, + int cursorOffset, + int numberOfCharacters, + UpdateInputStyleType type) { bool removed = false; - Controller::Impl& impl = *controller.mImpl; - EventData*& eventData = impl.mEventData; + Controller::Impl& impl = *controller.mImpl; + EventData*& eventData = impl.mEventData; - if( nullptr == eventData ) + if(nullptr == eventData) { return removed; } - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; LogicalModelPtr& logicalModel = model->mLogicalModel; - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n", - &controller, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p mText.Count() %d cursor %d cursorOffset %d numberOfCharacters %d\n", &controller, logicalModel->mText.Count(), eventData->mPrimaryCursorPosition, cursorOffset, numberOfCharacters); - if( !impl.IsShowingPlaceholderText() ) + if(!impl.IsShowingPlaceholderText()) { // Delete at current cursor position - Vector& currentText = logicalModel->mText; - CharacterIndex& oldCursorIndex = eventData->mPrimaryCursorPosition; + Vector& currentText = logicalModel->mText; + CharacterIndex& oldCursorIndex = eventData->mPrimaryCursorPosition; CharacterIndex cursorIndex = 0; // Validate the cursor position & number of characters - if( ( static_cast< int >( eventData->mPrimaryCursorPosition ) + cursorOffset ) >= 0 ) + if((static_cast(eventData->mPrimaryCursorPosition) + cursorOffset) >= 0) { cursorIndex = eventData->mPrimaryCursorPosition + cursorOffset; } - if( ( cursorIndex + numberOfCharacters ) > currentText.Count() ) + if((cursorIndex + numberOfCharacters) > currentText.Count()) { numberOfCharacters = currentText.Count() - cursorIndex; } TextUpdateInfo& textUpdateInfo = impl.mTextUpdateInfo; - if( eventData->mPreEditFlag || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time. - ( ( cursorIndex + numberOfCharacters ) <= textUpdateInfo.mPreviousNumberOfCharacters ) ) + if(eventData->mPreEditFlag || // If the preedit flag is enabled, it means two (or more) of them came together i.e. when two keys have been pressed at the same time. + ((cursorIndex + numberOfCharacters) <= textUpdateInfo.mPreviousNumberOfCharacters)) { // Mark the paragraphs to be updated. - if( Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout() ) + if(Layout::Engine::SINGLE_LINE_BOX == impl.mLayoutEngine.GetLayout()) { - textUpdateInfo.mCharacterIndex = 0; + textUpdateInfo.mCharacterIndex = 0; textUpdateInfo.mNumberOfCharactersToRemove = textUpdateInfo.mPreviousNumberOfCharacters; - textUpdateInfo.mNumberOfCharactersToAdd = textUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters; - textUpdateInfo.mClearAll = true; + textUpdateInfo.mNumberOfCharactersToAdd = textUpdateInfo.mPreviousNumberOfCharacters - numberOfCharacters; + textUpdateInfo.mClearAll = true; } else { - textUpdateInfo.mCharacterIndex = std::min( cursorIndex, textUpdateInfo.mCharacterIndex ); + textUpdateInfo.mCharacterIndex = std::min(cursorIndex, textUpdateInfo.mCharacterIndex); textUpdateInfo.mNumberOfCharactersToRemove += numberOfCharacters; } // Update the input style and remove the text's style before removing the text. - if( UPDATE_INPUT_STYLE == type ) + if(UPDATE_INPUT_STYLE == type) { InputStyle& eventDataInputStyle = eventData->mInputStyle; // Keep a copy of the current input style. InputStyle currentInputStyle; - currentInputStyle.Copy( eventDataInputStyle ); + currentInputStyle.Copy(eventDataInputStyle); // Set first the default input style. - impl.RetrieveDefaultInputStyle( eventDataInputStyle ); + impl.RetrieveDefaultInputStyle(eventDataInputStyle); // Update the input style. - logicalModel->RetrieveStyle( cursorIndex, eventDataInputStyle ); + logicalModel->RetrieveStyle(cursorIndex, eventDataInputStyle); // Compare if the input style has changed. - const bool hasInputStyleChanged = !currentInputStyle.Equal( eventDataInputStyle ); + const bool hasInputStyleChanged = !currentInputStyle.Equal(eventDataInputStyle); - if( hasInputStyleChanged ) + if(hasInputStyleChanged) { - const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask( eventDataInputStyle ); + const InputStyle::Mask styleChangedMask = currentInputStyle.GetInputStyleChangeMask(eventDataInputStyle); // Queue the input style changed signal. - eventData->mInputStyleChangedQueue.PushBack( styleChangedMask ); + eventData->mInputStyleChangedQueue.PushBack(styleChangedMask); } } // If the number of current text and the number of characters to be deleted are same, // it means all texts should be removed and all Preedit variables should be initialized. - if( ( currentText.Count() - numberOfCharacters == 0 ) && ( cursorIndex == 0 ) ) + if((currentText.Count() - numberOfCharacters == 0) && (cursorIndex == 0)) { impl.ClearPreEditFlag(); textUpdateInfo.mNumberOfCharactersToAdd = 0; } // Updates the text style runs by removing characters. Runs with no characters are removed. - logicalModel->UpdateTextStyleRuns( cursorIndex, -numberOfCharacters ); + logicalModel->UpdateTextStyleRuns(cursorIndex, -numberOfCharacters); // Remove the characters. Vector::Iterator first = currentText.Begin() + cursorIndex; Vector::Iterator last = first + numberOfCharacters; - if( NULL != impl.mEditableControlInterface ) + if(NULL != impl.mEditableControlInterface) { std::string utf8; - Utf32ToUtf8( first, numberOfCharacters, utf8 ); - impl.mEditableControlInterface->TextDeleted( cursorIndex, numberOfCharacters, utf8 ); + Utf32ToUtf8(first, numberOfCharacters, utf8); + impl.mEditableControlInterface->TextDeleted(cursorIndex, numberOfCharacters, utf8); } - currentText.Erase( first, last ); + currentText.Erase(first, last); // Cursor position retreat oldCursorIndex = cursorIndex; eventData->mScrollAfterDelete = true; - if( EventData::INACTIVE == eventData->mState ) + if(EventData::INACTIVE == eventData->mState) { - impl.ChangeState( EventData::EDITING ); + impl.ChangeState(EventData::EDITING); } - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", &controller, numberOfCharacters ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::RemoveText %p removed %d\n", &controller, numberOfCharacters); removed = true; } } @@ -575,19 +567,19 @@ bool Controller::TextUpdater::RemoveText( bool Controller::TextUpdater::RemoveSelectedText(Controller& controller) { - bool textRemoved( false ); + bool textRemoved(false); Controller::Impl& impl = *controller.mImpl; - if( EventData::SELECTING == impl.mEventData->mState ) + if(EventData::SELECTING == impl.mEventData->mState) { std::string removedString; - impl.RetrieveSelection( removedString, true ); + impl.RetrieveSelection(removedString, true); - if( !removedString.empty() ) + if(!removedString.empty()) { textRemoved = true; - impl.ChangeState( EventData::EDITING ); + impl.ChangeState(EventData::EDITING); } } @@ -596,8 +588,8 @@ bool Controller::TextUpdater::RemoveSelectedText(Controller& controller) void Controller::TextUpdater::ResetText(Controller& controller) { - Controller::Impl& impl = *controller.mImpl; - LogicalModelPtr& logicalModel = impl.mModel->mLogicalModel; + Controller::Impl& impl = *controller.mImpl; + LogicalModelPtr& logicalModel = impl.mModel->mLogicalModel; // Reset buffers. logicalModel->mText.Clear(); @@ -608,9 +600,9 @@ void Controller::TextUpdater::ResetText(Controller& controller) // We have cleared everything including the placeholder-text impl.PlaceholderCleared(); - impl.mTextUpdateInfo.mCharacterIndex = 0u; + impl.mTextUpdateInfo.mCharacterIndex = 0u; impl.mTextUpdateInfo.mNumberOfCharactersToRemove = impl.mTextUpdateInfo.mPreviousNumberOfCharacters; - impl.mTextUpdateInfo.mNumberOfCharactersToAdd = 0u; + impl.mTextUpdateInfo.mNumberOfCharactersToAdd = 0u; // Clear any previous text. impl.mTextUpdateInfo.mClearAll = true; diff --git a/dali-toolkit/internal/text/text-controller.cpp b/dali-toolkit/internal/text/text-controller.cpp index bcff10f..f29ab22 100644 --- a/dali-toolkit/internal/text/text-controller.cpp +++ b/dali-toolkit/internal/text/text-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,10 +19,10 @@ #include // EXTERNAL INCLUDES -#include -#include -#include #include +#include +#include +#include // INTERNAL INCLUDES #include @@ -35,7 +35,6 @@ namespace { - #if defined(DEBUG_ENABLED) Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif @@ -44,53 +43,50 @@ constexpr float MAX_FLOAT = std::numeric_limits::max(); const std::string EMPTY_STRING(""); -int ConvertPixelToPint( float pixel ) +int ConvertPixelToPint(float pixel) { - unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - Dali::TextAbstraction::FontClient fontClient = Dali::TextAbstraction::FontClient::Get(); - fontClient.GetDpi( horizontalDpi, verticalDpi ); + unsigned int horizontalDpi = 0u; + unsigned int verticalDpi = 0u; + Dali::TextAbstraction::FontClient fontClient = Dali::TextAbstraction::FontClient::Get(); + fontClient.GetDpi(horizontalDpi, verticalDpi); - return ( pixel * 72.f ) / static_cast< float >( horizontalDpi ); + return (pixel * 72.f) / static_cast(horizontalDpi); } } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - // public : Constructor. ControllerPtr Controller::New() { - return ControllerPtr( new Controller() ); + return ControllerPtr(new Controller()); } -ControllerPtr Controller::New( ControlInterface* controlInterface ) +ControllerPtr Controller::New(ControlInterface* controlInterface) { - return ControllerPtr( new Controller( controlInterface ) ); + return ControllerPtr(new Controller(controlInterface)); } -ControllerPtr Controller::New( ControlInterface* controlInterface, - EditableControlInterface* editableControlInterface, - SelectableControlInterface* selectableControlInterface ) +ControllerPtr Controller::New(ControlInterface* controlInterface, + EditableControlInterface* editableControlInterface, + SelectableControlInterface* selectableControlInterface) { - return ControllerPtr( new Controller( controlInterface, - editableControlInterface, - selectableControlInterface ) ); + return ControllerPtr(new Controller(controlInterface, + editableControlInterface, + selectableControlInterface)); } // public : Configure the text controller. -void Controller::EnableTextInput( DecoratorPtr decorator, InputMethodContext& inputMethodContext ) +void Controller::EnableTextInput(DecoratorPtr decorator, InputMethodContext& inputMethodContext) { - if( !decorator ) + if(!decorator) { delete mImpl->mEventData; mImpl->mEventData = NULL; @@ -99,16 +95,16 @@ void Controller::EnableTextInput( DecoratorPtr decorator, InputMethodContext& in return; } - if( NULL == mImpl->mEventData ) + if(NULL == mImpl->mEventData) { - mImpl->mEventData = new EventData( decorator, inputMethodContext ); + mImpl->mEventData = new EventData(decorator, inputMethodContext); } } -void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType ) +void Controller::SetGlyphType(TextAbstraction::GlyphType glyphType) { // Metrics for bitmap & vector based glyphs are different - mImpl->mMetrics->SetGlyphType( glyphType ); + mImpl->mMetrics->SetGlyphType(glyphType); // Clear the font-specific data ClearFontData(); @@ -116,15 +112,15 @@ void Controller::SetGlyphType( TextAbstraction::GlyphType glyphType ) mImpl->RequestRelayout(); } -void Controller::SetMarkupProcessorEnabled( bool enable ) +void Controller::SetMarkupProcessorEnabled(bool enable) { - if( enable != mImpl->mMarkupProcessorEnabled ) + if(enable != mImpl->mMarkupProcessorEnabled) { //If Text was already set, call the SetText again for enabling or disabling markup mImpl->mMarkupProcessorEnabled = enable; std::string text; - GetText( text ); - SetText( text ); + GetText(text); + SetText(text); } } @@ -133,31 +129,30 @@ bool Controller::IsMarkupProcessorEnabled() const return mImpl->mMarkupProcessorEnabled; } -void Controller::SetAutoScrollEnabled( bool enable ) +void Controller::SetAutoScrollEnabled(bool enable) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable)?"true":"false", ( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX)?"true":"false", this ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled[%s] SingleBox[%s]-> [%p]\n", (enable) ? "true" : "false", (mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX) ? "true" : "false", this); - if( mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX ) + if(mImpl->mLayoutEngine.GetLayout() == Layout::Engine::SINGLE_LINE_BOX) { - if( enable ) + if(enable) { - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n" ); - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | - LAYOUT | - ALIGN | - UPDATE_LAYOUT_SIZE | - UPDATE_DIRECTION | - REORDER ); - + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled for SINGLE_LINE_BOX\n"); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | + LAYOUT | + ALIGN | + UPDATE_LAYOUT_SIZE | + UPDATE_DIRECTION | + REORDER); } else { - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n"); - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | - LAYOUT | - ALIGN | - UPDATE_LAYOUT_SIZE | - REORDER ); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetAutoScrollEnabled Disabling autoscroll\n"); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | + LAYOUT | + ALIGN | + UPDATE_LAYOUT_SIZE | + REORDER); } mImpl->mIsAutoScrollEnabled = enable; @@ -165,14 +160,14 @@ void Controller::SetAutoScrollEnabled( bool enable ) } else { - DALI_LOG_WARNING( "Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n" ); + DALI_LOG_WARNING("Attempted AutoScrolling on a non SINGLE_LINE_BOX, request ignored\n"); mImpl->mIsAutoScrollEnabled = false; } } bool Controller::IsAutoScrollEnabled() const { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled?"true":"false" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::IsAutoScrollEnabled[%s]\n", mImpl->mIsAutoScrollEnabled ? "true" : "false"); return mImpl->mIsAutoScrollEnabled; } @@ -186,27 +181,27 @@ float Controller::GetAutoScrollLineAlignment() const { float offset = 0.f; - if( mImpl->mModel->mVisualModel && - ( 0u != mImpl->mModel->mVisualModel->mLines.Count() ) ) + if(mImpl->mModel->mVisualModel && + (0u != mImpl->mModel->mVisualModel->mLines.Count())) { - offset = ( *mImpl->mModel->mVisualModel->mLines.Begin() ).alignmentOffset; + offset = (*mImpl->mModel->mVisualModel->mLines.Begin()).alignmentOffset; } return offset; } -void Controller::SetHorizontalScrollEnabled( bool enable ) +void Controller::SetHorizontalScrollEnabled(bool enable) { - if( ( NULL != mImpl->mEventData ) && - mImpl->mEventData->mDecorator ) + if((NULL != mImpl->mEventData) && + mImpl->mEventData->mDecorator) { - mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled( enable ); + mImpl->mEventData->mDecorator->SetHorizontalScrollEnabled(enable); } } bool Controller::IsHorizontalScrollEnabled() const { - if( ( NULL != mImpl->mEventData ) && - mImpl->mEventData->mDecorator ) + if((NULL != mImpl->mEventData) && + mImpl->mEventData->mDecorator) { return mImpl->mEventData->mDecorator->IsHorizontalScrollEnabled(); } @@ -214,22 +209,22 @@ bool Controller::IsHorizontalScrollEnabled() const return false; } -void Controller::SetVerticalScrollEnabled( bool enable ) +void Controller::SetVerticalScrollEnabled(bool enable) { - if( ( NULL != mImpl->mEventData ) && - mImpl->mEventData->mDecorator ) + if((NULL != mImpl->mEventData) && + mImpl->mEventData->mDecorator) { - if( mImpl->mEventData->mDecorator ) + if(mImpl->mEventData->mDecorator) { - mImpl->mEventData->mDecorator->SetVerticalScrollEnabled( enable ); + mImpl->mEventData->mDecorator->SetVerticalScrollEnabled(enable); } } } bool Controller::IsVerticalScrollEnabled() const { - if( ( NULL != mImpl->mEventData ) && - mImpl->mEventData->mDecorator ) + if((NULL != mImpl->mEventData) && + mImpl->mEventData->mDecorator) { return mImpl->mEventData->mDecorator->IsVerticalScrollEnabled(); } @@ -237,19 +232,19 @@ bool Controller::IsVerticalScrollEnabled() const return false; } -void Controller::SetSmoothHandlePanEnabled( bool enable ) +void Controller::SetSmoothHandlePanEnabled(bool enable) { - if( ( NULL != mImpl->mEventData ) && - mImpl->mEventData->mDecorator ) + if((NULL != mImpl->mEventData) && + mImpl->mEventData->mDecorator) { - mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled( enable ); + mImpl->mEventData->mDecorator->SetSmoothHandlePanEnabled(enable); } } bool Controller::IsSmoothHandlePanEnabled() const { - if( ( NULL != mImpl->mEventData ) && - mImpl->mEventData->mDecorator ) + if((NULL != mImpl->mEventData) && + mImpl->mEventData->mDecorator) { return mImpl->mEventData->mDecorator->IsSmoothHandlePanEnabled(); } @@ -257,7 +252,7 @@ bool Controller::IsSmoothHandlePanEnabled() const return false; } -void Controller::SetMaximumNumberOfCharacters( Length maxCharacters ) +void Controller::SetMaximumNumberOfCharacters(Length maxCharacters) { mImpl->mMaximumNumberOfCharacters = maxCharacters; } @@ -267,16 +262,16 @@ int Controller::GetMaximumNumberOfCharacters() return mImpl->mMaximumNumberOfCharacters; } -void Controller::SetEnableCursorBlink( bool enable ) +void Controller::SetEnableCursorBlink(bool enable) { - DALI_ASSERT_DEBUG( NULL != mImpl->mEventData && "TextInput disabled" ); + DALI_ASSERT_DEBUG(NULL != mImpl->mEventData && "TextInput disabled"); - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mCursorBlinkEnabled = enable; - if( !enable && - mImpl->mEventData->mDecorator ) + if(!enable && + mImpl->mEventData->mDecorator) { mImpl->mEventData->mDecorator->StopCursorBlink(); } @@ -285,7 +280,7 @@ void Controller::SetEnableCursorBlink( bool enable ) bool Controller::GetEnableCursorBlink() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mCursorBlinkEnabled; } @@ -293,23 +288,23 @@ bool Controller::GetEnableCursorBlink() const return false; } -void Controller::SetMultiLineEnabled( bool enable ) +void Controller::SetMultiLineEnabled(bool enable) { const Layout::Engine::Type layout = enable ? Layout::Engine::MULTI_LINE_BOX : Layout::Engine::SINGLE_LINE_BOX; - if( layout != mImpl->mLayoutEngine.GetLayout() ) + if(layout != mImpl->mLayoutEngine.GetLayout()) { // Set the layout type. - mImpl->mLayoutEngine.SetLayout( layout ); + mImpl->mLayoutEngine.SetLayout(layout); // Set the flags to redo the layout operations - const OperationsMask layoutOperations = static_cast( LAYOUT | - UPDATE_LAYOUT_SIZE | - ALIGN | - REORDER ); + const OperationsMask layoutOperations = static_cast(LAYOUT | + UPDATE_LAYOUT_SIZE | + ALIGN | + REORDER); mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true; - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | layoutOperations ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | layoutOperations); // Need to recalculate natural size mImpl->mRecalculateNaturalSize = true; @@ -323,24 +318,24 @@ bool Controller::IsMultiLineEnabled() const return Layout::Engine::MULTI_LINE_BOX == mImpl->mLayoutEngine.GetLayout(); } -void Controller::SetHorizontalAlignment( Text::HorizontalAlignment::Type alignment ) +void Controller::SetHorizontalAlignment(Text::HorizontalAlignment::Type alignment) { - if( alignment != mImpl->mModel->mHorizontalAlignment ) + if(alignment != mImpl->mModel->mHorizontalAlignment) { // Set the alignment. mImpl->mModel->mHorizontalAlignment = alignment; // Set the flag to redo the alignment operation. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | ALIGN ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | ALIGN); - if( mImpl->mEventData ) + if(mImpl->mEventData) { mImpl->mEventData->mUpdateAlignment = true; // Update the cursor if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->ChangeState( EventData::EDITING ); + mImpl->ChangeState(EventData::EDITING); mImpl->mEventData->mUpdateCursorPosition = true; } } @@ -354,14 +349,14 @@ Text::HorizontalAlignment::Type Controller::GetHorizontalAlignment() const return mImpl->mModel->mHorizontalAlignment; } -void Controller::SetVerticalAlignment( VerticalAlignment::Type alignment ) +void Controller::SetVerticalAlignment(VerticalAlignment::Type alignment) { - if( alignment != mImpl->mModel->mVerticalAlignment ) + if(alignment != mImpl->mModel->mVerticalAlignment) { // Set the alignment. mImpl->mModel->mVerticalAlignment = alignment; - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | ALIGN ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | ALIGN); mImpl->RequestRelayout(); } @@ -377,7 +372,7 @@ bool Controller::IsIgnoreSpacesAfterText() const return mImpl->mModel->mIgnoreSpacesAfterText; } -void Controller::SetIgnoreSpacesAfterText( bool ignore ) +void Controller::SetIgnoreSpacesAfterText(bool ignore) { mImpl->mModel->mIgnoreSpacesAfterText = ignore; } @@ -387,12 +382,12 @@ bool Controller::IsMatchSystemLanguageDirection() const return mImpl->mModel->mMatchSystemLanguageDirection; } -void Controller::SetMatchSystemLanguageDirection( bool match ) +void Controller::SetMatchSystemLanguageDirection(bool match) { mImpl->mModel->mMatchSystemLanguageDirection = match; } -void Controller::SetLayoutDirection( Dali::LayoutDirection::Type layoutDirection ) +void Controller::SetLayoutDirection(Dali::LayoutDirection::Type layoutDirection) { mImpl->mLayoutDirection = layoutDirection; } @@ -402,24 +397,22 @@ bool Controller::IsShowingRealText() const return mImpl->IsShowingRealText(); } - -void Controller::SetLineWrapMode( Text::LineWrap::Mode lineWrapMode ) +void Controller::SetLineWrapMode(Text::LineWrap::Mode lineWrapMode) { - if( lineWrapMode != mImpl->mModel->mLineWrapMode ) + if(lineWrapMode != mImpl->mModel->mLineWrapMode) { // Set the text wrap mode. mImpl->mModel->mLineWrapMode = lineWrapMode; - // Update Text layout for applying wrap mode - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | - ALIGN | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER ); - mImpl->mTextUpdateInfo.mCharacterIndex = 0u; + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | + ALIGN | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER); + mImpl->mTextUpdateInfo.mCharacterIndex = 0u; mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count(); + mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count(); // Request relayout mImpl->RequestRelayout(); @@ -431,7 +424,7 @@ Text::LineWrap::Mode Controller::GetLineWrapMode() const return mImpl->mModel->mLineWrapMode; } -void Controller::SetTextElideEnabled( bool enabled ) +void Controller::SetTextElideEnabled(bool enabled) { mImpl->mModel->mElideEnabled = enabled; } @@ -451,9 +444,9 @@ bool Controller::IsTextFitEnabled() const return mImpl->mTextFitEnabled; } -void Controller::SetTextFitMinSize( float minSize, FontSizeType type ) +void Controller::SetTextFitMinSize(float minSize, FontSizeType type) { - switch( type ) + switch(type) { case POINT_SIZE: { @@ -462,7 +455,7 @@ void Controller::SetTextFitMinSize( float minSize, FontSizeType type ) } case PIXEL_SIZE: { - mImpl->mTextFitMinSize = ConvertPixelToPint( minSize ); + mImpl->mTextFitMinSize = ConvertPixelToPint(minSize); break; } } @@ -473,9 +466,9 @@ float Controller::GetTextFitMinSize() const return mImpl->mTextFitMinSize; } -void Controller::SetTextFitMaxSize( float maxSize, FontSizeType type ) +void Controller::SetTextFitMaxSize(float maxSize, FontSizeType type) { - switch( type ) + switch(type) { case POINT_SIZE: { @@ -484,7 +477,7 @@ void Controller::SetTextFitMaxSize( float maxSize, FontSizeType type ) } case PIXEL_SIZE: { - mImpl->mTextFitMaxSize = ConvertPixelToPint( maxSize ); + mImpl->mTextFitMaxSize = ConvertPixelToPint(maxSize); break; } } @@ -495,9 +488,9 @@ float Controller::GetTextFitMaxSize() const return mImpl->mTextFitMaxSize; } -void Controller::SetTextFitStepSize( float step, FontSizeType type ) +void Controller::SetTextFitStepSize(float step, FontSizeType type) { - switch( type ) + switch(type) { case POINT_SIZE: { @@ -506,7 +499,7 @@ void Controller::SetTextFitStepSize( float step, FontSizeType type ) } case PIXEL_SIZE: { - mImpl->mTextFitStepSize = ConvertPixelToPint( step ); + mImpl->mTextFitStepSize = ConvertPixelToPint(step); break; } } @@ -527,7 +520,7 @@ Vector2 Controller::GetTextFitContentSize() const return mImpl->mTextFitContentSize; } -void Controller::SetPlaceholderTextElideEnabled( bool enabled ) +void Controller::SetPlaceholderTextElideEnabled(bool enabled) { PlaceholderHandler::SetPlaceholderTextElideEnabled(*this, enabled); } @@ -537,7 +530,7 @@ bool Controller::IsPlaceholderTextElideEnabled() const return PlaceholderHandler::IsPlaceholderTextElideEnabled(*this); } -void Controller::SetSelectionEnabled( bool enabled ) +void Controller::SetSelectionEnabled(bool enabled) { mImpl->mEventData->mSelectionEnabled = enabled; } @@ -547,7 +540,7 @@ bool Controller::IsSelectionEnabled() const return mImpl->mEventData->mSelectionEnabled; } -void Controller::SetShiftSelectionEnabled( bool enabled ) +void Controller::SetShiftSelectionEnabled(bool enabled) { mImpl->mEventData->mShiftSelectionFlag = enabled; } @@ -557,7 +550,7 @@ bool Controller::IsShiftSelectionEnabled() const return mImpl->mEventData->mShiftSelectionFlag; } -void Controller::SetGrabHandleEnabled( bool enabled ) +void Controller::SetGrabHandleEnabled(bool enabled) { mImpl->mEventData->mGrabHandleEnabled = enabled; } @@ -579,41 +572,41 @@ bool Controller::IsGrabHandlePopupEnabled() const // public : Update -void Controller::SetText( const std::string& text ) +void Controller::SetText(const std::string& text) { TextUpdater::SetText(*this, text); } -void Controller::GetText( std::string& text ) const +void Controller::GetText(std::string& text) const { - if( !mImpl->IsShowingPlaceholderText() ) + if(!mImpl->IsShowingPlaceholderText()) { // Retrieves the text string. - mImpl->GetText( 0u, text ); + mImpl->GetText(0u, text); } else { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::GetText %p empty (but showing placeholder)\n", this); } } -void Controller::SetPlaceholderText( PlaceholderType type, const std::string& text ) +void Controller::SetPlaceholderText(PlaceholderType type, const std::string& text) { PlaceholderHandler::SetPlaceholderText(*this, type, text); } -void Controller::GetPlaceholderText( PlaceholderType type, std::string& text ) const +void Controller::GetPlaceholderText(PlaceholderType type, std::string& text) const { - PlaceholderHandler::GetPlaceholderText(*this, type, text ); + PlaceholderHandler::GetPlaceholderText(*this, type, text); } -void Controller::UpdateAfterFontChange( const std::string& newDefaultFont ) +void Controller::UpdateAfterFontChange(const std::string& newDefaultFont) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n"); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Controller::UpdateAfterFontChange\n"); - if( !mImpl->mFontDefaults->familyDefined ) // If user defined font then should not update when system font changes + if(!mImpl->mFontDefaults->familyDefined) // If user defined font then should not update when system font changes { - DALI_LOG_INFO( gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str() ); + DALI_LOG_INFO(gLogFilter, Debug::Concise, "Controller::UpdateAfterFontChange newDefaultFont(%s)\n", newDefaultFont.c_str()); mImpl->mFontDefaults->mFontDescription.family = newDefaultFont; ClearFontData(); @@ -622,50 +615,50 @@ void Controller::UpdateAfterFontChange( const std::string& newDefaultFont ) } } -void Controller::RetrieveSelection( std::string& selectedText ) const +void Controller::RetrieveSelection(std::string& selectedText) const { - mImpl->RetrieveSelection( selectedText, false ); + mImpl->RetrieveSelection(selectedText, false); } -void Controller::SetSelection( int start, int end ) +void Controller::SetSelection(int start, int end) { - mImpl->SetSelection( start, end ); + mImpl->SetSelection(start, end); } -std::pair< int, int > Controller::GetSelectionIndexes() const +std::pair Controller::GetSelectionIndexes() const { return mImpl->GetSelectionIndexes(); } -void Controller::CopyStringToClipboard( const std::string& source ) +void Controller::CopyStringToClipboard(const std::string& source) { - mImpl->CopyStringToClipboard( source ); + mImpl->CopyStringToClipboard(source); } -void Controller::SendSelectionToClipboard( bool deleteAfterSending ) +void Controller::SendSelectionToClipboard(bool deleteAfterSending) { - mImpl->SendSelectionToClipboard( deleteAfterSending ); + mImpl->SendSelectionToClipboard(deleteAfterSending); } // public : Default style & Input style -void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily ) +void Controller::SetDefaultFontFamily(const std::string& defaultFontFamily) { - if( NULL == mImpl->mFontDefaults ) + if(NULL == mImpl->mFontDefaults) { mImpl->mFontDefaults = new FontDefaults(); } mImpl->mFontDefaults->mFontDescription.family = defaultFontFamily; - DALI_LOG_INFO( gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str()); + DALI_LOG_INFO(gLogFilter, Debug::General, "Controller::SetDefaultFontFamily %s\n", defaultFontFamily.c_str()); mImpl->mFontDefaults->familyDefined = !defaultFontFamily.empty(); - if( mImpl->mEventData ) + if(mImpl->mEventData) { // Update the cursor position if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->mEventData->mDecoratorUpdated = true; + mImpl->mEventData->mDecoratorUpdated = true; mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font family is updated. } } @@ -678,7 +671,7 @@ void Controller::SetDefaultFontFamily( const std::string& defaultFontFamily ) const std::string& Controller::GetDefaultFontFamily() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->mFontDescription.family; } @@ -686,7 +679,7 @@ const std::string& Controller::GetDefaultFontFamily() const return EMPTY_STRING; } -void Controller::SetPlaceholderFontFamily( const std::string& placeholderTextFontFamily ) +void Controller::SetPlaceholderFontFamily(const std::string& placeholderTextFontFamily) { PlaceholderHandler::SetPlaceholderFontFamily(*this, placeholderTextFontFamily); } @@ -696,22 +689,22 @@ const std::string& Controller::GetPlaceholderFontFamily() const return PlaceholderHandler::GetPlaceholderFontFamily(*this); } -void Controller::SetDefaultFontWeight( FontWeight weight ) +void Controller::SetDefaultFontWeight(FontWeight weight) { - if( NULL == mImpl->mFontDefaults ) + if(NULL == mImpl->mFontDefaults) { mImpl->mFontDefaults = new FontDefaults(); } mImpl->mFontDefaults->mFontDescription.weight = weight; - mImpl->mFontDefaults->weightDefined = true; + mImpl->mFontDefaults->weightDefined = true; - if( mImpl->mEventData ) + if(mImpl->mEventData) { // Update the cursor position if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->mEventData->mDecoratorUpdated = true; + mImpl->mEventData->mDecoratorUpdated = true; mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font weight is updated. } } @@ -724,7 +717,7 @@ void Controller::SetDefaultFontWeight( FontWeight weight ) bool Controller::IsDefaultFontWeightDefined() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->weightDefined; } @@ -734,7 +727,7 @@ bool Controller::IsDefaultFontWeightDefined() const FontWeight Controller::GetDefaultFontWeight() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->mFontDescription.weight; } @@ -742,14 +735,15 @@ FontWeight Controller::GetDefaultFontWeight() const return TextAbstraction::FontWeight::NORMAL; } -void Controller::SetPlaceholderTextFontWeight( FontWeight weight ) +void Controller::SetPlaceholderTextFontWeight(FontWeight weight) { PlaceholderHandler::SetPlaceholderTextFontWeight(*this, weight); } bool Controller::IsPlaceholderTextFontWeightDefined() const { - return PlaceholderHandler::IsPlaceholderTextFontWeightDefined(*this);; + return PlaceholderHandler::IsPlaceholderTextFontWeightDefined(*this); + ; } FontWeight Controller::GetPlaceholderTextFontWeight() const @@ -757,22 +751,22 @@ FontWeight Controller::GetPlaceholderTextFontWeight() const return PlaceholderHandler::GetPlaceholderTextFontWeight(*this); } -void Controller::SetDefaultFontWidth( FontWidth width ) +void Controller::SetDefaultFontWidth(FontWidth width) { - if( NULL == mImpl->mFontDefaults ) + if(NULL == mImpl->mFontDefaults) { mImpl->mFontDefaults = new FontDefaults(); } mImpl->mFontDefaults->mFontDescription.width = width; - mImpl->mFontDefaults->widthDefined = true; + mImpl->mFontDefaults->widthDefined = true; - if( mImpl->mEventData ) + if(mImpl->mEventData) { // Update the cursor position if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->mEventData->mDecoratorUpdated = true; + mImpl->mEventData->mDecoratorUpdated = true; mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font width is updated. } } @@ -785,7 +779,7 @@ void Controller::SetDefaultFontWidth( FontWidth width ) bool Controller::IsDefaultFontWidthDefined() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->widthDefined; } @@ -795,7 +789,7 @@ bool Controller::IsDefaultFontWidthDefined() const FontWidth Controller::GetDefaultFontWidth() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->mFontDescription.width; } @@ -803,7 +797,7 @@ FontWidth Controller::GetDefaultFontWidth() const return TextAbstraction::FontWidth::NORMAL; } -void Controller::SetPlaceholderTextFontWidth( FontWidth width ) +void Controller::SetPlaceholderTextFontWidth(FontWidth width) { PlaceholderHandler::SetPlaceholderTextFontWidth(*this, width); } @@ -818,22 +812,22 @@ FontWidth Controller::GetPlaceholderTextFontWidth() const return PlaceholderHandler::GetPlaceholderTextFontWidth(*this); } -void Controller::SetDefaultFontSlant( FontSlant slant ) +void Controller::SetDefaultFontSlant(FontSlant slant) { - if( NULL == mImpl->mFontDefaults ) + if(NULL == mImpl->mFontDefaults) { mImpl->mFontDefaults = new FontDefaults(); } mImpl->mFontDefaults->mFontDescription.slant = slant; - mImpl->mFontDefaults->slantDefined = true; + mImpl->mFontDefaults->slantDefined = true; - if( mImpl->mEventData ) + if(mImpl->mEventData) { // Update the cursor position if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->mEventData->mDecoratorUpdated = true; + mImpl->mEventData->mDecoratorUpdated = true; mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font slant is updated. } } @@ -846,7 +840,7 @@ void Controller::SetDefaultFontSlant( FontSlant slant ) bool Controller::IsDefaultFontSlantDefined() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->slantDefined; } @@ -855,7 +849,7 @@ bool Controller::IsDefaultFontSlantDefined() const FontSlant Controller::GetDefaultFontSlant() const { - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { return mImpl->mFontDefaults->mFontDescription.slant; } @@ -863,7 +857,7 @@ FontSlant Controller::GetDefaultFontSlant() const return TextAbstraction::FontSlant::NORMAL; } -void Controller::SetPlaceholderTextFontSlant( FontSlant slant ) +void Controller::SetPlaceholderTextFontSlant(FontSlant slant) { PlaceholderHandler::SetPlaceholderTextFontSlant(*this, slant); } @@ -878,16 +872,16 @@ FontSlant Controller::GetPlaceholderTextFontSlant() const return PlaceholderHandler::GetPlaceholderTextFontSlant(*this); } -void Controller::SetFontSizeScale( float scale ) +void Controller::SetFontSizeScale(float scale) { mImpl->mFontSizeScale = scale; - if( mImpl->mEventData ) + if(mImpl->mEventData) { // Update the cursor position if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->mEventData->mDecoratorUpdated = true; + mImpl->mEventData->mDecoratorUpdated = true; mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font size is updated. } } @@ -900,7 +894,7 @@ void Controller::SetFontSizeScale( float scale ) float Controller::GetFontSizeScale() const { - if( nullptr != mImpl->mFontDefaults ) + if(nullptr != mImpl->mFontDefaults) { return mImpl->mFontSizeScale; } @@ -908,41 +902,41 @@ float Controller::GetFontSizeScale() const return 1.f; } -void Controller::SetDefaultFontSize( float fontSize, FontSizeType type ) +void Controller::SetDefaultFontSize(float fontSize, FontSizeType type) { - if( NULL == mImpl->mFontDefaults ) + if(NULL == mImpl->mFontDefaults) { mImpl->mFontDefaults = new FontDefaults(); } - switch( type ) + switch(type) { case POINT_SIZE: { mImpl->mFontDefaults->mDefaultPointSize = fontSize; - mImpl->mFontDefaults->sizeDefined = true; + mImpl->mFontDefaults->sizeDefined = true; break; } case PIXEL_SIZE: { // Point size = Pixel size * 72.f / DPI - unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - fontClient.GetDpi( horizontalDpi, verticalDpi ); + unsigned int horizontalDpi = 0u; + unsigned int verticalDpi = 0u; + TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); + fontClient.GetDpi(horizontalDpi, verticalDpi); - mImpl->mFontDefaults->mDefaultPointSize = ( fontSize * 72.f ) / static_cast< float >( horizontalDpi ); - mImpl->mFontDefaults->sizeDefined = true; + mImpl->mFontDefaults->mDefaultPointSize = (fontSize * 72.f) / static_cast(horizontalDpi); + mImpl->mFontDefaults->sizeDefined = true; break; } } - if( mImpl->mEventData ) + if(mImpl->mEventData) { // Update the cursor position if it's in editing mode - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { - mImpl->mEventData->mDecoratorUpdated = true; + mImpl->mEventData->mDecoratorUpdated = true; mImpl->mEventData->mUpdateCursorPosition = true; // Cursor position should be updated when the font size is updated. } } @@ -953,12 +947,12 @@ void Controller::SetDefaultFontSize( float fontSize, FontSizeType type ) mImpl->RequestRelayout(); } -float Controller::GetDefaultFontSize( FontSizeType type ) const +float Controller::GetDefaultFontSize(FontSizeType type) const { float value = 0.0f; - if( NULL != mImpl->mFontDefaults ) + if(NULL != mImpl->mFontDefaults) { - switch( type ) + switch(type) { case POINT_SIZE: { @@ -968,12 +962,12 @@ float Controller::GetDefaultFontSize( FontSizeType type ) const case PIXEL_SIZE: { // Pixel size = Point size * DPI / 72.f - unsigned int horizontalDpi = 0u; - unsigned int verticalDpi = 0u; - TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - fontClient.GetDpi( horizontalDpi, verticalDpi ); + unsigned int horizontalDpi = 0u; + unsigned int verticalDpi = 0u; + TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); + fontClient.GetDpi(horizontalDpi, verticalDpi); - value = mImpl->mFontDefaults->mDefaultPointSize * static_cast< float >( horizontalDpi ) / 72.f; + value = mImpl->mFontDefaults->mDefaultPointSize * static_cast(horizontalDpi) / 72.f; break; } } @@ -983,27 +977,27 @@ float Controller::GetDefaultFontSize( FontSizeType type ) const return value; } -void Controller::SetPlaceholderTextFontSize( float fontSize, FontSizeType type ) +void Controller::SetPlaceholderTextFontSize(float fontSize, FontSizeType type) { PlaceholderHandler::SetPlaceholderTextFontSize(*this, fontSize, type); } -float Controller::GetPlaceholderTextFontSize( FontSizeType type ) const +float Controller::GetPlaceholderTextFontSize(FontSizeType type) const { return PlaceholderHandler::GetPlaceholderTextFontSize(*this, type); } -void Controller::SetDefaultColor( const Vector4& color ) +void Controller::SetDefaultColor(const Vector4& color) { mImpl->mTextColor = color; - if( !mImpl->IsShowingPlaceholderText() ) + if(!mImpl->IsShowingPlaceholderText()) { - mImpl->mModel->mVisualModel->SetTextColor( color ); + mImpl->mModel->mVisualModel->SetTextColor(color); mImpl->mModel->mLogicalModel->mColorRuns.Clear(); - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | COLOR ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | COLOR); mImpl->RequestRelayout(); } @@ -1014,7 +1008,7 @@ const Vector4& Controller::GetDefaultColor() const return mImpl->mTextColor; } -void Controller::SetPlaceholderTextColor( const Vector4& textColor ) +void Controller::SetPlaceholderTextColor(const Vector4& textColor) { PlaceholderHandler::SetPlaceholderTextColor(*this, textColor); } @@ -1024,9 +1018,9 @@ const Vector4& Controller::GetPlaceholderTextColor() const return PlaceholderHandler::GetPlaceholderTextColor(*this); } -void Controller::SetShadowOffset( const Vector2& shadowOffset ) +void Controller::SetShadowOffset(const Vector2& shadowOffset) { - mImpl->mModel->mVisualModel->SetShadowOffset( shadowOffset ); + mImpl->mModel->mVisualModel->SetShadowOffset(shadowOffset); mImpl->RequestRelayout(); } @@ -1036,9 +1030,9 @@ const Vector2& Controller::GetShadowOffset() const return mImpl->mModel->mVisualModel->GetShadowOffset(); } -void Controller::SetShadowColor( const Vector4& shadowColor ) +void Controller::SetShadowColor(const Vector4& shadowColor) { - mImpl->mModel->mVisualModel->SetShadowColor( shadowColor ); + mImpl->mModel->mVisualModel->SetShadowColor(shadowColor); mImpl->RequestRelayout(); } @@ -1048,11 +1042,11 @@ const Vector4& Controller::GetShadowColor() const return mImpl->mModel->mVisualModel->GetShadowColor(); } -void Controller::SetShadowBlurRadius( const float& shadowBlurRadius ) +void Controller::SetShadowBlurRadius(const float& shadowBlurRadius) { - if ( fabsf( GetShadowBlurRadius() - shadowBlurRadius ) > Math::MACHINE_EPSILON_1 ) + if(fabsf(GetShadowBlurRadius() - shadowBlurRadius) > Math::MACHINE_EPSILON_1) { - mImpl->mModel->mVisualModel->SetShadowBlurRadius( shadowBlurRadius ); + mImpl->mModel->mVisualModel->SetShadowBlurRadius(shadowBlurRadius); mImpl->RequestRelayout(); } @@ -1063,9 +1057,9 @@ const float& Controller::GetShadowBlurRadius() const return mImpl->mModel->mVisualModel->GetShadowBlurRadius(); } -void Controller::SetUnderlineColor( const Vector4& color ) +void Controller::SetUnderlineColor(const Vector4& color) { - mImpl->mModel->mVisualModel->SetUnderlineColor( color ); + mImpl->mModel->mVisualModel->SetUnderlineColor(color); mImpl->RequestRelayout(); } @@ -1075,9 +1069,9 @@ const Vector4& Controller::GetUnderlineColor() const return mImpl->mModel->mVisualModel->GetUnderlineColor(); } -void Controller::SetUnderlineEnabled( bool enabled ) +void Controller::SetUnderlineEnabled(bool enabled) { - mImpl->mModel->mVisualModel->SetUnderlineEnabled( enabled ); + mImpl->mModel->mVisualModel->SetUnderlineEnabled(enabled); mImpl->RequestRelayout(); } @@ -1087,9 +1081,9 @@ bool Controller::IsUnderlineEnabled() const return mImpl->mModel->mVisualModel->IsUnderlineEnabled(); } -void Controller::SetUnderlineHeight( float height ) +void Controller::SetUnderlineHeight(float height) { - mImpl->mModel->mVisualModel->SetUnderlineHeight( height ); + mImpl->mModel->mVisualModel->SetUnderlineHeight(height); mImpl->RequestRelayout(); } @@ -1099,9 +1093,9 @@ float Controller::GetUnderlineHeight() const return mImpl->mModel->mVisualModel->GetUnderlineHeight(); } -void Controller::SetOutlineColor( const Vector4& color ) +void Controller::SetOutlineColor(const Vector4& color) { - mImpl->mModel->mVisualModel->SetOutlineColor( color ); + mImpl->mModel->mVisualModel->SetOutlineColor(color); mImpl->RequestRelayout(); } @@ -1111,9 +1105,9 @@ const Vector4& Controller::GetOutlineColor() const return mImpl->mModel->mVisualModel->GetOutlineColor(); } -void Controller::SetOutlineWidth( uint16_t width ) +void Controller::SetOutlineWidth(uint16_t width) { - mImpl->mModel->mVisualModel->SetOutlineWidth( width ); + mImpl->mModel->mVisualModel->SetOutlineWidth(width); mImpl->RequestRelayout(); } @@ -1123,9 +1117,9 @@ uint16_t Controller::GetOutlineWidth() const return mImpl->mModel->mVisualModel->GetOutlineWidth(); } -void Controller::SetBackgroundColor( const Vector4& color ) +void Controller::SetBackgroundColor(const Vector4& color) { - mImpl->mModel->mVisualModel->SetBackgroundColor( color ); + mImpl->mModel->mVisualModel->SetBackgroundColor(color); mImpl->RequestRelayout(); } @@ -1135,9 +1129,9 @@ const Vector4& Controller::GetBackgroundColor() const return mImpl->mModel->mVisualModel->GetBackgroundColor(); } -void Controller::SetBackgroundEnabled( bool enabled ) +void Controller::SetBackgroundEnabled(bool enabled) { - mImpl->mModel->mVisualModel->SetBackgroundEnabled( enabled ); + mImpl->mModel->mVisualModel->SetBackgroundEnabled(enabled); mImpl->RequestRelayout(); } @@ -1147,9 +1141,9 @@ bool Controller::IsBackgroundEnabled() const return mImpl->mModel->mVisualModel->IsBackgroundEnabled(); } -void Controller::SetDefaultEmbossProperties( const std::string& embossProperties ) +void Controller::SetDefaultEmbossProperties(const std::string& embossProperties) { - if( NULL == mImpl->mEmbossDefaults ) + if(NULL == mImpl->mEmbossDefaults) { mImpl->mEmbossDefaults = new EmbossDefaults(); } @@ -1159,7 +1153,7 @@ void Controller::SetDefaultEmbossProperties( const std::string& embossProperties const std::string& Controller::GetDefaultEmbossProperties() const { - if( NULL != mImpl->mEmbossDefaults ) + if(NULL != mImpl->mEmbossDefaults) { return mImpl->mEmbossDefaults->properties; } @@ -1167,9 +1161,9 @@ const std::string& Controller::GetDefaultEmbossProperties() const return EMPTY_STRING; } -void Controller::SetDefaultOutlineProperties( const std::string& outlineProperties ) +void Controller::SetDefaultOutlineProperties(const std::string& outlineProperties) { - if( NULL == mImpl->mOutlineDefaults ) + if(NULL == mImpl->mOutlineDefaults) { mImpl->mOutlineDefaults = new OutlineDefaults(); } @@ -1179,7 +1173,7 @@ void Controller::SetDefaultOutlineProperties( const std::string& outlineProperti const std::string& Controller::GetDefaultOutlineProperties() const { - if( NULL != mImpl->mOutlineDefaults ) + if(NULL != mImpl->mOutlineDefaults) { return mImpl->mOutlineDefaults->properties; } @@ -1187,9 +1181,9 @@ const std::string& Controller::GetDefaultOutlineProperties() const return EMPTY_STRING; } -bool Controller::SetDefaultLineSpacing( float lineSpacing ) +bool Controller::SetDefaultLineSpacing(float lineSpacing) { - if( std::fabs( lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing() ) > Math::MACHINE_EPSILON_1000 ) + if(std::fabs(lineSpacing - mImpl->mLayoutEngine.GetDefaultLineSpacing()) > Math::MACHINE_EPSILON_1000) { mImpl->mLayoutEngine.SetDefaultLineSpacing(lineSpacing); mImpl->mRecalculateNaturalSize = true; @@ -1203,9 +1197,9 @@ float Controller::GetDefaultLineSpacing() const return mImpl->mLayoutEngine.GetDefaultLineSpacing(); } -bool Controller::SetDefaultLineSize( float lineSize ) +bool Controller::SetDefaultLineSize(float lineSize) { - if( std::fabs( lineSize - mImpl->mLayoutEngine.GetDefaultLineSize() ) > Math::MACHINE_EPSILON_1000 ) + if(std::fabs(lineSize - mImpl->mLayoutEngine.GetDefaultLineSize()) > Math::MACHINE_EPSILON_1000) { mImpl->mLayoutEngine.SetDefaultLineSize(lineSize); mImpl->mRecalculateNaturalSize = true; @@ -1219,54 +1213,53 @@ float Controller::GetDefaultLineSize() const return mImpl->mLayoutEngine.GetDefaultLineSize(); } -void Controller::SetInputColor( const Vector4& color ) +void Controller::SetInputColor(const Vector4& color) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { - mImpl->mEventData->mInputStyle.textColor = color; + mImpl->mEventData->mInputStyle.textColor = color; mImpl->mEventData->mInputStyle.isDefaultColor = false; - if( EventData::SELECTING == mImpl->mEventData->mState || EventData::EDITING == mImpl->mEventData->mState || EventData::INACTIVE == mImpl->mEventData->mState ) + if(EventData::SELECTING == mImpl->mEventData->mState || EventData::EDITING == mImpl->mEventData->mState || EventData::INACTIVE == mImpl->mEventData->mState) { const bool handlesCrossed = mImpl->mEventData->mLeftSelectionPosition > mImpl->mEventData->mRightSelectionPosition; // Get start and end position of selection - const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition; - const Length lengthOfSelectedText = ( handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition ) - startOfSelectedText; + const CharacterIndex startOfSelectedText = handlesCrossed ? mImpl->mEventData->mRightSelectionPosition : mImpl->mEventData->mLeftSelectionPosition; + const Length lengthOfSelectedText = (handlesCrossed ? mImpl->mEventData->mLeftSelectionPosition : mImpl->mEventData->mRightSelectionPosition) - startOfSelectedText; // Add the color run. const VectorBase::SizeType numberOfRuns = mImpl->mModel->mLogicalModel->mColorRuns.Count(); - mImpl->mModel->mLogicalModel->mColorRuns.Resize( numberOfRuns + 1u ); + mImpl->mModel->mLogicalModel->mColorRuns.Resize(numberOfRuns + 1u); - ColorRun& colorRun = *( mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns ); - colorRun.color = color; - colorRun.characterRun.characterIndex = startOfSelectedText; + ColorRun& colorRun = *(mImpl->mModel->mLogicalModel->mColorRuns.Begin() + numberOfRuns); + colorRun.color = color; + colorRun.characterRun.characterIndex = startOfSelectedText; colorRun.characterRun.numberOfCharacters = lengthOfSelectedText; // Request to relayout. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | COLOR ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | COLOR); mImpl->RequestRelayout(); - mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; + mImpl->mTextUpdateInfo.mCharacterIndex = startOfSelectedText; mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = lengthOfSelectedText; - mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; + mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = lengthOfSelectedText; } } } const Vector4& Controller::GetInputColor() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mInputStyle.textColor; } // Return the default text's color if there is no EventData. return mImpl->mTextColor; - } -void Controller::SetInputFontFamily( const std::string& fontFamily ) +void Controller::SetInputFontFamily(const std::string& fontFamily) { InputFontHandler::SetInputFontFamily(*this, fontFamily); } @@ -1276,7 +1269,7 @@ const std::string& Controller::GetInputFontFamily() const return InputFontHandler::GetInputFontFamily(*this); } -void Controller::SetInputFontWeight( FontWeight weight ) +void Controller::SetInputFontWeight(FontWeight weight) { InputFontHandler::SetInputFontWeight(*this, weight); } @@ -1291,7 +1284,7 @@ FontWeight Controller::GetInputFontWeight() const return InputFontHandler::GetInputFontWeight(*this); } -void Controller::SetInputFontWidth( FontWidth width ) +void Controller::SetInputFontWidth(FontWidth width) { InputFontHandler::SetInputFontWidth(*this, width); } @@ -1306,7 +1299,7 @@ FontWidth Controller::GetInputFontWidth() const return InputFontHandler::GetInputFontWidth(*this); } -void Controller::SetInputFontSlant( FontSlant slant ) +void Controller::SetInputFontSlant(FontSlant slant) { InputFontHandler::SetInputFontSlant(*this, slant); } @@ -1321,7 +1314,7 @@ FontSlant Controller::GetInputFontSlant() const return InputFontHandler::GetInputFontSlant(*this); } -void Controller::SetInputFontPointSize( float size ) +void Controller::SetInputFontPointSize(float size) { InputFontHandler::SetInputFontPointSize(*this, size); } @@ -1331,18 +1324,18 @@ float Controller::GetInputFontPointSize() const return InputFontHandler::GetInputFontPointSize(*this); } -void Controller::SetInputLineSpacing( float lineSpacing ) +void Controller::SetInputLineSpacing(float lineSpacing) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { - mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing; + mImpl->mEventData->mInputStyle.lineSpacing = lineSpacing; mImpl->mEventData->mInputStyle.isLineSpacingDefined = true; } } float Controller::GetInputLineSpacing() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mInputStyle.lineSpacing; } @@ -1350,9 +1343,9 @@ float Controller::GetInputLineSpacing() const return 0.f; } -void Controller::SetInputShadowProperties( const std::string& shadowProperties ) +void Controller::SetInputShadowProperties(const std::string& shadowProperties) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mInputStyle.shadowProperties = shadowProperties; } @@ -1360,7 +1353,7 @@ void Controller::SetInputShadowProperties( const std::string& shadowProperties ) const std::string& Controller::GetInputShadowProperties() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mInputStyle.shadowProperties; } @@ -1368,9 +1361,9 @@ const std::string& Controller::GetInputShadowProperties() const return EMPTY_STRING; } -void Controller::SetInputUnderlineProperties( const std::string& underlineProperties ) +void Controller::SetInputUnderlineProperties(const std::string& underlineProperties) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mInputStyle.underlineProperties = underlineProperties; } @@ -1378,7 +1371,7 @@ void Controller::SetInputUnderlineProperties( const std::string& underlineProper const std::string& Controller::GetInputUnderlineProperties() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mInputStyle.underlineProperties; } @@ -1386,9 +1379,9 @@ const std::string& Controller::GetInputUnderlineProperties() const return EMPTY_STRING; } -void Controller::SetInputEmbossProperties( const std::string& embossProperties ) +void Controller::SetInputEmbossProperties(const std::string& embossProperties) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mInputStyle.embossProperties = embossProperties; } @@ -1396,7 +1389,7 @@ void Controller::SetInputEmbossProperties( const std::string& embossProperties ) const std::string& Controller::GetInputEmbossProperties() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mInputStyle.embossProperties; } @@ -1404,9 +1397,9 @@ const std::string& Controller::GetInputEmbossProperties() const return GetDefaultEmbossProperties(); } -void Controller::SetInputOutlineProperties( const std::string& outlineProperties ) +void Controller::SetInputOutlineProperties(const std::string& outlineProperties) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mInputStyle.outlineProperties = outlineProperties; } @@ -1414,7 +1407,7 @@ void Controller::SetInputOutlineProperties( const std::string& outlineProperties const std::string& Controller::GetInputOutlineProperties() const { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mInputStyle.outlineProperties; } @@ -1422,9 +1415,9 @@ const std::string& Controller::GetInputOutlineProperties() const return GetDefaultOutlineProperties(); } -void Controller::SetInputModePassword( bool passwordInput ) +void Controller::SetInputModePassword(bool passwordInput) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mPasswordInput = passwordInput; } @@ -1432,16 +1425,16 @@ void Controller::SetInputModePassword( bool passwordInput ) bool Controller::IsInputModePassword() { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { return mImpl->mEventData->mPasswordInput; } return false; } -void Controller::SetNoTextDoubleTapAction( NoTextTap::Action action ) +void Controller::SetNoTextDoubleTapAction(NoTextTap::Action action) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mDoubleTapAction = action; } @@ -1451,7 +1444,7 @@ Controller::NoTextTap::Action Controller::GetNoTextDoubleTapAction() const { NoTextTap::Action action = NoTextTap::NO_ACTION; - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { action = mImpl->mEventData->mDoubleTapAction; } @@ -1459,9 +1452,9 @@ Controller::NoTextTap::Action Controller::GetNoTextDoubleTapAction() const return action; } -void Controller::SetNoTextLongPressAction( NoTextTap::Action action ) +void Controller::SetNoTextLongPressAction(NoTextTap::Action action) { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mLongPressAction = action; } @@ -1471,7 +1464,7 @@ Controller::NoTextTap::Action Controller::GetNoTextLongPressAction() const { NoTextTap::Action action = NoTextTap::NO_ACTION; - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { action = mImpl->mEventData->mLongPressAction; } @@ -1484,7 +1477,7 @@ bool Controller::IsUnderlineSetByString() return mImpl->mUnderlineSetByString; } -void Controller::UnderlineSetByString( bool setByString ) +void Controller::UnderlineSetByString(bool setByString) { mImpl->mUnderlineSetByString = setByString; } @@ -1494,7 +1487,7 @@ bool Controller::IsShadowSetByString() return mImpl->mShadowSetByString; } -void Controller::ShadowSetByString( bool setByString ) +void Controller::ShadowSetByString(bool setByString) { mImpl->mShadowSetByString = setByString; } @@ -1504,7 +1497,7 @@ bool Controller::IsOutlineSetByString() return mImpl->mOutlineSetByString; } -void Controller::OutlineSetByString( bool setByString ) +void Controller::OutlineSetByString(bool setByString) { mImpl->mOutlineSetByString = setByString; } @@ -1514,7 +1507,7 @@ bool Controller::IsFontStyleSetByString() return mImpl->mFontStyleSetByString; } -void Controller::FontStyleSetByString( bool setByString ) +void Controller::FontStyleSetByString(bool setByString) { mImpl->mFontStyleSetByString = setByString; } @@ -1536,24 +1529,24 @@ Vector3 Controller::GetNaturalSize() return Relayouter::GetNaturalSize(*this); } -bool Controller::CheckForTextFit( float pointSize, Size& layoutSize ) +bool Controller::CheckForTextFit(float pointSize, Size& layoutSize) { return Relayouter::CheckForTextFit(*this, pointSize, layoutSize); } -void Controller::FitPointSizeforLayout( Size layoutSize ) +void Controller::FitPointSizeforLayout(Size layoutSize) { Relayouter::FitPointSizeforLayout(*this, layoutSize); } -float Controller::GetHeightForWidth( float width ) +float Controller::GetHeightForWidth(float width) { return Relayouter::GetHeightForWidth(*this, width); } -int Controller::GetLineCount( float width ) +int Controller::GetLineCount(float width) { - GetHeightForWidth( width ); + GetHeightForWidth(width); int numberofLines = mImpl->mModel->GetNumberOfLines(); return numberofLines; } @@ -1567,49 +1560,49 @@ float Controller::GetScrollAmountByUserInput() { float scrollAmount = 0.0f; - if (NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount) + if(NULL != mImpl->mEventData && mImpl->mEventData->mCheckScrollAmount) { - scrollAmount = mImpl->mModel->mScrollPosition.y - mImpl->mModel->mScrollPositionLast.y; + scrollAmount = mImpl->mModel->mScrollPosition.y - mImpl->mModel->mScrollPositionLast.y; mImpl->mEventData->mCheckScrollAmount = false; } return scrollAmount; } -bool Controller::GetTextScrollInfo( float& scrollPosition, float& controlHeight, float& layoutHeight ) +bool Controller::GetTextScrollInfo(float& scrollPosition, float& controlHeight, float& layoutHeight) { const Vector2& layout = mImpl->mModel->mVisualModel->GetLayoutSize(); - bool isScrolled; + bool isScrolled; - controlHeight = mImpl->mModel->mVisualModel->mControlSize.height; - layoutHeight = layout.height; + controlHeight = mImpl->mModel->mVisualModel->mControlSize.height; + layoutHeight = layout.height; scrollPosition = mImpl->mModel->mScrollPosition.y; - isScrolled = !Equals( mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1 ); + isScrolled = !Equals(mImpl->mModel->mScrollPosition.y, mImpl->mModel->mScrollPositionLast.y, Math::MACHINE_EPSILON_1); return isScrolled; } void Controller::SetHiddenInputOption(const Property::Map& options) { - if( NULL == mImpl->mHiddenInput ) + if(NULL == mImpl->mHiddenInput) { - mImpl->mHiddenInput = new HiddenText( this ); + mImpl->mHiddenInput = new HiddenText(this); } mImpl->mHiddenInput->SetProperties(options); } void Controller::GetHiddenInputOption(Property::Map& options) { - if( NULL != mImpl->mHiddenInput ) + if(NULL != mImpl->mHiddenInput) { mImpl->mHiddenInput->GetProperties(options); } } -void Controller::SetPlaceholderProperty( const Property::Map& map ) +void Controller::SetPlaceholderProperty(const Property::Map& map) { PlaceholderHandler::SetPlaceholderProperty(*this, map); } -void Controller::GetPlaceholderProperty( Property::Map& map ) +void Controller::GetPlaceholderProperty(Property::Map& map) { PlaceholderHandler::GetPlaceholderProperty(*this, map); } @@ -1619,32 +1612,32 @@ Toolkit::DevelText::TextDirection::Type Controller::GetTextDirection() // Make sure the model is up-to-date before layouting ProcessModifyEvents(); - if ( mImpl->mUpdateTextDirection ) + if(mImpl->mUpdateTextDirection) { // Operations that can be done only once until the text changes. - const OperationsMask onlyOnceOperations = static_cast( CONVERT_TO_UTF32 | - GET_SCRIPTS | - VALIDATE_FONTS | - GET_LINE_BREAKS | - BIDI_INFO | - SHAPE_TEXT | - GET_GLYPH_METRICS ); + const OperationsMask onlyOnceOperations = static_cast(CONVERT_TO_UTF32 | + GET_SCRIPTS | + VALIDATE_FONTS | + GET_LINE_BREAKS | + BIDI_INFO | + SHAPE_TEXT | + GET_GLYPH_METRICS); // Set the update info to relayout the whole text. - mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u; + mImpl->mTextUpdateInfo.mParagraphCharacterIndex = 0u; mImpl->mTextUpdateInfo.mRequestedNumberOfCharacters = mImpl->mModel->mLogicalModel->mText.Count(); // Make sure the model is up-to-date before layouting - mImpl->UpdateModel( onlyOnceOperations ); + mImpl->UpdateModel(onlyOnceOperations); Vector3 naturalSize; - DoRelayout( Size( MAX_FLOAT, MAX_FLOAT ), - static_cast( onlyOnceOperations | - LAYOUT | REORDER | UPDATE_DIRECTION ), - naturalSize.GetVectorXY() ); + DoRelayout(Size(MAX_FLOAT, MAX_FLOAT), + static_cast(onlyOnceOperations | + LAYOUT | REORDER | UPDATE_DIRECTION), + naturalSize.GetVectorXY()); // Do not do again the only once operations. - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending & ~onlyOnceOperations ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending & ~onlyOnceOperations); // Clear the update info. This info will be set the next time the text is updated. mImpl->mTextUpdateInfo.Clear(); @@ -1663,14 +1656,14 @@ Toolkit::DevelText::VerticalLineAlignment::Type Controller::GetVerticalLineAlign return mImpl->mModel->GetVerticalLineAlignment(); } -void Controller::SetVerticalLineAlignment( Toolkit::DevelText::VerticalLineAlignment::Type alignment ) +void Controller::SetVerticalLineAlignment(Toolkit::DevelText::VerticalLineAlignment::Type alignment) { mImpl->mModel->mVerticalLineAlignment = alignment; } // public : Relayout. -Controller::UpdateTextType Controller::Relayout( const Size& size, Dali::LayoutDirection::Type layoutDirection ) +Controller::UpdateTextType Controller::Relayout(const Size& size, Dali::LayoutDirection::Type layoutDirection) { return Relayouter::Relayout(*this, size, layoutDirection); } @@ -1684,28 +1677,28 @@ void Controller::RequestRelayout() bool Controller::IsInputStyleChangedSignalsQueueEmpty() { - return ( NULL == mImpl->mEventData ) || ( 0u == mImpl->mEventData->mInputStyleChangedQueue.Count() ); + return (NULL == mImpl->mEventData) || (0u == mImpl->mEventData->mInputStyleChangedQueue.Count()); } void Controller::ProcessInputStyleChangedSignals() { - if( NULL == mImpl->mEventData ) + if(NULL == mImpl->mEventData) { // Nothing to do. return; } - for( Vector::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(), - endIt = mImpl->mEventData->mInputStyleChangedQueue.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = mImpl->mEventData->mInputStyleChangedQueue.Begin(), + endIt = mImpl->mEventData->mInputStyleChangedQueue.End(); + it != endIt; + ++it) { const InputStyle::Mask mask = *it; - if( NULL != mImpl->mEditableControlInterface ) + if(NULL != mImpl->mEditableControlInterface) { // Emit the input style changed signal. - mImpl->mEditableControlInterface->InputStyleChanged( mask ); + mImpl->mEditableControlInterface->InputStyleChanged(mask); } } @@ -1724,37 +1717,37 @@ void Controller::KeyboardFocusLostEvent() EventHandler::KeyboardFocusLostEvent(*this); } -bool Controller::KeyEvent( const Dali::KeyEvent& keyEvent ) +bool Controller::KeyEvent(const Dali::KeyEvent& keyEvent) { return EventHandler::KeyEvent(*this, keyEvent); } -void Controller::TapEvent( unsigned int tapCount, float x, float y ) +void Controller::TapEvent(unsigned int tapCount, float x, float y) { EventHandler::TapEvent(*this, tapCount, x, y); } -void Controller::PanEvent( GestureState state, const Vector2& displacement ) +void Controller::PanEvent(GestureState state, const Vector2& displacement) { EventHandler::PanEvent(*this, state, displacement); } -void Controller::LongPressEvent( GestureState state, float x, float y ) +void Controller::LongPressEvent(GestureState state, float x, float y) { EventHandler::LongPressEvent(*this, state, x, y); } -void Controller::SelectEvent( float x, float y, SelectionType selectType ) +void Controller::SelectEvent(float x, float y, SelectionType selectType) { EventHandler::SelectEvent(*this, x, y, selectType); } -void Controller::SetTextSelectionRange(const uint32_t *start, const uint32_t *end) +void Controller::SetTextSelectionRange(const uint32_t* start, const uint32_t* end) { - if( mImpl->mEventData ) + if(mImpl->mEventData) { - mImpl->mEventData->mCheckScrollAmount = true; - mImpl->mEventData->mIsLeftHandleSelected = true; + mImpl->mEventData->mCheckScrollAmount = true; + mImpl->mEventData->mIsLeftHandleSelected = true; mImpl->mEventData->mIsRightHandleSelected = true; mImpl->SetTextSelectionRange(start, end); mImpl->RequestRelayout(); @@ -1772,15 +1765,15 @@ CharacterIndex Controller::GetPrimaryCursorPosition() const return mImpl->GetPrimaryCursorPosition(); } -bool Controller::SetPrimaryCursorPosition( CharacterIndex index ) +bool Controller::SetPrimaryCursorPosition(CharacterIndex index) { - if( mImpl->mEventData ) + if(mImpl->mEventData) { - mImpl->mEventData->mCheckScrollAmount = true; - mImpl->mEventData->mIsLeftHandleSelected = true; + mImpl->mEventData->mCheckScrollAmount = true; + mImpl->mEventData->mIsLeftHandleSelected = true; mImpl->mEventData->mIsRightHandleSelected = true; - mImpl->mEventData->mCheckScrollAmount = true; - if( mImpl->SetPrimaryCursorPosition(index) ) + mImpl->mEventData->mCheckScrollAmount = true; + if(mImpl->SetPrimaryCursorPosition(index)) { KeyboardFocusGainEvent(); return true; @@ -1791,25 +1784,25 @@ bool Controller::SetPrimaryCursorPosition( CharacterIndex index ) void Controller::SelectWholeText() { - SelectEvent( 0.f, 0.f, SelectionType::ALL ); + SelectEvent(0.f, 0.f, SelectionType::ALL); } void Controller::SelectNone() { - SelectEvent( 0.f, 0.f, SelectionType::NONE ); + SelectEvent(0.f, 0.f, SelectionType::NONE); } string Controller::GetSelectedText() const { string text; - if( EventData::SELECTING == mImpl->mEventData->mState ) + if(EventData::SELECTING == mImpl->mEventData->mState) { - mImpl->RetrieveSelection( text, false ); + mImpl->RetrieveSelection(text, false); } return text; } -InputMethodContext::CallbackData Controller::OnInputMethodContextEvent( InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent ) +InputMethodContext::CallbackData Controller::OnInputMethodContextEvent(InputMethodContext& inputMethodContext, const InputMethodContext::EventData& inputMethodContextEvent) { return EventHandler::OnInputMethodContextEvent(*this, inputMethodContext, inputMethodContextEvent); } @@ -1821,16 +1814,16 @@ void Controller::PasteClipboardItemEvent() // protected : Inherit from Text::Decorator::ControllerInterface. -void Controller::GetTargetSize( Vector2& targetSize ) +void Controller::GetTargetSize(Vector2& targetSize) { targetSize = mImpl->mModel->mVisualModel->mControlSize; } -void Controller::AddDecoration( Actor& actor, bool needsClipping ) +void Controller::AddDecoration(Actor& actor, bool needsClipping) { - if( NULL != mImpl->mEditableControlInterface ) + if(NULL != mImpl->mEditableControlInterface) { - mImpl->mEditableControlInterface->AddDecoration( actor, needsClipping ); + mImpl->mEditableControlInterface->AddDecoration(actor, needsClipping); } } @@ -1839,48 +1832,48 @@ bool Controller::IsEditable() const return mImpl->IsEditable(); } -void Controller::SetEditable( bool editable ) +void Controller::SetEditable(bool editable) { - mImpl->SetEditable( editable ); + mImpl->SetEditable(editable); if(mImpl->mEventData && mImpl->mEventData->mDecorator) { - mImpl->mEventData->mDecorator->SetEditable( editable ); + mImpl->mEventData->mDecorator->SetEditable(editable); } } -void Controller::ScrollBy( Vector2 scroll ) +void Controller::ScrollBy(Vector2 scroll) { - if( mImpl->mEventData && (fabs(scroll.x) > Math::MACHINE_EPSILON_0 || fabs(scroll.y) > Math::MACHINE_EPSILON_0)) + if(mImpl->mEventData && (fabs(scroll.x) > Math::MACHINE_EPSILON_0 || fabs(scroll.y) > Math::MACHINE_EPSILON_0)) { - const Vector2& layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize(); - const Vector2 currentScroll = mImpl->mModel->mScrollPosition; + const Vector2& layoutSize = mImpl->mModel->mVisualModel->GetLayoutSize(); + const Vector2 currentScroll = mImpl->mModel->mScrollPosition; - scroll.x = -scroll.x; - scroll.y = -scroll.y; + scroll.x = -scroll.x; + scroll.y = -scroll.y; - if( fabs(scroll.x) > Math::MACHINE_EPSILON_0 ) - { - mImpl->mModel->mScrollPosition.x += scroll.x; - mImpl->ClampHorizontalScroll( layoutSize ); - } + if(fabs(scroll.x) > Math::MACHINE_EPSILON_0) + { + mImpl->mModel->mScrollPosition.x += scroll.x; + mImpl->ClampHorizontalScroll(layoutSize); + } - if( fabs(scroll.y) > Math::MACHINE_EPSILON_0 ) - { - mImpl->mModel->mScrollPosition.y += scroll.y; - mImpl->ClampVerticalScroll( layoutSize ); - } + if(fabs(scroll.y) > Math::MACHINE_EPSILON_0) + { + mImpl->mModel->mScrollPosition.y += scroll.y; + mImpl->ClampVerticalScroll(layoutSize); + } - if (mImpl->mModel->mScrollPosition != currentScroll) - { - mImpl->mEventData->mDecorator->UpdatePositions( mImpl->mModel->mScrollPosition - currentScroll ); - mImpl->RequestRelayout(); - } + if(mImpl->mModel->mScrollPosition != currentScroll) + { + mImpl->mEventData->mDecorator->UpdatePositions(mImpl->mModel->mScrollPosition - currentScroll); + mImpl->RequestRelayout(); + } } } float Controller::GetHorizontalScrollPosition() { - if( mImpl->mEventData ) + if(mImpl->mEventData) { //scroll values are negative internally so we convert them to positive numbers return -mImpl->mModel->mScrollPosition.x; @@ -1890,7 +1883,7 @@ float Controller::GetHorizontalScrollPosition() float Controller::GetVerticalScrollPosition() { - if( mImpl->mEventData ) + if(mImpl->mEventData) { //scroll values are negative internally so we convert them to positive numbers return -mImpl->mModel->mScrollPosition.y; @@ -1898,14 +1891,14 @@ float Controller::GetVerticalScrollPosition() return 0; } -void Controller::DecorationEvent( HandleType handleType, HandleState state, float x, float y ) +void Controller::DecorationEvent(HandleType handleType, HandleState state, float x, float y) { EventHandler::DecorationEvent(*this, handleType, state, x, y); } // protected : Inherit from TextSelectionPopup::TextPopupButtonCallbackInterface. -void Controller::TextPopupButtonTouched( Dali::Toolkit::TextSelectionPopup::Buttons button ) +void Controller::TextPopupButtonTouched(Dali::Toolkit::TextSelectionPopup::Buttons button) { EventHandler::TextPopupButtonTouched(*this, button); } @@ -1921,19 +1914,19 @@ void Controller::DisplayTimeExpired() // private : Update. -void Controller::InsertText( const std::string& text, Controller::InsertType type ) +void Controller::InsertText(const std::string& text, Controller::InsertType type) { TextUpdater::InsertText(*this, text, type); } -void Controller::PasteText( const std::string& stringToPaste ) +void Controller::PasteText(const std::string& stringToPaste) { TextUpdater::PasteText(*this, stringToPaste); } -bool Controller::RemoveText( int cursorOffset, - int numberOfCharacters, - UpdateInputStyleType type ) +bool Controller::RemoveText(int cursorOffset, + int numberOfCharacters, + UpdateInputStyleType type) { return TextUpdater::RemoveText(*this, cursorOffset, numberOfCharacters, type); } @@ -1945,14 +1938,14 @@ bool Controller::RemoveSelectedText() // private : Relayout. -bool Controller::DoRelayout( const Size& size, - OperationsMask operationsRequired, - Size& layoutSize ) +bool Controller::DoRelayout(const Size& size, + OperationsMask operationsRequired, + Size& layoutSize) { return Relayouter::DoRelayout(*this, size, operationsRequired, layoutSize); } -void Controller::CalculateVerticalOffset( const Size& controlSize ) +void Controller::CalculateVerticalOffset(const Size& controlSize) { Relayouter::CalculateVerticalOffset(*this, controlSize); } @@ -1979,7 +1972,7 @@ void Controller::TextDeletedEvent() EventHandler::TextDeletedEvent(*this); } -bool Controller::DeleteEvent( int keyCode ) +bool Controller::DeleteEvent(int keyCode) { return EventHandler::DeleteEvent(*this, keyCode); } @@ -1998,29 +1991,29 @@ void Controller::ShowPlaceholderText() void Controller::ClearFontData() { - if( mImpl->mFontDefaults ) + if(mImpl->mFontDefaults) { mImpl->mFontDefaults->mFontId = 0u; // Remove old font ID } // Set flags to update the model. - mImpl->mTextUpdateInfo.mCharacterIndex = 0u; + mImpl->mTextUpdateInfo.mCharacterIndex = 0u; mImpl->mTextUpdateInfo.mNumberOfCharactersToRemove = mImpl->mTextUpdateInfo.mPreviousNumberOfCharacters; - mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count(); + mImpl->mTextUpdateInfo.mNumberOfCharactersToAdd = mImpl->mModel->mLogicalModel->mText.Count(); - mImpl->mTextUpdateInfo.mClearAll = true; + mImpl->mTextUpdateInfo.mClearAll = true; mImpl->mTextUpdateInfo.mFullRelayoutNeeded = true; - mImpl->mRecalculateNaturalSize = true; + mImpl->mRecalculateNaturalSize = true; - mImpl->mOperationsPending = static_cast( mImpl->mOperationsPending | - VALIDATE_FONTS | - SHAPE_TEXT | - BIDI_INFO | - GET_GLYPH_METRICS | - LAYOUT | - UPDATE_LAYOUT_SIZE | - REORDER | - ALIGN ); + mImpl->mOperationsPending = static_cast(mImpl->mOperationsPending | + VALIDATE_FONTS | + SHAPE_TEXT | + BIDI_INFO | + GET_GLYPH_METRICS | + LAYOUT | + UPDATE_LAYOUT_SIZE | + REORDER | + ALIGN); } void Controller::ClearStyleData() @@ -2029,15 +2022,15 @@ void Controller::ClearStyleData() mImpl->mModel->mLogicalModel->ClearFontDescriptionRuns(); } -void Controller::ResetCursorPosition( CharacterIndex cursorIndex ) +void Controller::ResetCursorPosition(CharacterIndex cursorIndex) { // Reset the cursor position - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { mImpl->mEventData->mPrimaryCursorPosition = cursorIndex; // Update the cursor if it's in editing mode. - if( EventData::IsEditingState( mImpl->mEventData->mState ) ) + if(EventData::IsEditingState(mImpl->mEventData->mState)) { mImpl->mEventData->mUpdateCursorPosition = true; } @@ -2046,7 +2039,7 @@ void Controller::ResetCursorPosition( CharacterIndex cursorIndex ) CharacterIndex Controller::GetCursorPosition() { - if( !mImpl->mEventData ) + if(!mImpl->mEventData) return 0; return mImpl->mEventData->mPrimaryCursorPosition; @@ -2054,15 +2047,15 @@ CharacterIndex Controller::GetCursorPosition() void Controller::ResetScrollPosition() { - if( NULL != mImpl->mEventData ) + if(NULL != mImpl->mEventData) { // Reset the scroll position. - mImpl->mModel->mScrollPosition = Vector2::ZERO; + mImpl->mModel->mScrollPosition = Vector2::ZERO; mImpl->mEventData->mScrollAfterUpdatePosition = true; } } -void Controller::SetControlInterface( ControlInterface* controlInterface ) +void Controller::SetControlInterface(ControlInterface* controlInterface) { mImpl->mControlInterface = controlInterface; } @@ -2084,14 +2077,14 @@ Controller::Controller() { } -Controller::Controller( ControlInterface* controlInterface ) -:Controller( controlInterface, nullptr, nullptr) +Controller::Controller(ControlInterface* controlInterface) +: Controller(controlInterface, nullptr, nullptr) { } -Controller::Controller( ControlInterface* controlInterface, - EditableControlInterface* editableControlInterface, - SelectableControlInterface* selectableControlInterface ) +Controller::Controller(ControlInterface* controlInterface, + EditableControlInterface* editableControlInterface, + SelectableControlInterface* selectableControlInterface) : mImpl(new Controller::Impl(controlInterface, editableControlInterface, selectableControlInterface)) { } diff --git a/dali-toolkit/internal/text/text-effects-style.cpp b/dali-toolkit/internal/text/text-effects-style.cpp old mode 100755 new mode 100644 index d5f8ff1..a367696 --- a/dali-toolkit/internal/text/text-effects-style.cpp +++ b/dali-toolkit/internal/text/text-effects-style.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,79 +25,76 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { -const std::string COLOR_KEY( "color" ); -const std::string OFFSET_KEY( "offset" ); -const std::string BLUR_RADIUS_KEY( "blurRadius" ); -const std::string WIDTH_KEY( "width" ); -const std::string HEIGHT_KEY( "height" ); -const std::string ENABLE_KEY( "enable" ); -const std::string TRUE_TOKEN( "true" ); -const std::string FALSE_TOKEN( "false" ); -} - -bool ParseShadowProperties( const Property::Map& shadowPropertiesMap, - bool& colorDefined, - Vector4& color, - bool& offsetDefined, - Vector2& offset, - bool& blurRadiusDefined, - float& blurRadius ) +const std::string COLOR_KEY("color"); +const std::string OFFSET_KEY("offset"); +const std::string BLUR_RADIUS_KEY("blurRadius"); +const std::string WIDTH_KEY("width"); +const std::string HEIGHT_KEY("height"); +const std::string ENABLE_KEY("enable"); +const std::string TRUE_TOKEN("true"); +const std::string FALSE_TOKEN("false"); +} // namespace + +bool ParseShadowProperties(const Property::Map& shadowPropertiesMap, + bool& colorDefined, + Vector4& color, + bool& offsetDefined, + Vector2& offset, + bool& blurRadiusDefined, + float& blurRadius) { const unsigned int numberOfItems = shadowPropertiesMap.Count(); // Parses and applies the style. - for( unsigned int index = 0u; index < numberOfItems; ++index ) + for(unsigned int index = 0u; index < numberOfItems; ++index) { - const KeyValuePair& valueGet = shadowPropertiesMap.GetKeyValue( index ); + const KeyValuePair& valueGet = shadowPropertiesMap.GetKeyValue(index); - if( ( DevelText::Shadow::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) ) + if((DevelText::Shadow::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey)) { /// Color key. colorDefined = true; - if( valueGet.second.GetType() == Dali::Property::STRING ) + if(valueGet.second.GetType() == Dali::Property::STRING) { const std::string colorStr = valueGet.second.Get(); - Text::ColorStringToVector4( colorStr.c_str(), colorStr.size(), color ); + Text::ColorStringToVector4(colorStr.c_str(), colorStr.size(), color); } else { color = valueGet.second.Get(); } } - else if( ( DevelText::Shadow::Property::OFFSET == valueGet.first.indexKey ) || ( OFFSET_KEY == valueGet.first.stringKey ) ) + else if((DevelText::Shadow::Property::OFFSET == valueGet.first.indexKey) || (OFFSET_KEY == valueGet.first.stringKey)) { /// Offset key. offsetDefined = true; - if( valueGet.second.GetType() == Dali::Property::STRING ) + if(valueGet.second.GetType() == Dali::Property::STRING) { const std::string offsetStr = valueGet.second.Get(); - StringToVector2( offsetStr.c_str(), offsetStr.size(), offset ); + StringToVector2(offsetStr.c_str(), offsetStr.size(), offset); } else { offset = valueGet.second.Get(); } } - else if( ( DevelText::Shadow::Property::BLUR_RADIUS == valueGet.first.indexKey ) || ( BLUR_RADIUS_KEY == valueGet.first.stringKey ) ) + else if((DevelText::Shadow::Property::BLUR_RADIUS == valueGet.first.indexKey) || (BLUR_RADIUS_KEY == valueGet.first.stringKey)) { /// Blur radius key. blurRadiusDefined = true; - if( valueGet.second.GetType() == Dali::Property::STRING ) + if(valueGet.second.GetType() == Dali::Property::STRING) { const std::string blurRadiusStr = valueGet.second.Get(); - blurRadius = StringToFloat( blurRadiusStr.c_str() ); + blurRadius = StringToFloat(blurRadiusStr.c_str()); } else { @@ -109,57 +106,57 @@ bool ParseShadowProperties( const Property::Map& shadowPropertiesMap, return 0u == numberOfItems; } -bool ParseUnderlineProperties( const Property::Map& underlinePropertiesMap, - bool& enabled, - bool& colorDefined, - Vector4& color, - bool& heightDefined, - float& height ) +bool ParseUnderlineProperties(const Property::Map& underlinePropertiesMap, + bool& enabled, + bool& colorDefined, + Vector4& color, + bool& heightDefined, + float& height) { const unsigned int numberOfItems = underlinePropertiesMap.Count(); // Parses and applies the style. - for( unsigned int index = 0u; index < numberOfItems; ++index ) + for(unsigned int index = 0u; index < numberOfItems; ++index) { - const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue( index ); + const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue(index); - if( ( DevelText::Underline::Property::ENABLE == valueGet.first.indexKey ) || ( ENABLE_KEY == valueGet.first.stringKey ) ) + if((DevelText::Underline::Property::ENABLE == valueGet.first.indexKey) || (ENABLE_KEY == valueGet.first.stringKey)) { /// Enable key. - if( valueGet.second.GetType() == Dali::Property::STRING ) + if(valueGet.second.GetType() == Dali::Property::STRING) { const std::string enableStr = valueGet.second.Get(); - enabled = Text::TokenComparison( TRUE_TOKEN, enableStr.c_str(), enableStr.size() ); + enabled = Text::TokenComparison(TRUE_TOKEN, enableStr.c_str(), enableStr.size()); } else { enabled = valueGet.second.Get(); } } - else if( ( DevelText::Underline::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) ) + else if((DevelText::Underline::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey)) { /// Color key. colorDefined = true; - if( valueGet.second.GetType() == Dali::Property::STRING ) + if(valueGet.second.GetType() == Dali::Property::STRING) { const std::string colorStr = valueGet.second.Get(); - Text::ColorStringToVector4( colorStr.c_str(), colorStr.size(), color ); + Text::ColorStringToVector4(colorStr.c_str(), colorStr.size(), color); } else { color = valueGet.second.Get(); } } - else if( ( DevelText::Underline::Property::HEIGHT == valueGet.first.indexKey ) || ( HEIGHT_KEY == valueGet.first.stringKey ) ) + else if((DevelText::Underline::Property::HEIGHT == valueGet.first.indexKey) || (HEIGHT_KEY == valueGet.first.stringKey)) { /// Height key. heightDefined = true; - if( valueGet.second.GetType() == Dali::Property::STRING ) + if(valueGet.second.GetType() == Dali::Property::STRING) { const std::string heightStr = valueGet.second.Get(); - height = StringToFloat( heightStr.c_str() ); + height = StringToFloat(heightStr.c_str()); } else { @@ -171,143 +168,143 @@ bool ParseUnderlineProperties( const Property::Map& underlinePropertiesMap, return 0u == numberOfItems; } -bool ParseOutlineProperties( const Property::Map& underlinePropertiesMap, - bool& colorDefined, - Vector4& color, - bool& widthDefined, - uint16_t& width ) +bool ParseOutlineProperties(const Property::Map& underlinePropertiesMap, + bool& colorDefined, + Vector4& color, + bool& widthDefined, + uint16_t& width) { const unsigned int numberOfItems = underlinePropertiesMap.Count(); // Parses and applies the style. - for( unsigned int index = 0u; index < numberOfItems; ++index ) + for(unsigned int index = 0u; index < numberOfItems; ++index) { - const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue( index ); + const KeyValuePair& valueGet = underlinePropertiesMap.GetKeyValue(index); - if( ( DevelText::Outline::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) ) + if((DevelText::Outline::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey)) { /// Color key. colorDefined = true; - color = valueGet.second.Get(); + color = valueGet.second.Get(); } - else if( ( DevelText::Outline::Property::WIDTH == valueGet.first.indexKey ) || ( WIDTH_KEY == valueGet.first.stringKey ) ) + else if((DevelText::Outline::Property::WIDTH == valueGet.first.indexKey) || (WIDTH_KEY == valueGet.first.stringKey)) { /// Width key. widthDefined = true; - width = static_cast( valueGet.second.Get() ); + width = static_cast(valueGet.second.Get()); } } return 0u == numberOfItems; } -bool ParseBackgroundProperties( const Property::Map& backgroundProperties, - bool& enabled, - bool& colorDefined, - Vector4& color ) +bool ParseBackgroundProperties(const Property::Map& backgroundProperties, + bool& enabled, + bool& colorDefined, + Vector4& color) { const unsigned int numberOfItems = backgroundProperties.Count(); // Parses and applies the style. - for( unsigned int index = 0u; index < numberOfItems; ++index ) + for(unsigned int index = 0u; index < numberOfItems; ++index) { - const KeyValuePair& valueGet = backgroundProperties.GetKeyValue( index ); + const KeyValuePair& valueGet = backgroundProperties.GetKeyValue(index); - if( ( DevelText::Background::Property::ENABLE == valueGet.first.indexKey ) || ( ENABLE_KEY == valueGet.first.stringKey ) ) + if((DevelText::Background::Property::ENABLE == valueGet.first.indexKey) || (ENABLE_KEY == valueGet.first.stringKey)) { /// Enable key. enabled = valueGet.second.Get(); } - else if( ( DevelText::Background::Property::COLOR == valueGet.first.indexKey ) || ( COLOR_KEY == valueGet.first.stringKey ) ) + else if((DevelText::Background::Property::COLOR == valueGet.first.indexKey) || (COLOR_KEY == valueGet.first.stringKey)) { /// Color key. colorDefined = true; - color = valueGet.second.Get(); + color = valueGet.second.Get(); } } return 0u == numberOfItems; } -bool SetUnderlineProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type ) +bool SetUnderlineProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type) { bool update = false; - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { const Property::Map& propertiesMap = value.Get(); - bool enabled = false; - bool colorDefined = false; + bool enabled = false; + bool colorDefined = false; Vector4 color; - bool heightDefined = false; - float height = 0.f; + bool heightDefined = false; + float height = 0.f; bool empty = true; - if ( propertiesMap.Empty() ) + if(propertiesMap.Empty()) { // Map empty so check if a string provided const std::string propertyString = value.Get(); - if ( !propertyString.empty() ) + if(!propertyString.empty()) { Property::Map parsedStringMap; - Text::ParsePropertyString( propertyString, parsedStringMap ); + Text::ParsePropertyString(propertyString, parsedStringMap); - empty = ParseUnderlineProperties( parsedStringMap, - enabled, - colorDefined, - color, - heightDefined, - height ); + empty = ParseUnderlineProperties(parsedStringMap, + enabled, + colorDefined, + color, + heightDefined, + height); - controller->UnderlineSetByString( !empty ); + controller->UnderlineSetByString(!empty); } } else { - empty = ParseUnderlineProperties( propertiesMap, - enabled, - colorDefined, - color, - heightDefined, - height ); + empty = ParseUnderlineProperties(propertiesMap, + enabled, + colorDefined, + color, + heightDefined, + height); - controller->UnderlineSetByString( false ); + controller->UnderlineSetByString(false); } - if( !empty ) + if(!empty) { - if( enabled != controller->IsUnderlineEnabled() ) + if(enabled != controller->IsUnderlineEnabled()) { - controller->SetUnderlineEnabled( enabled ); + controller->SetUnderlineEnabled(enabled); update = true; } // Sets the default underline values. - if( colorDefined && ( controller->GetUnderlineColor() != color ) ) + if(colorDefined && (controller->GetUnderlineColor() != color)) { - controller->SetUnderlineColor( color ); + controller->SetUnderlineColor(color); update = true; } - if( heightDefined && ( fabsf( controller->GetUnderlineHeight() - height ) > Math::MACHINE_EPSILON_1000 ) ) + if(heightDefined && (fabsf(controller->GetUnderlineHeight() - height) > Math::MACHINE_EPSILON_1000)) { - controller->SetUnderlineHeight( height ); + controller->SetUnderlineHeight(height); update = true; } } else { // Disable underline. - if( controller->IsUnderlineEnabled() ) + if(controller->IsUnderlineEnabled()) { - controller->SetUnderlineEnabled( false ); + controller->SetUnderlineEnabled(false); update = true; } } @@ -317,39 +314,39 @@ bool SetUnderlineProperties( ControllerPtr controller, const Property::Value& va { const std::string& underlineProperties = value.Get(); - controller->SetInputUnderlineProperties( underlineProperties ); + controller->SetInputUnderlineProperties(underlineProperties); break; } } // switch - } // if( controller ) + } // if( controller ) return update; } -void GetUnderlineProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type ) +void GetUnderlineProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type) { - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { - const bool enabled = controller->IsUnderlineEnabled(); - const Vector4& color = controller->GetUnderlineColor(); - const float height = controller->GetUnderlineHeight(); + const bool enabled = controller->IsUnderlineEnabled(); + const Vector4& color = controller->GetUnderlineColor(); + const float height = controller->GetUnderlineHeight(); - if ( controller->IsUnderlineSetByString() ) + if(controller->IsUnderlineSetByString()) { - std::string underlineProperties = "{\"enable\":"; - const std::string enabledStr = enabled ? "true" : "false"; + std::string underlineProperties = "{\"enable\":"; + const std::string enabledStr = enabled ? "true" : "false"; underlineProperties += "\"" + enabledStr + "\","; std::string colorStr; - Vector4ToColorString( color, colorStr ); + Vector4ToColorString(color, colorStr); underlineProperties += "\"color\":\"" + colorStr + "\","; std::string heightStr; - FloatToString( height, heightStr ); + FloatToString(height, heightStr); underlineProperties += "\"height\":\"" + heightStr + "\"}"; value = underlineProperties; @@ -358,9 +355,9 @@ void GetUnderlineProperties( ControllerPtr controller, Property::Value& value, E { Property::Map map; - map.Insert( ENABLE_KEY, enabled ); - map.Insert( COLOR_KEY, color ); - map.Insert( HEIGHT_KEY, height ); + map.Insert(ENABLE_KEY, enabled); + map.Insert(COLOR_KEY, color); + map.Insert(HEIGHT_KEY, height); value = map; } @@ -376,86 +373,85 @@ void GetUnderlineProperties( ControllerPtr controller, Property::Value& value, E } } -bool SetShadowProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type ) +bool SetShadowProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type) { bool update = false; - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { const Property::Map& propertiesMap = value.Get(); - bool colorDefined = false; + bool colorDefined = false; Vector4 color; - bool offsetDefined = false; + bool offsetDefined = false; Vector2 offset; - bool blurRadiusDefined = false; - float blurRadius; + bool blurRadiusDefined = false; + float blurRadius; bool empty = true; - if ( propertiesMap.Empty() ) + if(propertiesMap.Empty()) { - // Map empty so check if a string provided - const std::string propertyString = value.Get(); - - Property::Map parsedStringMap; - Text::ParsePropertyString( propertyString, parsedStringMap ); + // Map empty so check if a string provided + const std::string propertyString = value.Get(); - empty = ParseShadowProperties( parsedStringMap, - colorDefined, - color, - offsetDefined, - offset, - blurRadiusDefined, - blurRadius ); + Property::Map parsedStringMap; + Text::ParsePropertyString(propertyString, parsedStringMap); - controller->ShadowSetByString( !empty ); + empty = ParseShadowProperties(parsedStringMap, + colorDefined, + color, + offsetDefined, + offset, + blurRadiusDefined, + blurRadius); + controller->ShadowSetByString(!empty); } else { - empty = ParseShadowProperties( propertiesMap, - colorDefined, - color, - offsetDefined, - offset, - blurRadiusDefined, - blurRadius ); - - controller->ShadowSetByString( false ); + empty = ParseShadowProperties(propertiesMap, + colorDefined, + color, + offsetDefined, + offset, + blurRadiusDefined, + blurRadius); + + controller->ShadowSetByString(false); } - if( !empty ) + if(!empty) { // Sets the default shadow values. - if( colorDefined && ( controller->GetShadowColor() != color ) ) + if(colorDefined && (controller->GetShadowColor() != color)) { - controller->SetShadowColor( color ); + controller->SetShadowColor(color); update = true; } - if( offsetDefined && ( controller->GetShadowOffset() != offset ) ) + if(offsetDefined && (controller->GetShadowOffset() != offset)) { - controller->SetShadowOffset( offset ); + controller->SetShadowOffset(offset); update = true; } - if( blurRadiusDefined && ( controller->GetShadowBlurRadius() != blurRadius ) ) + if(blurRadiusDefined && (controller->GetShadowBlurRadius() != blurRadius)) { - controller->SetShadowBlurRadius( blurRadius ); + controller->SetShadowBlurRadius(blurRadius); update = true; } } else { // Disable shadow. - if( Vector2::ZERO != controller->GetShadowOffset() ) + if(Vector2::ZERO != controller->GetShadowOffset()) { - controller->SetShadowOffset( Vector2::ZERO ); + controller->SetShadowOffset(Vector2::ZERO); } } break; @@ -464,41 +460,41 @@ bool SetShadowProperties( ControllerPtr controller, const Property::Value& value { const std::string& shadowString = value.Get(); - controller->SetInputShadowProperties( shadowString ); + controller->SetInputShadowProperties(shadowString); break; } } // switch - } // if( controller ) + } // if( controller ) return update; } -void GetShadowProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type ) +void GetShadowProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type) { - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { - const Vector4& color = controller->GetShadowColor(); - const Vector2& offset = controller->GetShadowOffset(); - const float& blurRadius = controller->GetShadowBlurRadius(); + const Vector4& color = controller->GetShadowColor(); + const Vector2& offset = controller->GetShadowOffset(); + const float& blurRadius = controller->GetShadowBlurRadius(); - if ( controller->IsShadowSetByString() ) + if(controller->IsShadowSetByString()) { std::string shadowProperties = "{"; std::string colorStr; - Vector4ToColorString( color, colorStr ); + Vector4ToColorString(color, colorStr); shadowProperties += "\"color\":\"" + colorStr + "\","; std::string offsetStr; - Vector2ToString( offset, offsetStr ); + Vector2ToString(offset, offsetStr); shadowProperties += "\"offset\":\"" + offsetStr + "\","; std::string blurRadiusStr; - FloatToString( blurRadius, blurRadiusStr ); + FloatToString(blurRadius, blurRadiusStr); shadowProperties += "\"blurRadius\":\"" + blurRadiusStr + "\"}"; value = shadowProperties; @@ -507,9 +503,9 @@ void GetShadowProperties( ControllerPtr controller, Property::Value& value, Effe { Property::Map map; - map.Insert( COLOR_KEY, color ); - map.Insert( OFFSET_KEY, offset ); - map.Insert( BLUR_RADIUS_KEY, blurRadius ); + map.Insert(COLOR_KEY, color); + map.Insert(OFFSET_KEY, offset); + map.Insert(BLUR_RADIUS_KEY, blurRadius); value = map; } @@ -524,26 +520,26 @@ void GetShadowProperties( ControllerPtr controller, Property::Value& value, Effe } } -bool SetEmbossProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type ) +bool SetEmbossProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type) { bool update = false; - if( controller ) + if(controller) { - const std::string properties = value.Get< std::string >(); + const std::string properties = value.Get(); - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { // Stores the default emboss's properties string to be recovered by the GetEmbossProperties() function. - controller->SetDefaultEmbossProperties( properties ); + controller->SetDefaultEmbossProperties(properties); break; } case EffectStyle::INPUT: { // Stores the input emboss's properties string to be recovered by the GetEmbossProperties() function. - controller->SetInputEmbossProperties( properties ); + controller->SetInputEmbossProperties(properties); break; } } @@ -552,11 +548,11 @@ bool SetEmbossProperties( ControllerPtr controller, const Property::Value& value return update; } -void GetEmbossProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type ) +void GetEmbossProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type) { - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { @@ -572,68 +568,68 @@ void GetEmbossProperties( ControllerPtr controller, Property::Value& value, Effe } } -bool SetOutlineProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type ) +bool SetOutlineProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type) { bool update = false; - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { const Property::Map& propertiesMap = value.Get(); - bool colorDefined = false; - Vector4 color; - bool widthDefined = false; - uint16_t width = 0u; + bool colorDefined = false; + Vector4 color; + bool widthDefined = false; + uint16_t width = 0u; bool empty = true; - if ( propertiesMap.Empty() ) + if(propertiesMap.Empty()) { - // Map empty so check if a string provided - // This is purely to maintain backward compatibility, but we don't parse the string to be a property map. - const std::string propertyString = value.Get(); + // Map empty so check if a string provided + // This is purely to maintain backward compatibility, but we don't parse the string to be a property map. + const std::string propertyString = value.Get(); - // Stores the default outline's properties string to be recovered by the GetOutlineProperties() function. - controller->SetDefaultOutlineProperties( propertyString ); + // Stores the default outline's properties string to be recovered by the GetOutlineProperties() function. + controller->SetDefaultOutlineProperties(propertyString); - controller->OutlineSetByString( true ); + controller->OutlineSetByString(true); } else { - empty = ParseOutlineProperties( propertiesMap, - colorDefined, - color, - widthDefined, - width ); + empty = ParseOutlineProperties(propertiesMap, + colorDefined, + color, + widthDefined, + width); - controller->OutlineSetByString( false ); + controller->OutlineSetByString(false); } - if( !empty ) + if(!empty) { // Sets the default outline values. - if( colorDefined && ( controller->GetOutlineColor() != color ) ) + if(colorDefined && (controller->GetOutlineColor() != color)) { - controller->SetOutlineColor( color ); + controller->SetOutlineColor(color); update = true; } - if( widthDefined && ( controller->GetOutlineWidth() != width ) ) + if(widthDefined && (controller->GetOutlineWidth() != width)) { - controller->SetOutlineWidth( width ); + controller->SetOutlineWidth(width); update = true; } } else { // Disable outline - if( 0u != controller->GetOutlineWidth() ) + if(0u != controller->GetOutlineWidth()) { - controller->SetOutlineWidth( 0u ); + controller->SetOutlineWidth(0u); update = true; } } @@ -643,24 +639,24 @@ bool SetOutlineProperties( ControllerPtr controller, const Property::Value& valu { const std::string& outlineProperties = value.Get(); - controller->SetInputOutlineProperties( outlineProperties ); + controller->SetInputOutlineProperties(outlineProperties); break; } } // switch - } // if( controller ) + } // if( controller ) return update; } -void GetOutlineProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type ) +void GetOutlineProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type) { - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { - if ( controller->IsOutlineSetByString() ) + if(controller->IsOutlineSetByString()) { value = controller->GetDefaultOutlineProperties(); break; @@ -671,8 +667,8 @@ void GetOutlineProperties( ControllerPtr controller, Property::Value& value, Eff const uint16_t width = controller->GetOutlineWidth(); Property::Map map; - map.Insert( COLOR_KEY, color ); - map.Insert( WIDTH_KEY, static_cast( width ) ); + map.Insert(COLOR_KEY, color); + map.Insert(WIDTH_KEY, static_cast(width)); value = map; @@ -688,52 +684,52 @@ void GetOutlineProperties( ControllerPtr controller, Property::Value& value, Eff } } -bool SetBackgroundProperties( ControllerPtr controller, const Property::Value& value, EffectStyle::Type type ) +bool SetBackgroundProperties(ControllerPtr controller, const Property::Value& value, EffectStyle::Type type) { bool update = false; - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { const Property::Map& propertiesMap = value.Get(); - bool enabled = false; - bool colorDefined = false; + bool enabled = false; + bool colorDefined = false; Vector4 color; bool empty = true; - if ( !propertiesMap.Empty() ) + if(!propertiesMap.Empty()) { - empty = ParseBackgroundProperties( propertiesMap, - enabled, - colorDefined, - color ); + empty = ParseBackgroundProperties(propertiesMap, + enabled, + colorDefined, + color); } - if( !empty ) + if(!empty) { - if( enabled != controller->IsBackgroundEnabled() ) + if(enabled != controller->IsBackgroundEnabled()) { - controller->SetBackgroundEnabled( enabled ); + controller->SetBackgroundEnabled(enabled); update = true; } - if( colorDefined && ( controller->GetBackgroundColor() != color ) ) + if(colorDefined && (controller->GetBackgroundColor() != color)) { - controller->SetBackgroundColor( color ); + controller->SetBackgroundColor(color); update = true; } } else { // Disable background. - if( controller->IsBackgroundEnabled() ) + if(controller->IsBackgroundEnabled()) { - controller->SetBackgroundEnabled( false ); + controller->SetBackgroundEnabled(false); update = true; } } @@ -745,30 +741,29 @@ bool SetBackgroundProperties( ControllerPtr controller, const Property::Value& v break; } } // switch - } // if( controller ) + } // if( controller ) return update; } -void GetBackgroundProperties( ControllerPtr controller, Property::Value& value, EffectStyle::Type type ) +void GetBackgroundProperties(ControllerPtr controller, Property::Value& value, EffectStyle::Type type) { - if( controller ) + if(controller) { - switch( type ) + switch(type) { case EffectStyle::DEFAULT: { - const bool enabled = controller->IsBackgroundEnabled(); - const Vector4& color = controller->GetBackgroundColor(); + const bool enabled = controller->IsBackgroundEnabled(); + const Vector4& color = controller->GetBackgroundColor(); Property::Map map; - map.Insert( ENABLE_KEY, enabled ); - map.Insert( COLOR_KEY, color ); + map.Insert(ENABLE_KEY, enabled); + map.Insert(COLOR_KEY, color); value = map; break; - } case EffectStyle::INPUT: { @@ -779,7 +774,6 @@ void GetBackgroundProperties( ControllerPtr controller, Property::Value& value, } } - } // namespace Text } // namespace Toolkit diff --git a/dali-toolkit/internal/text/text-enumerations-impl.cpp b/dali-toolkit/internal/text/text-enumerations-impl.cpp index ce1c503..11ff5c6 100644 --- a/dali-toolkit/internal/text/text-enumerations-impl.cpp +++ b/dali-toolkit/internal/text/text-enumerations-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. @@ -26,60 +26,57 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { -DALI_ENUM_TO_STRING_TABLE_BEGIN( HORIZONTAL_ALIGNMENT_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::HorizontalAlignment, BEGIN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::HorizontalAlignment, CENTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::HorizontalAlignment, END ) -DALI_ENUM_TO_STRING_TABLE_END( HORIZONTAL_ALIGNMENT_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( VERTICAL_ALIGNMENT_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::VerticalAlignment, TOP ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::VerticalAlignment, CENTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::VerticalAlignment, BOTTOM ) -DALI_ENUM_TO_STRING_TABLE_END( VERTICAL_ALIGNMENT_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( LINE_WRAP_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::LineWrap, WORD ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Text::LineWrap, CHARACTER ) -DALI_ENUM_TO_STRING_TABLE_END( LINE_WRAP_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(HORIZONTAL_ALIGNMENT_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::HorizontalAlignment, BEGIN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::HorizontalAlignment, CENTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::HorizontalAlignment, END) +DALI_ENUM_TO_STRING_TABLE_END(HORIZONTAL_ALIGNMENT_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(VERTICAL_ALIGNMENT_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::VerticalAlignment, TOP) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::VerticalAlignment, CENTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::VerticalAlignment, BOTTOM) +DALI_ENUM_TO_STRING_TABLE_END(VERTICAL_ALIGNMENT_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(LINE_WRAP_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::LineWrap, WORD) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Text::LineWrap, CHARACTER) +DALI_ENUM_TO_STRING_TABLE_END(LINE_WRAP_MODE) } // namespace -bool GetHorizontalAlignmentEnumeration( const Property::Value& propertyValue, Toolkit::Text::HorizontalAlignment::Type& alignment ) +bool GetHorizontalAlignmentEnumeration(const Property::Value& propertyValue, Toolkit::Text::HorizontalAlignment::Type& alignment) { - return Scripting::GetEnumerationProperty( propertyValue, HORIZONTAL_ALIGNMENT_TYPE_TABLE, HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment ); + return Scripting::GetEnumerationProperty(propertyValue, HORIZONTAL_ALIGNMENT_TYPE_TABLE, HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment); } -bool GetVerticalAlignmentEnumeration( const Property::Value& propertyValue, Toolkit::Text::VerticalAlignment::Type& alignment ) +bool GetVerticalAlignmentEnumeration(const Property::Value& propertyValue, Toolkit::Text::VerticalAlignment::Type& alignment) { - return Scripting::GetEnumerationProperty( propertyValue, VERTICAL_ALIGNMENT_TYPE_TABLE, VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment ); + return Scripting::GetEnumerationProperty(propertyValue, VERTICAL_ALIGNMENT_TYPE_TABLE, VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT, alignment); } -bool GetLineWrapModeEnumeration( const Property::Value& propertyValue, Toolkit::Text::LineWrap::Mode& lineWrapMode ) +bool GetLineWrapModeEnumeration(const Property::Value& propertyValue, Toolkit::Text::LineWrap::Mode& lineWrapMode) { - return Scripting::GetEnumerationProperty( propertyValue, LINE_WRAP_MODE_TABLE, LINE_WRAP_MODE_TABLE_COUNT, lineWrapMode ); + return Scripting::GetEnumerationProperty(propertyValue, LINE_WRAP_MODE_TABLE, LINE_WRAP_MODE_TABLE_COUNT, lineWrapMode); } -const char* GetHorizontalAlignmentString( const Toolkit::Text::HorizontalAlignment::Type& alignment ) +const char* GetHorizontalAlignmentString(const Toolkit::Text::HorizontalAlignment::Type& alignment) { - return Scripting::GetLinearEnumerationName< Toolkit::Text::HorizontalAlignment::Type >( alignment, - HORIZONTAL_ALIGNMENT_TYPE_TABLE, - HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT ); + return Scripting::GetLinearEnumerationName(alignment, + HORIZONTAL_ALIGNMENT_TYPE_TABLE, + HORIZONTAL_ALIGNMENT_TYPE_TABLE_COUNT); } -const char* GetVerticalAlignmentString( const Toolkit::Text::VerticalAlignment::Type& alignment ) +const char* GetVerticalAlignmentString(const Toolkit::Text::VerticalAlignment::Type& alignment) { - return Scripting::GetLinearEnumerationName< Toolkit::Text::VerticalAlignment::Type >( alignment, - VERTICAL_ALIGNMENT_TYPE_TABLE, - VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT ); + return Scripting::GetLinearEnumerationName(alignment, + VERTICAL_ALIGNMENT_TYPE_TABLE, + VERTICAL_ALIGNMENT_TYPE_TABLE_COUNT); } } // namespace Text diff --git a/dali-toolkit/internal/text/text-font-style.cpp b/dali-toolkit/internal/text/text-font-style.cpp index 927f277..117268a 100644 --- a/dali-toolkit/internal/text/text-font-style.cpp +++ b/dali-toolkit/internal/text/text-font-style.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. @@ -22,282 +22,278 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Text { - namespace { -const std::string STYLE_KEY( "style" ); -const std::string WEIGHT_KEY( "weight" ); -const std::string WIDTH_KEY( "width" ); -const std::string SLANT_KEY( "slant" ); -const std::string FAMILY_KEY( "family" ); -const std::string TYPE_KEY( "type" ); +const std::string STYLE_KEY("style"); +const std::string WEIGHT_KEY("weight"); +const std::string WIDTH_KEY("width"); +const std::string SLANT_KEY("slant"); +const std::string FAMILY_KEY("family"); +const std::string TYPE_KEY("type"); -const std::string SYSTEM_TOKEN( "system" ); +const std::string SYSTEM_TOKEN("system"); } // namespace -void SetFontFamilyProperty( ControllerPtr controller, const Property::Value& value ) +void SetFontFamilyProperty(ControllerPtr controller, const Property::Value& value) { - if( controller ) + if(controller) { const std::string fontFamilyValue = value.Get(); - if( fontFamilyValue.empty() ) + if(fontFamilyValue.empty()) { // Resets the default's font family name. - controller->SetDefaultFontFamily( "" ); + controller->SetDefaultFontFamily(""); return; } Property::Map map; - ParsePropertyString( fontFamilyValue, map ); + ParsePropertyString(fontFamilyValue, map); - if( map.Empty() ) + if(map.Empty()) { // There is no map. The font has been passed as a font's family name with no format. - controller->SetDefaultFontFamily( fontFamilyValue ); + controller->SetDefaultFontFamily(fontFamilyValue); } else { /// Family key - Property::Value* familyValue = map.Find( FAMILY_KEY ); + Property::Value* familyValue = map.Find(FAMILY_KEY); std::string fontFamilyName; - if( NULL != familyValue ) + if(NULL != familyValue) { fontFamilyName = familyValue->Get(); } /// Type key - Property::Value* typeValue = map.Find( TYPE_KEY ); + Property::Value* typeValue = map.Find(TYPE_KEY); std::string typeStr; - if( NULL != typeValue ) + if(NULL != typeValue) { typeStr = typeValue->Get(); } - if( TokenComparison( SYSTEM_TOKEN, typeStr.c_str(), typeStr.size() ) ) + if(TokenComparison(SYSTEM_TOKEN, typeStr.c_str(), typeStr.size())) { - controller->UpdateAfterFontChange( fontFamilyName ); + controller->UpdateAfterFontChange(fontFamilyName); } else { - controller->SetDefaultFontFamily( fontFamilyName ); + controller->SetDefaultFontFamily(fontFamilyName); } } } } -void SetFontStyleProperty( ControllerPtr controller, const Property::Value& value, FontStyle::Type type ) +void SetFontStyleProperty(ControllerPtr controller, const Property::Value& value, FontStyle::Type type) { - if( controller ) + if(controller) { Property::Map map; - if( Property::STRING == value.GetType() ) + if(Property::STRING == value.GetType()) { const std::string& fontStyleProperties = value.Get(); - ParsePropertyString( fontStyleProperties, map ); - controller->FontStyleSetByString( true ); - + ParsePropertyString(fontStyleProperties, map); + controller->FontStyleSetByString(true); } else { map = value.Get(); - controller->FontStyleSetByString( false ); + controller->FontStyleSetByString(false); } - if( !map.Empty() ) + if(!map.Empty()) { /// Weight key - Property::Value* weightValue = map.Find( WEIGHT_KEY ); + Property::Value* weightValue = map.Find(WEIGHT_KEY); - FontWeight weight = TextAbstraction::FontWeight::NONE; + FontWeight weight = TextAbstraction::FontWeight::NONE; const bool weightDefined = weightValue != NULL; - if( weightDefined ) + if(weightDefined) { const std::string weightStr = weightValue->Get(); - Scripting::GetEnumeration< FontWeight >( weightStr.c_str(), - FONT_WEIGHT_STRING_TABLE, - FONT_WEIGHT_STRING_TABLE_COUNT, - weight ); + Scripting::GetEnumeration(weightStr.c_str(), + FONT_WEIGHT_STRING_TABLE, + FONT_WEIGHT_STRING_TABLE_COUNT, + weight); } /// Width key - Property::Value* widthValue = map.Find( WIDTH_KEY ); + Property::Value* widthValue = map.Find(WIDTH_KEY); - FontWidth width = TextAbstraction::FontWidth::NONE; + FontWidth width = TextAbstraction::FontWidth::NONE; const bool widthDefined = widthValue != NULL; - if( widthDefined ) + if(widthDefined) { const std::string widthStr = widthValue->Get(); - Scripting::GetEnumeration< FontWidth >( widthStr.c_str(), - FONT_WIDTH_STRING_TABLE, - FONT_WIDTH_STRING_TABLE_COUNT, - width ); + Scripting::GetEnumeration(widthStr.c_str(), + FONT_WIDTH_STRING_TABLE, + FONT_WIDTH_STRING_TABLE_COUNT, + width); } /// Slant key - Property::Value* slantValue = map.Find( SLANT_KEY ); + Property::Value* slantValue = map.Find(SLANT_KEY); - FontSlant slant = TextAbstraction::FontSlant::NONE; + FontSlant slant = TextAbstraction::FontSlant::NONE; const bool slantDefined = slantValue != NULL; - if( slantDefined ) + if(slantDefined) { const std::string slantStr = slantValue->Get(); - Scripting::GetEnumeration< FontSlant >( slantStr.c_str(), - FONT_SLANT_STRING_TABLE, - FONT_SLANT_STRING_TABLE_COUNT, - slant ); + Scripting::GetEnumeration(slantStr.c_str(), + FONT_SLANT_STRING_TABLE, + FONT_SLANT_STRING_TABLE_COUNT, + slant); } - switch( type ) + switch(type) { case FontStyle::DEFAULT: { // Sets the default font's style values. - if( !weightDefined || - ( weightDefined && ( controller->GetDefaultFontWeight() != weight ) ) ) + if(!weightDefined || + (weightDefined && (controller->GetDefaultFontWeight() != weight))) { - controller->SetDefaultFontWeight( weight ); + controller->SetDefaultFontWeight(weight); } - if( !widthDefined || - ( widthDefined && ( controller->GetDefaultFontWidth() != width ) ) ) + if(!widthDefined || + (widthDefined && (controller->GetDefaultFontWidth() != width))) { - controller->SetDefaultFontWidth( width ); + controller->SetDefaultFontWidth(width); } - if( !slantDefined || - ( slantDefined && ( controller->GetDefaultFontSlant() != slant ) ) ) + if(!slantDefined || + (slantDefined && (controller->GetDefaultFontSlant() != slant))) { - controller->SetDefaultFontSlant( slant ); + controller->SetDefaultFontSlant(slant); } break; } case FontStyle::INPUT: { // Sets the input font's style values. - if( !weightDefined || - ( weightDefined && ( controller->GetInputFontWeight() != weight ) ) ) + if(!weightDefined || + (weightDefined && (controller->GetInputFontWeight() != weight))) { - controller->SetInputFontWeight( weight ); + controller->SetInputFontWeight(weight); } - if( !widthDefined || - ( widthDefined && ( controller->GetInputFontWidth() != width ) ) ) + if(!widthDefined || + (widthDefined && (controller->GetInputFontWidth() != width))) { - controller->SetInputFontWidth( width ); + controller->SetInputFontWidth(width); } - if( !slantDefined || - ( slantDefined && ( controller->GetInputFontSlant() != slant ) ) ) + if(!slantDefined || + (slantDefined && (controller->GetInputFontSlant() != slant))) { - controller->SetInputFontSlant( slant ); + controller->SetInputFontSlant(slant); } break; } case FontStyle::PLACEHOLDER: { // Sets the placeholder text font's style values. - if( !weightDefined || - ( weightDefined && ( controller->GetPlaceholderTextFontWeight() != weight ) ) ) + if(!weightDefined || + (weightDefined && (controller->GetPlaceholderTextFontWeight() != weight))) { - controller->SetPlaceholderTextFontWeight( weight ); + controller->SetPlaceholderTextFontWeight(weight); } - if( !widthDefined || - ( widthDefined && ( controller->GetPlaceholderTextFontWidth() != width ) ) ) + if(!widthDefined || + (widthDefined && (controller->GetPlaceholderTextFontWidth() != width))) { - controller->SetPlaceholderTextFontWidth( width ); + controller->SetPlaceholderTextFontWidth(width); } - if( !slantDefined || - ( slantDefined && ( controller->GetPlaceholderTextFontSlant() != slant ) ) ) + if(!slantDefined || + (slantDefined && (controller->GetPlaceholderTextFontSlant() != slant))) { - controller->SetPlaceholderTextFontSlant( slant ); + controller->SetPlaceholderTextFontSlant(slant); } break; } } // switch - } // map not empty + } // map not empty else { - switch( type ) + switch(type) { case FontStyle::DEFAULT: { - controller->SetDefaultFontWeight( TextAbstraction::FontWeight::NONE ); - controller->SetDefaultFontWidth( TextAbstraction::FontWidth::NONE ); - controller->SetDefaultFontSlant( TextAbstraction::FontSlant::NONE ); + controller->SetDefaultFontWeight(TextAbstraction::FontWeight::NONE); + controller->SetDefaultFontWidth(TextAbstraction::FontWidth::NONE); + controller->SetDefaultFontSlant(TextAbstraction::FontSlant::NONE); break; } case FontStyle::INPUT: { - controller->SetInputFontWeight( TextAbstraction::FontWeight::NONE ); - controller->SetInputFontWidth( TextAbstraction::FontWidth::NONE ); - controller->SetInputFontSlant( TextAbstraction::FontSlant::NONE ); + controller->SetInputFontWeight(TextAbstraction::FontWeight::NONE); + controller->SetInputFontWidth(TextAbstraction::FontWidth::NONE); + controller->SetInputFontSlant(TextAbstraction::FontSlant::NONE); break; } case FontStyle::PLACEHOLDER: { - controller->SetPlaceholderTextFontWeight( TextAbstraction::FontWeight::NONE ); - controller->SetPlaceholderTextFontWidth( TextAbstraction::FontWidth::NONE ); - controller->SetPlaceholderTextFontSlant( TextAbstraction::FontSlant::NONE ); + controller->SetPlaceholderTextFontWeight(TextAbstraction::FontWeight::NONE); + controller->SetPlaceholderTextFontWidth(TextAbstraction::FontWidth::NONE); + controller->SetPlaceholderTextFontSlant(TextAbstraction::FontSlant::NONE); break; } } // switch - } // map.Empty() - } // controller + } // map.Empty() + } // controller } -void GetFontStyleProperty( ControllerPtr controller, Property::Value& value, FontStyle::Type type ) +void GetFontStyleProperty(ControllerPtr controller, Property::Value& value, FontStyle::Type type) { - if( controller ) + if(controller) { const bool isSetbyString = controller->IsFontStyleSetByString(); - bool weightDefined = false; - bool widthDefined = false; - bool slantDefined = false; - FontWeight weight = TextAbstraction::FontWeight::NONE; - FontWidth width = TextAbstraction::FontWidth::NONE; - FontSlant slant = TextAbstraction::FontSlant::NONE; + bool weightDefined = false; + bool widthDefined = false; + bool slantDefined = false; + FontWeight weight = TextAbstraction::FontWeight::NONE; + FontWidth width = TextAbstraction::FontWidth::NONE; + FontSlant slant = TextAbstraction::FontSlant::NONE; - switch( type ) + switch(type) { case FontStyle::DEFAULT: { weightDefined = controller->IsDefaultFontWeightDefined(); - widthDefined = controller->IsDefaultFontWidthDefined(); - slantDefined = controller->IsDefaultFontSlantDefined(); + widthDefined = controller->IsDefaultFontWidthDefined(); + slantDefined = controller->IsDefaultFontSlantDefined(); - if( weightDefined ) + if(weightDefined) { weight = controller->GetDefaultFontWeight(); } - if( widthDefined ) + if(widthDefined) { width = controller->GetDefaultFontWidth(); } - if( slantDefined ) + if(slantDefined) { slant = controller->GetDefaultFontSlant(); } @@ -306,20 +302,20 @@ void GetFontStyleProperty( ControllerPtr controller, Property::Value& value, Fon case FontStyle::INPUT: { weightDefined = controller->IsInputFontWeightDefined(); - widthDefined = controller->IsInputFontWidthDefined(); - slantDefined = controller->IsInputFontSlantDefined(); + widthDefined = controller->IsInputFontWidthDefined(); + slantDefined = controller->IsInputFontSlantDefined(); - if( weightDefined ) + if(weightDefined) { weight = controller->GetInputFontWeight(); } - if( widthDefined ) + if(widthDefined) { width = controller->GetInputFontWidth(); } - if( slantDefined ) + if(slantDefined) { slant = controller->GetInputFontSlant(); } @@ -329,20 +325,20 @@ void GetFontStyleProperty( ControllerPtr controller, Property::Value& value, Fon { // The type is FontStyle::PLACEHOLDER weightDefined = controller->IsPlaceholderTextFontWeightDefined(); - widthDefined = controller->IsPlaceholderTextFontWidthDefined(); - slantDefined = controller->IsPlaceholderTextFontSlantDefined(); + widthDefined = controller->IsPlaceholderTextFontWidthDefined(); + slantDefined = controller->IsPlaceholderTextFontSlantDefined(); - if( weightDefined ) + if(weightDefined) { weight = controller->GetPlaceholderTextFontWeight(); } - if( widthDefined ) + if(widthDefined) { width = controller->GetPlaceholderTextFontWidth(); } - if( slantDefined ) + if(slantDefined) { slant = controller->GetPlaceholderTextFontSlant(); } @@ -350,43 +346,43 @@ void GetFontStyleProperty( ControllerPtr controller, Property::Value& value, Fon } } - if( !isSetbyString ) + if(!isSetbyString) { Property::Map map; - if( weightDefined ) + if(weightDefined) { - if( TextAbstraction::FontWeight::NONE != weight ) + if(TextAbstraction::FontWeight::NONE != weight) { - const std::string weightStr( GetEnumerationName( weight, - FONT_WEIGHT_STRING_TABLE, - FONT_WEIGHT_STRING_TABLE_COUNT ) ); + const std::string weightStr(GetEnumerationName(weight, + FONT_WEIGHT_STRING_TABLE, + FONT_WEIGHT_STRING_TABLE_COUNT)); - map.Insert( WEIGHT_KEY, weightStr ); + map.Insert(WEIGHT_KEY, weightStr); } } - if( widthDefined ) + if(widthDefined) { - if( TextAbstraction::FontWidth::NONE != width ) + if(TextAbstraction::FontWidth::NONE != width) { - const std::string widthStr( GetEnumerationName( width, - FONT_WIDTH_STRING_TABLE, - FONT_WIDTH_STRING_TABLE_COUNT ) ); + const std::string widthStr(GetEnumerationName(width, + FONT_WIDTH_STRING_TABLE, + FONT_WIDTH_STRING_TABLE_COUNT)); - map.Insert( WIDTH_KEY, widthStr ); + map.Insert(WIDTH_KEY, widthStr); } } - if( slantDefined ) + if(slantDefined) { - if( TextAbstraction::FontSlant::NONE != slant ) + if(TextAbstraction::FontSlant::NONE != slant) { - const std::string slantStr( GetEnumerationName( slant, - FONT_SLANT_STRING_TABLE, - FONT_SLANT_STRING_TABLE_COUNT ) ); + const std::string slantStr(GetEnumerationName(slant, + FONT_SLANT_STRING_TABLE, + FONT_SLANT_STRING_TABLE_COUNT)); - map.Insert( SLANT_KEY, slantStr ); + map.Insert(SLANT_KEY, slantStr); } } @@ -396,82 +392,82 @@ void GetFontStyleProperty( ControllerPtr controller, Property::Value& value, Fon { std::string fontStyleProperties = "{"; - if( weightDefined ) + if(weightDefined) { - if( TextAbstraction::FontWeight::NONE != weight ) + if(TextAbstraction::FontWeight::NONE != weight) { - const std::string weightStr( GetEnumerationName( weight, - FONT_WEIGHT_STRING_TABLE, - FONT_WEIGHT_STRING_TABLE_COUNT ) ); + const std::string weightStr(GetEnumerationName(weight, + FONT_WEIGHT_STRING_TABLE, + FONT_WEIGHT_STRING_TABLE_COUNT)); fontStyleProperties += "\"weight\":\"" + weightStr + "\","; } } - if( widthDefined ) + if(widthDefined) { - if( TextAbstraction::FontWidth::NONE != width ) + if(TextAbstraction::FontWidth::NONE != width) { - const std::string widthStr( GetEnumerationName( width, - FONT_WIDTH_STRING_TABLE, - FONT_WIDTH_STRING_TABLE_COUNT ) ); + const std::string widthStr(GetEnumerationName(width, + FONT_WIDTH_STRING_TABLE, + FONT_WIDTH_STRING_TABLE_COUNT)); fontStyleProperties += "\"width\":\"" + widthStr + "\","; } } - if( slantDefined ) + if(slantDefined) { - if( TextAbstraction::FontSlant::NONE != slant ) + if(TextAbstraction::FontSlant::NONE != slant) { - const std::string slantStr( GetEnumerationName( slant, - FONT_SLANT_STRING_TABLE, - FONT_SLANT_STRING_TABLE_COUNT ) ); + const std::string slantStr(GetEnumerationName(slant, + FONT_SLANT_STRING_TABLE, + FONT_SLANT_STRING_TABLE_COUNT)); fontStyleProperties += "\"slant\":\"" + slantStr + "\""; } } // If last character is comma, it will be removed. - if((*fontStyleProperties.rbegin()) == ',' ) + if((*fontStyleProperties.rbegin()) == ',') { - fontStyleProperties = fontStyleProperties.substr( 0, fontStyleProperties.size()-1 ); + fontStyleProperties = fontStyleProperties.substr(0, fontStyleProperties.size() - 1); } fontStyleProperties += "}"; value = fontStyleProperties; } // SetbyString - }// controller + } // controller } -FontWeight StringToWeight( const char* const weightStr ) +FontWeight StringToWeight(const char* const weightStr) { FontWeight weight = TextAbstraction::FontWeight::NORMAL; - Scripting::GetEnumeration( weightStr, - FONT_WEIGHT_STRING_TABLE, - FONT_WEIGHT_STRING_TABLE_COUNT, - weight ); + Scripting::GetEnumeration(weightStr, + FONT_WEIGHT_STRING_TABLE, + FONT_WEIGHT_STRING_TABLE_COUNT, + weight); return weight; } -FontWidth StringToWidth( const char* const widthStr ) +FontWidth StringToWidth(const char* const widthStr) { FontWidth width = TextAbstraction::FontWidth::NORMAL; - Scripting::GetEnumeration( widthStr, - FONT_WIDTH_STRING_TABLE, - FONT_WIDTH_STRING_TABLE_COUNT, - width ); + Scripting::GetEnumeration(widthStr, + FONT_WIDTH_STRING_TABLE, + FONT_WIDTH_STRING_TABLE_COUNT, + width); return width; } -FontSlant StringToSlant( const char* const slantStr ) +FontSlant StringToSlant(const char* const slantStr) { FontSlant slant = TextAbstraction::FontSlant::NORMAL; - Scripting::GetEnumeration( slantStr, - FONT_SLANT_STRING_TABLE, - FONT_SLANT_STRING_TABLE_COUNT, - slant ); + Scripting::GetEnumeration(slantStr, + FONT_SLANT_STRING_TABLE, + FONT_SLANT_STRING_TABLE_COUNT, + slant); return slant; } diff --git a/dali-toolkit/internal/text/text-io.cpp b/dali-toolkit/internal/text/text-io.cpp index 279e1aa..f90822e 100644 --- a/dali-toolkit/internal/text/text-io.cpp +++ b/dali-toolkit/internal/text/text-io.cpp @@ -19,27 +19,24 @@ #include // EXTERNAL INCLUDES -#include #include #include +#include namespace Dali { - namespace Toolkit { - namespace Text { - -std::ostream& operator<< (std::ostream& o, const Vector& text) +std::ostream& operator<<(std::ostream& o, const Vector& text) { o << std::hex; - for( unsigned int i=0; i& text) return o << std::dec; } -std::ostream& operator<< (std::ostream& o, const Vector& scriptRun) +std::ostream& operator<<(std::ostream& o, const Vector& scriptRun) { - for( unsigned int i=0; i9: LATIN" for a ten character run staring from beginning of the model - o << scriptRun[i].characterRun.characterIndex << "->" << (scriptRun[i].characterRun.characterIndex + scriptRun[i].characterRun.numberOfCharacters ) << ": "; + o << scriptRun[i].characterRun.characterIndex << "->" << (scriptRun[i].characterRun.characterIndex + scriptRun[i].characterRun.numberOfCharacters) << ": "; o << TextAbstraction::ScriptName[scriptRun[i].script]; - if( i+1 < scriptRun.Count() ) + if(i + 1 < scriptRun.Count()) { o << ", "; } @@ -65,21 +62,21 @@ std::ostream& operator<< (std::ostream& o, const Vector& scriptRun) return o << std::dec; } -std::ostream& operator<< (std::ostream& o, const Vector& fontRun) +std::ostream& operator<<(std::ostream& o, const Vector& fontRun) { TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - for( unsigned int i=0; i9: ID:1 TizenSansKorean style:Regular size:10.0" for a ten character run staring from beginning of the model - o << fontRun[i].characterRun.characterIndex << "->" << (fontRun[i].characterRun.characterIndex + fontRun[i].characterRun.numberOfCharacters ) << ": "; + o << fontRun[i].characterRun.characterIndex << "->" << (fontRun[i].characterRun.characterIndex + fontRun[i].characterRun.numberOfCharacters) << ": "; - FontId id = fontRun[i].fontId; + FontId id = fontRun[i].fontId; TextAbstraction::FontDescription fontDescription; - fontClient.GetDescription( id, fontDescription ); - o << "ID:" << id << ", " << fontDescription.family << " width: " << fontDescription.width << " weight: " << fontDescription.weight << " slant: " << fontDescription.slant << " size:" << (fontClient.GetPointSize(id) / 64); + fontClient.GetDescription(id, fontDescription); + o << "ID:" << id << ", " << fontDescription.family << " width: " << fontDescription.width << " weight: " << fontDescription.weight << " slant: " << fontDescription.slant << " size:" << (fontClient.GetPointSize(id) / 64); - if( i+1 < fontRun.Count() ) + if(i + 1 < fontRun.Count()) { o << ", "; } @@ -88,18 +85,18 @@ std::ostream& operator<< (std::ostream& o, const Vector& fontRun) return o << std::dec; } -std::ostream& operator<< (std::ostream& o, const Vector& lineRuns) +std::ostream& operator<<(std::ostream& o, const Vector& lineRuns) { - for( unsigned int i=0; i9 Characters: 0->9 (10)" for a ten character run staring from beginning of the model - o << "Line " << i << " Glyphs: " << lineRuns[i].glyphRun.glyphIndex << "->" << (lineRuns[i].glyphRun.glyphIndex + lineRuns[i].glyphRun.numberOfGlyphs ); - o << " Characters: " << lineRuns[i].characterRun.characterIndex << "->" << (lineRuns[i].characterRun.characterIndex + lineRuns[i].characterRun.numberOfCharacters ); + o << "Line " << i << " Glyphs: " << lineRuns[i].glyphRun.glyphIndex << "->" << (lineRuns[i].glyphRun.glyphIndex + lineRuns[i].glyphRun.numberOfGlyphs); + o << " Characters: " << lineRuns[i].characterRun.characterIndex << "->" << (lineRuns[i].characterRun.characterIndex + lineRuns[i].characterRun.numberOfCharacters); o << " Width: " << lineRuns[i].width; o << " Ascender: " << lineRuns[i].ascender; o << " Descender: " << lineRuns[i].descender; - if( i+1 < lineRuns.Count() ) + if(i + 1 < lineRuns.Count()) { o << ", "; } diff --git a/dali-toolkit/internal/text/text-model.cpp b/dali-toolkit/internal/text/text-model.cpp old mode 100755 new mode 100644 index c1767d8..2d60854 --- a/dali-toolkit/internal/text/text-model.cpp +++ b/dali-toolkit/internal/text/text-model.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,16 +20,13 @@ namespace Dali { - namespace Toolkit { - namespace Text { - ModelPtr Model::New() { - return ModelPtr( new Model() ); + return ModelPtr(new Model()); } const Size& Model::GetControlSize() const @@ -162,9 +159,9 @@ Length Model::GetNumberOfUnderlineRuns() const return mVisualModel->GetNumberOfUnderlineRuns(); } -void Model::GetUnderlineRuns( GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns ) const +void Model::GetUnderlineRuns(GlyphRun* underlineRuns, UnderlineRunIndex index, Length numberOfRuns) const { - mVisualModel->GetUnderlineRuns( underlineRuns, index, numberOfRuns ); + mVisualModel->GetUnderlineRuns(underlineRuns, index, numberOfRuns); } const Vector4& Model::GetOutlineColor() const @@ -192,17 +189,17 @@ Model::Model() mVisualModel(), mScrollPosition(), mScrollPositionLast(), - mHorizontalAlignment( Text::HorizontalAlignment::BEGIN ), - mVerticalAlignment( Text::VerticalAlignment::TOP ), - mVerticalLineAlignment( DevelText::VerticalLineAlignment::TOP ), - mLineWrapMode( Text::LineWrap::WORD ), - mAlignmentOffset( 0.0f ), - mElideEnabled( false ), - mIgnoreSpacesAfterText( true ), - mMatchSystemLanguageDirection( false ) + mHorizontalAlignment(Text::HorizontalAlignment::BEGIN), + mVerticalAlignment(Text::VerticalAlignment::TOP), + mVerticalLineAlignment(DevelText::VerticalLineAlignment::TOP), + mLineWrapMode(Text::LineWrap::WORD), + mAlignmentOffset(0.0f), + mElideEnabled(false), + mIgnoreSpacesAfterText(true), + mMatchSystemLanguageDirection(false) { mLogicalModel = LogicalModel::New(); - mVisualModel = VisualModel::New(); + mVisualModel = VisualModel::New(); } Model::~Model() diff --git a/dali-toolkit/internal/text/text-scroller.cpp b/dali-toolkit/internal/text/text-scroller.cpp old mode 100755 new mode 100644 index d908d33..cec4081 --- a/dali-toolkit/internal/text/text-scroller.cpp +++ b/dali-toolkit/internal/text/text-scroller.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,20 +22,17 @@ #include // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace { - -#if defined ( DEBUG_ENABLED ) - Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_SCROLLING"); +#if defined(DEBUG_ENABLED) +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_SCROLLING"); #endif const int MINIMUM_SCROLL_SPEED = 1; // Speed should be set by Property system. @@ -48,26 +45,25 @@ const int MINIMUM_SCROLL_SPEED = 1; // Speed should be set by Property system. * 1) The alignment value of the text label (Use Text::HorizontalAlignment enumerations). * 2) The text direction, i.e. whether it's LTR or RTL (0 = LTR, 1 = RTL). */ -const float HORIZONTAL_ALIGNMENT_TABLE[ Text::HorizontalAlignment::END+1 ][ 2 ] = -{ - // HorizontalAlignment::BEGIN +const float HORIZONTAL_ALIGNMENT_TABLE[Text::HorizontalAlignment::END + 1][2] = { - -0.5f, // LTR - 0.5f // RTL - }, + // HorizontalAlignment::BEGIN + { + -0.5f, // LTR + 0.5f // RTL + }, - // HorizontalAlignment::CENTER - { - 0.0f, // LTR - 0.0f // RTL - }, + // HorizontalAlignment::CENTER + { + 0.0f, // LTR + 0.0f // RTL + }, - // HorizontalAlignment::END - { - 0.5f, // LTR - -0.5f // RTL - } -}; + // HorizontalAlignment::END + { + 0.5f, // LTR + -0.5f // RTL + }}; /** * @brief How the text should be aligned vertically when scrolling the text. @@ -75,29 +71,28 @@ const float HORIZONTAL_ALIGNMENT_TABLE[ Text::HorizontalAlignment::END+1 ][ 2 ] * -0.5f aligns the text to the top, 0.0f aligns the text to the center, 0.5f aligns the text to the bottom. * The alignment depends on the alignment value of the text label (Use Text::VerticalAlignment enumerations). */ -const float VERTICAL_ALIGNMENT_TABLE[ Text::VerticalAlignment::BOTTOM+1 ] = -{ - -0.5f, // VerticalAlignment::TOP - 0.0f, // VerticalAlignment::CENTER - 0.5f // VerticalAlignment::BOTTOM +const float VERTICAL_ALIGNMENT_TABLE[Text::VerticalAlignment::BOTTOM + 1] = + { + -0.5f, // VerticalAlignment::TOP + 0.0f, // VerticalAlignment::CENTER + 0.5f // VerticalAlignment::BOTTOM }; } // namespace namespace Text { - -TextScrollerPtr TextScroller::New( ScrollerInterface& scrollerInterface ) +TextScrollerPtr TextScroller::New(ScrollerInterface& scrollerInterface) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::New\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::New\n"); - TextScrollerPtr textScroller( new TextScroller( scrollerInterface) ); + TextScrollerPtr textScroller(new TextScroller(scrollerInterface)); return textScroller; } -void TextScroller::SetGap( int gap ) +void TextScroller::SetGap(int gap) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetGap gap[%d]\n", gap ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetGap gap[%d]\n", gap); mWrapGap = static_cast(gap); } @@ -106,9 +101,9 @@ int TextScroller::GetGap() const return static_cast(mWrapGap); } -void TextScroller::SetSpeed( int scrollSpeed ) +void TextScroller::SetSpeed(int scrollSpeed) { - mScrollSpeed = std::max( MINIMUM_SCROLL_SPEED, scrollSpeed ); + mScrollSpeed = std::max(MINIMUM_SCROLL_SPEED, scrollSpeed); } int TextScroller::GetSpeed() const @@ -116,14 +111,14 @@ int TextScroller::GetSpeed() const return mScrollSpeed; } -void TextScroller::SetLoopCount( int loopCount ) +void TextScroller::SetLoopCount(int loopCount) { - if ( loopCount >= 0 ) + if(loopCount >= 0) { mLoopCount = loopCount; } - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetLoopCount [%d] Status[%s]\n", mLoopCount, (loopCount)?"looping":"stop" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetLoopCount [%d] Status[%s]\n", mLoopCount, (loopCount) ? "looping" : "stop"); } int TextScroller::GetLoopCount() const @@ -131,7 +126,7 @@ int TextScroller::GetLoopCount() const return mLoopCount; } -void TextScroller::SetLoopDelay( float delay ) +void TextScroller::SetLoopDelay(float delay) { mLoopDelay = delay; } @@ -141,17 +136,17 @@ float TextScroller::GetLoopDelay() const return mLoopDelay; } -void TextScroller::SetStopMode( TextLabel::AutoScrollStopMode::Type stopMode ) +void TextScroller::SetStopMode(TextLabel::AutoScrollStopMode::Type stopMode) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetAutoScrollStopMode [%s]\n",(stopMode == TextLabel::AutoScrollStopMode::IMMEDIATE)?"IMMEDIATE":"FINISH_LOOP" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetAutoScrollStopMode [%s]\n", (stopMode == TextLabel::AutoScrollStopMode::IMMEDIATE) ? "IMMEDIATE" : "FINISH_LOOP"); mStopMode = stopMode; } void TextScroller::StopScrolling() { - if ( mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING ) + if(mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING) { - switch( mStopMode ) + switch(mStopMode) { case TextLabel::AutoScrollStopMode::IMMEDIATE: { @@ -161,12 +156,12 @@ void TextScroller::StopScrolling() } case TextLabel::AutoScrollStopMode::FINISH_LOOP: { - mScrollAnimation.SetLoopCount( 1 ); // As animation already playing this allows the current animation to finish instead of trying to stop mid-way + mScrollAnimation.SetLoopCount(1); // As animation already playing this allows the current animation to finish instead of trying to stop mid-way break; } default: { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Undifined AutoScrollStopMode\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Undifined AutoScrollStopMode\n"); } } } @@ -181,120 +176,119 @@ TextLabel::AutoScrollStopMode::Type TextScroller::GetStopMode() const return mStopMode; } -TextScroller::TextScroller( ScrollerInterface& scrollerInterface ) -: mScrollerInterface( scrollerInterface ), - mScrollDeltaIndex( Property::INVALID_INDEX ), - mScrollSpeed( MINIMUM_SCROLL_SPEED ), - mLoopCount( 1 ), - mLoopDelay( 0.0f ), - mWrapGap( 0.0f ), - mStopMode( TextLabel::AutoScrollStopMode::FINISH_LOOP ) +TextScroller::TextScroller(ScrollerInterface& scrollerInterface) +: mScrollerInterface(scrollerInterface), + mScrollDeltaIndex(Property::INVALID_INDEX), + mScrollSpeed(MINIMUM_SCROLL_SPEED), + mLoopCount(1), + mLoopDelay(0.0f), + mWrapGap(0.0f), + mStopMode(TextLabel::AutoScrollStopMode::FINISH_LOOP) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller Default Constructor\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller Default Constructor\n"); } TextScroller::~TextScroller() { } -void TextScroller::SetParameters( Actor scrollingTextActor, Renderer renderer, TextureSet textureSet, const Size& controlSize, const Size& textureSize, const float wrapGap, CharacterDirection direction, HorizontalAlignment::Type horizontalAlignment, VerticalAlignment::Type verticalAlignment ) +void TextScroller::SetParameters(Actor scrollingTextActor, Renderer renderer, TextureSet textureSet, const Size& controlSize, const Size& textureSize, const float wrapGap, CharacterDirection direction, HorizontalAlignment::Type horizontalAlignment, VerticalAlignment::Type verticalAlignment) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters controlSize[%f,%f] textureSize[%f,%f] direction[%d]\n", - controlSize.x, controlSize.y, textureSize.x, textureSize.y, direction ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetParameters controlSize[%f,%f] textureSize[%f,%f] direction[%d]\n", controlSize.x, controlSize.y, textureSize.x, textureSize.y, direction); mRenderer = renderer; float animationProgress = 0.0f; - int remainedLoop = mLoopCount; - if ( mScrollAnimation ) + int remainedLoop = mLoopCount; + if(mScrollAnimation) { - if( mScrollAnimation.GetState() == Animation::PLAYING ) + if(mScrollAnimation.GetState() == Animation::PLAYING) { animationProgress = mScrollAnimation.GetCurrentProgress(); - if( mLoopCount > 0 ) // If not a ininity loop, then calculate remained loop + if(mLoopCount > 0) // If not a ininity loop, then calculate remained loop { - remainedLoop = mLoopCount - ( mScrollAnimation.GetCurrentLoop() ); - remainedLoop = ( remainedLoop <= 0 ? 1 : remainedLoop ); + remainedLoop = mLoopCount - (mScrollAnimation.GetCurrentLoop()); + remainedLoop = (remainedLoop <= 0 ? 1 : remainedLoop); } } mScrollAnimation.Clear(); // Reset to the original shader and texture before scrolling mRenderer.SetShader(mShader); - if( mTextureSet ) + if(mTextureSet) { - mRenderer.SetTextures( mTextureSet ); + mRenderer.SetTextures(mTextureSet); } } - mShader = mRenderer.GetShader(); + mShader = mRenderer.GetShader(); mTextureSet = mRenderer.GetTextures(); // Set the shader and texture for scrolling - Shader shader = Shader::New( SHADER_TEXT_SCROLLER_SHADER_VERT, SHADER_TEXT_SCROLLER_SHADER_FRAG, Shader::Hint::NONE ); - mRenderer.SetShader( shader ); - mRenderer.SetTextures( textureSet ); + Shader shader = Shader::New(SHADER_TEXT_SCROLLER_SHADER_VERT, SHADER_TEXT_SCROLLER_SHADER_FRAG, Shader::Hint::NONE); + mRenderer.SetShader(shader); + mRenderer.SetTextures(textureSet); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters wrapGap[%f]\n", wrapGap ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetParameters wrapGap[%f]\n", wrapGap); float horizontalAlign; - if( textureSize.x > controlSize.x ) + if(textureSize.x > controlSize.x) { // if Text is elided, scroll should start at the begin of text. - horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[HorizontalAlignment::BEGIN][ direction ]; + horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[HorizontalAlignment::BEGIN][direction]; } else { - horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[ horizontalAlignment ][ direction ]; + horizontalAlign = HORIZONTAL_ALIGNMENT_TABLE[horizontalAlignment][direction]; } - const float verticalAlign = VERTICAL_ALIGNMENT_TABLE[ verticalAlignment ]; + const float verticalAlign = VERTICAL_ALIGNMENT_TABLE[verticalAlignment]; - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::SetParameters horizontalAlign[%f], verticalAlign[%f]\n", horizontalAlign, verticalAlign ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::SetParameters horizontalAlign[%f], verticalAlign[%f]\n", horizontalAlign, verticalAlign); - shader.RegisterProperty( "uTextureSize", textureSize ); - shader.RegisterProperty( "uHorizontalAlign", horizontalAlign ); - shader.RegisterProperty( "uVerticalAlign", verticalAlign ); - shader.RegisterProperty( "uGap", wrapGap ); - mScrollDeltaIndex = shader.RegisterProperty( "uDelta", 0.0f ); + shader.RegisterProperty("uTextureSize", textureSize); + shader.RegisterProperty("uHorizontalAlign", horizontalAlign); + shader.RegisterProperty("uVerticalAlign", verticalAlign); + shader.RegisterProperty("uGap", wrapGap); + mScrollDeltaIndex = shader.RegisterProperty("uDelta", 0.0f); - float scrollAmount = std::max( textureSize.width, controlSize.width ); - float scrollDuration = scrollAmount / mScrollSpeed; + float scrollAmount = std::max(textureSize.width, controlSize.width); + float scrollDuration = scrollAmount / mScrollSpeed; - if ( direction ) + if(direction) { - scrollAmount = -scrollAmount; // reverse direction of scrolling + scrollAmount = -scrollAmount; // reverse direction of scrolling } - StartScrolling( scrollingTextActor, scrollAmount, scrollDuration, remainedLoop ); + StartScrolling(scrollingTextActor, scrollAmount, scrollDuration, remainedLoop); mScrollAnimation.SetCurrentProgress(animationProgress); } -void TextScroller::AutoScrollAnimationFinished( Dali::Animation& animation ) +void TextScroller::AutoScrollAnimationFinished(Dali::Animation& animation) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::AutoScrollAnimationFinished\n" ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::AutoScrollAnimationFinished\n"); mScrollerInterface.ScrollingFinished(); // Revert to the original shader and texture after scrolling mRenderer.SetShader(mShader); - if ( mTextureSet ) + if(mTextureSet) { - mRenderer.SetTextures( mTextureSet ); + mRenderer.SetTextures(mTextureSet); } } -void TextScroller::StartScrolling( Actor scrollingTextActor, float scrollAmount, float scrollDuration, int loopCount ) +void TextScroller::StartScrolling(Actor scrollingTextActor, float scrollAmount, float scrollDuration, int loopCount) { - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "TextScroller::StartScrolling scrollAmount[%f] scrollDuration[%f], loop[%d] speed[%d]\n", scrollAmount, scrollDuration, loopCount, mScrollSpeed ); - - Shader shader = mRenderer.GetShader(); - mScrollAnimation = Animation::New( scrollDuration ); - mScrollAnimation.AnimateTo( Property( shader, mScrollDeltaIndex ), scrollAmount, TimePeriod( mLoopDelay, scrollDuration ) ); - mScrollAnimation.SetEndAction( Animation::DISCARD ); - mScrollAnimation.SetLoopCount( loopCount ); - mScrollAnimation.FinishedSignal().Connect( this, &TextScroller::AutoScrollAnimationFinished ); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TextScroller::StartScrolling scrollAmount[%f] scrollDuration[%f], loop[%d] speed[%d]\n", scrollAmount, scrollDuration, loopCount, mScrollSpeed); + + Shader shader = mRenderer.GetShader(); + mScrollAnimation = Animation::New(scrollDuration); + mScrollAnimation.AnimateTo(Property(shader, mScrollDeltaIndex), scrollAmount, TimePeriod(mLoopDelay, scrollDuration)); + mScrollAnimation.SetEndAction(Animation::DISCARD); + mScrollAnimation.SetLoopCount(loopCount); + mScrollAnimation.FinishedSignal().Connect(this, &TextScroller::AutoScrollAnimationFinished); mScrollAnimation.Play(); } diff --git a/dali-toolkit/internal/text/text-selection-handle-controller.cpp b/dali-toolkit/internal/text/text-selection-handle-controller.cpp index 664b59e..0601750 100644 --- a/dali-toolkit/internal/text/text-selection-handle-controller.cpp +++ b/dali-toolkit/internal/text/text-selection-handle-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. @@ -29,7 +29,6 @@ using namespace Dali; namespace { - /** * @brief Struct used to calculate the selection box. */ @@ -45,103 +44,100 @@ struct SelectionBoxInfo Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_CONTROLS"); #endif -const float MAX_FLOAT = std::numeric_limits::max(); -const float MIN_FLOAT = std::numeric_limits::min(); -const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction +const float MAX_FLOAT = std::numeric_limits::max(); +const float MIN_FLOAT = std::numeric_limits::min(); +const Dali::Toolkit::Text::CharacterDirection LTR = false; ///< Left To Right direction } // namespace namespace Dali { - namespace Toolkit { - namespace Text { - void SelectionHandleController::Reposition(Controller::Impl& impl) { EventData*& eventData = impl.mEventData; CharacterIndex selectionStart = eventData->mLeftSelectionPosition; - CharacterIndex selectionEnd = eventData->mRightSelectionPosition; + CharacterIndex selectionEnd = eventData->mRightSelectionPosition; DecoratorPtr& decorator = eventData->mDecorator; - if( selectionStart == selectionEnd ) + if(selectionStart == selectionEnd) { // Nothing to select if handles are in the same place. // So, deactive Highlight box. - decorator->SetHighlightActive( false ); + decorator->SetHighlightActive(false); return; } decorator->ClearHighlights(); - ModelPtr& model = impl.mModel; - VisualModelPtr& visualModel = model->mVisualModel; + ModelPtr& model = impl.mModel; + VisualModelPtr& visualModel = model->mVisualModel; LogicalModelPtr& logicalModel = model->mLogicalModel; - const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin(); - const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin(); - const GlyphInfo* const glyphsBuffer = visualModel->mGlyphs.Begin(); - const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin(); - const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin(); - const CharacterIndex* const glyphToCharacterBuffer = visualModel->mGlyphsToCharacters.Begin(); - const CharacterDirection* const modelCharacterDirectionsBuffer = ( 0u != logicalModel->mCharacterDirections.Count() ) ? logicalModel->mCharacterDirections.Begin() : NULL; + const GlyphIndex* const charactersToGlyphBuffer = visualModel->mCharactersToGlyph.Begin(); + const Length* const glyphsPerCharacterBuffer = visualModel->mGlyphsPerCharacter.Begin(); + const GlyphInfo* const glyphsBuffer = visualModel->mGlyphs.Begin(); + const Vector2* const positionsBuffer = visualModel->mGlyphPositions.Begin(); + const Length* const charactersPerGlyphBuffer = visualModel->mCharactersPerGlyph.Begin(); + const CharacterIndex* const glyphToCharacterBuffer = visualModel->mGlyphsToCharacters.Begin(); + const CharacterDirection* const modelCharacterDirectionsBuffer = (0u != logicalModel->mCharacterDirections.Count()) ? logicalModel->mCharacterDirections.Begin() : NULL; - const bool isLastCharacter = selectionEnd >= logicalModel->mText.Count(); - const CharacterDirection startDirection = ( ( NULL == modelCharacterDirectionsBuffer ) ? false : *( modelCharacterDirectionsBuffer + selectionStart ) ); - const CharacterDirection endDirection = ( ( NULL == modelCharacterDirectionsBuffer ) ? false : *( modelCharacterDirectionsBuffer + ( selectionEnd - ( isLastCharacter ? 1u : 0u ) ) ) ); + const bool isLastCharacter = selectionEnd >= logicalModel->mText.Count(); + const CharacterDirection startDirection = ((NULL == modelCharacterDirectionsBuffer) ? false : *(modelCharacterDirectionsBuffer + selectionStart)); + const CharacterDirection endDirection = ((NULL == modelCharacterDirectionsBuffer) ? false : *(modelCharacterDirectionsBuffer + (selectionEnd - (isLastCharacter ? 1u : 0u)))); // Swap the indices if the start is greater than the end. const bool indicesSwapped = selectionStart > selectionEnd; // Tell the decorator to flip the selection handles if needed. - decorator->SetSelectionHandleFlipState( indicesSwapped, startDirection, endDirection ); + decorator->SetSelectionHandleFlipState(indicesSwapped, startDirection, endDirection); - if( indicesSwapped ) + if(indicesSwapped) { - std::swap( selectionStart, selectionEnd ); + std::swap(selectionStart, selectionEnd); } // Get the indices to the first and last selected glyphs. const CharacterIndex selectionEndMinusOne = selectionEnd - 1u; - const GlyphIndex glyphStart = *( charactersToGlyphBuffer + selectionStart ); - const Length numberOfGlyphs = *( glyphsPerCharacterBuffer + selectionEndMinusOne ); - const GlyphIndex glyphEnd = *( charactersToGlyphBuffer + selectionEndMinusOne ) + ( ( numberOfGlyphs > 0 ) ? numberOfGlyphs - 1u : 0u ); + const GlyphIndex glyphStart = *(charactersToGlyphBuffer + selectionStart); + const Length numberOfGlyphs = *(glyphsPerCharacterBuffer + selectionEndMinusOne); + const GlyphIndex glyphEnd = *(charactersToGlyphBuffer + selectionEndMinusOne) + ((numberOfGlyphs > 0) ? numberOfGlyphs - 1u : 0u); // Get the lines where the glyphs are laid-out. const LineRun* lineRun = visualModel->mLines.Begin(); - LineIndex lineIndex = 0u; - Length numberOfLines = 0u; - visualModel->GetNumberOfLines( glyphStart, - 1u + glyphEnd - glyphStart, - lineIndex, - numberOfLines ); + LineIndex lineIndex = 0u; + Length numberOfLines = 0u; + visualModel->GetNumberOfLines(glyphStart, + 1u + glyphEnd - glyphStart, + lineIndex, + numberOfLines); const LineIndex firstLineIndex = lineIndex; // Create the structure to store some selection box info. Vector selectionBoxLinesInfo; - selectionBoxLinesInfo.Resize( numberOfLines ); + selectionBoxLinesInfo.Resize(numberOfLines); SelectionBoxInfo* selectionBoxInfo = selectionBoxLinesInfo.Begin(); - selectionBoxInfo->minX = MAX_FLOAT; - selectionBoxInfo->maxX = MIN_FLOAT; + selectionBoxInfo->minX = MAX_FLOAT; + selectionBoxInfo->maxX = MIN_FLOAT; // Keep the min and max 'x' position to calculate the size and position of the highlighed text. - float minHighlightX = std::numeric_limits::max(); - float maxHighlightX = std::numeric_limits::min(); - Size highLightSize; + float minHighlightX = std::numeric_limits::max(); + float maxHighlightX = std::numeric_limits::min(); + Size highLightSize; Vector2 highLightPosition; // The highlight position in decorator's coords. // Retrieve the first line and get the line's vertical offset, the line's height and the index to the last glyph. // The line's vertical offset of all the lines before the line where the first glyph is laid-out. - selectionBoxInfo->lineOffset = CalculateLineOffset( visualModel->mLines, - firstLineIndex ); + selectionBoxInfo->lineOffset = CalculateLineOffset(visualModel->mLines, + firstLineIndex); // Transform to decorator's (control) coords. selectionBoxInfo->lineOffset += model->mScrollPosition.y; @@ -155,86 +151,86 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) GlyphIndex lastGlyphOfLine = lineRun->glyphRun.glyphIndex + lineRun->glyphRun.numberOfGlyphs - 1u; // Check if the first glyph is a ligature that must be broken like Latin ff, fi, or Arabic ï»», etc which needs special code. - const Length numberOfCharactersStart = *( charactersPerGlyphBuffer + glyphStart ); - bool splitStartGlyph = ( numberOfCharactersStart > 1u ) && HasLigatureMustBreak( logicalModel->GetScript( selectionStart ) ); + const Length numberOfCharactersStart = *(charactersPerGlyphBuffer + glyphStart); + bool splitStartGlyph = (numberOfCharactersStart > 1u) && HasLigatureMustBreak(logicalModel->GetScript(selectionStart)); // Check if the last glyph is a ligature that must be broken like Latin ff, fi, or Arabic ï»», etc which needs special code. - const Length numberOfCharactersEnd = *( charactersPerGlyphBuffer + glyphEnd ); - bool splitEndGlyph = ( glyphStart != glyphEnd ) && ( numberOfCharactersEnd > 1u ) && HasLigatureMustBreak( logicalModel->GetScript( selectionEndMinusOne ) ); + const Length numberOfCharactersEnd = *(charactersPerGlyphBuffer + glyphEnd); + bool splitEndGlyph = (glyphStart != glyphEnd) && (numberOfCharactersEnd > 1u) && HasLigatureMustBreak(logicalModel->GetScript(selectionEndMinusOne)); // The number of quads of the selection box. - const unsigned int numberOfQuads = 1u + ( glyphEnd - glyphStart ) + ( ( numberOfLines > 1u ) ? 2u * numberOfLines : 0u ); - decorator->ResizeHighlightQuads( numberOfQuads ); + const unsigned int numberOfQuads = 1u + (glyphEnd - glyphStart) + ((numberOfLines > 1u) ? 2u * numberOfLines : 0u); + decorator->ResizeHighlightQuads(numberOfQuads); // Count the actual number of quads. unsigned int actualNumberOfQuads = 0u; - Vector4 quad; + Vector4 quad; // Traverse the glyphs. - for( GlyphIndex index = glyphStart; index <= glyphEnd; ++index ) + for(GlyphIndex index = glyphStart; index <= glyphEnd; ++index) { - const GlyphInfo& glyph = *( glyphsBuffer + index ); - const Vector2& position = *( positionsBuffer + index ); + const GlyphInfo& glyph = *(glyphsBuffer + index); + const Vector2& position = *(positionsBuffer + index); - if( splitStartGlyph ) + if(splitStartGlyph) { // If the first glyph is a ligature that must be broken it may be needed to add only part of the glyph to the highlight box. - const float glyphAdvance = glyph.advance / static_cast( numberOfCharactersStart ); - const CharacterIndex interGlyphIndex = selectionStart - *( glyphToCharacterBuffer + glyphStart ); + const float glyphAdvance = glyph.advance / static_cast(numberOfCharactersStart); + const CharacterIndex interGlyphIndex = selectionStart - *(glyphToCharacterBuffer + glyphStart); // Get the direction of the character. CharacterDirection isCurrentRightToLeft = false; - if( nullptr != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right. + if(nullptr != modelCharacterDirectionsBuffer) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right. { - isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + selectionStart ); + isCurrentRightToLeft = *(modelCharacterDirectionsBuffer + selectionStart); } // The end point could be in the middle of the ligature. // Calculate the number of characters selected. - const Length numberOfCharacters = ( glyphStart == glyphEnd ) ? ( selectionEnd - selectionStart ) : ( numberOfCharactersStart - interGlyphIndex ); + const Length numberOfCharacters = (glyphStart == glyphEnd) ? (selectionEnd - selectionStart) : (numberOfCharactersStart - interGlyphIndex); - quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + glyphAdvance * static_cast( isCurrentRightToLeft ? ( numberOfCharactersStart - interGlyphIndex - numberOfCharacters ) : interGlyphIndex ); + quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + glyphAdvance * static_cast(isCurrentRightToLeft ? (numberOfCharactersStart - interGlyphIndex - numberOfCharacters) : interGlyphIndex); quad.y = selectionBoxInfo->lineOffset; - quad.z = quad.x + static_cast( numberOfCharacters ) * glyphAdvance; + quad.z = quad.x + static_cast(numberOfCharacters) * glyphAdvance; quad.w = selectionBoxInfo->lineOffset + selectionBoxInfo->lineHeight; // Store the min and max 'x' for each line. - selectionBoxInfo->minX = std::min( selectionBoxInfo->minX, quad.x ); - selectionBoxInfo->maxX = std::max( selectionBoxInfo->maxX, quad.z ); + selectionBoxInfo->minX = std::min(selectionBoxInfo->minX, quad.x); + selectionBoxInfo->maxX = std::max(selectionBoxInfo->maxX, quad.z); - decorator->AddHighlight( actualNumberOfQuads, quad ); + decorator->AddHighlight(actualNumberOfQuads, quad); ++actualNumberOfQuads; splitStartGlyph = false; continue; } - if( splitEndGlyph && ( index == glyphEnd ) ) + if(splitEndGlyph && (index == glyphEnd)) { // Equally, if the last glyph is a ligature that must be broken it may be needed to add only part of the glyph to the highlight box. - const float glyphAdvance = glyph.advance / static_cast( numberOfCharactersEnd ); - const CharacterIndex interGlyphIndex = selectionEnd - *( glyphToCharacterBuffer + glyphEnd ); + const float glyphAdvance = glyph.advance / static_cast(numberOfCharactersEnd); + const CharacterIndex interGlyphIndex = selectionEnd - *(glyphToCharacterBuffer + glyphEnd); // Get the direction of the character. CharacterDirection isCurrentRightToLeft = false; - if( nullptr != modelCharacterDirectionsBuffer ) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right. + if(nullptr != modelCharacterDirectionsBuffer) // If modelCharacterDirectionsBuffer is NULL, it means the whole text is left to right. { - isCurrentRightToLeft = *( modelCharacterDirectionsBuffer + selectionEnd ); + isCurrentRightToLeft = *(modelCharacterDirectionsBuffer + selectionEnd); } const Length numberOfCharacters = numberOfCharactersEnd - interGlyphIndex; - quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + ( isCurrentRightToLeft ? ( glyphAdvance * static_cast( numberOfCharacters ) ) : 0.f ); + quad.x = lineRun->alignmentOffset + position.x - glyph.xBearing + model->mScrollPosition.x + (isCurrentRightToLeft ? (glyphAdvance * static_cast(numberOfCharacters)) : 0.f); quad.y = selectionBoxInfo->lineOffset; - quad.z = quad.x + static_cast( interGlyphIndex ) * glyphAdvance; + quad.z = quad.x + static_cast(interGlyphIndex) * glyphAdvance; quad.w = quad.y + selectionBoxInfo->lineHeight; // Store the min and max 'x' for each line. - selectionBoxInfo->minX = std::min( selectionBoxInfo->minX, quad.x ); - selectionBoxInfo->maxX = std::max( selectionBoxInfo->maxX, quad.z ); + selectionBoxInfo->minX = std::min(selectionBoxInfo->minX, quad.x); + selectionBoxInfo->maxX = std::max(selectionBoxInfo->maxX, quad.z); - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; splitEndGlyph = false; @@ -247,18 +243,18 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) quad.w = quad.y + selectionBoxInfo->lineHeight; // Store the min and max 'x' for each line. - selectionBoxInfo->minX = std::min( selectionBoxInfo->minX, quad.x ); - selectionBoxInfo->maxX = std::max( selectionBoxInfo->maxX, quad.z ); + selectionBoxInfo->minX = std::min(selectionBoxInfo->minX, quad.x); + selectionBoxInfo->maxX = std::max(selectionBoxInfo->maxX, quad.z); - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; // Whether to retrieve the next line. - if( index == lastGlyphOfLine ) + if(index == lastGlyphOfLine) { ++lineIndex; - if( lineIndex < firstLineIndex + numberOfLines ) + if(lineIndex < firstLineIndex + numberOfLines) { // Retrieve the next line. ++lineRun; @@ -288,31 +284,31 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) // Traverses all the lines and updates the min and max 'x' positions and the total height. // The final width is calculated after 'boxifying' the selection. - for( Vector::ConstIterator it = selectionBoxLinesInfo.Begin(), - endIt = selectionBoxLinesInfo.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = selectionBoxLinesInfo.Begin(), + endIt = selectionBoxLinesInfo.End(); + it != endIt; + ++it) { const SelectionBoxInfo& info = *it; // Update the size of the highlighted text. highLightSize.height += info.lineHeight; - minHighlightX = std::min( minHighlightX, info.minX ); - maxHighlightX = std::max( maxHighlightX, info.maxX ); + minHighlightX = std::min(minHighlightX, info.minX); + maxHighlightX = std::max(maxHighlightX, info.maxX); } // Add extra geometry to 'boxify' the selection. - if( 1u < numberOfLines ) + if(1u < numberOfLines) { // Boxify the first line. - lineRun = visualModel->mLines.Begin() + firstLineIndex; - const SelectionBoxInfo& firstSelectionBoxLineInfo = *( selectionBoxLinesInfo.Begin() ); + lineRun = visualModel->mLines.Begin() + firstLineIndex; + const SelectionBoxInfo& firstSelectionBoxLineInfo = *(selectionBoxLinesInfo.Begin()); - bool boxifyBegin = ( LTR != lineRun->direction ) && ( LTR != startDirection ); - bool boxifyEnd = ( LTR == lineRun->direction ) && ( LTR == startDirection ); + bool boxifyBegin = (LTR != lineRun->direction) && (LTR != startDirection); + bool boxifyEnd = (LTR == lineRun->direction) && (LTR == startDirection); - if( boxifyBegin ) + if(boxifyBegin) { quad.x = 0.f; quad.y = firstSelectionBoxLineInfo.lineOffset; @@ -320,15 +316,15 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) quad.w = firstSelectionBoxLineInfo.lineOffset + firstSelectionBoxLineInfo.lineHeight; // Boxify at the beginning of the line. - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; // Update the size of the highlighted text. minHighlightX = 0.f; } - if( boxifyEnd ) + if(boxifyEnd) { quad.x = firstSelectionBoxLineInfo.maxX; quad.y = firstSelectionBoxLineInfo.lineOffset; @@ -336,8 +332,8 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) quad.w = firstSelectionBoxLineInfo.lineOffset + firstSelectionBoxLineInfo.lineHeight; // Boxify at the end of the line. - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; // Update the size of the highlighted text. @@ -345,12 +341,12 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) } // Boxify the central lines. - if( 2u < numberOfLines ) + if(2u < numberOfLines) { - for( Vector::ConstIterator it = selectionBoxLinesInfo.Begin() + 1u, - endIt = selectionBoxLinesInfo.End() - 1u; - it != endIt; - ++it ) + for(Vector::ConstIterator it = selectionBoxLinesInfo.Begin() + 1u, + endIt = selectionBoxLinesInfo.End() - 1u; + it != endIt; + ++it) { const SelectionBoxInfo& info = *it; @@ -359,8 +355,8 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) quad.z = info.minX; quad.w = info.lineOffset + info.lineHeight; - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; quad.x = info.maxX; @@ -368,8 +364,8 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) quad.z = visualModel->mControlSize.width; quad.w = info.lineOffset + info.lineHeight; - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; } @@ -379,13 +375,13 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) } // Boxify the last line. - lineRun = visualModel->mLines.Begin() + firstLineIndex + numberOfLines - 1u; - const SelectionBoxInfo& lastSelectionBoxLineInfo = *( selectionBoxLinesInfo.End() - 1u ); + lineRun = visualModel->mLines.Begin() + firstLineIndex + numberOfLines - 1u; + const SelectionBoxInfo& lastSelectionBoxLineInfo = *(selectionBoxLinesInfo.End() - 1u); - boxifyBegin = ( LTR == lineRun->direction ) && ( LTR == endDirection ); - boxifyEnd = ( LTR != lineRun->direction ) && ( LTR != endDirection ); + boxifyBegin = (LTR == lineRun->direction) && (LTR == endDirection); + boxifyEnd = (LTR != lineRun->direction) && (LTR != endDirection); - if( boxifyBegin ) + if(boxifyBegin) { quad.x = 0.f; quad.y = lastSelectionBoxLineInfo.lineOffset; @@ -393,15 +389,15 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) quad.w = lastSelectionBoxLineInfo.lineOffset + lastSelectionBoxLineInfo.lineHeight; // Boxify at the beginning of the line. - decorator->AddHighlight( actualNumberOfQuads, - quad ); + decorator->AddHighlight(actualNumberOfQuads, + quad); ++actualNumberOfQuads; // Update the size of the highlighted text. minHighlightX = 0.f; } - if( boxifyEnd ) + if(boxifyEnd) { quad.x = lastSelectionBoxLineInfo.maxX; quad.y = lastSelectionBoxLineInfo.lineOffset; @@ -418,19 +414,19 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) } // Set the actual number of quads. - decorator->ResizeHighlightQuads( actualNumberOfQuads ); + decorator->ResizeHighlightQuads(actualNumberOfQuads); // Sets the highlight's size and position. In decorator's coords. // The highlight's height has been calculated above (before 'boxifying' the highlight). highLightSize.width = maxHighlightX - minHighlightX; - highLightPosition.x = minHighlightX; - const SelectionBoxInfo& firstSelectionBoxLineInfo = *( selectionBoxLinesInfo.Begin() ); - highLightPosition.y = firstSelectionBoxLineInfo.lineOffset; + highLightPosition.x = minHighlightX; + const SelectionBoxInfo& firstSelectionBoxLineInfo = *(selectionBoxLinesInfo.Begin()); + highLightPosition.y = firstSelectionBoxLineInfo.lineOffset; - decorator->SetHighLightBox( highLightPosition, highLightSize, static_cast( model->GetOutlineWidth() ) ); + decorator->SetHighLightBox(highLightPosition, highLightSize, static_cast(model->GetOutlineWidth())); - if( !decorator->IsSmoothHandlePanEnabled() ) + if(!decorator->IsSmoothHandlePanEnabled()) { CursorInfo primaryCursorInfo; impl.GetCursorPosition(eventData->mLeftSelectionPosition, primaryCursorInfo); @@ -440,7 +436,7 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) decorator->SetPosition(LEFT_SELECTION_HANDLE, primaryPosition.x, primaryCursorInfo.lineOffset + model->mScrollPosition.y, - primaryCursorInfo.lineHeight ); + primaryCursorInfo.lineHeight); CursorInfo secondaryCursorInfo; impl.GetCursorPosition(eventData->mRightSelectionPosition, secondaryCursorInfo); @@ -450,7 +446,7 @@ void SelectionHandleController::Reposition(Controller::Impl& impl) decorator->SetPosition(RIGHT_SELECTION_HANDLE, secondaryPosition.x, secondaryCursorInfo.lineOffset + model->mScrollPosition.y, - secondaryCursorInfo.lineHeight ); + secondaryCursorInfo.lineHeight); } // Set the flag to update the decorator. @@ -472,41 +468,41 @@ void SelectionHandleController::Reposition(Controller::Impl& impl, float visualX return; } - ModelPtr& model = impl.mModel; - VisualModelPtr& visualModel = model->mVisualModel; - const Length numberOfGlyphs = visualModel->mGlyphs.Count(); - const Length numberOfLines = visualModel->mLines.Count(); - if( ( 0 == numberOfGlyphs ) || - ( 0 == numberOfLines ) ) + ModelPtr& model = impl.mModel; + VisualModelPtr& visualModel = model->mVisualModel; + const Length numberOfGlyphs = visualModel->mGlyphs.Count(); + const Length numberOfLines = visualModel->mLines.Count(); + if((0 == numberOfGlyphs) || + (0 == numberOfLines)) { // Nothing to do if there is no text. return; } // Find which word was selected - CharacterIndex selectionStart( 0 ); - CharacterIndex selectionEnd( 0 ); - CharacterIndex noTextHitIndex( 0 ); - const bool characterHit = FindSelectionIndices( visualModel, - model->mLogicalModel, - impl.mMetrics, - visualX, - visualY, - selectionStart, - selectionEnd, - noTextHitIndex ); - DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%p selectionStart %d selectionEnd %d\n", &impl, selectionStart, selectionEnd ); - - if( characterHit || ( Controller::NoTextTap::HIGHLIGHT == action ) ) + CharacterIndex selectionStart(0); + CharacterIndex selectionEnd(0); + CharacterIndex noTextHitIndex(0); + const bool characterHit = FindSelectionIndices(visualModel, + model->mLogicalModel, + impl.mMetrics, + visualX, + visualY, + selectionStart, + selectionEnd, + noTextHitIndex); + DALI_LOG_INFO(gLogFilter, Debug::Verbose, "%p selectionStart %d selectionEnd %d\n", &impl, selectionStart, selectionEnd); + + if(characterHit || (Controller::NoTextTap::HIGHLIGHT == action)) { - impl.ChangeState( EventData::SELECTING ); + impl.ChangeState(EventData::SELECTING); - eventData->mLeftSelectionPosition = selectionStart; + eventData->mLeftSelectionPosition = selectionStart; eventData->mRightSelectionPosition = selectionEnd; - eventData->mUpdateLeftSelectionPosition = true; + eventData->mUpdateLeftSelectionPosition = true; eventData->mUpdateRightSelectionPosition = true; - eventData->mUpdateHighlightBox = true; + eventData->mUpdateHighlightBox = true; // It may happen an InputMethodContext commit event arrives before the selection event // if the InputMethodContext is in pre-edit state. The commit event will set the @@ -514,44 +510,44 @@ void SelectionHandleController::Reposition(Controller::Impl& impl, float visualX // to false, the highlight box won't be updated. eventData->mUpdateCursorPosition = false; - eventData->mScrollAfterUpdatePosition = ( eventData->mLeftSelectionPosition != eventData->mRightSelectionPosition ); + eventData->mScrollAfterUpdatePosition = (eventData->mLeftSelectionPosition != eventData->mRightSelectionPosition); // Cursor to be positioned at end of selection so if selection interrupted and edit mode restarted the cursor will be at end of selection - eventData->mPrimaryCursorPosition = std::max( eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition ); + eventData->mPrimaryCursorPosition = std::max(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition); } - else if( Controller::NoTextTap::SHOW_SELECTION_POPUP == action ) + else if(Controller::NoTextTap::SHOW_SELECTION_POPUP == action) { // Nothing to select. i.e. a white space, out of bounds - impl.ChangeState( EventData::EDITING_WITH_POPUP ); + impl.ChangeState(EventData::EDITING_WITH_POPUP); eventData->mPrimaryCursorPosition = noTextHitIndex; - eventData->mUpdateCursorPosition = true; - eventData->mUpdateGrabHandlePosition = true; + eventData->mUpdateCursorPosition = true; + eventData->mUpdateGrabHandlePosition = true; eventData->mScrollAfterUpdatePosition = true; - eventData->mUpdateInputStyle = true; + eventData->mUpdateInputStyle = true; } - else if( Controller::NoTextTap::NO_ACTION == action ) + else if(Controller::NoTextTap::NO_ACTION == action) { // Nothing to select. i.e. a white space, out of bounds eventData->mPrimaryCursorPosition = noTextHitIndex; - eventData->mUpdateCursorPosition = true; - eventData->mUpdateGrabHandlePosition = true; + eventData->mUpdateCursorPosition = true; + eventData->mUpdateGrabHandlePosition = true; eventData->mScrollAfterUpdatePosition = true; - eventData->mUpdateInputStyle = true; + eventData->mUpdateInputStyle = true; } } void SelectionHandleController::Update(Controller::Impl& impl, HandleType handleType, const CursorInfo& cursorInfo) { - if( ( LEFT_SELECTION_HANDLE != handleType ) && - ( RIGHT_SELECTION_HANDLE != handleType ) ) + if((LEFT_SELECTION_HANDLE != handleType) && + (RIGHT_SELECTION_HANDLE != handleType)) { return; } - ModelPtr& model = impl.mModel; + ModelPtr& model = impl.mModel; const Vector2 cursorPosition = cursorInfo.primaryPosition + model->mScrollPosition; // Sets the handle's position. @@ -559,12 +555,12 @@ void SelectionHandleController::Update(Controller::Impl& impl, HandleType handle eventData->mDecorator->SetPosition(handleType, cursorPosition.x, cursorInfo.lineOffset + model->mScrollPosition.y, - cursorInfo.lineHeight ); + cursorInfo.lineHeight); // If selection handle at start of the text and other at end of the text then all text is selected. - const CharacterIndex startOfSelection = std::min( eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition ); - const CharacterIndex endOfSelection = std::max ( eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition ); - eventData->mAllTextSelected = ( startOfSelection == 0 ) && ( endOfSelection == model->mLogicalModel->mText.Count() ); + const CharacterIndex startOfSelection = std::min(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition); + const CharacterIndex endOfSelection = std::max(eventData->mLeftSelectionPosition, eventData->mRightSelectionPosition); + eventData->mAllTextSelected = (startOfSelection == 0) && (endOfSelection == model->mLogicalModel->mText.Count()); } } // namespace Text diff --git a/dali-toolkit/internal/text/text-vertical-scroller.cpp b/dali-toolkit/internal/text/text-vertical-scroller.cpp index 4f1c4b3..03d87a6 100644 --- a/dali-toolkit/internal/text/text-vertical-scroller.cpp +++ b/dali-toolkit/internal/text/text-vertical-scroller.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,29 +24,25 @@ namespace Dali { - namespace Toolkit { - namespace { - -const float DEFAULT_VERTICAL_SCROLL_DURATION(0.15f); ///< Duration to complete scroll animation +const float DEFAULT_VERTICAL_SCROLL_DURATION(0.15f); ///< Duration to complete scroll animation } // namespace namespace Text { - TextVerticalScrollerPtr TextVerticalScroller::New() { - TextVerticalScrollerPtr textScroller( new TextVerticalScroller() ); + TextVerticalScrollerPtr textScroller(new TextVerticalScroller()); return textScroller; } TextVerticalScroller::TextVerticalScroller() -: mDuration( DEFAULT_VERTICAL_SCROLL_DURATION ), - mScrollTo( 0.0f ) +: mDuration(DEFAULT_VERTICAL_SCROLL_DURATION), + mScrollTo(0.0f) { } @@ -54,39 +50,39 @@ TextVerticalScroller::~TextVerticalScroller() { } -void TextVerticalScroller::CheckStartAnimation( Actor& sourceActor, float x, float y, float scrollAmount ) +void TextVerticalScroller::CheckStartAnimation(Actor& sourceActor, float x, float y, float scrollAmount) { - if ( Equals( scrollAmount, 0.0f, Math::MACHINE_EPSILON_1 ) ) + if(Equals(scrollAmount, 0.0f, Math::MACHINE_EPSILON_1)) { // scroll animation isn't required, set position only - if( mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING ) + if(mScrollAnimation && mScrollAnimation.GetState() == Animation::PLAYING) { mScrollAnimation.Clear(); } - sourceActor.SetProperty( Actor::Property::POSITION, Vector2( x, y )); + sourceActor.SetProperty(Actor::Property::POSITION, Vector2(x, y)); return; } float toY = y + scrollAmount; // Either actor or scroll area is changed, so restart animation - if( mScrollAnimation ) + if(mScrollAnimation) { mScrollAnimation.Clear(); } else { // Create animation at first - mScrollAnimation = Animation::New( mDuration ); + mScrollAnimation = Animation::New(mDuration); } mScrollingActor = sourceActor; - mScrollTo = toY; + mScrollTo = toY; // Set animation attribute - sourceActor.SetProperty( Actor::Property::POSITION, Vector2( x, y )); - mScrollAnimation.AnimateTo( Property(sourceActor, Actor::Property::POSITION_Y), mScrollTo, AlphaFunction::EASE_OUT_SINE ); + sourceActor.SetProperty(Actor::Property::POSITION, Vector2(x, y)); + mScrollAnimation.AnimateTo(Property(sourceActor, Actor::Property::POSITION_Y), mScrollTo, AlphaFunction::EASE_OUT_SINE); mScrollAnimation.Play(); } -void TextVerticalScroller::SetDuration( float duration ) +void TextVerticalScroller::SetDuration(float duration) { mDuration = duration; } diff --git a/dali-toolkit/internal/text/text-view-interface.cpp b/dali-toolkit/internal/text/text-view-interface.cpp index 54d1589..5088ae1 100644 --- a/dali-toolkit/internal/text/text-view-interface.cpp +++ b/dali-toolkit/internal/text/text-view-interface.cpp @@ -20,13 +20,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - ViewInterface::ViewInterface() { } diff --git a/dali-toolkit/internal/text/text-view.cpp b/dali-toolkit/internal/text/text-view.cpp old mode 100755 new mode 100644 index 9d9f991..83ad28f --- a/dali-toolkit/internal/text/text-view.cpp +++ b/dali-toolkit/internal/text/text-view.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,26 +19,23 @@ #include // EXTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Text { - struct View::Impl { - VisualModelPtr mVisualModel; + VisualModelPtr mVisualModel; TextAbstraction::FontClient mFontClient; ///< Handle to the font client. }; View::View() -: mImpl( NULL ) +: mImpl(NULL) { mImpl = new View::Impl(); @@ -50,14 +47,14 @@ View::~View() delete mImpl; } -void View::SetVisualModel( VisualModelPtr visualModel ) +void View::SetVisualModel(VisualModelPtr visualModel) { mImpl->mVisualModel = visualModel; } const Vector2& View::GetControlSize() const { - if ( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->mControlSize; } @@ -67,7 +64,7 @@ const Vector2& View::GetControlSize() const const Vector2& View::GetLayoutSize() const { - if ( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetLayoutSize(); } @@ -77,14 +74,14 @@ const Vector2& View::GetLayoutSize() const Length View::GetNumberOfGlyphs() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { const VisualModel& model = *mImpl->mVisualModel; - const Length glyphCount = model.mGlyphs.Count(); + const Length glyphCount = model.mGlyphs.Count(); const Length positionCount = model.mGlyphPositions.Count(); - DALI_ASSERT_DEBUG( positionCount <= glyphCount && "Invalid glyph positions in Model" ); + DALI_ASSERT_DEBUG(positionCount <= glyphCount && "Invalid glyph positions in Model"); return (positionCount < glyphCount) ? positionCount : glyphCount; } @@ -92,27 +89,27 @@ Length View::GetNumberOfGlyphs() const return 0; } -Length View::GetGlyphs( GlyphInfo* glyphs, - Vector2* glyphPositions, - float& minLineOffset, - GlyphIndex glyphIndex, - Length numberOfGlyphs ) const +Length View::GetGlyphs(GlyphInfo* glyphs, + Vector2* glyphPositions, + float& minLineOffset, + GlyphIndex glyphIndex, + Length numberOfGlyphs) const { Length numberOfLaidOutGlyphs = 0u; - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { // If ellipsis is enabled, the number of glyphs the layout engine has laid out may be less than 'numberOfGlyphs'. // Check the last laid out line to know if the layout engine elided some text. const Length numberOfLines = mImpl->mVisualModel->mLines.Count(); - if( numberOfLines > 0u ) + if(numberOfLines > 0u) { - const LineRun& lastLine = *( mImpl->mVisualModel->mLines.Begin() + ( numberOfLines - 1u ) ); + const LineRun& lastLine = *(mImpl->mVisualModel->mLines.Begin() + (numberOfLines - 1u)); // If ellipsis is enabled, calculate the number of laid out glyphs. // Otherwise use the given number of glyphs. - if( lastLine.ellipsis ) + if(lastLine.ellipsis) { numberOfLaidOutGlyphs = lastLine.glyphRun.glyphIndex + lastLine.glyphRun.numberOfGlyphs; } @@ -121,37 +118,37 @@ Length View::GetGlyphs( GlyphInfo* glyphs, numberOfLaidOutGlyphs = numberOfGlyphs; } - if( 0u < numberOfLaidOutGlyphs ) + if(0u < numberOfLaidOutGlyphs) { // Retrieve from the visual model the glyphs and positions. - mImpl->mVisualModel->GetGlyphs( glyphs, - glyphIndex, - numberOfLaidOutGlyphs ); + mImpl->mVisualModel->GetGlyphs(glyphs, + glyphIndex, + numberOfLaidOutGlyphs); - mImpl->mVisualModel->GetGlyphPositions( glyphPositions, - glyphIndex, - numberOfLaidOutGlyphs ); + mImpl->mVisualModel->GetGlyphPositions(glyphPositions, + glyphIndex, + numberOfLaidOutGlyphs); // Get the lines for the given range of glyphs. // The lines contain the alignment offset which needs to be added to the glyph's position. - LineIndex firstLine = 0u; - Length numberOfLines = 0u; - mImpl->mVisualModel->GetNumberOfLines( glyphIndex, - numberOfLaidOutGlyphs, - firstLine, - numberOfLines ); + LineIndex firstLine = 0u; + Length numberOfLines = 0u; + mImpl->mVisualModel->GetNumberOfLines(glyphIndex, + numberOfLaidOutGlyphs, + firstLine, + numberOfLines); Vector lines; - lines.Resize( numberOfLines ); + lines.Resize(numberOfLines); LineRun* lineBuffer = lines.Begin(); - mImpl->mVisualModel->GetLinesOfGlyphRange( lineBuffer, - glyphIndex, - numberOfLaidOutGlyphs ); + mImpl->mVisualModel->GetLinesOfGlyphRange(lineBuffer, + glyphIndex, + numberOfLaidOutGlyphs); // Get the first line for the given glyph range. LineIndex lineIndex = firstLine; - LineRun* line = lineBuffer + lineIndex; + LineRun* line = lineBuffer + lineIndex; // Index of the last glyph of the line. GlyphIndex lastGlyphIndexOfLine = line->glyphRun.glyphIndex + line->glyphRun.numberOfGlyphs - 1u; @@ -159,24 +156,24 @@ Length View::GetGlyphs( GlyphInfo* glyphs, // Add the alignment offset to the glyph's position. minLineOffset = line->alignmentOffset; - float penY = line->ascender; - for( Length index = 0u; index < numberOfLaidOutGlyphs; ++index ) + float penY = line->ascender; + for(Length index = 0u; index < numberOfLaidOutGlyphs; ++index) { - Vector2& position = *( glyphPositions + index ); + Vector2& position = *(glyphPositions + index); position.x += line->alignmentOffset; position.y += penY; - if( lastGlyphIndexOfLine == index ) + if(lastGlyphIndexOfLine == index) { penY += -line->descender; // Get the next line. ++lineIndex; - if( lineIndex < numberOfLines ) + if(lineIndex < numberOfLines) { - line = lineBuffer + lineIndex; - minLineOffset = std::min( minLineOffset, line->alignmentOffset ); + line = lineBuffer + lineIndex; + minLineOffset = std::min(minLineOffset, line->alignmentOffset); lastGlyphIndexOfLine = line->glyphRun.glyphIndex + line->glyphRun.numberOfGlyphs - 1u; @@ -185,65 +182,65 @@ Length View::GetGlyphs( GlyphInfo* glyphs, } } - if( 1u == numberOfLaidOutGlyphs ) + if(1u == numberOfLaidOutGlyphs) { // not a point try to do ellipsis with only one laid out character. return numberOfLaidOutGlyphs; } - if( lastLine.ellipsis ) + if(lastLine.ellipsis) { - if( ( 1u == numberOfLines ) && - ( lastLine.ascender - lastLine.descender > mImpl->mVisualModel->mControlSize.height ) ) + if((1u == numberOfLines) && + (lastLine.ascender - lastLine.descender > mImpl->mVisualModel->mControlSize.height)) { // Get the first glyph which is going to be replaced and the ellipsis glyph. - GlyphInfo& glyphInfo = *glyphs; - const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph( mImpl->mFontClient.GetPointSize( glyphInfo.fontId ) ); + GlyphInfo& glyphInfo = *glyphs; + const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph(mImpl->mFontClient.GetPointSize(glyphInfo.fontId)); // Change the 'x' and 'y' position of the ellipsis glyph. Vector2& position = *glyphPositions; - position.x = ellipsisGlyph.xBearing; - position.y = mImpl->mVisualModel->mControlSize.height - ellipsisGlyph.yBearing; + position.x = ellipsisGlyph.xBearing; + position.y = mImpl->mVisualModel->mControlSize.height - ellipsisGlyph.yBearing; // Replace the glyph by the ellipsis glyph. glyphInfo = ellipsisGlyph; - return 1u; + return 1u; } // firstPenX, penY and firstPenSet are used to position the ellipsis glyph if needed. - float firstPenX = 0.f; // Used if rtl text is elided. - float penY = 0.f; - bool firstPenSet = false; + float firstPenX = 0.f; // Used if rtl text is elided. + float penY = 0.f; + bool firstPenSet = false; // Add the ellipsis glyph. - bool inserted = false; - float removedGlypsWidth = 0.f; - Length numberOfRemovedGlyphs = 0u; - GlyphIndex index = numberOfLaidOutGlyphs - 1u; + bool inserted = false; + float removedGlypsWidth = 0.f; + Length numberOfRemovedGlyphs = 0u; + GlyphIndex index = numberOfLaidOutGlyphs - 1u; // The ellipsis glyph has to fit in the place where the last glyph(s) is(are) removed. - while( !inserted ) + while(!inserted) { - const GlyphInfo& glyphToRemove = *( glyphs + index ); + const GlyphInfo& glyphToRemove = *(glyphs + index); - if( 0u != glyphToRemove.fontId ) + if(0u != glyphToRemove.fontId) { // i.e. The font id of the glyph shaped from the '\n' character is zero. // Need to reshape the glyph as the font may be different in size. - const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph( mImpl->mFontClient.GetPointSize( glyphToRemove.fontId ) ); + const GlyphInfo& ellipsisGlyph = mImpl->mFontClient.GetEllipsisGlyph(mImpl->mFontClient.GetPointSize(glyphToRemove.fontId)); - if( !firstPenSet ) + if(!firstPenSet) { - const Vector2& position = *( glyphPositions + index ); + const Vector2& position = *(glyphPositions + index); // Calculates the penY of the current line. It will be used to position the ellipsis glyph. penY = position.y + glyphToRemove.yBearing; // Calculates the first penX which will be used if rtl text is elided. firstPenX = position.x - glyphToRemove.xBearing; - if( firstPenX < -ellipsisGlyph.xBearing ) + if(firstPenX < -ellipsisGlyph.xBearing) { // Avoids to exceed the bounding box when rtl text is elided. firstPenX = -ellipsisGlyph.xBearing; @@ -254,22 +251,22 @@ Length View::GetGlyphs( GlyphInfo* glyphs, firstPenSet = true; } - removedGlypsWidth += std::min( glyphToRemove.advance, ( glyphToRemove.xBearing + glyphToRemove.width ) ); + removedGlypsWidth += std::min(glyphToRemove.advance, (glyphToRemove.xBearing + glyphToRemove.width)); // Calculate the width of the ellipsis glyph and check if it fits. const float ellipsisGlyphWidth = ellipsisGlyph.width + ellipsisGlyph.xBearing; - if( ellipsisGlyphWidth < removedGlypsWidth ) + if(ellipsisGlyphWidth < removedGlypsWidth) { - GlyphInfo& glyphInfo = *( glyphs + index ); - Vector2& position = *( glyphPositions + index ); - position.x -= ( 0.f > glyphInfo.xBearing ) ? glyphInfo.xBearing : 0.f; + GlyphInfo& glyphInfo = *(glyphs + index); + Vector2& position = *(glyphPositions + index); + position.x -= (0.f > glyphInfo.xBearing) ? glyphInfo.xBearing : 0.f; // Replace the glyph by the ellipsis glyph. glyphInfo = ellipsisGlyph; // Change the 'x' and 'y' position of the ellipsis glyph. - if( position.x > firstPenX ) + if(position.x > firstPenX) { position.x = firstPenX + removedGlypsWidth - ellipsisGlyphWidth; } @@ -281,9 +278,9 @@ Length View::GetGlyphs( GlyphInfo* glyphs, } } - if( !inserted ) + if(!inserted) { - if( index > 0u ) + if(index > 0u) { --index; } @@ -308,7 +305,7 @@ Length View::GetGlyphs( GlyphInfo* glyphs, const Vector4* const View::GetColors() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->mColors.Begin(); } @@ -318,7 +315,7 @@ const Vector4* const View::GetColors() const const ColorIndex* const View::GetColorIndices() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->mColorIndices.Begin(); } @@ -328,7 +325,7 @@ const ColorIndex* const View::GetColorIndices() const const Vector4* const View::GetBackgroundColors() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->mBackgroundColors.Begin(); } @@ -338,7 +335,7 @@ const Vector4* const View::GetBackgroundColors() const const ColorIndex* const View::GetBackgroundColorIndices() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->mBackgroundColorIndices.Begin(); } @@ -348,7 +345,7 @@ const ColorIndex* const View::GetBackgroundColorIndices() const const Vector4& View::GetTextColor() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetTextColor(); } @@ -357,7 +354,7 @@ const Vector4& View::GetTextColor() const const Vector2& View::GetShadowOffset() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetShadowOffset(); } @@ -366,7 +363,7 @@ const Vector2& View::GetShadowOffset() const const Vector4& View::GetShadowColor() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetShadowColor(); } @@ -375,7 +372,7 @@ const Vector4& View::GetShadowColor() const const Vector4& View::GetUnderlineColor() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetUnderlineColor(); } @@ -384,7 +381,7 @@ const Vector4& View::GetUnderlineColor() const bool View::IsUnderlineEnabled() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->IsUnderlineEnabled(); } @@ -393,7 +390,7 @@ bool View::IsUnderlineEnabled() const float View::GetUnderlineHeight() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetUnderlineHeight(); } @@ -402,7 +399,7 @@ float View::GetUnderlineHeight() const Length View::GetNumberOfUnderlineRuns() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetNumberOfUnderlineRuns(); } @@ -410,21 +407,21 @@ Length View::GetNumberOfUnderlineRuns() const return 0u; } -void View::GetUnderlineRuns( GlyphRun* underlineRuns, - UnderlineRunIndex index, - Length numberOfRuns ) const +void View::GetUnderlineRuns(GlyphRun* underlineRuns, + UnderlineRunIndex index, + Length numberOfRuns) const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { - mImpl->mVisualModel->GetUnderlineRuns( underlineRuns, - index, - numberOfRuns ); + mImpl->mVisualModel->GetUnderlineRuns(underlineRuns, + index, + numberOfRuns); } } const Vector4& View::GetOutlineColor() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetOutlineColor(); } @@ -433,7 +430,7 @@ const Vector4& View::GetOutlineColor() const uint16_t View::GetOutlineWidth() const { - if( mImpl->mVisualModel ) + if(mImpl->mVisualModel) { return mImpl->mVisualModel->GetOutlineWidth(); } diff --git a/dali-toolkit/internal/text/visual-model-impl.cpp b/dali-toolkit/internal/text/visual-model-impl.cpp old mode 100755 new mode 100644 index 6a06e58..eda5633 --- a/dali-toolkit/internal/text/visual-model-impl.cpp +++ b/dali-toolkit/internal/text/visual-model-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. @@ -23,48 +23,45 @@ namespace Dali { - namespace Toolkit { - namespace Text { - VisualModelPtr VisualModel::New() { - return VisualModelPtr( new VisualModel() ); + return VisualModelPtr(new VisualModel()); } -void VisualModel::CreateCharacterToGlyphTable( CharacterIndex startIndex, - GlyphIndex startGlyphIndex, - Length numberOfCharacters ) +void VisualModel::CreateCharacterToGlyphTable(CharacterIndex startIndex, + GlyphIndex startGlyphIndex, + Length numberOfCharacters) { - if( 0u == numberOfCharacters ) + if(0u == numberOfCharacters) { // Nothing to do. return; } - DALI_ASSERT_DEBUG( mGlyphsPerCharacter.Count() != 0u ); + DALI_ASSERT_DEBUG(mGlyphsPerCharacter.Count() != 0u); // Get the total number of characters. - const Length totalNumberOfCharacters = ( 0u == mGlyphsToCharacters.Count() ) ? 0u : *( mGlyphsToCharacters.End() - 1u ) + *( mCharactersPerGlyph.End() - 1u ); // Index to the first character + the number of characters that form the last glyph. + const Length totalNumberOfCharacters = (0u == mGlyphsToCharacters.Count()) ? 0u : *(mGlyphsToCharacters.End() - 1u) + *(mCharactersPerGlyph.End() - 1u); // Index to the first character + the number of characters that form the last glyph. // Whether the current buffer is being updated or is set from scratch. const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters; Vector newCharactersToGlyph; - GlyphIndex* charactersToGlyphBuffer = NULL; + GlyphIndex* charactersToGlyphBuffer = NULL; // 1) Reserve some space for the glyph indices to avoid reallocations. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newCharactersToGlyph.Resize( numberOfCharacters ); + newCharactersToGlyph.Resize(numberOfCharacters); charactersToGlyphBuffer = newCharactersToGlyph.Begin(); } else { - mCharactersToGlyph.Resize( numberOfCharacters ); + mCharactersToGlyph.Resize(numberOfCharacters); charactersToGlyphBuffer = mCharactersToGlyph.Begin() + startIndex; } @@ -73,75 +70,74 @@ void VisualModel::CreateCharacterToGlyphTable( CharacterIndex startIndex, // 2) Traverse the glyphs and set the glyph indices per character. // Index to the glyph. - GlyphIndex glyphIndex = startGlyphIndex; - CharacterIndex characterIndex = startIndex; + GlyphIndex glyphIndex = startGlyphIndex; + CharacterIndex characterIndex = startIndex; const CharacterIndex lastCharacterIndexPlusOne = startIndex + numberOfCharacters; - for( Vector::ConstIterator it = mCharactersPerGlyph.Begin() + glyphIndex, - endIt = mCharactersPerGlyph.End(); - ( it != endIt ) && ( characterIndex < lastCharacterIndexPlusOne ); - ++it ) + for(Vector::ConstIterator it = mCharactersPerGlyph.Begin() + glyphIndex, + endIt = mCharactersPerGlyph.End(); + (it != endIt) && (characterIndex < lastCharacterIndexPlusOne); + ++it) { const Length numberOfCharactersPerGlyph = *it; Length numberOfGlyphs = 0u; // Set the glyph indices. - for( Length index = 0u; index < numberOfCharactersPerGlyph; ++index, ++characterIndex ) + for(Length index = 0u; index < numberOfCharactersPerGlyph; ++index, ++characterIndex) { *charactersToGlyphBuffer = glyphIndex; - numberOfGlyphs += *( glyphsPerCharacterBuffer + characterIndex ); + numberOfGlyphs += *(glyphsPerCharacterBuffer + characterIndex); ++charactersToGlyphBuffer; } glyphIndex += numberOfGlyphs; } // If the character to glyph buffer is updated, it needs to be inserted in the model. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { // Update the indices. const Length numberOfGlyphs = glyphIndex - startGlyphIndex; - for( Vector::Iterator it = mCharactersToGlyph.Begin() + startIndex, - endIt = mCharactersToGlyph.End(); - it != endIt; - ++it ) + for(Vector::Iterator it = mCharactersToGlyph.Begin() + startIndex, + endIt = mCharactersToGlyph.End(); + it != endIt; + ++it) { *it += numberOfGlyphs; } - mCharactersToGlyph.Insert( mCharactersToGlyph.Begin() + startIndex, - newCharactersToGlyph.Begin(), - newCharactersToGlyph.End() ); - + mCharactersToGlyph.Insert(mCharactersToGlyph.Begin() + startIndex, + newCharactersToGlyph.Begin(), + newCharactersToGlyph.End()); } } -void VisualModel::CreateGlyphsPerCharacterTable( CharacterIndex startIndex, - GlyphIndex startGlyphIndex, - Length numberOfCharacters ) +void VisualModel::CreateGlyphsPerCharacterTable(CharacterIndex startIndex, + GlyphIndex startGlyphIndex, + Length numberOfCharacters) { - if( 0u == numberOfCharacters ) + if(0u == numberOfCharacters) { // Nothing to do. return; } // Get the total number of characters. - const Length totalNumberOfCharacters = ( 0u == mGlyphsToCharacters.Count() ) ? 0u : *( mGlyphsToCharacters.End() - 1u ) + *( mCharactersPerGlyph.End() - 1u ); // Index to the first character + the number of characters that form the last glyph. + const Length totalNumberOfCharacters = (0u == mGlyphsToCharacters.Count()) ? 0u : *(mGlyphsToCharacters.End() - 1u) + *(mCharactersPerGlyph.End() - 1u); // Index to the first character + the number of characters that form the last glyph. // Whether the current buffer is being updated or is set from scratch. const bool updateCurrentBuffer = numberOfCharacters < totalNumberOfCharacters; Vector newGlyphsPerCharacter; - Length* glyphsPerCharacterBuffer = NULL; + Length* glyphsPerCharacterBuffer = NULL; // 1) Reserve some space for the glyphs per character to avoid reallocations. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - newGlyphsPerCharacter.Resize( numberOfCharacters ); + newGlyphsPerCharacter.Resize(numberOfCharacters); glyphsPerCharacterBuffer = newGlyphsPerCharacter.Begin(); } else { - mGlyphsPerCharacter.Resize( numberOfCharacters ); + mGlyphsPerCharacter.Resize(numberOfCharacters); glyphsPerCharacterBuffer = mGlyphsPerCharacter.Begin() + startIndex; } @@ -152,23 +148,23 @@ void VisualModel::CreateGlyphsPerCharacterTable( CharacterIndex startIndex, // The number of 'characters per glyph' equal to zero. Length zeroCharactersPerGlyph = 0u; - for( Vector::ConstIterator it = mCharactersPerGlyph.Begin() + startGlyphIndex, - endIt = mCharactersPerGlyph.End(); - ( it != endIt ) && ( traversedCharacters < numberOfCharacters ); - ++it ) + for(Vector::ConstIterator it = mCharactersPerGlyph.Begin() + startGlyphIndex, + endIt = mCharactersPerGlyph.End(); + (it != endIt) && (traversedCharacters < numberOfCharacters); + ++it) { const Length numberOfCharactersPerGlyph = *it; traversedCharacters += numberOfCharactersPerGlyph; // Set the glyphs per character. - if( 0u == numberOfCharactersPerGlyph ) + if(0u == numberOfCharactersPerGlyph) { ++zeroCharactersPerGlyph; } else { - const Length numberOfZeroGlyphsPerCharacter = ( numberOfCharactersPerGlyph - 1u ); - for( Length zeroIndex = 0u; zeroIndex < numberOfZeroGlyphsPerCharacter; ++zeroIndex ) + const Length numberOfZeroGlyphsPerCharacter = (numberOfCharactersPerGlyph - 1u); + for(Length zeroIndex = 0u; zeroIndex < numberOfZeroGlyphsPerCharacter; ++zeroIndex) { *glyphsPerCharacterBuffer = 0u; @@ -186,94 +182,94 @@ void VisualModel::CreateGlyphsPerCharacterTable( CharacterIndex startIndex, } // If the glyphs per character buffer is updated, it needs to be inserted in the model. - if( updateCurrentBuffer ) + if(updateCurrentBuffer) { - mGlyphsPerCharacter.Insert( mGlyphsPerCharacter.Begin() + startIndex, - newGlyphsPerCharacter.Begin(), - newGlyphsPerCharacter.End() ); + mGlyphsPerCharacter.Insert(mGlyphsPerCharacter.Begin() + startIndex, + newGlyphsPerCharacter.Begin(), + newGlyphsPerCharacter.End()); } } -void VisualModel::GetGlyphs( GlyphInfo* glyphs, - GlyphIndex glyphIndex, - Length numberOfGlyphs ) const +void VisualModel::GetGlyphs(GlyphInfo* glyphs, + GlyphIndex glyphIndex, + Length numberOfGlyphs) const { - memcpy( glyphs, mGlyphs.Begin() + glyphIndex, numberOfGlyphs * sizeof( GlyphInfo ) ); + memcpy(glyphs, mGlyphs.Begin() + glyphIndex, numberOfGlyphs * sizeof(GlyphInfo)); } -void VisualModel::GetGlyphPositions( Vector2* glyphPositions, - GlyphIndex glyphIndex, - Length numberOfGlyphs ) const +void VisualModel::GetGlyphPositions(Vector2* glyphPositions, + GlyphIndex glyphIndex, + Length numberOfGlyphs) const { - memcpy( glyphPositions, mGlyphPositions.Begin() + glyphIndex, numberOfGlyphs * sizeof( Vector2 ) ); + memcpy(glyphPositions, mGlyphPositions.Begin() + glyphIndex, numberOfGlyphs * sizeof(Vector2)); } -void VisualModel::GetNumberOfLines( GlyphIndex glyphIndex, - Length numberOfGlyphs, - LineIndex& firstLine, - Length& numberOfLines ) const +void VisualModel::GetNumberOfLines(GlyphIndex glyphIndex, + Length numberOfGlyphs, + LineIndex& firstLine, + Length& numberOfLines) const { // Initialize the number of lines and the first line. - firstLine = 0u; - numberOfLines = 0u; + firstLine = 0u; + numberOfLines = 0u; bool firstLineFound = false; const GlyphIndex lastGlyphIndex = glyphIndex + numberOfGlyphs; // Traverse the lines and count those lines within the range of glyphs. - for( Vector::ConstIterator it = mLines.Begin(), - endIt = mLines.End(); - it != endIt; - ++it ) + for(Vector::ConstIterator it = mLines.Begin(), + endIt = mLines.End(); + it != endIt; + ++it) { const LineRun& line = *it; - if( ( line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs > glyphIndex ) && - ( lastGlyphIndex > line.glyphRun.glyphIndex ) ) + if((line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs > glyphIndex) && + (lastGlyphIndex > line.glyphRun.glyphIndex)) { firstLineFound = true; ++numberOfLines; } - else if( lastGlyphIndex <= line.glyphRun.glyphIndex ) + else if(lastGlyphIndex <= line.glyphRun.glyphIndex) { // nothing else to do. break; } - if( !firstLineFound ) + if(!firstLineFound) { ++firstLine; } } } -void VisualModel::GetLinesOfGlyphRange( LineRun* lines, - GlyphIndex glyphIndex, - Length numberOfGlyphs ) const +void VisualModel::GetLinesOfGlyphRange(LineRun* lines, + GlyphIndex glyphIndex, + Length numberOfGlyphs) const { - LineIndex firstLine = 0u; - Length numberOfLines = 0u; + LineIndex firstLine = 0u; + Length numberOfLines = 0u; - GetNumberOfLines( glyphIndex, - numberOfGlyphs, - firstLine, - numberOfLines ); + GetNumberOfLines(glyphIndex, + numberOfGlyphs, + firstLine, + numberOfLines); - memcpy( lines, mLines.Begin() + firstLine, numberOfLines * sizeof( LineRun ) ); + memcpy(lines, mLines.Begin() + firstLine, numberOfLines * sizeof(LineRun)); } -LineIndex VisualModel::GetLineOfCharacter( CharacterIndex characterIndex ) +LineIndex VisualModel::GetLineOfCharacter(CharacterIndex characterIndex) { // 1) Check line is empty or not. - if( mLines.Empty() ) + if(mLines.Empty()) { return 0u; } // 2) Check in the cached line. - const LineRun& lineRun = *( mLines.Begin() + mCachedLineIndex ); - if( ( lineRun.characterRun.characterIndex <= characterIndex ) && - ( characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters ) ) + const LineRun& lineRun = *(mLines.Begin() + mCachedLineIndex); + if((lineRun.characterRun.characterIndex <= characterIndex) && + (characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters)) { return mCachedLineIndex; } @@ -281,14 +277,14 @@ LineIndex VisualModel::GetLineOfCharacter( CharacterIndex characterIndex ) // 3) Is not in the cached line. Check in the other lines. LineIndex index = characterIndex < lineRun.characterRun.characterIndex ? 0u : mCachedLineIndex + 1u; - for( Vector::ConstIterator it = mLines.Begin() + index, - endIt = mLines.End(); - it != endIt; - ++it, ++index ) + for(Vector::ConstIterator it = mLines.Begin() + index, + endIt = mLines.End(); + it != endIt; + ++it, ++index) { const LineRun& lineRun = *it; - if( characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters ) + if(characterIndex < lineRun.characterRun.characterIndex + lineRun.characterRun.numberOfCharacters) { mCachedLineIndex = index; break; @@ -298,16 +294,16 @@ LineIndex VisualModel::GetLineOfCharacter( CharacterIndex characterIndex ) return index; } -void VisualModel::GetUnderlineRuns( GlyphRun* underlineRuns, - UnderlineRunIndex index, - Length numberOfRuns ) const +void VisualModel::GetUnderlineRuns(GlyphRun* underlineRuns, + UnderlineRunIndex index, + Length numberOfRuns) const { - memcpy( underlineRuns, - mUnderlineRuns.Begin() + index, - numberOfRuns * sizeof( GlyphRun ) ); + memcpy(underlineRuns, + mUnderlineRuns.Begin() + index, + numberOfRuns * sizeof(GlyphRun)); } -void VisualModel::SetNaturalSize( const Vector2& size ) +void VisualModel::SetNaturalSize(const Vector2& size) { mNaturalSize = size; } @@ -317,7 +313,7 @@ const Vector2& VisualModel::GetNaturalSize() const return mNaturalSize; } -void VisualModel::SetLayoutSize( const Vector2& size ) +void VisualModel::SetLayoutSize(const Vector2& size) { mLayoutSize = size; } @@ -327,63 +323,63 @@ const Vector2& VisualModel::GetLayoutSize() const return mLayoutSize; } -void VisualModel::SetTextColor( const Vector4& textColor ) +void VisualModel::SetTextColor(const Vector4& textColor) { mTextColor = textColor; - if ( !mUnderlineColorSet ) + if(!mUnderlineColorSet) { mUnderlineColor = textColor; } } -void VisualModel::SetShadowOffset( const Vector2& shadowOffset ) +void VisualModel::SetShadowOffset(const Vector2& shadowOffset) { mShadowOffset = shadowOffset; } -void VisualModel::SetShadowColor( const Vector4& shadowColor ) +void VisualModel::SetShadowColor(const Vector4& shadowColor) { mShadowColor = shadowColor; } -void VisualModel::SetShadowBlurRadius( const float& shadowBlurRadius ) +void VisualModel::SetShadowBlurRadius(const float& shadowBlurRadius) { mShadowBlurRadius = shadowBlurRadius; } -void VisualModel::SetUnderlineColor( const Vector4& color ) +void VisualModel::SetUnderlineColor(const Vector4& color) { - mUnderlineColor = color; + mUnderlineColor = color; mUnderlineColorSet = true; } -void VisualModel::SetOutlineColor( const Vector4& color ) +void VisualModel::SetOutlineColor(const Vector4& color) { mOutlineColor = color; } -void VisualModel::SetUnderlineEnabled( bool enabled ) +void VisualModel::SetUnderlineEnabled(bool enabled) { mUnderlineEnabled = enabled; } -void VisualModel::SetUnderlineHeight( float height ) +void VisualModel::SetUnderlineHeight(float height) { mUnderlineHeight = height; } -void VisualModel::SetOutlineWidth( uint16_t width ) +void VisualModel::SetOutlineWidth(uint16_t width) { mOutlineWidth = width; } -void VisualModel::SetBackgroundColor( const Vector4& color ) +void VisualModel::SetBackgroundColor(const Vector4& color) { mBackgroundColor = color; } -void VisualModel::SetBackgroundEnabled( bool enabled ) +void VisualModel::SetBackgroundEnabled(bool enabled) { mBackgroundEnabled = enabled; } @@ -465,22 +461,22 @@ VisualModel::VisualModel() mGlyphsPerCharacter(), mGlyphPositions(), mLines(), - mTextColor( Color::BLACK ), - mShadowColor( Color::BLACK ), - mUnderlineColor( Color::BLACK ), - mOutlineColor( Color::WHITE ), - mBackgroundColor( Color::TRANSPARENT ), + mTextColor(Color::BLACK), + mShadowColor(Color::BLACK), + mUnderlineColor(Color::BLACK), + mOutlineColor(Color::WHITE), + mBackgroundColor(Color::TRANSPARENT), mControlSize(), mShadowOffset(), - mUnderlineHeight( 0.0f ), - mShadowBlurRadius( 0.0f ), - mOutlineWidth( 0u ), + mUnderlineHeight(0.0f), + mShadowBlurRadius(0.0f), + mOutlineWidth(0u), mNaturalSize(), mLayoutSize(), - mCachedLineIndex( 0u ), - mUnderlineEnabled( false ), - mUnderlineColorSet( false ), - mBackgroundEnabled( false ) + mCachedLineIndex(0u), + mUnderlineEnabled(false), + mUnderlineColorSet(false), + mBackgroundEnabled(false) { } diff --git a/dali-toolkit/internal/text/xhtml-entities.cpp b/dali-toolkit/internal/text/xhtml-entities.cpp old mode 100755 new mode 100644 index 3ee7215..ac3981f --- a/dali-toolkit/internal/text/xhtml-entities.cpp +++ b/dali-toolkit/internal/text/xhtml-entities.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,13 +23,10 @@ namespace Dali { - namespace Toolkit { - namespace Text { - namespace { /** @@ -37,8 +34,8 @@ namespace */ struct XHTMLEntityLookup { - const char* const entityName; // XHTML Named Entity string - const char* const entityCode; // Corresponding UTF-8 + const char* const entityName; // XHTML Named Entity string + const char* const entityCode; // Corresponding UTF-8 }; /* table of html name entities supported in DALi @@ -46,279 +43,281 @@ struct XHTMLEntityLookup * these are stored as pair with Named entity as Key and * its utf 8 as value */ +// clang-format off const XHTMLEntityLookup XHTMLEntityLookupTable[] = - { - { ""\0" ,"\x22\0" }, - { "&\0" ,"\x26\0" }, - { "'\0" ,"\x27\0" }, - { "<\0" ,"\x3c\0" }, - { ">\0" ,"\x3e\0" }, - { " \0" ,"\xc2\xa0\0" }, - { "¡\0" ,"\xc2\xa1\0" }, - { "¢\0" ,"\xc2\xa2\0" }, - { "£\0" ,"\xc2\xa3\0" }, - { "¤\0" ,"\xc2\xa4\0" }, - { "¥\0" ,"\xc2\xa5\0" }, - { "¦\0" ,"\xc2\xa6\0" }, - { "§\0" ,"\xc2\xa7\0" }, - { "¨\0" ,"\xc2\xa8\0" }, - { "©\0" ,"\xc2\xa9\0" }, - { "ª\0" ,"\xc2\xaa\0" }, - { "«\0" ,"\xc2\xab\0" }, - { "¬\0" ,"\xc2\xac\0" }, - { "­\0" ,"\xc2\xad\0" }, - { "®\0" ,"\xc2\xae\0" }, - { "¯\0" ,"\xc2\xaf\0" }, - { "°\0" ,"\xc2\xb0\0" }, - { "±\0" ,"\xc2\xb1\0" }, - { "²\0" ,"\xc2\xb2\0" }, - { "³\0" ,"\xc2\xb3\0" }, - { "´\0" ,"\xc2\xb4\0" }, - { "µ\0" ,"\xc2\xb5\0" }, - { "¶\0" ,"\xc2\xb6\0" }, - { "·\0" ,"\xc2\xb7\0" }, - { "¸\0" ,"\xc2\xb8\0" }, - { "¹\0" ,"\xc2\xb9\0" }, - { "º\0" ,"\xc2\xba\0" }, - { "»\0" ,"\xc2\xbb\0" }, - { "¼\0" ,"\xc2\xbc\0" }, - { "½\0" ,"\xc2\xbd\0" }, - { "¾\0" ,"\xc2\xbe\0" }, - { "¿\0" ,"\xc2\xbf\0" }, - { "À\0" ,"\xc3\x80\0" }, - { "Á\0" ,"\xc3\x81\0" }, - { "Â\0" ,"\xc3\x82\0" }, - { "Ã\0" ,"\xc3\x83\0" }, - { "Ä\0" ,"\xc3\x84\0" }, - { "Å\0" ,"\xc3\x85\0" }, - { "Æ\0" ,"\xc3\x86\0" }, - { "Ç\0" ,"\xc3\x87\0" }, - { "È\0" ,"\xc3\x88\0" }, - { "É\0" ,"\xc3\x89\0" }, - { "Ê\0" ,"\xc3\x8a\0" }, - { "Ë\0" ,"\xc3\x8b\0" }, - { "Ì\0" ,"\xc3\x8c\0" }, - { "Í\0" ,"\xc3\x8d\0" }, - { "Î\0" ,"\xc3\x8e\0" }, - { "Ï\0" ,"\xc3\x8f\0" }, - { "Ð\0" ,"\xc3\x90\0" }, - { "Ñ\0" ,"\xc3\x91\0" }, - { "Ò\0" ,"\xc3\x92\0" }, - { "Ó\0" ,"\xc3\x93\0" }, - { "Ô\0" ,"\xc3\x94\0" }, - { "Õ\0" ,"\xc3\x95\0" }, - { "Ö\0" ,"\xc3\x96\0" }, - { "×\0" ,"\xc3\x97\0" }, - { "Ø\0" ,"\xc3\x98\0" }, - { "Ù\0" ,"\xc3\x99\0" }, - { "Ú\0" ,"\xc3\x9a\0" }, - { "Û\0" ,"\xc3\x9b\0" }, - { "Ü\0" ,"\xc3\x9c\0" }, - { "Ý\0" ,"\xc3\x9d\0" }, - { "Þ\0" ,"\xc3\x9e\0" }, - { "ß\0" ,"\xc3\x9f\0" }, - { "à\0" ,"\xc3\xa0\0" }, - { "á\0" ,"\xc3\xa1\0" }, - { "â\0" ,"\xc3\xa2\0" }, - { "ã\0" ,"\xc3\xa3\0" }, - { "ä\0" ,"\xc3\xa4\0" }, - { "å\0" ,"\xc3\xa5\0" }, - { "æ\0" ,"\xc3\xa6\0" }, - { "ç\0" ,"\xc3\xa7\0" }, - { "è\0" ,"\xc3\xa8\0" }, - { "é\0" ,"\xc3\xa9\0" }, - { "ê\0" ,"\xc3\xaa\0" }, - { "ë\0" ,"\xc3\xab\0" }, - { "ì\0" ,"\xc3\xac\0" }, - { "í\0" ,"\xc3\xad\0" }, - { "î\0" ,"\xc3\xae\0" }, - { "ï\0" ,"\xc3\xaf\0" }, - { "ð\0" ,"\xc3\xb0\0" }, - { "ñ\0" ,"\xc3\xb1\0" }, - { "ò\0" ,"\xc3\xb2\0" }, - { "ó\0" ,"\xc3\xb3\0" }, - { "ô\0" ,"\xc3\xb4\0" }, - { "õ\0" ,"\xc3\xb5\0" }, - { "ö\0" ,"\xc3\xb6\0" }, - { "÷\0" ,"\xc3\xb7\0" }, - { "ø\0" ,"\xc3\xb8\0" }, - { "ù\0" ,"\xc3\xb9\0" }, - { "ú\0" ,"\xc3\xba\0" }, - { "û\0" ,"\xc3\xbb\0" }, - { "ü\0" ,"\xc3\xbc\0" }, - { "ý\0" ,"\xc3\xbd\0" }, - { "þ\0" ,"\xc3\xbe\0" }, - { "ÿ\0" ,"\xc3\xbf\0" }, - { "Œ\0" ,"\xc5\x92\0" }, - { "œ\0" ,"\xc5\x93\0" }, - { "Š\0" ,"\xc5\xa0\0" }, - { "š\0" ,"\xc5\xa1\0" }, - { "Ÿ\0" ,"\xc5\xb8\0" }, - { "ƒ\0" ,"\xc6\x92\0" }, - { "ˆ\0" ,"\xcb\x86\0" }, - { "˜\0" ,"\xcb\x9c\0" }, - { "Α\0" ,"\xce\x91\0" }, - { "Β\0" ,"\xce\x92\0" }, - { "Γ\0" ,"\xce\x93\0" }, - { "Δ\0" ,"\xce\x94\0" }, - { "Ε\0" ,"\xce\x95\0" }, - { "Ζ\0" ,"\xce\x96\0" }, - { "Η\0" ,"\xce\x97\0" }, - { "Θ\0" ,"\xce\x98\0" }, - { "Ι\0" ,"\xce\x99\0" }, - { "Κ\0" ,"\xce\x9a\0" }, - { "Λ\0" ,"\xce\x9b\0" }, - { "Μ\0" ,"\xce\x9c\0" }, - { "Ν\0" ,"\xce\x9d\0" }, - { "Ξ\0" ,"\xce\x9e\0" }, - { "Ο\0" ,"\xce\x9f\0" }, - { "Π\0" ,"\xce\xa0\0" }, - { "Ρ\0" ,"\xce\xa1\0" }, - { "Σ\0" ,"\xce\xa3\0" }, - { "Τ\0" ,"\xce\xa4\0" }, - { "Υ\0" ,"\xce\xa5\0" }, - { "Φ\0" ,"\xce\xa6\0" }, - { "Χ\0" ,"\xce\xa7\0" }, - { "Ψ\0" ,"\xce\xa8\0" }, - { "Ω\0" ,"\xce\xa9\0" }, - { "α\0" ,"\xce\xb1\0" }, - { "β\0" ,"\xce\xb2\0" }, - { "γ\0" ,"\xce\xb3\0" }, - { "δ\0" ,"\xce\xb4\0" }, - { "ε\0" ,"\xce\xb5\0" }, - { "ζ\0" ,"\xce\xb6\0" }, - { "η\0" ,"\xce\xb7\0" }, - { "θ\0" ,"\xce\xb8\0" }, - { "ι\0" ,"\xce\xb9\0" }, - { "κ\0" ,"\xce\xba\0" }, - { "λ\0" ,"\xce\xbb\0" }, - { "μ\0" ,"\xce\xbc\0" }, - { "ν\0" ,"\xce\xbd\0" }, - { "ξ\0" ,"\xce\xbe\0" }, - { "ο\0" ,"\xce\xbf\0" }, - { "π\0" ,"\xcf\x80\0" }, - { "ρ\0" ,"\xcf\x81\0" }, - { "ς\0" ,"\xcf\x82\0" }, - { "σ\0" ,"\xcf\x83\0" }, - { "τ\0" ,"\xcf\x84\0" }, - { "υ\0" ,"\xcf\x85\0" }, - { "φ\0" ,"\xcf\x86\0" }, - { "χ\0" ,"\xcf\x87\0" }, - { "ψ\0" ,"\xcf\x88\0" }, - { "ω\0" ,"\xcf\x89\0" }, - { "ϑ\0","\xcf\x91\0" }, - { "ϒ\0" ,"\xcf\x92\0" }, - { "ϖ\0" ,"\xcf\x96\0" }, - { " \0" ,"\xe2\x80\x82\0" }, - { " \0" ,"\xe2\x80\x83\0" }, - { " \0" ,"\xe2\x80\x89\0" }, - { "‌\0" ,"\xe2\x80\x8c\0" }, - { "‍\0" ,"\xe2\x80\x8d\0" }, - { "‎\0" ,"\xe2\x80\x8e\0" }, - { "‏\0" ,"\xe2\x80\x8f\0" }, - { "–\0" ,"\xe2\x80\x93\0" }, - { "—\0" ,"\xe2\x80\x94\0" }, - { "‘\0" ,"\xe2\x80\x98\0" }, - { "’\0" ,"\xe2\x80\x99\0" }, - { "‚\0" ,"\xe2\x80\x9a\0" }, - { "“\0" ,"\xe2\x80\x9c\0" }, - { "”\0" ,"\xe2\x80\x9d\0" }, - { "„\0" ,"\xe2\x80\x9e\0" }, - { "†\0" ,"\xe2\x80\xa0\0" }, - { "‡\0" ,"\xe2\x80\xa1\0" }, - { "•\0" ,"\xe2\x80\xa2\0" }, - { "…\0" ,"\xe2\x80\xa6\0" }, - { "‰\0" ,"\xe2\x80\xb0\0" }, - { "′\0" ,"\xe2\x80\xb2\0" }, - { "″\0" ,"\xe2\x80\xb3\0" }, - { "‹\0" ,"\xe2\x80\xb9\0" }, - { "›\0" ,"\xe2\x80\xba\0" }, - { "‾\0" ,"\xe2\x80\xbe\0" }, - { "⁄\0" ,"\xe2\x81\x84\0" }, - { "€\0" ,"\xe2\x82\xac\0" }, - { "ℑ\0" ,"\xe2\x84\x91\0" }, - { "℘\0" ,"\xe2\x84\x98\0" }, - { "ℜ\0" ,"\xe2\x84\x9c\0" }, - { "™\0" ,"\xe2\x84\xa2\0" }, - { "ℵ\0" ,"\xe2\x84\xb5\0" }, - { "←\0" ,"\xe2\x86\x90\0" }, - { "↑\0" ,"\xe2\x86\x91\0" }, - { "→\0" ,"\xe2\x86\x92\0" }, - { "↓\0" ,"\xe2\x86\x93\0" }, - { "↔\0" ,"\xe2\x86\x94\0" }, - { "↵\0" ,"\xe2\x86\xb5\0" }, - { "⇐\0" ,"\xe2\x87\x90\0" }, - { "⇑\0" ,"\xe2\x87\x91\0" }, - { "⇒\0" ,"\xe2\x87\x92\0" }, - { "⇓\0" ,"\xe2\x87\x93\0" }, - { "⇔\0" ,"\xe2\x87\x94\0" }, - { "∀\0" ,"\xe2\x88\x80\0" }, - { "∂\0" ,"\xe2\x88\x82\0" }, - { "∃\0" ,"\xe2\x88\x83\0" }, - { "∅\0" ,"\xe2\x88\x85\0" }, - { "∇\0" ,"\xe2\x88\x87\0" }, - { "∈\0" ,"\xe2\x88\x88\0" }, - { "∉\0" ,"\xe2\x88\x89\0" }, - { "∋\0" ,"\xe2\x88\x8b\0" }, - { "∏\0" ,"\xe2\x88\x8f\0" }, - { "∑\0" ,"\xe2\x88\x91\0" }, - { "−\0" ,"\xe2\x88\x92\0" }, - { "∗\0" ,"\xe2\x88\x97\0" }, - { "√\0" ,"\xe2\x88\x9a\0" }, - { "∝\0" ,"\xe2\x88\x9d\0" }, - { "∞\0" ,"\xe2\x88\x9e\0" }, - { "∠\0" ,"\xe2\x88\xa0\0" }, - { "∧\0" ,"\xe2\x88\xa7\0" }, - { "∨\0" ,"\xe2\x88\xa8\0" }, - { "∩\0" ,"\xe2\x88\xa9\0" }, - { "∪\0" ,"\xe2\x88\xaa\0" }, - { "∫\0" ,"\xe2\x88\xab\0" }, - { "∴\0" ,"\xe2\x88\xb4\0" }, - { "∼\0" ,"\xe2\x88\xbc\0" }, - { "≅\0" ,"\xe2\x89\x85\0" }, - { "≈\0" ,"\xe2\x89\x88\0" }, - { "≠\0" ,"\xe2\x89\xa0\0" }, - { "≡\0" ,"\xe2\x89\xa1\0" }, - { "≤\0" ,"\xe2\x89\xa4\0" }, - { "≥\0" ,"\xe2\x89\xa5\0" }, - { "⊂\0" ,"\xe2\x8a\x82\0" }, - { "⊃\0" ,"\xe2\x8a\x83\0" }, - { "⊄\0" ,"\xe2\x8a\x84\0" }, - { "⊆\0" ,"\xe2\x8a\x86\0" }, - { "⊇\0" ,"\xe2\x8a\x87\0" }, - { "⊕\0" ,"\xe2\x8a\x95\0" }, - { "⊗\0" ,"\xe2\x8a\x97\0" }, - { "⊥\0" ,"\xe2\x8a\xa5\0" }, - { "⋅\0" ,"\xe2\x8b\x85\0" }, - { "⌈\0" ,"\xe2\x8c\x88\0" }, - { "⌉\0" ,"\xe2\x8c\x89\0" }, - { "⌊\0" ,"\xe2\x8c\x8a\0" }, - { "⌋\0" ,"\xe2\x8c\x8b\0" }, - { "◊\0" ,"\xe2\x97\x8a\0" }, - { "♠\0" ,"\xe2\x99\xa0\0" }, - { "♣\0" ,"\xe2\x99\xa3\0" }, - { "♥\0" ,"\xe2\x99\xa5\0" }, - { "♦\0" ,"\xe2\x99\xa6\0" }, - { "⟨\0" ,"\xe2\x9f\xa8\0" }, - { "⟩\0" ,"\xe2\x9f\xa9\0" } +{ + {""\0" ,"\x22\0" }, + {"&\0" ,"\x26\0" }, + {"'\0" ,"\x27\0" }, + {"<\0" ,"\x3c\0" }, + {">\0" ,"\x3e\0" }, + {" \0" ,"\xc2\xa0\0" }, + {"¡\0" ,"\xc2\xa1\0" }, + {"¢\0" ,"\xc2\xa2\0" }, + {"£\0" ,"\xc2\xa3\0" }, + {"¤\0" ,"\xc2\xa4\0" }, + {"¥\0" ,"\xc2\xa5\0" }, + {"¦\0" ,"\xc2\xa6\0" }, + {"§\0" ,"\xc2\xa7\0" }, + {"¨\0" ,"\xc2\xa8\0" }, + {"©\0" ,"\xc2\xa9\0" }, + {"ª\0" ,"\xc2\xaa\0" }, + {"«\0" ,"\xc2\xab\0" }, + {"¬\0" ,"\xc2\xac\0" }, + {"­\0" ,"\xc2\xad\0" }, + {"®\0" ,"\xc2\xae\0" }, + {"¯\0" ,"\xc2\xaf\0" }, + {"°\0" ,"\xc2\xb0\0" }, + {"±\0" ,"\xc2\xb1\0" }, + {"²\0" ,"\xc2\xb2\0" }, + {"³\0" ,"\xc2\xb3\0" }, + {"´\0" ,"\xc2\xb4\0" }, + {"µ\0" ,"\xc2\xb5\0" }, + {"¶\0" ,"\xc2\xb6\0" }, + {"·\0" ,"\xc2\xb7\0" }, + {"¸\0" ,"\xc2\xb8\0" }, + {"¹\0" ,"\xc2\xb9\0" }, + {"º\0" ,"\xc2\xba\0" }, + {"»\0" ,"\xc2\xbb\0" }, + {"¼\0" ,"\xc2\xbc\0" }, + {"½\0" ,"\xc2\xbd\0" }, + {"¾\0" ,"\xc2\xbe\0" }, + {"¿\0" ,"\xc2\xbf\0" }, + {"À\0" ,"\xc3\x80\0" }, + {"Á\0" ,"\xc3\x81\0" }, + {"Â\0" ,"\xc3\x82\0" }, + {"Ã\0" ,"\xc3\x83\0" }, + {"Ä\0" ,"\xc3\x84\0" }, + {"Å\0" ,"\xc3\x85\0" }, + {"Æ\0" ,"\xc3\x86\0" }, + {"Ç\0" ,"\xc3\x87\0" }, + {"È\0" ,"\xc3\x88\0" }, + {"É\0" ,"\xc3\x89\0" }, + {"Ê\0" ,"\xc3\x8a\0" }, + {"Ë\0" ,"\xc3\x8b\0" }, + {"Ì\0" ,"\xc3\x8c\0" }, + {"Í\0" ,"\xc3\x8d\0" }, + {"Î\0" ,"\xc3\x8e\0" }, + {"Ï\0" ,"\xc3\x8f\0" }, + {"Ð\0" ,"\xc3\x90\0" }, + {"Ñ\0" ,"\xc3\x91\0" }, + {"Ò\0" ,"\xc3\x92\0" }, + {"Ó\0" ,"\xc3\x93\0" }, + {"Ô\0" ,"\xc3\x94\0" }, + {"Õ\0" ,"\xc3\x95\0" }, + {"Ö\0" ,"\xc3\x96\0" }, + {"×\0" ,"\xc3\x97\0" }, + {"Ø\0" ,"\xc3\x98\0" }, + {"Ù\0" ,"\xc3\x99\0" }, + {"Ú\0" ,"\xc3\x9a\0" }, + {"Û\0" ,"\xc3\x9b\0" }, + {"Ü\0" ,"\xc3\x9c\0" }, + {"Ý\0" ,"\xc3\x9d\0" }, + {"Þ\0" ,"\xc3\x9e\0" }, + {"ß\0" ,"\xc3\x9f\0" }, + {"à\0" ,"\xc3\xa0\0" }, + {"á\0" ,"\xc3\xa1\0" }, + {"â\0" ,"\xc3\xa2\0" }, + {"ã\0" ,"\xc3\xa3\0" }, + {"ä\0" ,"\xc3\xa4\0" }, + {"å\0" ,"\xc3\xa5\0" }, + {"æ\0" ,"\xc3\xa6\0" }, + {"ç\0" ,"\xc3\xa7\0" }, + {"è\0" ,"\xc3\xa8\0" }, + {"é\0" ,"\xc3\xa9\0" }, + {"ê\0" ,"\xc3\xaa\0" }, + {"ë\0" ,"\xc3\xab\0" }, + {"ì\0" ,"\xc3\xac\0" }, + {"í\0" ,"\xc3\xad\0" }, + {"î\0" ,"\xc3\xae\0" }, + {"ï\0" ,"\xc3\xaf\0" }, + {"ð\0" ,"\xc3\xb0\0" }, + {"ñ\0" ,"\xc3\xb1\0" }, + {"ò\0" ,"\xc3\xb2\0" }, + {"ó\0" ,"\xc3\xb3\0" }, + {"ô\0" ,"\xc3\xb4\0" }, + {"õ\0" ,"\xc3\xb5\0" }, + {"ö\0" ,"\xc3\xb6\0" }, + {"÷\0" ,"\xc3\xb7\0" }, + {"ø\0" ,"\xc3\xb8\0" }, + {"ù\0" ,"\xc3\xb9\0" }, + {"ú\0" ,"\xc3\xba\0" }, + {"û\0" ,"\xc3\xbb\0" }, + {"ü\0" ,"\xc3\xbc\0" }, + {"ý\0" ,"\xc3\xbd\0" }, + {"þ\0" ,"\xc3\xbe\0" }, + {"ÿ\0" ,"\xc3\xbf\0" }, + {"Œ\0" ,"\xc5\x92\0" }, + {"œ\0" ,"\xc5\x93\0" }, + {"Š\0" ,"\xc5\xa0\0" }, + {"š\0" ,"\xc5\xa1\0" }, + {"Ÿ\0" ,"\xc5\xb8\0" }, + {"ƒ\0" ,"\xc6\x92\0" }, + {"ˆ\0" ,"\xcb\x86\0" }, + {"˜\0" ,"\xcb\x9c\0" }, + {"Α\0" ,"\xce\x91\0" }, + {"Β\0" ,"\xce\x92\0" }, + {"Γ\0" ,"\xce\x93\0" }, + {"Δ\0" ,"\xce\x94\0" }, + {"Ε\0" ,"\xce\x95\0" }, + {"Ζ\0" ,"\xce\x96\0" }, + {"Η\0" ,"\xce\x97\0" }, + {"Θ\0" ,"\xce\x98\0" }, + {"Ι\0" ,"\xce\x99\0" }, + {"Κ\0" ,"\xce\x9a\0" }, + {"Λ\0" ,"\xce\x9b\0" }, + {"Μ\0" ,"\xce\x9c\0" }, + {"Ν\0" ,"\xce\x9d\0" }, + {"Ξ\0" ,"\xce\x9e\0" }, + {"Ο\0" ,"\xce\x9f\0" }, + {"Π\0" ,"\xce\xa0\0" }, + {"Ρ\0" ,"\xce\xa1\0" }, + {"Σ\0" ,"\xce\xa3\0" }, + {"Τ\0" ,"\xce\xa4\0" }, + {"Υ\0" ,"\xce\xa5\0" }, + {"Φ\0" ,"\xce\xa6\0" }, + {"Χ\0" ,"\xce\xa7\0" }, + {"Ψ\0" ,"\xce\xa8\0" }, + {"Ω\0" ,"\xce\xa9\0" }, + {"α\0" ,"\xce\xb1\0" }, + {"β\0" ,"\xce\xb2\0" }, + {"γ\0" ,"\xce\xb3\0" }, + {"δ\0" ,"\xce\xb4\0" }, + {"ε\0" ,"\xce\xb5\0" }, + {"ζ\0" ,"\xce\xb6\0" }, + {"η\0" ,"\xce\xb7\0" }, + {"θ\0" ,"\xce\xb8\0" }, + {"ι\0" ,"\xce\xb9\0" }, + {"κ\0" ,"\xce\xba\0" }, + {"λ\0" ,"\xce\xbb\0" }, + {"μ\0" ,"\xce\xbc\0" }, + {"ν\0" ,"\xce\xbd\0" }, + {"ξ\0" ,"\xce\xbe\0" }, + {"ο\0" ,"\xce\xbf\0" }, + {"π\0" ,"\xcf\x80\0" }, + {"ρ\0" ,"\xcf\x81\0" }, + {"ς\0" ,"\xcf\x82\0" }, + {"σ\0" ,"\xcf\x83\0" }, + {"τ\0" ,"\xcf\x84\0" }, + {"υ\0" ,"\xcf\x85\0" }, + {"φ\0" ,"\xcf\x86\0" }, + {"χ\0" ,"\xcf\x87\0" }, + {"ψ\0" ,"\xcf\x88\0" }, + {"ω\0" ,"\xcf\x89\0" }, + {"ϑ\0","\xcf\x91\0" }, + {"ϒ\0" ,"\xcf\x92\0" }, + {"ϖ\0" ,"\xcf\x96\0" }, + {" \0" ,"\xe2\x80\x82\0" }, + {" \0" ,"\xe2\x80\x83\0" }, + {" \0" ,"\xe2\x80\x89\0" }, + {"‌\0" ,"\xe2\x80\x8c\0" }, + {"‍\0" ,"\xe2\x80\x8d\0" }, + {"‎\0" ,"\xe2\x80\x8e\0" }, + {"‏\0" ,"\xe2\x80\x8f\0" }, + {"–\0" ,"\xe2\x80\x93\0" }, + {"—\0" ,"\xe2\x80\x94\0" }, + {"‘\0" ,"\xe2\x80\x98\0" }, + {"’\0" ,"\xe2\x80\x99\0" }, + {"‚\0" ,"\xe2\x80\x9a\0" }, + {"“\0" ,"\xe2\x80\x9c\0" }, + {"”\0" ,"\xe2\x80\x9d\0" }, + {"„\0" ,"\xe2\x80\x9e\0" }, + {"†\0" ,"\xe2\x80\xa0\0" }, + {"‡\0" ,"\xe2\x80\xa1\0" }, + {"•\0" ,"\xe2\x80\xa2\0" }, + {"…\0" ,"\xe2\x80\xa6\0" }, + {"‰\0" ,"\xe2\x80\xb0\0" }, + {"′\0" ,"\xe2\x80\xb2\0" }, + {"″\0" ,"\xe2\x80\xb3\0" }, + {"‹\0" ,"\xe2\x80\xb9\0" }, + {"›\0" ,"\xe2\x80\xba\0" }, + {"‾\0" ,"\xe2\x80\xbe\0" }, + {"⁄\0" ,"\xe2\x81\x84\0" }, + {"€\0" ,"\xe2\x82\xac\0" }, + {"ℑ\0" ,"\xe2\x84\x91\0" }, + {"℘\0" ,"\xe2\x84\x98\0" }, + {"ℜ\0" ,"\xe2\x84\x9c\0" }, + {"™\0" ,"\xe2\x84\xa2\0" }, + {"ℵ\0" ,"\xe2\x84\xb5\0" }, + {"←\0" ,"\xe2\x86\x90\0" }, + {"↑\0" ,"\xe2\x86\x91\0" }, + {"→\0" ,"\xe2\x86\x92\0" }, + {"↓\0" ,"\xe2\x86\x93\0" }, + {"↔\0" ,"\xe2\x86\x94\0" }, + {"↵\0" ,"\xe2\x86\xb5\0" }, + {"⇐\0" ,"\xe2\x87\x90\0" }, + {"⇑\0" ,"\xe2\x87\x91\0" }, + {"⇒\0" ,"\xe2\x87\x92\0" }, + {"⇓\0" ,"\xe2\x87\x93\0" }, + {"⇔\0" ,"\xe2\x87\x94\0" }, + {"∀\0" ,"\xe2\x88\x80\0" }, + {"∂\0" ,"\xe2\x88\x82\0" }, + {"∃\0" ,"\xe2\x88\x83\0" }, + {"∅\0" ,"\xe2\x88\x85\0" }, + {"∇\0" ,"\xe2\x88\x87\0" }, + {"∈\0" ,"\xe2\x88\x88\0" }, + {"∉\0" ,"\xe2\x88\x89\0" }, + {"∋\0" ,"\xe2\x88\x8b\0" }, + {"∏\0" ,"\xe2\x88\x8f\0" }, + {"∑\0" ,"\xe2\x88\x91\0" }, + {"−\0" ,"\xe2\x88\x92\0" }, + {"∗\0" ,"\xe2\x88\x97\0" }, + {"√\0" ,"\xe2\x88\x9a\0" }, + {"∝\0" ,"\xe2\x88\x9d\0" }, + {"∞\0" ,"\xe2\x88\x9e\0" }, + {"∠\0" ,"\xe2\x88\xa0\0" }, + {"∧\0" ,"\xe2\x88\xa7\0" }, + {"∨\0" ,"\xe2\x88\xa8\0" }, + {"∩\0" ,"\xe2\x88\xa9\0" }, + {"∪\0" ,"\xe2\x88\xaa\0" }, + {"∫\0" ,"\xe2\x88\xab\0" }, + {"∴\0" ,"\xe2\x88\xb4\0" }, + {"∼\0" ,"\xe2\x88\xbc\0" }, + {"≅\0" ,"\xe2\x89\x85\0" }, + {"≈\0" ,"\xe2\x89\x88\0" }, + {"≠\0" ,"\xe2\x89\xa0\0" }, + {"≡\0" ,"\xe2\x89\xa1\0" }, + {"≤\0" ,"\xe2\x89\xa4\0" }, + {"≥\0" ,"\xe2\x89\xa5\0" }, + {"⊂\0" ,"\xe2\x8a\x82\0" }, + {"⊃\0" ,"\xe2\x8a\x83\0" }, + {"⊄\0" ,"\xe2\x8a\x84\0" }, + {"⊆\0" ,"\xe2\x8a\x86\0" }, + {"⊇\0" ,"\xe2\x8a\x87\0" }, + {"⊕\0" ,"\xe2\x8a\x95\0" }, + {"⊗\0" ,"\xe2\x8a\x97\0" }, + {"⊥\0" ,"\xe2\x8a\xa5\0" }, + {"⋅\0" ,"\xe2\x8b\x85\0" }, + {"⌈\0" ,"\xe2\x8c\x88\0" }, + {"⌉\0" ,"\xe2\x8c\x89\0" }, + {"⌊\0" ,"\xe2\x8c\x8a\0" }, + {"⌋\0" ,"\xe2\x8c\x8b\0" }, + {"◊\0" ,"\xe2\x97\x8a\0" }, + {"♠\0" ,"\xe2\x99\xa0\0" }, + {"♣\0" ,"\xe2\x99\xa3\0" }, + {"♥\0" ,"\xe2\x99\xa5\0" }, + {"♦\0" ,"\xe2\x99\xa6\0" }, + {"⟨\0" ,"\xe2\x9f\xa8\0" }, + {"⟩\0" ,"\xe2\x9f\xa9\0" } }; +// clang-format on -const std::size_t XHTMLENTITY_LOOKUP_COUNT = (sizeof( XHTMLEntityLookupTable))/ (sizeof(XHTMLEntityLookup)); +const std::size_t XHTMLENTITY_LOOKUP_COUNT = (sizeof(XHTMLEntityLookupTable)) / (sizeof(XHTMLEntityLookup)); } // unnamed namespace -const char* const NamedEntityToUtf8( const char* const markupText, unsigned int len ) +const char* const NamedEntityToUtf8(const char* const markupText, unsigned int len) { // finding if given XHTML named entity is supported or not - for( size_t i = 0; i < XHTMLENTITY_LOOKUP_COUNT ; ++i ) + for(size_t i = 0; i < XHTMLENTITY_LOOKUP_COUNT; ++i) { unsigned int entityLen = strlen(XHTMLEntityLookupTable[i].entityName); - if( len == entityLen ) + if(len == entityLen) { - if( strncmp( markupText, XHTMLEntityLookupTable[i].entityName, len ) == 0 ) // if named Entity found in table - { - return XHTMLEntityLookupTable[i].entityCode; - } + if(strncmp(markupText, XHTMLEntityLookupTable[i].entityName, len) == 0) // if named Entity found in table + { + return XHTMLEntityLookupTable[i].entityCode; + } } } return NULL; diff --git a/dali-toolkit/internal/transition-effects/cube-transition-cross-effect-impl.cpp b/dali-toolkit/internal/transition-effects/cube-transition-cross-effect-impl.cpp index b1df2b9..b1b15b7 100644 --- a/dali-toolkit/internal/transition-effects/cube-transition-cross-effect-impl.cpp +++ b/dali-toolkit/internal/transition-effects/cube-transition-cross-effect-impl.cpp @@ -20,26 +20,23 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - -CubeTransitionCrossEffect::CubeTransitionCrossEffect( unsigned int numRows, unsigned int numColumns ) -: CubeTransitionEffect( numRows, numColumns ), - mDisplacementSpreadFactor( 0.008f ) +CubeTransitionCrossEffect::CubeTransitionCrossEffect(unsigned int numRows, unsigned int numColumns) +: CubeTransitionEffect(numRows, numColumns), + mDisplacementSpreadFactor(0.008f) { } -Toolkit::CubeTransitionCrossEffect CubeTransitionCrossEffect::New(unsigned int numRows, unsigned int numColumns ) +Toolkit::CubeTransitionCrossEffect CubeTransitionCrossEffect::New(unsigned int numRows, unsigned int numColumns) { // Create the implementation - IntrusivePtr< CubeTransitionCrossEffect > internalCubeTransEffect = new CubeTransitionCrossEffect( numRows, numColumns ); + IntrusivePtr internalCubeTransEffect = new CubeTransitionCrossEffect(numRows, numColumns); // Pass ownership to CustomActor handle - Toolkit::CubeTransitionCrossEffect cubeTransEffect( *internalCubeTransEffect ); + Toolkit::CubeTransitionCrossEffect cubeTransEffect(*internalCubeTransEffect); //Initialization internalCubeTransEffect->Initialize(); @@ -50,39 +47,39 @@ Toolkit::CubeTransitionCrossEffect CubeTransitionCrossEffect::New(unsigned int n void CubeTransitionCrossEffect::OnInitialize() { unsigned int idx; - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - for( unsigned int x = y % 2; x < mColumns; x += 2 ) + for(unsigned int x = y % 2; x < mColumns; x += 2) { idx = y * mColumns + x; - SetTargetTop( idx ); + SetTargetTop(idx); } - for( unsigned int x = ( y + 1 ) % 2; x < mColumns; x += 2 ) + for(unsigned int x = (y + 1) % 2; x < mColumns; x += 2) { idx = y * mColumns + x; - SetTargetRight( idx ); + SetTargetRight(idx); } } } -void CubeTransitionCrossEffect::OnStartTransition( Vector2 panPosition, Vector2 panDisplacement ) +void CubeTransitionCrossEffect::OnStartTransition(Vector2 panPosition, Vector2 panDisplacement) { - float angle = Math::PI_2; + float angle = Math::PI_2; unsigned int idx; - if( panDisplacement.x < 0 ) + if(panDisplacement.x < 0) { - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - for( unsigned int x = y % 2; x < mColumns; x += 2 ) + for(unsigned int x = y % 2; x < mColumns; x += 2) { idx = y * mColumns + x; - SetTargetTop( idx ); + SetTargetTop(idx); } - for( unsigned int x = ( y + 1 ) % 2; x < mColumns; x += 2 ) + for(unsigned int x = (y + 1) % 2; x < mColumns; x += 2) { idx = y * mColumns + x; - SetTargetRight( idx ); + SetTargetRight(idx); } } } @@ -90,36 +87,36 @@ void CubeTransitionCrossEffect::OnStartTransition( Vector2 panPosition, Vector2 { angle = -angle; - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - for( unsigned int x = y % 2; x < mColumns; x += 2 ) + for(unsigned int x = y % 2; x < mColumns; x += 2) { idx = y * mColumns + x; - SetTargetBottom( idx ); + SetTargetBottom(idx); } - for( unsigned int x = ( y + 1 ) % 2; x < mColumns; x += 2 ) + for(unsigned int x = (y + 1) % 2; x < mColumns; x += 2) { idx = y * mColumns + x; - SetTargetLeft( idx ); + SetTargetLeft(idx); } } } - const Vector2 halfSize = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).GetVectorXY() * 0.5f; + const Vector2 halfSize = Self().GetCurrentProperty(Actor::Property::SIZE).GetVectorXY() * 0.5f; //the centre to "explode" the tiles outwards from - Vector3 centre( halfSize.x, halfSize.y, -1.0f / mDisplacementSpreadFactor ); + Vector3 centre(halfSize.x, halfSize.y, -1.0f / mDisplacementSpreadFactor); - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - for( unsigned int x = y%2; x < mColumns; x=x+2) // rotate vertically + for(unsigned int x = y % 2; x < mColumns; x = x + 2) // rotate vertically { - idx = y*mColumns + x; - SetupAnimation( idx, x, y, -angle, Vector3::XAXIS, centre ); + idx = y * mColumns + x; + SetupAnimation(idx, x, y, -angle, Vector3::XAXIS, centre); } - for( unsigned int x = (y+1)%2; x < mColumns; x=x+2) // rotate horizontally + for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2) // rotate horizontally { - idx = y*mColumns + x; - SetupAnimation( idx, x, y, angle, Vector3::YAXIS, centre ); + idx = y * mColumns + x; + SetupAnimation(idx, x, y, angle, Vector3::YAXIS, centre); } } @@ -127,28 +124,28 @@ void CubeTransitionCrossEffect::OnStartTransition( Vector2 panPosition, Vector2 mIsAnimating = true; } -void CubeTransitionCrossEffect::SetupAnimation( unsigned int actorIndex, unsigned int x, unsigned int y, float angle, const Vector3 axis, const Vector3& displacementCentre ) +void CubeTransitionCrossEffect::SetupAnimation(unsigned int actorIndex, unsigned int x, unsigned int y, float angle, const Vector3 axis, const Vector3& displacementCentre) { - const Vector2 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).GetVectorXY(); - Vector2 halfSize = size * 0.5f; + const Vector2 size = Self().GetCurrentProperty(Actor::Property::SIZE).GetVectorXY(); + Vector2 halfSize = size * 0.5f; //the position of the centre of the front face tile - Vector3 position( halfSize.x * (2.0f * x + 1.0f) / mColumns, halfSize.y * (2.0f * y + 1.0f ) / mRows, 0.0f ); + Vector3 position(halfSize.x * (2.0f * x + 1.0f) / mColumns, halfSize.y * (2.0f * y + 1.0f) / mRows, 0.0f); Vector3 direction = position - displacementCentre; - float length = direction.Length(); + float length = direction.Length(); direction.Normalize(); float deltaLength = mCubeDisplacement / direction.z; //the length along the direction vector such that the projected direction onto the z axis is equal to mCubeDisplacement - Vector3 newPosition = ( direction * (length + deltaLength ) ) + displacementCentre; + Vector3 newPosition = (direction * (length + deltaLength)) + displacementCentre; Vector3 newLocalPosition = newPosition - position; - mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::ORIENTATION ), Quaternion( Radian( -angle ), axis ), AlphaFunction::EASE_IN_OUT_SINE ); - mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::POSITION ), newLocalPosition, AlphaFunction::BOUNCE ); + mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::ORIENTATION), Quaternion(Radian(-angle), axis), AlphaFunction::EASE_IN_OUT_SINE); + mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::POSITION), newLocalPosition, AlphaFunction::BOUNCE); - mAnimation.AnimateTo( Property( mCurrentTiles[ actorIndex ], Actor::Property::COLOR ), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT ); - mAnimation.AnimateTo( Property( mTargetTiles[ actorIndex ], Actor::Property::COLOR ), FULL_BRIGHTNESS, AlphaFunction::EASE_IN ); + mAnimation.AnimateTo(Property(mCurrentTiles[actorIndex], Actor::Property::COLOR), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT); + mAnimation.AnimateTo(Property(mTargetTiles[actorIndex], Actor::Property::COLOR), FULL_BRIGHTNESS, AlphaFunction::EASE_IN); } } // namespace Internal diff --git a/dali-toolkit/internal/transition-effects/cube-transition-effect-impl.cpp b/dali-toolkit/internal/transition-effects/cube-transition-effect-impl.cpp index bd52a8b..31dd157 100644 --- a/dali-toolkit/internal/transition-effects/cube-transition-effect-impl.cpp +++ b/dali-toolkit/internal/transition-effects/cube-transition-effect-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,10 +19,10 @@ #include "cube-transition-effect-impl.h" // EXTERNAL INCLUDES -#include // for strcmp -#include -#include #include +#include +#include +#include // for strcmp // INTERNAL INCLUDES #include @@ -31,44 +31,40 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // Setup properties, signals and actions using the type-registry. -DALI_TYPE_REGISTRATION_BEGIN( Toolkit::CubeTransitionEffect, Dali::BaseHandle, NULL ); +DALI_TYPE_REGISTRATION_BEGIN(Toolkit::CubeTransitionEffect, Dali::BaseHandle, NULL); -DALI_SIGNAL_REGISTRATION( Toolkit, CubeTransitionEffect, "transitionCompleted", SIGNAL_TRANSITION_COMPLETED ) +DALI_SIGNAL_REGISTRATION(Toolkit, CubeTransitionEffect, "transitionCompleted", SIGNAL_TRANSITION_COMPLETED) DALI_TYPE_REGISTRATION_END() -Actor CreateTile( const Vector4& samplerRect ) +Actor CreateTile(const Vector4& samplerRect) { - Actor tile = Actor::New(); - tile.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); - tile.RegisterProperty( "uTextureRect", samplerRect ); + Actor tile = Actor::New(); + tile.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); + tile.RegisterProperty("uTextureRect", samplerRect); return tile; } -} +} // namespace + +const Vector4 CubeTransitionEffect::FULL_BRIGHTNESS(1.0f, 1.0f, 1.0f, 1.0f); +const Vector4 CubeTransitionEffect::HALF_BRIGHTNESS(0.5f, 0.5f, 0.5f, 1.0f); -const Vector4 CubeTransitionEffect::FULL_BRIGHTNESS( 1.0f, 1.0f, 1.0f, 1.0f ); -const Vector4 CubeTransitionEffect::HALF_BRIGHTNESS( 0.5f, 0.5f, 0.5f, 1.0f ); - -CubeTransitionEffect::CubeTransitionEffect( unsigned int rows, unsigned int columns ) -: Control( ControlBehaviour( DISABLE_STYLE_CHANGE_SIGNALS ) ), - mRows( rows ), - mColumns( columns ), - mIsAnimating( false ), - mIsPaused( false ), - mAnimationDuration( 1.f ), - mCubeDisplacement( 0.f ) +CubeTransitionEffect::CubeTransitionEffect(unsigned int rows, unsigned int columns) +: Control(ControlBehaviour(DISABLE_STYLE_CHANGE_SIGNALS)), + mRows(rows), + mColumns(columns), + mIsAnimating(false), + mIsPaused(false), + mAnimationDuration(1.f), + mCubeDisplacement(0.f) { } @@ -76,181 +72,181 @@ CubeTransitionEffect::~CubeTransitionEffect() { } -void CubeTransitionEffect::SetTargetRight( unsigned int idx ) +void CubeTransitionEffect::SetTargetRight(unsigned int idx) { - mBoxType[ idx ] = RIGHT; + mBoxType[idx] = RIGHT; - mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f ); + mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f); - mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 1.f, 0.5f, 0.5f) ); - mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( 90.f ), Vector3::YAXIS ) ); + mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(1.f, 0.5f, 0.5f)); + mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(90.f), Vector3::YAXIS)); } -void CubeTransitionEffect::SetTargetLeft( unsigned int idx ) +void CubeTransitionEffect::SetTargetLeft(unsigned int idx) { - mBoxType[ idx ] = LEFT; + mBoxType[idx] = LEFT; - mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f ); + mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f); - mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.f, 0.5f, 0.5f) ); - mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( -90.f ), Vector3::YAXIS ) ); + mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.f, 0.5f, 0.5f)); + mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(-90.f), Vector3::YAXIS)); } -void CubeTransitionEffect::SetTargetBottom( unsigned int idx ) +void CubeTransitionEffect::SetTargetBottom(unsigned int idx) { - mBoxType[ idx ] = BOTTOM; + mBoxType[idx] = BOTTOM; - mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f ); + mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f); - mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.f, 0.5f) ); - mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( 90.f ), Vector3::XAXIS ) ); + mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 0.f, 0.5f)); + mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(90.f), Vector3::XAXIS)); } -void CubeTransitionEffect::SetTargetTop( unsigned int idx ) +void CubeTransitionEffect::SetTargetTop(unsigned int idx) { - mBoxType[ idx ] = TOP; + mBoxType[idx] = TOP; - mBoxes[ idx ].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f ); + mBoxes[idx].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f); - mTargetTiles[ idx ].SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 1.f, 0.5f) ); - mTargetTiles[ idx ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( -90.f ), Vector3::XAXIS ) ); + mTargetTiles[idx].SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 1.f, 0.5f)); + mTargetTiles[idx].SetProperty(Actor::Property::ORIENTATION, Quaternion(Degree(-90.f), Vector3::XAXIS)); } -void CubeTransitionEffect::OnRelayout( const Vector2& size, RelayoutContainer& container ) +void CubeTransitionEffect::OnRelayout(const Vector2& size, RelayoutContainer& container) { - mTileSize = Vector2( size.x / mColumns, size.y / mRows ); + mTileSize = Vector2(size.x / mColumns, size.y / mRows); - mBoxRoot.SetProperty( Actor::Property::SIZE_WIDTH, size.x ); - mBoxRoot.SetProperty( Actor::Property::SIZE_HEIGHT, size.y ); - mBoxRoot.SetProperty( Actor::Property::SIZE_DEPTH, 1.0f ); + mBoxRoot.SetProperty(Actor::Property::SIZE_WIDTH, size.x); + mBoxRoot.SetProperty(Actor::Property::SIZE_HEIGHT, size.y); + mBoxRoot.SetProperty(Actor::Property::SIZE_DEPTH, 1.0f); - for( size_t i = 0; i < mBoxes.size(); ++i ) + for(size_t i = 0; i < mBoxes.size(); ++i) { - mBoxes[ i ].SetProperty( Actor::Property::SIZE_WIDTH, mTileSize.x ); - mBoxes[ i ].SetProperty( Actor::Property::SIZE_HEIGHT, mTileSize.y ); + mBoxes[i].SetProperty(Actor::Property::SIZE_WIDTH, mTileSize.x); + mBoxes[i].SetProperty(Actor::Property::SIZE_HEIGHT, mTileSize.y); - switch( mBoxType[i] ) + switch(mBoxType[i]) { case LEFT: case RIGHT: { - mBoxes[ i ].SetProperty( Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f ); - mBoxes[ i ].SetProperty( Actor::Property::SIZE_DEPTH, mTileSize.x ); + mBoxes[i].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.x * 0.5f); + mBoxes[i].SetProperty(Actor::Property::SIZE_DEPTH, mTileSize.x); break; } case BOTTOM: case TOP: { - mBoxes[ i ].SetProperty( Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f ); - mBoxes[ i ].SetProperty( Actor::Property::SIZE_DEPTH, mTileSize.y ); + mBoxes[i].SetProperty(Actor::Property::PARENT_ORIGIN_Z, 1.0f - mTileSize.y * 0.5f); + mBoxes[i].SetProperty(Actor::Property::SIZE_DEPTH, mTileSize.y); break; } } } - for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it ) + for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it) { - it->SetProperty( Actor::Property::SIZE_WIDTH, mTileSize.x ); - it->SetProperty( Actor::Property::SIZE_HEIGHT, mTileSize.y ); + it->SetProperty(Actor::Property::SIZE_WIDTH, mTileSize.x); + it->SetProperty(Actor::Property::SIZE_HEIGHT, mTileSize.y); } - for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it ) + for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it) { - it->SetProperty( Actor::Property::SIZE_WIDTH, mTileSize.x ); - it->SetProperty( Actor::Property::SIZE_HEIGHT, mTileSize.y ); + it->SetProperty(Actor::Property::SIZE_WIDTH, mTileSize.x); + it->SetProperty(Actor::Property::SIZE_HEIGHT, mTileSize.y); } } void CubeTransitionEffect::Initialize() { - Self().RegisterProperty( "uTextureRect", Vector4( 0.0f, 0.0f, 1.0f, 1.0f ) ); + Self().RegisterProperty("uTextureRect", Vector4(0.0f, 0.0f, 1.0f, 1.0f)); mBoxType.Resize(mColumns * mRows); //create the box parents mBoxRoot = Actor::New(); - mBoxRoot.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); - mBoxRoot.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); + mBoxRoot.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); + mBoxRoot.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); mCurrentTiles.clear(); mTargetTiles.clear(); - mCurrentTiles.reserve( mColumns * mRows ); - mTargetTiles.reserve( mColumns * mRows ); + mCurrentTiles.reserve(mColumns * mRows); + mTargetTiles.reserve(mColumns * mRows); - Vector2 gridSizeInv( 1.0f / mColumns, 1.0f / mRows ); - Vector3 offset( 0.5f * gridSizeInv.x, 0.5f * gridSizeInv.y, 0.0f ); + Vector2 gridSizeInv(1.0f / mColumns, 1.0f / mRows); + Vector3 offset(0.5f * gridSizeInv.x, 0.5f * gridSizeInv.y, 0.0f); Vector3 anchor; - for( unsigned int y = 0; y < mRows; ++y, anchor.y += 1.0f / mRows ) + for(unsigned int y = 0; y < mRows; ++y, anchor.y += 1.0f / mRows) { anchor.x = 0.0f; - for( unsigned int x = 0; x RemoveRenderer( mCurrentRenderer ); + it->RemoveRenderer(mCurrentRenderer); } mCurrentRenderer.Reset(); } - if( mTargetRenderer ) + if(mTargetRenderer) { - for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it ) + for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it) { - it->RemoveRenderer( mTargetRenderer ); + it->RemoveRenderer(mTargetRenderer); } mTargetRenderer.Reset(); } @@ -258,17 +254,17 @@ void CubeTransitionEffect::OnSceneDisconnection() Control::OnSceneDisconnection(); } -void CubeTransitionEffect::SetTransitionDuration( float duration ) +void CubeTransitionEffect::SetTransitionDuration(float duration) { mAnimationDuration = duration; } -float CubeTransitionEffect::GetTransitionDuration( ) const +float CubeTransitionEffect::GetTransitionDuration() const { return mAnimationDuration; } -void CubeTransitionEffect::SetCubeDisplacement( float displacement ) +void CubeTransitionEffect::SetCubeDisplacement(float displacement) { mCubeDisplacement = displacement; } @@ -283,81 +279,81 @@ bool CubeTransitionEffect::IsTransitioning() return mIsAnimating; } -void CubeTransitionEffect::SetCurrentTexture( Texture texture ) +void CubeTransitionEffect::SetCurrentTexture(Texture texture) { mCurrentTexture = texture; - if( mCurrentRenderer ) + if(mCurrentRenderer) { TextureSet textureSet = mCurrentRenderer.GetTextures(); - textureSet.SetTexture( 0u, mCurrentTexture); + textureSet.SetTexture(0u, mCurrentTexture); } } -void CubeTransitionEffect::SetTargetTexture( Texture texture ) +void CubeTransitionEffect::SetTargetTexture(Texture texture) { mTargetTexture = texture; - if( mTargetRenderer ) + if(mTargetRenderer) { TextureSet textureSet = mTargetRenderer.GetTextures(); - textureSet.SetTexture( 0u, mTargetTexture ); + textureSet.SetTexture(0u, mTargetTexture); } } -void CubeTransitionEffect::StartTransition( bool toNextImage ) +void CubeTransitionEffect::StartTransition(bool toNextImage) { - Vector3 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - if( toNextImage ) + Vector3 size = Self().GetCurrentProperty(Actor::Property::SIZE); + if(toNextImage) { - StartTransition( Vector2(size.x* 0.5f, size.y*0.5f), Vector2( -10.f, 0.f ) ); + StartTransition(Vector2(size.x * 0.5f, size.y * 0.5f), Vector2(-10.f, 0.f)); } else { - StartTransition( Vector2(size.x* 0.5f, size.y*0.5f), Vector2( 10.f, 0.f )); + StartTransition(Vector2(size.x * 0.5f, size.y * 0.5f), Vector2(10.f, 0.f)); } } -void CubeTransitionEffect::StartTransition( Vector2 panPosition, Vector2 panDisplacement ) +void CubeTransitionEffect::StartTransition(Vector2 panPosition, Vector2 panDisplacement) { - if( !mCurrentRenderer ) + if(!mCurrentRenderer) { - DALI_LOG_ERROR( "Trying to transition a cube transition without an image set\n" ); + DALI_LOG_ERROR("Trying to transition a cube transition without an image set\n"); return; } //create the target renderer TextureSet textureSet = TextureSet::New(); - if( mTargetTexture ) + if(mTargetTexture) { - textureSet.SetTexture( 0u, mTargetTexture ); + textureSet.SetTexture(0u, mTargetTexture); } Geometry geometry = mCurrentRenderer.GetGeometry(); - Shader shader( mCurrentRenderer.GetShader() ); - mTargetRenderer = Renderer::New( geometry, shader ); - mTargetRenderer.SetTextures( textureSet ); + Shader shader(mCurrentRenderer.GetShader()); + mTargetRenderer = Renderer::New(geometry, shader); + mTargetRenderer.SetTextures(textureSet); int depthIndex = mCurrentRenderer.GetProperty(Renderer::Property::DEPTH_INDEX); - mTargetRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex ); + mTargetRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, depthIndex); - for( size_t i = 0; i < mBoxes.size(); ++i ) + for(size_t i = 0; i < mBoxes.size(); ++i) { - mBoxes[ i ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) ); + mBoxes[i].SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS)); } - for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it ) + for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it) { - it->SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.5f, 1.0f) ); - it->SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) ); - it->AddRenderer( mCurrentRenderer ); + it->SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 0.5f, 1.0f)); + it->SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS)); + it->AddRenderer(mCurrentRenderer); } - for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it ) + for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it) { - it->AddRenderer( mTargetRenderer ); + it->AddRenderer(mTargetRenderer); } - Self().RemoveRenderer( mCurrentRenderer ); - Self().Add( mBoxRoot ); + Self().RemoveRenderer(mCurrentRenderer); + Self().Add(mBoxRoot); if(mAnimation) { @@ -365,15 +361,15 @@ void CubeTransitionEffect::StartTransition( Vector2 panPosition, Vector2 panDisp mAnimation.Reset(); } - mAnimation = Animation::New( mAnimationDuration ); - mAnimation.FinishedSignal().Connect( this, &CubeTransitionEffect::OnTransitionFinished ); + mAnimation = Animation::New(mAnimationDuration); + mAnimation.FinishedSignal().Connect(this, &CubeTransitionEffect::OnTransitionFinished); - OnStartTransition( panPosition, panDisplacement ); + OnStartTransition(panPosition, panDisplacement); } void CubeTransitionEffect::PauseTransition() { - if( mIsAnimating && !mIsPaused ) + if(mIsAnimating && !mIsPaused) { mAnimation.Pause(); mIsPaused = true; @@ -382,7 +378,7 @@ void CubeTransitionEffect::PauseTransition() void CubeTransitionEffect::ResumeTransition() { - if( mIsAnimating && mIsPaused) + if(mIsAnimating && mIsPaused) { mAnimation.Play(); mIsPaused = false; @@ -400,53 +396,52 @@ void CubeTransitionEffect::ResetToInitialState() mAnimation.Reset(); mIsAnimating = false; - Self().Remove( mBoxRoot ); + Self().Remove(mBoxRoot); - for( size_t i = 0; i < mBoxes.size(); ++i ) + for(size_t i = 0; i < mBoxes.size(); ++i) { - mBoxes[ i ].SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) ); + mBoxes[i].SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS)); } - for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it ) + for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it) { - it->SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.5f, 1.0f) ); - it->SetProperty( Actor::Property::ORIENTATION, Quaternion( Radian( 0.0f ), Vector3::XAXIS ) ); - it->SetProperty( Actor::Property::COLOR, FULL_BRIGHTNESS ); + it->SetProperty(Actor::Property::PARENT_ORIGIN, Vector3(0.5f, 0.5f, 1.0f)); + it->SetProperty(Actor::Property::ORIENTATION, Quaternion(Radian(0.0f), Vector3::XAXIS)); + it->SetProperty(Actor::Property::COLOR, FULL_BRIGHTNESS); } - if( mCurrentRenderer ) + if(mCurrentRenderer) { - for( ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it ) + for(ActorArray::iterator it = mCurrentTiles.begin(); it != mCurrentTiles.end(); ++it) { - it->RemoveRenderer( mCurrentRenderer ); + it->RemoveRenderer(mCurrentRenderer); } - Self().AddRenderer( mCurrentRenderer ); + Self().AddRenderer(mCurrentRenderer); } - for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it ) + for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it) { - it->SetProperty( Actor::Property::COLOR, HALF_BRIGHTNESS ); + it->SetProperty(Actor::Property::COLOR, HALF_BRIGHTNESS); } - if( mTargetRenderer ) + if(mTargetRenderer) { - for( ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it ) + for(ActorArray::iterator it = mTargetTiles.begin(); it != mTargetTiles.end(); ++it) { - it->RemoveRenderer( mTargetRenderer ); + it->RemoveRenderer(mTargetRenderer); } } } void CubeTransitionEffect::OnTransitionFinished(Animation& source) { - - std::swap( mCurrentTiles, mTargetTiles ); - std::swap( mCurrentRenderer, mTargetRenderer ); - std::swap( mCurrentTexture, mTargetTexture ); + std::swap(mCurrentTiles, mTargetTiles); + std::swap(mCurrentRenderer, mTargetRenderer); + std::swap(mCurrentTexture, mTargetTexture); ResetToInitialState(); //Emit signal - Toolkit::CubeTransitionEffect handle( GetOwner() ); - mTransitionCompletedSignal.Emit( handle, mCurrentTexture ); + Toolkit::CubeTransitionEffect handle(GetOwner()); + mTransitionCompletedSignal.Emit(handle, mCurrentTexture); } Toolkit::CubeTransitionEffect::TransitionCompletedSignalType& CubeTransitionEffect::TransitionCompletedSignal() @@ -454,16 +449,16 @@ Toolkit::CubeTransitionEffect::TransitionCompletedSignalType& CubeTransitionEffe return mTransitionCompletedSignal; } -bool CubeTransitionEffect::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) +bool CubeTransitionEffect::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { - Dali::BaseHandle handle( object ); + Dali::BaseHandle handle(object); - bool connected( true ); - Toolkit::CubeTransitionEffect cubeTransitionEffect = Toolkit::CubeTransitionEffect::DownCast( handle ); + bool connected(true); + Toolkit::CubeTransitionEffect cubeTransitionEffect = Toolkit::CubeTransitionEffect::DownCast(handle); - if( 0 == strcmp( signalName.c_str(), SIGNAL_TRANSITION_COMPLETED ) ) + if(0 == strcmp(signalName.c_str(), SIGNAL_TRANSITION_COMPLETED)) { - cubeTransitionEffect.TransitionCompletedSignal().Connect( tracker, functor ); + cubeTransitionEffect.TransitionCompletedSignal().Connect(tracker, functor); } else { diff --git a/dali-toolkit/internal/transition-effects/cube-transition-fold-effect-impl.cpp b/dali-toolkit/internal/transition-effects/cube-transition-fold-effect-impl.cpp index b1feba8..5866bbc 100644 --- a/dali-toolkit/internal/transition-effects/cube-transition-fold-effect-impl.cpp +++ b/dali-toolkit/internal/transition-effects/cube-transition-fold-effect-impl.cpp @@ -20,24 +20,22 @@ namespace Dali { - namespace Toolkit { - namespace Internal { -CubeTransitionFoldEffect::CubeTransitionFoldEffect( unsigned int numRows, unsigned int numColumns ) -: CubeTransitionEffect( numRows, numColumns ) +CubeTransitionFoldEffect::CubeTransitionFoldEffect(unsigned int numRows, unsigned int numColumns) +: CubeTransitionEffect(numRows, numColumns) { } -Toolkit::CubeTransitionFoldEffect CubeTransitionFoldEffect::New(unsigned int numRows, unsigned int numColumns ) +Toolkit::CubeTransitionFoldEffect CubeTransitionFoldEffect::New(unsigned int numRows, unsigned int numColumns) { // Create the implementation - IntrusivePtr< CubeTransitionFoldEffect > internalCubeTransEffect = new CubeTransitionFoldEffect( numRows, numColumns ); + IntrusivePtr internalCubeTransEffect = new CubeTransitionFoldEffect(numRows, numColumns); // Pass ownership to CustomActor handle - Toolkit::CubeTransitionFoldEffect cubeTransEffect( *internalCubeTransEffect ); + Toolkit::CubeTransitionFoldEffect cubeTransEffect(*internalCubeTransEffect); //Initialization internalCubeTransEffect->Initialize(); @@ -48,37 +46,37 @@ Toolkit::CubeTransitionFoldEffect CubeTransitionFoldEffect::New(unsigned int num void CubeTransitionFoldEffect::OnInitialize() { unsigned int idx; - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - idx = y*mColumns; - for( unsigned int x = y%2; x < mColumns; x=x+2) + idx = y * mColumns; + for(unsigned int x = y % 2; x < mColumns; x = x + 2) { - SetTargetLeft( idx + x ); + SetTargetLeft(idx + x); } - for( unsigned int x = (y+1)%2; x < mColumns; x=x+2) + for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2) { - SetTargetRight( idx + x ); + SetTargetRight(idx + x); } } } -void CubeTransitionFoldEffect::OnStartTransition( Vector2 panPosition, Vector2 panDisplacement ) +void CubeTransitionFoldEffect::OnStartTransition(Vector2 panPosition, Vector2 panDisplacement) { float angle = Math::PI_2; unsigned int idx; - if( panDisplacement.x < 0 ) + if(panDisplacement.x < 0) { - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - idx = y*mColumns; - for( unsigned int x = y%2; x < mColumns; x=x+2) + idx = y * mColumns; + for(unsigned int x = y % 2; x < mColumns; x = x + 2) { - SetTargetLeft( idx + x ); + SetTargetLeft(idx + x); } - for( unsigned int x = (y+1)%2; x < mColumns; x=x+2) + for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2) { - SetTargetRight( idx + x ); + SetTargetRight(idx + x); } } } @@ -86,30 +84,30 @@ void CubeTransitionFoldEffect::OnStartTransition( Vector2 panPosition, Vector2 p { angle = -angle; - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - idx = y*mColumns; - for( unsigned int x = y%2; x < mColumns; x=x+2) + idx = y * mColumns; + for(unsigned int x = y % 2; x < mColumns; x = x + 2) { - SetTargetRight( idx + x ); + SetTargetRight(idx + x); } - for( unsigned int x = (y+1)%2; x < mColumns; x=x+2) + for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2) { - SetTargetLeft( idx + x ); + SetTargetLeft(idx + x); } } } - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { - idx = y*mColumns; - for( unsigned int x = y%2; x < mColumns; x=x+2) + idx = y * mColumns; + for(unsigned int x = y % 2; x < mColumns; x = x + 2) { - SetupAnimation( idx + x, x, angle ); + SetupAnimation(idx + x, x, angle); } - for( unsigned int x = (y+1)%2; x < mColumns; x=x+2) + for(unsigned int x = (y + 1) % 2; x < mColumns; x = x + 2) { - SetupAnimation( idx + x, x, -angle ); + SetupAnimation(idx + x, x, -angle); } } @@ -117,7 +115,7 @@ void CubeTransitionFoldEffect::OnStartTransition( Vector2 panPosition, Vector2 p mIsAnimating = true; } -void CubeTransitionFoldEffect::SetupAnimation( unsigned int actorIndex, unsigned int x, float angle ) +void CubeTransitionFoldEffect::SetupAnimation(unsigned int actorIndex, unsigned int x, float angle) { //rotate and translate the cube such that the edges remain in constant contact //calculate the maximum distance the cube has to move when it the box has rotated 45 degrees @@ -130,14 +128,14 @@ void CubeTransitionFoldEffect::SetupAnimation( unsigned int actorIndex, unsigned //accumulating over the length of the row we get: // delta_distance_at_x = x * delta_distance; - float delta = (float)x * mTileSize.x * ( 1.4142f - 1.0f ); + float delta = (float)x * mTileSize.x * (1.4142f - 1.0f); - Vector3 position( mBoxes[ actorIndex ].GetCurrentProperty< Vector3 >( Actor::Property::POSITION ) ); - mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::ORIENTATION ), Quaternion( Radian( angle ), Vector3::YAXIS ), AlphaFunction::LINEAR ); - mAnimation.AnimateTo( Property( mBoxes[ actorIndex ], Actor::Property::POSITION_X ), position.x + delta, AlphaFunction::BOUNCE ); + Vector3 position(mBoxes[actorIndex].GetCurrentProperty(Actor::Property::POSITION)); + mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::ORIENTATION), Quaternion(Radian(angle), Vector3::YAXIS), AlphaFunction::LINEAR); + mAnimation.AnimateTo(Property(mBoxes[actorIndex], Actor::Property::POSITION_X), position.x + delta, AlphaFunction::BOUNCE); - mAnimation.AnimateTo( Property( mCurrentTiles[ actorIndex ], Actor::Property::COLOR ), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT ); - mAnimation.AnimateTo( Property( mTargetTiles[ actorIndex ], Actor::Property::COLOR ), FULL_BRIGHTNESS, AlphaFunction::EASE_IN ); + mAnimation.AnimateTo(Property(mCurrentTiles[actorIndex], Actor::Property::COLOR), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT); + mAnimation.AnimateTo(Property(mTargetTiles[actorIndex], Actor::Property::COLOR), FULL_BRIGHTNESS, AlphaFunction::EASE_IN); } } // namespace Internal diff --git a/dali-toolkit/internal/transition-effects/cube-transition-wave-effect-impl.cpp b/dali-toolkit/internal/transition-effects/cube-transition-wave-effect-impl.cpp index c9fdb2e..abbe286 100644 --- a/dali-toolkit/internal/transition-effects/cube-transition-wave-effect-impl.cpp +++ b/dali-toolkit/internal/transition-effects/cube-transition-wave-effect-impl.cpp @@ -20,28 +20,25 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - -CubeTransitionWaveEffect::CubeTransitionWaveEffect( unsigned int numRows, unsigned int numColumns ) -: CubeTransitionEffect( numRows, numColumns ), - mSaddleAA( 1.f ), - mSaddleBB( 1.f ), - mSaddleB( 1.f ) +CubeTransitionWaveEffect::CubeTransitionWaveEffect(unsigned int numRows, unsigned int numColumns) +: CubeTransitionEffect(numRows, numColumns), + mSaddleAA(1.f), + mSaddleBB(1.f), + mSaddleB(1.f) { } -Toolkit::CubeTransitionWaveEffect CubeTransitionWaveEffect::New(unsigned int numRows, unsigned int numColumns ) +Toolkit::CubeTransitionWaveEffect CubeTransitionWaveEffect::New(unsigned int numRows, unsigned int numColumns) { // Create the implementation - IntrusivePtr< CubeTransitionWaveEffect > internalCubeTransEffect = new CubeTransitionWaveEffect( numRows, numColumns ); + IntrusivePtr internalCubeTransEffect = new CubeTransitionWaveEffect(numRows, numColumns); // Pass ownership to CustomActor handle - Toolkit::CubeTransitionWaveEffect cubeTransEffect( *internalCubeTransEffect ); + Toolkit::CubeTransitionWaveEffect cubeTransEffect(*internalCubeTransEffect); //Initialization internalCubeTransEffect->Initialize(); @@ -51,55 +48,51 @@ Toolkit::CubeTransitionWaveEffect CubeTransitionWaveEffect::New(unsigned int num void CubeTransitionWaveEffect::OnInitialize() { - for( unsigned int idx = 0; idx < mTargetTiles.size(); idx++ ) + for(unsigned int idx = 0; idx < mTargetTiles.size(); idx++) { - SetTargetRight( idx ); + SetTargetRight(idx); } } -void CubeTransitionWaveEffect::OnStartTransition( Vector2 panPosition, Vector2 panDisplacement ) +void CubeTransitionWaveEffect::OnStartTransition(Vector2 panPosition, Vector2 panDisplacement) { bool forward = panDisplacement.x < 0.0; - CalculateSaddleSurfaceParameters( panPosition, forward ? panDisplacement : -panDisplacement ); + CalculateSaddleSurfaceParameters(panPosition, forward ? panDisplacement : -panDisplacement); float angle = Math::PI_2; unsigned int idx; - if( forward ) + if(forward) { - for( idx = 0; idx < mTargetTiles.size(); idx++ ) + for(idx = 0; idx < mTargetTiles.size(); idx++) { - SetTargetRight( idx ); + SetTargetRight(idx); } } else { angle = -angle; - for( idx = 0; idx < mTargetTiles.size(); idx++ ) + for(idx = 0; idx < mTargetTiles.size(); idx++) { - SetTargetLeft( idx ); + SetTargetLeft(idx); } } float thirdAnimationDuration = mAnimationDuration / 3.f; - for( unsigned int y = 0; y < mRows; y++ ) + for(unsigned int y = 0; y < mRows; y++) { idx = y * mColumns; - for( unsigned int x = 0; x < mColumns; x++, idx++) + for(unsigned int x = 0; x < mColumns; x++, idx++) { // the delay value is within 0.f ~ 2.f*thirdAnimationDuration - float delay = thirdAnimationDuration * CalculateDelay( x * mTileSize.width, y * mTileSize.height, forward ); + float delay = thirdAnimationDuration * CalculateDelay(x * mTileSize.width, y * mTileSize.height, forward); - mAnimation.AnimateTo( Property( mBoxes[ idx ], Actor::Property::ORIENTATION ), Quaternion( Radian( -angle ), Vector3::YAXIS ), - AlphaFunction::EASE_OUT_SINE, TimePeriod( delay, thirdAnimationDuration ) ); - mAnimation.AnimateBy( Property( mBoxes[idx], Actor::Property::POSITION ), Vector3( 0.f, 0.f, -mCubeDisplacement ), - AlphaFunction::BOUNCE, TimePeriod( delay, thirdAnimationDuration ) ); + mAnimation.AnimateTo(Property(mBoxes[idx], Actor::Property::ORIENTATION), Quaternion(Radian(-angle), Vector3::YAXIS), AlphaFunction::EASE_OUT_SINE, TimePeriod(delay, thirdAnimationDuration)); + mAnimation.AnimateBy(Property(mBoxes[idx], Actor::Property::POSITION), Vector3(0.f, 0.f, -mCubeDisplacement), AlphaFunction::BOUNCE, TimePeriod(delay, thirdAnimationDuration)); - mAnimation.AnimateTo( Property( mCurrentTiles[ idx ], Actor::Property::COLOR ), HALF_BRIGHTNESS, - AlphaFunction::EASE_OUT, TimePeriod( delay, thirdAnimationDuration ) ); - mAnimation.AnimateTo( Property( mTargetTiles[ idx ], Actor::Property::COLOR ), FULL_BRIGHTNESS, - AlphaFunction::EASE_IN, TimePeriod( delay, thirdAnimationDuration ) ); + mAnimation.AnimateTo(Property(mCurrentTiles[idx], Actor::Property::COLOR), HALF_BRIGHTNESS, AlphaFunction::EASE_OUT, TimePeriod(delay, thirdAnimationDuration)); + mAnimation.AnimateTo(Property(mTargetTiles[idx], Actor::Property::COLOR), FULL_BRIGHTNESS, AlphaFunction::EASE_IN, TimePeriod(delay, thirdAnimationDuration)); } } @@ -107,50 +100,50 @@ void CubeTransitionWaveEffect::OnStartTransition( Vector2 panPosition, Vector2 p mIsAnimating = true; } -void CubeTransitionWaveEffect::CalculateSaddleSurfaceParameters( Vector2 position, Vector2 displacement ) +void CubeTransitionWaveEffect::CalculateSaddleSurfaceParameters(Vector2 position, Vector2 displacement) { - const Vector2 size = Self().GetCurrentProperty< Vector3 >( Actor::Property::SIZE ).GetVectorXY(); + const Vector2 size = Self().GetCurrentProperty(Actor::Property::SIZE).GetVectorXY(); // the line passes through 'position' and has the direction of 'displacement' float coefA, coefB, coefC; //line equation: Ax+By+C=0; coefA = displacement.y; coefB = -displacement.x; - coefC = -displacement.y*position.x + displacement.x*position.y; + coefC = -displacement.y * position.x + displacement.x * position.y; - float inversedAABB = 1.f / (coefA*coefA+coefB*coefB); + float inversedAABB = 1.f / (coefA * coefA + coefB * coefB); float inversedSqrtAABB = sqrtf(inversedAABB); float saddleA; if(displacement.y > 0) { //distance from (0,0) to the line - float distanceTopLeft = fabsf(coefC) * inversedSqrtAABB; + float distanceTopLeft = fabsf(coefC) * inversedSqrtAABB; //distance from (viewAreaSize.x, viewAreaSize.y) to the line - float distanceBottomRight = fabsf(coefA*size.x+coefB*size.y+coefC) * inversedSqrtAABB; - saddleA = std::max( distanceTopLeft, distanceBottomRight ); + float distanceBottomRight = fabsf(coefA * size.x + coefB * size.y + coefC) * inversedSqrtAABB; + saddleA = std::max(distanceTopLeft, distanceBottomRight); //foot of a perpendicular: (viewAreaSize.x,0) to the line - float footX1 = ( coefB*coefB*size.x - coefA*coefC) * inversedAABB; - float footY1 = (-coefA*coefB*size.x - coefB*coefC) * inversedAABB; + float footX1 = (coefB * coefB * size.x - coefA * coefC) * inversedAABB; + float footY1 = (-coefA * coefB * size.x - coefB * coefC) * inversedAABB; //foot of a perpendicular: (0,viewAreaSize.y) to the line - float footX2 = (-coefA*coefB*size.y - coefA*coefC) * inversedAABB; - float footY2 = ( coefA*coefA*size.y - coefB*coefC) * inversedAABB; - mSaddleBB = (footX1-footX2)*(footX1-footX2) + (footY1-footY2)*(footY1-footY2); - mTranslation = Vector2(-footX2,-footY2); + float footX2 = (-coefA * coefB * size.y - coefA * coefC) * inversedAABB; + float footY2 = (coefA * coefA * size.y - coefB * coefC) * inversedAABB; + mSaddleBB = (footX1 - footX2) * (footX1 - footX2) + (footY1 - footY2) * (footY1 - footY2); + mTranslation = Vector2(-footX2, -footY2); } else { //distance from(viewAreaSize.x,0) to the line - float distanceTopRight = fabsf(coefA*size.x+coefC) * inversedSqrtAABB; + float distanceTopRight = fabsf(coefA * size.x + coefC) * inversedSqrtAABB; //distance from(0,viewAreaSize.y) to the line - float distanceBottomLeft = fabsf(coefB*size.y+coefC) * inversedSqrtAABB; - saddleA = std::max( distanceTopRight, distanceBottomLeft ); + float distanceBottomLeft = fabsf(coefB * size.y + coefC) * inversedSqrtAABB; + saddleA = std::max(distanceTopRight, distanceBottomLeft); //foot of a perpendicular: (0,0) to the line - float footX3 = (-coefA*coefC) * inversedAABB; - float footY3 = (-coefB*coefC) * inversedAABB; + float footX3 = (-coefA * coefC) * inversedAABB; + float footY3 = (-coefB * coefC) * inversedAABB; //foot of a perpendicular: (viewAreaSize.x,viewAreaSize.y) to the line - float footX4 = ( coefB*coefB*size.x - coefA*coefB*size.y - coefA*coefC) * inversedAABB; - float footY4 = (-coefA*coefB*size.x + coefA*coefA*size.y - coefB*coefC) * inversedAABB; - mSaddleBB = (footX3-footX4)*(footX3-footX4) + (footY3-footY4)*(footY3-footY4); + float footX4 = (coefB * coefB * size.x - coefA * coefB * size.y - coefA * coefC) * inversedAABB; + float footY4 = (-coefA * coefB * size.x + coefA * coefA * size.y - coefB * coefC) * inversedAABB; + mSaddleBB = (footX3 - footX4) * (footX3 - footX4) + (footY3 - footY4) * (footY3 - footY4); mTranslation = Vector2(-footX3, -footY3); } @@ -162,26 +155,26 @@ void CubeTransitionWaveEffect::CalculateSaddleSurfaceParameters( Vector2 positi } else if(mSaddleB < saddleA) { - mSaddleB = saddleA; - mSaddleBB = mSaddleB*mSaddleB; + mSaddleB = saddleA; + mSaddleBB = mSaddleB * mSaddleB; } - mSaddleAA = saddleA*saddleA; + mSaddleAA = saddleA * saddleA; mRotation = Vector2(-displacement.x, displacement.y); mRotation.Normalize(); } -float CubeTransitionWaveEffect::CalculateDelay( float x, float y, bool forward ) +float CubeTransitionWaveEffect::CalculateDelay(float x, float y, bool forward) { - float tx = x + mTranslation.x; - float ty = y + mTranslation.y; + float tx = x + mTranslation.x; + float ty = y + mTranslation.y; float valueX = mRotation.x * tx - mRotation.y * ty; float valueY = mRotation.y * tx + mRotation.x * ty; - if( !forward ) // to previous image + if(!forward) // to previous image { valueX = mSaddleB - valueX; } //the return value is a float number between 0.f and 2.f - return (1.f + valueY*valueY / mSaddleAA - valueX*valueX / mSaddleBB); + return (1.f + valueY * valueY / mSaddleAA - valueX * valueX / mSaddleBB); } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.cpp b/dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.cpp old mode 100755 new mode 100644 index 5ef6044..ef55fd8 --- a/dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.cpp +++ b/dali-toolkit/internal/visuals/animated-gradient/animated-gradient-visual.cpp @@ -19,68 +19,65 @@ //INTERNAL INCLUDES #include -#include #include -#include +#include +#include #include +#include #include -#include -#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { -DALI_ENUM_TO_STRING_TABLE_BEGIN( GRADIENT_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::GradientType, LINEAR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::GradientType, RADIAL ) -DALI_ENUM_TO_STRING_TABLE_END( GRADIENT_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( UNIT_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::UnitType, OBJECT_BOUNDING_BOX ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::UnitType, USER_SPACE ) -DALI_ENUM_TO_STRING_TABLE_END( UNIT_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( SPREAD_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::SpreadType, REFLECT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::SpreadType, REPEAT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::SpreadType, CLAMP ) -DALI_ENUM_TO_STRING_TABLE_END( SPREAD_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( DIRECTION_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, FORWARD ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, BACKWARD ) -DALI_ENUM_TO_STRING_TABLE_END( DIRECTION_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( MOTION_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, LOOP ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, MIRROR ) -DALI_ENUM_TO_STRING_TABLE_END( MOTION_TYPE ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( EASING_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, LINEAR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, OUT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN_OUT ) -DALI_ENUM_TO_STRING_TABLE_END( EASING_TYPE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(GRADIENT_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::GradientType, LINEAR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::GradientType, RADIAL) +DALI_ENUM_TO_STRING_TABLE_END(GRADIENT_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(UNIT_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::UnitType, OBJECT_BOUNDING_BOX) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::UnitType, USER_SPACE) +DALI_ENUM_TO_STRING_TABLE_END(UNIT_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(SPREAD_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::SpreadType, REFLECT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::SpreadType, REPEAT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::SpreadType, CLAMP) +DALI_ENUM_TO_STRING_TABLE_END(SPREAD_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(DIRECTION_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, FORWARD) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType, BACKWARD) +DALI_ENUM_TO_STRING_TABLE_END(DIRECTION_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(MOTION_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, LOOP) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType, MIRROR) +DALI_ENUM_TO_STRING_TABLE_END(MOTION_TYPE) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(EASING_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, LINEAR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, OUT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType, IN_OUT) +DALI_ENUM_TO_STRING_TABLE_END(EASING_TYPE) // Default values of each properties const Toolkit::DevelAnimatedGradientVisual::GradientType::Type DEFAULT_GRADIENT_TYPE = Toolkit::DevelAnimatedGradientVisual::GradientType::LINEAR; const Toolkit::DevelAnimatedGradientVisual::UnitType::Type DEFAULT_UNIT_TYPE = Toolkit::DevelAnimatedGradientVisual::UnitType::OBJECT_BOUNDING_BOX; const Toolkit::DevelAnimatedGradientVisual::SpreadType::Type DEFAULT_SPREAD_TYPE = Toolkit::DevelAnimatedGradientVisual::SpreadType::REFLECT; -const float DEFAULT_START_POSITION[] = { -0.5f, 0.0f }; -const float DEFAULT_START_COLOR[] = { 143.0f/255.0f, 170.0f/255.0f, 220.0f/255.0f, 255.0f/255.0f }; -const float DEFAULT_END_POSITION[] = { 0.5f, 0.0f }; -const float DEFAULT_END_COLOR[] = { 255.0f/255.0f, 163.0f/255.0f, 163.0f/255.0f, 255.0f/255.0f }; -const float DEFAULT_ROTATE_CENTER[] = { 0.0f, 0.0f }; +const float DEFAULT_START_POSITION[] = {-0.5f, 0.0f}; +const float DEFAULT_START_COLOR[] = {143.0f / 255.0f, 170.0f / 255.0f, 220.0f / 255.0f, 255.0f / 255.0f}; +const float DEFAULT_END_POSITION[] = {0.5f, 0.0f}; +const float DEFAULT_END_COLOR[] = {255.0f / 255.0f, 163.0f / 255.0f, 163.0f / 255.0f, 255.0f / 255.0f}; +const float DEFAULT_ROTATE_CENTER[] = {0.0f, 0.0f}; const float DEFAULT_ROTATE_AMOUNT = 0.0f; const float DEFAULT_ANIMATION_START_VALUE = 0.0f; @@ -94,55 +91,53 @@ const Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::T const Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::Type DEFAULT_ANIMATION_MOTION_TYPE = Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::LOOP; const Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::Type DEFAULT_ANIMATION_EASING_TYPE = Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR; -Property::Value GetStartValue( const Property::Map& map, Property::Index index, const char* const name ) +Property::Value GetStartValue(const Property::Map& map, Property::Index index, const char* const name) { // Get start value of animation parameter - Property::Value* res = map.Find( index, name ); - if( res ) + Property::Value* res = map.Find(index, name); + if(res) { Property::Map* s_map = res->GetMap(); - if( s_map ) + if(s_map) { - res = s_map->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, START_VALUE_NAME ); - DALI_ASSERT_ALWAYS( res && "Start value is not setup in Property::Map" ); + res = s_map->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, START_VALUE_NAME); + DALI_ASSERT_ALWAYS(res && "Start value is not setup in Property::Map"); } } else { - DALI_ASSERT_ALWAYS( !"Start value is not setup even default" ); + DALI_ASSERT_ALWAYS(!"Start value is not setup even default"); } return *res; } -VisualFactoryCache::ShaderType GetShaderType( Toolkit::DevelAnimatedGradientVisual::GradientType::Type grad, Toolkit::DevelAnimatedGradientVisual::UnitType::Type unit, Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spread ) +VisualFactoryCache::ShaderType GetShaderType(Toolkit::DevelAnimatedGradientVisual::GradientType::Type grad, Toolkit::DevelAnimatedGradientVisual::UnitType::Type unit, Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spread) { return static_cast( VisualFactoryCache::ANIMATED_GRADIENT_SHADER_LINEAR_BOUNDING_REFLECT + - static_cast( grad ) * 6 + // 6 is the number of UnitType * SpreadType - static_cast( unit ) * 3 + // 3 is the number of SpreadType. - static_cast( spread ) - ); + static_cast(grad) * 6 + // 6 is the number of UnitType * SpreadType + static_cast(unit) * 3 + // 3 is the number of SpreadType. + static_cast(spread)); } } // unnamed namespace -AnimatedGradientVisualPtr AnimatedGradientVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +AnimatedGradientVisualPtr AnimatedGradientVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - AnimatedGradientVisualPtr animatedGradientVisualPtr( new AnimatedGradientVisual( factoryCache ) ); - animatedGradientVisualPtr->SetProperties( properties ); + AnimatedGradientVisualPtr animatedGradientVisualPtr(new AnimatedGradientVisual(factoryCache)); + animatedGradientVisualPtr->SetProperties(properties); animatedGradientVisualPtr->Initialize(); return animatedGradientVisualPtr; } -AnimatedGradientVisual::AnimatedGradientVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FILL, static_cast( Toolkit::DevelVisual::ANIMATED_GRADIENT ) ) +AnimatedGradientVisual::AnimatedGradientVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast(Toolkit::DevelVisual::ANIMATED_GRADIENT)) { SetupDefaultValue(); } AnimatedGradientVisual::~AnimatedGradientVisual() { - } void AnimatedGradientVisual::SetupDefaultValue() @@ -151,100 +146,100 @@ void AnimatedGradientVisual::SetupDefaultValue() mUnitType = DEFAULT_UNIT_TYPE; mSpreadType = DEFAULT_SPREAD_TYPE; - mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = Vector2( DEFAULT_START_POSITION ); - mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = Vector4( DEFAULT_START_COLOR ); - mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = Vector2( DEFAULT_END_POSITION ); - mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = Vector4( DEFAULT_END_COLOR ); - mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = Vector2( DEFAULT_ROTATE_CENTER ); + mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = Vector2(DEFAULT_START_POSITION); + mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = Vector4(DEFAULT_START_COLOR); + mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = Vector2(DEFAULT_END_POSITION); + mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = Vector4(DEFAULT_END_COLOR); + mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = Vector2(DEFAULT_ROTATE_CENTER); mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT] = DEFAULT_ROTATE_AMOUNT; // Default Offset value is very special. unlimited animation from 0.0f to 2.0f { Property::Map map; - map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, 0.0f ); - map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, 2.0f ); - map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, -1 ); + map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, 0.0f); + map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, 2.0f); + map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, -1); mValueMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET] = map; } } -void AnimatedGradientVisual::DoSetProperties( const Property::Map& propertyMap ) +void AnimatedGradientVisual::DoSetProperties(const Property::Map& propertyMap) { //GRADIENT_TYPE - Property::Value* gradientTypeValue = propertyMap.Find( Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, GRADIENT_TYPE_NAME ); - Toolkit::DevelAnimatedGradientVisual::GradientType::Type gradientType = mGradientType; - if( gradientTypeValue ) + Property::Value* gradientTypeValue = propertyMap.Find(Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, GRADIENT_TYPE_NAME); + Toolkit::DevelAnimatedGradientVisual::GradientType::Type gradientType = mGradientType; + if(gradientTypeValue) { - Scripting::GetEnumerationProperty( *gradientTypeValue, GRADIENT_TYPE_TABLE, GRADIENT_TYPE_TABLE_COUNT, gradientType ); + Scripting::GetEnumerationProperty(*gradientTypeValue, GRADIENT_TYPE_TABLE, GRADIENT_TYPE_TABLE_COUNT, gradientType); } //UNIT_TYPE - Property::Value* unitTypeValue = propertyMap.Find( Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE, UNIT_TYPE_NAME ); - Toolkit::DevelAnimatedGradientVisual::UnitType::Type unitType = mUnitType; - if( unitTypeValue ) + Property::Value* unitTypeValue = propertyMap.Find(Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE, UNIT_TYPE_NAME); + Toolkit::DevelAnimatedGradientVisual::UnitType::Type unitType = mUnitType; + if(unitTypeValue) { - Scripting::GetEnumerationProperty( *unitTypeValue, UNIT_TYPE_TABLE, UNIT_TYPE_TABLE_COUNT, unitType ); + Scripting::GetEnumerationProperty(*unitTypeValue, UNIT_TYPE_TABLE, UNIT_TYPE_TABLE_COUNT, unitType); } //SPREAD_TYPE - Property::Value* spreadTypeValue = propertyMap.Find( Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE, SPREAD_TYPE_NAME ); - Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spreadType = mSpreadType; - if( spreadTypeValue ) + Property::Value* spreadTypeValue = propertyMap.Find(Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE, SPREAD_TYPE_NAME); + Toolkit::DevelAnimatedGradientVisual::SpreadType::Type spreadType = mSpreadType; + if(spreadTypeValue) { - Scripting::GetEnumerationProperty( *spreadTypeValue, SPREAD_TYPE_TABLE, SPREAD_TYPE_TABLE_COUNT, spreadType ); + Scripting::GetEnumerationProperty(*spreadTypeValue, SPREAD_TYPE_TABLE, SPREAD_TYPE_TABLE_COUNT, spreadType); } mGradientType = gradientType; - mUnitType = unitType; - mSpreadType = spreadType; + mUnitType = unitType; + mSpreadType = spreadType; SetupGradientAnimationData(propertyMap); } -void AnimatedGradientVisual::SetupGradientAnimationData( const Property::Map& propertyMap ) +void AnimatedGradientVisual::SetupGradientAnimationData(const Property::Map& propertyMap) { mGradientAnimationDataList.Clear(); // Clear Transition Information. All animation will deleted safely static Property::Map propertyNameMap; static Property::Map propertyUniformNameMap; - if( propertyNameMap.Empty() ) + if(propertyNameMap.Empty()) { propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = START_POSITION_NAME; - propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR ] = START_COLOR_NAME; - propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION ] = END_POSITION_NAME; - propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR ] = END_COLOR_NAME; - propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER ] = ROTATE_CENTER_NAME; - propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT ] = ROTATE_AMOUNT_NAME; - propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET ] = OFFSET_NAME; + propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = START_COLOR_NAME; + propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = END_POSITION_NAME; + propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = END_COLOR_NAME; + propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = ROTATE_CENTER_NAME; + propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT] = ROTATE_AMOUNT_NAME; + propertyNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET] = OFFSET_NAME; } - if( propertyUniformNameMap.Empty() ) + if(propertyUniformNameMap.Empty()) { propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION] = UNIFORM_START_POINT_NAME; - propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR ] = UNIFORM_START_COLOR_NAME; - propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION ] = UNIFORM_END_POINT_NAME; - propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR ] = UNIFORM_END_COLOR_NAME; - propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER ] = UNIFORM_ROTATE_CENTER_NAME; - propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT ] = UNIFORM_ROTATE_ANGLE_NAME; - propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET ] = UNIFORM_OFFSET_NAME; + propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR] = UNIFORM_START_COLOR_NAME; + propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION] = UNIFORM_END_POINT_NAME; + propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR] = UNIFORM_END_COLOR_NAME; + propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER] = UNIFORM_ROTATE_CENTER_NAME; + propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT] = UNIFORM_ROTATE_ANGLE_NAME; + propertyUniformNameMap[Toolkit::DevelAnimatedGradientVisual::Property::OFFSET] = UNIFORM_OFFSET_NAME; } Property::Map::SizeType map_index_end = propertyNameMap.Count(); - for( Property::Map::SizeType map_index = 0; map_index < map_index_end; map_index++ ) + for(Property::Map::SizeType map_index = 0; map_index < map_index_end; map_index++) { - KeyValuePair property_pair = propertyNameMap.GetKeyValue( map_index ); - KeyValuePair uniform_pair = propertyUniformNameMap.GetKeyValue( map_index ); - Property::Index index = property_pair.first.indexKey; - const std::string property_name = property_pair.second.Get< std::string >(); - const std::string uniform_name = uniform_pair.second.Get< std::string >(); + KeyValuePair property_pair = propertyNameMap.GetKeyValue(map_index); + KeyValuePair uniform_pair = propertyUniformNameMap.GetKeyValue(map_index); + Property::Index index = property_pair.first.indexKey; + const std::string property_name = property_pair.second.Get(); + const std::string uniform_name = uniform_pair.second.Get(); - Property::Map map; + Property::Map map; Property::Value default_value = mValueMap[index]; - map["target"] = "background"; + map["target"] = "background"; map["property"] = uniform_name; - Property::Value *value = propertyMap.Find( index, property_name ); - if( !value ) + Property::Value* value = propertyMap.Find(index, property_name); + if(!value) { value = &default_value; } @@ -254,18 +249,17 @@ void AnimatedGradientVisual::SetupGradientAnimationData( const Property::Map& pr mValueMap[index] = (*value); } - int loop_count = 0; - float delay = 0.0f; - bool forward = true; - bool auto_mirror = false; - std::string ease_str = "LINEAR"; - Property::Map *map_value = value->GetMap(); - if( map_value ) + int loop_count = 0; + float delay = 0.0f; + bool forward = true; + bool auto_mirror = false; + std::string ease_str = "LINEAR"; + Property::Map* map_value = value->GetMap(); + if(map_value) { - auto getValueFromMap = [ &map_value ]( const Property::Index& index, const std::string& name, Property::Value& res ) -> void - { - Property::Value *sub_value = map_value->Find( index, name ); - if( sub_value ) + auto getValueFromMap = [&map_value](const Property::Index& index, const std::string& name, Property::Value& res) -> void { + Property::Value* sub_value = map_value->Find(index, name); + if(sub_value) { res = *sub_value; } @@ -278,39 +272,39 @@ void AnimatedGradientVisual::SetupGradientAnimationData( const Property::Map& pr Property::Value value_repeat = DEFAULT_ANIMATION_REPEAT; Property::Value value_repeat_delay = DEFAULT_ANIMATION_REPEAT_DELAY; - getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START , START_VALUE_NAME , value_start ); - getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET , TARGET_VALUE_NAME , value_target ); - getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION , DURATION_NAME , value_duration ); - getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY , DELAY_NAME , value_delay ); - getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT , REPEAT_NAME , value_repeat ); - getValueFromMap( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, REPEAT_DELAY_NAME , value_repeat_delay ); + getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, START_VALUE_NAME, value_start); + getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, TARGET_VALUE_NAME, value_target); + getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION, DURATION_NAME, value_duration); + getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY, DELAY_NAME, value_delay); + getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, REPEAT_NAME, value_repeat); + getValueFromMap(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, REPEAT_DELAY_NAME, value_repeat_delay); Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::Type direction_type = DEFAULT_ANIMATION_DIRECTION_TYPE; Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::Type motion_type = DEFAULT_ANIMATION_MOTION_TYPE; Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::Type easing_type = DEFAULT_ANIMATION_EASING_TYPE; - Property::Value *direction_sub_value = map_value->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION, DIRECTION_TYPE_NAME ); - if( direction_sub_value ) + Property::Value* direction_sub_value = map_value->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION, DIRECTION_TYPE_NAME); + if(direction_sub_value) { - Scripting::GetEnumerationProperty( *direction_sub_value, DIRECTION_TYPE_TABLE, DIRECTION_TYPE_TABLE_COUNT, direction_type ); + Scripting::GetEnumerationProperty(*direction_sub_value, DIRECTION_TYPE_TABLE, DIRECTION_TYPE_TABLE_COUNT, direction_type); } - Property::Value *motion_sub_value = map_value->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE, MOTION_TYPE_NAME ); - if( motion_sub_value ) + Property::Value* motion_sub_value = map_value->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE, MOTION_TYPE_NAME); + if(motion_sub_value) { - Scripting::GetEnumerationProperty( *motion_sub_value , MOTION_TYPE_TABLE , MOTION_TYPE_TABLE_COUNT , motion_type ); + Scripting::GetEnumerationProperty(*motion_sub_value, MOTION_TYPE_TABLE, MOTION_TYPE_TABLE_COUNT, motion_type); } - Property::Value *easing_sub_value = map_value->Find( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE, EASING_TYPE_NAME ); - if( easing_sub_value ) + Property::Value* easing_sub_value = map_value->Find(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE, EASING_TYPE_NAME); + if(easing_sub_value) { - Scripting::GetEnumerationProperty( *easing_sub_value , EASING_TYPE_TABLE , EASING_TYPE_TABLE_COUNT , easing_type ); + Scripting::GetEnumerationProperty(*easing_sub_value, EASING_TYPE_TABLE, EASING_TYPE_TABLE_COUNT, easing_type); } - forward = ( direction_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD ); - delay = value_delay.Get< float >(); - loop_count = value_repeat.Get< int >(); - auto_mirror = ( motion_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR ); + forward = (direction_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD); + delay = value_delay.Get(); + loop_count = value_repeat.Get(); + auto_mirror = (motion_type == Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR); - switch( easing_type ) + switch(easing_type) { case Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR: { @@ -335,62 +329,60 @@ void AnimatedGradientVisual::SetupGradientAnimationData( const Property::Map& pr } map["initialValue"] = forward ? value_start : value_target; - map["targetValue"] = forward ? value_target : value_start; - if( loop_count != 0 ) + map["targetValue"] = forward ? value_target : value_start; + if(loop_count != 0) { map["animator"] = Property::Map() - .Add( "alphaFunction", ease_str ) - .Add( "timePeriod", Property::Map() - .Add( "delay", value_repeat_delay.Get< float >() ) - .Add( "duration", value_duration.Get< float >() ) ); + .Add("alphaFunction", ease_str) + .Add("timePeriod", Property::Map().Add("delay", value_repeat_delay.Get()).Add("duration", value_duration.Get())); } } else { map["initialValue"] = *value; - map["targetValue"] = *value; + map["targetValue"] = *value; } - AnimatedGradientVisual::GradientAnimationData *animData = new AnimatedGradientVisual::GradientAnimationData(); - animData->transition = Toolkit::TransitionData::New( map ); - animData->index = index; - animData->loop_count = loop_count; - animData->delay = delay; - animData->forward = forward; - animData->auto_mirror = auto_mirror; - mGradientAnimationDataList.PushBack( animData ); + AnimatedGradientVisual::GradientAnimationData* animData = new AnimatedGradientVisual::GradientAnimationData(); + animData->transition = Toolkit::TransitionData::New(map); + animData->index = index; + animData->loop_count = loop_count; + animData->delay = delay; + animData->forward = forward; + animData->auto_mirror = auto_mirror; + mGradientAnimationDataList.PushBack(animData); } } void AnimatedGradientVisual::SetupAnimation() { - for( auto&& elem : mGradientAnimationDataList ) + for(auto&& elem : mGradientAnimationDataList) { - Toolkit::TransitionData& transition = elem->transition; - Animation& animation = elem->animation; - int loop_count = elem->loop_count; - bool auto_mirror = elem->auto_mirror; - bool without_animation = ( loop_count == 0 ); - - const Internal::TransitionData& transitionData = Toolkit::GetImplementation( transition ); - for( auto iter = transitionData.Begin(); iter != transitionData.End(); iter++ ) + Toolkit::TransitionData& transition = elem->transition; + Animation& animation = elem->animation; + int loop_count = elem->loop_count; + bool auto_mirror = elem->auto_mirror; + bool without_animation = (loop_count == 0); + + const Internal::TransitionData& transitionData = Toolkit::GetImplementation(transition); + for(auto iter = transitionData.Begin(); iter != transitionData.End(); iter++) { - TransitionData::Animator *animator = (*iter); - AnimateProperty( animation, *animator ); + TransitionData::Animator* animator = (*iter); + AnimateProperty(animation, *animator); } - if( animation && !without_animation ) + if(animation && !without_animation) { - if( loop_count < 0 ) + if(loop_count < 0) { - animation.SetLooping( true ); + animation.SetLooping(true); } - else if( loop_count > 0 ) + else if(loop_count > 0) { - animation.SetLoopCount( loop_count ); + animation.SetLoopCount(loop_count); } - if( auto_mirror ) + if(auto_mirror) { - animation.SetLoopingMode( Animation::LoopingMode::AUTO_REVERSE ); + animation.SetLoopingMode(Animation::LoopingMode::AUTO_REVERSE); } } } @@ -398,51 +390,51 @@ void AnimatedGradientVisual::SetupAnimation() void AnimatedGradientVisual::PlayAnimation() { - for( auto&& elem : mGradientAnimationDataList ) + for(auto&& elem : mGradientAnimationDataList) { Animation& animation = elem->animation; - if( animation ) + if(animation) { float delay = elem->delay; - if( delay > 0.0f ) + if(delay > 0.0f) { - animation.PlayAfter( delay ); + animation.PlayAfter(delay); } - else if( delay < 0.0f ) + else if(delay < 0.0f) { float progress = -delay / animation.GetDuration(); // (duration + repeat_duration) if(progress >= 1.0f) { - int cur_loop = animation.GetLoopCount(); - int decrease_loop = floor( progress ) + 1; - while( decrease_loop > progress ) + int cur_loop = animation.GetLoopCount(); + int decrease_loop = floor(progress) + 1; + while(decrease_loop > progress) { decrease_loop--; } progress -= decrease_loop; - if( cur_loop == 0 ) + if(cur_loop == 0) { - animation.PlayFrom( progress ); + animation.PlayFrom(progress); } else { cur_loop -= decrease_loop; - if( cur_loop > 0 ) + if(cur_loop > 0) { - animation.SetLoopCount( cur_loop ); - animation.PlayFrom( progress ); + animation.SetLoopCount(cur_loop); + animation.PlayFrom(progress); } else { // animation done. make this animation finished safely. - animation.SetLoopCount( 1 ); - animation.PlayFrom( 1.0f ); + animation.SetLoopCount(1); + animation.PlayFrom(1.0f); } } } else { - animation.PlayFrom( progress ); + animation.PlayFrom(progress); } } else @@ -455,10 +447,10 @@ void AnimatedGradientVisual::PlayAnimation() void AnimatedGradientVisual::StopAnimation() { - for( auto&& elem : mGradientAnimationDataList ) + for(auto&& elem : mGradientAnimationDataList) { Animation& animation = elem->animation; - if( animation ) + if(animation) { animation.Stop(); } @@ -467,135 +459,134 @@ void AnimatedGradientVisual::StopAnimation() void AnimatedGradientVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } -void AnimatedGradientVisual::DoSetOnScene( Actor& actor ) +void AnimatedGradientVisual::DoSetOnScene(Actor& actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); SetupAnimation(); PlayAnimation(); - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } -void AnimatedGradientVisual::DoSetOffScene( Actor& actor ) +void AnimatedGradientVisual::DoSetOffScene(Actor& actor) { - DALI_ASSERT_DEBUG( (bool)mImpl->mRenderer && "There should always be a renderer whilst on stage"); + DALI_ASSERT_DEBUG((bool)mImpl->mRenderer && "There should always be a renderer whilst on stage"); StopAnimation(); - actor.RemoveRenderer( mImpl->mRenderer ); + actor.RemoveRenderer(mImpl->mRenderer); } -void AnimatedGradientVisual::DoCreatePropertyMap( Property::Map& map ) const +void AnimatedGradientVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_GRADIENT ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_GRADIENT); //Create non-animated properties - map.Insert( Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, static_cast(mGradientType) ); - map.Insert( Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE , static_cast(mUnitType) ); - map.Insert( Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE , static_cast(mSpreadType) ); + map.Insert(Toolkit::DevelAnimatedGradientVisual::Property::GRADIENT_TYPE, static_cast(mGradientType)); + map.Insert(Toolkit::DevelAnimatedGradientVisual::Property::UNIT_TYPE, static_cast(mUnitType)); + map.Insert(Toolkit::DevelAnimatedGradientVisual::Property::SPREAD_TYPE, static_cast(mSpreadType)); //Create animated properties. Get from transition for more realistic test. Not from animation cause Animation may not setuped - for( auto&& elem : mGradientAnimationDataList ) + for(auto&& elem : mGradientAnimationDataList) { - Toolkit::TransitionData& transition = elem->transition; - Property::Index index = elem->index; - int loop_count = elem->loop_count; - float delay = elem->delay; - bool forward = elem->forward; - bool auto_mirror = elem->auto_mirror; - - const Internal::TransitionData& transitionData = Toolkit::GetImplementation( transition ); - for( auto iter = transitionData.Begin(); iter != transitionData.End(); iter++ ) + Toolkit::TransitionData& transition = elem->transition; + Property::Index index = elem->index; + int loop_count = elem->loop_count; + float delay = elem->delay; + bool forward = elem->forward; + bool auto_mirror = elem->auto_mirror; + + const Internal::TransitionData& transitionData = Toolkit::GetImplementation(transition); + for(auto iter = transitionData.Begin(); iter != transitionData.End(); iter++) { - TransitionData::Animator *animator = (*iter); - if( animator->animate ) + TransitionData::Animator* animator = (*iter); + if(animator->animate) { //with animation - Property::Map animation_map; - Property::Value value_start = forward ? animator->initialValue : animator->targetValue; + Property::Map animation_map; + Property::Value value_start = forward ? animator->initialValue : animator->targetValue; Property::Value value_target = forward ? animator->targetValue : animator->initialValue; Property::Value value_direction; - Property::Value value_duration = Property::Value( animator->timePeriodDuration ); - Property::Value value_delay = Property::Value( delay ); - Property::Value value_repeat = Property::Value( loop_count ); - Property::Value value_repeat_delay = Property::Value( animator->timePeriodDelay ); + Property::Value value_duration = Property::Value(animator->timePeriodDuration); + Property::Value value_delay = Property::Value(delay); + Property::Value value_repeat = Property::Value(loop_count); + Property::Value value_repeat_delay = Property::Value(animator->timePeriodDelay); Property::Value value_motion_type; Property::Value value_easing_type; - if( forward ) + if(forward) { - value_direction = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD ); + value_direction = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::FORWARD); } else { - value_direction = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::BACKWARD ); + value_direction = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::DirectionType::BACKWARD); } - if( auto_mirror ) + if(auto_mirror) { - value_motion_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR ); + value_motion_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::MIRROR); } else { - value_motion_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::LOOP ); + value_motion_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::MotionType::LOOP); } - switch( animator->alphaFunction.GetBuiltinFunction() ) + switch(animator->alphaFunction.GetBuiltinFunction()) { case Dali::AlphaFunction::LINEAR: { - value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR ); + value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR); break; } case Dali::AlphaFunction::EASE_IN_SQUARE: { - value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN ); + value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN); break; } case Dali::AlphaFunction::EASE_OUT_SQUARE: { - value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::OUT ); + value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::OUT); break; } case Dali::AlphaFunction::EASE_IN_OUT: { - value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN_OUT ); + value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::IN_OUT); break; } default: { - value_easing_type = Property::Value( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR ); + value_easing_type = Property::Value(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::EasingType::LINEAR); } } - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START , value_start ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET , value_target ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION , value_direction ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION , value_duration ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY , value_delay ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT , value_repeat ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, value_repeat_delay ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE , value_motion_type ); - animation_map.Insert( Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE , value_easing_type ); - - map.Insert( index, animation_map ); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::START, value_start); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::TARGET, value_target); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DIRECTION, value_direction); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DURATION, value_duration); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::DELAY, value_delay); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT, value_repeat); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::REPEAT_DELAY, value_repeat_delay); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::MOTION_TYPE, value_motion_type); + animation_map.Insert(Toolkit::DevelAnimatedGradientVisual::AnimationParameter::Property::EASING_TYPE, value_easing_type); + + map.Insert(index, animation_map); } else { //without animation - map.Insert( index, animator->targetValue ); + map.Insert(index, animator->targetValue); } } } } -void AnimatedGradientVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void AnimatedGradientVisual::DoCreateInstancePropertyMap(Property::Map& map) const { - } Shader AnimatedGradientVisual::CreateShader() @@ -605,7 +596,7 @@ Shader AnimatedGradientVisual::CreateShader() std::string tagUnit; std::string tagGrad; std::string tagSpread; - switch( mUnitType ) + switch(mUnitType) { case Toolkit::DevelAnimatedGradientVisual::UnitType::OBJECT_BOUNDING_BOX: { @@ -618,7 +609,7 @@ Shader AnimatedGradientVisual::CreateShader() break; } } - switch( mGradientType ) + switch(mGradientType) { case Toolkit::DevelAnimatedGradientVisual::GradientType::LINEAR: { @@ -631,7 +622,7 @@ Shader AnimatedGradientVisual::CreateShader() break; } } - switch( mSpreadType ) + switch(mSpreadType) { case Toolkit::DevelAnimatedGradientVisual::SpreadType::REFLECT: { @@ -653,43 +644,40 @@ Shader AnimatedGradientVisual::CreateShader() std::string vert; std::string frag; - vert = "#define " + tagUnit + "\n" - + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_VERT.data(); - frag = "#define " + tagGrad + "\n" - + "#define " + tagSpread + "\n" - + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_FRAG.data(); + vert = "#define " + tagUnit + "\n" + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_VERT.data(); + frag = "#define " + tagGrad + "\n" + "#define " + tagSpread + "\n" + SHADER_ANIMATED_GRADIENT_VISUAL_SHADER_FRAG.data(); - shader = Shader::New( vert, frag ); + shader = Shader::New(vert, frag); return shader; } void AnimatedGradientVisual::OnInitialize() { - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); - VisualFactoryCache::ShaderType shaderType = GetShaderType( mGradientType, mUnitType, mSpreadType ); - Shader shader = mFactoryCache.GetShader( shaderType ); - if( !shader ) + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); + VisualFactoryCache::ShaderType shaderType = GetShaderType(mGradientType, mUnitType, mSpreadType); + Shader shader = mFactoryCache.GetShader(shaderType); + if(!shader) { shader = CreateShader(); - mFactoryCache.SaveShader( shaderType, shader ); + mFactoryCache.SaveShader(shaderType, shader); } - mImpl->mRenderer = Renderer::New( geometry, shader ); + mImpl->mRenderer = Renderer::New(geometry, shader); - mImpl->mRenderer.RegisterProperty( UNIFORM_START_POINT_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION, START_POSITION_NAME ) ); - mImpl->mRenderer.RegisterProperty( UNIFORM_START_COLOR_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR , START_COLOR_NAME ) ); - mImpl->mRenderer.RegisterProperty( UNIFORM_END_POINT_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION , END_POSITION_NAME ) ); - mImpl->mRenderer.RegisterProperty( UNIFORM_END_COLOR_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR , END_COLOR_NAME ) ); - mImpl->mRenderer.RegisterProperty( UNIFORM_ROTATE_CENTER_NAME, GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER , ROTATE_CENTER_NAME ) ); - mImpl->mRenderer.RegisterProperty( UNIFORM_ROTATE_ANGLE_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT , ROTATE_AMOUNT_NAME ) ); - mImpl->mRenderer.RegisterProperty( UNIFORM_OFFSET_NAME , GetStartValue( mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::OFFSET , OFFSET_NAME ) ); + mImpl->mRenderer.RegisterProperty(UNIFORM_START_POINT_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_POSITION, START_POSITION_NAME)); + mImpl->mRenderer.RegisterProperty(UNIFORM_START_COLOR_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::START_COLOR, START_COLOR_NAME)); + mImpl->mRenderer.RegisterProperty(UNIFORM_END_POINT_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_POSITION, END_POSITION_NAME)); + mImpl->mRenderer.RegisterProperty(UNIFORM_END_COLOR_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::END_COLOR, END_COLOR_NAME)); + mImpl->mRenderer.RegisterProperty(UNIFORM_ROTATE_CENTER_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_CENTER, ROTATE_CENTER_NAME)); + mImpl->mRenderer.RegisterProperty(UNIFORM_ROTATE_ANGLE_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::ROTATE_AMOUNT, ROTATE_AMOUNT_NAME)); + mImpl->mRenderer.RegisterProperty(UNIFORM_OFFSET_NAME, GetStartValue(mValueMap, Toolkit::DevelAnimatedGradientVisual::Property::OFFSET, OFFSET_NAME)); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } -}//namespace Internal +} //namespace Internal -}//namespace Toolkit +} //namespace Toolkit -}//namespace Dali +} //namespace Dali diff --git a/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp b/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp old mode 100755 new mode 100644 index db1be08..9952c55 --- a/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp +++ b/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp @@ -24,54 +24,50 @@ #include // INTERNAL INCLUDES -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { // stop behavior -DALI_ENUM_TO_STRING_TABLE_BEGIN( STOP_BEHAVIOR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME ) -DALI_ENUM_TO_STRING_TABLE_END( STOP_BEHAVIOR ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(STOP_BEHAVIOR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME) +DALI_ENUM_TO_STRING_TABLE_END(STOP_BEHAVIOR) // wrap modes -DALI_ENUM_TO_STRING_TABLE_BEGIN( WRAP_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, DEFAULT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, CLAMP_TO_EDGE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, REPEAT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, MIRRORED_REPEAT ) -DALI_ENUM_TO_STRING_TABLE_END( WRAP_MODE ) - -const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); +DALI_ENUM_TO_STRING_TABLE_BEGIN(WRAP_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, DEFAULT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, CLAMP_TO_EDGE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, REPEAT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, MIRRORED_REPEAT) +DALI_ENUM_TO_STRING_TABLE_END(WRAP_MODE) + +const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); constexpr auto LOOP_FOREVER = -1; #if defined(DEBUG_ENABLED) Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE"); #endif -} - +} // namespace /** * Multi-image Flow of execution @@ -108,13 +104,13 @@ Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, " * Time */ -AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties ) +AnimatedImageVisualPtr AnimatedImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties) { - AnimatedImageVisualPtr visual( new AnimatedImageVisual( factoryCache, shaderFactory ) ); - visual->InitializeAnimatedImage( imageUrl ); - visual->SetProperties( properties ); + AnimatedImageVisualPtr visual(new AnimatedImageVisual(factoryCache, shaderFactory)); + visual->InitializeAnimatedImage(imageUrl); + visual->SetProperties(properties); - if( visual->mFrameCount > 0 ) + if(visual->mFrameCount > 0) { visual->LoadFirstBatch(); } @@ -124,23 +120,23 @@ AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCach return visual; } -AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Property::Array& imageUrls, const Property::Map& properties ) +AnimatedImageVisualPtr AnimatedImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Property::Array& imageUrls, const Property::Map& properties) { - AnimatedImageVisualPtr visual( new AnimatedImageVisual( factoryCache, shaderFactory ) ); + AnimatedImageVisualPtr visual(new AnimatedImageVisual(factoryCache, shaderFactory)); visual->mImageUrls = new ImageCache::UrlList(); - visual->mImageUrls->reserve( imageUrls.Count() ); + visual->mImageUrls->reserve(imageUrls.Count()); - for( unsigned int i=0; i < imageUrls.Count(); ++i) + for(unsigned int i = 0; i < imageUrls.Count(); ++i) { ImageCache::UrlStore urlStore; urlStore.mTextureId = TextureManager::INVALID_TEXTURE_ID; - urlStore.mUrl = imageUrls[i].Get(); - visual->mImageUrls->push_back( urlStore ); + urlStore.mUrl = imageUrls[i].Get(); + visual->mImageUrls->push_back(urlStore); } visual->mFrameCount = imageUrls.Count(); - visual->SetProperties( properties ); + visual->SetProperties(properties); - if( visual->mFrameCount > 0 ) + if(visual->mFrameCount > 0) { visual->LoadFirstBatch(); } @@ -150,12 +146,12 @@ AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCach return visual; } -AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl ) +AnimatedImageVisualPtr AnimatedImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl) { - AnimatedImageVisualPtr visual( new AnimatedImageVisual( factoryCache, shaderFactory ) ); - visual->InitializeAnimatedImage( imageUrl ); + AnimatedImageVisualPtr visual(new AnimatedImageVisual(factoryCache, shaderFactory)); + visual->InitializeAnimatedImage(imageUrl); - if( visual->mFrameCount > 0 ) + if(visual->mFrameCount > 0) { visual->LoadFirstBatch(); } @@ -165,39 +161,40 @@ AnimatedImageVisualPtr AnimatedImageVisual::New( VisualFactoryCache& factoryCach return visual; } -void AnimatedImageVisual::InitializeAnimatedImage( const VisualUrl& imageUrl ) +void AnimatedImageVisual::InitializeAnimatedImage(const VisualUrl& imageUrl) { - mImageUrl = imageUrl; - mAnimatedImageLoading = AnimatedImageLoading::New( imageUrl.GetUrl(), imageUrl.IsLocalResource() ); - mFrameCount = mAnimatedImageLoading.GetImageCount(); + mImageUrl = imageUrl; + mAnimatedImageLoading = AnimatedImageLoading::New(imageUrl.GetUrl(), imageUrl.IsLocalResource()); + mFrameCount = mAnimatedImageLoading.GetImageCount(); } -AnimatedImageVisual::AnimatedImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory ) -: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::ANIMATED_IMAGE ), +AnimatedImageVisual::AnimatedImageVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory) +: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::ANIMATED_IMAGE), mFrameDelayTimer(), mPlacementActor(), - mImageVisualShaderFactory( shaderFactory ), - mPixelArea( FULL_TEXTURE_RECT ), + mImageVisualShaderFactory(shaderFactory), + mPixelArea(FULL_TEXTURE_RECT), mImageUrl(), mAnimatedImageLoading(), - mFrameIndexForJumpTo( 0 ), - mImageUrls( NULL ), - mImageCache( NULL ), - mCacheSize( 2 ), - mBatchSize( 2 ), - mFrameDelay( 100 ), - mLoopCount( LOOP_FOREVER ), - mCurrentLoopIndex( 0 ), - mUrlIndex( 0 ), - mFrameCount( 0 ), + mFrameIndexForJumpTo(0), + mImageUrls(NULL), + mImageCache(NULL), + mCacheSize(2), + mBatchSize(2), + mFrameDelay(100), + mLoopCount(LOOP_FOREVER), + mCurrentLoopIndex(0), + mUrlIndex(0), + mFrameCount(0), mImageSize(), - mWrapModeU( WrapMode::DEFAULT ), - mWrapModeV( WrapMode::DEFAULT ), - mActionStatus( DevelAnimatedImageVisual::Action::PLAY ), - mStopBehavior( DevelImageVisual::StopBehavior::CURRENT_FRAME ), + mWrapModeU(WrapMode::DEFAULT), + mWrapModeV(WrapMode::DEFAULT), + mActionStatus(DevelAnimatedImageVisual::Action::PLAY), + mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME), mStartFirstFrame(false), - mIsJumpTo( false ) -{} + mIsJumpTo(false) +{ +} AnimatedImageVisual::~AnimatedImageVisual() { @@ -205,72 +202,72 @@ AnimatedImageVisual::~AnimatedImageVisual() delete mImageUrls; } -void AnimatedImageVisual::GetNaturalSize( Vector2& naturalSize ) +void AnimatedImageVisual::GetNaturalSize(Vector2& naturalSize) { - if( mImageSize.GetWidth() == 0 && mImageSize.GetHeight() == 0) + if(mImageSize.GetWidth() == 0 && mImageSize.GetHeight() == 0) { - if( mImageUrl.IsValid() ) + if(mImageUrl.IsValid()) { mImageSize = mAnimatedImageLoading.GetImageSize(); } - else if( mImageUrls && mImageUrls->size() > 0 ) + else if(mImageUrls && mImageUrls->size() > 0) { - mImageSize = Dali::GetClosestImageSize( (*mImageUrls)[0].mUrl ); + mImageSize = Dali::GetClosestImageSize((*mImageUrls)[0].mUrl); } } - naturalSize.width = mImageSize.GetWidth(); + naturalSize.width = mImageSize.GetWidth(); naturalSize.height = mImageSize.GetHeight(); } -void AnimatedImageVisual::DoCreatePropertyMap( Property::Map& map ) const +void AnimatedImageVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); bool sync = IsSynchronousLoadingRequired(); - map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync ); + map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::ANIMATED_IMAGE ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::ANIMATED_IMAGE); - if( mImageUrl.IsValid() ) + if(mImageUrl.IsValid()) { - map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() ); + map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl()); } - if( mImageUrls != NULL && ! mImageUrls->empty() ) + if(mImageUrls != NULL && !mImageUrls->empty()) { Property::Array urls; - for( unsigned int i=0; isize(); ++i) + for(unsigned int i = 0; i < mImageUrls->size(); ++i) { - urls.Add( (*mImageUrls)[i].mUrl ); + urls.Add((*mImageUrls)[i].mUrl); } - Property::Value value( const_cast(urls) ); - map.Insert( Toolkit::ImageVisual::Property::URL, value ); + Property::Value value(const_cast(urls)); + map.Insert(Toolkit::ImageVisual::Property::URL, value); } - map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea ); - map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU ); - map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV ); + map.Insert(Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea); + map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU); + map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV); - map.Insert( Toolkit::ImageVisual::Property::BATCH_SIZE, static_cast(mBatchSize) ); - map.Insert( Toolkit::ImageVisual::Property::CACHE_SIZE, static_cast(mCacheSize) ); - map.Insert( Toolkit::ImageVisual::Property::FRAME_DELAY, static_cast(mFrameDelay) ); - map.Insert( Toolkit::DevelImageVisual::Property::LOOP_COUNT, static_cast(mLoopCount) ); - map.Insert( Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, (mImageCache) ? static_cast(mImageCache->GetCurrentFrameIndex()) : -1 ); - map.Insert( Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, (mImageCache) ? static_cast(mImageCache->GetTotalFrameCount()) : -1 ); + map.Insert(Toolkit::ImageVisual::Property::BATCH_SIZE, static_cast(mBatchSize)); + map.Insert(Toolkit::ImageVisual::Property::CACHE_SIZE, static_cast(mCacheSize)); + map.Insert(Toolkit::ImageVisual::Property::FRAME_DELAY, static_cast(mFrameDelay)); + map.Insert(Toolkit::DevelImageVisual::Property::LOOP_COUNT, static_cast(mLoopCount)); + map.Insert(Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, (mImageCache) ? static_cast(mImageCache->GetCurrentFrameIndex()) : -1); + map.Insert(Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, (mImageCache) ? static_cast(mImageCache->GetTotalFrameCount()) : -1); - map.Insert( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mStopBehavior ); + map.Insert(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mStopBehavior); } -void AnimatedImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void AnimatedImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } -void AnimatedImageVisual::OnDoAction( const Dali::Property::Index actionId, const Dali::Property::Value& attributes ) +void AnimatedImageVisual::OnDoAction(const Dali::Property::Index actionId, const Dali::Property::Value& attributes) { // Check if action is valid for this visual type and perform action if possible - switch ( actionId ) + switch(actionId) { case DevelAnimatedImageVisual::Action::PAUSE: { @@ -280,7 +277,7 @@ void AnimatedImageVisual::OnDoAction( const Dali::Property::Index actionId, cons } case DevelAnimatedImageVisual::Action::PLAY: { - if( mFrameDelayTimer && IsOnScene() && mActionStatus != DevelAnimatedImageVisual::Action::PLAY ) + if(mFrameDelayTimer && IsOnScene() && mActionStatus != DevelAnimatedImageVisual::Action::PLAY) { mFrameDelayTimer.Start(); } @@ -292,7 +289,7 @@ void AnimatedImageVisual::OnDoAction( const Dali::Property::Index actionId, cons // STOP reset functionality will actually be done in a future change // Stop will be executed on next timer tick mActionStatus = DevelAnimatedImageVisual::Action::STOP; - if( IsOnScene() ) + if(IsOnScene()) { DisplayNextFrame(); } @@ -301,17 +298,17 @@ void AnimatedImageVisual::OnDoAction( const Dali::Property::Index actionId, cons case DevelAnimatedImageVisual::Action::JUMP_TO: { int32_t frameNumber; - if( attributes.Get( frameNumber ) ) + if(attributes.Get(frameNumber)) { - if( frameNumber < 0 || frameNumber >= static_cast( mFrameCount ) ) + if(frameNumber < 0 || frameNumber >= static_cast(mFrameCount)) { - DALI_LOG_ERROR( "Invalid frame index used.\n" ); + DALI_LOG_ERROR("Invalid frame index used.\n"); } else { - mIsJumpTo = true; + mIsJumpTo = true; mFrameIndexForJumpTo = frameNumber; - if( IsOnScene() ) + if(IsOnScene()) { DisplayNextFrame(); } @@ -322,69 +319,69 @@ void AnimatedImageVisual::OnDoAction( const Dali::Property::Index actionId, cons } } -void AnimatedImageVisual::DoSetProperties( const Property::Map& propertyMap ) +void AnimatedImageVisual::DoSetProperties(const Property::Map& propertyMap) { // url[s] already passed in from constructor - for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter ) + for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter) { - KeyValuePair keyValue = propertyMap.GetKeyValue( iter ); - if( keyValue.first.type == Property::Key::INDEX ) + KeyValuePair keyValue = propertyMap.GetKeyValue(iter); + if(keyValue.first.type == Property::Key::INDEX) { - DoSetProperty( keyValue.first.indexKey, keyValue.second ); + DoSetProperty(keyValue.first.indexKey, keyValue.second); } else { - if( keyValue.first == PIXEL_AREA_UNIFORM_NAME ) + if(keyValue.first == PIXEL_AREA_UNIFORM_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second); } - else if( keyValue.first == IMAGE_WRAP_MODE_U ) + else if(keyValue.first == IMAGE_WRAP_MODE_U) { - DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second); } - else if( keyValue.first == IMAGE_WRAP_MODE_V ) + else if(keyValue.first == IMAGE_WRAP_MODE_V) { - DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second); } - else if( keyValue.first == BATCH_SIZE_NAME ) + else if(keyValue.first == BATCH_SIZE_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::BATCH_SIZE, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::BATCH_SIZE, keyValue.second); } - else if( keyValue.first == CACHE_SIZE_NAME ) + else if(keyValue.first == CACHE_SIZE_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::CACHE_SIZE, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::CACHE_SIZE, keyValue.second); } - else if( keyValue.first == FRAME_DELAY_NAME ) + else if(keyValue.first == FRAME_DELAY_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::FRAME_DELAY, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::FRAME_DELAY, keyValue.second); } - else if( keyValue.first == LOOP_COUNT_NAME ) + else if(keyValue.first == LOOP_COUNT_NAME) { - DoSetProperty( Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second ); + DoSetProperty(Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second); } - else if( keyValue.first == STOP_BEHAVIOR_NAME ) + else if(keyValue.first == STOP_BEHAVIOR_NAME) { - DoSetProperty( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second ); + DoSetProperty(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second); } } } } -void AnimatedImageVisual::DoSetProperty( Property::Index index, - const Property::Value& value ) +void AnimatedImageVisual::DoSetProperty(Property::Index index, + const Property::Value& value) { switch(index) { case Toolkit::ImageVisual::Property::PIXEL_AREA: { - value.Get( mPixelArea ); + value.Get(mPixelArea); break; } case Toolkit::ImageVisual::Property::WRAP_MODE_U: { int wrapMode = 0; - if(Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode )) + if(Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode)) { mWrapModeU = Dali::WrapMode::Type(wrapMode); } @@ -397,7 +394,7 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::ImageVisual::Property::WRAP_MODE_V: { int wrapMode = 0; - if(Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode )) + if(Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode)) { mWrapModeV = Dali::WrapMode::Type(wrapMode); } @@ -411,11 +408,11 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::ImageVisual::Property::BATCH_SIZE: { int batchSize; - if( value.Get( batchSize ) ) + if(value.Get(batchSize)) { - if( batchSize < 2 ) + if(batchSize < 2) { - DALI_LOG_ERROR( "The minimum value of batch size is 2." ); + DALI_LOG_ERROR("The minimum value of batch size is 2."); } else { @@ -428,11 +425,11 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::ImageVisual::Property::CACHE_SIZE: { int cacheSize; - if( value.Get( cacheSize ) ) + if(value.Get(cacheSize)) { - if( cacheSize < 2 ) + if(cacheSize < 2) { - DALI_LOG_ERROR( "The minimum value of cache size is 2." ); + DALI_LOG_ERROR("The minimum value of cache size is 2."); } else { @@ -445,7 +442,7 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::ImageVisual::Property::FRAME_DELAY: { int frameDelay; - if( value.Get( frameDelay ) ) + if(value.Get(frameDelay)) { mFrameDelay = frameDelay; } @@ -455,7 +452,7 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::DevelImageVisual::Property::LOOP_COUNT: { int loopCount; - if( value.Get( loopCount ) ) + if(value.Get(loopCount)) { mLoopCount = loopCount; } @@ -465,9 +462,9 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR: { int32_t stopBehavior = mStopBehavior; - if( Scripting::GetEnumerationProperty( value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior ) ) + if(Scripting::GetEnumerationProperty(value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior)) { - mStopBehavior = DevelImageVisual::StopBehavior::Type( stopBehavior ); + mStopBehavior = DevelImageVisual::StopBehavior::Type(stopBehavior); } break; } @@ -475,8 +472,8 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING: { bool sync = false; - value.Get( sync ); - if( sync ) + value.Get(sync); + if(sync) { mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING; } @@ -489,14 +486,14 @@ void AnimatedImageVisual::DoSetProperty( Property::Index index, } } -void AnimatedImageVisual::DoSetOnScene( Actor& actor ) +void AnimatedImageVisual::DoSetOnScene(Actor& actor) { - mPlacementActor = actor; + mPlacementActor = actor; TextureSet textureSet = PrepareTextureSet(); - if( textureSet ) // if the image loading is successful + if(textureSet) // if the image loading is successful { - StartFirstFrame( textureSet ); + StartFirstFrame(textureSet); } else { @@ -504,52 +501,52 @@ void AnimatedImageVisual::DoSetOnScene( Actor& actor ) } } -void AnimatedImageVisual::DoSetOffScene( Actor& actor ) +void AnimatedImageVisual::DoSetOffScene(Actor& actor) { - DALI_ASSERT_DEBUG( (bool)mImpl->mRenderer && "There should always be a renderer whilst on stage"); + DALI_ASSERT_DEBUG((bool)mImpl->mRenderer && "There should always be a renderer whilst on stage"); - if( mFrameDelayTimer ) + if(mFrameDelayTimer) { mFrameDelayTimer.Stop(); mFrameDelayTimer.Reset(); } - actor.RemoveRenderer( mImpl->mRenderer ); + actor.RemoveRenderer(mImpl->mRenderer); mPlacementActor.Reset(); mStartFirstFrame = false; } void AnimatedImageVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } void AnimatedImageVisual::OnInitialize() { - bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE; - bool atlasing = false; - Shader shader = mImageVisualShaderFactory.GetShader( mFactoryCache, atlasing, defaultWrapMode, IsRoundedCornerRequired() ); + bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE; + bool atlasing = false; + Shader shader = mImageVisualShaderFactory.GetShader(mFactoryCache, atlasing, defaultWrapMode, IsRoundedCornerRequired()); - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); - mImpl->mRenderer = Renderer::New( geometry, shader ); + mImpl->mRenderer = Renderer::New(geometry, shader); // Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); - if( !defaultWrapMode ) // custom wrap mode + if(!defaultWrapMode) // custom wrap mode { - Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE); - wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) ); - mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode ); + Vector2 wrapMode(mWrapModeU - WrapMode::CLAMP_TO_EDGE, mWrapModeV - WrapMode::CLAMP_TO_EDGE); + wrapMode.Clamp(Vector2::ZERO, Vector2(2.f, 2.f)); + mImpl->mRenderer.RegisterProperty(WRAP_MODE_UNIFORM_NAME, wrapMode); } - if( mPixelArea != FULL_TEXTURE_RECT ) + if(mPixelArea != FULL_TEXTURE_RECT) { - mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea ); + mImpl->mRenderer.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, mPixelArea); } } @@ -557,11 +554,11 @@ void AnimatedImageVisual::LoadFirstBatch() { // Ensure the batch size and cache size are no bigger than the number of URLs, // and that the cache is at least as big as the batch size. - uint16_t numUrls = 0; + uint16_t numUrls = 0; uint16_t batchSize = 1; uint16_t cacheSize = 1; - if( mImageUrls ) + if(mImageUrls) { numUrls = mImageUrls->size(); } @@ -570,105 +567,105 @@ void AnimatedImageVisual::LoadFirstBatch() numUrls = mFrameCount; } - batchSize = std::min( mBatchSize, numUrls ); - cacheSize = std::min( std::max( batchSize, mCacheSize ), numUrls ); + batchSize = std::min(mBatchSize, numUrls); + cacheSize = std::min(std::max(batchSize, mCacheSize), numUrls); - DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::LoadFirstBatch() batchSize:%d cacheSize:%d\n", batchSize, cacheSize); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::LoadFirstBatch() batchSize:%d cacheSize:%d\n", batchSize, cacheSize); - mUrlIndex = 0; + mUrlIndex = 0; TextureManager& textureManager = mFactoryCache.GetTextureManager(); - if( mAnimatedImageLoading ) + if(mAnimatedImageLoading) { - mImageCache = new RollingAnimatedImageCache( textureManager, mAnimatedImageLoading, mFrameCount, *this, cacheSize, batchSize, IsSynchronousLoadingRequired() ); + mImageCache = new RollingAnimatedImageCache(textureManager, mAnimatedImageLoading, mFrameCount, *this, cacheSize, batchSize, IsSynchronousLoadingRequired()); } - else if( mImageUrls ) + else if(mImageUrls) { - if( batchSize > 0 && cacheSize > 0 ) + if(batchSize > 0 && cacheSize > 0) { - if( cacheSize < numUrls ) + if(cacheSize < numUrls) { - mImageCache = new RollingImageCache( textureManager, *mImageUrls, *this, cacheSize, batchSize ); + mImageCache = new RollingImageCache(textureManager, *mImageUrls, *this, cacheSize, batchSize); } else { - mImageCache = new FixedImageCache( textureManager, *mImageUrls, *this, batchSize ); + mImageCache = new FixedImageCache(textureManager, *mImageUrls, *this, batchSize); } } else { - mImageCache = new RollingImageCache( textureManager, *mImageUrls, *this, 1, 1 ); + mImageCache = new RollingImageCache(textureManager, *mImageUrls, *this, 1, 1); } } - if (!mImageCache) + if(!mImageCache) { DALI_LOG_ERROR("mImageCache is null\n"); } } -void AnimatedImageVisual::StartFirstFrame( TextureSet& textureSet ) +void AnimatedImageVisual::StartFirstFrame(TextureSet& textureSet) { - DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::StartFirstFrame()\n"); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::StartFirstFrame()\n"); mStartFirstFrame = false; if(mImpl->mRenderer) { - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); mPlacementActor.Reset(); } } - if( mFrameCount > 1 ) + if(mFrameCount > 1) { - int frameDelay = mImageCache->GetFrameInterval( 0 ); - if( frameDelay == 0u ) + int frameDelay = mImageCache->GetFrameInterval(0); + if(frameDelay == 0u) { frameDelay = mFrameDelay; // from URL array } - mFrameDelayTimer = Timer::New( frameDelay ); - mFrameDelayTimer.TickSignal().Connect( this, &AnimatedImageVisual::DisplayNextFrame ); + mFrameDelayTimer = Timer::New(frameDelay); + mFrameDelayTimer.TickSignal().Connect(this, &AnimatedImageVisual::DisplayNextFrame); mFrameDelayTimer.Start(); } - DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"ResourceReady(ResourceStatus::READY)\n"); - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "ResourceReady(ResourceStatus::READY)\n"); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } TextureSet AnimatedImageVisual::PrepareTextureSet() { TextureSet textureSet; - if (mImageCache) + if(mImageCache) { textureSet = mImageCache->FirstFrame(); } - if( textureSet ) + if(textureSet) { - SetImageSize( textureSet ); + SetImageSize(textureSet); } return textureSet; } -void AnimatedImageVisual::SetImageSize( TextureSet& textureSet ) +void AnimatedImageVisual::SetImageSize(TextureSet& textureSet) { - if( textureSet ) + if(textureSet) { - Texture texture = textureSet.GetTexture( 0 ); - if( texture ) + Texture texture = textureSet.GetTexture(0); + if(texture) { - mImageSize.SetWidth( texture.GetWidth() ); - mImageSize.SetHeight( texture.GetHeight() ); + mImageSize.SetWidth(texture.GetWidth()); + mImageSize.SetHeight(texture.GetHeight()); } } } -void AnimatedImageVisual::FrameReady( TextureSet textureSet ) +void AnimatedImageVisual::FrameReady(TextureSet textureSet) { if(textureSet) { @@ -688,8 +685,8 @@ void AnimatedImageVisual::FrameReady( TextureSet textureSet ) } else { - DALI_LOG_INFO( gAnimImgLogFilter, Debug::Concise, "ResourceReady(ResourceStatus::FAILED)\n" ); - ResourceReady( Toolkit::Visual::ResourceStatus::FAILED ); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "ResourceReady(ResourceStatus::FAILED)\n"); + ResourceReady(Toolkit::Visual::ResourceStatus::FAILED); } } @@ -699,26 +696,26 @@ bool AnimatedImageVisual::DisplayNextFrame() if(mImageCache) { - bool nextFrame = false; + bool nextFrame = false; uint32_t frameIndex = mImageCache->GetCurrentFrameIndex(); - if( mIsJumpTo ) + if(mIsJumpTo) { - mIsJumpTo = false; + mIsJumpTo = false; frameIndex = mFrameIndexForJumpTo; } - else if( mActionStatus == DevelAnimatedImageVisual::Action::PAUSE ) + else if(mActionStatus == DevelAnimatedImageVisual::Action::PAUSE) { return false; } - else if( mActionStatus == DevelAnimatedImageVisual::Action::STOP ) + else if(mActionStatus == DevelAnimatedImageVisual::Action::STOP) { frameIndex = 0; - if( mStopBehavior == DevelImageVisual::StopBehavior::FIRST_FRAME ) + if(mStopBehavior == DevelImageVisual::StopBehavior::FIRST_FRAME) { frameIndex = 0; } - else if( mStopBehavior == DevelImageVisual::StopBehavior::LAST_FRAME ) + else if(mStopBehavior == DevelImageVisual::StopBehavior::LAST_FRAME) { frameIndex = mFrameCount - 1; } @@ -729,11 +726,11 @@ bool AnimatedImageVisual::DisplayNextFrame() } else { - if( mFrameCount > 1 ) + if(mFrameCount > 1) { nextFrame = true; frameIndex++; - if( frameIndex >= mFrameCount ) + if(frameIndex >= mFrameCount) { frameIndex %= mFrameCount; ++mCurrentLoopIndex; @@ -747,17 +744,17 @@ bool AnimatedImageVisual::DisplayNextFrame() } } - unsigned int delay = mImageCache->GetFrameInterval( frameIndex ); - if( delay > 0u ) + unsigned int delay = mImageCache->GetFrameInterval(frameIndex); + if(delay > 0u) { - if( mFrameDelayTimer.GetInterval() != delay ) + if(mFrameDelayTimer.GetInterval() != delay) { - mFrameDelayTimer.SetInterval( delay ); + mFrameDelayTimer.SetInterval(delay); } } } - DALI_LOG_INFO( gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::DisplayNextFrame(this:%p) CurrentFrameIndex:%d\n", this, frameIndex); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::DisplayNextFrame(this:%p) CurrentFrameIndex:%d\n", this, frameIndex); TextureSet textureSet; if(nextFrame) @@ -766,25 +763,24 @@ bool AnimatedImageVisual::DisplayNextFrame() } else { - textureSet = mImageCache->Frame( frameIndex ); + textureSet = mImageCache->Frame(frameIndex); } - if( textureSet ) + if(textureSet) { - SetImageSize( textureSet ); - if( mImpl->mRenderer ) + SetImageSize(textureSet); + if(mImpl->mRenderer) { - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); } } - continueTimer = ( mActionStatus == DevelAnimatedImageVisual::Action::PLAY ) ? true : false; + continueTimer = (mActionStatus == DevelAnimatedImageVisual::Action::PLAY) ? true : false; } return continueTimer; } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/visuals/animated-image/fixed-image-cache.cpp b/dali-toolkit/internal/visuals/animated-image/fixed-image-cache.cpp index 1eea6e6..4593bc7 100644 --- a/dali-toolkit/internal/visuals/animated-image/fixed-image-cache.cpp +++ b/dali-toolkit/internal/visuals/animated-image/fixed-image-cache.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,40 +26,38 @@ namespace Toolkit { namespace Internal { - namespace { -const bool ENABLE_ORIENTATION_CORRECTION( true ); +const bool ENABLE_ORIENTATION_CORRECTION(true); } // namespace FixedImageCache::FixedImageCache( - TextureManager& textureManager, UrlList& urlList, ImageCache::FrameReadyObserver& observer, - unsigned int batchSize ) -: ImageCache( textureManager, observer, batchSize ), - mImageUrls( urlList ), + TextureManager& textureManager, UrlList& urlList, ImageCache::FrameReadyObserver& observer, unsigned int batchSize) +: ImageCache(textureManager, observer, batchSize), + mImageUrls(urlList), mFront(0u) { - mReadyFlags.reserve( mImageUrls.size() ); + mReadyFlags.reserve(mImageUrls.size()); LoadBatch(); } FixedImageCache::~FixedImageCache() { - if( mTextureManagerAlive ) + if(mTextureManagerAlive) { - for( std::size_t i = 0; i < mImageUrls.size() ; ++i ) + for(std::size_t i = 0; i < mImageUrls.size(); ++i) { - mTextureManager.Remove( mImageUrls[i].mTextureId, this ); + mTextureManager.Remove(mImageUrls[i].mTextureId, this); } } } -TextureSet FixedImageCache::Frame( uint32_t frameIndex ) +TextureSet FixedImageCache::Frame(uint32_t frameIndex) { - while( frameIndex > mFront ) + while(frameIndex > mFront) { ++mFront; - if( mFront >= mImageUrls.size() ) + if(mFront >= mImageUrls.size()) { mFront = 0; } @@ -69,7 +67,7 @@ TextureSet FixedImageCache::Frame( uint32_t frameIndex ) mFront = frameIndex; TextureSet textureSet; - if( IsFrontReady() == true ) + if(IsFrontReady() == true) { textureSet = GetFrontTextureSet(); } @@ -85,7 +83,7 @@ TextureSet FixedImageCache::FirstFrame() { TextureSet textureSet = GetFrontTextureSet(); - if( ! textureSet ) + if(!textureSet) { mWaitingForReadyFrame = true; } @@ -100,7 +98,7 @@ TextureSet FixedImageCache::NextFrame() return textureSet; } -uint32_t FixedImageCache::GetFrameInterval( uint32_t frameIndex ) const +uint32_t FixedImageCache::GetFrameInterval(uint32_t frameIndex) const { return 0u; } @@ -117,7 +115,7 @@ int32_t FixedImageCache::GetTotalFrameCount() const bool FixedImageCache::IsFrontReady() const { - return ( mReadyFlags.size() > 0 && mReadyFlags[mFront] == true ); + return (mReadyFlags.size() > 0 && mReadyFlags[mFront] == true); } void FixedImageCache::LoadBatch() @@ -127,9 +125,9 @@ void FixedImageCache::LoadBatch() // no more images are loaded. bool frontFrameReady = IsFrontReady(); - for( unsigned int i=0; i< mBatchSize && mUrlIndex < mImageUrls.size(); ++i ) + for(unsigned int i = 0; i < mBatchSize && mUrlIndex < mImageUrls.size(); ++i) { - std::string& url = mImageUrls[ mUrlIndex ].mUrl; + std::string& url = mImageUrls[mUrlIndex].mUrl; mReadyFlags.push_back(false); @@ -138,41 +136,35 @@ void FixedImageCache::LoadBatch() // need to account for this inside the UploadComplete method using mRequestingLoad. mRequestingLoad = true; - bool synchronousLoading = false; - bool atlasingStatus = false; - bool loadingStatus = false; - TextureManager::MaskingDataPointer maskInfo = nullptr; - AtlasUploadObserver* atlasObserver = nullptr; - ImageAtlasManagerPtr imageAtlasManager = nullptr; - Vector4 textureRect; - Dali::ImageDimensions textureRectSize; - auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; + bool synchronousLoading = false; + bool atlasingStatus = false; + bool loadingStatus = false; + TextureManager::MaskingDataPointer maskInfo = nullptr; + AtlasUploadObserver* atlasObserver = nullptr; + ImageAtlasManagerPtr imageAtlasManager = nullptr; + Vector4 textureRect; + Dali::ImageDimensions textureRectSize; + auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; mTextureManager.LoadTexture( - url, ImageDimensions(), FittingMode::SCALE_TO_FILL, - SamplingMode::BOX_THEN_LINEAR, maskInfo, - synchronousLoading, mImageUrls[ mUrlIndex ].mTextureId, textureRect, textureRectSize, - atlasingStatus, loadingStatus, Dali::WrapMode::Type::DEFAULT, - Dali::WrapMode::Type::DEFAULT, this, - atlasObserver, imageAtlasManager, ENABLE_ORIENTATION_CORRECTION, TextureManager::ReloadPolicy::CACHED, - preMultiply ); - - if( loadingStatus == false ) // not loading, means it's already ready. + url, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, maskInfo, synchronousLoading, mImageUrls[mUrlIndex].mTextureId, textureRect, textureRectSize, atlasingStatus, loadingStatus, Dali::WrapMode::Type::DEFAULT, Dali::WrapMode::Type::DEFAULT, this, atlasObserver, imageAtlasManager, ENABLE_ORIENTATION_CORRECTION, TextureManager::ReloadPolicy::CACHED, preMultiply); + + if(loadingStatus == false) // not loading, means it's already ready. { - SetImageFrameReady( mImageUrls[ mUrlIndex ].mTextureId ); + SetImageFrameReady(mImageUrls[mUrlIndex].mTextureId); } mRequestingLoad = false; ++mUrlIndex; } - CheckFrontFrame( frontFrameReady ); + CheckFrontFrame(frontFrameReady); } -void FixedImageCache::SetImageFrameReady( TextureManager::TextureId textureId ) +void FixedImageCache::SetImageFrameReady(TextureManager::TextureId textureId) { - for( std::size_t i = 0; i < mImageUrls.size() ; ++i ) + for(std::size_t i = 0; i < mImageUrls.size(); ++i) { - if( mImageUrls[i].mTextureId == textureId ) + if(mImageUrls[i].mTextureId == textureId) { mReadyFlags[i] = true; break; @@ -182,15 +174,15 @@ void FixedImageCache::SetImageFrameReady( TextureManager::TextureId textureId ) TextureSet FixedImageCache::GetFrontTextureSet() const { - return mTextureManager.GetTextureSet( mImageUrls[mFront].mTextureId ); + return mTextureManager.GetTextureSet(mImageUrls[mFront].mTextureId); } -void FixedImageCache::CheckFrontFrame( bool wasReady ) +void FixedImageCache::CheckFrontFrame(bool wasReady) { - if( mWaitingForReadyFrame && wasReady == false && IsFrontReady() ) + if(mWaitingForReadyFrame && wasReady == false && IsFrontReady()) { mWaitingForReadyFrame = false; - mObserver.FrameReady( GetFrontTextureSet() ); + mObserver.FrameReady(GetFrontTextureSet()); } } @@ -204,11 +196,11 @@ void FixedImageCache::UploadComplete( { bool frontFrameReady = IsFrontReady(); - if( ! mRequestingLoad ) + if(!mRequestingLoad) { - SetImageFrameReady( textureId ); + SetImageFrameReady(textureId); - CheckFrontFrame( frontFrameReady ); + CheckFrontFrame(frontFrameReady); } else { @@ -220,10 +212,10 @@ void FixedImageCache::UploadComplete( } void FixedImageCache::LoadComplete( - bool loadSuccess, + bool loadSuccess, Devel::PixelBuffer pixelBuffer, - const VisualUrl& url, - bool preMultiplied ) + const VisualUrl& url, + bool preMultiplied) { // LoadComplete is called if this TextureUploadObserver requested to load // an image that will be returned as a type of PixelBuffer by using a method diff --git a/dali-toolkit/internal/visuals/animated-image/image-cache.cpp b/dali-toolkit/internal/visuals/animated-image/image-cache.cpp index 78ca796..cccb085 100644 --- a/dali-toolkit/internal/visuals/animated-image/image-cache.cpp +++ b/dali-toolkit/internal/visuals/animated-image/image-cache.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,26 +22,25 @@ namespace Toolkit { namespace Internal { - -ImageCache::ImageCache( TextureManager& textureManager, - ImageCache::FrameReadyObserver& observer, - unsigned int batchSize ) -: mTextureManager( textureManager ), - mObserver( observer ), - mBatchSize( batchSize ), +ImageCache::ImageCache(TextureManager& textureManager, + ImageCache::FrameReadyObserver& observer, + unsigned int batchSize) +: mTextureManager(textureManager), + mObserver(observer), + mBatchSize(batchSize), mUrlIndex(0u), mWaitingForReadyFrame(false), mRequestingLoad(false), mTextureManagerAlive(true) { - mTextureManager.AddObserver( *this ); + mTextureManager.AddObserver(*this); } ImageCache::~ImageCache() { - if( mTextureManagerAlive ) + if(mTextureManagerAlive) { - mTextureManager.RemoveObserver( *this ); + mTextureManager.RemoveObserver(*this); } } diff --git a/dali-toolkit/internal/visuals/animated-image/rolling-animated-image-cache.cpp b/dali-toolkit/internal/visuals/animated-image/rolling-animated-image-cache.cpp index 565252f..eba9341 100644 --- a/dali-toolkit/internal/visuals/animated-image/rolling-animated-image-cache.cpp +++ b/dali-toolkit/internal/visuals/animated-image/rolling-animated-image-cache.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,27 +29,25 @@ namespace #if defined(DEBUG_ENABLED) Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE"); -#define LOG_CACHE \ - { \ - std::ostringstream oss; \ - oss<<"Size:"<(mCacheSize) && !mQueue.IsFull(); ++i ) + for(unsigned int i = 0; i < mBatchSize && mQueue.Count() + mLoadWaitingQueue.size() < static_cast(mCacheSize) && !mQueue.IsFull(); ++i) { - if( !mOnLoading ) + if(!mOnLoading) { mOnLoading = true; - RequestFrameLoading( mFrameIndex ); + RequestFrameLoading(mFrameIndex); } else { - mLoadWaitingQueue.push_back( mFrameIndex ); + mLoadWaitingQueue.push_back(mFrameIndex); } mFrameIndex++; mFrameIndex %= mFrameCount; } - CheckFrontFrame( frontFrameReady ); + CheckFrontFrame(frontFrameReady); LOG_CACHE; } -void RollingAnimatedImageCache::SetImageFrameReady( TextureManager::TextureId textureId ) +void RollingAnimatedImageCache::SetImageFrameReady(TextureManager::TextureId textureId) { - for( std::size_t i = 0; i < mQueue.Count() ; ++i ) + for(std::size_t i = 0; i < mQueue.Count(); ++i) { - if( GetCachedTextureId( i ) == textureId ) + if(GetCachedTextureId(i) == textureId) { mQueue[i].mReady = true; break; @@ -262,23 +254,23 @@ void RollingAnimatedImageCache::SetImageFrameReady( TextureManager::TextureId te TextureSet RollingAnimatedImageCache::GetFrontTextureSet() const { - DALI_LOG_INFO( gAnimImgLogFilter, Debug::Concise, "RollingAnimatedImageCache::GetFrontTextureSet() FrameNumber:%d\n", mQueue[ 0 ].mFrameNumber ); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "RollingAnimatedImageCache::GetFrontTextureSet() FrameNumber:%d\n", mQueue[0].mFrameNumber); - TextureManager::TextureId textureId = GetCachedTextureId( 0 ); - return mTextureManager.GetTextureSet( textureId ); + TextureManager::TextureId textureId = GetCachedTextureId(0); + return mTextureManager.GetTextureSet(textureId); } -TextureManager::TextureId RollingAnimatedImageCache::GetCachedTextureId( int index ) const +TextureManager::TextureId RollingAnimatedImageCache::GetCachedTextureId(int index) const { - return mImageUrls[ mQueue[ index ].mFrameNumber ].mTextureId; + return mImageUrls[mQueue[index].mFrameNumber].mTextureId; } -void RollingAnimatedImageCache::CheckFrontFrame( bool wasReady ) +void RollingAnimatedImageCache::CheckFrontFrame(bool wasReady) { - if( mWaitingForReadyFrame && wasReady == false && IsFrontReady() ) + if(mWaitingForReadyFrame && wasReady == false && IsFrontReady()) { mWaitingForReadyFrame = false; - mObserver.FrameReady( GetFrontTextureSet() ); + mObserver.FrameReady(GetFrontTextureSet()); } } @@ -288,18 +280,18 @@ void RollingAnimatedImageCache::UploadComplete( TextureSet textureSet, bool useAtlasing, const Vector4& atlasRect, - bool preMultiplied ) + bool preMultiplied) { - DALI_LOG_INFO(gAnimImgLogFilter,Debug::Concise,"AnimatedImageVisual::UploadComplete(textureId:%d) start\n", textureId); + DALI_LOG_INFO(gAnimImgLogFilter, Debug::Concise, "AnimatedImageVisual::UploadComplete(textureId:%d) start\n", textureId); LOG_CACHE; bool frontFrameReady = IsFrontReady(); - if( !mRequestingLoad ) + if(!mRequestingLoad) { - SetImageFrameReady( textureId ); + SetImageFrameReady(textureId); - CheckFrontFrame( frontFrameReady ); + CheckFrontFrame(frontFrameReady); } else { @@ -313,22 +305,22 @@ void RollingAnimatedImageCache::UploadComplete( // The frames of a single animated image can not be loaded parallelly. // Therefore, a frame is now loading, other orders are waiting. // And, after the frame is loaded, requests load of next order. - if( !mLoadWaitingQueue.empty() ) + if(!mLoadWaitingQueue.empty()) { uint32_t loadingIndex = mLoadWaitingQueue.front(); - mLoadWaitingQueue.erase( mLoadWaitingQueue.begin() ); + mLoadWaitingQueue.erase(mLoadWaitingQueue.begin()); mOnLoading = true; - RequestFrameLoading( loadingIndex ); + RequestFrameLoading(loadingIndex); } LOG_CACHE; } void RollingAnimatedImageCache::LoadComplete( - bool loadSuccess, + bool loadSuccess, Devel::PixelBuffer pixelBuffer, - const VisualUrl& url, - bool preMultiplied ) + const VisualUrl& url, + bool preMultiplied) { // LoadComplete is called if this TextureUploadObserver requested to load // an image that will be returned as a type of PixelBuffer by using a method diff --git a/dali-toolkit/internal/visuals/animated-image/rolling-image-cache.cpp b/dali-toolkit/internal/visuals/animated-image/rolling-image-cache.cpp index dee6149..9bcf8e4 100644 --- a/dali-toolkit/internal/visuals/animated-image/rolling-image-cache.cpp +++ b/dali-toolkit/internal/visuals/animated-image/rolling-image-cache.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,28 +28,25 @@ namespace #if defined(DEBUG_ENABLED) Debug::Filter* gAnimImgLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_ANIMATED_IMAGE"); -#define LOG_CACHE \ - { \ - std::ostringstream oss; \ - oss<<"Size:"< // EXTERNAL INCLUDES +#include #include #include -#include #include // INTERNAL INCLUDES -#include -#include -#include #include +#include +#include #include +#include #include #include -#include -#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -const Dali::Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f ); +const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); // stop behavior -DALI_ENUM_TO_STRING_TABLE_BEGIN( STOP_BEHAVIOR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME ) -DALI_ENUM_TO_STRING_TABLE_END( STOP_BEHAVIOR ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(STOP_BEHAVIOR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, CURRENT_FRAME) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, FIRST_FRAME) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::StopBehavior, LAST_FRAME) +DALI_ENUM_TO_STRING_TABLE_END(STOP_BEHAVIOR) // looping mode -DALI_ENUM_TO_STRING_TABLE_BEGIN( LOOPING_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE ) -DALI_ENUM_TO_STRING_TABLE_END( LOOPING_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(LOOPING_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, RESTART) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::DevelImageVisual::LoopingMode, AUTO_REVERSE) +DALI_ENUM_TO_STRING_TABLE_END(LOOPING_MODE) #if defined(DEBUG_ENABLED) -Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" ); +Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION"); #endif } // unnamed namespace -AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties ) +AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties) { - AnimatedVectorImageVisualPtr visual( new AnimatedVectorImageVisual( factoryCache, shaderFactory, imageUrl ) ); - visual->SetProperties( properties ); + AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl)); + visual->SetProperties(properties); visual->Initialize(); return visual; } -AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl ) +AnimatedVectorImageVisualPtr AnimatedVectorImageVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl) { - AnimatedVectorImageVisualPtr visual( new AnimatedVectorImageVisual( factoryCache, shaderFactory, imageUrl ) ); + AnimatedVectorImageVisualPtr visual(new AnimatedVectorImageVisual(factoryCache, shaderFactory, imageUrl)); visual->Initialize(); return visual; } -AnimatedVectorImageVisual::AnimatedVectorImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl ) -: Visual::Base( factoryCache, Visual::FittingMode::FILL, static_cast( Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE ) ), - mUrl( imageUrl ), +AnimatedVectorImageVisual::AnimatedVectorImageVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl) +: Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast(Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE)), + mUrl(imageUrl), mAnimationData(), - mVectorAnimationTask( new VectorAnimationTask( factoryCache, imageUrl.GetUrl() ) ), - mImageVisualShaderFactory( shaderFactory ), + mVectorAnimationTask(new VectorAnimationTask(factoryCache, imageUrl.GetUrl())), + mImageVisualShaderFactory(shaderFactory), mVisualSize(), - mVisualScale( Vector2::ONE ), + mVisualScale(Vector2::ONE), mPlacementActor(), - mPlayState( DevelImageVisual::PlayState::STOPPED ), - mEventCallback( nullptr ), - mRendererAdded( false ), + mPlayState(DevelImageVisual::PlayState::STOPPED), + mEventCallback(nullptr), + mRendererAdded(false), mCoreShutdown(false), mRedrawInScalingDown(true) { // the rasterized image is with pre-multiplied alpha format mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA; - mVectorAnimationTask->UploadCompletedSignal().Connect( this, &AnimatedVectorImageVisual::OnUploadCompleted ); - mVectorAnimationTask->SetAnimationFinishedCallback( new EventThreadCallback( MakeCallback( this, &AnimatedVectorImageVisual::OnAnimationFinished ) ) ); + mVectorAnimationTask->UploadCompletedSignal().Connect(this, &AnimatedVectorImageVisual::OnUploadCompleted); + mVectorAnimationTask->SetAnimationFinishedCallback(new EventThreadCallback(MakeCallback(this, &AnimatedVectorImageVisual::OnAnimationFinished))); auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager(); vectorAnimationManager.AddObserver(*this); @@ -110,18 +106,18 @@ AnimatedVectorImageVisual::AnimatedVectorImageVisual( VisualFactoryCache& factor AnimatedVectorImageVisual::~AnimatedVectorImageVisual() { - if( ! mCoreShutdown ) + if(!mCoreShutdown) { auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager(); vectorAnimationManager.RemoveObserver(*this); - if( mEventCallback ) + if(mEventCallback) { - mFactoryCache.GetVectorAnimationManager().UnregisterEventCallback( mEventCallback ); + mFactoryCache.GetVectorAnimationManager().UnregisterEventCallback(mEventCallback); } // Finalize animation task and disconnect the signal in the main thread - mVectorAnimationTask->UploadCompletedSignal().Disconnect( this, &AnimatedVectorImageVisual::OnUploadCompleted ); + mVectorAnimationTask->UploadCompletedSignal().Disconnect(this, &AnimatedVectorImageVisual::OnUploadCompleted); mVectorAnimationTask->Finalize(); } } @@ -132,105 +128,105 @@ void AnimatedVectorImageVisual::VectorAnimationManagerDestroyed() mCoreShutdown = true; } -void AnimatedVectorImageVisual::GetNaturalSize( Vector2& naturalSize ) +void AnimatedVectorImageVisual::GetNaturalSize(Vector2& naturalSize) { - if( mVisualSize != Vector2::ZERO ) + if(mVisualSize != Vector2::ZERO) { naturalSize = mVisualSize; } else { uint32_t width, height; - mVectorAnimationTask->GetDefaultSize( width, height ); + mVectorAnimationTask->GetDefaultSize(width, height); naturalSize.x = width; naturalSize.y = height; } - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::GetNaturalSize: w = %f, h = %f [%p]\n", naturalSize.width, naturalSize.height, this); } -void AnimatedVectorImageVisual::DoCreatePropertyMap( Property::Map& map ) const +void AnimatedVectorImageVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE ); - if( mUrl.IsValid() ) + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE); + if(mUrl.IsValid()) { - map.Insert( Toolkit::ImageVisual::Property::URL, mUrl.GetUrl() ); + map.Insert(Toolkit::ImageVisual::Property::URL, mUrl.GetUrl()); } - map.Insert( Toolkit::DevelImageVisual::Property::LOOP_COUNT, mAnimationData.loopCount ); + map.Insert(Toolkit::DevelImageVisual::Property::LOOP_COUNT, mAnimationData.loopCount); uint32_t startFrame, endFrame; - mVectorAnimationTask->GetPlayRange( startFrame, endFrame ); + mVectorAnimationTask->GetPlayRange(startFrame, endFrame); Property::Array playRange; - playRange.PushBack( static_cast< int32_t >( startFrame ) ); - playRange.PushBack( static_cast< int32_t >( endFrame ) ); - map.Insert( Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange ); + playRange.PushBack(static_cast(startFrame)); + playRange.PushBack(static_cast(endFrame)); + map.Insert(Toolkit::DevelImageVisual::Property::PLAY_RANGE, playRange); - map.Insert( Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast< int32_t >( mPlayState ) ); - map.Insert( Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast< int32_t >( mVectorAnimationTask->GetCurrentFrameNumber() ) ); - map.Insert( Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast< int32_t >( mVectorAnimationTask->GetTotalFrameNumber() ) ); + map.Insert(Toolkit::DevelImageVisual::Property::PLAY_STATE, static_cast(mPlayState)); + map.Insert(Toolkit::DevelImageVisual::Property::CURRENT_FRAME_NUMBER, static_cast(mVectorAnimationTask->GetCurrentFrameNumber())); + map.Insert(Toolkit::DevelImageVisual::Property::TOTAL_FRAME_NUMBER, static_cast(mVectorAnimationTask->GetTotalFrameNumber())); - map.Insert( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mAnimationData.stopBehavior ); - map.Insert( Toolkit::DevelImageVisual::Property::LOOPING_MODE, mAnimationData.loopingMode ); - map.Insert( Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, mRedrawInScalingDown ); + map.Insert(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, mAnimationData.stopBehavior); + map.Insert(Toolkit::DevelImageVisual::Property::LOOPING_MODE, mAnimationData.loopingMode); + map.Insert(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, mRedrawInScalingDown); Property::Map layerInfo; - mVectorAnimationTask->GetLayerInfo( layerInfo ); - map.Insert( Toolkit::DevelImageVisual::Property::CONTENT_INFO, layerInfo ); + mVectorAnimationTask->GetLayerInfo(layerInfo); + map.Insert(Toolkit::DevelImageVisual::Property::CONTENT_INFO, layerInfo); } -void AnimatedVectorImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void AnimatedVectorImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } -void AnimatedVectorImageVisual::DoSetProperties( const Property::Map& propertyMap ) +void AnimatedVectorImageVisual::DoSetProperties(const Property::Map& propertyMap) { // url already passed in from constructor - for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter ) + for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter) { - KeyValuePair keyValue = propertyMap.GetKeyValue( iter ); - if( keyValue.first.type == Property::Key::INDEX ) + KeyValuePair keyValue = propertyMap.GetKeyValue(iter); + if(keyValue.first.type == Property::Key::INDEX) { - DoSetProperty( keyValue.first.indexKey, keyValue.second ); + DoSetProperty(keyValue.first.indexKey, keyValue.second); } else { - if( keyValue.first == LOOP_COUNT_NAME ) - { - DoSetProperty( Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second ); - } - else if( keyValue.first == PLAY_RANGE_NAME ) - { - DoSetProperty( Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second ); - } - else if( keyValue.first == STOP_BEHAVIOR_NAME ) - { - DoSetProperty( Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second ); - } - else if( keyValue.first == LOOPING_MODE_NAME ) - { - DoSetProperty( Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second ); - } - else if( keyValue.first == REDRAW_IN_SCALING_DOWN_NAME ) - { - DoSetProperty( Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, keyValue.second ); - } + if(keyValue.first == LOOP_COUNT_NAME) + { + DoSetProperty(Toolkit::DevelImageVisual::Property::LOOP_COUNT, keyValue.second); + } + else if(keyValue.first == PLAY_RANGE_NAME) + { + DoSetProperty(Toolkit::DevelImageVisual::Property::PLAY_RANGE, keyValue.second); + } + else if(keyValue.first == STOP_BEHAVIOR_NAME) + { + DoSetProperty(Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR, keyValue.second); + } + else if(keyValue.first == LOOPING_MODE_NAME) + { + DoSetProperty(Toolkit::DevelImageVisual::Property::LOOPING_MODE, keyValue.second); + } + else if(keyValue.first == REDRAW_IN_SCALING_DOWN_NAME) + { + DoSetProperty(Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN, keyValue.second); + } } } TriggerVectorRasterization(); } -void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Property::Value& value ) +void AnimatedVectorImageVisual::DoSetProperty(Property::Index index, const Property::Value& value) { switch(index) { case Toolkit::DevelImageVisual::Property::LOOP_COUNT: { int32_t loopCount; - if( value.Get( loopCount ) ) + if(value.Get(loopCount)) { mAnimationData.loopCount = loopCount; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOP_COUNT; @@ -240,7 +236,7 @@ void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Prop case Toolkit::DevelImageVisual::Property::PLAY_RANGE: { const Property::Array* array = value.GetArray(); - if( array ) + if(array) { mAnimationData.playRange = *array; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_RANGE; @@ -250,9 +246,9 @@ void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Prop case Toolkit::DevelImageVisual::Property::STOP_BEHAVIOR: { int32_t stopBehavior = mAnimationData.stopBehavior; - if( Scripting::GetEnumerationProperty( value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior ) ) + if(Scripting::GetEnumerationProperty(value, STOP_BEHAVIOR_TABLE, STOP_BEHAVIOR_TABLE_COUNT, stopBehavior)) { - mAnimationData.stopBehavior = DevelImageVisual::StopBehavior::Type( stopBehavior ); + mAnimationData.stopBehavior = DevelImageVisual::StopBehavior::Type(stopBehavior); mAnimationData.resendFlag |= VectorAnimationTask::RESEND_STOP_BEHAVIOR; } break; @@ -260,9 +256,9 @@ void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Prop case Toolkit::DevelImageVisual::Property::LOOPING_MODE: { int32_t loopingMode = mAnimationData.loopingMode; - if( Scripting::GetEnumerationProperty( value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode ) ) + if(Scripting::GetEnumerationProperty(value, LOOPING_MODE_TABLE, LOOPING_MODE_TABLE_COUNT, loopingMode)) { - mAnimationData.loopingMode = DevelImageVisual::LoopingMode::Type( loopingMode ); + mAnimationData.loopingMode = DevelImageVisual::LoopingMode::Type(loopingMode); mAnimationData.resendFlag |= VectorAnimationTask::RESEND_LOOPING_MODE; } break; @@ -270,7 +266,7 @@ void AnimatedVectorImageVisual::DoSetProperty( Property::Index index, const Prop case Toolkit::DevelImageVisual::Property::REDRAW_IN_SCALING_DOWN: { bool redraw; - if( value.Get( redraw ) ) + if(value.Get(redraw)) { mRedrawInScalingDown = redraw; } @@ -283,28 +279,28 @@ void AnimatedVectorImageVisual::OnInitialize(void) { Shader shader; - if( mImpl->mCustomShader ) + if(mImpl->mCustomShader) { - shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader, - mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader, - mImpl->mCustomShader->mHints ); + shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader, + mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader, + mImpl->mCustomShader->mHints); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); } else { - shader = mImageVisualShaderFactory.GetShader( mFactoryCache, false, true, IsRoundedCornerRequired() ); + shader = mImageVisualShaderFactory.GetShader(mFactoryCache, false, true, IsRoundedCornerRequired()); } - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); - mImpl->mRenderer = Renderer::New( geometry, shader ); + mImpl->mRenderer = Renderer::New(geometry, shader); TextureSet textureSet = TextureSet::New(); - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); // Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } void AnimatedVectorImageVisual::DoSetOnScene(Actor& actor) @@ -314,71 +310,71 @@ void AnimatedVectorImageVisual::DoSetOnScene(Actor& actor) // Hold the weak handle of the placement actor and delay the adding of renderer until the rasterization is finished. mPlacementActor = actor; - mVectorAnimationTask->SetRenderer( mImpl->mRenderer ); + mVectorAnimationTask->SetRenderer(mImpl->mRenderer); // Add property notification for scaling & size - mScaleNotification = actor.AddPropertyNotification( Actor::Property::WORLD_SCALE, StepCondition( 0.1f, 1.0f ) ); - mScaleNotification.NotifySignal().Connect( this, &AnimatedVectorImageVisual::OnScaleNotification ); + mScaleNotification = actor.AddPropertyNotification(Actor::Property::WORLD_SCALE, StepCondition(0.1f, 1.0f)); + mScaleNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnScaleNotification); - mSizeNotification = actor.AddPropertyNotification( Actor::Property::SIZE, StepCondition( 3.0f ) ); - mSizeNotification.NotifySignal().Connect( this, &AnimatedVectorImageVisual::OnSizeNotification ); + mSizeNotification = actor.AddPropertyNotification(Actor::Property::SIZE, StepCondition(3.0f)); + mSizeNotification.NotifySignal().Connect(this, &AnimatedVectorImageVisual::OnSizeNotification); - DevelActor::VisibilityChangedSignal( actor ).Connect( this, &AnimatedVectorImageVisual::OnControlVisibilityChanged ); + DevelActor::VisibilityChangedSignal(actor).Connect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged); - Window window = DevelWindow::Get( actor ); - if( window ) + Window window = DevelWindow::Get(actor); + if(window) { - DevelWindow::VisibilityChangedSignal( window ).Connect( this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged ); + DevelWindow::VisibilityChangedSignal(window).Connect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged); } - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnScene [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOnScene [%p]\n", this); } -void AnimatedVectorImageVisual::DoSetOffScene( Actor& actor ) +void AnimatedVectorImageVisual::DoSetOffScene(Actor& actor) { StopAnimation(); SendAnimationData(); - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - actor.RemoveRenderer( mImpl->mRenderer ); + actor.RemoveRenderer(mImpl->mRenderer); mRendererAdded = false; } // Remove property notification - actor.RemovePropertyNotification( mScaleNotification ); - actor.RemovePropertyNotification( mSizeNotification ); + actor.RemovePropertyNotification(mScaleNotification); + actor.RemovePropertyNotification(mSizeNotification); - DevelActor::VisibilityChangedSignal( actor ).Disconnect( this, &AnimatedVectorImageVisual::OnControlVisibilityChanged ); + DevelActor::VisibilityChangedSignal(actor).Disconnect(this, &AnimatedVectorImageVisual::OnControlVisibilityChanged); - Window window = DevelWindow::Get( actor ); - if( window ) + Window window = DevelWindow::Get(actor); + if(window) { - DevelWindow::VisibilityChangedSignal( window ).Disconnect( this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged ); + DevelWindow::VisibilityChangedSignal(window).Disconnect(this, &AnimatedVectorImageVisual::OnWindowVisibilityChanged); } mPlacementActor.Reset(); // Reset the visual size to zero so that when adding the actor back to stage the rasterization is forced - mVisualSize = Vector2::ZERO; + mVisualSize = Vector2::ZERO; mVisualScale = Vector2::ONE; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffScene [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::DoSetOffScene [%p]\n", this); } void AnimatedVectorImageVisual::OnSetTransform() { - Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize ); + Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize); - if( IsOnScene() && visualSize != mVisualSize ) + if(IsOnScene() && visualSize != mVisualSize) { - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSetTransform: width = %f, height = %f [%p]\n", visualSize.width, visualSize.height, this); mVisualSize = visualSize; SetVectorImageSize(); - if( mPlayState == DevelImageVisual::PlayState::PLAYING && mAnimationData.playState != DevelImageVisual::PlayState::PLAYING ) + if(mPlayState == DevelImageVisual::PlayState::PLAYING && mAnimationData.playState != DevelImageVisual::PlayState::PLAYING) { mAnimationData.playState = DevelImageVisual::PlayState::PLAYING; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE; @@ -388,16 +384,16 @@ void AnimatedVectorImageVisual::OnSetTransform() } } -void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes ) +void AnimatedVectorImageVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes) { // Check if action is valid for this visual type and perform action if possible - switch( actionId ) + switch(actionId) { case DevelAnimatedVectorImageVisual::Action::PLAY: { - if( IsOnScene() && mVisualSize != Vector2::ZERO ) + if(IsOnScene() && mVisualSize != Vector2::ZERO) { - if( mAnimationData.playState != DevelImageVisual::PlayState::PLAYING ) + if(mAnimationData.playState != DevelImageVisual::PlayState::PLAYING) { mAnimationData.playState = DevelImageVisual::PlayState::PLAYING; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE; @@ -408,7 +404,7 @@ void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, cons } case DevelAnimatedVectorImageVisual::Action::PAUSE: { - if( mAnimationData.playState == DevelImageVisual::PlayState::PLAYING ) + if(mAnimationData.playState == DevelImageVisual::PlayState::PLAYING) { mAnimationData.playState = DevelImageVisual::PlayState::PAUSED; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE; @@ -418,7 +414,7 @@ void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, cons } case DevelAnimatedVectorImageVisual::Action::STOP: { - if( mAnimationData.playState != DevelImageVisual::PlayState::STOPPED ) + if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED) { mAnimationData.playState = DevelImageVisual::PlayState::STOPPED; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE; @@ -429,7 +425,7 @@ void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, cons case DevelAnimatedVectorImageVisual::Action::JUMP_TO: { int32_t frameNumber; - if( attributes.Get( frameNumber ) ) + if(attributes.Get(frameNumber)) { mAnimationData.currentFrame = frameNumber; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_CURRENT_FRAME; @@ -439,9 +435,9 @@ void AnimatedVectorImageVisual::OnDoAction( const Property::Index actionId, cons case DevelAnimatedVectorImageVisual::Action::UPDATE_PROPERTY: { const Property::Map* map = attributes.GetMap(); - if( map ) + if(map) { - DoSetProperties( *map ); + DoSetProperties(*map); } break; } @@ -454,54 +450,54 @@ void AnimatedVectorImageVisual::OnUploadCompleted() { // If weak handle is holding a placement actor, it is the time to add the renderer to actor. Actor actor = mPlacementActor.GetHandle(); - if( actor && !mRendererAdded ) + if(actor && !mRendererAdded) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); mRendererAdded = true; - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnUploadCompleted: Renderer is added [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnUploadCompleted: Renderer is added [%p]\n", this); } } void AnimatedVectorImageVisual::OnAnimationFinished() { - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnAnimationFinished: action state = %d [%p]\n", mPlayState, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnAnimationFinished: action state = %d [%p]\n", mPlayState, this); - if( mPlayState != DevelImageVisual::PlayState::STOPPED ) + if(mPlayState != DevelImageVisual::PlayState::STOPPED) { mPlayState = DevelImageVisual::PlayState::STOPPED; mAnimationData.playState = DevelImageVisual::PlayState::STOPPED; - if( mImpl->mEventObserver ) + if(mImpl->mEventObserver) { - mImpl->mEventObserver->NotifyVisualEvent( *this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED ); + mImpl->mEventObserver->NotifyVisualEvent(*this, DevelAnimatedVectorImageVisual::Signal::ANIMATION_FINISHED); } } - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED ); + mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED); } } void AnimatedVectorImageVisual::SendAnimationData() { - if( mAnimationData.resendFlag ) + if(mAnimationData.resendFlag) { - mVectorAnimationTask->SetAnimationData( mAnimationData ); + mVectorAnimationTask->SetAnimationData(mAnimationData); - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - if( mAnimationData.playState == DevelImageVisual::PlayState::PLAYING ) + if(mAnimationData.playState == DevelImageVisual::PlayState::PLAYING) { - mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY ); + mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::CONTINUOUSLY); } else { - mImpl->mRenderer.SetProperty( DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED ); + mImpl->mRenderer.SetProperty(DevelRenderer::Property::RENDERING_BEHAVIOR, DevelRenderer::Rendering::IF_REQUIRED); } } @@ -511,17 +507,17 @@ void AnimatedVectorImageVisual::SendAnimationData() void AnimatedVectorImageVisual::SetVectorImageSize() { - uint32_t width = static_cast< uint32_t >( mVisualSize.width * mVisualScale.width ); - uint32_t height = static_cast< uint32_t >( mVisualSize.height * mVisualScale.height ); + uint32_t width = static_cast(mVisualSize.width * mVisualScale.width); + uint32_t height = static_cast(mVisualSize.height * mVisualScale.height); - mAnimationData.width = width; + mAnimationData.width = width; mAnimationData.height = height; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_SIZE; } void AnimatedVectorImageVisual::StopAnimation() { - if( mAnimationData.playState != DevelImageVisual::PlayState::STOPPED ) + if(mAnimationData.playState != DevelImageVisual::PlayState::STOPPED) { mAnimationData.playState = DevelImageVisual::PlayState::STOPPED; mAnimationData.resendFlag |= VectorAnimationTask::RESEND_PLAY_STATE; @@ -532,74 +528,74 @@ void AnimatedVectorImageVisual::StopAnimation() void AnimatedVectorImageVisual::TriggerVectorRasterization() { - if( !mEventCallback && !mCoreShutdown ) + if(!mEventCallback && !mCoreShutdown) { - mEventCallback = MakeCallback( this, &AnimatedVectorImageVisual::OnProcessEvents ); + mEventCallback = MakeCallback(this, &AnimatedVectorImageVisual::OnProcessEvents); auto& vectorAnimationManager = mFactoryCache.GetVectorAnimationManager(); - vectorAnimationManager.RegisterEventCallback( mEventCallback ); - Stage::GetCurrent().KeepRendering( 0.0f ); // Trigger event processing + vectorAnimationManager.RegisterEventCallback(mEventCallback); + Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing } } -void AnimatedVectorImageVisual::OnScaleNotification( PropertyNotification& source ) +void AnimatedVectorImageVisual::OnScaleNotification(PropertyNotification& source) { Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { - Vector3 scale = actor.GetProperty< Vector3 >( Actor::Property::WORLD_SCALE ); + Vector3 scale = actor.GetProperty(Actor::Property::WORLD_SCALE); if(mRedrawInScalingDown || scale.width >= 1.0f || scale.height >= 1.0f) { - mVisualScale.width = scale.width; + mVisualScale.width = scale.width; mVisualScale.height = scale.height; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnScaleNotification: scale = %f, %f [%p]\n", mVisualScale.width, mVisualScale.height, this); SetVectorImageSize(); SendAnimationData(); - Stage::GetCurrent().KeepRendering( 0.0f ); // Trigger event processing + Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing } } } -void AnimatedVectorImageVisual::OnSizeNotification( PropertyNotification& source ) +void AnimatedVectorImageVisual::OnSizeNotification(PropertyNotification& source) { Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { - Vector3 size = actor.GetCurrentProperty< Vector3 >( Actor::Property::SIZE ); - mVisualSize.width = size.width; + Vector3 size = actor.GetCurrentProperty(Actor::Property::SIZE); + mVisualSize.width = size.width; mVisualSize.height = size.height; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnSizeNotification: size = %f, %f [%p]\n", mVisualSize.width, mVisualSize.height, this); SetVectorImageSize(); SendAnimationData(); - Stage::GetCurrent().KeepRendering( 0.0f ); // Trigger event processing + Stage::GetCurrent().KeepRendering(0.0f); // Trigger event processing } } -void AnimatedVectorImageVisual::OnControlVisibilityChanged( Actor actor, bool visible, DevelActor::VisibilityChange::Type type ) +void AnimatedVectorImageVisual::OnControlVisibilityChanged(Actor actor, bool visible, DevelActor::VisibilityChange::Type type) { - if( !visible ) + if(!visible) { StopAnimation(); TriggerVectorRasterization(); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnControlVisibilityChanged: invisibile. Pause animation [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnControlVisibilityChanged: invisibile. Pause animation [%p]\n", this); } } -void AnimatedVectorImageVisual::OnWindowVisibilityChanged( Window window, bool visible ) +void AnimatedVectorImageVisual::OnWindowVisibilityChanged(Window window, bool visible) { - if( !visible ) + if(!visible) { StopAnimation(); TriggerVectorRasterization(); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnWindowVisibilityChanged: invisibile. Pause animation [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "AnimatedVectorImageVisual::OnWindowVisibilityChanged: invisibile. Pause animation [%p]\n", this); } } @@ -607,7 +603,7 @@ void AnimatedVectorImageVisual::OnProcessEvents() { SendAnimationData(); - mEventCallback = nullptr; // The callback will be deleted in the VectorAnimationManager + mEventCallback = nullptr; // The callback will be deleted in the VectorAnimationManager } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.cpp b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.cpp index ad56227..2286ea0 100644 --- a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.cpp +++ b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-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. @@ -19,26 +19,22 @@ #include // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" ); +Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION"); #endif } // unnamed namespace @@ -46,40 +42,40 @@ Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, VectorAnimationManager::VectorAnimationManager() : mEventCallbacks(), mLifecycleObservers(), - mVectorAnimationThread( nullptr ), - mProcessorRegistered( false ) + mVectorAnimationThread(nullptr), + mProcessorRegistered(false) { } VectorAnimationManager::~VectorAnimationManager() { - for( auto&& iter : mEventCallbacks ) + for(auto&& iter : mEventCallbacks) { delete iter; } mEventCallbacks.clear(); - if( mProcessorRegistered ) + if(mProcessorRegistered) { - Adaptor::Get().UnregisterProcessor( *this ); + Adaptor::Get().UnregisterProcessor(*this); } - for( auto observer : mLifecycleObservers ) + for(auto observer : mLifecycleObservers) { observer->VectorAnimationManagerDestroyed(); } } -void VectorAnimationManager::AddObserver( VectorAnimationManager::LifecycleObserver& observer ) +void VectorAnimationManager::AddObserver(VectorAnimationManager::LifecycleObserver& observer) { - DALI_ASSERT_DEBUG( mLifecycleObservers.end() == std::find( mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer)); - mLifecycleObservers.push_back( &observer ); + DALI_ASSERT_DEBUG(mLifecycleObservers.end() == std::find(mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer)); + mLifecycleObservers.push_back(&observer); } -void VectorAnimationManager::RemoveObserver( VectorAnimationManager::LifecycleObserver& observer) +void VectorAnimationManager::RemoveObserver(VectorAnimationManager::LifecycleObserver& observer) { - auto iterator=std::find(mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer); - if( iterator != mLifecycleObservers.end() ) + auto iterator = std::find(mLifecycleObservers.begin(), mLifecycleObservers.end(), &observer); + if(iterator != mLifecycleObservers.end()) { mLifecycleObservers.erase(iterator); } @@ -87,37 +83,37 @@ void VectorAnimationManager::RemoveObserver( VectorAnimationManager::LifecycleOb VectorAnimationThread& VectorAnimationManager::GetVectorAnimationThread() { - if( !mVectorAnimationThread ) + if(!mVectorAnimationThread) { - mVectorAnimationThread = std::unique_ptr< VectorAnimationThread >( new VectorAnimationThread() ); + mVectorAnimationThread = std::unique_ptr(new VectorAnimationThread()); mVectorAnimationThread->Start(); } return *mVectorAnimationThread; } -void VectorAnimationManager::RegisterEventCallback( CallbackBase* callback ) +void VectorAnimationManager::RegisterEventCallback(CallbackBase* callback) { - mEventCallbacks.push_back( callback ); + mEventCallbacks.push_back(callback); - if( !mProcessorRegistered ) + if(!mProcessorRegistered) { - Adaptor::Get().RegisterProcessor( *this ); + Adaptor::Get().RegisterProcessor(*this); mProcessorRegistered = true; } } -void VectorAnimationManager::UnregisterEventCallback( CallbackBase* callback ) +void VectorAnimationManager::UnregisterEventCallback(CallbackBase* callback) { - auto iter = std::find( mEventCallbacks.begin(), mEventCallbacks.end(), callback ); - if( iter != mEventCallbacks.end() ) + auto iter = std::find(mEventCallbacks.begin(), mEventCallbacks.end(), callback); + if(iter != mEventCallbacks.end()) { - mEventCallbacks.erase( iter ); + mEventCallbacks.erase(iter); - if( mEventCallbacks.empty() ) + if(mEventCallbacks.empty()) { - if( Adaptor::IsAvailable() ) + if(Adaptor::IsAvailable()) { - Adaptor::Get().UnregisterProcessor( *this ); + Adaptor::Get().UnregisterProcessor(*this); mProcessorRegistered = false; } } @@ -126,14 +122,14 @@ void VectorAnimationManager::UnregisterEventCallback( CallbackBase* callback ) void VectorAnimationManager::Process() { - for( auto&& iter : mEventCallbacks ) + for(auto&& iter : mEventCallbacks) { - CallbackBase::Execute( *iter ); + CallbackBase::Execute(*iter); delete iter; } mEventCallbacks.clear(); - Adaptor::Get().UnregisterProcessor( *this ); + Adaptor::Get().UnregisterProcessor(*this); mProcessorRegistered = false; } diff --git a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp index c5978d6..c229a99 100644 --- a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp +++ b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.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,77 +20,73 @@ // EXTERNAL INCLUDES #include -#include #include +#include // INTERNAL INCLUDES -#include -#include #include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - constexpr auto LOOP_FOREVER = -1; -constexpr auto NANOSECONDS_PER_SECOND( 1e+9 ); +constexpr auto NANOSECONDS_PER_SECOND(1e+9); #if defined(DEBUG_ENABLED) -Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" ); +Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION"); #endif } // unnamed namespace -VectorAnimationTask::VectorAnimationTask( VisualFactoryCache& factoryCache, const std::string& url ) -: mUrl( url ), +VectorAnimationTask::VectorAnimationTask(VisualFactoryCache& factoryCache, const std::string& url) +: mUrl(url), mVectorRenderer(), mAnimationData(), - mVectorAnimationThread( factoryCache.GetVectorAnimationManager().GetVectorAnimationThread() ), + mVectorAnimationThread(factoryCache.GetVectorAnimationManager().GetVectorAnimationThread()), mConditionalWait(), mAnimationFinishedTrigger(), - mPlayState( PlayState::STOPPED ), - mStopBehavior( DevelImageVisual::StopBehavior::CURRENT_FRAME ), - mLoopingMode( DevelImageVisual::LoopingMode::RESTART ), + mPlayState(PlayState::STOPPED), + mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME), + mLoopingMode(DevelImageVisual::LoopingMode::RESTART), mNextFrameStartTime(), - mFrameDurationNanoSeconds( 0 ), - mFrameRate( 60.0f ), - mCurrentFrame( 0 ), - mTotalFrame( 0 ), - mStartFrame( 0 ), - mEndFrame( 0 ), - mWidth( 0 ), - mHeight( 0 ), - mAnimationDataIndex( 0 ), - mLoopCount( LOOP_FOREVER ), - mCurrentLoop( 0 ), - mForward( true ), - mUpdateFrameNumber( false ), - mNeedAnimationFinishedTrigger( true ), - mAnimationDataUpdated( false ), - mDestroyTask( false ) + mFrameDurationNanoSeconds(0), + mFrameRate(60.0f), + mCurrentFrame(0), + mTotalFrame(0), + mStartFrame(0), + mEndFrame(0), + mWidth(0), + mHeight(0), + mAnimationDataIndex(0), + mLoopCount(LOOP_FOREVER), + mCurrentLoop(0), + mForward(true), + mUpdateFrameNumber(false), + mNeedAnimationFinishedTrigger(true), + mAnimationDataUpdated(false), + mDestroyTask(false) { Initialize(); } VectorAnimationTask::~VectorAnimationTask() { - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::~VectorAnimationTask: destructor [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::~VectorAnimationTask: destructor [%p]\n", this); } void VectorAnimationTask::Finalize() { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); // Release some objects in the main thread - if( mAnimationFinishedTrigger ) + if(mAnimationFinishedTrigger) { mAnimationFinishedTrigger.reset(); } @@ -100,125 +96,125 @@ void VectorAnimationTask::Finalize() mDestroyTask = true; } -void VectorAnimationTask::SetRenderer( Renderer renderer ) +void VectorAnimationTask::SetRenderer(Renderer renderer) { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - mVectorRenderer.SetRenderer( renderer ); + mVectorRenderer.SetRenderer(renderer); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetRenderer [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetRenderer [%p]\n", this); } -void VectorAnimationTask::SetAnimationData( const AnimationData& data ) +void VectorAnimationTask::SetAnimationData(const AnimationData& data) { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetAnimationData [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetAnimationData [%p]\n", this); - uint32_t index = mAnimationDataIndex == 0 ? 1 : 0; // Use the other buffer + uint32_t index = mAnimationDataIndex == 0 ? 1 : 0; // Use the other buffer mAnimationData[index] = data; mAnimationDataUpdated = true; - if( data.resendFlag & VectorAnimationTask::RESEND_SIZE ) + if(data.resendFlag & VectorAnimationTask::RESEND_SIZE) { // The size should be changed in the main thread. - SetSize( data.width, data.height ); + SetSize(data.width, data.height); } - mVectorAnimationThread.AddTask( this ); + mVectorAnimationThread.AddTask(this); } -void VectorAnimationTask::SetSize( uint32_t width, uint32_t height ) +void VectorAnimationTask::SetSize(uint32_t width, uint32_t height) { - if( mWidth != width || mHeight != height ) + if(mWidth != width || mHeight != height) { - mVectorRenderer.SetSize( width, height ); + mVectorRenderer.SetSize(width, height); - mWidth = width; + mWidth = width; mHeight = height; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetSize: width = %d, height = %d [%p]\n", width, height, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetSize: width = %d, height = %d [%p]\n", width, height, this); } } void VectorAnimationTask::PlayAnimation() { - if( mPlayState != PlayState::PLAYING ) + if(mPlayState != PlayState::PLAYING) { mNeedAnimationFinishedTrigger = true; - mUpdateFrameNumber = false; - mPlayState = PlayState::PLAYING; + mUpdateFrameNumber = false; + mPlayState = PlayState::PLAYING; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PlayAnimation: Play [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PlayAnimation: Play [%p]\n", this); } } void VectorAnimationTask::StopAnimation() { - if( mPlayState != PlayState::STOPPING ) + if(mPlayState != PlayState::STOPPING) { mNeedAnimationFinishedTrigger = false; - mPlayState = PlayState::STOPPING; + mPlayState = PlayState::STOPPING; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::StopAnimation: Stop [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::StopAnimation: Stop [%p]\n", this); } } void VectorAnimationTask::PauseAnimation() { - if( mPlayState == PlayState::PLAYING ) + if(mPlayState == PlayState::PLAYING) { mPlayState = PlayState::PAUSED; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PauseAnimation: Pause [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PauseAnimation: Pause [%p]\n", this); } } -void VectorAnimationTask::SetAnimationFinishedCallback( EventThreadCallback* callback ) +void VectorAnimationTask::SetAnimationFinishedCallback(EventThreadCallback* callback) { - ConditionalWait::ScopedLock lock( mConditionalWait ); - if( callback ) + ConditionalWait::ScopedLock lock(mConditionalWait); + if(callback) { - mAnimationFinishedTrigger = std::unique_ptr< EventThreadCallback >( callback ); + mAnimationFinishedTrigger = std::unique_ptr(callback); } } -void VectorAnimationTask::SetLoopCount( int32_t count ) +void VectorAnimationTask::SetLoopCount(int32_t count) { - if( mLoopCount != count ) + if(mLoopCount != count) { - mLoopCount = count; + mLoopCount = count; mCurrentLoop = 0; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopCount: [%d] [%p]\n", count, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopCount: [%d] [%p]\n", count, this); } } -void VectorAnimationTask::SetPlayRange( const Property::Array& playRange ) +void VectorAnimationTask::SetPlayRange(const Property::Array& playRange) { - bool valid = false; + bool valid = false; uint32_t startFrame = 0, endFrame = 0; - size_t count = playRange.Count(); + size_t count = playRange.Count(); - if( count >= 2 ) + if(count >= 2) { int32_t start = 0, end = 0; - if( playRange.GetElementAt( 0 ).Get( start ) && playRange.GetElementAt( 1 ).Get( end ) ) + if(playRange.GetElementAt(0).Get(start) && playRange.GetElementAt(1).Get(end)) { - startFrame = static_cast< uint32_t >( start ); - endFrame = static_cast< uint32_t >( end ); - valid = true; + startFrame = static_cast(start); + endFrame = static_cast(end); + valid = true; } else { std::string startMarker, endMarker; - if( playRange.GetElementAt( 0 ).Get( startMarker ) && playRange.GetElementAt( 1 ).Get( endMarker ) ) + if(playRange.GetElementAt(0).Get(startMarker) && playRange.GetElementAt(1).Get(endMarker)) { - if( mVectorRenderer ) + if(mVectorRenderer) { - uint32_t frame; // We don't use this later - if( mVectorRenderer.GetMarkerInfo( startMarker, startFrame, frame ) && mVectorRenderer.GetMarkerInfo( endMarker, frame, endFrame ) ) + uint32_t frame; // We don't use this later + if(mVectorRenderer.GetMarkerInfo(startMarker, startFrame, frame) && mVectorRenderer.GetMarkerInfo(endMarker, frame, endFrame)) { valid = true; } @@ -226,85 +222,85 @@ void VectorAnimationTask::SetPlayRange( const Property::Array& playRange ) } } } - else if( count == 1 ) + else if(count == 1) { std::string marker; - if( playRange.GetElementAt( 0 ).Get( marker ) ) + if(playRange.GetElementAt(0).Get(marker)) { - if( mVectorRenderer ) + if(mVectorRenderer) { - mVectorRenderer.GetMarkerInfo( marker, startFrame, endFrame ); + mVectorRenderer.GetMarkerInfo(marker, startFrame, endFrame); valid = true; } } } - if( !valid ) + if(!valid) { - DALI_LOG_ERROR( "VectorAnimationTask::SetPlayRange: Invalid range [%p]\n", this ); + DALI_LOG_ERROR("VectorAnimationTask::SetPlayRange: Invalid range [%p]\n", this); return; } // Make sure the range specified is between 0 and the total frame number - if( startFrame < mTotalFrame && endFrame < mTotalFrame ) + if(startFrame < mTotalFrame && endFrame < mTotalFrame) { // If the range is not in order swap values - if( startFrame > endFrame ) + if(startFrame > endFrame) { uint32_t temp = startFrame; - startFrame = endFrame; - endFrame = temp; + startFrame = endFrame; + endFrame = temp; } - if( startFrame != mStartFrame || endFrame != mEndFrame ) + if(startFrame != mStartFrame || endFrame != mEndFrame) { mStartFrame = startFrame; - mEndFrame = endFrame; + mEndFrame = endFrame; // If the current frame is out of the range, change the current frame also. - if( mStartFrame > mCurrentFrame ) + if(mStartFrame > mCurrentFrame) { mCurrentFrame = mStartFrame; } - else if( mEndFrame < mCurrentFrame ) + else if(mEndFrame < mCurrentFrame) { mCurrentFrame = mEndFrame; } - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetPlayRange: [%d, %d] [%p]\n", mStartFrame, mEndFrame, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetPlayRange: [%d, %d] [%p]\n", mStartFrame, mEndFrame, this); } } else { - DALI_LOG_ERROR( "VectorAnimationTask::SetPlayRange: Invalid range (%d, %d) [%p]\n", startFrame, endFrame, this ); + DALI_LOG_ERROR("VectorAnimationTask::SetPlayRange: Invalid range (%d, %d) [%p]\n", startFrame, endFrame, this); return; } } -void VectorAnimationTask::GetPlayRange( uint32_t& startFrame, uint32_t& endFrame ) +void VectorAnimationTask::GetPlayRange(uint32_t& startFrame, uint32_t& endFrame) { startFrame = mStartFrame; - endFrame = mEndFrame; + endFrame = mEndFrame; } -void VectorAnimationTask::SetCurrentFrameNumber( uint32_t frameNumber ) +void VectorAnimationTask::SetCurrentFrameNumber(uint32_t frameNumber) { - if( mCurrentFrame == frameNumber ) + if(mCurrentFrame == frameNumber) { - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: Set same frame [%d] [%p]\n", frameNumber, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: Set same frame [%d] [%p]\n", frameNumber, this); return; } - if( frameNumber >= mStartFrame && frameNumber <= mEndFrame ) + if(frameNumber >= mStartFrame && frameNumber <= mEndFrame) { - mCurrentFrame = frameNumber; + mCurrentFrame = frameNumber; mUpdateFrameNumber = false; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: frame number = %d [%p]\n", mCurrentFrame, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: frame number = %d [%p]\n", mCurrentFrame, this); } else { - DALI_LOG_ERROR( "Invalid frame number [%d (%d, %d)]\n", frameNumber, mStartFrame, mEndFrame ); + DALI_LOG_ERROR("Invalid frame number [%d (%d, %d)]\n", frameNumber, mStartFrame, mEndFrame); } } @@ -318,28 +314,28 @@ uint32_t VectorAnimationTask::GetTotalFrameNumber() const return mTotalFrame; } -void VectorAnimationTask::GetDefaultSize( uint32_t& width, uint32_t& height ) const +void VectorAnimationTask::GetDefaultSize(uint32_t& width, uint32_t& height) const { - mVectorRenderer.GetDefaultSize( width, height ); + mVectorRenderer.GetDefaultSize(width, height); } -void VectorAnimationTask::SetStopBehavior( DevelImageVisual::StopBehavior::Type stopBehavior ) +void VectorAnimationTask::SetStopBehavior(DevelImageVisual::StopBehavior::Type stopBehavior) { mStopBehavior = stopBehavior; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetStopBehavior: stop behavor = %d [%p]\n", mStopBehavior, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetStopBehavior: stop behavor = %d [%p]\n", mStopBehavior, this); } -void VectorAnimationTask::SetLoopingMode( DevelImageVisual::LoopingMode::Type loopingMode ) +void VectorAnimationTask::SetLoopingMode(DevelImageVisual::LoopingMode::Type loopingMode) { mLoopingMode = loopingMode; - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopingMode: looping mode = %d [%p]\n", mLoopingMode, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopingMode: looping mode = %d [%p]\n", mLoopingMode, this); } -void VectorAnimationTask::GetLayerInfo( Property::Map& map ) const +void VectorAnimationTask::GetLayerInfo(Property::Map& map) const { - mVectorRenderer.GetLayerInfo( map ); + mVectorRenderer.GetLayerInfo(map); } VectorAnimationTask::UploadCompletedSignalType& VectorAnimationTask::UploadCompletedSignal() @@ -349,31 +345,31 @@ VectorAnimationTask::UploadCompletedSignalType& VectorAnimationTask::UploadCompl void VectorAnimationTask::Initialize() { - mVectorRenderer = VectorAnimationRenderer::New( mUrl ); + mVectorRenderer = VectorAnimationRenderer::New(mUrl); mTotalFrame = mVectorRenderer.GetTotalFrameNumber(); mEndFrame = mTotalFrame - 1; - mFrameRate = mVectorRenderer.GetFrameRate(); + mFrameRate = mVectorRenderer.GetFrameRate(); mFrameDurationNanoSeconds = NANOSECONDS_PER_SECOND / mFrameRate; uint32_t width, height; - mVectorRenderer.GetDefaultSize( width, height ); + mVectorRenderer.GetDefaultSize(width, height); - SetSize( width, height ); + SetSize(width, height); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Initialize: file = %s [%d frames, %f fps] [%p]\n", mUrl.c_str(), mTotalFrame, mFrameRate, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Initialize: file = %s [%d frames, %f fps] [%p]\n", mUrl.c_str(), mTotalFrame, mFrameRate, this); } bool VectorAnimationTask::Rasterize() { - bool stopped = false; + bool stopped = false; uint32_t currentFrame; { - ConditionalWait::ScopedLock lock( mConditionalWait ); - if( mDestroyTask ) + ConditionalWait::ScopedLock lock(mConditionalWait); + if(mDestroyTask) { // The task will be destroyed. We don't need rasterization. return false; @@ -382,60 +378,60 @@ bool VectorAnimationTask::Rasterize() ApplyAnimationData(); - if( mPlayState == PlayState::PLAYING && mUpdateFrameNumber ) + if(mPlayState == PlayState::PLAYING && mUpdateFrameNumber) { mCurrentFrame = mForward ? mCurrentFrame + 1 : mCurrentFrame - 1; - Dali::ClampInPlace( mCurrentFrame, mStartFrame, mEndFrame ); + Dali::ClampInPlace(mCurrentFrame, mStartFrame, mEndFrame); } currentFrame = mCurrentFrame; mUpdateFrameNumber = true; - if( mPlayState == PlayState::STOPPING ) + if(mPlayState == PlayState::STOPPING) { - mCurrentFrame = GetStoppedFrame( mStartFrame, mEndFrame, mCurrentFrame ); - currentFrame = mCurrentFrame; - stopped = true; + mCurrentFrame = GetStoppedFrame(mStartFrame, mEndFrame, mCurrentFrame); + currentFrame = mCurrentFrame; + stopped = true; } - else if( mPlayState == PlayState::PLAYING ) + else if(mPlayState == PlayState::PLAYING) { bool animationFinished = false; - if( currentFrame >= mEndFrame ) // last frame + if(currentFrame >= mEndFrame) // last frame { - if( mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE ) + if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE) { mForward = false; } else { - if( mLoopCount < 0 || ++mCurrentLoop < mLoopCount ) // repeat forever or before the last loop + if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop { - mCurrentFrame = mStartFrame; + mCurrentFrame = mStartFrame; mUpdateFrameNumber = false; } else { - animationFinished = true; // end of animation + animationFinished = true; // end of animation } } } - else if( currentFrame == mStartFrame && !mForward ) // first frame + else if(currentFrame == mStartFrame && !mForward) // first frame { - if( mLoopCount < 0 || ++mCurrentLoop < mLoopCount ) // repeat forever or before the last loop + if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop { mForward = true; } else { - animationFinished = true; // end of animation + animationFinished = true; // end of animation } } - if( animationFinished ) + if(animationFinished) { - if( mStopBehavior == DevelImageVisual::StopBehavior::CURRENT_FRAME ) + if(mStopBehavior == DevelImageVisual::StopBehavior::CURRENT_FRAME) { stopped = true; } @@ -448,36 +444,36 @@ bool VectorAnimationTask::Rasterize() // Rasterize bool renderSuccess = false; - if( mVectorRenderer ) + if(mVectorRenderer) { - renderSuccess = mVectorRenderer.Render( currentFrame ); - if( !renderSuccess ) + renderSuccess = mVectorRenderer.Render(currentFrame); + if(!renderSuccess) { - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Rendering failed. Try again later.[%d] [%p]\n", currentFrame, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Rendering failed. Try again later.[%d] [%p]\n", currentFrame, this); mUpdateFrameNumber = false; } } - if( stopped && renderSuccess ) + if(stopped && renderSuccess) { - mPlayState = PlayState::STOPPED; - mForward = true; + mPlayState = PlayState::STOPPED; + mForward = true; mCurrentLoop = 0; // Animation is finished { - ConditionalWait::ScopedLock lock( mConditionalWait ); - if( mNeedAnimationFinishedTrigger && mAnimationFinishedTrigger ) + ConditionalWait::ScopedLock lock(mConditionalWait); + if(mNeedAnimationFinishedTrigger && mAnimationFinishedTrigger) { mAnimationFinishedTrigger->Trigger(); } } - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Animation is finished [current = %d] [%p]\n", currentFrame, this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Animation is finished [current = %d] [%p]\n", currentFrame, this); } bool keepAnimation = true; - if( mPlayState == PlayState::PAUSED || mPlayState == PlayState::STOPPED ) + if(mPlayState == PlayState::PAUSED || mPlayState == PlayState::STOPPED) { keepAnimation = false; } @@ -485,11 +481,11 @@ bool VectorAnimationTask::Rasterize() return keepAnimation; } -uint32_t VectorAnimationTask::GetStoppedFrame( uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame ) +uint32_t VectorAnimationTask::GetStoppedFrame(uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame) { uint32_t frame = currentFrame; - switch( mStopBehavior ) + switch(mStopBehavior) { case DevelImageVisual::StopBehavior::FIRST_FRAME: { @@ -498,7 +494,7 @@ uint32_t VectorAnimationTask::GetStoppedFrame( uint32_t startFrame, uint32_t end } case DevelImageVisual::StopBehavior::LAST_FRAME: { - if( mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE ) + if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE) { frame = startFrame; } @@ -518,22 +514,22 @@ uint32_t VectorAnimationTask::GetStoppedFrame( uint32_t startFrame, uint32_t end return frame; } -std::chrono::time_point< std::chrono::system_clock > VectorAnimationTask::CalculateNextFrameTime( bool renderNow ) +std::chrono::time_point VectorAnimationTask::CalculateNextFrameTime(bool renderNow) { // std::chrono::time_point template has second parameter duration which defaults to the std::chrono::system_clock supported // duration. In some C++11 implementations it is a milliseconds duration, so it fails to compile unless mNextFrameStartTime // is casted to use the default duration. - mNextFrameStartTime = std::chrono::time_point_cast< std::chrono::time_point< std::chrono::system_clock >::duration >( - mNextFrameStartTime + std::chrono::nanoseconds( mFrameDurationNanoSeconds ) ); + mNextFrameStartTime = std::chrono::time_point_cast::duration>( + mNextFrameStartTime + std::chrono::nanoseconds(mFrameDurationNanoSeconds)); auto current = std::chrono::system_clock::now(); - if( renderNow || mNextFrameStartTime < current ) + if(renderNow || mNextFrameStartTime < current) { mNextFrameStartTime = current; } return mNextFrameStartTime; } -std::chrono::time_point< std::chrono::system_clock > VectorAnimationTask::GetNextFrameTime() +std::chrono::time_point VectorAnimationTask::GetNextFrameTime() { return mNextFrameStartTime; } @@ -543,56 +539,56 @@ void VectorAnimationTask::ApplyAnimationData() uint32_t index; { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - if( !mAnimationDataUpdated || mAnimationData[mAnimationDataIndex].resendFlag != 0 ) + if(!mAnimationDataUpdated || mAnimationData[mAnimationDataIndex].resendFlag != 0) { // Data is not updated or the previous data is not applied yet. return; } - mAnimationDataIndex = mAnimationDataIndex == 0 ? 1 : 0; // Swap index + mAnimationDataIndex = mAnimationDataIndex == 0 ? 1 : 0; // Swap index mAnimationDataUpdated = false; index = mAnimationDataIndex; } - if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOP_COUNT ) + if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOP_COUNT) { - SetLoopCount( mAnimationData[index].loopCount ); + SetLoopCount(mAnimationData[index].loopCount); } - if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_RANGE ) + if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_RANGE) { - SetPlayRange( mAnimationData[index].playRange ); + SetPlayRange(mAnimationData[index].playRange); } - if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_STOP_BEHAVIOR ) + if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_STOP_BEHAVIOR) { - SetStopBehavior( mAnimationData[index].stopBehavior ); + SetStopBehavior(mAnimationData[index].stopBehavior); } - if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOPING_MODE ) + if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOPING_MODE) { - SetLoopingMode( mAnimationData[index].loopingMode ); + SetLoopingMode(mAnimationData[index].loopingMode); } - if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_CURRENT_FRAME ) + if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_CURRENT_FRAME) { - SetCurrentFrameNumber( mAnimationData[index].currentFrame ); + SetCurrentFrameNumber(mAnimationData[index].currentFrame); } - if( mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_STATE ) + if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_STATE) { - if( mAnimationData[index].playState == DevelImageVisual::PlayState::PLAYING ) + if(mAnimationData[index].playState == DevelImageVisual::PlayState::PLAYING) { PlayAnimation(); } - else if( mAnimationData[index].playState == DevelImageVisual::PlayState::PAUSED ) + else if(mAnimationData[index].playState == DevelImageVisual::PlayState::PAUSED) { PauseAnimation(); } - else if( mAnimationData[index].playState == DevelImageVisual::PlayState::STOPPED ) + else if(mAnimationData[index].playState == DevelImageVisual::PlayState::STOPPED) { StopAnimation(); } diff --git a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp index c80e00a..a5b1166 100644 --- a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp +++ b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.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,39 +19,35 @@ #include // EXTERNAL INCLUDES -#include #include +#include +#include #include #include -#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { +constexpr auto DEFAULT_NUMBER_OF_RASTERIZE_THREADS = size_t{4u}; +constexpr auto NUMBER_OF_RASTERIZE_THREADS_ENV = "DALI_VECTOR_RASTERIZE_THREADS"; -constexpr auto DEFAULT_NUMBER_OF_RASTERIZE_THREADS = size_t{ 4u }; -constexpr auto NUMBER_OF_RASTERIZE_THREADS_ENV = "DALI_VECTOR_RASTERIZE_THREADS"; - -size_t GetNumberOfThreads( const char* environmentVariable, size_t defaultValue ) +size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue) { using Dali::EnvironmentVariable::GetEnvironmentVariable; - auto numberString = GetEnvironmentVariable( environmentVariable ); - auto numberOfThreads = numberString ? std::strtoul( numberString, nullptr, 10 ) : 0; + auto numberString = GetEnvironmentVariable(environmentVariable); + auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0; constexpr auto MAX_NUMBER_OF_THREADS = 100u; - DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS ); - return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue; + DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS); + return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue; } #if defined(DEBUG_ENABLED) -Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" ); +Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION"); #endif } // unnamed namespace @@ -60,12 +56,12 @@ VectorAnimationThread::VectorAnimationThread() : mAnimationTasks(), mCompletedTasks(), mWorkingTasks(), - mRasterizers( GetNumberOfThreads( NUMBER_OF_RASTERIZE_THREADS_ENV, DEFAULT_NUMBER_OF_RASTERIZE_THREADS ), [&]() { return RasterizeHelper( *this ); } ), - mSleepThread( MakeCallback( this, &VectorAnimationThread::OnAwakeFromSleep ) ), + mRasterizers(GetNumberOfThreads(NUMBER_OF_RASTERIZE_THREADS_ENV, DEFAULT_NUMBER_OF_RASTERIZE_THREADS), [&]() { return RasterizeHelper(*this); }), + mSleepThread(MakeCallback(this, &VectorAnimationThread::OnAwakeFromSleep)), mConditionalWait(), - mNeedToSleep( false ), - mDestroyThread( false ), - mLogFactory( Dali::Adaptor::Get().GetLogFactory() ) + mNeedToSleep(false), + mDestroyThread(false), + mLogFactory(Dali::Adaptor::Get().GetLogFactory()) { mSleepThread.Start(); } @@ -74,88 +70,88 @@ VectorAnimationThread::~VectorAnimationThread() { // Stop the thread { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); mDestroyThread = true; - mNeedToSleep = false; - mConditionalWait.Notify( lock ); + mNeedToSleep = false; + mConditionalWait.Notify(lock); } - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::~VectorAnimationThread: Join [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::~VectorAnimationThread: Join [%p]\n", this); Join(); } -void VectorAnimationThread::AddTask( VectorAnimationTaskPtr task ) +void VectorAnimationThread::AddTask(VectorAnimationTaskPtr task) { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - if( mAnimationTasks.end() == std::find( mAnimationTasks.begin(), mAnimationTasks.end(), task ) ) + if(mAnimationTasks.end() == std::find(mAnimationTasks.begin(), mAnimationTasks.end(), task)) { - auto currentTime = task->CalculateNextFrameTime( true ); // Rasterize as soon as possible + auto currentTime = task->CalculateNextFrameTime(true); // Rasterize as soon as possible bool inserted = false; - for( auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter ) + for(auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter) { auto nextTime = (*iter)->GetNextFrameTime(); - if( nextTime > currentTime ) + if(nextTime > currentTime) { - mAnimationTasks.insert( iter, task ); + mAnimationTasks.insert(iter, task); inserted = true; break; } } - if( !inserted ) + if(!inserted) { - mAnimationTasks.push_back( task ); + mAnimationTasks.push_back(task); } mNeedToSleep = false; // wake up the animation thread - mConditionalWait.Notify( lock ); + mConditionalWait.Notify(lock); } } -void VectorAnimationThread::OnTaskCompleted( VectorAnimationTaskPtr task, bool keepAnimation ) +void VectorAnimationThread::OnTaskCompleted(VectorAnimationTaskPtr task, bool keepAnimation) { - if( !mDestroyThread ) + if(!mDestroyThread) { - ConditionalWait::ScopedLock lock( mConditionalWait ); - bool needRasterize = false; + ConditionalWait::ScopedLock lock(mConditionalWait); + bool needRasterize = false; - auto workingTask = std::find( mWorkingTasks.begin(), mWorkingTasks.end(), task ); - if( workingTask != mWorkingTasks.end() ) + auto workingTask = std::find(mWorkingTasks.begin(), mWorkingTasks.end(), task); + if(workingTask != mWorkingTasks.end()) { - mWorkingTasks.erase( workingTask ); + mWorkingTasks.erase(workingTask); } // Check pending task - if( mAnimationTasks.end() != std::find( mAnimationTasks.begin(), mAnimationTasks.end(), task ) ) + if(mAnimationTasks.end() != std::find(mAnimationTasks.begin(), mAnimationTasks.end(), task)) { needRasterize = true; } - if( keepAnimation ) + if(keepAnimation) { - if( mCompletedTasks.end() == std::find( mCompletedTasks.begin(), mCompletedTasks.end(), task ) ) + if(mCompletedTasks.end() == std::find(mCompletedTasks.begin(), mCompletedTasks.end(), task)) { - mCompletedTasks.push_back( task ); + mCompletedTasks.push_back(task); needRasterize = true; } } - if( needRasterize ) + if(needRasterize) { mNeedToSleep = false; // wake up the animation thread - mConditionalWait.Notify( lock ); + mConditionalWait.Notify(lock); } } } void VectorAnimationThread::OnAwakeFromSleep() { - if( !mDestroyThread ) + if(!mDestroyThread) { mNeedToSleep = false; // wake up the animation thread @@ -165,10 +161,10 @@ void VectorAnimationThread::OnAwakeFromSleep() void VectorAnimationThread::Run() { - SetThreadName( "VectorAnimationThread" ); + SetThreadName("VectorAnimationThread"); mLogFactory.InstallLogFunction(); - while( !mDestroyThread ) + while(!mDestroyThread) { Rasterize(); } @@ -177,72 +173,72 @@ void VectorAnimationThread::Run() void VectorAnimationThread::Rasterize() { // Lock while popping task out from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); // conditional wait - if( mNeedToSleep ) + if(mNeedToSleep) { - mConditionalWait.Wait( lock ); + mConditionalWait.Wait(lock); } mNeedToSleep = true; // Process completed tasks - for( auto&& task : mCompletedTasks ) + for(auto&& task : mCompletedTasks) { - if( mAnimationTasks.end() == std::find( mAnimationTasks.begin(), mAnimationTasks.end(), task ) ) + if(mAnimationTasks.end() == std::find(mAnimationTasks.begin(), mAnimationTasks.end(), task)) { // Should use the frame rate of the animation file - auto nextFrameTime = task->CalculateNextFrameTime( false ); + auto nextFrameTime = task->CalculateNextFrameTime(false); bool inserted = false; - for( auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter ) + for(auto iter = mAnimationTasks.begin(); iter != mAnimationTasks.end(); ++iter) { auto time = (*iter)->GetNextFrameTime(); - if( time > nextFrameTime ) + if(time > nextFrameTime) { - mAnimationTasks.insert( iter, task ); + mAnimationTasks.insert(iter, task); inserted = true; break; } } - if( !inserted ) + if(!inserted) { - mAnimationTasks.push_back( task ); + mAnimationTasks.push_back(task); } } } mCompletedTasks.clear(); // pop out the next task from the queue - for( auto it = mAnimationTasks.begin(); it != mAnimationTasks.end(); ) + for(auto it = mAnimationTasks.begin(); it != mAnimationTasks.end();) { VectorAnimationTaskPtr nextTask = *it; - auto currentTime = std::chrono::system_clock::now(); + auto currentTime = std::chrono::system_clock::now(); auto nextFrameTime = nextTask->GetNextFrameTime(); #if defined(DEBUG_ENABLED) - auto duration = std::chrono::duration_cast< std::chrono::milliseconds >( nextFrameTime - currentTime ); + auto duration = std::chrono::duration_cast(nextFrameTime - currentTime); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::Rasterize: [next time = %lld]\n", duration.count() ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::Rasterize: [next time = %lld]\n", duration.count()); #endif - if( nextFrameTime <= currentTime ) + if(nextFrameTime <= currentTime) { // If the task is not in the working list - if( std::find( mWorkingTasks.begin(), mWorkingTasks.end(), nextTask ) == mWorkingTasks.end() ) + if(std::find(mWorkingTasks.begin(), mWorkingTasks.end(), nextTask) == mWorkingTasks.end()) { - it = mAnimationTasks.erase( it ); + it = mAnimationTasks.erase(it); // Add it to the working list - mWorkingTasks.push_back( nextTask ); + mWorkingTasks.push_back(nextTask); auto rasterizerHelperIt = mRasterizers.GetNext(); - DALI_ASSERT_ALWAYS( rasterizerHelperIt != mRasterizers.End() ); + DALI_ASSERT_ALWAYS(rasterizerHelperIt != mRasterizers.End()); - rasterizerHelperIt->Rasterize( nextTask ); + rasterizerHelperIt->Rasterize(nextTask); } else { @@ -251,44 +247,44 @@ void VectorAnimationThread::Rasterize() } else { - mSleepThread.SleepUntil( nextFrameTime ); + mSleepThread.SleepUntil(nextFrameTime); break; } } } -VectorAnimationThread::RasterizeHelper::RasterizeHelper( VectorAnimationThread& animationThread ) -: RasterizeHelper( std::unique_ptr< VectorRasterizeThread >( new VectorRasterizeThread() ), animationThread ) +VectorAnimationThread::RasterizeHelper::RasterizeHelper(VectorAnimationThread& animationThread) +: RasterizeHelper(std::unique_ptr(new VectorRasterizeThread()), animationThread) { } -VectorAnimationThread::RasterizeHelper::RasterizeHelper( RasterizeHelper&& rhs ) -: RasterizeHelper( std::move( rhs.mRasterizer ), rhs.mAnimationThread ) +VectorAnimationThread::RasterizeHelper::RasterizeHelper(RasterizeHelper&& rhs) +: RasterizeHelper(std::move(rhs.mRasterizer), rhs.mAnimationThread) { } -VectorAnimationThread::RasterizeHelper::RasterizeHelper( std::unique_ptr< VectorRasterizeThread > rasterizer, VectorAnimationThread& animationThread ) -: mRasterizer( std::move( rasterizer ) ), - mAnimationThread( animationThread ) +VectorAnimationThread::RasterizeHelper::RasterizeHelper(std::unique_ptr rasterizer, VectorAnimationThread& animationThread) +: mRasterizer(std::move(rasterizer)), + mAnimationThread(animationThread) { - mRasterizer->SetCompletedCallback( MakeCallback( &mAnimationThread, &VectorAnimationThread::OnTaskCompleted ) ); + mRasterizer->SetCompletedCallback(MakeCallback(&mAnimationThread, &VectorAnimationThread::OnTaskCompleted)); } -void VectorAnimationThread::RasterizeHelper::Rasterize( VectorAnimationTaskPtr task ) +void VectorAnimationThread::RasterizeHelper::Rasterize(VectorAnimationTaskPtr task) { - if( task ) + if(task) { - mRasterizer->AddTask( task ); + mRasterizer->AddTask(task); } } -VectorAnimationThread::SleepThread::SleepThread( CallbackBase* callback ) +VectorAnimationThread::SleepThread::SleepThread(CallbackBase* callback) : mConditionalWait(), - mAwakeCallback( std::unique_ptr< CallbackBase >( callback ) ), + mAwakeCallback(std::unique_ptr(callback)), mSleepTimePoint(), - mLogFactory( Dali::Adaptor::Get().GetLogFactory() ), - mNeedToSleep( false ), - mDestroyThread( false ) + mLogFactory(Dali::Adaptor::Get().GetLogFactory()), + mNeedToSleep(false), + mDestroyThread(false) { } @@ -296,62 +292,62 @@ VectorAnimationThread::SleepThread::~SleepThread() { // Stop the thread { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); mDestroyThread = true; - mConditionalWait.Notify( lock ); + mConditionalWait.Notify(lock); } Join(); } -void VectorAnimationThread::SleepThread::SleepUntil( std::chrono::time_point< std::chrono::system_clock > timeToSleepUntil ) +void VectorAnimationThread::SleepThread::SleepUntil(std::chrono::time_point timeToSleepUntil) { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); mSleepTimePoint = timeToSleepUntil; - mNeedToSleep = true; - mConditionalWait.Notify( lock ); + mNeedToSleep = true; + mConditionalWait.Notify(lock); } void VectorAnimationThread::SleepThread::Run() { - SetThreadName( "VectorSleepThread" ); + SetThreadName("VectorSleepThread"); mLogFactory.InstallLogFunction(); - while( !mDestroyThread ) + while(!mDestroyThread) { - bool needToSleep; - std::chrono::time_point< std::chrono::system_clock > sleepTimePoint; + bool needToSleep; + std::chrono::time_point sleepTimePoint; { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - needToSleep = mNeedToSleep; + needToSleep = mNeedToSleep; sleepTimePoint = mSleepTimePoint; mNeedToSleep = false; } - if( needToSleep ) + if(needToSleep) { #if defined(DEBUG_ENABLED) - auto sleepDuration = std::chrono::duration_cast< std::chrono::milliseconds >( mSleepTimePoint - std::chrono::system_clock::now() ); + auto sleepDuration = std::chrono::duration_cast(mSleepTimePoint - std::chrono::system_clock::now()); - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::SleepThread::Run: [sleep duration = %lld]\n", sleepDuration.count() ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationThread::SleepThread::Run: [sleep duration = %lld]\n", sleepDuration.count()); #endif - std::this_thread::sleep_until( sleepTimePoint ); + std::this_thread::sleep_until(sleepTimePoint); - if( mAwakeCallback ) + if(mAwakeCallback) { - CallbackBase::Execute( *mAwakeCallback ); + CallbackBase::Execute(*mAwakeCallback); } } { - ConditionalWait::ScopedLock lock( mConditionalWait ); - if( !mDestroyThread && !mNeedToSleep ) + ConditionalWait::ScopedLock lock(mConditionalWait); + if(!mDestroyThread && !mNeedToSleep) { - mConditionalWait.Wait( lock ); + mConditionalWait.Wait(lock); } } } diff --git a/dali-toolkit/internal/visuals/animated-vector-image/vector-rasterize-thread.cpp b/dali-toolkit/internal/visuals/animated-vector-image/vector-rasterize-thread.cpp index 08cad31..9a3f909 100644 --- a/dali-toolkit/internal/visuals/animated-vector-image/vector-rasterize-thread.cpp +++ b/dali-toolkit/internal/visuals/animated-vector-image/vector-rasterize-thread.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,25 +20,21 @@ // EXTERNAL INCLUDES #include +#include #include #include #include -#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VECTOR_ANIMATION" ); +Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION"); #endif } // unnamed namespace @@ -47,9 +43,9 @@ VectorRasterizeThread::VectorRasterizeThread() : mRasterizeTasks(), mConditionalWait(), mCompletedCallback(), - mDestroyThread( false ), - mIsThreadStarted( false ), - mLogFactory( Dali::Adaptor::Get().GetLogFactory() ) + mDestroyThread(false), + mIsThreadStarted(false), + mLogFactory(Dali::Adaptor::Get().GetLogFactory()) { } @@ -57,49 +53,49 @@ VectorRasterizeThread::~VectorRasterizeThread() { // Stop the thread { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); mDestroyThread = true; - mConditionalWait.Notify( lock ); + mConditionalWait.Notify(lock); } - DALI_LOG_INFO( gVectorAnimationLogFilter, Debug::Verbose, "VectorRasterizeThread::~VectorRasterizeThread: Join [%p]\n", this ); + DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorRasterizeThread::~VectorRasterizeThread: Join [%p]\n", this); Join(); } -void VectorRasterizeThread::SetCompletedCallback( CallbackBase* callback ) +void VectorRasterizeThread::SetCompletedCallback(CallbackBase* callback) { - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - mCompletedCallback = std::unique_ptr< CallbackBase >( callback ); + mCompletedCallback = std::unique_ptr(callback); } -void VectorRasterizeThread::AddTask( VectorAnimationTaskPtr task ) +void VectorRasterizeThread::AddTask(VectorAnimationTaskPtr task) { // Lock while adding task to the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - if( !mIsThreadStarted ) + if(!mIsThreadStarted) { Start(); mIsThreadStarted = true; } - if( mRasterizeTasks.end() == std::find( mRasterizeTasks.begin(), mRasterizeTasks.end(), task ) ) + if(mRasterizeTasks.end() == std::find(mRasterizeTasks.begin(), mRasterizeTasks.end(), task)) { - mRasterizeTasks.push_back( task ); + mRasterizeTasks.push_back(task); // wake up the animation thread - mConditionalWait.Notify( lock ); + mConditionalWait.Notify(lock); } } void VectorRasterizeThread::Run() { - SetThreadName( "VectorRasterizeThread" ); + SetThreadName("VectorRasterizeThread"); mLogFactory.InstallLogFunction(); - while( !mDestroyThread ) + while(!mDestroyThread) { Rasterize(); } @@ -110,30 +106,30 @@ void VectorRasterizeThread::Rasterize() VectorAnimationTaskPtr nextTask; { // Lock while popping task out from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); // conditional wait - if( mRasterizeTasks.empty() ) + if(mRasterizeTasks.empty()) { - mConditionalWait.Wait( lock ); + mConditionalWait.Wait(lock); } // pop out the next task from the queue - if( !mRasterizeTasks.empty() ) + if(!mRasterizeTasks.empty()) { - std::vector< VectorAnimationTaskPtr >::iterator next = mRasterizeTasks.begin(); - nextTask = *next; - mRasterizeTasks.erase( next ); + std::vector::iterator next = mRasterizeTasks.begin(); + nextTask = *next; + mRasterizeTasks.erase(next); } } - if( nextTask ) + if(nextTask) { bool keepAnimation = nextTask->Rasterize(); - if( mCompletedCallback ) + if(mCompletedCallback) { - CallbackBase::Execute( *mCompletedCallback, nextTask, keepAnimation ); + CallbackBase::Execute(*mCompletedCallback, nextTask, keepAnimation); } } } diff --git a/dali-toolkit/internal/visuals/arc/arc-visual.cpp b/dali-toolkit/internal/visuals/arc/arc-visual.cpp index 029cd71..76328f4 100644 --- a/dali-toolkit/internal/visuals/arc/arc-visual.cpp +++ b/dali-toolkit/internal/visuals/arc/arc-visual.cpp @@ -22,53 +22,49 @@ #include //INTERNAL INCLUDES -#include #include -#include +#include +#include +#include #include +#include #include -#include -#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // cap -DALI_ENUM_TO_STRING_TABLE_BEGIN( CAP ) -DALI_ENUM_TO_STRING_WITH_SCOPE( DevelArcVisual::Cap, BUTT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( DevelArcVisual::Cap, ROUND ) -DALI_ENUM_TO_STRING_TABLE_END( CAP ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(CAP) + DALI_ENUM_TO_STRING_WITH_SCOPE(DevelArcVisual::Cap, BUTT) + DALI_ENUM_TO_STRING_WITH_SCOPE(DevelArcVisual::Cap, ROUND) +DALI_ENUM_TO_STRING_TABLE_END(CAP) -} +} // namespace -ArcVisualPtr ArcVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +ArcVisualPtr ArcVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - ArcVisualPtr arcVisualPtr( new ArcVisual( factoryCache ) ); - arcVisualPtr->SetProperties( properties ); + ArcVisualPtr arcVisualPtr(new ArcVisual(factoryCache)); + arcVisualPtr->SetProperties(properties); arcVisualPtr->Initialize(); return arcVisualPtr; } -ArcVisual::ArcVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FILL, static_cast( Toolkit::DevelVisual::ARC ) ), - mThickness( 0.0f ), - mRadius( 0.0f ), - mStartAngle( 0.0f ), - mSweepAngle( 360.0f ), - mRadiusIndex( Property::INVALID_INDEX ), - mThicknessIndex( Property::INVALID_INDEX ), - mStartAngleIndex( Property::INVALID_INDEX ), - mSweepAngleIndex( Property::INVALID_INDEX ), - mCapType( DevelArcVisual::Cap::BUTT ) +ArcVisual::ArcVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FILL, static_cast(Toolkit::DevelVisual::ARC)), + mThickness(0.0f), + mRadius(0.0f), + mStartAngle(0.0f), + mSweepAngle(360.0f), + mRadiusIndex(Property::INVALID_INDEX), + mThicknessIndex(Property::INVALID_INDEX), + mStartAngleIndex(Property::INVALID_INDEX), + mSweepAngleIndex(Property::INVALID_INDEX), + mCapType(DevelArcVisual::Cap::BUTT) { } @@ -76,20 +72,20 @@ ArcVisual::~ArcVisual() { } -void ArcVisual::DoSetProperties( const Property::Map& propertyMap ) +void ArcVisual::DoSetProperties(const Property::Map& propertyMap) { - Property::Value* thicknessValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::THICKNESS, THICKNESS_NAME ); - if( thicknessValue ) + Property::Value* thicknessValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::THICKNESS, THICKNESS_NAME); + if(thicknessValue) { - if( !thicknessValue->Get( mThickness ) ) + if(!thicknessValue->Get(mThickness)) { - DALI_LOG_ERROR( "ArcVisual:DoSetProperties:: THICKNESS property has incorrect type: %d\n", thicknessValue->GetType() ); + DALI_LOG_ERROR("ArcVisual:DoSetProperties:: THICKNESS property has incorrect type: %d\n", thicknessValue->GetType()); } else { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( mThicknessIndex, mThickness ); + mImpl->mRenderer.SetProperty(mThicknessIndex, mThickness); // Need to calculate radius again OnSetTransform(); @@ -97,53 +93,53 @@ void ArcVisual::DoSetProperties( const Property::Map& propertyMap ) } } - Property::Value* startAngleValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::START_ANGLE, START_ANGLE_NAME ); - if( startAngleValue ) + Property::Value* startAngleValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::START_ANGLE, START_ANGLE_NAME); + if(startAngleValue) { - if( !startAngleValue->Get( mStartAngle ) ) + if(!startAngleValue->Get(mStartAngle)) { - DALI_LOG_ERROR( "ArcVisual:DoSetProperties:: START_ANGLE property has incorrect type: %d\n", startAngleValue->GetType() ); + DALI_LOG_ERROR("ArcVisual:DoSetProperties:: START_ANGLE property has incorrect type: %d\n", startAngleValue->GetType()); } else { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( mStartAngleIndex, mStartAngle ); + mImpl->mRenderer.SetProperty(mStartAngleIndex, mStartAngle); } } } - Property::Value* sweepAngleValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::SWEEP_ANGLE, SWEEP_ANGLE_NAME ); - if( sweepAngleValue ) + Property::Value* sweepAngleValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::SWEEP_ANGLE, SWEEP_ANGLE_NAME); + if(sweepAngleValue) { - if( !sweepAngleValue->Get( mSweepAngle ) ) + if(!sweepAngleValue->Get(mSweepAngle)) { - DALI_LOG_ERROR( "ArcVisual:DoSetProperties:: SWEEP_ANGLE property has incorrect type: %d\n", sweepAngleValue->GetType() ); + DALI_LOG_ERROR("ArcVisual:DoSetProperties:: SWEEP_ANGLE property has incorrect type: %d\n", sweepAngleValue->GetType()); } else { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( mSweepAngleIndex, mSweepAngle ); + mImpl->mRenderer.SetProperty(mSweepAngleIndex, mSweepAngle); } } } - Property::Value* capValue = propertyMap.Find( Toolkit::DevelArcVisual::Property::CAP, CAP_NAME ); - if( capValue ) + Property::Value* capValue = propertyMap.Find(Toolkit::DevelArcVisual::Property::CAP, CAP_NAME); + if(capValue) { int capType = 0; - Scripting::GetEnumerationProperty( *capValue, CAP_TABLE, CAP_TABLE_COUNT, capType ); - mCapType = Toolkit::DevelArcVisual::Cap::Type( capType ); + Scripting::GetEnumerationProperty(*capValue, CAP_TABLE, CAP_TABLE_COUNT, capType); + mCapType = Toolkit::DevelArcVisual::Cap::Type(capType); } } -void ArcVisual::DoSetOnScene( Actor& actor ) +void ArcVisual::DoSetOnScene(Actor& actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // Arc Visual generated and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } void ArcVisual::DoSetOffScene(Actor& actor) @@ -151,7 +147,7 @@ void ArcVisual::DoSetOffScene(Actor& actor) actor.RemoveRenderer(mImpl->mRenderer); } -void ArcVisual::DoCreatePropertyMap( Property::Map& map ) const +void ArcVisual::DoCreatePropertyMap(Property::Map& map) const { float thickness, startAngle, sweepAngle; if(mImpl->mRenderer) @@ -169,40 +165,40 @@ void ArcVisual::DoCreatePropertyMap( Property::Map& map ) const } map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ARC ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::DevelVisual::ARC); map.Insert(Toolkit::DevelArcVisual::Property::THICKNESS, thickness); map.Insert(Toolkit::DevelArcVisual::Property::START_ANGLE, startAngle); map.Insert(Toolkit::DevelArcVisual::Property::SWEEP_ANGLE, sweepAngle); - map.Insert( Toolkit::DevelArcVisual::Property::CAP, mCapType ); + map.Insert(Toolkit::DevelArcVisual::Property::CAP, mCapType); } -void ArcVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void ArcVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } void ArcVisual::OnSetTransform() { - Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize ); - mRadius = ( std::min( visualSize.width, visualSize.height ) - mThickness ) / 2.0f; + Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize); + mRadius = (std::min(visualSize.width, visualSize.height) - mThickness) / 2.0f; - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( mRadiusIndex, mRadius ); + mImpl->mRenderer.SetProperty(mRadiusIndex, mRadius); } } -void ArcVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes ) +void ArcVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes) { // Check if action is valid for this visual type and perform action if possible - switch( actionId ) + switch(actionId) { case DevelArcVisual::Action::UPDATE_PROPERTY: { const Property::Map* map = attributes.GetMap(); - if( map ) + if(map) { - DoSetProperties( *map ); + DoSetProperties(*map); } break; } @@ -211,40 +207,40 @@ void ArcVisual::OnDoAction( const Property::Index actionId, const Property::Valu void ArcVisual::OnInitialize() { - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); Shader shader; - if( mCapType == DevelArcVisual::Cap::BUTT ) + if(mCapType == DevelArcVisual::Cap::BUTT) { - shader = mFactoryCache.GetShader( VisualFactoryCache::ARC_BUTT_CAP_SHADER ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::ARC_BUTT_CAP_SHADER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_BUTT_CAP_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::ARC_BUTT_CAP_SHADER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_BUTT_CAP_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::ARC_BUTT_CAP_SHADER, shader); } } else { - shader = mFactoryCache.GetShader( VisualFactoryCache::ARC_ROUND_CAP_SHADER ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::ARC_ROUND_CAP_SHADER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_ROUND_CAP_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::ARC_ROUND_CAP_SHADER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_ARC_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_ARC_VISUAL_ROUND_CAP_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::ARC_ROUND_CAP_SHADER, shader); } } - mImpl->mRenderer = Renderer::New( geometry, shader ); + mImpl->mRenderer = Renderer::New(geometry, shader); mThicknessIndex = mImpl->mRenderer.RegisterProperty(DevelArcVisual::Property::THICKNESS, THICKNESS_NAME, mThickness); mStartAngleIndex = mImpl->mRenderer.RegisterProperty(DevelArcVisual::Property::START_ANGLE, START_ANGLE_NAME, mStartAngle); mSweepAngleIndex = mImpl->mRenderer.RegisterProperty(DevelArcVisual::Property::SWEEP_ANGLE, SWEEP_ANGLE_NAME, mSweepAngle); - mRadiusIndex = mImpl->mRenderer.RegisterProperty( RADIUS_NAME, mRadius ); + mRadiusIndex = mImpl->mRenderer.RegisterProperty(RADIUS_NAME, mRadius); - mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON ); + mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); // Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/border/border-visual.cpp b/dali-toolkit/internal/visuals/border/border-visual.cpp index 4146b80..e0e5830 100644 --- a/dali-toolkit/internal/visuals/border/border-visual.cpp +++ b/dali-toolkit/internal/visuals/border/border-visual.cpp @@ -19,49 +19,46 @@ #include "border-visual.h" // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES -#include -#include -#include +#include +#include #include +#include #include -#include -#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { -const char * const POSITION_ATTRIBUTE_NAME("aPosition"); -const char * const DRIFT_ATTRIBUTE_NAME("aDrift"); -const char * const INDEX_NAME("indices"); -} +const char* const POSITION_ATTRIBUTE_NAME("aPosition"); +const char* const DRIFT_ATTRIBUTE_NAME("aDrift"); +const char* const INDEX_NAME("indices"); +} // namespace -BorderVisualPtr BorderVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +BorderVisualPtr BorderVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - BorderVisualPtr borderVisualPtr( new BorderVisual( factoryCache ) ); - borderVisualPtr->SetProperties( properties ); + BorderVisualPtr borderVisualPtr(new BorderVisual(factoryCache)); + borderVisualPtr->SetProperties(properties); borderVisualPtr->Initialize(); return borderVisualPtr; } -BorderVisual::BorderVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::BORDER ), - mBorderColor( Color::TRANSPARENT ), - mBorderSize( 0.f ), - mBorderColorIndex( Property::INVALID_INDEX ), - mBorderSizeIndex( Property::INVALID_INDEX ), - mAntiAliasing( false ) +BorderVisual::BorderVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::BORDER), + mBorderColor(Color::TRANSPARENT), + mBorderSize(0.f), + mBorderColorIndex(Property::INVALID_INDEX), + mBorderSizeIndex(Property::INVALID_INDEX), + mAntiAliasing(false) { } @@ -69,41 +66,41 @@ BorderVisual::~BorderVisual() { } -void BorderVisual::DoSetProperties( const Property::Map& propertyMap ) +void BorderVisual::DoSetProperties(const Property::Map& propertyMap) { - for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter ) + for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter) { - KeyValuePair keyValue = propertyMap.GetKeyValue( iter ); - if( keyValue.first.type == Property::Key::INDEX ) + KeyValuePair keyValue = propertyMap.GetKeyValue(iter); + if(keyValue.first.type == Property::Key::INDEX) { - DoSetProperty( keyValue.first.indexKey, keyValue.second ); + DoSetProperty(keyValue.first.indexKey, keyValue.second); } else { - if( keyValue.first == COLOR_NAME ) + if(keyValue.first == COLOR_NAME) { - DoSetProperty( Toolkit::BorderVisual::Property::COLOR, keyValue.second ); + DoSetProperty(Toolkit::BorderVisual::Property::COLOR, keyValue.second); } - else if( keyValue.first == SIZE_NAME ) + else if(keyValue.first == SIZE_NAME) { - DoSetProperty( Toolkit::BorderVisual::Property::SIZE, keyValue.second ); + DoSetProperty(Toolkit::BorderVisual::Property::SIZE, keyValue.second); } - else if( keyValue.first == ANTI_ALIASING ) + else if(keyValue.first == ANTI_ALIASING) { - DoSetProperty( Toolkit::BorderVisual::Property::ANTI_ALIASING, keyValue.second ); + DoSetProperty(Toolkit::BorderVisual::Property::ANTI_ALIASING, keyValue.second); } } } } -void BorderVisual::DoSetProperty( Dali::Property::Index index, - const Dali::Property::Value& value ) +void BorderVisual::DoSetProperty(Dali::Property::Index index, + const Dali::Property::Value& value) { - switch( index ) + switch(index) { case Toolkit::BorderVisual::Property::COLOR: { - if( !value.Get( mBorderColor ) ) + if(!value.Get(mBorderColor)) { DALI_LOG_ERROR("BorderVisual: borderColor property has incorrect type\n"); } @@ -111,7 +108,7 @@ void BorderVisual::DoSetProperty( Dali::Property::Index index, } case Toolkit::BorderVisual::Property::SIZE: { - if( !value.Get( mBorderSize ) ) + if(!value.Get(mBorderSize)) { DALI_LOG_ERROR("BorderVisual: borderSize property has incorrect type\n"); } @@ -119,7 +116,7 @@ void BorderVisual::DoSetProperty( Dali::Property::Index index, } case Toolkit::BorderVisual::Property::ANTI_ALIASING: { - if( !value.Get( mAntiAliasing ) ) + if(!value.Get(mAntiAliasing)) { DALI_LOG_ERROR("BorderVisual: antiAliasing property has incorrect type\n"); } @@ -128,78 +125,78 @@ void BorderVisual::DoSetProperty( Dali::Property::Index index, } } -void BorderVisual::DoSetOnScene( Actor& actor ) +void BorderVisual::DoSetOnScene(Actor& actor) { - mBorderColorIndex = mImpl->mRenderer.RegisterProperty( Toolkit::BorderVisual::Property::COLOR, COLOR_NAME, mBorderColor ); - if( mBorderColor.a < 1.f || mAntiAliasing ) + mBorderColorIndex = mImpl->mRenderer.RegisterProperty(Toolkit::BorderVisual::Property::COLOR, COLOR_NAME, mBorderColor); + if(mBorderColor.a < 1.f || mAntiAliasing) { - mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON ); + mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); } - mBorderSizeIndex = mImpl->mRenderer.RegisterProperty( Toolkit::BorderVisual::Property::SIZE, SIZE_NAME, mBorderSize ); + mBorderSizeIndex = mImpl->mRenderer.RegisterProperty(Toolkit::BorderVisual::Property::SIZE, SIZE_NAME, mBorderSize); - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // Border Visual Generated and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } -void BorderVisual::DoCreatePropertyMap( Property::Map& map ) const +void BorderVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::BORDER ); - map.Insert( Toolkit::BorderVisual::Property::COLOR, mBorderColor ); - map.Insert( Toolkit::BorderVisual::Property::SIZE, mBorderSize ); - map.Insert( Toolkit::BorderVisual::Property::ANTI_ALIASING, mAntiAliasing ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::BORDER); + map.Insert(Toolkit::BorderVisual::Property::COLOR, mBorderColor); + map.Insert(Toolkit::BorderVisual::Property::SIZE, mBorderSize); + map.Insert(Toolkit::BorderVisual::Property::ANTI_ALIASING, mAntiAliasing); } -void BorderVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void BorderVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } void BorderVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } void BorderVisual::OnInitialize() { - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::BORDER_GEOMETRY ); - if( !geometry ) + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::BORDER_GEOMETRY); + if(!geometry) { - geometry = CreateBorderGeometry(); - mFactoryCache.SaveGeometry( VisualFactoryCache::BORDER_GEOMETRY, geometry ); + geometry = CreateBorderGeometry(); + mFactoryCache.SaveGeometry(VisualFactoryCache::BORDER_GEOMETRY, geometry); } - Shader shader = GetBorderShader(); - mImpl->mRenderer = Renderer::New( geometry, shader ); + Shader shader = GetBorderShader(); + mImpl->mRenderer = Renderer::New(geometry, shader); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } Shader BorderVisual::GetBorderShader() { Shader shader; - if( mAntiAliasing ) + if(mAntiAliasing) { - shader = mFactoryCache.GetShader( VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_ANTI_ALIASING_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::BORDER_SHADER_ANTI_ALIASING, shader); } } else { - shader = mFactoryCache.GetShader( VisualFactoryCache::BORDER_SHADER ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::BORDER_SHADER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::BORDER_SHADER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_BORDER_VISUAL_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::BORDER_SHADER, shader); } } @@ -224,46 +221,50 @@ Shader BorderVisual::GetBorderShader() */ Geometry BorderVisual::CreateBorderGeometry() { - const float halfWidth = 0.5f; + const float halfWidth = 0.5f; const float halfHeight = 0.5f; - struct BorderVertex { Vector2 position; Vector2 drift;}; - BorderVertex borderVertexData[16] = + struct BorderVertex { - { Vector2(-halfWidth, -halfHeight), Vector2(0.f, 0.f) }, - { Vector2(-halfWidth, -halfHeight), Vector2(1.f, 0.f) }, - { Vector2(halfWidth, -halfHeight), Vector2(-1.f, 0.f) }, - { Vector2(halfWidth, -halfHeight), Vector2(0.f, 0.f) }, - - { Vector2(-halfWidth, -halfHeight), Vector2(0.f, 1.f) }, - { Vector2(-halfWidth, -halfHeight), Vector2(1.f, 1.f) }, - { Vector2(halfWidth, -halfHeight), Vector2(-1.f, 1.f) }, - { Vector2(halfWidth, -halfHeight), Vector2(0.f, 1.f) }, - - { Vector2(-halfWidth, halfHeight), Vector2(0.f, -1.f) }, - { Vector2(-halfWidth, halfHeight), Vector2(1.f, -1.f) }, - { Vector2(halfWidth, halfHeight), Vector2(-1.f, -1.f) }, - { Vector2(halfWidth, halfHeight), Vector2(0.f, -1.f) }, - - { Vector2(-halfWidth, halfHeight), Vector2(0.f, 0.f) }, - { Vector2(-halfWidth, halfHeight), Vector2(1.f, 0.f) }, - { Vector2(halfWidth, halfHeight), Vector2(-1.f, 0.f) }, - { Vector2(halfWidth, halfHeight), Vector2(0.f, 0.f) }, + Vector2 position; + Vector2 drift; }; + BorderVertex borderVertexData[16] = + { + {Vector2(-halfWidth, -halfHeight), Vector2(0.f, 0.f)}, + {Vector2(-halfWidth, -halfHeight), Vector2(1.f, 0.f)}, + {Vector2(halfWidth, -halfHeight), Vector2(-1.f, 0.f)}, + {Vector2(halfWidth, -halfHeight), Vector2(0.f, 0.f)}, + + {Vector2(-halfWidth, -halfHeight), Vector2(0.f, 1.f)}, + {Vector2(-halfWidth, -halfHeight), Vector2(1.f, 1.f)}, + {Vector2(halfWidth, -halfHeight), Vector2(-1.f, 1.f)}, + {Vector2(halfWidth, -halfHeight), Vector2(0.f, 1.f)}, + + {Vector2(-halfWidth, halfHeight), Vector2(0.f, -1.f)}, + {Vector2(-halfWidth, halfHeight), Vector2(1.f, -1.f)}, + {Vector2(halfWidth, halfHeight), Vector2(-1.f, -1.f)}, + {Vector2(halfWidth, halfHeight), Vector2(0.f, -1.f)}, + + {Vector2(-halfWidth, halfHeight), Vector2(0.f, 0.f)}, + {Vector2(-halfWidth, halfHeight), Vector2(1.f, 0.f)}, + {Vector2(halfWidth, halfHeight), Vector2(-1.f, 0.f)}, + {Vector2(halfWidth, halfHeight), Vector2(0.f, 0.f)}, + }; Property::Map borderVertexFormat; borderVertexFormat[POSITION_ATTRIBUTE_NAME] = Property::VECTOR2; - borderVertexFormat[DRIFT_ATTRIBUTE_NAME] = Property::VECTOR2; - VertexBuffer borderVertices = VertexBuffer::New( borderVertexFormat ); - borderVertices.SetData( borderVertexData, 16 ); + borderVertexFormat[DRIFT_ATTRIBUTE_NAME] = Property::VECTOR2; + VertexBuffer borderVertices = VertexBuffer::New(borderVertexFormat); + borderVertices.SetData(borderVertexData, 16); // Create indices - unsigned short indexData[24] = { 1,5,2,6,3,7,7,6,11,10,15,14,14,10,13,9,12,8,8,9,4,5,0,1}; + unsigned short indexData[24] = {1, 5, 2, 6, 3, 7, 7, 6, 11, 10, 15, 14, 14, 10, 13, 9, 12, 8, 8, 9, 4, 5, 0, 1}; // Create the geometry object Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( borderVertices ); - geometry.SetIndexBuffer( indexData, sizeof(indexData)/sizeof(indexData[0]) ); - geometry.SetType( Geometry::TRIANGLE_STRIP ); + geometry.AddVertexBuffer(borderVertices); + geometry.SetIndexBuffer(indexData, sizeof(indexData) / sizeof(indexData[0])); + geometry.SetType(Geometry::TRIANGLE_STRIP); return geometry; } diff --git a/dali-toolkit/internal/visuals/color/color-visual.cpp b/dali-toolkit/internal/visuals/color/color-visual.cpp index 77b0be0..9ce3a29 100644 --- a/dali-toolkit/internal/visuals/color/color-visual.cpp +++ b/dali-toolkit/internal/visuals/color/color-visual.cpp @@ -19,33 +19,30 @@ #include "color-visual.h" // EXTERNAL INCLUDES -#include #include +#include //INTERNAL INCLUDES -#include -#include -#include #include -#include +#include +#include +#include #include +#include #include -#include -#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - -ColorVisualPtr ColorVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +ColorVisualPtr ColorVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - ColorVisualPtr colorVisualPtr( new ColorVisual( factoryCache ) ); - colorVisualPtr->SetProperties( properties ); + ColorVisualPtr colorVisualPtr(new ColorVisual(factoryCache)); + colorVisualPtr->SetProperties(properties); colorVisualPtr->Initialize(); return colorVisualPtr; } @@ -63,25 +60,25 @@ ColorVisual::~ColorVisual() { } -void ColorVisual::DoSetProperties( const Property::Map& propertyMap ) +void ColorVisual::DoSetProperties(const Property::Map& propertyMap) { // By virtue of DoSetProperties being called last, this will override // anything set by Toolkit::Visual::Property::MIX_COLOR - Property::Value* colorValue = propertyMap.Find( Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR ); - if( colorValue ) + Property::Value* colorValue = propertyMap.Find(Toolkit::ColorVisual::Property::MIX_COLOR, MIX_COLOR); + if(colorValue) { Vector4 color; - if( colorValue->Get( color ) ) + if(colorValue->Get(color)) { Property::Type type = colorValue->GetType(); - if( type == Property::VECTOR4 ) + if(type == Property::VECTOR4) { - SetMixColor( color ); + SetMixColor(color); } - else if( type == Property::VECTOR3 ) + else if(type == Property::VECTOR3) { Vector3 color3(color); - SetMixColor( color3 ); + SetMixColor(color3); } } else @@ -90,36 +87,36 @@ void ColorVisual::DoSetProperties( const Property::Map& propertyMap ) } } - Property::Value* renderIfTransparentValue = propertyMap.Find( Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, RENDER_IF_TRANSPARENT_NAME ); - if( renderIfTransparentValue ) + Property::Value* renderIfTransparentValue = propertyMap.Find(Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, RENDER_IF_TRANSPARENT_NAME); + if(renderIfTransparentValue) { - if( ! renderIfTransparentValue->Get( mRenderIfTransparent ) ) + if(!renderIfTransparentValue->Get(mRenderIfTransparent)) { - DALI_LOG_ERROR( "ColorVisual: renderIfTransparent property has incorrect type: %d\n", renderIfTransparentValue->GetType() ); + DALI_LOG_ERROR("ColorVisual: renderIfTransparent property has incorrect type: %d\n", renderIfTransparentValue->GetType()); } } - Property::Value* blurRadiusValue = propertyMap.Find( Toolkit::DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME ); - if( blurRadiusValue ) + Property::Value* blurRadiusValue = propertyMap.Find(Toolkit::DevelColorVisual::Property::BLUR_RADIUS, BLUR_RADIUS_NAME); + if(blurRadiusValue) { - if( !blurRadiusValue->Get( mBlurRadius ) ) + if(!blurRadiusValue->Get(mBlurRadius)) { - DALI_LOG_ERROR( "ColorVisual:DoSetProperties:: BLUR_RADIUS property has incorrect type: %d\n", blurRadiusValue->GetType() ); + DALI_LOG_ERROR("ColorVisual:DoSetProperties:: BLUR_RADIUS property has incorrect type: %d\n", blurRadiusValue->GetType()); } } } -void ColorVisual::DoSetOnScene( Actor& actor ) +void ColorVisual::DoSetOnScene(Actor& actor) { // Only add the renderer if it's not fully transparent // We cannot avoid creating a renderer as it's used in the base class - if( mRenderIfTransparent || mImpl->mMixColor.a > 0.0f ) + if(mRenderIfTransparent || mImpl->mMixColor.a > 0.0f) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); } // Color Visual generated and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } void ColorVisual::DoSetOffScene(Actor& actor) @@ -127,12 +124,12 @@ void ColorVisual::DoSetOffScene(Actor& actor) actor.RemoveRenderer(mImpl->mRenderer); } -void ColorVisual::DoCreatePropertyMap( Property::Map& map ) const +void ColorVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR ); - map.Insert( Toolkit::ColorVisual::Property::MIX_COLOR, mImpl->mMixColor ); - map.Insert( Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, mRenderIfTransparent ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR); + map.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, mImpl->mMixColor); + map.Insert(Toolkit::DevelColorVisual::Property::RENDER_IF_TRANSPARENT, mRenderIfTransparent); if(mImpl->mRenderer && mBlurRadiusIndex != Property::INVALID_INDEX) { @@ -146,30 +143,30 @@ void ColorVisual::DoCreatePropertyMap( Property::Map& map ) const } } -void ColorVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void ColorVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } void ColorVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } -void ColorVisual::OnDoAction( const Property::Index actionId, const Property::Value& attributes ) +void ColorVisual::OnDoAction(const Property::Index actionId, const Property::Value& attributes) { // Check if action is valid for this visual type and perform action if possible - switch( actionId ) + switch(actionId) { case DevelColorVisual::Action::UPDATE_PROPERTY: { const Property::Map* map = attributes.GetMap(); - if( map ) + if(map) { - DoSetProperties( *map ); + DoSetProperties(*map); } break; } @@ -187,7 +184,7 @@ void ColorVisual::UpdateShader() void ColorVisual::OnInitialize() { - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); Shader shader = GetShader(); @@ -213,29 +210,29 @@ Shader ColorVisual::GetShader() Shader shader; if(!EqualsZero(mBlurRadius) || mNeedBlurRadius) { - shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER_BLUR_EDGE ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER_BLUR_EDGE); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER_BLUR_EDGE, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_BLUR_EDGE_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER_BLUR_EDGE, shader); } } - else if( !IsRoundedCornerRequired() ) + else if(!IsRoundedCornerRequired()) { - shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER, shader); } } else { - shader = mFactoryCache.GetShader( VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER ); - if( !shader ) + shader = mFactoryCache.GetShader(VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data() ); - mFactoryCache.SaveShader( VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), Dali::Shader::GetFragmentShaderPrefix() + SHADER_COLOR_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data()); + mFactoryCache.SaveShader(VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, shader); } } diff --git a/dali-toolkit/internal/visuals/gradient/gradient-visual.cpp b/dali-toolkit/internal/visuals/gradient/gradient-visual.cpp index 96f9f85..b122359 100644 --- a/dali-toolkit/internal/visuals/gradient/gradient-visual.cpp +++ b/dali-toolkit/internal/visuals/gradient/gradient-visual.cpp @@ -19,23 +19,15 @@ #include "gradient-visual.h" // EXTERNAL INCLUDES -#include +#include +#include +#include #include #include #include -#include -#include -#include +#include // INTERNAL INCLUDES -#include -#include -#include -#include -#include -#include -#include -#include #include #include #include @@ -44,84 +36,81 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { +DALI_ENUM_TO_STRING_TABLE_BEGIN(UNITS) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::Units, OBJECT_BOUNDING_BOX) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::Units, USER_SPACE) +DALI_ENUM_TO_STRING_TABLE_END(UNITS) -DALI_ENUM_TO_STRING_TABLE_BEGIN( UNITS ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::Units, OBJECT_BOUNDING_BOX ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::Units, USER_SPACE ) -DALI_ENUM_TO_STRING_TABLE_END( UNITS ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( SPREAD_METHOD ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::SpreadMethod, PAD ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::SpreadMethod, REFLECT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::GradientVisual::SpreadMethod, REPEAT ) -DALI_ENUM_TO_STRING_TABLE_END( SPREAD_METHOD ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(SPREAD_METHOD) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::SpreadMethod, PAD) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::SpreadMethod, REFLECT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::GradientVisual::SpreadMethod, REPEAT) +DALI_ENUM_TO_STRING_TABLE_END(SPREAD_METHOD) // uniform names -const char * const UNIFORM_ALIGNMENT_MATRIX_NAME( "uAlignmentMatrix" ); +const char* const UNIFORM_ALIGNMENT_MATRIX_NAME("uAlignmentMatrix"); // default offset value const unsigned int DEFAULT_OFFSET_MINIMUM = 0.0f; const unsigned int DEFAULT_OFFSET_MAXIMUM = 1.0f; VisualFactoryCache::ShaderType SHADER_TYPE_TABLE[][4] = -{ - { - VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE, - VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX, - VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE_ROUNDED_CORNER, - VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX_ROUNDED_CORNER - }, { - VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE, - VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX, - VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE_ROUNDED_CORNER, - VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX_ROUNDED_CORNER - } -}; + {VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE, + VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX, + VisualFactoryCache::GRADIENT_SHADER_LINEAR_USER_SPACE_ROUNDED_CORNER, + VisualFactoryCache::GRADIENT_SHADER_LINEAR_BOUNDING_BOX_ROUNDED_CORNER}, + {VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE, + VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX, + VisualFactoryCache::GRADIENT_SHADER_RADIAL_USER_SPACE_ROUNDED_CORNER, + VisualFactoryCache::GRADIENT_SHADER_RADIAL_BOUNDING_BOX_ROUNDED_CORNER}}; const std::string_view VERTEX_SHADER[] = -{ - // vertex shader for gradient units as OBJECT_BOUNDING_BOX - SHADER_GRADIENT_VISUAL_BOUNDING_BOX_SHADER_VERT, + { + // vertex shader for gradient units as OBJECT_BOUNDING_BOX + SHADER_GRADIENT_VISUAL_BOUNDING_BOX_SHADER_VERT, - // vertex shader for gradient units as USER_SPACE - SHADER_GRADIENT_VISUAL_USER_SPACE_SHADER_VERT, + // vertex shader for gradient units as USER_SPACE + SHADER_GRADIENT_VISUAL_USER_SPACE_SHADER_VERT, - // vertex shader for gradient units as OBJECT_BOUNDING_BOX with corner radius - SHADER_GRADIENT_VISUAL_BOUNDING_BOX_ROUNDED_CORNER_SHADER_VERT, + // vertex shader for gradient units as OBJECT_BOUNDING_BOX with corner radius + SHADER_GRADIENT_VISUAL_BOUNDING_BOX_ROUNDED_CORNER_SHADER_VERT, - // vertex shader for gradient units as USER_SPACE with corner radius - SHADER_GRADIENT_VISUAL_USER_SPACE_ROUNDED_CORNER_SHADER_VERT -}; + // vertex shader for gradient units as USER_SPACE with corner radius + SHADER_GRADIENT_VISUAL_USER_SPACE_ROUNDED_CORNER_SHADER_VERT}; const std::string_view FRAGMENT_SHADER[] = -{ - // fragment shader for linear gradient - SHADER_GRADIENT_VISUAL_LINEAR_SHADER_FRAG, + { + // fragment shader for linear gradient + SHADER_GRADIENT_VISUAL_LINEAR_SHADER_FRAG, - // fragment shader for radial gradient - SHADER_GRADIENT_VISUAL_RADIAL_SHADER_FRAG, + // fragment shader for radial gradient + SHADER_GRADIENT_VISUAL_RADIAL_SHADER_FRAG, - // fragment shader for linear gradient with corner radius - SHADER_GRADIENT_VISUAL_LINEAR_ROUNDED_CORNER_SHADER_FRAG, + // fragment shader for linear gradient with corner radius + SHADER_GRADIENT_VISUAL_LINEAR_ROUNDED_CORNER_SHADER_FRAG, - // fragment shader for radial gradient with corner radius - SHADER_GRADIENT_VISUAL_RADIAL_ROUNDED_CORNER_SHADER_FRAG -}; + // fragment shader for radial gradient with corner radius + SHADER_GRADIENT_VISUAL_RADIAL_ROUNDED_CORNER_SHADER_FRAG}; -Dali::WrapMode::Type GetWrapMode( Toolkit::GradientVisual::SpreadMethod::Type spread ) +Dali::WrapMode::Type GetWrapMode(Toolkit::GradientVisual::SpreadMethod::Type spread) { switch(spread) { @@ -143,18 +132,18 @@ Dali::WrapMode::Type GetWrapMode( Toolkit::GradientVisual::SpreadMethod::Type sp } // unnamed namespace -GradientVisualPtr GradientVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +GradientVisualPtr GradientVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - GradientVisualPtr gradientVisualPtr( new GradientVisual( factoryCache ) ); - gradientVisualPtr->SetProperties( properties ); + GradientVisualPtr gradientVisualPtr(new GradientVisual(factoryCache)); + gradientVisualPtr->SetProperties(properties); gradientVisualPtr->Initialize(); return gradientVisualPtr; } -GradientVisual::GradientVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::GRADIENT ), - mGradientType( LINEAR ), - mIsOpaque( true ) +GradientVisual::GradientVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::GRADIENT), + mGradientType(LINEAR), + mIsOpaque(true) { mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA; } @@ -163,47 +152,47 @@ GradientVisual::~GradientVisual() { } -void GradientVisual::DoSetProperties( const Property::Map& propertyMap ) +void GradientVisual::DoSetProperties(const Property::Map& propertyMap) { Toolkit::GradientVisual::Units::Type gradientUnits = Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX; - Property::Value* unitsValue = propertyMap.Find( Toolkit::GradientVisual::Property::UNITS, UNITS_NAME ); - if( unitsValue ) + Property::Value* unitsValue = propertyMap.Find(Toolkit::GradientVisual::Property::UNITS, UNITS_NAME); + if(unitsValue) { - Scripting::GetEnumerationProperty( *unitsValue, UNITS_TABLE, UNITS_TABLE_COUNT, gradientUnits ); + Scripting::GetEnumerationProperty(*unitsValue, UNITS_TABLE, UNITS_TABLE_COUNT, gradientUnits); } mGradientType = LINEAR; - if( propertyMap.Find( Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME ) ) + if(propertyMap.Find(Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME)) { mGradientType = RADIAL; } - if( NewGradient( mGradientType, propertyMap ) ) + if(NewGradient(mGradientType, propertyMap)) { - mGradient->SetGradientUnits( gradientUnits ); + mGradient->SetGradientUnits(gradientUnits); mGradientTransform = mGradient->GetAlignmentTransform(); } else { - DALI_LOG_ERROR( "Fail to provide valid properties to create a GradientVisual object\n" ); + DALI_LOG_ERROR("Fail to provide valid properties to create a GradientVisual object\n"); } } void GradientVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } -void GradientVisual::DoSetOnScene( Actor& actor ) +void GradientVisual::DoSetOnScene(Actor& actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // Gradient Visual generated and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } void GradientVisual::UpdateShader() @@ -215,96 +204,95 @@ void GradientVisual::UpdateShader() } } -void GradientVisual::DoCreatePropertyMap( Property::Map& map ) const +void GradientVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::GRADIENT ); - map.Insert( Toolkit::GradientVisual::Property::UNITS, mGradient->GetGradientUnits() ); - map.Insert( Toolkit::GradientVisual::Property::SPREAD_METHOD, mGradient->GetSpreadMethod() ); - - const Vector& stops( mGradient->GetStops() ); - Property::Array offsets; - Property::Array colors; - for( unsigned int i=0; iGetGradientUnits()); + map.Insert(Toolkit::GradientVisual::Property::SPREAD_METHOD, mGradient->GetSpreadMethod()); + + const Vector& stops(mGradient->GetStops()); + Property::Array offsets; + Property::Array colors; + for(unsigned int i = 0; i < stops.Count(); i++) { - offsets.PushBack( stops[i].mOffset ); - if( EqualsZero(stops[i].mStopColor.a) ) + offsets.PushBack(stops[i].mOffset); + if(EqualsZero(stops[i].mStopColor.a)) { - colors.PushBack( Vector4::ZERO ); + colors.PushBack(Vector4::ZERO); } else { - colors.PushBack( Vector4( stops[i].mStopColor.r / stops[i].mStopColor.a, - stops[i].mStopColor.g / stops[i].mStopColor.a, - stops[i].mStopColor.b / stops[i].mStopColor.a, - stops[i].mStopColor.a)); + colors.PushBack(Vector4(stops[i].mStopColor.r / stops[i].mStopColor.a, + stops[i].mStopColor.g / stops[i].mStopColor.a, + stops[i].mStopColor.b / stops[i].mStopColor.a, + stops[i].mStopColor.a)); } } - map.Insert( Toolkit::GradientVisual::Property::STOP_OFFSET, offsets ); - map.Insert( Toolkit::GradientVisual::Property::STOP_COLOR, colors ); + map.Insert(Toolkit::GradientVisual::Property::STOP_OFFSET, offsets); + map.Insert(Toolkit::GradientVisual::Property::STOP_COLOR, colors); - if( &typeid( *mGradient ) == &typeid(LinearGradient) ) + if(&typeid(*mGradient) == &typeid(LinearGradient)) { - LinearGradient* gradient = static_cast( mGradient.Get() ); - map.Insert( Toolkit::GradientVisual::Property::START_POSITION, gradient->GetStartPosition() ); - map.Insert( Toolkit::GradientVisual::Property::END_POSITION, gradient->GetEndPosition() ); + LinearGradient* gradient = static_cast(mGradient.Get()); + map.Insert(Toolkit::GradientVisual::Property::START_POSITION, gradient->GetStartPosition()); + map.Insert(Toolkit::GradientVisual::Property::END_POSITION, gradient->GetEndPosition()); } else // if( &typeid( *mGradient ) == &typeid(RadialGradient) ) { - RadialGradient* gradient = static_cast( mGradient.Get() ); - map.Insert( Toolkit::GradientVisual::Property::CENTER, gradient->GetCenter() ); - map.Insert( Toolkit::GradientVisual::Property::RADIUS, gradient->GetRadius() ); + RadialGradient* gradient = static_cast(mGradient.Get()); + map.Insert(Toolkit::GradientVisual::Property::CENTER, gradient->GetCenter()); + map.Insert(Toolkit::GradientVisual::Property::RADIUS, gradient->GetRadius()); } } -void GradientVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void GradientVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } void GradientVisual::OnInitialize() { - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); Shader shader = GetShader(); //Set up the texture set - TextureSet textureSet = TextureSet::New(); + TextureSet textureSet = TextureSet::New(); Dali::Texture lookupTexture = mGradient->GenerateLookupTexture(); - textureSet.SetTexture( 0u, lookupTexture ); - Dali::WrapMode::Type wrap = GetWrapMode( mGradient->GetSpreadMethod() ); - Sampler sampler = Sampler::New(); - sampler.SetWrapMode( wrap, wrap ); - textureSet.SetSampler( 0u, sampler ); + textureSet.SetTexture(0u, lookupTexture); + Dali::WrapMode::Type wrap = GetWrapMode(mGradient->GetSpreadMethod()); + Sampler sampler = Sampler::New(); + sampler.SetWrapMode(wrap, wrap); + textureSet.SetSampler(0u, sampler); - mImpl->mRenderer = Renderer::New( geometry, shader ); - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer = Renderer::New(geometry, shader); + mImpl->mRenderer.SetTextures(textureSet); // If opaque and then no need to have blending - if( mIsOpaque ) + if(mIsOpaque) { - mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::OFF ); + mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::OFF); } - mImpl->mRenderer.RegisterProperty( UNIFORM_ALIGNMENT_MATRIX_NAME, mGradientTransform ); + mImpl->mRenderer.RegisterProperty(UNIFORM_ALIGNMENT_MATRIX_NAME, mGradientTransform); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } bool GradientVisual::NewGradient(Type gradientType, const Property::Map& propertyMap) { - if( gradientType == LINEAR ) + if(gradientType == LINEAR) { - Property::Value* startPositionValue = propertyMap.Find( Toolkit::GradientVisual::Property::START_POSITION, START_POSITION_NAME ); - Property::Value* endPositionValue = propertyMap.Find( Toolkit::GradientVisual::Property::END_POSITION, END_POSITION_NAME ); - Vector2 startPosition; - Vector2 endPosition; + Property::Value* startPositionValue = propertyMap.Find(Toolkit::GradientVisual::Property::START_POSITION, START_POSITION_NAME); + Property::Value* endPositionValue = propertyMap.Find(Toolkit::GradientVisual::Property::END_POSITION, END_POSITION_NAME); + Vector2 startPosition; + Vector2 endPosition; - if( startPositionValue && startPositionValue->Get(startPosition) - && endPositionValue && endPositionValue->Get( endPosition ) ) + if(startPositionValue && startPositionValue->Get(startPosition) && endPositionValue && endPositionValue->Get(endPosition)) { - mGradient = new LinearGradient( startPosition, endPosition ); + mGradient = new LinearGradient(startPosition, endPosition); } else { @@ -313,14 +301,13 @@ bool GradientVisual::NewGradient(Type gradientType, const Property::Map& propert } else // type==RADIAL { - Property::Value* centerValue = propertyMap.Find( Toolkit::GradientVisual::Property::CENTER, CENTER_NAME ); - Property::Value* radiusValue = propertyMap.Find( Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME ); - Vector2 center; - float radius; - if( centerValue && centerValue->Get(center) - && radiusValue && radiusValue->Get(radius) ) + Property::Value* centerValue = propertyMap.Find(Toolkit::GradientVisual::Property::CENTER, CENTER_NAME); + Property::Value* radiusValue = propertyMap.Find(Toolkit::GradientVisual::Property::RADIUS, RADIUS_NAME); + Vector2 center; + float radius; + if(centerValue && centerValue->Get(center) && radiusValue && radiusValue->Get(radius)) { - mGradient = new RadialGradient( center, radius ); + mGradient = new RadialGradient(center, radius); } else { @@ -328,26 +315,25 @@ bool GradientVisual::NewGradient(Type gradientType, const Property::Map& propert } } - unsigned int numValidStop = 0u; - Property::Value* stopOffsetValue = propertyMap.Find( Toolkit::GradientVisual::Property::STOP_OFFSET, STOP_OFFSET_NAME ); - Property::Value* stopColorValue = propertyMap.Find( Toolkit::GradientVisual::Property::STOP_COLOR, STOP_COLOR_NAME ); - if( stopColorValue ) + unsigned int numValidStop = 0u; + Property::Value* stopOffsetValue = propertyMap.Find(Toolkit::GradientVisual::Property::STOP_OFFSET, STOP_OFFSET_NAME); + Property::Value* stopColorValue = propertyMap.Find(Toolkit::GradientVisual::Property::STOP_COLOR, STOP_COLOR_NAME); + if(stopColorValue) { - Vector offsetArray; + Vector offsetArray; Property::Array* colorArray = stopColorValue->GetArray(); - if( colorArray ) + if(colorArray) { - GetStopOffsets( stopOffsetValue, offsetArray ); - unsigned int numStop = offsetArray.Count() < colorArray->Count() ? - offsetArray.Count() : colorArray->Count(); - Vector4 color; - for( unsigned int i=0; iCount() ? offsetArray.Count() : colorArray->Count(); + Vector4 color; + for(unsigned int i = 0; i < numStop; i++) { - if( (colorArray->GetElementAt(i)).Get(color) ) + if((colorArray->GetElementAt(i)).Get(color)) { - mGradient->AddStop( offsetArray[i], Vector4(color.r*color.a, color.g*color.a, color.b*color.a, color.a)); + mGradient->AddStop(offsetArray[i], Vector4(color.r * color.a, color.g * color.a, color.b * color.a, color.a)); numValidStop++; - if( ! Equals( color.a, 1.0f, Math::MACHINE_EPSILON_1 ) ) + if(!Equals(color.a, 1.0f, Math::MACHINE_EPSILON_1)) { mIsOpaque = false; } @@ -356,19 +342,19 @@ bool GradientVisual::NewGradient(Type gradientType, const Property::Map& propert } } - if( numValidStop < 1u ) // no valid stop + if(numValidStop < 1u) // no valid stop { return false; } - Property::Value* spread = propertyMap.Find( Toolkit::GradientVisual::Property::SPREAD_METHOD, SPREAD_METHOD_NAME ); + Property::Value* spread = propertyMap.Find(Toolkit::GradientVisual::Property::SPREAD_METHOD, SPREAD_METHOD_NAME); // The default spread method is PAD. Only need to set new spread if it's anything else. - if( spread ) + if(spread) { Toolkit::GradientVisual::SpreadMethod::Type spreadMethod = Toolkit::GradientVisual::SpreadMethod::PAD; - if( Scripting::GetEnumerationProperty( *spread, SPREAD_METHOD_TABLE, SPREAD_METHOD_TABLE_COUNT, spreadMethod ) ) + if(Scripting::GetEnumerationProperty(*spread, SPREAD_METHOD_TABLE, SPREAD_METHOD_TABLE_COUNT, spreadMethod)) { - mGradient->SetSpreadMethod( spreadMethod ); + mGradient->SetSpreadMethod(spreadMethod); } } @@ -392,50 +378,49 @@ Shader GradientVisual::GetShader() void GradientVisual::GetStopOffsets(const Property::Value* value, Vector& stopOffsets) { - - if ( value ) // Only check valve type if a valid Property has been passed in + if(value) // Only check valve type if a valid Property has been passed in { - switch ( value->GetType() ) + switch(value->GetType()) { case Property::VECTOR2: { Vector2 offset2; - value->Get( offset2 ); - stopOffsets.PushBack( offset2.x ); - stopOffsets.PushBack( offset2.y ); + value->Get(offset2); + stopOffsets.PushBack(offset2.x); + stopOffsets.PushBack(offset2.y); break; } case Property::VECTOR3: { Vector3 offset3; - value->Get( offset3 ); - stopOffsets.PushBack( offset3.x ); - stopOffsets.PushBack( offset3.y ); - stopOffsets.PushBack( offset3.z ); + value->Get(offset3); + stopOffsets.PushBack(offset3.x); + stopOffsets.PushBack(offset3.y); + stopOffsets.PushBack(offset3.z); break; } case Property::VECTOR4: { Vector4 offset4; - value->Get( offset4 ); - stopOffsets.PushBack( offset4.x ); - stopOffsets.PushBack( offset4.y ); - stopOffsets.PushBack( offset4.z ); - stopOffsets.PushBack( offset4.w ); + value->Get(offset4); + stopOffsets.PushBack(offset4.x); + stopOffsets.PushBack(offset4.y); + stopOffsets.PushBack(offset4.z); + stopOffsets.PushBack(offset4.w); break; } case Property::ARRAY: { const Property::Array* offsetArray = value->GetArray(); - if( offsetArray ) + if(offsetArray) { unsigned int numStop = offsetArray->Count(); - float offset; - for( unsigned int i=0; iGetElementAt(i).Get(offset) ) + if(offsetArray->GetElementAt(i).Get(offset)) { - stopOffsets.PushBack( offset ); + stopOffsets.PushBack(offset); } } } @@ -449,11 +434,11 @@ void GradientVisual::GetStopOffsets(const Property::Value* value, Vector& } } - if ( stopOffsets.Empty() ) + if(stopOffsets.Empty()) { // Set default offset if none set by Property system, need a minimum and maximum - stopOffsets.PushBack( DEFAULT_OFFSET_MINIMUM ); - stopOffsets.PushBack( DEFAULT_OFFSET_MAXIMUM ); + stopOffsets.PushBack(DEFAULT_OFFSET_MINIMUM); + stopOffsets.PushBack(DEFAULT_OFFSET_MAXIMUM); } } diff --git a/dali-toolkit/internal/visuals/gradient/gradient.cpp b/dali-toolkit/internal/visuals/gradient/gradient.cpp index 2c90e52..34da8a6 100644 --- a/dali-toolkit/internal/visuals/gradient/gradient.cpp +++ b/dali-toolkit/internal/visuals/gradient/gradient.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. @@ -17,36 +17,35 @@ #include "gradient.h" -#include // std::sort #include +#include // std::sort namespace { // The maximum width of the lookup texture ( it is a 1-dimension texture with the height as 1 ) const unsigned int MAXIMUM_TEXTURE_RESOLUTION(128u); -} +} // namespace namespace Dali { - namespace Toolkit { - namespace Internal { - Gradient::Gradient() -: mGradientUnits( Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX ), - mSpreadMethod( Toolkit::GradientVisual::SpreadMethod::PAD ) -{} +: mGradientUnits(Toolkit::GradientVisual::Units::OBJECT_BOUNDING_BOX), + mSpreadMethod(Toolkit::GradientVisual::SpreadMethod::PAD) +{ +} Gradient::~Gradient() -{} +{ +} -void Gradient::AddStop( float offset, const Vector4& color ) +void Gradient::AddStop(float offset, const Vector4& color) { // the offset is clamped to the range [0.0, 1.0] - mGradientStops.PushBack( GradientStop( Clamp( offset, 0.f, 1.f ), color) ); + mGradientStops.PushBack(GradientStop(Clamp(offset, 0.f, 1.f), color)); } const Vector& Gradient::GetStops() @@ -54,7 +53,7 @@ const Vector& Gradient::GetStops() return mGradientStops; } -void Gradient::SetGradientUnits( Toolkit::GradientVisual::Units::Type gradientUnits ) +void Gradient::SetGradientUnits(Toolkit::GradientVisual::Units::Type gradientUnits) { mGradientUnits = gradientUnits; } @@ -64,7 +63,7 @@ Toolkit::GradientVisual::Units::Type Gradient::GetGradientUnits() const return mGradientUnits; } -void Gradient::SetSpreadMethod( Toolkit::GradientVisual::SpreadMethod::Type spread ) +void Gradient::SetSpreadMethod(Toolkit::GradientVisual::SpreadMethod::Type spread) { mSpreadMethod = spread; } @@ -90,7 +89,7 @@ const Matrix3& Gradient::GetAlignmentTransform() const */ Dali::Texture Gradient::GenerateLookupTexture() { - std::sort( mGradientStops.Begin(), mGradientStops.End() ); + std::sort(mGradientStops.Begin(), mGradientStops.End()); unsigned int numStops = mGradientStops.Count(); @@ -101,31 +100,29 @@ Dali::Texture Gradient::GenerateLookupTexture() * for REPEAT, mix the two color of the first and last stop to fill the remainder */ bool tempFirstStop = false; - if( mGradientStops[0].mOffset > 0.f ) + if(mGradientStops[0].mOffset > 0.f) { tempFirstStop = true; - Vector4 firstStopColor( mGradientStops[0].mStopColor ); // If spread method is PAD or REFLECT - if( mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT ) + Vector4 firstStopColor(mGradientStops[0].mStopColor); // If spread method is PAD or REFLECT + if(mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT) { - firstStopColor = ( mGradientStops[0].mStopColor * (1.f-mGradientStops[numStops-1].mOffset) - + mGradientStops[numStops-1].mStopColor * mGradientStops[0].mOffset ) - / ( mGradientStops[0].mOffset+1.f-mGradientStops[numStops-1].mOffset); + firstStopColor = (mGradientStops[0].mStopColor * (1.f - mGradientStops[numStops - 1].mOffset) + mGradientStops[numStops - 1].mStopColor * mGradientStops[0].mOffset) / (mGradientStops[0].mOffset + 1.f - mGradientStops[numStops - 1].mOffset); } - mGradientStops.Insert( mGradientStops.Begin(), GradientStop(0.f, firstStopColor) ); + mGradientStops.Insert(mGradientStops.Begin(), GradientStop(0.f, firstStopColor)); numStops++; } bool tempLastStop = false; - if( mGradientStops[numStops-1].mOffset < 1.f ) + if(mGradientStops[numStops - 1].mOffset < 1.f) { tempLastStop = true; - Vector4 lastStopColor( mGradientStops[numStops-1].mStopColor ); // If spread method is PAD or REFLECT - if( mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT ) + Vector4 lastStopColor(mGradientStops[numStops - 1].mStopColor); // If spread method is PAD or REFLECT + if(mSpreadMethod == Toolkit::GradientVisual::SpreadMethod::REPEAT) { lastStopColor = mGradientStops[0].mStopColor; } - mGradientStops.PushBack( GradientStop(1.f, lastStopColor) ); + mGradientStops.PushBack(GradientStop(1.f, lastStopColor)); numStops++; } @@ -134,47 +131,47 @@ Dali::Texture Gradient::GenerateLookupTexture() */ unsigned int resolution = EstimateTextureResolution(); - unsigned int bufferSize = resolution * 4u; - unsigned char* pixels = new unsigned char[ bufferSize ]; - PixelData pixelData = PixelData::New( pixels, bufferSize, resolution, 1u, Pixel::RGBA8888, PixelData::DELETE_ARRAY ); + unsigned int bufferSize = resolution * 4u; + unsigned char* pixels = new unsigned char[bufferSize]; + PixelData pixelData = PixelData::New(pixels, bufferSize, resolution, 1u, Pixel::RGBA8888, PixelData::DELETE_ARRAY); - int segmentStart = 0; - int segmentEnd = 0; - int k = 0; - float length = static_cast(resolution); - for( unsigned int i=0; i(resolution); + for(unsigned int i = 0; i < numStops - 1u; i++) { - segmentEnd = floorf(mGradientStops[i+1].mOffset * length + 0.5f); - if( segmentEnd == segmentStart ) + segmentEnd = floorf(mGradientStops[i + 1].mOffset * length + 0.5f); + if(segmentEnd == segmentStart) { continue; } - float segmentWidth = static_cast(segmentEnd-segmentStart); + float segmentWidth = static_cast(segmentEnd - segmentStart); - for( int j = segmentStart; j(j-segmentStart)/(segmentWidth - 1); - Vector4 currentColor = mGradientStops[i].mStopColor * (1.f-ratio) + mGradientStops[i+1].mStopColor * ratio; - pixels[k*4] = static_cast( 255.f * Clamp( currentColor.r, 0.f, 1.f ) ); - pixels[k*4+1] = static_cast( 255.f * Clamp( currentColor.g, 0.f, 1.f ) ); - pixels[k*4+2] = static_cast( 255.f * Clamp( currentColor.b, 0.f, 1.f ) ); - pixels[k*4+3] = static_cast( 255.f * Clamp( currentColor.a, 0.f, 1.f ) ); + float ratio = static_cast(j - segmentStart) / (segmentWidth - 1); + Vector4 currentColor = mGradientStops[i].mStopColor * (1.f - ratio) + mGradientStops[i + 1].mStopColor * ratio; + pixels[k * 4] = static_cast(255.f * Clamp(currentColor.r, 0.f, 1.f)); + pixels[k * 4 + 1] = static_cast(255.f * Clamp(currentColor.g, 0.f, 1.f)); + pixels[k * 4 + 2] = static_cast(255.f * Clamp(currentColor.b, 0.f, 1.f)); + pixels[k * 4 + 3] = static_cast(255.f * Clamp(currentColor.a, 0.f, 1.f)); k++; } segmentStart = segmentEnd; } - Texture texture = Texture::New( TextureType::TEXTURE_2D, Pixel::RGBA8888, resolution, 1u ); - texture.Upload( pixelData ); + Texture texture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, resolution, 1u); + texture.Upload(pixelData); // remove the stops added temporarily for generating the pixels, as the spread method might get changed later - if( tempLastStop ) + if(tempLastStop) { - mGradientStops.Erase( mGradientStops.Begin()+numStops-1 ); + mGradientStops.Erase(mGradientStops.Begin() + numStops - 1); } - if( tempFirstStop ) + if(tempFirstStop) { - mGradientStops.Erase( mGradientStops.Begin()); + mGradientStops.Erase(mGradientStops.Begin()); } return texture; @@ -183,15 +180,15 @@ Dali::Texture Gradient::GenerateLookupTexture() unsigned int Gradient::EstimateTextureResolution() { float minInterval = 1.0; - for( unsigned int i=0, numStops = mGradientStops.Count(); i minInterval ? minInterval:interval; + float interval = mGradientStops[i + 1].mOffset - mGradientStops[i].mOffset; + minInterval = interval > minInterval ? minInterval : interval; } // Use at least three pixels for each segment between two stops - unsigned int resolution = static_cast(3.f/(minInterval+Math::MACHINE_EPSILON_100)+0.5f); + unsigned int resolution = static_cast(3.f / (minInterval + Math::MACHINE_EPSILON_100) + 0.5f); // Clamp the resolution to handle the overlapping stops - if( resolution > MAXIMUM_TEXTURE_RESOLUTION ) + if(resolution > MAXIMUM_TEXTURE_RESOLUTION) { return MAXIMUM_TEXTURE_RESOLUTION; } diff --git a/dali-toolkit/internal/visuals/gradient/linear-gradient.cpp b/dali-toolkit/internal/visuals/gradient/linear-gradient.cpp index d1453a6..1c428d8 100644 --- a/dali-toolkit/internal/visuals/gradient/linear-gradient.cpp +++ b/dali-toolkit/internal/visuals/gradient/linear-gradient.cpp @@ -19,31 +19,29 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - -LinearGradient::LinearGradient( const Vector2& startPosition, const Vector2& endPosition ) +LinearGradient::LinearGradient(const Vector2& startPosition, const Vector2& endPosition) : Gradient() { - SetStartAndEndPosition( startPosition, endPosition ); + SetStartAndEndPosition(startPosition, endPosition); } LinearGradient::~LinearGradient() -{} +{ +} -void LinearGradient::SetStartAndEndPosition( const Vector2& startPosition, const Vector2& endPosition ) +void LinearGradient::SetStartAndEndPosition(const Vector2& startPosition, const Vector2& endPosition) { mStartPosition = startPosition; - mEndPosition = endPosition; + mEndPosition = endPosition; // Calculate the transform aligning to the gradient line - float dx = mEndPosition.x - mStartPosition.x; - float dy = mEndPosition.y - mStartPosition.y; - Matrix3 alignMatrix( dy, -dx, 0.f, dx, dy, 0.f, mStartPosition.x, mStartPosition.y, 1.f ); + float dx = mEndPosition.x - mStartPosition.x; + float dy = mEndPosition.y - mStartPosition.y; + Matrix3 alignMatrix(dy, -dx, 0.f, dx, dy, 0.f, mStartPosition.x, mStartPosition.y, 1.f); alignMatrix.Invert(); mAlignmentTransform = alignMatrix; diff --git a/dali-toolkit/internal/visuals/gradient/radial-gradient.cpp b/dali-toolkit/internal/visuals/gradient/radial-gradient.cpp index e986612..1abb7da 100644 --- a/dali-toolkit/internal/visuals/gradient/radial-gradient.cpp +++ b/dali-toolkit/internal/visuals/gradient/radial-gradient.cpp @@ -19,29 +19,27 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - -RadialGradient::RadialGradient( const Vector2& center, float radius ) +RadialGradient::RadialGradient(const Vector2& center, float radius) : Gradient() { - SetCenterAndRadius( center, radius ); + SetCenterAndRadius(center, radius); } RadialGradient::~RadialGradient() -{} +{ +} -void RadialGradient::SetCenterAndRadius( const Vector2& center, float radius ) +void RadialGradient::SetCenterAndRadius(const Vector2& center, float radius) { mCenter = center; mRadius = radius; // Calculate the transform aligning to the circle - Matrix3 alignMatrix( mRadius, 0.f, 0.f, 0.f, mRadius, 0.f, mCenter.x, mCenter.y, 1.f ); + Matrix3 alignMatrix(mRadius, 0.f, 0.f, 0.f, mRadius, 0.f, mCenter.x, mCenter.y, 1.f); alignMatrix.Invert(); mAlignmentTransform = alignMatrix; diff --git a/dali-toolkit/internal/visuals/image-atlas-manager.cpp b/dali-toolkit/internal/visuals/image-atlas-manager.cpp index a9a4786..1f634e1 100644 --- a/dali-toolkit/internal/visuals/image-atlas-manager.cpp +++ b/dali-toolkit/internal/visuals/image-atlas-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. @@ -23,22 +23,19 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { -const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); // this size can fit 8 by 8 images of average size 128*128 -const uint32_t MAX_ITEM_SIZE( 512u ); -const uint32_t MAX_ITEM_AREA( MAX_ITEM_SIZE*MAX_ITEM_SIZE ); -} +const uint32_t DEFAULT_ATLAS_SIZE(1024u); // this size can fit 8 by 8 images of average size 128*128 +const uint32_t MAX_ITEM_SIZE(512u); +const uint32_t MAX_ITEM_AREA(MAX_ITEM_SIZE* MAX_ITEM_SIZE); +} // namespace ImageAtlasManager::ImageAtlasManager() -: mBrokenImageUrl( "" ) +: mBrokenImageUrl("") { } @@ -46,33 +43,31 @@ ImageAtlasManager::~ImageAtlasManager() { } -TextureSet ImageAtlasManager::Add( Vector4& textureRect, - const std::string& url, - ImageDimensions& size, - FittingMode::Type fittingMode, - bool orientationCorrection, - AtlasUploadObserver* atlasUploadObserver ) +TextureSet ImageAtlasManager::Add(Vector4& textureRect, + const std::string& url, + ImageDimensions& size, + FittingMode::Type fittingMode, + bool orientationCorrection, + AtlasUploadObserver* atlasUploadObserver) { ImageDimensions dimensions = size; ImageDimensions zero; - if( size == zero ) + if(size == zero) { - dimensions = Dali::GetClosestImageSize( url ); + dimensions = Dali::GetClosestImageSize(url); } // big image, atlasing is not applied - if( static_cast(dimensions.GetWidth()) * static_cast(dimensions.GetHeight()) > MAX_ITEM_AREA - || dimensions.GetWidth()>DEFAULT_ATLAS_SIZE - || dimensions.GetHeight()>DEFAULT_ATLAS_SIZE) + if(static_cast(dimensions.GetWidth()) * static_cast(dimensions.GetHeight()) > MAX_ITEM_AREA || dimensions.GetWidth() > DEFAULT_ATLAS_SIZE || dimensions.GetHeight() > DEFAULT_ATLAS_SIZE) { return TextureSet(); } size = dimensions; unsigned int i = 0; - for( AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter) + for(AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter) { - if( (*iter).Upload( textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver ) ) + if((*iter).Upload(textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver)) { return mTextureSetList[i]; } @@ -80,26 +75,23 @@ TextureSet ImageAtlasManager::Add( Vector4& textureRect, } CreateNewAtlas(); - mAtlasList.back().Upload( textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver ); + mAtlasList.back().Upload(textureRect, url, size, fittingMode, orientationCorrection, atlasUploadObserver); return mTextureSetList.back(); } -TextureSet ImageAtlasManager::Add( Vector4& textureRect, - PixelData pixelData ) +TextureSet ImageAtlasManager::Add(Vector4& textureRect, + PixelData pixelData) { - // big buffer, atlasing is not applied - if( static_cast(pixelData.GetWidth()) * static_cast(pixelData.GetHeight()) > MAX_ITEM_AREA - || pixelData.GetWidth()>DEFAULT_ATLAS_SIZE - || pixelData.GetHeight()>DEFAULT_ATLAS_SIZE ) + if(static_cast(pixelData.GetWidth()) * static_cast(pixelData.GetHeight()) > MAX_ITEM_AREA || pixelData.GetWidth() > DEFAULT_ATLAS_SIZE || pixelData.GetHeight() > DEFAULT_ATLAS_SIZE) { return TextureSet(); } unsigned int i = 0; - for( AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter) + for(AtlasContainer::iterator iter = mAtlasList.begin(); iter != mAtlasList.end(); ++iter) { - if( (*iter).Upload( textureRect, pixelData ) ) + if((*iter).Upload(textureRect, pixelData)) { return mTextureSetList[i]; } @@ -107,17 +99,16 @@ TextureSet ImageAtlasManager::Add( Vector4& textureRect, } CreateNewAtlas(); - mAtlasList.back().Upload( textureRect, pixelData ); + mAtlasList.back().Upload(textureRect, pixelData); return mTextureSetList.back(); - } -void ImageAtlasManager::Remove( TextureSet textureSet, const Vector4& textureRect ) +void ImageAtlasManager::Remove(TextureSet textureSet, const Vector4& textureRect) { unsigned int i = 0; - for( TextureSetContainer::iterator iter = mTextureSetList.begin(); iter != mTextureSetList.end(); ++iter) + for(TextureSetContainer::iterator iter = mTextureSetList.begin(); iter != mTextureSetList.end(); ++iter) { - if( (*iter) == textureSet ) + if((*iter) == textureSet) { mAtlasList[i].Remove(textureRect); return; @@ -126,9 +117,9 @@ void ImageAtlasManager::Remove( TextureSet textureSet, const Vector4& textureRec } } -void ImageAtlasManager::SetBrokenImage( const std::string& brokenImageUrl ) +void ImageAtlasManager::SetBrokenImage(const std::string& brokenImageUrl) { - if( !brokenImageUrl.empty() ) + if(!brokenImageUrl.empty()) { mBrokenImageUrl = brokenImageUrl; } @@ -136,15 +127,15 @@ void ImageAtlasManager::SetBrokenImage( const std::string& brokenImageUrl ) void ImageAtlasManager::CreateNewAtlas() { - Toolkit::ImageAtlas newAtlas = Toolkit::ImageAtlas::New( DEFAULT_ATLAS_SIZE, DEFAULT_ATLAS_SIZE ); - if( !mBrokenImageUrl.empty() ) + Toolkit::ImageAtlas newAtlas = Toolkit::ImageAtlas::New(DEFAULT_ATLAS_SIZE, DEFAULT_ATLAS_SIZE); + if(!mBrokenImageUrl.empty()) { - newAtlas.SetBrokenImage( mBrokenImageUrl ); + newAtlas.SetBrokenImage(mBrokenImageUrl); } - mAtlasList.push_back( newAtlas ); + mAtlasList.push_back(newAtlas); TextureSet textureSet = TextureSet::New(); - textureSet.SetTexture( 0u, newAtlas.GetAtlas() ); - mTextureSetList.push_back( textureSet ); + textureSet.SetTexture(0u, newAtlas.GetAtlas()); + mTextureSetList.push_back(textureSet); } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/image-visual-shader-factory.cpp b/dali-toolkit/internal/visuals/image-visual-shader-factory.cpp index 523c374..f8f7e5e 100644 --- a/dali-toolkit/internal/visuals/image-visual-shader-factory.cpp +++ b/dali-toolkit/internal/visuals/image-visual-shader-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. @@ -20,22 +20,18 @@ // EXTERNAL INCLUDES // INTERNAL INCLUDES -#include #include +#include #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); // global string variable to caching complate vertex shader @@ -54,56 +50,56 @@ ImageVisualShaderFactory::~ImageVisualShaderFactory() { } -Shader ImageVisualShaderFactory::GetShader( VisualFactoryCache& factoryCache, bool atlasing, bool defaultTextureWrapping, bool roundedCorner ) +Shader ImageVisualShaderFactory::GetShader(VisualFactoryCache& factoryCache, bool atlasing, bool defaultTextureWrapping, bool roundedCorner) { Shader shader; - if( atlasing ) + if(atlasing) { - if( defaultTextureWrapping ) + if(defaultTextureWrapping) { - shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(), - Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_CLAMP_SHADER_FRAG.data() ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(), + Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_CLAMP_SHADER_FRAG.data()); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_DEFAULT_WRAP, shader); } } else { - shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(), - Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_VARIOUS_WRAP_SHADER_FRAG.data() ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(), + Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ATLAS_VARIOUS_WRAP_SHADER_FRAG.data()); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER_ATLAS_CUSTOM_WRAP, shader); } } } else { - if( roundedCorner ) + if(roundedCorner) { - shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), - Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data() ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_VERT.data(), + Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_ROUNDED_CORNER_SHADER_FRAG.data()); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER_ROUNDED_CORNER, shader); } } else { - shader = factoryCache.GetShader( VisualFactoryCache::IMAGE_SHADER ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::IMAGE_SHADER); + if(!shader) { - shader = Shader::New( Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(), - Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_NO_ATLAS_SHADER_FRAG.data() ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::IMAGE_SHADER, shader ); + shader = Shader::New(Dali::Shader::GetVertexShaderPrefix() + SHADER_IMAGE_VISUAL_SHADER_VERT.data(), + Dali::Shader::GetFragmentShaderPrefix() + SHADER_IMAGE_VISUAL_NO_ATLAS_SHADER_FRAG.data()); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::IMAGE_SHADER, shader); } } } diff --git a/dali-toolkit/internal/visuals/image/image-visual.cpp b/dali-toolkit/internal/visuals/image/image-visual.cpp index 028773d..03e0657 100644 --- a/dali-toolkit/internal/visuals/image/image-visual.cpp +++ b/dali-toolkit/internal/visuals/image/image-visual.cpp @@ -19,99 +19,95 @@ #include // EXTERNAL HEADERS -#include // for strlen() -#include -#include #include +#include #include #include #include #include #include +#include +#include // for strlen() // INTERNAL HEADERS -#include -#include #include -#include -#include -#include -#include -#include #include +#include +#include #include +#include +#include +#include +#include #include -#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // fitting modes -DALI_ENUM_TO_STRING_TABLE_BEGIN( FITTING_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SHRINK_TO_FIT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SCALE_TO_FILL ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_WIDTH ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_HEIGHT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, DEFAULT ) -DALI_ENUM_TO_STRING_TABLE_END( FITTING_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(FITTING_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, SHRINK_TO_FIT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, SCALE_TO_FILL) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, FIT_WIDTH) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, FIT_HEIGHT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, DEFAULT) +DALI_ENUM_TO_STRING_TABLE_END(FITTING_MODE) // sampling modes -DALI_ENUM_TO_STRING_TABLE_BEGIN( SAMPLING_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NEAREST ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, LINEAR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_NEAREST ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_LINEAR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NO_FILTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, DONT_CARE ) -DALI_ENUM_TO_STRING_TABLE_END( SAMPLING_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(SAMPLING_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, NEAREST) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, LINEAR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_NEAREST) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_LINEAR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, NO_FILTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, DONT_CARE) +DALI_ENUM_TO_STRING_TABLE_END(SAMPLING_MODE) // wrap modes -DALI_ENUM_TO_STRING_TABLE_BEGIN( WRAP_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, DEFAULT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, CLAMP_TO_EDGE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, REPEAT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, MIRRORED_REPEAT ) -DALI_ENUM_TO_STRING_TABLE_END( WRAP_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(WRAP_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, DEFAULT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, CLAMP_TO_EDGE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, REPEAT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::WrapMode, MIRRORED_REPEAT) +DALI_ENUM_TO_STRING_TABLE_END(WRAP_MODE) // load policies -DALI_ENUM_TO_STRING_TABLE_BEGIN( LOAD_POLICY ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, IMMEDIATE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, ATTACHED ) -DALI_ENUM_TO_STRING_TABLE_END( LOAD_POLICY ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(LOAD_POLICY) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::LoadPolicy, IMMEDIATE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::LoadPolicy, ATTACHED) +DALI_ENUM_TO_STRING_TABLE_END(LOAD_POLICY) // release policies -DALI_ENUM_TO_STRING_TABLE_BEGIN( RELEASE_POLICY ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DETACHED ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DESTROYED ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, NEVER ) -DALI_ENUM_TO_STRING_TABLE_END( RELEASE_POLICY ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(RELEASE_POLICY) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::ReleasePolicy, DETACHED) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::ReleasePolicy, DESTROYED) + DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::Toolkit::ImageVisual::ReleasePolicy, NEVER) +DALI_ENUM_TO_STRING_TABLE_END(RELEASE_POLICY) const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); -const float PIXEL_ALIGN_ON = 1.0f; +const float PIXEL_ALIGN_ON = 1.0f; const float PIXEL_ALIGN_OFF = 0.0f; -Geometry CreateGeometry( VisualFactoryCache& factoryCache, ImageDimensions gridSize ) +Geometry CreateGeometry(VisualFactoryCache& factoryCache, ImageDimensions gridSize) { Geometry geometry; - if( gridSize == ImageDimensions( 1, 1 ) ) + if(gridSize == ImageDimensions(1, 1)) { - geometry = factoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + geometry = factoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); } else { - geometry = VisualFactoryCache::CreateGridGeometry( gridSize ); + geometry = VisualFactoryCache::CreateGridGeometry(gridSize); } return geometry; @@ -119,27 +115,26 @@ Geometry CreateGeometry( VisualFactoryCache& factoryCache, ImageDimensions gridS } // unnamed namespace - -ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache, - ImageVisualShaderFactory& shaderFactory, - const VisualUrl& imageUrl, - const Property::Map& properties, - ImageDimensions size, - FittingMode::Type fittingMode, - Dali::SamplingMode::Type samplingMode ) +ImageVisualPtr ImageVisual::New(VisualFactoryCache& factoryCache, + ImageVisualShaderFactory& shaderFactory, + const VisualUrl& imageUrl, + const Property::Map& properties, + ImageDimensions size, + FittingMode::Type fittingMode, + Dali::SamplingMode::Type samplingMode) { - ImageVisualPtr imageVisualPtr( new ImageVisual( factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode ) ); - imageVisualPtr->SetProperties( properties ); + ImageVisualPtr imageVisualPtr(new ImageVisual(factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode)); + imageVisualPtr->SetProperties(properties); imageVisualPtr->Initialize(); return imageVisualPtr; } -ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache, - ImageVisualShaderFactory& shaderFactory, - const VisualUrl& imageUrl, - ImageDimensions size, - FittingMode::Type fittingMode, - Dali::SamplingMode::Type samplingMode ) +ImageVisualPtr ImageVisual::New(VisualFactoryCache& factoryCache, + ImageVisualShaderFactory& shaderFactory, + const VisualUrl& imageUrl, + ImageDimensions size, + FittingMode::Type fittingMode, + Dali::SamplingMode::Type samplingMode) { ImageVisualPtr imageVisualPtr(new ImageVisual(factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode)); imageVisualPtr->Initialize(); @@ -173,126 +168,125 @@ ImageVisual::ImageVisual(VisualFactoryCache& factoryCache, mAttemptAtlasing(false), mOrientationCorrection(true) { - EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() ); + EnablePreMultipliedAlpha(mFactoryCache.GetPreMultiplyOnLoad()); } ImageVisual::~ImageVisual() { - if( Stage::IsInstalled() ) + if(Stage::IsInstalled()) { - if( mMaskingData ) + if(mMaskingData) { // TextureManager could have been deleted before the actor that contains this // ImageVisual is destroyed (e.g. due to stage shutdown). Ensure the stage // is still valid before accessing texture manager. - if( mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID ) + if(mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID) { TextureManager& textureManager = mFactoryCache.GetTextureManager(); - textureManager.Remove( mMaskingData->mAlphaMaskId, this ); + textureManager.Remove(mMaskingData->mAlphaMaskId, this); } } // ImageVisual destroyed so remove texture unless ReleasePolicy is set to never release - if( ( mTextureId != TextureManager::INVALID_TEXTURE_ID ) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ) ) + if((mTextureId != TextureManager::INVALID_TEXTURE_ID) && (mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER)) { RemoveTexture(); } } } -void ImageVisual::DoSetProperties( const Property::Map& propertyMap ) +void ImageVisual::DoSetProperties(const Property::Map& propertyMap) { // Url is already received in constructor - for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter ) + for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter) { - KeyValuePair keyValue = propertyMap.GetKeyValue( iter ); - if( keyValue.first.type == Property::Key::INDEX ) + KeyValuePair keyValue = propertyMap.GetKeyValue(iter); + if(keyValue.first.type == Property::Key::INDEX) { - DoSetProperty( keyValue.first.indexKey, keyValue.second ); + DoSetProperty(keyValue.first.indexKey, keyValue.second); } else { - if( keyValue.first == IMAGE_FITTING_MODE ) + if(keyValue.first == IMAGE_FITTING_MODE) { - DoSetProperty( Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second); } - else if( keyValue.first == IMAGE_SAMPLING_MODE ) + else if(keyValue.first == IMAGE_SAMPLING_MODE) { - DoSetProperty( Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second); } - else if( keyValue.first == IMAGE_DESIRED_WIDTH ) + else if(keyValue.first == IMAGE_DESIRED_WIDTH) { - DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second); } - else if( keyValue.first == IMAGE_DESIRED_HEIGHT ) + else if(keyValue.first == IMAGE_DESIRED_HEIGHT) { - DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second); } - else if( keyValue.first == PIXEL_AREA_UNIFORM_NAME ) + else if(keyValue.first == PIXEL_AREA_UNIFORM_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second); } - else if( keyValue.first == IMAGE_WRAP_MODE_U ) + else if(keyValue.first == IMAGE_WRAP_MODE_U) { - DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second); } - else if( keyValue.first == IMAGE_WRAP_MODE_V ) + else if(keyValue.first == IMAGE_WRAP_MODE_V) { - DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second); } - else if( keyValue.first == SYNCHRONOUS_LOADING ) + else if(keyValue.first == SYNCHRONOUS_LOADING) { - DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second); } - else if( keyValue.first == IMAGE_ATLASING ) + else if(keyValue.first == IMAGE_ATLASING) { - DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second); } - else if( keyValue.first == ALPHA_MASK_URL ) + else if(keyValue.first == ALPHA_MASK_URL) { - DoSetProperty( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second); } - else if( keyValue.first == MASK_CONTENT_SCALE_NAME ) + else if(keyValue.first == MASK_CONTENT_SCALE_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second); } - else if( keyValue.first == CROP_TO_MASK_NAME ) + else if(keyValue.first == CROP_TO_MASK_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second); } - else if ( keyValue.first == LOAD_POLICY_NAME ) + else if(keyValue.first == LOAD_POLICY_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second); } - else if( keyValue.first == RELEASE_POLICY_NAME ) + else if(keyValue.first == RELEASE_POLICY_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second); } - else if( keyValue.first == ORIENTATION_CORRECTION_NAME ) + else if(keyValue.first == ORIENTATION_CORRECTION_NAME) { - DoSetProperty( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second); } } } // Load image immediately if LOAD_POLICY requires it - if ( mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE ) + if(mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE) { auto attemptAtlasing = AttemptAtlasing(); - LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, - TextureManager::ReloadPolicy::CACHED ); + LoadTexture(attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, TextureManager::ReloadPolicy::CACHED); } } -void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& value ) +void ImageVisual::DoSetProperty(Property::Index index, const Property::Value& value) { - switch( index ) + switch(index) { case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING: { bool sync = false; - if( value.Get( sync ) ) + if(value.Get(sync)) { - if( sync ) + if(sync) { mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING; } @@ -311,9 +305,9 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v case Toolkit::ImageVisual::Property::DESIRED_WIDTH: { float desiredWidth = 0.0f; - if( value.Get( desiredWidth ) ) + if(value.Get(desiredWidth)) { - mDesiredSize.SetWidth( desiredWidth ); + mDesiredSize.SetWidth(desiredWidth); } else { @@ -325,9 +319,9 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v case Toolkit::ImageVisual::Property::DESIRED_HEIGHT: { float desiredHeight = 0.0f; - if( value.Get( desiredHeight ) ) + if(value.Get(desiredHeight)) { - mDesiredSize.SetHeight( desiredHeight ); + mDesiredSize.SetHeight(desiredHeight); } else { @@ -339,51 +333,51 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v case Toolkit::ImageVisual::Property::FITTING_MODE: { int fittingMode = 0; - Scripting::GetEnumerationProperty( value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode ); - mFittingMode = Dali::FittingMode::Type( fittingMode ); + Scripting::GetEnumerationProperty(value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode); + mFittingMode = Dali::FittingMode::Type(fittingMode); break; } case Toolkit::ImageVisual::Property::SAMPLING_MODE: { int samplingMode = 0; - Scripting::GetEnumerationProperty( value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode ); - mSamplingMode = Dali::SamplingMode::Type( samplingMode ); + Scripting::GetEnumerationProperty(value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode); + mSamplingMode = Dali::SamplingMode::Type(samplingMode); break; } case Toolkit::ImageVisual::Property::PIXEL_AREA: { - value.Get( mPixelArea ); + value.Get(mPixelArea); break; } case Toolkit::ImageVisual::Property::WRAP_MODE_U: { int wrapMode = 0; - Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode ); - mWrapModeU = Dali::WrapMode::Type( wrapMode ); + Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode); + mWrapModeU = Dali::WrapMode::Type(wrapMode); break; } case Toolkit::ImageVisual::Property::WRAP_MODE_V: { int wrapMode = 0; - Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode ); - mWrapModeV = Dali::WrapMode::Type( wrapMode ); + Scripting::GetEnumerationProperty(value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode); + mWrapModeV = Dali::WrapMode::Type(wrapMode); break; } case Toolkit::ImageVisual::Property::ATLASING: { - value.Get( mAttemptAtlasing ); + value.Get(mAttemptAtlasing); break; } case Toolkit::ImageVisual::Property::ALPHA_MASK_URL: { std::string alphaUrl = ""; - if( value.Get( alphaUrl ) ) + if(value.Get(alphaUrl)) { AllocateMaskData(); mMaskingData->mAlphaMaskUrl = alphaUrl; @@ -394,7 +388,7 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v case Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE: { float scale = 1.0f; - if( value.Get( scale ) ) + if(value.Get(scale)) { AllocateMaskData(); mMaskingData->mContentScaleFactor = scale; @@ -404,8 +398,8 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v case Toolkit::ImageVisual::Property::CROP_TO_MASK: { - bool crop=false; - if( value.Get( crop ) ) + bool crop = false; + if(value.Get(crop)) { AllocateMaskData(); mMaskingData->mCropToMask = crop; @@ -416,22 +410,22 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v case Toolkit::ImageVisual::Property::RELEASE_POLICY: { int releasePolicy = 0; - Scripting::GetEnumerationProperty( value, RELEASE_POLICY_TABLE, RELEASE_POLICY_TABLE_COUNT, releasePolicy ); - mReleasePolicy = Toolkit::ImageVisual::ReleasePolicy::Type( releasePolicy ); + Scripting::GetEnumerationProperty(value, RELEASE_POLICY_TABLE, RELEASE_POLICY_TABLE_COUNT, releasePolicy); + mReleasePolicy = Toolkit::ImageVisual::ReleasePolicy::Type(releasePolicy); break; } case Toolkit::ImageVisual::Property::LOAD_POLICY: { int loadPolicy = 0; - Scripting::GetEnumerationProperty( value, LOAD_POLICY_TABLE, LOAD_POLICY_TABLE_COUNT, loadPolicy ); - mLoadPolicy = Toolkit::ImageVisual::LoadPolicy::Type( loadPolicy ); + Scripting::GetEnumerationProperty(value, LOAD_POLICY_TABLE, LOAD_POLICY_TABLE_COUNT, loadPolicy); + mLoadPolicy = Toolkit::ImageVisual::LoadPolicy::Type(loadPolicy); break; } case Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION: { - bool orientationCorrection( mOrientationCorrection ); - if( value.Get( orientationCorrection ) ) + bool orientationCorrection(mOrientationCorrection); + if(value.Get(orientationCorrection)) { mOrientationCorrection = orientationCorrection; } @@ -442,23 +436,23 @@ void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& v void ImageVisual::AllocateMaskData() { - if( !mMaskingData ) + if(!mMaskingData) { mMaskingData.reset(new TextureManager::MaskingData()); } } -void ImageVisual::GetNaturalSize( Vector2& naturalSize ) +void ImageVisual::GetNaturalSize(Vector2& naturalSize) { - if( mDesiredSize.GetWidth()>0 && mDesiredSize.GetHeight()>0) + if(mDesiredSize.GetWidth() > 0 && mDesiredSize.GetHeight() > 0) { naturalSize.x = mDesiredSize.GetWidth(); naturalSize.y = mDesiredSize.GetHeight(); return; } - else if( mImpl->mRenderer ) // Check if we have a loaded image + else if(mImpl->mRenderer) // Check if we have a loaded image { - if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED ) + if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED) { naturalSize.x = mAtlasRectSize.GetWidth(); naturalSize.y = mAtlasRectSize.GetHeight(); @@ -466,10 +460,10 @@ void ImageVisual::GetNaturalSize( Vector2& naturalSize ) } auto textureSet = mImpl->mRenderer.GetTextures(); - if( textureSet ) + if(textureSet) { auto texture = textureSet.GetTexture(0); - if( texture ) + if(texture) { naturalSize.x = texture.GetWidth(); naturalSize.y = texture.GetHeight(); @@ -478,24 +472,24 @@ void ImageVisual::GetNaturalSize( Vector2& naturalSize ) } } - if( mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() && - mMaskingData->mCropToMask ) + if(mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() && + mMaskingData->mCropToMask) { - ImageDimensions dimensions = Dali::GetClosestImageSize( mMaskingData->mAlphaMaskUrl.GetUrl() ); - if( dimensions != ImageDimensions( 0, 0 ) ) + ImageDimensions dimensions = Dali::GetClosestImageSize(mMaskingData->mAlphaMaskUrl.GetUrl()); + if(dimensions != ImageDimensions(0, 0)) { naturalSize.x = dimensions.GetWidth(); naturalSize.y = dimensions.GetHeight(); } return; } - else if( mImageUrl.IsValid() ) + else if(mImageUrl.IsValid()) { - if( mImageUrl.GetProtocolType() == VisualUrl::LOCAL ) + if(mImageUrl.GetProtocolType() == VisualUrl::LOCAL) { - ImageDimensions dimensions = Dali::GetClosestImageSize( mImageUrl.GetUrl() ); + ImageDimensions dimensions = Dali::GetClosestImageSize(mImageUrl.GetUrl()); - if( dimensions != ImageDimensions( 0, 0 ) ) + if(dimensions != ImageDimensions(0, 0)) { naturalSize.x = dimensions.GetWidth(); naturalSize.y = dimensions.GetHeight(); @@ -518,60 +512,59 @@ void ImageVisual::OnInitialize() Geometry geometry; // Get the geometry - if( mImpl->mCustomShader ) + if(mImpl->mCustomShader) { - geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize ); + geometry = CreateGeometry(mFactoryCache, mImpl->mCustomShader->mGridSize); } else // Get any geometry associated with the texture { TextureManager& textureManager = mFactoryCache.GetTextureManager(); - uint32_t firstElementCount {0u}; - uint32_t secondElementCount {0u}; + uint32_t firstElementCount{0u}; + uint32_t secondElementCount{0u}; geometry = textureManager.GetRenderGeometry(mTextureId, firstElementCount, secondElementCount); if(!firstElementCount && !secondElementCount) // Otherwise use quad { - geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) ); + geometry = CreateGeometry(mFactoryCache, ImageDimensions(1, 1)); } } Shader shader = GetShader(); // Create the renderer - mImpl->mRenderer = Renderer::New( geometry, shader ); + mImpl->mRenderer = Renderer::New(geometry, shader); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); - EnablePreMultipliedAlpha( IsPreMultipliedAlphaEnabled() ); + EnablePreMultipliedAlpha(IsPreMultipliedAlphaEnabled()); } -void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection, - TextureManager::ReloadPolicy forceReload ) +void ImageVisual::LoadTexture(bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection, TextureManager::ReloadPolicy forceReload) { TextureManager& textureManager = mFactoryCache.GetTextureManager(); - ImageAtlasManagerPtr atlasManager = nullptr; + ImageAtlasManagerPtr atlasManager = nullptr; AtlasUploadObserver* atlasUploadObserver = nullptr; - auto textureObserver = this; + auto textureObserver = this; - if( atlasing ) + if(atlasing) { - atlasManager = mFactoryCache.GetAtlasManager(); + atlasManager = mFactoryCache.GetAtlasManager(); atlasUploadObserver = this; } auto preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader - ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD - : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; + ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD + : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; bool synchronousLoading = IsSynchronousLoadingRequired(); bool loadingStatus; textures = textureManager.LoadTexture(mImageUrl, mDesiredSize, mFittingMode, mSamplingMode, mMaskingData, synchronousLoading, mTextureId, atlasRect, mAtlasRectSize, atlasing, loadingStatus, mWrapModeU, mWrapModeV, textureObserver, atlasUploadObserver, atlasManager, mOrientationCorrection, forceReload, preMultiplyOnLoad); - if( textures ) + if(textures) { if(loadingStatus) { @@ -582,7 +575,7 @@ void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& t mLoadState = TextureManager::LoadState::LOAD_FINISHED; } - EnablePreMultipliedAlpha( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD ); + EnablePreMultipliedAlpha(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD); } else if(synchronousLoading) { @@ -590,7 +583,7 @@ void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& t mLoadState = TextureManager::LoadState::LOAD_FAILED; } - if( atlasing ) // Flag needs to be set before creating renderer + if(atlasing) // Flag needs to be set before creating renderer { mImpl->mFlags |= Impl::IS_ATLASING_APPLIED; } @@ -602,7 +595,7 @@ void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& t bool ImageVisual::AttemptAtlasing() { - return ( ! mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing ); + return (!mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing); } void ImageVisual::InitializeRenderer() @@ -618,16 +611,15 @@ void ImageVisual::InitializeRenderer() // - If ReleasePolicy is DESTROYED, InitializeRenderer called every on stage called. // - Then every resources those contained in Visual are Reset but mTextureId is remained when the Off stage time, // - So, mTextures needed to be get from texture manager to created resources like mImpl->mRenderer. - if( ! mTextures ) + if(!mTextures) { - if( mTextureId == TextureManager::INVALID_TEXTURE_ID ) + if(mTextureId == TextureManager::INVALID_TEXTURE_ID) { - LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, - TextureManager::ReloadPolicy::CACHED ); + LoadTexture(attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, TextureManager::ReloadPolicy::CACHED); } else { - mTextures = mFactoryCache.GetTextureManager().GetTextureSet( mTextureId ); + mTextures = mFactoryCache.GetTextureManager().GetTextureSet(mTextureId); } } @@ -637,29 +629,29 @@ void ImageVisual::InitializeRenderer() mTextures.Reset(); // Visual should not keep a handle to the texture after this point. } - if( attemptAtlasing ) // the texture is packed inside atlas + if(attemptAtlasing) // the texture is packed inside atlas { - mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect ); + mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, mAtlasRect); bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE; - if( !defaultWrapMode ) // custom wrap mode + if(!defaultWrapMode) // custom wrap mode { - Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE); - wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) ); - mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode ); + Vector2 wrapMode(mWrapModeU - WrapMode::CLAMP_TO_EDGE, mWrapModeV - WrapMode::CLAMP_TO_EDGE); + wrapMode.Clamp(Vector2::ZERO, Vector2(2.f, 2.f)); + mImpl->mRenderer.RegisterProperty(WRAP_MODE_UNIFORM_NAME, wrapMode); } } } -void ImageVisual::DoSetOnScene( Actor& actor ) +void ImageVisual::DoSetOnScene(Actor& actor) { - if( mImageUrl.IsValid() ) + if(mImageUrl.IsValid()) { InitializeRenderer(); } - if( !mImpl->mRenderer ) + if(!mImpl->mRenderer) { return; } @@ -667,24 +659,24 @@ void ImageVisual::DoSetOnScene( Actor& actor ) mPlacementActor = actor; // Search the Actor tree to find if Layer UI behaviour set. Layer layer = actor.GetLayer(); - if( layer && layer.GetProperty( Layer::Property::BEHAVIOR ) == Layer::LAYER_3D ) + if(layer && layer.GetProperty(Layer::Property::BEHAVIOR) == Layer::LAYER_3D) { - // Layer 3D set, do not align pixels - mImpl->mRenderer.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF ); + // Layer 3D set, do not align pixels + mImpl->mRenderer.RegisterProperty(PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF); } - if( mPixelArea != FULL_TEXTURE_RECT ) + if(mPixelArea != FULL_TEXTURE_RECT) { - mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea ); + mImpl->mRenderer.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, mPixelArea); } if(mLoadState == TextureManager::LoadState::LOAD_FINISHED) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); mPlacementActor.Reset(); // Image loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } else if(mLoadState == TextureManager::LoadState::LOAD_FAILED) { @@ -701,13 +693,13 @@ void ImageVisual::DoSetOnScene( Actor& actor ) } } -void ImageVisual::DoSetOffScene( Actor& actor ) +void ImageVisual::DoSetOffScene(Actor& actor) { // Visual::Base::SetOffScene only calls DoSetOffScene if mRenderer exists (is on onstage) // Image release is dependent on the ReleasePolicy, renderer is removed. - actor.RemoveRenderer( mImpl->mRenderer); - if( mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED ) + actor.RemoveRenderer(mImpl->mRenderer); + if(mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED) { RemoveTexture(); // If INVALID_TEXTURE_ID then removal will be attempted on atlas mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING; @@ -721,63 +713,62 @@ void ImageVisual::DoSetOffScene( Actor& actor ) mPlacementActor.Reset(); } -void ImageVisual::DoCreatePropertyMap( Property::Map& map ) const +void ImageVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE); bool sync = IsSynchronousLoadingRequired(); - map.Insert( SYNCHRONOUS_LOADING, sync ); - if( mImageUrl.IsValid() ) + map.Insert(SYNCHRONOUS_LOADING, sync); + if(mImageUrl.IsValid()) { - map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() ); - map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() ); - map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() ); + map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl()); + map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth()); + map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight()); } - map.Insert( Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode ); - map.Insert( Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode ); + map.Insert(Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode); + map.Insert(Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode); - map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea ); - map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU ); - map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV ); + map.Insert(Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea); + map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU); + map.Insert(Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV); - map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing ); + map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing); - if( mMaskingData != NULL ) + if(mMaskingData != NULL) { - map.Insert( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl() ); - map.Insert( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor ); - map.Insert( Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask ); + map.Insert(Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl()); + map.Insert(Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor); + map.Insert(Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask); } - map.Insert( Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy ); - map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy ); - map.Insert( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection ); + map.Insert(Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy); + map.Insert(Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy); + map.Insert(Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection); } -void ImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void ImageVisual::DoCreateInstancePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE ); - if( mImageUrl.IsValid() ) + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE); + if(mImageUrl.IsValid()) { - map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() ); - map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() ); + map.Insert(Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth()); + map.Insert(Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight()); } } -void ImageVisual::OnDoAction( const Dali::Property::Index actionName, const Dali::Property::Value& attributes ) +void ImageVisual::OnDoAction(const Dali::Property::Index actionName, const Dali::Property::Value& attributes) { // Check if action is valid for this visual type and perform action if possible - switch ( actionName ) + switch(actionName) { case DevelImageVisual::Action::RELOAD: { auto attemptAtlasing = AttemptAtlasing(); - LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, - TextureManager::ReloadPolicy::FORCED ); + LoadTexture(attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection, TextureManager::ReloadPolicy::FORCED); break; } } @@ -785,16 +776,16 @@ void ImageVisual::OnDoAction( const Dali::Property::Index actionName, const Dali void ImageVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } bool ImageVisual::IsResourceReady() const { - return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY || - mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED ); + return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY || + mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED); } void ImageVisual::UpdateShader() @@ -812,65 +803,63 @@ void ImageVisual::UploadCompleted() // Texture has been uploaded. If weak handle is holding a placement actor, // it is the time to add the renderer to actor. Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { - mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect ); - actor.AddRenderer( mImpl->mRenderer ); + mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, mAtlasRect); + actor.AddRenderer(mImpl->mRenderer); // reset the weak handle so that the renderer only get added to actor once mPlacementActor.Reset(); } // Image loaded - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); mLoadState = TextureManager::LoadState::LOAD_FINISHED; } // From Texture Manager -void ImageVisual::UploadComplete( bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas, - const Vector4& atlasRectangle, bool preMultiplied ) +void ImageVisual::UploadComplete(bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas, const Vector4& atlasRectangle, bool preMultiplied) { Toolkit::Visual::ResourceStatus resourceStatus; - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - if( usingAtlas ) + if(usingAtlas) { - mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect ); + mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, mAtlasRect); } - EnablePreMultipliedAlpha( preMultiplied ); + EnablePreMultipliedAlpha(preMultiplied); Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // reset the weak handle so that the renderer only get added to actor once mPlacementActor.Reset(); } - if( !loadingSuccess ) + if(!loadingSuccess) { Texture brokenImage = mFactoryCache.GetBrokenVisualImage(); textureSet = TextureSet::New(); textureSet.SetTexture(0u, brokenImage); - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); } Sampler sampler = Sampler::New(); - sampler.SetWrapMode( mWrapModeU, mWrapModeV ); - textureSet.SetSampler( 0u, sampler ); + sampler.SetWrapMode(mWrapModeU, mWrapModeV); + textureSet.SetSampler(0u, sampler); mImpl->mRenderer.SetTextures(textureSet); - } // Storing TextureSet needed when renderer staged. - if( ! mImpl->mRenderer ) + if(!mImpl->mRenderer) { mTextures = textureSet; } // Image loaded, set status regardless of staged status. - if( loadingSuccess ) + if(loadingSuccess) { resourceStatus = Toolkit::Visual::ResourceStatus::READY; mLoadState = TextureManager::LoadState::LOAD_FINISHED; @@ -882,61 +871,61 @@ void ImageVisual::UploadComplete( bool loadingSuccess, int32_t textureId, Textur } // use geometry if needed - if( loadingSuccess ) + if(loadingSuccess) { uint32_t firstElementCount{0u}; uint32_t secondElementCount{0u}; - auto geometry = mFactoryCache.GetTextureManager().GetRenderGeometry(mTextureId, firstElementCount, secondElementCount); - if (mImpl->mRenderer && geometry) + auto geometry = mFactoryCache.GetTextureManager().GetRenderGeometry(mTextureId, firstElementCount, secondElementCount); + if(mImpl->mRenderer && geometry) { mImpl->mRenderer.SetGeometry(geometry); Dali::DevelRenderer::DrawCommand drawCommand{}; drawCommand.drawType = DevelRenderer::DrawType::INDEXED; - if (firstElementCount) + if(firstElementCount) { - drawCommand.firstIndex = 0; + drawCommand.firstIndex = 0; drawCommand.elementCount = firstElementCount; - drawCommand.queue = DevelRenderer::RENDER_QUEUE_OPAQUE; + drawCommand.queue = DevelRenderer::RENDER_QUEUE_OPAQUE; DevelRenderer::AddDrawCommand(mImpl->mRenderer, drawCommand); } - if (secondElementCount) + if(secondElementCount) { - drawCommand.firstIndex = firstElementCount; + drawCommand.firstIndex = firstElementCount; drawCommand.elementCount = secondElementCount; - drawCommand.queue = DevelRenderer::RENDER_QUEUE_TRANSPARENT; + drawCommand.queue = DevelRenderer::RENDER_QUEUE_TRANSPARENT; DevelRenderer::AddDrawCommand(mImpl->mRenderer, drawCommand); } } } // Signal to observers ( control ) that resources are ready. Must be all resources. - ResourceReady( resourceStatus ); + ResourceReady(resourceStatus); } void ImageVisual::RemoveTexture() { - if( mTextureId != TextureManager::INVALID_TEXTURE_ID ) + if(mTextureId != TextureManager::INVALID_TEXTURE_ID) { - mFactoryCache.GetTextureManager().Remove( mTextureId, this ); + mFactoryCache.GetTextureManager().Remove(mTextureId, this); mTextureId = TextureManager::INVALID_TEXTURE_ID; } else { - Vector4 atlasRect( 0.f, 0.f, 1.f, 1.f ); - Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME ); - if( index != Property::INVALID_INDEX ) + Vector4 atlasRect(0.f, 0.f, 1.f, 1.f); + Property::Index index = mImpl->mRenderer.GetPropertyIndex(ATLAS_RECT_UNIFORM_NAME); + if(index != Property::INVALID_INDEX) { - Property::Value atlasRectValue = mImpl->mRenderer.GetProperty( index ); - atlasRectValue.Get( atlasRect ); + Property::Value atlasRectValue = mImpl->mRenderer.GetProperty(index); + atlasRectValue.Get(atlasRect); } TextureSet textureSet = mImpl->mRenderer.GetTextures(); - if( index != Property::INVALID_INDEX ) + if(index != Property::INVALID_INDEX) { - mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect ); + mFactoryCache.GetAtlasManager()->Remove(textureSet, atlasRect); } } } @@ -946,7 +935,7 @@ Shader ImageVisual::GetShader() Shader shader; std::string_view vertexShaderView; - bool usesWholeTexture = true; + bool usesWholeTexture = true; if(mImpl->mCustomShader && !mImpl->mCustomShader->mVertexShader.empty()) { vertexShaderView = mImpl->mCustomShader->mVertexShader; @@ -969,11 +958,11 @@ Shader ImageVisual::GetShader() // If the texture is native, we may need to change prefix and sampler in // the fragment shader - bool modifiedFragmentShader = false; + bool modifiedFragmentShader = false; std::string fragmentShaderString; if(mTextures && DevelTexture::IsNative(mTextures.GetTexture(0))) { - Texture nativeTexture = mTextures.GetTexture(0); + Texture nativeTexture = mTextures.GetTexture(0); fragmentShaderString = std::string(fragmentShaderView); modifiedFragmentShader = DevelTexture::ApplyNativeFragmentShader(nativeTexture, fragmentShaderString); fragmentShaderView = fragmentShaderString; @@ -987,7 +976,7 @@ Shader ImageVisual::GetShader() mFactoryCache, mImpl->mFlags & Impl::IS_ATLASING_APPLIED, mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE, - IsRoundedCornerRequired() ); + IsRoundedCornerRequired()); } else if(mImpl->mCustomShader) { @@ -1000,13 +989,13 @@ Shader ImageVisual::GetShader() if(usesWholeTexture) { - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); } // Set pixel align off as default. // ToDo: Pixel align causes issues such as rattling image animation. // We should trun it off until issues are resolved - shader.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF ); + shader.RegisterProperty(PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF); return shader; } diff --git a/dali-toolkit/internal/visuals/mesh/mesh-visual.cpp b/dali-toolkit/internal/visuals/mesh/mesh-visual.cpp index 6a1215c..e814bf1 100644 --- a/dali-toolkit/internal/visuals/mesh/mesh-visual.cpp +++ b/dali-toolkit/internal/visuals/mesh/mesh-visual.cpp @@ -19,98 +19,93 @@ #include "mesh-visual.h" // EXTERNAL INCLUDES -#include -#include -#include #include +#include +#include #include #include +#include //INTERNAL INCLUDES -#include +#include #include #include -#include +#include namespace Dali { - namespace { - /** +/** * @brief Loads a texture from a file * @param[in] imageUrl The url of the file * @param[in] generateMipmaps Indicates whether to generate mipmaps for the texture * @return A texture if loading succeeds, an empty handle otherwise */ - Texture LoadTexture( const char* imageUrl, bool generateMipmaps ) +Texture LoadTexture(const char* imageUrl, bool generateMipmaps) +{ + Texture texture; + + Devel::PixelBuffer pixelBuffer = LoadImageFromFile(imageUrl); + if(pixelBuffer) { - Texture texture; + texture = Texture::New(TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight()); + PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); + texture.Upload(pixelData); - Devel::PixelBuffer pixelBuffer = LoadImageFromFile( imageUrl ); - if( pixelBuffer ) + if(generateMipmaps) { - texture = Texture::New( TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight() ); - PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer ); - texture.Upload( pixelData ); - - if( generateMipmaps ) - { - texture.GenerateMipmaps(); - } + texture.GenerateMipmaps(); } - - return texture; } -}// unnamed namespace + + return texture; +} +} // unnamed namespace namespace Toolkit { - namespace Internal { - namespace { - //Defines ordering of textures for shaders. //All shaders, if including certain texture types, must include them in the same order. //Within the texture set for the renderer, textures are ordered in the same manner. enum TextureIndex { DIFFUSE_INDEX = 0u, - NORMAL_INDEX = 1u, - GLOSS_INDEX = 2u + NORMAL_INDEX = 1u, + GLOSS_INDEX = 2u }; - //Shading mode -DALI_ENUM_TO_STRING_TABLE_BEGIN( SHADING_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURELESS_WITH_DIFFUSE_LIGHTING ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_SPECULAR_LIGHTING ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) -DALI_ENUM_TO_STRING_TABLE_END( SHADING_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(SHADING_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::MeshVisual::ShadingMode, TEXTURELESS_WITH_DIFFUSE_LIGHTING) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_SPECULAR_LIGHTING) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::MeshVisual::ShadingMode, TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING) +DALI_ENUM_TO_STRING_TABLE_END(SHADING_MODE) //Shader properties -const char * const OBJECT_MATRIX_UNIFORM_NAME( "uObjectMatrix" ); -const char * const STAGE_OFFSET_UNIFORM_NAME( "uStageOffset" ); +const char* const OBJECT_MATRIX_UNIFORM_NAME("uObjectMatrix"); +const char* const STAGE_OFFSET_UNIFORM_NAME("uStageOffset"); } // unnamed namespace -MeshVisualPtr MeshVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +MeshVisualPtr MeshVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - MeshVisualPtr meshVisualPtr( new MeshVisual( factoryCache ) ); - meshVisualPtr->SetProperties( properties ); + MeshVisualPtr meshVisualPtr(new MeshVisual(factoryCache)); + meshVisualPtr->SetProperties(properties); meshVisualPtr->Initialize(); return meshVisualPtr; } -MeshVisual::MeshVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::MESH ), - mShadingMode( Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ), - mUseTexture( true ), - mUseMipmapping( true ), - mUseSoftNormals( true ) +MeshVisual::MeshVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::MESH), + mShadingMode(Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING), + mUseTexture(true), + mUseMipmapping(true), + mUseSoftNormals(true) { } @@ -118,70 +113,70 @@ MeshVisual::~MeshVisual() { } -void MeshVisual::DoSetProperties( const Property::Map& propertyMap ) +void MeshVisual::DoSetProperties(const Property::Map& propertyMap) { - for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter ) + for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter) { - KeyValuePair keyValue = propertyMap.GetKeyValue( iter ); - if( keyValue.first.type == Property::Key::INDEX ) + KeyValuePair keyValue = propertyMap.GetKeyValue(iter); + if(keyValue.first.type == Property::Key::INDEX) { - DoSetProperty( keyValue.first.indexKey, keyValue.second ); + DoSetProperty(keyValue.first.indexKey, keyValue.second); } else { - if( keyValue.first == OBJECT_URL_NAME ) + if(keyValue.first == OBJECT_URL_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::OBJECT_URL, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::OBJECT_URL, keyValue.second); } - else if( keyValue.first == MATERIAL_URL_NAME ) + else if(keyValue.first == MATERIAL_URL_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::MATERIAL_URL, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::MATERIAL_URL, keyValue.second); } - else if( keyValue.first == TEXTURES_PATH_NAME ) + else if(keyValue.first == TEXTURES_PATH_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::TEXTURES_PATH, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::TEXTURES_PATH, keyValue.second); } - else if( keyValue.first == SHADING_MODE_NAME ) + else if(keyValue.first == SHADING_MODE_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::SHADING_MODE, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::SHADING_MODE, keyValue.second); } - else if( keyValue.first == USE_MIPMAPPING_NAME ) + else if(keyValue.first == USE_MIPMAPPING_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::USE_MIPMAPPING, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::USE_MIPMAPPING, keyValue.second); } - else if( keyValue.first == USE_SOFT_NORMALS_NAME ) + else if(keyValue.first == USE_SOFT_NORMALS_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, keyValue.second); } - else if( keyValue.first == LIGHT_POSITION_NAME ) + else if(keyValue.first == LIGHT_POSITION_NAME) { - DoSetProperty( Toolkit::MeshVisual::Property::LIGHT_POSITION, keyValue.second ); + DoSetProperty(Toolkit::MeshVisual::Property::LIGHT_POSITION, keyValue.second); } } } - if( mMaterialUrl.empty() ) + if(mMaterialUrl.empty()) { mUseTexture = false; } - if( mLightPosition == Vector3::ZERO ) + if(mLightPosition == Vector3::ZERO) { // Default behaviour is to place the light directly in front of the object, // at a reasonable distance to light everything on screen. Stage stage = Stage::GetCurrent(); - mLightPosition = Vector3( stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5 ); + mLightPosition = Vector3(stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5); } } -void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& value ) +void MeshVisual::DoSetProperty(Property::Index index, const Property::Value& value) { - switch( index ) + switch(index) { case Toolkit::MeshVisual::Property::OBJECT_URL: { - if( !value.Get( mObjectUrl ) ) + if(!value.Get(mObjectUrl)) { DALI_LOG_ERROR("MeshVisual: property objectUrl is the wrong type, use STRING\n"); } @@ -189,7 +184,7 @@ void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& va } case Toolkit::MeshVisual::Property::MATERIAL_URL: { - if( ! value.Get( mMaterialUrl ) ) + if(!value.Get(mMaterialUrl)) { DALI_LOG_ERROR("MeshVisual: property materialUrl is the wrong type, use STRING\n"); } @@ -197,7 +192,7 @@ void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& va } case Toolkit::MeshVisual::Property::TEXTURES_PATH: { - if( ! value.Get( mTexturesPath ) ) + if(!value.Get(mTexturesPath)) { mTexturesPath.clear(); } @@ -205,12 +200,12 @@ void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& va } case Toolkit::MeshVisual::Property::SHADING_MODE: { - Scripting::GetEnumerationProperty( value, SHADING_MODE_TABLE, SHADING_MODE_TABLE_COUNT, mShadingMode ); + Scripting::GetEnumerationProperty(value, SHADING_MODE_TABLE, SHADING_MODE_TABLE_COUNT, mShadingMode); break; } case Toolkit::MeshVisual::Property::USE_MIPMAPPING: { - if( !value.Get( mUseMipmapping ) ) + if(!value.Get(mUseMipmapping)) { DALI_LOG_ERROR("MeshVisual: property useMipmapping is the wrong type, use BOOLEAN\n"); } @@ -218,7 +213,7 @@ void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& va } case Toolkit::MeshVisual::Property::USE_SOFT_NORMALS: { - if( !value.Get( mUseSoftNormals ) ) + if(!value.Get(mUseSoftNormals)) { DALI_LOG_ERROR("MeshVisual: property useSoftNormals is the wrong type, use BOOLEAN\n"); } @@ -226,7 +221,7 @@ void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& va } case Toolkit::MeshVisual::Property::LIGHT_POSITION: { - if( !value.Get( mLightPosition ) ) + if(!value.Get(mLightPosition)) { mLightPosition = Vector3::ZERO; DALI_LOG_ERROR("MeshVisual: property lightPosition is the wrong type, use VECTOR3\n"); @@ -238,34 +233,34 @@ void MeshVisual::DoSetProperty( Property::Index index, const Property::Value& va void MeshVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } -void MeshVisual::DoSetOnScene( Actor& actor ) +void MeshVisual::DoSetOnScene(Actor& actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // Mesh loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } -void MeshVisual::DoCreatePropertyMap( Property::Map& map ) const +void MeshVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::MESH ); - map.Insert( Toolkit::MeshVisual::Property::OBJECT_URL, mObjectUrl ); - map.Insert( Toolkit::MeshVisual::Property::MATERIAL_URL, mMaterialUrl ); - map.Insert( Toolkit::MeshVisual::Property::TEXTURES_PATH, mTexturesPath ); - map.Insert( Toolkit::MeshVisual::Property::SHADING_MODE, mShadingMode ); - map.Insert( Toolkit::MeshVisual::Property::USE_MIPMAPPING, mUseMipmapping ); - map.Insert( Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, mUseSoftNormals ); - map.Insert( Toolkit::MeshVisual::Property::LIGHT_POSITION, mLightPosition ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::MESH); + map.Insert(Toolkit::MeshVisual::Property::OBJECT_URL, mObjectUrl); + map.Insert(Toolkit::MeshVisual::Property::MATERIAL_URL, mMaterialUrl); + map.Insert(Toolkit::MeshVisual::Property::TEXTURES_PATH, mTexturesPath); + map.Insert(Toolkit::MeshVisual::Property::SHADING_MODE, mShadingMode); + map.Insert(Toolkit::MeshVisual::Property::USE_MIPMAPPING, mUseMipmapping); + map.Insert(Toolkit::MeshVisual::Property::USE_SOFT_NORMALS, mUseSoftNormals); + map.Insert(Toolkit::MeshVisual::Property::LIGHT_POSITION, mLightPosition); } -void MeshVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void MeshVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } @@ -273,16 +268,16 @@ void MeshVisual::DoCreateInstancePropertyMap( Property::Map& map ) const void MeshVisual::OnInitialize() { //Try to load the geometry from the file. - if( !LoadGeometry() ) + if(!LoadGeometry()) { SupplyEmptyGeometry(); return; } //If a texture is used by the obj file, load the supplied material file. - if( mObjLoader.IsTexturePresent() && !mMaterialUrl.empty() ) + if(mObjLoader.IsTexturePresent() && !mMaterialUrl.empty()) { - if( !LoadMaterial() ) + if(!LoadMaterial()) { SupplyEmptyGeometry(); return; @@ -290,7 +285,7 @@ void MeshVisual::OnInitialize() } //Now that the required parts are loaded, create the geometry for the object. - if( !CreateGeometry() ) + if(!CreateGeometry()) { SupplyEmptyGeometry(); return; @@ -299,57 +294,57 @@ void MeshVisual::OnInitialize() CreateShader(); //Load the various texture files supplied by the material file. - if( !LoadTextures() ) + if(!LoadTextures()) { SupplyEmptyGeometry(); return; } - mImpl->mRenderer = Renderer::New( mGeometry, mShader ); - mImpl->mRenderer.SetTextures( mTextureSet ); - mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON ); - mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON ); + mImpl->mRenderer = Renderer::New(mGeometry, mShader); + mImpl->mRenderer.SetTextures(mTextureSet); + mImpl->mRenderer.SetProperty(Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON); + mImpl->mRenderer.SetProperty(Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } void MeshVisual::SupplyEmptyGeometry() { - mGeometry = Geometry::New(); - mShader = Shader::New( SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG ); - mImpl->mRenderer = Renderer::New( mGeometry, mShader ); + mGeometry = Geometry::New(); + mShader = Shader::New(SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG); + mImpl->mRenderer = Renderer::New(mGeometry, mShader); - DALI_LOG_ERROR( "Initialisation error in mesh visual.\n" ); + DALI_LOG_ERROR("Initialisation error in mesh visual.\n"); } void MeshVisual::UpdateShaderUniforms() { - Stage stage = Stage::GetCurrent(); - float width = stage.GetSize().width; + Stage stage = Stage::GetCurrent(); + float width = stage.GetSize().width; float height = stage.GetSize().height; Matrix scaleMatrix; - scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) ); + scaleMatrix.SetIdentityAndScale(Vector3(1.0, -1.0, 1.0)); - mShader.RegisterProperty( STAGE_OFFSET_UNIFORM_NAME, Vector2( width, height ) / 2.0f ); - mShader.RegisterProperty( LIGHT_POSITION_NAME, mLightPosition ); - mShader.RegisterProperty( OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix ); + mShader.RegisterProperty(STAGE_OFFSET_UNIFORM_NAME, Vector2(width, height) / 2.0f); + mShader.RegisterProperty(LIGHT_POSITION_NAME, mLightPosition); + mShader.RegisterProperty(OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix); } void MeshVisual::CreateShader() { - if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) + if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING) { - mShader = Shader::New( SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_VERT, SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_FRAG ); + mShader = Shader::New(SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_VERT, SHADER_MESH_VISUAL_NORMAL_MAP_SHADER_FRAG); } - else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING ) + else if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING) { - mShader = Shader::New( SHADER_MESH_VISUAL_SHADER_VERT, SHADER_MESH_VISUAL_SHADER_FRAG ); + mShader = Shader::New(SHADER_MESH_VISUAL_SHADER_VERT, SHADER_MESH_VISUAL_SHADER_FRAG); } else //Textureless { - mShader = Shader::New( SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG ); + mShader = Shader::New(SHADER_MESH_VISUAL_SIMPLE_SHADER_VERT, SHADER_MESH_VISUAL_SIMPLE_SHADER_FRAG); } UpdateShaderUniforms(); @@ -358,74 +353,74 @@ void MeshVisual::CreateShader() bool MeshVisual::CreateGeometry() { //Determine if we need to use a simpler shader to handle the provided data - if( !mUseTexture || !mObjLoader.IsDiffuseMapPresent() ) + if(!mUseTexture || !mObjLoader.IsDiffuseMapPresent()) { mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING; } - else if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent()) ) + else if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING && (!mObjLoader.IsNormalMapPresent() || !mObjLoader.IsSpecularMapPresent())) { mShadingMode = Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING; } int objectProperties = 0; - if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING || - mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) + if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_SPECULAR_LIGHTING || + mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING) { objectProperties |= ObjLoader::TEXTURE_COORDINATES; } - if( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) + if(mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING) { objectProperties |= ObjLoader::TANGENTS | ObjLoader::BINORMALS; } //Create geometry with attributes required by shader. - mGeometry = mObjLoader.CreateGeometry( objectProperties, mUseSoftNormals ); + mGeometry = mObjLoader.CreateGeometry(objectProperties, mUseSoftNormals); - if( mGeometry ) + if(mGeometry) { return true; } - DALI_LOG_ERROR( "Failed to load geometry in mesh visual.\n" ); + DALI_LOG_ERROR("Failed to load geometry in mesh visual.\n"); return false; } bool MeshVisual::LoadGeometry() { - std::streampos fileSize; + std::streampos fileSize; Dali::Vector fileContent; - if( FileLoader::ReadFile( mObjectUrl, fileSize, fileContent, FileLoader::TEXT ) ) + if(FileLoader::ReadFile(mObjectUrl, fileSize, fileContent, FileLoader::TEXT)) { mObjLoader.ClearArrays(); - mObjLoader.LoadObject( fileContent.Begin(), fileSize ); + mObjLoader.LoadObject(fileContent.Begin(), fileSize); //Get size information from the obj loaded mSceneCenter = mObjLoader.GetCenter(); - mSceneSize = mObjLoader.GetSize(); + mSceneSize = mObjLoader.GetSize(); return true; } - DALI_LOG_ERROR( "Failed to find object to load in mesh visual.\n" ); + DALI_LOG_ERROR("Failed to find object to load in mesh visual.\n"); return false; } bool MeshVisual::LoadMaterial() { - std::streampos fileSize; + std::streampos fileSize; Dali::Vector fileContent; - if( FileLoader::ReadFile( mMaterialUrl, fileSize, fileContent, FileLoader::TEXT ) ) + if(FileLoader::ReadFile(mMaterialUrl, fileSize, fileContent, FileLoader::TEXT)) { //Load data into obj (usable) form - mObjLoader.LoadMaterial( fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl ); + mObjLoader.LoadMaterial(fileContent.Begin(), fileSize, mDiffuseTextureUrl, mNormalTextureUrl, mGlossTextureUrl); return true; } - DALI_LOG_ERROR( "Failed to find texture set to load in mesh visual.\n" ); + DALI_LOG_ERROR("Failed to find texture set to load in mesh visual.\n"); mUseTexture = false; return false; } @@ -434,64 +429,64 @@ bool MeshVisual::LoadTextures() { mTextureSet = TextureSet::New(); - if( mShadingMode != Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING ) + if(mShadingMode != Toolkit::MeshVisual::ShadingMode::TEXTURELESS_WITH_DIFFUSE_LIGHTING) { Sampler sampler = Sampler::New(); - if( mUseMipmapping ) + if(mUseMipmapping) { - sampler.SetFilterMode( FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR ); + sampler.SetFilterMode(FilterMode::LINEAR_MIPMAP_LINEAR, FilterMode::LINEAR_MIPMAP_LINEAR); } - if( !mDiffuseTextureUrl.empty() ) + if(!mDiffuseTextureUrl.empty()) { std::string imageUrl = mTexturesPath + mDiffuseTextureUrl; //Load textures - Texture diffuseTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping ); - if( diffuseTexture ) + Texture diffuseTexture = LoadTexture(imageUrl.c_str(), mUseMipmapping); + if(diffuseTexture) { - mTextureSet.SetTexture( DIFFUSE_INDEX, diffuseTexture ); - mTextureSet.SetSampler( DIFFUSE_INDEX, sampler ); + mTextureSet.SetTexture(DIFFUSE_INDEX, diffuseTexture); + mTextureSet.SetSampler(DIFFUSE_INDEX, sampler); } else { - DALI_LOG_ERROR( "Failed to load diffuse map texture in mesh visual.\n"); + DALI_LOG_ERROR("Failed to load diffuse map texture in mesh visual.\n"); return false; } } - if( !mNormalTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) ) + if(!mNormalTextureUrl.empty() && (mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING)) { std::string imageUrl = mTexturesPath + mNormalTextureUrl; //Load textures - Texture normalTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping ); - if( normalTexture ) + Texture normalTexture = LoadTexture(imageUrl.c_str(), mUseMipmapping); + if(normalTexture) { - mTextureSet.SetTexture( NORMAL_INDEX, normalTexture ); - mTextureSet.SetSampler( NORMAL_INDEX, sampler ); + mTextureSet.SetTexture(NORMAL_INDEX, normalTexture); + mTextureSet.SetSampler(NORMAL_INDEX, sampler); } else { - DALI_LOG_ERROR( "Failed to load normal map texture in mesh visual.\n"); + DALI_LOG_ERROR("Failed to load normal map texture in mesh visual.\n"); return false; } } - if( !mGlossTextureUrl.empty() && ( mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING ) ) + if(!mGlossTextureUrl.empty() && (mShadingMode == Toolkit::MeshVisual::ShadingMode::TEXTURED_WITH_DETAILED_SPECULAR_LIGHTING)) { std::string imageUrl = mTexturesPath + mGlossTextureUrl; //Load textures - Texture glossTexture = LoadTexture( imageUrl.c_str(), mUseMipmapping ); - if( glossTexture ) + Texture glossTexture = LoadTexture(imageUrl.c_str(), mUseMipmapping); + if(glossTexture) { - mTextureSet.SetTexture( GLOSS_INDEX, glossTexture ); - mTextureSet.SetSampler( GLOSS_INDEX, sampler ); + mTextureSet.SetTexture(GLOSS_INDEX, glossTexture); + mTextureSet.SetSampler(GLOSS_INDEX, sampler); } else { - DALI_LOG_ERROR( "Failed to load gloss map texture in mesh visual.\n"); + DALI_LOG_ERROR("Failed to load gloss map texture in mesh visual.\n"); return false; } } diff --git a/dali-toolkit/internal/visuals/npatch-data.cpp b/dali-toolkit/internal/visuals/npatch-data.cpp index e959003..45cb99f 100644 --- a/dali-toolkit/internal/visuals/npatch-data.cpp +++ b/dali-toolkit/internal/visuals/npatch-data.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,13 +26,10 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - NPatchData::NPatchData() : mId(INVALID_NPATCH_DATA_ID), mUrl(), @@ -50,9 +47,9 @@ NPatchData::NPatchData() NPatchData::~NPatchData() { // If there is an opacity map, it has to be destroyed using addon call - if( mRenderingMap ) + if(mRenderingMap) { - RenderingAddOn::Get().DestroyNPatch( mRenderingMap ); + RenderingAddOn::Get().DestroyNPatch(mRenderingMap); } } @@ -68,16 +65,16 @@ NPatchData::NPatchDataId NPatchData::GetId() const void NPatchData::AddObserver(TextureUploadObserver* textureObserver) { - mObserverList.PushBack( textureObserver ); + mObserverList.PushBack(textureObserver); } void NPatchData::RemoveObserver(TextureUploadObserver* textureObserver) { - for(uint32_t index = 0; index < mObserverList.Count(); ++index ) + for(uint32_t index = 0; index < mObserverList.Count(); ++index) { if(textureObserver == mObserverList[index]) { - mObserverList.Erase( mObserverList.begin() + index ); + mObserverList.Erase(mObserverList.begin() + index); break; } } @@ -193,45 +190,45 @@ void* NPatchData::GetRenderingMap() const return mRenderingMap; } -void NPatchData::SetLoadedNPatchData( Devel::PixelBuffer& pixelBuffer, bool preMultiplied ) +void NPatchData::SetLoadedNPatchData(Devel::PixelBuffer& pixelBuffer, bool preMultiplied) { - if( mBorder == Rect< int >( 0, 0, 0, 0 ) ) + if(mBorder == Rect(0, 0, 0, 0)) { - NPatchUtility::ParseBorders( pixelBuffer, mStretchPixelsX, mStretchPixelsY ); + NPatchUtility::ParseBorders(pixelBuffer, mStretchPixelsX, mStretchPixelsY); // Crop the image - pixelBuffer.Crop( 1, 1, pixelBuffer.GetWidth() - 2, pixelBuffer.GetHeight() - 2 ); + pixelBuffer.Crop(1, 1, pixelBuffer.GetWidth() - 2, pixelBuffer.GetHeight() - 2); } else { - mStretchPixelsX.PushBack( Uint16Pair( mBorder.left, ( (pixelBuffer.GetWidth() >= static_cast< unsigned int >( mBorder.right )) ? pixelBuffer.GetWidth() - mBorder.right : 0 ) ) ); - mStretchPixelsY.PushBack( Uint16Pair( mBorder.top, ( (pixelBuffer.GetHeight() >= static_cast< unsigned int >( mBorder.bottom )) ? pixelBuffer.GetHeight() - mBorder.bottom : 0 ) ) ); + mStretchPixelsX.PushBack(Uint16Pair(mBorder.left, ((pixelBuffer.GetWidth() >= static_cast(mBorder.right)) ? pixelBuffer.GetWidth() - mBorder.right : 0))); + mStretchPixelsY.PushBack(Uint16Pair(mBorder.top, ((pixelBuffer.GetHeight() >= static_cast(mBorder.bottom)) ? pixelBuffer.GetHeight() - mBorder.bottom : 0))); } - mCroppedWidth = pixelBuffer.GetWidth(); + mCroppedWidth = pixelBuffer.GetWidth(); mCroppedHeight = pixelBuffer.GetHeight(); // Create opacity map mRenderingMap = RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().BuildNPatch(pixelBuffer, this) : nullptr; - PixelData pixels = Devel::PixelBuffer::Convert( pixelBuffer ); // takes ownership of buffer + PixelData pixels = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer - Texture texture = Texture::New( TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight() ); - texture.Upload( pixels ); + Texture texture = Texture::New(TextureType::TEXTURE_2D, pixels.GetPixelFormat(), pixels.GetWidth(), pixels.GetHeight()); + texture.Upload(pixels); mTextureSet = TextureSet::New(); - mTextureSet.SetTexture( 0u, texture ); + mTextureSet.SetTexture(0u, texture); mPreMultiplyOnLoad = preMultiplied; mLoadingState = LoadingState::LOAD_COMPLETE; } -void NPatchData::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied ) +void NPatchData::LoadComplete(bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied) { if(loadSuccess) { - SetLoadedNPatchData( pixelBuffer, preMultiplied ); + SetLoadedNPatchData(pixelBuffer, preMultiplied); } else { diff --git a/dali-toolkit/internal/visuals/npatch-loader.cpp b/dali-toolkit/internal/visuals/npatch-loader.cpp index f0b154a..a7734da 100644 --- a/dali-toolkit/internal/visuals/npatch-loader.cpp +++ b/dali-toolkit/internal/visuals/npatch-loader.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. @@ -27,18 +27,14 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - constexpr auto INVALID_CACHE_INDEX = int32_t{-1}; ///< Invalid Cache index -constexpr auto UNINITIALIZED_ID = int32_t{0}; ///< uninitialised id, use to initialize ids +constexpr auto UNINITIALIZED_ID = int32_t{0}; ///< uninitialised id, use to initialize ids } // Anonymous namespace @@ -56,58 +52,58 @@ NPatchData::NPatchDataId NPatchLoader::GenerateUniqueNPatchDataId() return mCurrentNPatchDataId++; } -std::size_t NPatchLoader::Load( TextureManager& textureManager, TextureUploadObserver* textureObserver, const std::string& url, const Rect< int >& border, bool& preMultiplyOnLoad, bool synchronousLoading ) +std::size_t NPatchLoader::Load(TextureManager& textureManager, TextureUploadObserver* textureObserver, const std::string& url, const Rect& border, bool& preMultiplyOnLoad, bool synchronousLoading) { - std::size_t hash = CalculateHash( url ); - OwnerContainer< NPatchData* >::SizeType index = UNINITIALIZED_ID; - const OwnerContainer< NPatchData* >::SizeType count = mCache.Count(); + std::size_t hash = CalculateHash(url); + OwnerContainer::SizeType index = UNINITIALIZED_ID; + const OwnerContainer::SizeType count = mCache.Count(); - for( ; index < count; ++index ) + for(; index < count; ++index) { - if( mCache[ index ]->GetHash() == hash ) + if(mCache[index]->GetHash() == hash) { // hash match, check url as well in case of hash collision - if(mCache[ index ]->GetUrl() == url) + if(mCache[index]->GetUrl() == url) { // Use cached data - if( mCache[ index ]->GetBorder() == border ) + if(mCache[index]->GetBorder() == border) { - if( mCache[ index ]->GetLoadingState() == NPatchData::LoadingState::LOADING ) + if(mCache[index]->GetLoadingState() == NPatchData::LoadingState::LOADING) { - mCache[ index ]->AddObserver( textureObserver ); + mCache[index]->AddObserver(textureObserver); } - return mCache[ index ]->GetId(); // valid indices are from 1 onwards + return mCache[index]->GetId(); // valid indices are from 1 onwards } else { - if( mCache[ index ]->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE ) + if(mCache[index]->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE) { // Same url but border is different - use the existing texture NPatchData* newData = new NPatchData(); newData->SetId(GenerateUniqueNPatchDataId()); newData->SetHash(hash); newData->SetUrl(url); - newData->SetCroppedWidth(mCache[ index ]->GetCroppedWidth()); - newData->SetCroppedHeight(mCache[ index ]->GetCroppedHeight()); + newData->SetCroppedWidth(mCache[index]->GetCroppedWidth()); + newData->SetCroppedHeight(mCache[index]->GetCroppedHeight()); - newData->SetTextures(mCache[ index ]->GetTextures()); + newData->SetTextures(mCache[index]->GetTextures()); NPatchUtility::StretchRanges stretchRangesX; - stretchRangesX.PushBack( Uint16Pair( border.left, ( (newData->GetCroppedWidth() >= static_cast< unsigned int >( border.right )) ? newData->GetCroppedHeight() - border.right : 0 ) ) ); + stretchRangesX.PushBack(Uint16Pair(border.left, ((newData->GetCroppedWidth() >= static_cast(border.right)) ? newData->GetCroppedHeight() - border.right : 0))); NPatchUtility::StretchRanges stretchRangesY; - stretchRangesY.PushBack( Uint16Pair( border.top, ( (newData->GetCroppedWidth() >= static_cast< unsigned int >( border.bottom )) ? newData->GetCroppedHeight() - border.bottom : 0 ) ) ); + stretchRangesY.PushBack(Uint16Pair(border.top, ((newData->GetCroppedWidth() >= static_cast(border.bottom)) ? newData->GetCroppedHeight() - border.bottom : 0))); newData->SetStretchPixelsX(stretchRangesX); newData->SetStretchPixelsY(stretchRangesY); newData->SetBorder(border); - newData->SetPreMultiplyOnLoad(mCache[ index ]->IsPreMultiplied()); + newData->SetPreMultiplyOnLoad(mCache[index]->IsPreMultiplied()); newData->SetLoadingState(NPatchData::LoadingState::LOAD_COMPLETE); - newData->AddObserver( textureObserver ); + newData->AddObserver(textureObserver); - mCache.PushBack( newData ); + mCache.PushBack(newData); return newData->GetId(); // valid ids start from 1u } @@ -130,26 +126,24 @@ std::size_t NPatchLoader::Load( TextureManager& textureManager, TextureUploadObs auto preMultiplyOnLoading = preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; - Devel::PixelBuffer pixelBuffer = textureManager.LoadPixelBuffer( url, Dali::ImageDimensions(), FittingMode::DEFAULT, - SamplingMode::BOX_THEN_LINEAR, synchronousLoading, - data, true, preMultiplyOnLoading ); + Devel::PixelBuffer pixelBuffer = textureManager.LoadPixelBuffer(url, Dali::ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, data, true, preMultiplyOnLoading); - if( pixelBuffer ) + if(pixelBuffer) { - preMultiplyOnLoad = ( preMultiplyOnLoading == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD ) ? true : false; - data->SetLoadedNPatchData( pixelBuffer, preMultiplyOnLoad ); + preMultiplyOnLoad = (preMultiplyOnLoading == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD) ? true : false; + data->SetLoadedNPatchData(pixelBuffer, preMultiplyOnLoad); } return data->GetId(); } -int32_t NPatchLoader::GetCacheIndexFromId( const NPatchData::NPatchDataId id ) +int32_t NPatchLoader::GetCacheIndexFromId(const NPatchData::NPatchDataId id) { const unsigned int size = mCache.Count(); - for( unsigned int i = 0; i < size; ++i ) + for(unsigned int i = 0; i < size; ++i) { - if( mCache[i]->GetId() == id ) + if(mCache[i]->GetId() == id) { return i; } @@ -158,10 +152,10 @@ int32_t NPatchLoader::GetCacheIndexFromId( const NPatchData::NPatchDataId id ) return INVALID_CACHE_INDEX; } -bool NPatchLoader::GetNPatchData( const NPatchData::NPatchDataId id, const NPatchData*& data ) +bool NPatchLoader::GetNPatchData(const NPatchData::NPatchDataId id, const NPatchData*& data) { int32_t cacheIndex = GetCacheIndexFromId(id); - if( cacheIndex != INVALID_CACHE_INDEX ) + if(cacheIndex != INVALID_CACHE_INDEX) { data = mCache[cacheIndex]; return true; @@ -170,10 +164,10 @@ bool NPatchLoader::GetNPatchData( const NPatchData::NPatchDataId id, const NPatc return false; } -void NPatchLoader::Remove( std::size_t id, TextureUploadObserver* textureObserver ) +void NPatchLoader::Remove(std::size_t id, TextureUploadObserver* textureObserver) { int32_t cacheIndex = GetCacheIndexFromId(id); - if( cacheIndex == INVALID_CACHE_INDEX ) + if(cacheIndex == INVALID_CACHE_INDEX) { return; } @@ -185,7 +179,7 @@ void NPatchLoader::Remove( std::size_t id, TextureUploadObserver* textureObserve if(data->GetObserverCount() == 0) { - mCache.Erase( mCache.Begin() + cacheIndex ); + mCache.Erase(mCache.Begin() + cacheIndex); } } diff --git a/dali-toolkit/internal/visuals/npatch/npatch-visual.cpp b/dali-toolkit/internal/visuals/npatch/npatch-visual.cpp index ccee97d..4e95dfe 100644 --- a/dali-toolkit/internal/visuals/npatch/npatch-visual.cpp +++ b/dali-toolkit/internal/visuals/npatch/npatch-visual.cpp @@ -19,8 +19,8 @@ #include "npatch-visual.h" // EXTERNAL INCLUDES -#include #include +#include #include // INTERNAL INCLUDES @@ -38,16 +38,12 @@ namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - /** * @brief Creates the geometry formed from the vertices and indices * @@ -55,25 +51,24 @@ namespace * @param[in] indices The indices to generate the geometry from * @return The geometry formed from the vertices and indices */ -Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices ) +Geometry GenerateGeometry(const Vector& vertices, const Vector& indices) { Property::Map vertexFormat; - vertexFormat[ "aPosition" ] = Property::VECTOR2; - VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat ); - if( vertices.Size() > 0 ) + vertexFormat["aPosition"] = Property::VECTOR2; + VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat); + if(vertices.Size() > 0) { - vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() ); + vertexBuffer.SetData(&vertices[0], vertices.Size()); } // Create the geometry object Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( vertexBuffer ); - if( indices.Size() > 0 ) + geometry.AddVertexBuffer(vertexBuffer); + if(indices.Size() > 0) { - geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() ); + geometry.SetIndexBuffer(&indices[0], indices.Size()); } - return geometry; } @@ -84,42 +79,42 @@ Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsi * @param[in] rowIdx The row index to start the quad * @param[in] nextRowIdx The index to the next row */ -void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx ) +void AddQuadIndices(Vector& indices, unsigned int rowIdx, unsigned int nextRowIdx) { - indices.PushBack( rowIdx ); - indices.PushBack( nextRowIdx + 1 ); - indices.PushBack( rowIdx + 1 ); + indices.PushBack(rowIdx); + indices.PushBack(nextRowIdx + 1); + indices.PushBack(rowIdx + 1); - indices.PushBack( rowIdx ); - indices.PushBack( nextRowIdx ); - indices.PushBack( nextRowIdx + 1 ); + indices.PushBack(rowIdx); + indices.PushBack(nextRowIdx); + indices.PushBack(nextRowIdx + 1); } -void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y ) +void AddVertex(Vector& vertices, unsigned int x, unsigned int y) { - vertices.PushBack( Vector2( x, y ) ); + vertices.PushBack(Vector2(x, y)); } -void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent) +void RegisterStretchProperties(Renderer& renderer, const char* uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent) { - uint16_t prevEnd = 0; - uint16_t prevFix = 0; - uint16_t prevStretch = 0; - unsigned int i = 1; - for( NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i ) + uint16_t prevEnd = 0; + uint16_t prevFix = 0; + uint16_t prevStretch = 0; + unsigned int i = 1; + for(NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i) { uint16_t start = it->GetX(); - uint16_t end = it->GetY(); + uint16_t end = it->GetY(); - uint16_t fix = prevFix + start - prevEnd; + uint16_t fix = prevFix + start - prevEnd; uint16_t stretch = prevStretch + end - start; std::stringstream uniform; uniform << uniformName << "[" << i << "]"; - renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) ); + renderer.RegisterProperty(uniform.str(), Vector2(fix, stretch)); - prevEnd = end; - prevFix = fix; + prevEnd = end; + prevFix = fix; prevStretch = stretch; } @@ -127,7 +122,7 @@ void RegisterStretchProperties( Renderer& renderer, const char * uniformName, co prevFix += imageExtent - prevEnd; std::stringstream uniform; uniform << uniformName << "[" << i << "]"; - renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) ); + renderer.RegisterProperty(uniform.str(), Vector2(prevFix, prevStretch)); } } @@ -139,7 +134,7 @@ NPatchVisualPtr NPatchVisual::New(VisualFactoryCache& factoryCache, ImageVisualS { NPatchVisualPtr nPatchVisual(new NPatchVisual(factoryCache, shaderFactory)); nPatchVisual->mImageUrl = imageUrl; - nPatchVisual->SetProperties( properties ); + nPatchVisual->SetProperties(properties); nPatchVisual->Initialize(); return nPatchVisual; } @@ -154,49 +149,47 @@ NPatchVisualPtr NPatchVisual::New(VisualFactoryCache& factoryCache, ImageVisualS void NPatchVisual::LoadImages() { - TextureManager& textureManager = mFactoryCache.GetTextureManager(); - bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING; + TextureManager& textureManager = mFactoryCache.GetTextureManager(); + bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING; - if( mId == NPatchData::INVALID_NPATCH_DATA_ID && mImageUrl.IsLocalResource() ) + if(mId == NPatchData::INVALID_NPATCH_DATA_ID && mImageUrl.IsLocalResource()) { bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false; - mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading ); + mId = mLoader.Load(textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading); const NPatchData* data; - if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE ) + if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE) { - EnablePreMultipliedAlpha( data->IsPreMultiplied() ); + EnablePreMultipliedAlpha(data->IsPreMultiplied()); } } - if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() ) + if(!mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource()) { // Load the auxiliary image auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; - mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT, - SamplingMode::BOX_THEN_LINEAR, synchronousLoading, - this, true, preMultiplyOnLoading ); + mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer(mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, this, true, preMultiplyOnLoading); } } -void NPatchVisual::GetNaturalSize( Vector2& naturalSize ) +void NPatchVisual::GetNaturalSize(Vector2& naturalSize) { naturalSize.x = 0u; naturalSize.y = 0u; // load now if not already loaded const NPatchData* data; - if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() != NPatchData::LoadingState::LOADING ) + if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() != NPatchData::LoadingState::LOADING) { naturalSize.x = data->GetCroppedWidth(); naturalSize.y = data->GetCroppedHeight(); } else { - if( mImageUrl.IsValid() ) + if(mImageUrl.IsValid()) { - ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() ); - if( dimensions != ImageDimensions( 0, 0 ) ) + ImageDimensions dimensions = Dali::GetOriginalImageSize(mImageUrl.GetUrl()); + if(dimensions != ImageDimensions(0, 0)) { naturalSize.x = dimensions.GetWidth(); naturalSize.y = dimensions.GetHeight(); @@ -204,59 +197,59 @@ void NPatchVisual::GetNaturalSize( Vector2& naturalSize ) } } - if( mAuxiliaryPixelBuffer ) + if(mAuxiliaryPixelBuffer) { - naturalSize.x = std::max( naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()) ); - naturalSize.y = std::max( naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()) ); + naturalSize.x = std::max(naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth())); + naturalSize.y = std::max(naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight())); } } -void NPatchVisual::DoSetProperties( const Property::Map& propertyMap ) +void NPatchVisual::DoSetProperties(const Property::Map& propertyMap) { // URL is already passed in via constructor - Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY ); - if( borderOnlyValue ) + Property::Value* borderOnlyValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY); + if(borderOnlyValue) { - borderOnlyValue->Get( mBorderOnly ); + borderOnlyValue->Get(mBorderOnly); } - Property::Value* borderValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER, BORDER ); - if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder + Property::Value* borderValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER, BORDER); + if(borderValue && !borderValue->Get(mBorder)) // If value exists and is rect, just set mBorder { // Not a rect so try vector4 Vector4 border; - if( borderValue->Get( border ) ) + if(borderValue->Get(border)) { - mBorder.left = static_cast< int >( border.x ); - mBorder.right = static_cast< int >( border.y ); - mBorder.bottom = static_cast< int >( border.z ); - mBorder.top = static_cast< int >( border.w ); + mBorder.left = static_cast(border.x); + mBorder.right = static_cast(border.y); + mBorder.bottom = static_cast(border.z); + mBorder.top = static_cast(border.w); } } - Property::Value* auxImage = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME ); - if( auxImage ) + Property::Value* auxImage = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME); + if(auxImage) { std::string url; - if( auxImage->Get( url ) ) + if(auxImage->Get(url)) { mAuxiliaryUrl = url; } } - Property::Value* auxImageAlpha = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME ); - if( auxImageAlpha ) + Property::Value* auxImageAlpha = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME); + if(auxImageAlpha) { - auxImageAlpha->Get( mAuxiliaryImageAlpha ); + auxImageAlpha->Get(mAuxiliaryImageAlpha); } - Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING ); - if( synchronousLoading ) + Property::Value* synchronousLoading = propertyMap.Find(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING); + if(synchronousLoading) { bool sync = false; - synchronousLoading->Get( sync ); - if( sync ) + synchronousLoading->Get(sync); + if(sync) { mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING; } @@ -266,90 +259,90 @@ void NPatchVisual::DoSetProperties( const Property::Map& propertyMap ) } } - Property::Value* releasePolicy = propertyMap.Find( Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME ); - if( releasePolicy ) + Property::Value* releasePolicy = propertyMap.Find(Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME); + if(releasePolicy) { - releasePolicy->Get( mReleasePolicy ); + releasePolicy->Get(mReleasePolicy); } } -void NPatchVisual::DoSetOnScene( Actor& actor ) +void NPatchVisual::DoSetOnScene(Actor& actor) { // load when first go on stage LoadImages(); const NPatchData* data; - if( mLoader.GetNPatchData( mId, data ) ) + if(mLoader.GetNPatchData(mId, data)) { Geometry geometry = CreateGeometry(); - Shader shader = CreateShader(); + Shader shader = CreateShader(); mImpl->mRenderer.SetGeometry(geometry); mImpl->mRenderer.SetShader(shader); mPlacementActor = actor; - if( data->GetLoadingState() != NPatchData::LoadingState::LOADING ) + if(data->GetLoadingState() != NPatchData::LoadingState::LOADING) { - if( RenderingAddOn::Get().IsValid() ) + if(RenderingAddOn::Get().IsValid()) { - RenderingAddOn::Get().SubmitRenderTask( mImpl->mRenderer, data->GetRenderingMap() ); + RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap()); } ApplyTextureAndUniforms(); - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); mPlacementActor.Reset(); // npatch loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } } } -void NPatchVisual::DoSetOffScene( Actor& actor ) +void NPatchVisual::DoSetOffScene(Actor& actor) { if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED) { mLoader.Remove(mId, this); mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING; - mId = NPatchData::INVALID_NPATCH_DATA_ID; + mId = NPatchData::INVALID_NPATCH_DATA_ID; } - actor.RemoveRenderer( mImpl->mRenderer ); + actor.RemoveRenderer(mImpl->mRenderer); mPlacementActor.Reset(); } void NPatchVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } -void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const +void NPatchVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); bool sync = IsSynchronousLoadingRequired(); - map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync ); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH ); - map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() ); - map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly ); - map.Insert( Toolkit::ImageVisual::Property::BORDER, mBorder ); - map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy ); + map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH); + map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl()); + map.Insert(Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly); + map.Insert(Toolkit::ImageVisual::Property::BORDER, mBorder); + map.Insert(Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy); - if( mAuxiliaryUrl.IsValid() ) + if(mAuxiliaryUrl.IsValid()) { - map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() ); - map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha ); + map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl()); + map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha); } } -void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void NPatchVisual::DoCreateInstancePropertyMap(Property::Map& map) const { - if( mAuxiliaryUrl.IsValid() ) + if(mAuxiliaryUrl.IsValid()) { - map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() ); - map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha ); + map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl()); + map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha); } } @@ -366,12 +359,12 @@ NPatchVisual::NPatchVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFa mAuxiliaryImageAlpha(0.0f), mReleasePolicy(Toolkit::ImageVisual::ReleasePolicy::DETACHED) { - EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() ); + EnablePreMultipliedAlpha(mFactoryCache.GetPreMultiplyOnLoad()); } NPatchVisual::~NPatchVisual() { - if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER )) + if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && (mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER)) { mLoader.Remove(mId, this); mId = NPatchData::INVALID_NPATCH_DATA_ID; @@ -392,46 +385,45 @@ void NPatchVisual::OnInitialize() Geometry NPatchVisual::CreateGeometry() { - Geometry geometry; + Geometry geometry; const NPatchData* data; - if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE ) + if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE) { - if( data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1 ) + if(data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1) { - if( DALI_UNLIKELY( mBorderOnly ) ) + if(DALI_UNLIKELY(mBorderOnly)) { - geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY ); + geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY); } else { - if( data->GetRenderingMap() ) + if(data->GetRenderingMap()) { uint32_t elementCount[2]; - geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount ); - if( mImpl->mRenderer ) + geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount); + if(mImpl->mRenderer) { RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap()); } } else { - geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY ); + geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY); } } } - else if( data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0) + else if(data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0) { - Uint16Pair gridSize( 2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1 ); - if( !data->GetRenderingMap() ) + Uint16Pair gridSize(2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1); + if(!data->GetRenderingMap()) { - geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize ); + geometry = !mBorderOnly ? CreateGridGeometry(gridSize) : CreateBorderGeometry(gridSize); } else { uint32_t elementCount[2]; - geometry = !mBorderOnly ? - RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount ) : CreateBorderGeometry(gridSize ); - if( mImpl->mRenderer ) + geometry = !mBorderOnly ? RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount) : CreateBorderGeometry(gridSize); + if(mImpl->mRenderer) { RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap()); } @@ -441,14 +433,14 @@ Geometry NPatchVisual::CreateGeometry() else { // no N patch data so use default geometry - geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY ); + geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY); } return geometry; } Shader NPatchVisual::CreateShader() { - Shader shader; + Shader shader; const NPatchData* data; // 0 is either no data (load failed?) or no stretch regions on image // for both cases we use the default shader @@ -457,69 +449,69 @@ Shader NPatchVisual::CreateShader() auto fragmentShader = mAuxiliaryPixelBuffer ? SHADER_NPATCH_VISUAL_MASK_SHADER_FRAG : SHADER_NPATCH_VISUAL_SHADER_FRAG; - auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER - : VisualFactoryCache::NINE_PATCH_SHADER; + auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER + : VisualFactoryCache::NINE_PATCH_SHADER; // ask loader for the regions - if( mLoader.GetNPatchData( mId, data ) ) + if(mLoader.GetNPatchData(mId, data)) { xStretchCount = data->GetStretchPixelsX().Count(); yStretchCount = data->GetStretchPixelsY().Count(); } - if( DALI_LIKELY( !mImpl->mCustomShader ) ) + if(DALI_LIKELY(!mImpl->mCustomShader)) { - if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) || - ( xStretchCount == 0 && yStretchCount == 0 ) ) ) + if(DALI_LIKELY((xStretchCount == 1 && yStretchCount == 1) || + (xStretchCount == 0 && yStretchCount == 0))) { - shader = mFactoryCache.GetShader( shaderType ); - if( DALI_UNLIKELY( !shader ) ) + shader = mFactoryCache.GetShader(shaderType); + if(DALI_UNLIKELY(!shader)) { - shader = Shader::New( SHADER_NPATCH_VISUAL_3X3_SHADER_VERT, fragmentShader ); + shader = Shader::New(SHADER_NPATCH_VISUAL_3X3_SHADER_VERT, fragmentShader); // Only cache vanilla 9 patch shaders - mFactoryCache.SaveShader( shaderType, shader ); + mFactoryCache.SaveShader(shaderType, shader); } } - else if( xStretchCount > 0 || yStretchCount > 0) + else if(xStretchCount > 0 || yStretchCount > 0) { std::stringstream vertexShader; vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n" << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n" << SHADER_NPATCH_VISUAL_SHADER_VERT; - shader = Shader::New( vertexShader.str(), fragmentShader ); + shader = Shader::New(vertexShader.str(), fragmentShader); } } else { Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE; - if( !mImpl->mCustomShader->mFragmentShader.empty() ) + if(!mImpl->mCustomShader->mFragmentShader.empty()) { fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str(); } hints = mImpl->mCustomShader->mHints; /* Apply Custom Vertex Shader only if image is 9-patch */ - if( ( xStretchCount == 1 && yStretchCount == 1 ) || - ( xStretchCount == 0 && yStretchCount == 0 ) ) + if((xStretchCount == 1 && yStretchCount == 1) || + (xStretchCount == 0 && yStretchCount == 0)) { const char* vertexShader = SHADER_NPATCH_VISUAL_3X3_SHADER_VERT.data(); - if( !mImpl->mCustomShader->mVertexShader.empty() ) + if(!mImpl->mCustomShader->mVertexShader.empty()) { vertexShader = mImpl->mCustomShader->mVertexShader.c_str(); } - shader = Shader::New( vertexShader, fragmentShader, hints ); + shader = Shader::New(vertexShader, fragmentShader, hints); } - else if( xStretchCount > 0 || yStretchCount > 0) + else if(xStretchCount > 0 || yStretchCount > 0) { std::stringstream vertexShader; vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n" << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n" << SHADER_NPATCH_VISUAL_SHADER_VERT; - shader = Shader::New( vertexShader.str(), fragmentShader, hints ); + shader = Shader::New(vertexShader.str(), fragmentShader, hints); } } @@ -529,267 +521,269 @@ Shader NPatchVisual::CreateShader() void NPatchVisual::ApplyTextureAndUniforms() { const NPatchData* data; - TextureSet textureSet; + TextureSet textureSet; - if( mLoader.GetNPatchData( mId, data ) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE ) + if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE) { textureSet = data->GetTextures(); - if( data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1 ) + if(data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1) { //special case for 9 patch - Uint16Pair stretchX = data->GetStretchPixelsX()[ 0 ]; - Uint16Pair stretchY = data->GetStretchPixelsY()[ 0 ]; + Uint16Pair stretchX = data->GetStretchPixelsX()[0]; + Uint16Pair stretchY = data->GetStretchPixelsY()[0]; - uint16_t stretchWidth = ( stretchX.GetY() >= stretchX.GetX() ) ? stretchX.GetY() - stretchX.GetX() : 0; - uint16_t stretchHeight = ( stretchY.GetY() >= stretchY.GetX() ) ? stretchY.GetY() - stretchY.GetX() : 0; + uint16_t stretchWidth = (stretchX.GetY() >= stretchX.GetX()) ? stretchX.GetY() - stretchX.GetX() : 0; + uint16_t stretchHeight = (stretchY.GetY() >= stretchY.GetX()) ? stretchY.GetY() - stretchY.GetX() : 0; - mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO ); - mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) ); - mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->GetCroppedWidth() - stretchWidth, data->GetCroppedHeight() - stretchHeight ) ); - mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) ); + mImpl->mRenderer.RegisterProperty("uFixed[0]", Vector2::ZERO); + mImpl->mRenderer.RegisterProperty("uFixed[1]", Vector2(stretchX.GetX(), stretchY.GetX())); + mImpl->mRenderer.RegisterProperty("uFixed[2]", Vector2(data->GetCroppedWidth() - stretchWidth, data->GetCroppedHeight() - stretchHeight)); + mImpl->mRenderer.RegisterProperty("uStretchTotal", Vector2(stretchWidth, stretchHeight)); } else { - mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO ); - mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO ); + mImpl->mRenderer.RegisterProperty("uNinePatchFactorsX[0]", Vector2::ZERO); + mImpl->mRenderer.RegisterProperty("uNinePatchFactorsY[0]", Vector2::ZERO); - RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->GetStretchPixelsX(), data->GetCroppedWidth() ); - RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->GetStretchPixelsY(), data->GetCroppedHeight() ); + RegisterStretchProperties(mImpl->mRenderer, "uNinePatchFactorsX", data->GetStretchPixelsX(), data->GetCroppedWidth()); + RegisterStretchProperties(mImpl->mRenderer, "uNinePatchFactorsY", data->GetStretchPixelsY(), data->GetCroppedHeight()); } } else { - DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() ); + DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str()); textureSet = TextureSet::New(); Texture croppedImage = mFactoryCache.GetBrokenVisualImage(); - textureSet.SetTexture( 0u, croppedImage ); - mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO ); - mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO ); - mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO ); - mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) ); + textureSet.SetTexture(0u, croppedImage); + mImpl->mRenderer.RegisterProperty("uFixed[0]", Vector2::ZERO); + mImpl->mRenderer.RegisterProperty("uFixed[1]", Vector2::ZERO); + mImpl->mRenderer.RegisterProperty("uFixed[2]", Vector2::ZERO); + mImpl->mRenderer.RegisterProperty("uStretchTotal", Vector2(croppedImage.GetWidth(), croppedImage.GetHeight())); } - if( mAuxiliaryPixelBuffer ) + if(mAuxiliaryPixelBuffer) { // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the // same size as the unstretched NPatch. This will give slightly higher quality results than just relying // on GL interpolation alone. - if( mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() && - mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight() ) + if(mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() && + mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight()) { - mAuxiliaryPixelBuffer.Resize( data->GetCroppedWidth(), data->GetCroppedHeight() ); + mAuxiliaryPixelBuffer.Resize(data->GetCroppedWidth(), data->GetCroppedHeight()); } // Note, this resets mAuxiliaryPixelBuffer handle - auto auxiliaryPixelData = Devel::PixelBuffer::Convert( mAuxiliaryPixelBuffer ); + auto auxiliaryPixelData = Devel::PixelBuffer::Convert(mAuxiliaryPixelBuffer); - auto texture = Texture::New( TextureType::TEXTURE_2D, - auxiliaryPixelData.GetPixelFormat(), auxiliaryPixelData.GetWidth(), - auxiliaryPixelData.GetHeight() ); - texture.Upload( auxiliaryPixelData ); - textureSet.SetTexture( 1, texture ); - mImpl->mRenderer.RegisterProperty( DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, - AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha ); + auto texture = Texture::New(TextureType::TEXTURE_2D, + auxiliaryPixelData.GetPixelFormat(), + auxiliaryPixelData.GetWidth(), + auxiliaryPixelData.GetHeight()); + texture.Upload(auxiliaryPixelData); + textureSet.SetTexture(1, texture); + mImpl->mRenderer.RegisterProperty(DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, + AUXILIARY_IMAGE_ALPHA_NAME, + mAuxiliaryImageAlpha); } - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); // Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } -Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType ) +Geometry NPatchVisual::GetNinePatchGeometry(VisualFactoryCache::GeometryType subType) { - Geometry geometry = mFactoryCache.GetGeometry( subType ); - if( !geometry ) + Geometry geometry = mFactoryCache.GetGeometry(subType); + if(!geometry) { - if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) ) + if(DALI_LIKELY(VisualFactoryCache::NINE_PATCH_GEOMETRY == subType)) { - geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) ); + geometry = CreateGridGeometry(Uint16Pair(3, 3)); } - else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType ) + else if(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType) { - geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) ); + geometry = CreateBorderGeometry(Uint16Pair(3, 3)); } - mFactoryCache.SaveGeometry( subType, geometry ); + mFactoryCache.SaveGeometry(subType, geometry); } return geometry; } -Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize ) +Geometry NPatchVisual::CreateGridGeometry(Uint16Pair gridSize) { - uint16_t gridWidth = gridSize.GetWidth(); + uint16_t gridWidth = gridSize.GetWidth(); uint16_t gridHeight = gridSize.GetHeight(); // Create vertices - Vector< Vector2 > vertices; - vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) ); + Vector vertices; + vertices.Reserve((gridWidth + 1) * (gridHeight + 1)); - for( int y = 0; y < gridHeight + 1; ++y ) + for(int y = 0; y < gridHeight + 1; ++y) { - for( int x = 0; x < gridWidth + 1; ++x ) + for(int x = 0; x < gridWidth + 1; ++x) { - AddVertex( vertices, x, y ); + AddVertex(vertices, x, y); } } // Create indices - Vector< unsigned short > indices; - indices.Reserve( gridWidth * gridHeight * 6 ); + Vector indices; + indices.Reserve(gridWidth * gridHeight * 6); unsigned int rowIdx = 0; unsigned int nextRowIdx = gridWidth + 1; - for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx ) + for(int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx) { - for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx ) + for(int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx) { - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); } } - return GenerateGeometry( vertices, indices ); + return GenerateGeometry(vertices, indices); } -Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize ) +Geometry NPatchVisual::CreateBorderGeometry(Uint16Pair gridSize) { - uint16_t gridWidth = gridSize.GetWidth(); + uint16_t gridWidth = gridSize.GetWidth(); uint16_t gridHeight = gridSize.GetHeight(); // Create vertices - Vector< Vector2 > vertices; - vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) ); + Vector vertices; + vertices.Reserve((gridWidth + 1) * (gridHeight + 1)); //top int y = 0; for(; y < 2; ++y) { - for( int x = 0; x < gridWidth + 1; ++x ) + for(int x = 0; x < gridWidth + 1; ++x) { - AddVertex( vertices, x, y ); + AddVertex(vertices, x, y); } } for(; y < gridHeight - 1; ++y) { //left - AddVertex( vertices, 0, y ); - AddVertex( vertices, 1, y ); + AddVertex(vertices, 0, y); + AddVertex(vertices, 1, y); //right - AddVertex( vertices, gridWidth - 1, y ); - AddVertex( vertices, gridWidth, y ); + AddVertex(vertices, gridWidth - 1, y); + AddVertex(vertices, gridWidth, y); } //bottom for(; y < gridHeight + 1; ++y) { - for( int x = 0; x < gridWidth + 1; ++x ) + for(int x = 0; x < gridWidth + 1; ++x) { - AddVertex( vertices, x, y ); + AddVertex(vertices, x, y); } } // Create indices - Vector< unsigned short > indices; - indices.Reserve( gridWidth * gridHeight * 6 ); + Vector indices; + indices.Reserve(gridWidth * gridHeight * 6); //top - unsigned int rowIdx = 0 ; + unsigned int rowIdx = 0; unsigned int nextRowIdx = gridWidth + 1; - for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx ) + for(int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx) { - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); } if(gridHeight > 2) { rowIdx = gridWidth + 1; - nextRowIdx = ( gridWidth + 1 ) * 2; + nextRowIdx = (gridWidth + 1) * 2; unsigned increment = gridWidth - 1; if(gridHeight > 3) { increment = 2; //second row left - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); rowIdx = gridWidth * 2; - nextRowIdx = ( gridWidth + 1 ) * 2 + 2; + nextRowIdx = (gridWidth + 1) * 2 + 2; //second row right - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); //left and right rowIdx = nextRowIdx - 2; nextRowIdx = rowIdx + 4; - for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2) + for(int y = 2; y < 2 * (gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2) { - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); } } //second row left - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); - rowIdx += increment; + rowIdx += increment; nextRowIdx += gridWidth - 1; //second row right - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); } //bottom rowIdx = nextRowIdx - gridWidth + 1; nextRowIdx = rowIdx + gridWidth + 1; - for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx ) + for(int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx) { - AddQuadIndices( indices, rowIdx, nextRowIdx ); + AddQuadIndices(indices, rowIdx, nextRowIdx); } - return GenerateGeometry( vertices, indices ); + return GenerateGeometry(vertices, indices); } void NPatchVisual::SetResource() { const NPatchData* data; - if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) ) + if(mImpl->mRenderer && mLoader.GetNPatchData(mId, data)) { Geometry geometry = CreateGeometry(); - Shader shader = CreateShader(); + Shader shader = CreateShader(); - mImpl->mRenderer.SetGeometry( geometry ); - mImpl->mRenderer.SetShader( shader ); + mImpl->mRenderer.SetGeometry(geometry); + mImpl->mRenderer.SetShader(shader); Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { ApplyTextureAndUniforms(); - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); mPlacementActor.Reset(); // npatch loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } } } -void NPatchVisual::UploadComplete( bool loadSuccess, int32_t textureId, TextureSet textureSet, bool useAtlasing, const Vector4& atlasRect, bool preMultiplied ) +void NPatchVisual::UploadComplete(bool loadSuccess, int32_t textureId, TextureSet textureSet, bool useAtlasing, const Vector4& atlasRect, bool preMultiplied) { - EnablePreMultipliedAlpha( preMultiplied ); + EnablePreMultipliedAlpha(preMultiplied); if(!loadSuccess) { // Image loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::FAILED ); + ResourceReady(Toolkit::Visual::ResourceStatus::FAILED); } - if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() ) + if(mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid()) { SetResource(); } } -void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied ) +void NPatchVisual::LoadComplete(bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied) { - if( loadSuccess && url.GetUrl() == mAuxiliaryUrl.GetUrl() ) + if(loadSuccess && url.GetUrl() == mAuxiliaryUrl.GetUrl()) { mAuxiliaryPixelBuffer = pixelBuffer; SetResource(); @@ -797,7 +791,7 @@ void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffe else { // Image loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::FAILED ); + ResourceReady(Toolkit::Visual::ResourceStatus::FAILED); } } diff --git a/dali-toolkit/internal/visuals/primitive/primitive-visual.cpp b/dali-toolkit/internal/visuals/primitive/primitive-visual.cpp index 48f8fa4..ae5138e 100644 --- a/dali-toolkit/internal/visuals/primitive/primitive-visual.cpp +++ b/dali-toolkit/internal/visuals/primitive/primitive-visual.cpp @@ -19,102 +19,98 @@ #include "primitive-visual.h" // EXTERNAL INCLUDES -#include #include -#include #include #include +#include +#include // INTERNAL INCLUDES -#include +#include #include #include -#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - // shapes -DALI_ENUM_TO_STRING_TABLE_BEGIN( SHAPE_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, SPHERE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CONE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CYLINDER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CUBE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, OCTAHEDRON ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, BEVELLED_CUBE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::PrimitiveVisual::Shape, CONICAL_FRUSTUM ) -DALI_ENUM_TO_STRING_TABLE_END( SHAPE_TYPE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(SHAPE_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, SPHERE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CONE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CYLINDER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CUBE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, OCTAHEDRON) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, BEVELLED_CUBE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::PrimitiveVisual::Shape, CONICAL_FRUSTUM) +DALI_ENUM_TO_STRING_TABLE_END(SHAPE_TYPE) //Primitive property defaults -const int DEFAULT_SLICES = 128; ///< For spheres and conics -const int DEFAULT_STACKS = 128; ///< For spheres and conics -const float DEFAULT_SCALE_TOP_RADIUS = 1.0; ///< For conical frustums -const float DEFAULT_SCALE_BOTTOM_RADIUS = 1.5; ///< For cones and conical frustums -const float DEFAULT_SCALE_HEIGHT = 3.0; ///< For all conics -const float DEFAULT_SCALE_RADIUS = 1.0; ///< For cylinders -const float DEFAULT_BEVEL_PERCENTAGE = 0.0; ///< For bevelled cubes -const float DEFAULT_BEVEL_SMOOTHNESS = 0.0; ///< For bevelled cubes -const Vector4 DEFAULT_COLOR = Vector4( 0.5, 0.5, 0.5, 1.0 ); ///< Grey, for all. +const int DEFAULT_SLICES = 128; ///< For spheres and conics +const int DEFAULT_STACKS = 128; ///< For spheres and conics +const float DEFAULT_SCALE_TOP_RADIUS = 1.0; ///< For conical frustums +const float DEFAULT_SCALE_BOTTOM_RADIUS = 1.5; ///< For cones and conical frustums +const float DEFAULT_SCALE_HEIGHT = 3.0; ///< For all conics +const float DEFAULT_SCALE_RADIUS = 1.0; ///< For cylinders +const float DEFAULT_BEVEL_PERCENTAGE = 0.0; ///< For bevelled cubes +const float DEFAULT_BEVEL_SMOOTHNESS = 0.0; ///< For bevelled cubes +const Vector4 DEFAULT_COLOR = Vector4(0.5, 0.5, 0.5, 1.0); ///< Grey, for all. //Property limits -const int MIN_SLICES = 3; ///< Minimum number of slices for spheres and conics -const int MIN_STACKS = 2; ///< Minimum number of stacks for spheres and conics -const int MAX_PARTITIONS = 255; ///< Maximum number of slices or stacks for spheres and conics +const int MIN_SLICES = 3; ///< Minimum number of slices for spheres and conics +const int MIN_STACKS = 2; ///< Minimum number of stacks for spheres and conics +const int MAX_PARTITIONS = 255; ///< Maximum number of slices or stacks for spheres and conics const float MIN_BEVEL_PERCENTAGE = 0.0; ///< Minimum bevel percentage for bevelled cubes const float MAX_BEVEL_PERCENTAGE = 1.0; ///< Maximum bevel percentage for bevelled cubes -const float MIN_SMOOTHNESS = 0.0; ///< Minimum bevel smoothness for bevelled cubes -const float MAX_SMOOTHNESS = 1.0; ///< Maximum bevel smoothness for bevelled cubes +const float MIN_SMOOTHNESS = 0.0; ///< Minimum bevel smoothness for bevelled cubes +const float MAX_SMOOTHNESS = 1.0; ///< Maximum bevel smoothness for bevelled cubes //Specific shape labels. -const char * const SPHERE_LABEL( "SPHERE" ); -const char * const CONE_LABEL( "CONE" ); -const char * const CYLINDER_LABEL( "CYLINDER" ); -const char * const CUBE_LABEL( "CUBE" ); -const char * const OCTAHEDRON_LABEL( "OCTAHEDRON" ); -const char * const BEVELLED_CUBE_LABEL( "BEVELLED_CUBE" ); -const char * const CONICAL_FRUSTUM_LABEL( "CONICAL_FRUSTUM" ); +const char* const SPHERE_LABEL("SPHERE"); +const char* const CONE_LABEL("CONE"); +const char* const CYLINDER_LABEL("CYLINDER"); +const char* const CUBE_LABEL("CUBE"); +const char* const OCTAHEDRON_LABEL("OCTAHEDRON"); +const char* const BEVELLED_CUBE_LABEL("BEVELLED_CUBE"); +const char* const CONICAL_FRUSTUM_LABEL("CONICAL_FRUSTUM"); //Shader properties -const char * const OBJECT_MATRIX_UNIFORM_NAME( "uObjectMatrix" ); -const char * const OBJECT_DIMENSIONS_UNIFORM_NAME( "uObjectDimensions" ); -const char * const STAGE_OFFSET_UNIFORM_NAME( "uStageOffset" ); +const char* const OBJECT_MATRIX_UNIFORM_NAME("uObjectMatrix"); +const char* const OBJECT_DIMENSIONS_UNIFORM_NAME("uObjectDimensions"); +const char* const STAGE_OFFSET_UNIFORM_NAME("uStageOffset"); //Vertex properties -const char * const POSITION( "aPosition"); -const char * const NORMAL( "aNormal" ); -const char * const INDICES( "aIndices" ); +const char* const POSITION("aPosition"); +const char* const NORMAL("aNormal"); +const char* const INDICES("aIndices"); } // unnamed namespace -PrimitiveVisualPtr PrimitiveVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +PrimitiveVisualPtr PrimitiveVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { - PrimitiveVisualPtr primitiveVisualPtr( new PrimitiveVisual( factoryCache ) ); - primitiveVisualPtr->SetProperties( properties ); + PrimitiveVisualPtr primitiveVisualPtr(new PrimitiveVisual(factoryCache)); + primitiveVisualPtr->SetProperties(properties); primitiveVisualPtr->Initialize(); return primitiveVisualPtr; } -PrimitiveVisual::PrimitiveVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::PRIMITIVE ), - mScaleDimensions( Vector3::ONE ), - mScaleTopRadius( DEFAULT_SCALE_TOP_RADIUS ), - mScaleBottomRadius( DEFAULT_SCALE_BOTTOM_RADIUS ), - mScaleHeight( DEFAULT_SCALE_HEIGHT ), - mScaleRadius( DEFAULT_SCALE_RADIUS ), - mBevelPercentage( DEFAULT_BEVEL_PERCENTAGE ), - mBevelSmoothness( DEFAULT_BEVEL_SMOOTHNESS ), - mSlices( DEFAULT_SLICES ), - mStacks( DEFAULT_STACKS ), - mPrimitiveType( Toolkit::PrimitiveVisual::Shape::SPHERE ) +PrimitiveVisual::PrimitiveVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::PRIMITIVE), + mScaleDimensions(Vector3::ONE), + mScaleTopRadius(DEFAULT_SCALE_TOP_RADIUS), + mScaleBottomRadius(DEFAULT_SCALE_BOTTOM_RADIUS), + mScaleHeight(DEFAULT_SCALE_HEIGHT), + mScaleRadius(DEFAULT_SCALE_RADIUS), + mBevelPercentage(DEFAULT_BEVEL_PERCENTAGE), + mBevelSmoothness(DEFAULT_BEVEL_SMOOTHNESS), + mSlices(DEFAULT_SLICES), + mStacks(DEFAULT_STACKS), + mPrimitiveType(Toolkit::PrimitiveVisual::Shape::SPHERE) { mImpl->mMixColor = DEFAULT_COLOR; } @@ -123,191 +119,191 @@ PrimitiveVisual::~PrimitiveVisual() { } -void PrimitiveVisual::DoSetProperties( const Property::Map& propertyMap ) +void PrimitiveVisual::DoSetProperties(const Property::Map& propertyMap) { //Find out which shape to renderer. - Property::Value* primitiveTypeValue = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SHAPE, PRIMITIVE_SHAPE ); - if( primitiveTypeValue ) + Property::Value* primitiveTypeValue = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SHAPE, PRIMITIVE_SHAPE); + if(primitiveTypeValue) { - Scripting::GetEnumerationProperty( *primitiveTypeValue, SHAPE_TYPE_TABLE, SHAPE_TYPE_TABLE_COUNT, mPrimitiveType ); + Scripting::GetEnumerationProperty(*primitiveTypeValue, SHAPE_TYPE_TABLE, SHAPE_TYPE_TABLE_COUNT, mPrimitiveType); } else { - DALI_LOG_ERROR( "Fail to provide shape to the PrimitiveVisual object.\n" ); + DALI_LOG_ERROR("Fail to provide shape to the PrimitiveVisual object.\n"); } // By virtue of DoSetProperties being called last, this will override // anything set by Toolkit::Visual::Property::MIX_COLOR - Property::Value* colorValue = propertyMap.Find( Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR ); - if( colorValue ) + Property::Value* colorValue = propertyMap.Find(Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR); + if(colorValue) { Vector4 color; - if( colorValue->Get( color ) ) + if(colorValue->Get(color)) { Property::Type type = colorValue->GetType(); - if( type == Property::VECTOR4 ) + if(type == Property::VECTOR4) { - SetMixColor( color ); + SetMixColor(color); } - else if( type == Property::VECTOR3 ) + else if(type == Property::VECTOR3) { Vector3 color3(color); - SetMixColor( color3 ); + SetMixColor(color3); } } } - Property::Value* slices = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SLICES, SLICES ); - if( slices ) + Property::Value* slices = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SLICES, SLICES); + if(slices) { - if( slices->Get( mSlices ) ) + if(slices->Get(mSlices)) { //Clamp value. - if( mSlices > MAX_PARTITIONS ) + if(mSlices > MAX_PARTITIONS) { mSlices = MAX_PARTITIONS; - DALI_LOG_WARNING( "Value for slices clamped.\n" ); + DALI_LOG_WARNING("Value for slices clamped.\n"); } - else if ( mSlices < MIN_SLICES ) + else if(mSlices < MIN_SLICES) { mSlices = MIN_SLICES; - DALI_LOG_WARNING( "Value for slices clamped.\n" ); + DALI_LOG_WARNING("Value for slices clamped.\n"); } } else { - DALI_LOG_ERROR( "Invalid type for slices in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for slices in PrimitiveVisual.\n"); } } - Property::Value* stacks = propertyMap.Find( Toolkit::PrimitiveVisual::Property::STACKS, STACKS ); - if( stacks ) + Property::Value* stacks = propertyMap.Find(Toolkit::PrimitiveVisual::Property::STACKS, STACKS); + if(stacks) { - if( stacks->Get( mStacks ) ) + if(stacks->Get(mStacks)) { //Clamp value. - if( mStacks > MAX_PARTITIONS ) + if(mStacks > MAX_PARTITIONS) { mStacks = MAX_PARTITIONS; - DALI_LOG_WARNING( "Value for stacks clamped.\n" ); + DALI_LOG_WARNING("Value for stacks clamped.\n"); } - else if ( mStacks < MIN_STACKS ) + else if(mStacks < MIN_STACKS) { mStacks = MIN_STACKS; - DALI_LOG_WARNING( "Value for stacks clamped.\n" ); + DALI_LOG_WARNING("Value for stacks clamped.\n"); } } else { - DALI_LOG_ERROR( "Invalid type for stacks in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for stacks in PrimitiveVisual.\n"); } } - Property::Value* scaleTop = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, SCALE_TOP_RADIUS ); - if( scaleTop && !scaleTop->Get( mScaleTopRadius ) ) + Property::Value* scaleTop = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, SCALE_TOP_RADIUS); + if(scaleTop && !scaleTop->Get(mScaleTopRadius)) { - DALI_LOG_ERROR( "Invalid type for scale top radius in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for scale top radius in PrimitiveVisual.\n"); } - Property::Value* scaleBottom = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, SCALE_BOTTOM_RADIUS ); - if( scaleBottom && !scaleBottom->Get( mScaleBottomRadius ) ) + Property::Value* scaleBottom = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, SCALE_BOTTOM_RADIUS); + if(scaleBottom && !scaleBottom->Get(mScaleBottomRadius)) { - DALI_LOG_ERROR( "Invalid type for scale bottom radius in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for scale bottom radius in PrimitiveVisual.\n"); } - Property::Value* scaleHeight = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, SCALE_HEIGHT ); - if( scaleHeight && !scaleHeight->Get( mScaleHeight ) ) + Property::Value* scaleHeight = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, SCALE_HEIGHT); + if(scaleHeight && !scaleHeight->Get(mScaleHeight)) { - DALI_LOG_ERROR( "Invalid type for scale height in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for scale height in PrimitiveVisual.\n"); } - Property::Value* scaleRadius = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, SCALE_RADIUS ); - if( scaleRadius && !scaleRadius->Get( mScaleRadius ) ) + Property::Value* scaleRadius = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, SCALE_RADIUS); + if(scaleRadius && !scaleRadius->Get(mScaleRadius)) { - DALI_LOG_ERROR( "Invalid type for scale radius in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for scale radius in PrimitiveVisual.\n"); } - Property::Value* dimensions = propertyMap.Find( Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, SCALE_DIMENSIONS ); - if( dimensions ) + Property::Value* dimensions = propertyMap.Find(Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, SCALE_DIMENSIONS); + if(dimensions) { - if( dimensions->Get( mScaleDimensions ) ) + if(dimensions->Get(mScaleDimensions)) { //If any dimension is invalid, set it to a sensible default. - if( mScaleDimensions.x <= 0.0 ) + if(mScaleDimensions.x <= 0.0) { mScaleDimensions.x = 1.0; - DALI_LOG_WARNING( "Value for scale dimensions clamped. Must be greater than zero.\n" ); + DALI_LOG_WARNING("Value for scale dimensions clamped. Must be greater than zero.\n"); } - if( mScaleDimensions.y <= 0.0 ) + if(mScaleDimensions.y <= 0.0) { mScaleDimensions.y = 1.0; - DALI_LOG_WARNING( "Value for scale dimensions clamped. Must be greater than zero.\n" ); + DALI_LOG_WARNING("Value for scale dimensions clamped. Must be greater than zero.\n"); } - if( mScaleDimensions.z <= 0.0 ) + if(mScaleDimensions.z <= 0.0) { mScaleDimensions.z = 1.0; - DALI_LOG_WARNING( "Value for scale dimensions clamped. Must be greater than zero.\n" ); + DALI_LOG_WARNING("Value for scale dimensions clamped. Must be greater than zero.\n"); } } else { - DALI_LOG_ERROR( "Invalid type for scale dimensions in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for scale dimensions in PrimitiveVisual.\n"); } } - Property::Value* bevel = propertyMap.Find( Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, BEVEL_PERCENTAGE ); - if( bevel ) + Property::Value* bevel = propertyMap.Find(Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, BEVEL_PERCENTAGE); + if(bevel) { - if( bevel->Get( mBevelPercentage ) ) + if(bevel->Get(mBevelPercentage)) { //Clamp value. - if( mBevelPercentage < MIN_BEVEL_PERCENTAGE ) + if(mBevelPercentage < MIN_BEVEL_PERCENTAGE) { mBevelPercentage = MIN_BEVEL_PERCENTAGE; - DALI_LOG_WARNING( "Value for bevel percentage clamped.\n" ); + DALI_LOG_WARNING("Value for bevel percentage clamped.\n"); } - else if( mBevelPercentage > MAX_BEVEL_PERCENTAGE ) + else if(mBevelPercentage > MAX_BEVEL_PERCENTAGE) { mBevelPercentage = MAX_BEVEL_PERCENTAGE; - DALI_LOG_WARNING( "Value for bevel percentage clamped.\n" ); + DALI_LOG_WARNING("Value for bevel percentage clamped.\n"); } } else { - DALI_LOG_ERROR( "Invalid type for bevel percentage in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for bevel percentage in PrimitiveVisual.\n"); } } - Property::Value* smoothness = propertyMap.Find( Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, BEVEL_SMOOTHNESS ); - if( smoothness ) + Property::Value* smoothness = propertyMap.Find(Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, BEVEL_SMOOTHNESS); + if(smoothness) { - if( smoothness->Get( mBevelSmoothness ) ) + if(smoothness->Get(mBevelSmoothness)) { //Clamp value. - if( mBevelSmoothness < MIN_SMOOTHNESS ) + if(mBevelSmoothness < MIN_SMOOTHNESS) { mBevelSmoothness = MIN_SMOOTHNESS; - DALI_LOG_WARNING( "Value for bevel smoothness clamped.\n" ); + DALI_LOG_WARNING("Value for bevel smoothness clamped.\n"); } - else if( mBevelSmoothness > MAX_SMOOTHNESS ) + else if(mBevelSmoothness > MAX_SMOOTHNESS) { mBevelSmoothness = MAX_SMOOTHNESS; - DALI_LOG_WARNING( "Value for bevel smoothness clamped.\n" ); + DALI_LOG_WARNING("Value for bevel smoothness clamped.\n"); } } else { - DALI_LOG_ERROR( "Invalid type for bevel smoothness in PrimitiveVisual.\n" ); + DALI_LOG_ERROR("Invalid type for bevel smoothness in PrimitiveVisual.\n"); } } //Read in light position. - Property::Value* lightPosition = propertyMap.Find( Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, LIGHT_POSITION_UNIFORM_NAME ); - if( lightPosition ) + Property::Value* lightPosition = propertyMap.Find(Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, LIGHT_POSITION_UNIFORM_NAME); + if(lightPosition) { - if( !lightPosition->Get( mLightPosition ) ) + if(!lightPosition->Get(mLightPosition)) { - DALI_LOG_ERROR( "Invalid value passed for light position in MeshVisual object.\n" ); + DALI_LOG_ERROR("Invalid value passed for light position in MeshVisual object.\n"); mLightPosition = Vector3::ZERO; } } @@ -317,13 +313,13 @@ void PrimitiveVisual::DoSetProperties( const Property::Map& propertyMap ) // at a reasonable distance to light everything on screen. Stage stage = Stage::GetCurrent(); - mLightPosition = Vector3( stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5 ); + mLightPosition = Vector3(stage.GetSize().width / 2, stage.GetSize().height / 2, stage.GetSize().width * 5); } } -void PrimitiveVisual::GetNaturalSize( Vector2& naturalSize ) +void PrimitiveVisual::GetNaturalSize(Vector2& naturalSize) { - if( !mGeometry ) + if(!mGeometry) { CreateGeometry(); } @@ -332,132 +328,132 @@ void PrimitiveVisual::GetNaturalSize( Vector2& naturalSize ) naturalSize.y = mObjectDimensions.y; } -void PrimitiveVisual::DoSetOnScene( Actor& actor ) +void PrimitiveVisual::DoSetOnScene(Actor& actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // Primitive generated and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } -void PrimitiveVisual::DoCreatePropertyMap( Property::Map& map ) const +void PrimitiveVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::PRIMITIVE ); - map.Insert( Toolkit::PrimitiveVisual::Property::MIX_COLOR, mImpl->mMixColor ); - map.Insert( Toolkit::PrimitiveVisual::Property::SHAPE, mPrimitiveType ); - map.Insert( Toolkit::PrimitiveVisual::Property::SLICES, mSlices ); - map.Insert( Toolkit::PrimitiveVisual::Property::STACKS, mStacks ); - map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, mScaleTopRadius ); - map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, mScaleBottomRadius ); - map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, mScaleHeight ); - map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, mScaleRadius ); - map.Insert( Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, mScaleDimensions ); - map.Insert( Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, mBevelPercentage ); - map.Insert( Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, mBevelSmoothness ); - map.Insert( Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, mLightPosition ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::PRIMITIVE); + map.Insert(Toolkit::PrimitiveVisual::Property::MIX_COLOR, mImpl->mMixColor); + map.Insert(Toolkit::PrimitiveVisual::Property::SHAPE, mPrimitiveType); + map.Insert(Toolkit::PrimitiveVisual::Property::SLICES, mSlices); + map.Insert(Toolkit::PrimitiveVisual::Property::STACKS, mStacks); + map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_TOP_RADIUS, mScaleTopRadius); + map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_BOTTOM_RADIUS, mScaleBottomRadius); + map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_HEIGHT, mScaleHeight); + map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_RADIUS, mScaleRadius); + map.Insert(Toolkit::PrimitiveVisual::Property::SCALE_DIMENSIONS, mScaleDimensions); + map.Insert(Toolkit::PrimitiveVisual::Property::BEVEL_PERCENTAGE, mBevelPercentage); + map.Insert(Toolkit::PrimitiveVisual::Property::BEVEL_SMOOTHNESS, mBevelSmoothness); + map.Insert(Toolkit::PrimitiveVisual::Property::LIGHT_POSITION, mLightPosition); } -void PrimitiveVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void PrimitiveVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } void PrimitiveVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } void PrimitiveVisual::OnInitialize() { - if( !mGeometry ) + if(!mGeometry) { CreateGeometry(); } - if( !mShader ) + if(!mShader) { CreateShader(); } - mImpl->mRenderer = Renderer::New( mGeometry, mShader ); - mImpl->mRenderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK ); + mImpl->mRenderer = Renderer::New(mGeometry, mShader); + mImpl->mRenderer.SetProperty(Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK); // Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); - mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty( Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR, Vector3(mImpl->mMixColor) ); + mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty(Toolkit::PrimitiveVisual::Property::MIX_COLOR, MIX_COLOR, Vector3(mImpl->mMixColor)); } void PrimitiveVisual::UpdateShaderUniforms() { - Stage stage = Stage::GetCurrent(); - float width = stage.GetSize().width; + Stage stage = Stage::GetCurrent(); + float width = stage.GetSize().width; float height = stage.GetSize().height; //Flip model to account for DALi starting with (0, 0) at the top left. Matrix scaleMatrix; - scaleMatrix.SetIdentityAndScale( Vector3( 1.0, -1.0, 1.0 ) ); + scaleMatrix.SetIdentityAndScale(Vector3(1.0, -1.0, 1.0)); - mShader.RegisterProperty( STAGE_OFFSET_UNIFORM_NAME, Vector2( width, height ) / 2.0f ); - mShader.RegisterProperty( LIGHT_POSITION_UNIFORM_NAME, mLightPosition ); - mShader.RegisterProperty( OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix ); - mShader.RegisterProperty( OBJECT_DIMENSIONS_UNIFORM_NAME, mObjectDimensions ); + mShader.RegisterProperty(STAGE_OFFSET_UNIFORM_NAME, Vector2(width, height) / 2.0f); + mShader.RegisterProperty(LIGHT_POSITION_UNIFORM_NAME, mLightPosition); + mShader.RegisterProperty(OBJECT_MATRIX_UNIFORM_NAME, scaleMatrix); + mShader.RegisterProperty(OBJECT_DIMENSIONS_UNIFORM_NAME, mObjectDimensions); } void PrimitiveVisual::CreateShader() { - mShader = Shader::New( SHADER_PRIMITIVE_VISUAL_SHADER_VERT, SHADER_PRIMITIVE_VISUAL_SHADER_FRAG ); + mShader = Shader::New(SHADER_PRIMITIVE_VISUAL_SHADER_VERT, SHADER_PRIMITIVE_VISUAL_SHADER_FRAG); UpdateShaderUniforms(); } void PrimitiveVisual::CreateGeometry() { - Dali::Vector vertices; + Dali::Vector vertices; Dali::Vector indices; - switch( mPrimitiveType ) + switch(mPrimitiveType) { case Toolkit::PrimitiveVisual::Shape::SPHERE: { - CreateSphere( vertices, indices, mSlices, mStacks ); + CreateSphere(vertices, indices, mSlices, mStacks); break; } case Toolkit::PrimitiveVisual::Shape::CONE: { //Create a conic with zero top radius. - CreateConic( vertices, indices, 0, mScaleBottomRadius, mScaleHeight, mSlices ); + CreateConic(vertices, indices, 0, mScaleBottomRadius, mScaleHeight, mSlices); break; } case Toolkit::PrimitiveVisual::Shape::CYLINDER: { //Create a conic with equal radii on the top and bottom. - CreateConic( vertices, indices, mScaleRadius, mScaleRadius, mScaleHeight, mSlices ); + CreateConic(vertices, indices, mScaleRadius, mScaleRadius, mScaleHeight, mSlices); break; } case Toolkit::PrimitiveVisual::Shape::CUBE: { //Create a cube by creating a bevelled cube with minimum bevel. - CreateBevelledCube( vertices, indices, mScaleDimensions, 0.0, 0.0 ); + CreateBevelledCube(vertices, indices, mScaleDimensions, 0.0, 0.0); break; } case Toolkit::PrimitiveVisual::Shape::OCTAHEDRON: { //Create an octahedron by creating a bevelled cube with maximum bevel. - CreateBevelledCube( vertices, indices, mScaleDimensions, 1.0, mBevelSmoothness ); + CreateBevelledCube(vertices, indices, mScaleDimensions, 1.0, mBevelSmoothness); break; } case Toolkit::PrimitiveVisual::Shape::BEVELLED_CUBE: { - CreateBevelledCube( vertices, indices, mScaleDimensions, mBevelPercentage, mBevelSmoothness ); + CreateBevelledCube(vertices, indices, mScaleDimensions, mBevelPercentage, mBevelSmoothness); break; } case Toolkit::PrimitiveVisual::Shape::CONICAL_FRUSTUM: { - CreateConic( vertices, indices, mScaleTopRadius, mScaleBottomRadius, mScaleHeight, mSlices ); + CreateConic(vertices, indices, mScaleTopRadius, mScaleBottomRadius, mScaleHeight, mSlices); break; } } @@ -466,86 +462,82 @@ void PrimitiveVisual::CreateGeometry() //Vertices Property::Map vertexFormat; - vertexFormat[POSITION] = Property::VECTOR3; - vertexFormat[NORMAL] = Property::VECTOR3; - VertexBuffer surfaceVertices = VertexBuffer::New( vertexFormat ); - surfaceVertices.SetData( &vertices[0], vertices.Size() ); + vertexFormat[POSITION] = Property::VECTOR3; + vertexFormat[NORMAL] = Property::VECTOR3; + VertexBuffer surfaceVertices = VertexBuffer::New(vertexFormat); + surfaceVertices.SetData(&vertices[0], vertices.Size()); - mGeometry.AddVertexBuffer( surfaceVertices ); + mGeometry.AddVertexBuffer(surfaceVertices); //Indices for triangle formulation - mGeometry.SetIndexBuffer( &indices[0], indices.Size() ); + mGeometry.SetIndexBuffer(&indices[0], indices.Size()); } -void PrimitiveVisual::CreateSphere( Vector& vertices, Vector& indices, int slices, int stacks ) +void PrimitiveVisual::CreateSphere(Vector& vertices, Vector& indices, int slices, int stacks) { - ComputeSphereVertices( vertices, slices, stacks ); - FormSphereTriangles( indices, slices, stacks ); + ComputeSphereVertices(vertices, slices, stacks); + FormSphereTriangles(indices, slices, stacks); mObjectDimensions = Vector3::ONE; } -void PrimitiveVisual::CreateConic( Vector& vertices, Vector& indices, float scaleTopRadius, - float scaleBottomRadius, float scaleHeight, int slices ) +void PrimitiveVisual::CreateConic(Vector& vertices, Vector& indices, float scaleTopRadius, float scaleBottomRadius, float scaleHeight, int slices) { - ComputeConicVertices( vertices, scaleTopRadius, scaleBottomRadius, scaleHeight, slices ); - FormConicTriangles( indices, scaleTopRadius, scaleBottomRadius, slices ); + ComputeConicVertices(vertices, scaleTopRadius, scaleBottomRadius, scaleHeight, slices); + FormConicTriangles(indices, scaleTopRadius, scaleBottomRadius, slices); //Determine object dimensions, and scale them to be between 0.0 and 1.0. - float xDimension = std::max( scaleTopRadius, scaleBottomRadius ) * 2.0f; - float yDimension = scaleHeight; - float largestDimension = std::max( xDimension, yDimension ); + float xDimension = std::max(scaleTopRadius, scaleBottomRadius) * 2.0f; + float yDimension = scaleHeight; + float largestDimension = std::max(xDimension, yDimension); - mObjectDimensions = Vector3( xDimension / largestDimension, yDimension / largestDimension, - xDimension / largestDimension ); + mObjectDimensions = Vector3(xDimension / largestDimension, yDimension / largestDimension, xDimension / largestDimension); } -void PrimitiveVisual::CreateBevelledCube( Vector& vertices, Vector& indices, - Vector3 dimensions, float bevelPercentage, float bevelSmoothness ) +void PrimitiveVisual::CreateBevelledCube(Vector& vertices, Vector& indices, Vector3 dimensions, float bevelPercentage, float bevelSmoothness) { - float maxDimension = std::max( std::max( dimensions.x, dimensions.y ), dimensions.z ); - dimensions = dimensions / maxDimension; + float maxDimension = std::max(std::max(dimensions.x, dimensions.y), dimensions.z); + dimensions = dimensions / maxDimension; - if( bevelPercentage <= MIN_BEVEL_PERCENTAGE ) //No bevel, form a cube. + if(bevelPercentage <= MIN_BEVEL_PERCENTAGE) //No bevel, form a cube. { - ComputeCubeVertices( vertices, dimensions ); - FormCubeTriangles( indices ); + ComputeCubeVertices(vertices, dimensions); + FormCubeTriangles(indices); } - else if( bevelPercentage >= MAX_BEVEL_PERCENTAGE ) //Max bevel, form an octahedron. + else if(bevelPercentage >= MAX_BEVEL_PERCENTAGE) //Max bevel, form an octahedron. { - ComputeOctahedronVertices( vertices, dimensions, bevelSmoothness ); - FormOctahedronTriangles( indices ); + ComputeOctahedronVertices(vertices, dimensions, bevelSmoothness); + FormOctahedronTriangles(indices); } else //In between, form a bevelled cube. { - ComputeBevelledCubeVertices( vertices, dimensions, bevelPercentage, bevelSmoothness ); - FormBevelledCubeTriangles( indices ); + ComputeBevelledCubeVertices(vertices, dimensions, bevelPercentage, bevelSmoothness); + FormBevelledCubeTriangles(indices); } mObjectDimensions = dimensions; } -void PrimitiveVisual::ComputeCircleTables( Vector& sinTable, Vector& cosTable, int divisions, - bool halfCircle ) +void PrimitiveVisual::ComputeCircleTables(Vector& sinTable, Vector& cosTable, int divisions, bool halfCircle) { - if( divisions < 0 ) + if(divisions < 0) { return; } - const float angleDivision = ( halfCircle ? 1.0f : 2.0f ) * Dali::Math::PI / ( float ) divisions; + const float angleDivision = (halfCircle ? 1.0f : 2.0f) * Dali::Math::PI / (float)divisions; - sinTable.Resize( divisions ); - cosTable.Resize( divisions ); + sinTable.Resize(divisions); + cosTable.Resize(divisions); - for( int i = 0; i < divisions; i++ ) + for(int i = 0; i < divisions; i++) { - sinTable[i] = sin( angleDivision * i ); - cosTable[i] = cos( angleDivision * i ); + sinTable[i] = sin(angleDivision * i); + cosTable[i] = cos(angleDivision * i); } } -void PrimitiveVisual::ComputeSphereVertices( Vector& vertices, int slices, int stacks ) +void PrimitiveVisual::ComputeSphereVertices(Vector& vertices, int slices, int stacks) { //Tables for calculating slices angles and stacks angles, respectively. Vector sinTable1; @@ -553,64 +545,64 @@ void PrimitiveVisual::ComputeSphereVertices( Vector& vertices, int slice Vector sinTable2; Vector cosTable2; - ComputeCircleTables( sinTable1, cosTable1, slices, false ); - ComputeCircleTables( sinTable2, cosTable2, stacks, true ); + ComputeCircleTables(sinTable1, cosTable1, slices, false); + ComputeCircleTables(sinTable2, cosTable2, stacks, true); - int numVertices = slices * ( stacks - 1 ) + 2; - vertices.Resize( numVertices ); + int numVertices = slices * (stacks - 1) + 2; + vertices.Resize(numVertices); - int vertexIndex = 0; //Track progress through vertices. + int vertexIndex = 0; //Track progress through vertices. float x; float y; float z; //Top stack. - vertices[vertexIndex].position = Vector3( 0.0, 0.5, 0.0 ); - vertices[vertexIndex].normal = Vector3( 0.0, 1.0, 0.0 ); + vertices[vertexIndex].position = Vector3(0.0, 0.5, 0.0); + vertices[vertexIndex].normal = Vector3(0.0, 1.0, 0.0); vertexIndex++; //Middle stacks. - for( int i = 1; i < stacks; i++ ) + for(int i = 1; i < stacks; i++) { - for( int j = 0; j < slices; j++, vertexIndex++ ) + for(int j = 0; j < slices; j++, vertexIndex++) { x = cosTable1[j] * sinTable2[i]; y = cosTable2[i]; z = sinTable1[j] * sinTable2[i]; - vertices[vertexIndex].position = Vector3( x / 2.0f, y / 2.0f, z / 2.0f ); - vertices[vertexIndex].normal = Vector3( x, y, z ); + vertices[vertexIndex].position = Vector3(x / 2.0f, y / 2.0f, z / 2.0f); + vertices[vertexIndex].normal = Vector3(x, y, z); } } //Bottom stack. - vertices[vertexIndex].position = Vector3( 0.0, -0.5, 0.0 ); - vertices[vertexIndex].normal = Vector3( 0.0, -1.0, 0.0 ); + vertices[vertexIndex].position = Vector3(0.0, -0.5, 0.0); + vertices[vertexIndex].normal = Vector3(0.0, -1.0, 0.0); } -void PrimitiveVisual::FormSphereTriangles( Vector& indices, int slices, int stacks ) +void PrimitiveVisual::FormSphereTriangles(Vector& indices, int slices, int stacks) { - if( stacks <= 1 ) + if(stacks <= 1) { //Set indices to placeholder "error" values. //This will display nothing, which is the expected behaviour for this edge case. - indices.Resize( 3 ); + indices.Resize(3); return; } - int numTriangles = 2 * slices * ( stacks - 1 ); + int numTriangles = 2 * slices * (stacks - 1); - indices.Resize( 3 * numTriangles ); + indices.Resize(3 * numTriangles); - int indiceIndex = 0; //Used to keep track of progress through indices. - int previousCycleBeginning = 1; //Stores the index of the vertex that started the cycle of the previous stack. - int currentCycleBeginning = 1 + slices; + int indiceIndex = 0; //Used to keep track of progress through indices. + int previousCycleBeginning = 1; //Stores the index of the vertex that started the cycle of the previous stack. + int currentCycleBeginning = 1 + slices; //Top stack. Loop from index 1 to index slices, as not counting the very first vertex. - for( int i = 1; i <= slices; i++, indiceIndex += 3 ) + for(int i = 1; i <= slices; i++, indiceIndex += 3) { indices[indiceIndex] = 0; - if( i == slices ) + if(i == slices) { //End, so loop around. indices[indiceIndex + 1] = 1; @@ -623,14 +615,14 @@ void PrimitiveVisual::FormSphereTriangles( Vector& indices, int } //Middle Stacks. Want to form triangles between the top and bottom stacks, so loop up to the number of stacks - 2. - for( int i = 0; i < stacks - 2; i++, previousCycleBeginning += slices, currentCycleBeginning += slices ) + for(int i = 0; i < stacks - 2; i++, previousCycleBeginning += slices, currentCycleBeginning += slices) { - for( int j = 0; j < slices; j++, indiceIndex += 6 ) + for(int j = 0; j < slices; j++, indiceIndex += 6) { - if( j == slices - 1 ) + if(j == slices - 1) { //End, so loop around. - indices[indiceIndex] = previousCycleBeginning + j; + indices[indiceIndex] = previousCycleBeginning + j; indices[indiceIndex + 1] = previousCycleBeginning; indices[indiceIndex + 2] = currentCycleBeginning + j; indices[indiceIndex + 3] = currentCycleBeginning + j; @@ -639,7 +631,7 @@ void PrimitiveVisual::FormSphereTriangles( Vector& indices, int } else { - indices[indiceIndex] = previousCycleBeginning + j; + indices[indiceIndex] = previousCycleBeginning + j; indices[indiceIndex + 1] = previousCycleBeginning + 1 + j; indices[indiceIndex + 2] = currentCycleBeginning + j; indices[indiceIndex + 3] = currentCycleBeginning + j; @@ -650,11 +642,11 @@ void PrimitiveVisual::FormSphereTriangles( Vector& indices, int } //Bottom stack. Loop around the last stack from the previous loop, and go up to the penultimate vertex. - for( int i = 0; i < slices; i++, indiceIndex += 3 ) + for(int i = 0; i < slices; i++, indiceIndex += 3) { - indices[indiceIndex] = previousCycleBeginning + slices; + indices[indiceIndex] = previousCycleBeginning + slices; indices[indiceIndex + 1] = previousCycleBeginning + i; - if( i == slices - 1 ) + if(i == slices - 1) { //End, so loop around. indices[indiceIndex + 2] = previousCycleBeginning; @@ -666,34 +658,32 @@ void PrimitiveVisual::FormSphereTriangles( Vector& indices, int } } -void PrimitiveVisual::ComputeConicVertices( Vector& vertices, float scaleTopRadius, - float scaleBottomRadius, float scaleHeight, int slices ) +void PrimitiveVisual::ComputeConicVertices(Vector& vertices, float scaleTopRadius, float scaleBottomRadius, float scaleHeight, int slices) { - int vertexIndex = 0; //Track progress through vertices. + int vertexIndex = 0; //Track progress through vertices. Vector sinTable; Vector cosTable; - ComputeCircleTables( sinTable, cosTable, slices, false ); + ComputeCircleTables(sinTable, cosTable, slices, false); - int numVertices = 2; //Always will have one at the top and one at the bottom. + int numVertices = 2; //Always will have one at the top and one at the bottom. //Add vertices for each circle. Need two per point for different face normals. - if( scaleTopRadius > 0.0 ) + if(scaleTopRadius > 0.0) { numVertices += 2 * slices; } - if( scaleBottomRadius > 0.0 ) + if(scaleBottomRadius > 0.0) { numVertices += 2 * slices; } - vertices.Resize( numVertices ); - + vertices.Resize(numVertices); //Scale to bounding region of -0.5 to 0.5 (i.e range of 1). - float biggestObjectDimension = std::max( std::max( scaleTopRadius * 2.0f, scaleBottomRadius * 2.0f ), scaleHeight ); - scaleTopRadius = scaleTopRadius / biggestObjectDimension; - scaleBottomRadius = scaleBottomRadius / biggestObjectDimension; + float biggestObjectDimension = std::max(std::max(scaleTopRadius * 2.0f, scaleBottomRadius * 2.0f), scaleHeight); + scaleTopRadius = scaleTopRadius / biggestObjectDimension; + scaleBottomRadius = scaleBottomRadius / biggestObjectDimension; //Dimensions for vertex coordinates. Y is constant, and so can be initialised now. float x; @@ -701,94 +691,93 @@ void PrimitiveVisual::ComputeConicVertices( Vector& vertices, float scal float z; //Top center. - vertices[0].position = Vector3( 0, y, 0 ); - vertices[0].normal = Vector3( 0, 1, 0 ); + vertices[0].position = Vector3(0, y, 0); + vertices[0].normal = Vector3(0, 1, 0); vertexIndex++; //Top circle. - if( scaleTopRadius > 0.0 ) + if(scaleTopRadius > 0.0) { //Loop around the circle. - for( int i = 0; i < slices; i++, vertexIndex++ ) + for(int i = 0; i < slices; i++, vertexIndex++) { x = sinTable[i] * scaleTopRadius; z = cosTable[i] * scaleTopRadius; //Upward-facing normal. - vertices[vertexIndex].position = Vector3( x, y, z ); - vertices[vertexIndex].normal = Vector3( 0, 1, 0 ); + vertices[vertexIndex].position = Vector3(x, y, z); + vertices[vertexIndex].normal = Vector3(0, 1, 0); //Outward-facing normal. - vertices[vertexIndex + slices].position = Vector3( x, y, z ); - vertices[vertexIndex + slices].normal = Vector3( x, 0, z ); + vertices[vertexIndex + slices].position = Vector3(x, y, z); + vertices[vertexIndex + slices].normal = Vector3(x, 0, z); } vertexIndex += slices; } //Bottom circle. - if( scaleBottomRadius > 0.0 ) + if(scaleBottomRadius > 0.0) { //Loop around the circle. - for( int i = 0; i < slices; i++, vertexIndex++ ) + for(int i = 0; i < slices; i++, vertexIndex++) { x = sinTable[i] * scaleBottomRadius; z = cosTable[i] * scaleBottomRadius; //Outward-facing normal. - vertices[vertexIndex].position = Vector3( x, -y, z ); - vertices[vertexIndex].normal = Vector3( x, 0, z ); + vertices[vertexIndex].position = Vector3(x, -y, z); + vertices[vertexIndex].normal = Vector3(x, 0, z); //Downward-facing normal. - vertices[vertexIndex + slices].position = Vector3( x, -y, z ); - vertices[vertexIndex + slices].normal = Vector3( 0, -1, 0 ); + vertices[vertexIndex + slices].position = Vector3(x, -y, z); + vertices[vertexIndex + slices].normal = Vector3(0, -1, 0); } vertexIndex += slices; } //Bottom center. - vertices[vertexIndex].position = Vector3( 0, -y, 0 ); - vertices[vertexIndex].normal = Vector3( 0, -1, 0 ); + vertices[vertexIndex].position = Vector3(0, -y, 0); + vertices[vertexIndex].normal = Vector3(0, -1, 0); vertexIndex++; } -void PrimitiveVisual::FormConicTriangles( Vector& indices, float scaleTopRadius, - float scaleBottomRadius, int slices ) +void PrimitiveVisual::FormConicTriangles(Vector& indices, float scaleTopRadius, float scaleBottomRadius, int slices) { - int indiceIndex = 0; //Track progress through indices. + int indiceIndex = 0; //Track progress through indices. int numTriangles = 0; - bool coneTop = scaleTopRadius <= 0.0; - bool coneBottom = scaleBottomRadius <= 0.0; + bool coneTop = scaleTopRadius <= 0.0; + bool coneBottom = scaleBottomRadius <= 0.0; - if( coneTop && coneBottom ) + if(coneTop && coneBottom) { //Set indices to placeholder "error" values. //This will display nothing, which is the expected behaviour for this edge case. - indices.Resize( 3 ); + indices.Resize(3); return; } - if( !coneTop ) + if(!coneTop) { numTriangles += 2 * slices; } - if( !coneBottom ) + if(!coneBottom) { numTriangles += 2 * slices; } - indices.Resize( 3 * numTriangles ); + indices.Resize(3 * numTriangles); //Switch on the type of conic we have. - if( !coneTop && !coneBottom ) + if(!coneTop && !coneBottom) { //Top circle. Start at index of first outer point and go around. - for( int i = 1; i <= slices; i++, indiceIndex += 3 ) + for(int i = 1; i <= slices; i++, indiceIndex += 3) { - indices[indiceIndex] = 0; + indices[indiceIndex] = 0; indices[indiceIndex + 1] = i; - if( i == slices ) + if(i == slices) { //End, so loop around. indices[indiceIndex + 2] = 1; @@ -799,16 +788,16 @@ void PrimitiveVisual::FormConicTriangles( Vector& indices, float } } - int topCycleBeginning = slices + 1; + int topCycleBeginning = slices + 1; int bottomCycleBeginning = topCycleBeginning + slices; //Vertical edges. - for( int i = 0; i < slices; i++, indiceIndex += 6 ) + for(int i = 0; i < slices; i++, indiceIndex += 6) { - if( i == slices - 1 ) + if(i == slices - 1) { //End, so loop around. - indices[indiceIndex] = topCycleBeginning + i; + indices[indiceIndex] = topCycleBeginning + i; indices[indiceIndex + 1] = bottomCycleBeginning + i; indices[indiceIndex + 2] = topCycleBeginning; indices[indiceIndex + 3] = bottomCycleBeginning + i; @@ -817,7 +806,7 @@ void PrimitiveVisual::FormConicTriangles( Vector& indices, float } else { - indices[indiceIndex] = topCycleBeginning + i; + indices[indiceIndex] = topCycleBeginning + i; indices[indiceIndex + 1] = bottomCycleBeginning + i; indices[indiceIndex + 2] = topCycleBeginning + 1 + i; indices[indiceIndex + 3] = bottomCycleBeginning + i; @@ -829,10 +818,10 @@ void PrimitiveVisual::FormConicTriangles( Vector& indices, float int bottomFaceCycleBeginning = bottomCycleBeginning + slices; //Bottom circle. - for( int i = 0; i < slices; i++, indiceIndex += 3 ) + for(int i = 0; i < slices; i++, indiceIndex += 3) { indices[indiceIndex] = bottomFaceCycleBeginning; - if( i == slices - 1 ) + if(i == slices - 1) { //End, so loop around. indices[indiceIndex + 1] = bottomFaceCycleBeginning; @@ -844,14 +833,14 @@ void PrimitiveVisual::FormConicTriangles( Vector& indices, float indices[indiceIndex + 2] = bottomFaceCycleBeginning + i; } } - else if( !coneTop || !coneBottom ) + else if(!coneTop || !coneBottom) { //Top circle/edges. Start at index of first outer point and go around. - for( int i = 1; i <= slices; i++, indiceIndex += 3 ) + for(int i = 1; i <= slices; i++, indiceIndex += 3) { - indices[indiceIndex] = 0; + indices[indiceIndex] = 0; indices[indiceIndex + 1] = i; - if( i == slices ) + if(i == slices) { //End, so loop around. indices[indiceIndex + 2] = 1; @@ -863,10 +852,10 @@ void PrimitiveVisual::FormConicTriangles( Vector& indices, float } //Bottom circle/edges. Start at index of first outer point and go around. - for( int i = 1; i <= slices; i++, indiceIndex += 3 ) + for(int i = 1; i <= slices; i++, indiceIndex += 3) { indices[indiceIndex] = 2 * slices + 1; - if( i == slices ) + if(i == slices) { //End, so loop around. indices[indiceIndex + 1] = slices + 1; @@ -880,51 +869,51 @@ void PrimitiveVisual::FormConicTriangles( Vector& indices, float } } -void PrimitiveVisual::ComputeCubeVertices( Vector& vertices, Vector3 dimensions ) +void PrimitiveVisual::ComputeCubeVertices(Vector& vertices, Vector3 dimensions) { - int numVertices = 4 * 6; //Four per face. - int vertexIndex = 0; //Tracks progress through vertices. - float scaledX = 0.5 * dimensions.x; - float scaledY = 0.5 * dimensions.y; - float scaledZ = 0.5 * dimensions.z; + int numVertices = 4 * 6; //Four per face. + int vertexIndex = 0; //Tracks progress through vertices. + float scaledX = 0.5 * dimensions.x; + float scaledY = 0.5 * dimensions.y; + float scaledZ = 0.5 * dimensions.z; - vertices.Resize( numVertices ); + vertices.Resize(numVertices); Vector positions; //Stores vertex positions, which are shared between vertexes at the same position but with a different normal. positions.Resize(8); Vector normals; //Stores normals, which are shared between vertexes of the same face. normals.Resize(6); - positions[0] = Vector3( -scaledX, scaledY, -scaledZ ); - positions[1] = Vector3( scaledX, scaledY, -scaledZ ); - positions[2] = Vector3( scaledX, scaledY, scaledZ ); - positions[3] = Vector3( -scaledX, scaledY, scaledZ ); - positions[4] = Vector3( -scaledX, -scaledY, -scaledZ ); - positions[5] = Vector3( scaledX, -scaledY, -scaledZ ); - positions[6] = Vector3( scaledX, -scaledY, scaledZ ); - positions[7] = Vector3( -scaledX, -scaledY, scaledZ ); - - normals[0] = Vector3( 0, 1, 0 ); - normals[1] = Vector3( 0, 0, -1 ); - normals[2] = Vector3( 1, 0, 0 ); - normals[3] = Vector3( 0, 0, 1 ); - normals[4] = Vector3( -1, 0, 0 ); - normals[5] = Vector3( 0, -1, 0 ); + positions[0] = Vector3(-scaledX, scaledY, -scaledZ); + positions[1] = Vector3(scaledX, scaledY, -scaledZ); + positions[2] = Vector3(scaledX, scaledY, scaledZ); + positions[3] = Vector3(-scaledX, scaledY, scaledZ); + positions[4] = Vector3(-scaledX, -scaledY, -scaledZ); + positions[5] = Vector3(scaledX, -scaledY, -scaledZ); + positions[6] = Vector3(scaledX, -scaledY, scaledZ); + positions[7] = Vector3(-scaledX, -scaledY, scaledZ); + + normals[0] = Vector3(0, 1, 0); + normals[1] = Vector3(0, 0, -1); + normals[2] = Vector3(1, 0, 0); + normals[3] = Vector3(0, 0, 1); + normals[4] = Vector3(-1, 0, 0); + normals[5] = Vector3(0, -1, 0); //Top face, upward normals. - for( int i = 0; i < 4; i++, vertexIndex++ ) + for(int i = 0; i < 4; i++, vertexIndex++) { vertices[vertexIndex].position = positions[i]; - vertices[vertexIndex].normal = normals[0]; + vertices[vertexIndex].normal = normals[0]; } //Top face, outward normals. - for( int i = 0; i < 4; i++, vertexIndex += 2 ) + for(int i = 0; i < 4; i++, vertexIndex += 2) { vertices[vertexIndex].position = positions[i]; - vertices[vertexIndex].normal = normals[i + 1]; + vertices[vertexIndex].normal = normals[i + 1]; - if( i == 3 ) + if(i == 3) { //End, so loop around. vertices[vertexIndex + 1].position = positions[0]; @@ -937,12 +926,12 @@ void PrimitiveVisual::ComputeCubeVertices( Vector& vertices, Vector3 dim } //Bottom face, outward normals. - for( int i = 0; i < 4; i++, vertexIndex += 2 ) + for(int i = 0; i < 4; i++, vertexIndex += 2) { vertices[vertexIndex].position = positions[i + 4]; - vertices[vertexIndex].normal = normals[i + 1]; + vertices[vertexIndex].normal = normals[i + 1]; - if( i == 3 ) + if(i == 3) { //End, so loop around. vertices[vertexIndex + 1].position = positions[4]; @@ -955,23 +944,22 @@ void PrimitiveVisual::ComputeCubeVertices( Vector& vertices, Vector3 dim } //Bottom face, downward normals. - for( int i = 0; i < 4; i++, vertexIndex++ ) + for(int i = 0; i < 4; i++, vertexIndex++) { vertices[vertexIndex].position = positions[i + 4]; - vertices[vertexIndex].normal = normals[5]; + vertices[vertexIndex].normal = normals[5]; } - } -void PrimitiveVisual::FormCubeTriangles( Vector& indices ) +void PrimitiveVisual::FormCubeTriangles(Vector& indices) { - int numTriangles = 12; - int triangleIndex = 0; //Track progress through indices. + int numTriangles = 12; + int triangleIndex = 0; //Track progress through indices. - indices.Resize( 3 * numTriangles ); + indices.Resize(3 * numTriangles); //Top face. - indices[triangleIndex] = 0; + indices[triangleIndex] = 0; indices[triangleIndex + 1] = 2; indices[triangleIndex + 2] = 1; indices[triangleIndex + 3] = 2; @@ -979,13 +967,13 @@ void PrimitiveVisual::FormCubeTriangles( Vector& indices ) indices[triangleIndex + 5] = 3; triangleIndex += 6; - int topFaceStart = 4; + int topFaceStart = 4; int bottomFaceStart = 12; //Side faces. - for( int i = 0; i < 8; i += 2, triangleIndex += 6 ) + for(int i = 0; i < 8; i += 2, triangleIndex += 6) { - indices[triangleIndex ] = i + topFaceStart; + indices[triangleIndex] = i + topFaceStart; indices[triangleIndex + 1] = i + topFaceStart + 1; indices[triangleIndex + 2] = i + bottomFaceStart + 1; indices[triangleIndex + 3] = i + topFaceStart; @@ -994,7 +982,7 @@ void PrimitiveVisual::FormCubeTriangles( Vector& indices ) } //Bottom face. - indices[triangleIndex] = 20; + indices[triangleIndex] = 20; indices[triangleIndex + 1] = 21; indices[triangleIndex + 2] = 22; indices[triangleIndex + 3] = 22; @@ -1002,120 +990,119 @@ void PrimitiveVisual::FormCubeTriangles( Vector& indices ) indices[triangleIndex + 5] = 20; } -void PrimitiveVisual::ComputeOctahedronVertices( Vector& vertices, Vector3 dimensions, float smoothness ) +void PrimitiveVisual::ComputeOctahedronVertices(Vector& vertices, Vector3 dimensions, float smoothness) { - int numVertices = 3 * 8; //Three per face - int vertexIndex = 0; //Tracks progress through vertices. - float scaledX = 0.5 * dimensions.x; - float scaledY = 0.5 * dimensions.y; - float scaledZ = 0.5 * dimensions.z; + int numVertices = 3 * 8; //Three per face + int vertexIndex = 0; //Tracks progress through vertices. + float scaledX = 0.5 * dimensions.x; + float scaledY = 0.5 * dimensions.y; + float scaledZ = 0.5 * dimensions.z; - vertices.Resize( numVertices ); + vertices.Resize(numVertices); Vector positions; //Stores vertex positions, which are shared between vertexes at the same position but with a different normal. positions.Resize(6); Vector normals; //Stores normals, which are shared between vertexes of the same face. normals.Resize(8); - Vector outerNormals; //Holds normals that point outwards at each vertex. - outerNormals.Resize( 6 ); - - positions[0] = Vector3( 0.0, scaledY, 0.0 ); - positions[1] = Vector3( -scaledX, 0.0, 0.0 ); - positions[2] = Vector3( 0.0, 0.0, -scaledZ ); - positions[3] = Vector3( scaledX, 0.0, 0.0 ); - positions[4] = Vector3( 0.0, 0.0, scaledZ ); - positions[5] = Vector3( 0.0, -scaledY, 0.0 ); - - normals[0] = Vector3( -1, 1, -1 ); - normals[1] = Vector3( 1, 1, -1 ); - normals[2] = Vector3( 1, 1, 1 ); - normals[3] = Vector3( -1, 1, 1 ); - normals[4] = Vector3( -1, -1, -1 ); - normals[5] = Vector3( 1, -1, -1 ); - normals[6] = Vector3( 1, -1, 1 ); - normals[7] = Vector3( -1, -1, 1 ); - - outerNormals[0] = Vector3( 0, 1, 0 ); - outerNormals[1] = Vector3( -1, 0, 0 ); - outerNormals[2] = Vector3( 0, 0, -1 ); - outerNormals[3] = Vector3( 1, 0, 0 ); - outerNormals[4] = Vector3( 0, 0, 1 ); - outerNormals[5] = Vector3( 0, -1, 0 ); + Vector outerNormals; //Holds normals that point outwards at each vertex. + outerNormals.Resize(6); + + positions[0] = Vector3(0.0, scaledY, 0.0); + positions[1] = Vector3(-scaledX, 0.0, 0.0); + positions[2] = Vector3(0.0, 0.0, -scaledZ); + positions[3] = Vector3(scaledX, 0.0, 0.0); + positions[4] = Vector3(0.0, 0.0, scaledZ); + positions[5] = Vector3(0.0, -scaledY, 0.0); + + normals[0] = Vector3(-1, 1, -1); + normals[1] = Vector3(1, 1, -1); + normals[2] = Vector3(1, 1, 1); + normals[3] = Vector3(-1, 1, 1); + normals[4] = Vector3(-1, -1, -1); + normals[5] = Vector3(1, -1, -1); + normals[6] = Vector3(1, -1, 1); + normals[7] = Vector3(-1, -1, 1); + + outerNormals[0] = Vector3(0, 1, 0); + outerNormals[1] = Vector3(-1, 0, 0); + outerNormals[2] = Vector3(0, 0, -1); + outerNormals[3] = Vector3(1, 0, 0); + outerNormals[4] = Vector3(0, 0, 1); + outerNormals[5] = Vector3(0, -1, 0); //Loop through top faces. - for( int i = 0; i < 4; i++, vertexIndex += 3 ) + for(int i = 0; i < 4; i++, vertexIndex += 3) { - if( i == 3 ) + if(i == 3) { //End, so loop around. - vertices[vertexIndex ].position = positions[0]; - vertices[vertexIndex ].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness); + vertices[vertexIndex].position = positions[0]; + vertices[vertexIndex].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness); vertices[vertexIndex + 1].position = positions[1]; - vertices[vertexIndex + 1].normal = outerNormals[1] * smoothness + normals[i] * (1 - smoothness); + vertices[vertexIndex + 1].normal = outerNormals[1] * smoothness + normals[i] * (1 - smoothness); vertices[vertexIndex + 2].position = positions[i + 1]; - vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness); + vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness); } else { - vertices[vertexIndex ].position = positions[0]; - vertices[vertexIndex ].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness); + vertices[vertexIndex].position = positions[0]; + vertices[vertexIndex].normal = outerNormals[0] * smoothness + normals[i] * (1 - smoothness); vertices[vertexIndex + 1].position = positions[i + 2]; - vertices[vertexIndex + 1].normal = outerNormals[i + 2] * smoothness + normals[i] * (1 - smoothness); + vertices[vertexIndex + 1].normal = outerNormals[i + 2] * smoothness + normals[i] * (1 - smoothness); vertices[vertexIndex + 2].position = positions[i + 1]; - vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness); + vertices[vertexIndex + 2].normal = outerNormals[i + 1] * smoothness + normals[i] * (1 - smoothness); } } //Loop through bottom faces. - for( int i = 0; i < 4; i++, vertexIndex += 3 ) + for(int i = 0; i < 4; i++, vertexIndex += 3) { - if( i == 3 ) + if(i == 3) { //End, so loop around. - vertices[vertexIndex ].position = positions[5]; - vertices[vertexIndex ].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness); + vertices[vertexIndex].position = positions[5]; + vertices[vertexIndex].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness); vertices[vertexIndex + 1].position = positions[i + 1]; - vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness); + vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness); vertices[vertexIndex + 2].position = positions[1]; - vertices[vertexIndex + 2].normal = outerNormals[1] * smoothness + normals[i + 4] * (1 - smoothness); + vertices[vertexIndex + 2].normal = outerNormals[1] * smoothness + normals[i + 4] * (1 - smoothness); } else { - vertices[vertexIndex ].position = positions[5]; - vertices[vertexIndex ].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness); + vertices[vertexIndex].position = positions[5]; + vertices[vertexIndex].normal = outerNormals[5] * smoothness + normals[i + 4] * (1 - smoothness); vertices[vertexIndex + 1].position = positions[i + 1]; - vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness); + vertices[vertexIndex + 1].normal = outerNormals[i + 1] * smoothness + normals[i + 4] * (1 - smoothness); vertices[vertexIndex + 2].position = positions[i + 2]; - vertices[vertexIndex + 2].normal = outerNormals[i + 2] * smoothness + normals[i + 4] * (1 - smoothness); + vertices[vertexIndex + 2].normal = outerNormals[i + 2] * smoothness + normals[i + 4] * (1 - smoothness); } } } -void PrimitiveVisual::FormOctahedronTriangles( Vector& indices ) +void PrimitiveVisual::FormOctahedronTriangles(Vector& indices) { int numTriangles = 8; - int numIndices = numTriangles * 3; + int numIndices = numTriangles * 3; - indices.Resize( numIndices ); + indices.Resize(numIndices); - for( unsigned short i = 0; i < numIndices; i++ ) + for(unsigned short i = 0; i < numIndices; i++) { indices[i] = i; } } -void PrimitiveVisual::ComputeBevelledCubeVertices( Vector& vertices, Vector3 dimensions, - float bevelPercentage, float bevelSmoothness ) +void PrimitiveVisual::ComputeBevelledCubeVertices(Vector& vertices, Vector3 dimensions, float bevelPercentage, float bevelSmoothness) { - int numPositions = 24; - int numFaces = 26; + int numPositions = 24; + int numFaces = 26; int numOuterFaces = 6; - int numVertices = 6 * 4 + 12 * 4 + 8 * 3; //Six outer faces, 12 slanting rectangles, 8 slanting triangles. - int vertexIndex = 0; //Track progress through vertices. - int normalIndex = 0; //Track progress through normals, as vertices are calculated per face. + int numVertices = 6 * 4 + 12 * 4 + 8 * 3; //Six outer faces, 12 slanting rectangles, 8 slanting triangles. + int vertexIndex = 0; //Track progress through vertices. + int normalIndex = 0; //Track progress through normals, as vertices are calculated per face. - float minDimension = std::min( std::min( dimensions.x, dimensions.y ), dimensions.z ); - float bevelAmount = 0.5 * std::min( bevelPercentage, minDimension ); //Cap bevel amount if necessary. + float minDimension = std::min(std::min(dimensions.x, dimensions.y), dimensions.z); + float bevelAmount = 0.5 * std::min(bevelPercentage, minDimension); //Cap bevel amount if necessary. //Distances from centre to outer edge points. float outerX = 0.5 * dimensions.x; @@ -1127,238 +1114,238 @@ void PrimitiveVisual::ComputeBevelledCubeVertices( Vector& vertices, Vec float bevelY = outerY - bevelAmount; float bevelZ = outerZ - bevelAmount; - Vector positions; //Holds object points, to be shared between vertexes. - positions.Resize( numPositions ); - Vector normals; //Holds face normals, to be shared between vertexes. - normals.Resize( numFaces ); - Vector outerNormals; //Holds normals of the outermost faces specifically. - outerNormals.Resize( numOuterFaces ); - vertices.Resize( numVertices ); + Vector positions; //Holds object points, to be shared between vertexes. + positions.Resize(numPositions); + Vector normals; //Holds face normals, to be shared between vertexes. + normals.Resize(numFaces); + Vector outerNormals; //Holds normals of the outermost faces specifically. + outerNormals.Resize(numOuterFaces); + vertices.Resize(numVertices); //Topmost face positions. - positions[0 ] = Vector3( -bevelX, outerY, -bevelZ ); - positions[1 ] = Vector3( bevelX, outerY, -bevelZ ); - positions[2 ] = Vector3( bevelX, outerY, bevelZ ); - positions[3 ] = Vector3( -bevelX, outerY, bevelZ ); + positions[0] = Vector3(-bevelX, outerY, -bevelZ); + positions[1] = Vector3(bevelX, outerY, -bevelZ); + positions[2] = Vector3(bevelX, outerY, bevelZ); + positions[3] = Vector3(-bevelX, outerY, bevelZ); //Second layer positions. - positions[4 ] = Vector3( -outerX, bevelY, -bevelZ ); - positions[5 ] = Vector3( -bevelX, bevelY, -outerZ ); - positions[6 ] = Vector3( bevelX, bevelY, -outerZ ); - positions[7 ] = Vector3( outerX, bevelY, -bevelZ ); - positions[8 ] = Vector3( outerX, bevelY, bevelZ ); - positions[9 ] = Vector3( bevelX, bevelY, outerZ ); - positions[10] = Vector3( -bevelX, bevelY, outerZ ); - positions[11] = Vector3( -outerX, bevelY, bevelZ ); + positions[4] = Vector3(-outerX, bevelY, -bevelZ); + positions[5] = Vector3(-bevelX, bevelY, -outerZ); + positions[6] = Vector3(bevelX, bevelY, -outerZ); + positions[7] = Vector3(outerX, bevelY, -bevelZ); + positions[8] = Vector3(outerX, bevelY, bevelZ); + positions[9] = Vector3(bevelX, bevelY, outerZ); + positions[10] = Vector3(-bevelX, bevelY, outerZ); + positions[11] = Vector3(-outerX, bevelY, bevelZ); //Third layer positions. - positions[12] = Vector3( -outerX, -bevelY, -bevelZ ); - positions[13] = Vector3( -bevelX, -bevelY, -outerZ ); - positions[14] = Vector3( bevelX, -bevelY, -outerZ ); - positions[15] = Vector3( outerX, -bevelY, -bevelZ ); - positions[16] = Vector3( outerX, -bevelY, bevelZ ); - positions[17] = Vector3( bevelX, -bevelY, outerZ ); - positions[18] = Vector3( -bevelX, -bevelY, outerZ ); - positions[19] = Vector3( -outerX, -bevelY, bevelZ ); + positions[12] = Vector3(-outerX, -bevelY, -bevelZ); + positions[13] = Vector3(-bevelX, -bevelY, -outerZ); + positions[14] = Vector3(bevelX, -bevelY, -outerZ); + positions[15] = Vector3(outerX, -bevelY, -bevelZ); + positions[16] = Vector3(outerX, -bevelY, bevelZ); + positions[17] = Vector3(bevelX, -bevelY, outerZ); + positions[18] = Vector3(-bevelX, -bevelY, outerZ); + positions[19] = Vector3(-outerX, -bevelY, bevelZ); //Bottom-most face positions. - positions[20] = Vector3( -bevelX, -outerY, -bevelZ ); - positions[21] = Vector3( bevelX, -outerY, -bevelZ ); - positions[22] = Vector3( bevelX, -outerY, bevelZ ); - positions[23] = Vector3( -bevelX, -outerY, bevelZ ); + positions[20] = Vector3(-bevelX, -outerY, -bevelZ); + positions[21] = Vector3(bevelX, -outerY, -bevelZ); + positions[22] = Vector3(bevelX, -outerY, bevelZ); + positions[23] = Vector3(-bevelX, -outerY, bevelZ); //Top face normal. - normals[0 ] = Vector3( 0, 1, 0 ); + normals[0] = Vector3(0, 1, 0); //Top slope normals. - normals[1 ] = Vector3( -1, 1, -1 ); - normals[2 ] = Vector3( 0, 1, -1 ); - normals[3 ] = Vector3( 1, 1, -1 ); - normals[4 ] = Vector3( 1, 1, 0 ); - normals[5 ] = Vector3( 1, 1, 1 ); - normals[6 ] = Vector3( 0, 1, 1 ); - normals[7 ] = Vector3( -1, 1, 1 ); - normals[8 ] = Vector3( -1, 1, 0 ); + normals[1] = Vector3(-1, 1, -1); + normals[2] = Vector3(0, 1, -1); + normals[3] = Vector3(1, 1, -1); + normals[4] = Vector3(1, 1, 0); + normals[5] = Vector3(1, 1, 1); + normals[6] = Vector3(0, 1, 1); + normals[7] = Vector3(-1, 1, 1); + normals[8] = Vector3(-1, 1, 0); //Side normals. - normals[9 ] = Vector3( -1, 0, -1 ); - normals[10] = Vector3( 0, 0, -1 ); - normals[11] = Vector3( 1, 0, -1 ); - normals[12] = Vector3( 1, 0, 0 ); - normals[13] = Vector3( 1, 0, 1 ); - normals[14] = Vector3( 0, 0, 1 ); - normals[15] = Vector3( -1, 0, 1 ); - normals[16] = Vector3( -1, 0, 0 ); + normals[9] = Vector3(-1, 0, -1); + normals[10] = Vector3(0, 0, -1); + normals[11] = Vector3(1, 0, -1); + normals[12] = Vector3(1, 0, 0); + normals[13] = Vector3(1, 0, 1); + normals[14] = Vector3(0, 0, 1); + normals[15] = Vector3(-1, 0, 1); + normals[16] = Vector3(-1, 0, 0); //Bottom slope normals. - normals[17] = Vector3( -1, -1, -1 ); - normals[18] = Vector3( 0, -1, -1 ); - normals[19] = Vector3( 1, -1, -1 ); - normals[20] = Vector3( 1, -1, 0 ); - normals[21] = Vector3( 1, -1, 1 ); - normals[22] = Vector3( 0, -1, 1 ); - normals[23] = Vector3( -1, -1, 1 ); - normals[24] = Vector3( -1, -1, 0 ); + normals[17] = Vector3(-1, -1, -1); + normals[18] = Vector3(0, -1, -1); + normals[19] = Vector3(1, -1, -1); + normals[20] = Vector3(1, -1, 0); + normals[21] = Vector3(1, -1, 1); + normals[22] = Vector3(0, -1, 1); + normals[23] = Vector3(-1, -1, 1); + normals[24] = Vector3(-1, -1, 0); //Bottom face normal. - normals[25] = Vector3( 0, -1, 0 ); + normals[25] = Vector3(0, -1, 0); //Top, back, right, front, left and bottom faces, respectively. - outerNormals[0] = Vector3( 0, 1, 0 ); - outerNormals[1] = Vector3( 0, 0, -1 ); - outerNormals[2] = Vector3( 1, 0, 0 ); - outerNormals[3] = Vector3( 0, 0, 1 ); - outerNormals[4] = Vector3( -1, 0, 0 ); - outerNormals[5] = Vector3( 0, -1, 0 ); + outerNormals[0] = Vector3(0, 1, 0); + outerNormals[1] = Vector3(0, 0, -1); + outerNormals[2] = Vector3(1, 0, 0); + outerNormals[3] = Vector3(0, 0, 1); + outerNormals[4] = Vector3(-1, 0, 0); + outerNormals[5] = Vector3(0, -1, 0); //Topmost face vertices. - for( int i = 0; i < 4; i++, vertexIndex++ ) + for(int i = 0; i < 4; i++, vertexIndex++) { vertices[vertexIndex].position = positions[i]; - vertices[vertexIndex].normal = normals[normalIndex]; + vertices[vertexIndex].normal = normals[normalIndex]; } normalIndex++; //Top slope vertices. - for( int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2 ) + for(int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2) { //Triangle part - vertices[vertexIndex ].position = positions[i]; - vertices[vertexIndex ].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex].position = positions[i]; + vertices[vertexIndex].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 1].position = positions[2 * i + 4]; - vertices[vertexIndex + 1].normal = outerNormals[( i == 0 ) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 1].normal = outerNormals[(i == 0) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 2].position = positions[2 * i + 5]; - vertices[vertexIndex + 2].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 2].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); //Rectangle part - if( i == 3 ) + if(i == 3) { //End, so loop around. vertices[vertexIndex + 3].position = positions[i]; - vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 4].position = positions[0]; - vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 5].position = positions[2 * i + 5]; - vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 6].position = positions[4]; - vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); } else { vertices[vertexIndex + 3].position = positions[i]; - vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 3].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 4].position = positions[i + 1]; - vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 4].normal = outerNormals[0] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 5].position = positions[2 * i + 5]; - vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 5].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 6].position = positions[2 * i + 6]; - vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 6].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); } } int secondCycleBeginning = 4; - int thirdCycleBeginning = secondCycleBeginning + 8; + int thirdCycleBeginning = secondCycleBeginning + 8; int bottomCycleBeginning = thirdCycleBeginning + 8; //Side vertices. - for( int i = 0; i < 8; i++, vertexIndex += 4, normalIndex++ ) + for(int i = 0; i < 8; i++, vertexIndex += 4, normalIndex++) { - if( i == 7 ) + if(i == 7) { //End, so loop around. - vertices[vertexIndex ].position = positions[secondCycleBeginning + i]; - vertices[vertexIndex ].normal = normals[normalIndex]; + vertices[vertexIndex].position = positions[secondCycleBeginning + i]; + vertices[vertexIndex].normal = normals[normalIndex]; vertices[vertexIndex + 1].position = positions[secondCycleBeginning]; - vertices[vertexIndex + 1].normal = normals[normalIndex]; + vertices[vertexIndex + 1].normal = normals[normalIndex]; vertices[vertexIndex + 2].position = positions[thirdCycleBeginning + i]; - vertices[vertexIndex + 2].normal = normals[normalIndex]; + vertices[vertexIndex + 2].normal = normals[normalIndex]; vertices[vertexIndex + 3].position = positions[thirdCycleBeginning]; - vertices[vertexIndex + 3].normal = normals[normalIndex]; + vertices[vertexIndex + 3].normal = normals[normalIndex]; } - else if( (i % 2) == 0 ) + else if((i % 2) == 0) { //'even' faces are corner ones, and need smoothing. - vertices[vertexIndex ].position = positions[secondCycleBeginning + i]; - vertices[vertexIndex ].normal = outerNormals[( i == 0 ) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex].position = positions[secondCycleBeginning + i]; + vertices[vertexIndex].normal = outerNormals[(i == 0) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 1].position = positions[secondCycleBeginning + i + 1]; - vertices[vertexIndex + 1].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 1].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 2].position = positions[thirdCycleBeginning + i]; - vertices[vertexIndex + 2].normal = outerNormals[( i == 0 ) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 2].normal = outerNormals[(i == 0) ? 4 : i / 2] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + i + 1]; - vertices[vertexIndex + 3].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 3].normal = outerNormals[i / 2 + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); } else { //'odd' faces are outer ones, and so don't need smoothing. - vertices[vertexIndex ].position = positions[secondCycleBeginning + i]; - vertices[vertexIndex ].normal = normals[normalIndex]; + vertices[vertexIndex].position = positions[secondCycleBeginning + i]; + vertices[vertexIndex].normal = normals[normalIndex]; vertices[vertexIndex + 1].position = positions[secondCycleBeginning + i + 1]; - vertices[vertexIndex + 1].normal = normals[normalIndex]; + vertices[vertexIndex + 1].normal = normals[normalIndex]; vertices[vertexIndex + 2].position = positions[thirdCycleBeginning + i]; - vertices[vertexIndex + 2].normal = normals[normalIndex]; + vertices[vertexIndex + 2].normal = normals[normalIndex]; vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + i + 1]; - vertices[vertexIndex + 3].normal = normals[normalIndex]; + vertices[vertexIndex + 3].normal = normals[normalIndex]; } } //Bottom slope vertices. - for( int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2 ) + for(int i = 0; i < 4; i++, vertexIndex += 7, normalIndex += 2) { //Triangle part - vertices[vertexIndex ].position = positions[thirdCycleBeginning + 2 * i]; - vertices[vertexIndex ].normal = outerNormals[( i == 0 ) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex].position = positions[thirdCycleBeginning + 2 * i]; + vertices[vertexIndex].normal = outerNormals[(i == 0) ? 4 : i] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 1].position = positions[thirdCycleBeginning + 2 * i + 1]; - vertices[vertexIndex + 1].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 1].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); vertices[vertexIndex + 2].position = positions[bottomCycleBeginning + i]; - vertices[vertexIndex + 2].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); + vertices[vertexIndex + 2].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex] * (1 - bevelSmoothness); //Rectangle part - if( i == 3 ) + if(i == 3) { //End, so loop around. vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + 2 * i + 1]; - vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 4].position = positions[thirdCycleBeginning]; - vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 5].position = positions[bottomCycleBeginning + i]; - vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 6].position = positions[bottomCycleBeginning]; - vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); } else { vertices[vertexIndex + 3].position = positions[thirdCycleBeginning + 2 * i + 1]; - vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 3].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 4].position = positions[thirdCycleBeginning + 2 * i + 2]; - vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 4].normal = outerNormals[i + 1] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 5].position = positions[bottomCycleBeginning + i]; - vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 5].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); vertices[vertexIndex + 6].position = positions[bottomCycleBeginning + i + 1]; - vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); + vertices[vertexIndex + 6].normal = outerNormals[5] * bevelSmoothness + normals[normalIndex + 1] * (1 - bevelSmoothness); } } //Bottom-most face vertices. - for( int i = 0; i < 4; i++, vertexIndex++ ) + for(int i = 0; i < 4; i++, vertexIndex++) { - vertices[vertexIndex].position = positions[ bottomCycleBeginning + i]; - vertices[vertexIndex].normal = normals[normalIndex]; + vertices[vertexIndex].position = positions[bottomCycleBeginning + i]; + vertices[vertexIndex].normal = normals[normalIndex]; } normalIndex++; } -void PrimitiveVisual::FormBevelledCubeTriangles( Vector& indices ) +void PrimitiveVisual::FormBevelledCubeTriangles(Vector& indices) { int numTriangles = 44; //(Going from top to bottom, that's 2 + 12 + 16 + 12 + 2) - int indiceIndex = 0; //Track progress through indices. - int vertexIndex = 0; //Track progress through vertices as they're processed. + int indiceIndex = 0; //Track progress through indices. + int vertexIndex = 0; //Track progress through vertices as they're processed. - indices.Resize( 3 * numTriangles ); + indices.Resize(3 * numTriangles); //Top face. - indices[indiceIndex ] = vertexIndex; + indices[indiceIndex] = vertexIndex; indices[indiceIndex + 1] = vertexIndex + 2; indices[indiceIndex + 2] = vertexIndex + 1; indices[indiceIndex + 3] = vertexIndex + 0; @@ -1368,10 +1355,10 @@ void PrimitiveVisual::FormBevelledCubeTriangles( Vector& indices vertexIndex += 4; //Top slopes. - for( int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7 ) + for(int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7) { //Triangle part. - indices[indiceIndex ] = vertexIndex; + indices[indiceIndex] = vertexIndex; indices[indiceIndex + 1] = vertexIndex + 2; indices[indiceIndex + 2] = vertexIndex + 1; @@ -1385,9 +1372,9 @@ void PrimitiveVisual::FormBevelledCubeTriangles( Vector& indices } //Side faces. - for( int i = 0; i < 8; i++, indiceIndex += 6, vertexIndex += 4 ) + for(int i = 0; i < 8; i++, indiceIndex += 6, vertexIndex += 4) { - indices[indiceIndex ] = vertexIndex; + indices[indiceIndex] = vertexIndex; indices[indiceIndex + 1] = vertexIndex + 1; indices[indiceIndex + 2] = vertexIndex + 2; indices[indiceIndex + 3] = vertexIndex + 1; @@ -1396,10 +1383,10 @@ void PrimitiveVisual::FormBevelledCubeTriangles( Vector& indices } //Bottom slopes. - for( int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7 ) + for(int i = 0; i < 4; i++, indiceIndex += 9, vertexIndex += 7) { //Triangle part. - indices[indiceIndex ] = vertexIndex; + indices[indiceIndex] = vertexIndex; indices[indiceIndex + 1] = vertexIndex + 1; indices[indiceIndex + 2] = vertexIndex + 2; @@ -1413,7 +1400,7 @@ void PrimitiveVisual::FormBevelledCubeTriangles( Vector& indices } //Bottom face. - indices[indiceIndex ] = vertexIndex; + indices[indiceIndex] = vertexIndex; indices[indiceIndex + 1] = vertexIndex + 1; indices[indiceIndex + 2] = vertexIndex + 2; indices[indiceIndex + 3] = vertexIndex + 0; diff --git a/dali-toolkit/internal/visuals/svg/svg-rasterize-thread.cpp b/dali-toolkit/internal/visuals/svg/svg-rasterize-thread.cpp index c5f0555..e2b55b5 100644 --- a/dali-toolkit/internal/visuals/svg/svg-rasterize-thread.cpp +++ b/dali-toolkit/internal/visuals/svg/svg-rasterize-thread.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 "svg-rasterize-thread.h" // EXTERNAL INCLUDES -#include #include +#include #include #include @@ -29,10 +29,8 @@ namespace Dali { - namespace Toolkit { - namespace Internal { RasterizingTask::RasterizingTask(SvgVisual* svgRenderer, VectorImageRenderer vectorRenderer, const VisualUrl& url, float dpi, unsigned int width, unsigned int height) @@ -44,7 +42,6 @@ RasterizingTask::RasterizingTask(SvgVisual* svgRenderer, VectorImageRenderer vec mHeight(height), mLoadSuccess(false) { - } RasterizingTask::~RasterizingTask() @@ -125,27 +122,27 @@ PixelData RasterizingTask::GetPixelData() const } SvgRasterizeThread::SvgRasterizeThread() -: mTrigger( new EventThreadCallback( MakeCallback( this, &SvgRasterizeThread::ApplyRasterizedSVGToSampler ) ) ), - mLogFactory( Dali::Adaptor::Get().GetLogFactory() ), - mIsThreadWaiting( false ), - mProcessorRegistered( false ) +: mTrigger(new EventThreadCallback(MakeCallback(this, &SvgRasterizeThread::ApplyRasterizedSVGToSampler))), + mLogFactory(Dali::Adaptor::Get().GetLogFactory()), + mIsThreadWaiting(false), + mProcessorRegistered(false) { } SvgRasterizeThread::~SvgRasterizeThread() { - if( mProcessorRegistered ) + if(mProcessorRegistered) { - Adaptor::Get().UnregisterProcessor( *this ); + Adaptor::Get().UnregisterProcessor(*this); } } -void SvgRasterizeThread::TerminateThread( SvgRasterizeThread*& thread ) +void SvgRasterizeThread::TerminateThread(SvgRasterizeThread*& thread) { - if( thread ) + if(thread) { // add an empty task would stop the thread from conditional wait. - thread->AddTask( RasterizingTaskPtr() ); + thread->AddTask(RasterizingTaskPtr()); // stop the thread thread->Join(); // delete the thread @@ -154,37 +151,37 @@ void SvgRasterizeThread::TerminateThread( SvgRasterizeThread*& thread ) } } -void SvgRasterizeThread::AddTask( RasterizingTaskPtr task ) +void SvgRasterizeThread::AddTask(RasterizingTaskPtr task) { bool wasEmpty = false; { // Lock while adding task to the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); wasEmpty = mRasterizeTasks.empty(); - if( !wasEmpty && task != NULL) + if(!wasEmpty && task != NULL) { // Remove the tasks with the same renderer. // Older task which waiting to rasterize and apply the svg to the same renderer is expired. - for( std::vector< RasterizingTaskPtr >::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it ) + for(std::vector::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it) { - if( (*it) && (*it)->GetSvgVisual() == task->GetSvgVisual() ) + if((*it) && (*it)->GetSvgVisual() == task->GetSvgVisual()) { - mRasterizeTasks.erase( it ); + mRasterizeTasks.erase(it); break; } } } - mRasterizeTasks.push_back( task ); + mRasterizeTasks.push_back(task); - if( !mProcessorRegistered ) + if(!mProcessorRegistered) { - Adaptor::Get().RegisterProcessor( *this ); + Adaptor::Get().RegisterProcessor(*this); mProcessorRegistered = true; } } - if( wasEmpty) + if(wasEmpty) { // wake up the image loading thread mConditionalWait.Notify(); @@ -194,31 +191,31 @@ void SvgRasterizeThread::AddTask( RasterizingTaskPtr task ) RasterizingTaskPtr SvgRasterizeThread::NextCompletedTask() { // Lock while popping task out from the queue - Mutex::ScopedLock lock( mMutex ); + Mutex::ScopedLock lock(mMutex); - if( mCompletedTasks.empty() ) + if(mCompletedTasks.empty()) { return RasterizingTaskPtr(); } - std::vector< RasterizingTaskPtr >::iterator next = mCompletedTasks.begin(); - RasterizingTaskPtr nextTask = *next; - mCompletedTasks.erase( next ); + std::vector::iterator next = mCompletedTasks.begin(); + RasterizingTaskPtr nextTask = *next; + mCompletedTasks.erase(next); return nextTask; } -void SvgRasterizeThread::RemoveTask( SvgVisual* visual ) +void SvgRasterizeThread::RemoveTask(SvgVisual* visual) { // Lock while remove task from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); - if( !mRasterizeTasks.empty() ) + ConditionalWait::ScopedLock lock(mConditionalWait); + if(!mRasterizeTasks.empty()) { - for( std::vector< RasterizingTaskPtr >::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it ) + for(std::vector::iterator it = mRasterizeTasks.begin(), endIt = mRasterizeTasks.end(); it != endIt; ++it) { - if( (*it) && (*it)->GetSvgVisual() == visual ) + if((*it) && (*it)->GetSvgVisual() == visual) { - mRasterizeTasks.erase( it ); + mRasterizeTasks.erase(it); break; } } @@ -227,53 +224,53 @@ void SvgRasterizeThread::RemoveTask( SvgVisual* visual ) UnregisterProcessor(); } -void SvgRasterizeThread::DeleteImage( VectorImageRenderer vectorRenderer ) +void SvgRasterizeThread::DeleteImage(VectorImageRenderer vectorRenderer) { // Lock while adding image to the delete queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); - if( mIsThreadWaiting ) // no rasterization is ongoing, save to delete + if(mIsThreadWaiting) // no rasterization is ongoing, save to delete { // TODO: what? } else // wait to delete until current rasterization completed. { - mDeleteSvg.PushBack( &vectorRenderer ); + mDeleteSvg.PushBack(&vectorRenderer); } } RasterizingTaskPtr SvgRasterizeThread::NextTaskToProcess() { // Lock while popping task out from the queue - ConditionalWait::ScopedLock lock( mConditionalWait ); + ConditionalWait::ScopedLock lock(mConditionalWait); // Delete the image here to make sure that it is not used in the nsvgRasterize() - if( !mDeleteSvg.Empty() ) + if(!mDeleteSvg.Empty()) { mDeleteSvg.Clear(); } // conditional wait - while( mRasterizeTasks.empty() ) + while(mRasterizeTasks.empty()) { mIsThreadWaiting = true; - mConditionalWait.Wait( lock ); + mConditionalWait.Wait(lock); } mIsThreadWaiting = false; // pop out the next task from the queue - std::vector< RasterizingTaskPtr >::iterator next = mRasterizeTasks.begin(); - RasterizingTaskPtr nextTask = *next; - mRasterizeTasks.erase( next ); + std::vector::iterator next = mRasterizeTasks.begin(); + RasterizingTaskPtr nextTask = *next; + mRasterizeTasks.erase(next); return nextTask; } -void SvgRasterizeThread::AddCompletedTask( RasterizingTaskPtr task ) +void SvgRasterizeThread::AddCompletedTask(RasterizingTaskPtr task) { // Lock while adding task to the queue - Mutex::ScopedLock lock( mMutex ); - mCompletedTasks.push_back( task ); + Mutex::ScopedLock lock(mMutex); + mCompletedTasks.push_back(task); // wake up the main thread mTrigger->Trigger(); @@ -281,20 +278,20 @@ void SvgRasterizeThread::AddCompletedTask( RasterizingTaskPtr task ) void SvgRasterizeThread::Run() { - SetThreadName( "SVGThread" ); + SetThreadName("SVGThread"); mLogFactory.InstallLogFunction(); - while( RasterizingTaskPtr task = NextTaskToProcess() ) + while(RasterizingTaskPtr task = NextTaskToProcess()) { - task->Load( ); - task->Rasterize( ); - AddCompletedTask( task ); + task->Load(); + task->Rasterize(); + AddCompletedTask(task); } } void SvgRasterizeThread::ApplyRasterizedSVGToSampler() { - while( RasterizingTaskPtr task = NextCompletedTask() ) + while(RasterizingTaskPtr task = NextCompletedTask()) { task->GetSvgVisual()->ApplyRasterizedImage(task->GetVectorRenderer(), task->GetPixelData(), task->IsLoaded()); } @@ -309,17 +306,16 @@ void SvgRasterizeThread::Process() void SvgRasterizeThread::UnregisterProcessor() { - if ( mProcessorRegistered ) + if(mProcessorRegistered) { - if( mRasterizeTasks.empty() && mCompletedTasks.empty() ) + if(mRasterizeTasks.empty() && mCompletedTasks.empty()) { - Adaptor::Get().UnregisterProcessor( *this ); + Adaptor::Get().UnregisterProcessor(*this); mProcessorRegistered = false; } } } - } // namespace Internal } // namespace Toolkit diff --git a/dali-toolkit/internal/visuals/svg/svg-visual.cpp b/dali-toolkit/internal/visuals/svg/svg-visual.cpp index ec19635..dc148a2 100644 --- a/dali-toolkit/internal/visuals/svg/svg-visual.cpp +++ b/dali-toolkit/internal/visuals/svg/svg-visual.cpp @@ -19,46 +19,43 @@ #include "svg-visual.h" // INTERNAL INCLUDES -#include #include -#include -#include #include +#include +#include +#include #include // EXTERNAL INCLUDES -#include #include +#include #include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { // property name const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); -} +} // namespace -SvgVisualPtr SvgVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties ) +SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties) { - SvgVisualPtr svgVisual( new SvgVisual( factoryCache, shaderFactory, imageUrl ) ); + SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl)); svgVisual->Load(); svgVisual->SetProperties(properties); svgVisual->Initialize(); return svgVisual; } -SvgVisualPtr SvgVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl ) +SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl) { - SvgVisualPtr svgVisual( new SvgVisual( factoryCache, shaderFactory, imageUrl ) ); + SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl)); svgVisual->Load(); svgVisual->Initialize(); return svgVisual; @@ -105,42 +102,42 @@ void SvgVisual::OnInitialize() mImpl->mRenderer = Renderer::New(geometry, shader); } -void SvgVisual::DoSetProperties( const Property::Map& propertyMap ) +void SvgVisual::DoSetProperties(const Property::Map& propertyMap) { // url already passed in from constructor - for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter ) + for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter) { - KeyValuePair keyValue = propertyMap.GetKeyValue( iter ); - if( keyValue.first.type == Property::Key::INDEX ) + KeyValuePair keyValue = propertyMap.GetKeyValue(iter); + if(keyValue.first.type == Property::Key::INDEX) { - DoSetProperty( keyValue.first.indexKey, keyValue.second ); + DoSetProperty(keyValue.first.indexKey, keyValue.second); } - else if( keyValue.first == IMAGE_ATLASING ) + else if(keyValue.first == IMAGE_ATLASING) { - DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second); } - else if( keyValue.first == SYNCHRONOUS_LOADING ) + else if(keyValue.first == SYNCHRONOUS_LOADING) { - DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second ); + DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second); } } } -void SvgVisual::DoSetProperty( Property::Index index, const Property::Value& value ) +void SvgVisual::DoSetProperty(Property::Index index, const Property::Value& value) { - switch( index ) + switch(index) { case Toolkit::ImageVisual::Property::ATLASING: { - value.Get( mAttemptAtlasing ); + value.Get(mAttemptAtlasing); break; } case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING: { bool sync = false; - if( value.Get( sync ) ) + if(value.Get(sync)) { - if( sync ) + if(sync) { mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING; } @@ -158,13 +155,13 @@ void SvgVisual::DoSetProperty( Property::Index index, const Property::Value& val } } -void SvgVisual::DoSetOnScene( Actor& actor ) +void SvgVisual::DoSetOnScene(Actor& actor) { TextureSet textureSet = TextureSet::New(); - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); // Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm) @@ -187,36 +184,36 @@ void SvgVisual::DoSetOnScene( Actor& actor ) } } -void SvgVisual::DoSetOffScene( Actor& actor ) +void SvgVisual::DoSetOffScene(Actor& actor) { - mFactoryCache.GetSVGRasterizationThread()->RemoveTask( this ); + mFactoryCache.GetSVGRasterizationThread()->RemoveTask(this); - actor.RemoveRenderer( mImpl->mRenderer ); + actor.RemoveRenderer(mImpl->mRenderer); mPlacementActor.Reset(); // Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced mVisualSize = Vector2::ZERO; } -void SvgVisual::GetNaturalSize( Vector2& naturalSize ) +void SvgVisual::GetNaturalSize(Vector2& naturalSize) { naturalSize.x = mDefaultWidth; naturalSize.y = mDefaultHeight; } -void SvgVisual::DoCreatePropertyMap( Property::Map& map ) const +void SvgVisual::DoCreatePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG ); - if( mImageUrl.IsValid() ) + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG); + if(mImageUrl.IsValid()) { - map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() ); - map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing ); + map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl()); + map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing); } - map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired() ); + map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired()); } -void SvgVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void SvgVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } @@ -231,8 +228,8 @@ void SvgVisual::Load() { buffer.PushBack('\0'); - Vector2 dpi = Stage::GetCurrent().GetDpi(); - float meanDpi = (dpi.height + dpi.width) * 0.5f; + Vector2 dpi = Stage::GetCurrent().GetDpi(); + float meanDpi = (dpi.height + dpi.width) * 0.5f; if(!mVectorRenderer.Load(buffer, meanDpi)) { mLoadFailed = true; @@ -249,15 +246,15 @@ void SvgVisual::Load() } } -void SvgVisual::AddRasterizationTask( const Vector2& size ) +void SvgVisual::AddRasterizationTask(const Vector2& size) { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - unsigned int width = static_cast(size.width); - unsigned int height = static_cast( size.height ); + unsigned int width = static_cast(size.width); + unsigned int height = static_cast(size.height); - Vector2 dpi = Stage::GetCurrent().GetDpi(); - float meanDpi = ( dpi.height + dpi.width ) * 0.5f; + Vector2 dpi = Stage::GetCurrent().GetDpi(); + float meanDpi = (dpi.height + dpi.width) * 0.5f; RasterizingTaskPtr newTask = new RasterizingTask(this, mVectorRenderer, mImageUrl, meanDpi, width, height); if(IsSynchronousLoadingRequired() && mImageUrl.IsLocalResource()) @@ -268,76 +265,75 @@ void SvgVisual::AddRasterizationTask( const Vector2& size ) } else { - mFactoryCache.GetSVGRasterizationThread()->AddTask( newTask ); + mFactoryCache.GetSVGRasterizationThread()->AddTask(newTask); } } } -void SvgVisual::ApplyRasterizedImage( VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded ) +void SvgVisual::ApplyRasterizedImage(VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded) { if(isLoaded && rasterizedPixelData && IsOnScene()) { TextureSet currentTextureSet = mImpl->mRenderer.GetTextures(); - if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED ) + if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED) { - mFactoryCache.GetAtlasManager()->Remove( currentTextureSet, mAtlasRect ); + mFactoryCache.GetAtlasManager()->Remove(currentTextureSet, mAtlasRect); } TextureSet textureSet; - if( mAttemptAtlasing && !mImpl->mCustomShader ) + if(mAttemptAtlasing && !mImpl->mCustomShader) { Vector4 atlasRect; - textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData ); - if( textureSet ) // atlasing + textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData); + if(textureSet) // atlasing { - if( textureSet != currentTextureSet ) + if(textureSet != currentTextureSet) { - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); } - mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect ); + mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, atlasRect); mAtlasRect = atlasRect; mImpl->mFlags |= Impl::IS_ATLASING_APPLIED; } } - if( !textureSet ) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed + if(!textureSet) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed { - Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, - rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight() ); - texture.Upload( rasterizedPixelData ); + Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight()); + texture.Upload(rasterizedPixelData); mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED; - if( mAtlasRect == FULL_TEXTURE_RECT ) + if(mAtlasRect == FULL_TEXTURE_RECT) { textureSet = currentTextureSet; } else { textureSet = TextureSet::New(); - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); - mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT ); + mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT); mAtlasRect = FULL_TEXTURE_RECT; } - if( textureSet ) + if(textureSet) { - textureSet.SetTexture( 0, texture ); + textureSet.SetTexture(0, texture); } } // Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor. Actor actor = mPlacementActor.GetHandle(); - if( actor ) + if(actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // reset the weak handle so that the renderer only get added to actor once mPlacementActor.Reset(); } // Svg loaded and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } else if(!isLoaded || !rasterizedPixelData) { @@ -352,19 +348,19 @@ void SvgVisual::ApplyRasterizedImage( VectorImageRenderer vectorRenderer, PixelD actor.AddRenderer(mImpl->mRenderer); } - ResourceReady( Toolkit::Visual::ResourceStatus::FAILED ); + ResourceReady(Toolkit::Visual::ResourceStatus::FAILED); } } void SvgVisual::OnSetTransform() { - Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize ); + Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize); if(IsOnScene() && !mLoadFailed) { - if( visualSize != mVisualSize ) + if(visualSize != mVisualSize) { - AddRasterizationTask( visualSize ); + AddRasterizationTask(visualSize); mVisualSize = visualSize; } } @@ -377,8 +373,8 @@ void SvgVisual::OnSetTransform() bool SvgVisual::IsResourceReady() const { - return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY || - mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED ); + return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY || + mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED); } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/text/text-visual.cpp b/dali-toolkit/internal/visuals/text/text-visual.cpp old mode 100755 new mode 100644 index 56d3a8d..19e08b2 --- a/dali-toolkit/internal/visuals/text/text-visual.cpp +++ b/dali-toolkit/internal/visuals/text/text-visual.cpp @@ -19,42 +19,39 @@ #include // EXTERNAL INCLUDES -#include -#include -#include #include #include #include +#include +#include +#include #include // INTERNAL HEADER -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include #include -#include #include +#include #include -#include -#include -#include -#include -#include -#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { -const Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f ); +const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); /** * Return Property index for the given string key @@ -62,63 +59,63 @@ const Vector4 FULL_TEXTURE_RECT( 0.f, 0.f, 1.f, 1.f ); * return the key as an index */ -Dali::Property::Index StringKeyToIndexKey( const std::string& stringKey ) +Dali::Property::Index StringKeyToIndexKey(const std::string& stringKey) { Dali::Property::Index result = Property::INVALID_KEY; - if( stringKey == VISUAL_TYPE ) + if(stringKey == VISUAL_TYPE) { result = Toolkit::Visual::Property::TYPE; } - else if( stringKey == TEXT_PROPERTY ) + else if(stringKey == TEXT_PROPERTY) { result = Toolkit::TextVisual::Property::TEXT; } - else if( stringKey == FONT_FAMILY_PROPERTY ) + else if(stringKey == FONT_FAMILY_PROPERTY) { result = Toolkit::TextVisual::Property::FONT_FAMILY; } - else if( stringKey == FONT_STYLE_PROPERTY ) + else if(stringKey == FONT_STYLE_PROPERTY) { result = Toolkit::TextVisual::Property::FONT_STYLE; } - else if( stringKey == POINT_SIZE_PROPERTY ) + else if(stringKey == POINT_SIZE_PROPERTY) { result = Toolkit::TextVisual::Property::POINT_SIZE; } - else if( stringKey == MULTI_LINE_PROPERTY ) + else if(stringKey == MULTI_LINE_PROPERTY) { result = Toolkit::TextVisual::Property::MULTI_LINE; } - else if( stringKey == HORIZONTAL_ALIGNMENT_PROPERTY ) + else if(stringKey == HORIZONTAL_ALIGNMENT_PROPERTY) { result = Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT; } - else if( stringKey == VERTICAL_ALIGNMENT_PROPERTY ) + else if(stringKey == VERTICAL_ALIGNMENT_PROPERTY) { result = Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT; } - else if( stringKey == TEXT_COLOR_PROPERTY ) + else if(stringKey == TEXT_COLOR_PROPERTY) { result = Toolkit::TextVisual::Property::TEXT_COLOR; } - else if( stringKey == ENABLE_MARKUP_PROPERTY ) + else if(stringKey == ENABLE_MARKUP_PROPERTY) { result = Toolkit::TextVisual::Property::ENABLE_MARKUP; } - else if( stringKey == SHADOW_PROPERTY ) + else if(stringKey == SHADOW_PROPERTY) { result = Toolkit::TextVisual::Property::SHADOW; } - else if( stringKey == UNDERLINE_PROPERTY ) + else if(stringKey == UNDERLINE_PROPERTY) { result = Toolkit::TextVisual::Property::UNDERLINE; } - else if( stringKey == OUTLINE_PROPERTY ) + else if(stringKey == OUTLINE_PROPERTY) { result = Toolkit::DevelTextVisual::Property::OUTLINE; } - else if( stringKey == BACKGROUND_PROPERTY ) + else if(stringKey == BACKGROUND_PROPERTY) { result = Toolkit::DevelTextVisual::Property::BACKGROUND; } @@ -126,19 +123,19 @@ Dali::Property::Index StringKeyToIndexKey( const std::string& stringKey ) return result; } -void TextColorConstraint( Vector4& current, const PropertyInputContainer& inputs ) +void TextColorConstraint(Vector4& current, const PropertyInputContainer& inputs) { Vector4 color = inputs[0]->GetVector4(); - current.r = color.r * color.a; - current.g = color.g * color.a; - current.b = color.b * color.a; - current.a = color.a; + current.r = color.r * color.a; + current.g = color.g * color.a; + current.b = color.b * color.a; + current.a = color.a; } -void OpacityConstraint( float& current, const PropertyInputContainer& inputs ) +void OpacityConstraint(float& current, const PropertyInputContainer& inputs) { // Make zero if the alpha value of text color is zero to skip rendering text - if( EqualsZero( inputs[0]->GetVector4().a ) ) + if(EqualsZero(inputs[0]->GetVector4().a)) { current = 0.0f; } @@ -150,7 +147,7 @@ void OpacityConstraint( float& current, const PropertyInputContainer& inputs ) } // unnamed namespace -TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +TextVisualPtr TextVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { TextVisualPtr textVisualPtr(new TextVisual(factoryCache)); textVisualPtr->SetProperties(properties); @@ -158,94 +155,93 @@ TextVisualPtr TextVisual::New( VisualFactoryCache& factoryCache, const Property: return textVisualPtr; } -Property::Map TextVisual::ConvertStringKeysToIndexKeys( const Property::Map& propertyMap ) +Property::Map TextVisual::ConvertStringKeysToIndexKeys(const Property::Map& propertyMap) { Property::Map outMap; - for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index ) + for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index) { - const KeyValuePair& keyValue = propertyMap.GetKeyValue( index ); + const KeyValuePair& keyValue = propertyMap.GetKeyValue(index); Property::Index indexKey = keyValue.first.indexKey; - if ( keyValue.first.type == Property::Key::STRING ) + if(keyValue.first.type == Property::Key::STRING) { - indexKey = StringKeyToIndexKey( keyValue.first.stringKey ); + indexKey = StringKeyToIndexKey(keyValue.first.stringKey); } - outMap.Insert( indexKey, keyValue.second ); + outMap.Insert(indexKey, keyValue.second); } return outMap; } -float TextVisual::GetHeightForWidth( float width ) +float TextVisual::GetHeightForWidth(float width) { - return mController->GetHeightForWidth( width ); + return mController->GetHeightForWidth(width); } -void TextVisual::GetNaturalSize( Vector2& naturalSize ) +void TextVisual::GetNaturalSize(Vector2& naturalSize) { naturalSize = mController->GetNaturalSize().GetVectorXY(); } -void TextVisual::DoCreatePropertyMap( Property::Map& map ) const +void TextVisual::DoCreatePropertyMap(Property::Map& map) const { Property::Value value; map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT); std::string text; - mController->GetText( text ); - map.Insert( Toolkit::TextVisual::Property::TEXT, text ); + mController->GetText(text); + map.Insert(Toolkit::TextVisual::Property::TEXT, text); - map.Insert( Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily() ); + map.Insert(Toolkit::TextVisual::Property::FONT_FAMILY, mController->GetDefaultFontFamily()); - GetFontStyleProperty( mController, value, Text::FontStyle::DEFAULT ); - map.Insert( Toolkit::TextVisual::Property::FONT_STYLE, value ); + GetFontStyleProperty(mController, value, Text::FontStyle::DEFAULT); + map.Insert(Toolkit::TextVisual::Property::FONT_STYLE, value); - map.Insert( Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ) ); + map.Insert(Toolkit::TextVisual::Property::POINT_SIZE, mController->GetDefaultFontSize(Text::Controller::POINT_SIZE)); - map.Insert( Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled() ); + map.Insert(Toolkit::TextVisual::Property::MULTI_LINE, mController->IsMultiLineEnabled()); - map.Insert( Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, mController->GetHorizontalAlignment() ); + map.Insert(Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT, mController->GetHorizontalAlignment()); - map.Insert( Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, mController->GetVerticalAlignment() ); + map.Insert(Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT, mController->GetVerticalAlignment()); - map.Insert( Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor() ); + map.Insert(Toolkit::TextVisual::Property::TEXT_COLOR, mController->GetDefaultColor()); - map.Insert( Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled() ); + map.Insert(Toolkit::TextVisual::Property::ENABLE_MARKUP, mController->IsMarkupProcessorEnabled()); - GetShadowProperties( mController, value, Text::EffectStyle::DEFAULT ); - map.Insert( Toolkit::TextVisual::Property::SHADOW, value ); + GetShadowProperties(mController, value, Text::EffectStyle::DEFAULT); + map.Insert(Toolkit::TextVisual::Property::SHADOW, value); - GetUnderlineProperties( mController, value, Text::EffectStyle::DEFAULT ); - map.Insert( Toolkit::TextVisual::Property::UNDERLINE, value ); + GetUnderlineProperties(mController, value, Text::EffectStyle::DEFAULT); + map.Insert(Toolkit::TextVisual::Property::UNDERLINE, value); - GetOutlineProperties( mController, value, Text::EffectStyle::DEFAULT ); - map.Insert( Toolkit::DevelTextVisual::Property::OUTLINE, value ); + GetOutlineProperties(mController, value, Text::EffectStyle::DEFAULT); + map.Insert(Toolkit::DevelTextVisual::Property::OUTLINE, value); - GetBackgroundProperties( mController, value, Text::EffectStyle::DEFAULT ); - map.Insert( Toolkit::DevelTextVisual::Property::BACKGROUND, value ); + GetBackgroundProperties(mController, value, Text::EffectStyle::DEFAULT); + map.Insert(Toolkit::DevelTextVisual::Property::BACKGROUND, value); } -void TextVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void TextVisual::DoCreateInstancePropertyMap(Property::Map& map) const { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::TEXT); std::string text; - mController->GetText( text ); - map.Insert( Toolkit::TextVisual::Property::TEXT, text ); + mController->GetText(text); + map.Insert(Toolkit::TextVisual::Property::TEXT, text); } - -TextVisual::TextVisual( VisualFactoryCache& factoryCache ) -: Visual::Base( factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT ), - mController( Text::Controller::New() ), - mTypesetter( Text::Typesetter::New( mController->GetTextModel() ) ), - mAnimatableTextColorPropertyIndex( Property::INVALID_INDEX ), - mRendererUpdateNeeded( false ) +TextVisual::TextVisual(VisualFactoryCache& factoryCache) +: Visual::Base(factoryCache, Visual::FittingMode::FIT_KEEP_ASPECT_RATIO, Toolkit::Visual::TEXT), + mController(Text::Controller::New()), + mTypesetter(Text::Typesetter::New(mController->GetTextModel())), + mAnimatableTextColorPropertyIndex(Property::INVALID_INDEX), + mRendererUpdateNeeded(false) { } @@ -261,56 +257,56 @@ void TextVisual::OnInitialize() mImpl->mRenderer = Renderer::New(geometry, shader); } -void TextVisual::DoSetProperties( const Property::Map& propertyMap ) +void TextVisual::DoSetProperties(const Property::Map& propertyMap) { - for( Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index ) + for(Property::Map::SizeType index = 0u, count = propertyMap.Count(); index < count; ++index) { - const KeyValuePair& keyValue = propertyMap.GetKeyValue( index ); + const KeyValuePair& keyValue = propertyMap.GetKeyValue(index); Property::Index indexKey = keyValue.first.indexKey; - if( keyValue.first.type == Property::Key::STRING ) + if(keyValue.first.type == Property::Key::STRING) { - indexKey = StringKeyToIndexKey( keyValue.first.stringKey ); + indexKey = StringKeyToIndexKey(keyValue.first.stringKey); } - DoSetProperty( indexKey, keyValue.second ); + DoSetProperty(indexKey, keyValue.second); } // Elide the text if it exceeds the boundaries. - mController->SetTextElideEnabled( true ); + mController->SetTextElideEnabled(true); // Retrieve the layout engine to set the cursor's width. Text::Layout::Engine& engine = mController->GetLayoutEngine(); // Sets 0 as cursor's width. - engine.SetCursorWidth( 0u ); // Do not layout space for the cursor. + engine.SetCursorWidth(0u); // Do not layout space for the cursor. } -void TextVisual::DoSetOnScene( Actor& actor ) +void TextVisual::DoSetOnScene(Actor& actor) { mControl = actor; - mImpl->mRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT ); + mImpl->mRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT); // Enable the pre-multiplied alpha to improve the text quality EnablePreMultipliedAlpha(true); - const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor(); - Dali::Property::Index shaderTextColorIndex = mImpl->mRenderer.RegisterProperty( "uTextColorAnimatable", defaultColor ); + const Vector4& defaultColor = mController->GetTextModel()->GetDefaultColor(); + Dali::Property::Index shaderTextColorIndex = mImpl->mRenderer.RegisterProperty("uTextColorAnimatable", defaultColor); - if ( mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX ) + if(mAnimatableTextColorPropertyIndex != Property::INVALID_INDEX) { // Create constraint for the animatable text's color Property with uTextColorAnimatable in the renderer. - if( shaderTextColorIndex != Property::INVALID_INDEX ) + if(shaderTextColorIndex != Property::INVALID_INDEX) { - Constraint colorConstraint = Constraint::New( mImpl->mRenderer, shaderTextColorIndex, TextColorConstraint ); - colorConstraint.AddSource( Source( actor, mAnimatableTextColorPropertyIndex ) ); + Constraint colorConstraint = Constraint::New(mImpl->mRenderer, shaderTextColorIndex, TextColorConstraint); + colorConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex)); colorConstraint.Apply(); // Make zero if the alpha value of text color is zero to skip rendering text - Constraint opacityConstraint = Constraint::New< float >( mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint ); - opacityConstraint.AddSource( Source( actor, mAnimatableTextColorPropertyIndex ) ); + Constraint opacityConstraint = Constraint::New(mImpl->mRenderer, Dali::DevelRenderer::Property::OPACITY, OpacityConstraint); + opacityConstraint.AddSource(Source(actor, mAnimatableTextColorPropertyIndex)); opacityConstraint.Apply(); } } @@ -318,29 +314,29 @@ void TextVisual::DoSetOnScene( Actor& actor ) // Renderer needs textures and to be added to control mRendererUpdateNeeded = true; - mRendererList.push_back( mImpl->mRenderer ); + mRendererList.push_back(mImpl->mRenderer); UpdateRenderer(); } -void TextVisual::RemoveRenderer( Actor& actor ) +void TextVisual::RemoveRenderer(Actor& actor) { - for( RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter) + for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter) { Renderer renderer = (*iter); - if( renderer ) + if(renderer) { // Removes the renderer from the actor. - actor.RemoveRenderer( renderer ); + actor.RemoveRenderer(renderer); } } // Clear the renderer list mRendererList.clear(); } -void TextVisual::DoSetOffScene( Actor& actor ) +void TextVisual::DoSetOffScene(Actor& actor) { - RemoveRenderer( actor ); + RemoveRenderer(actor); // Resets the control handle. mControl.Reset(); @@ -351,96 +347,96 @@ void TextVisual::OnSetTransform() UpdateRenderer(); } -void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue ) +void TextVisual::DoSetProperty(Dali::Property::Index index, const Dali::Property::Value& propertyValue) { - switch( index ) + switch(index) { case Toolkit::TextVisual::Property::ENABLE_MARKUP: { const bool enableMarkup = propertyValue.Get(); - mController->SetMarkupProcessorEnabled( enableMarkup ); + mController->SetMarkupProcessorEnabled(enableMarkup); break; } case Toolkit::TextVisual::Property::TEXT: { - mController->SetText( propertyValue.Get() ); + mController->SetText(propertyValue.Get()); break; } case Toolkit::TextVisual::Property::FONT_FAMILY: { - SetFontFamilyProperty( mController, propertyValue ); + SetFontFamilyProperty(mController, propertyValue); break; } case Toolkit::TextVisual::Property::FONT_STYLE: { - SetFontStyleProperty( mController, propertyValue, Text::FontStyle::DEFAULT ); + SetFontStyleProperty(mController, propertyValue, Text::FontStyle::DEFAULT); break; } case Toolkit::TextVisual::Property::POINT_SIZE: { const float pointSize = propertyValue.Get(); - if( !Equals( mController->GetDefaultFontSize( Text::Controller::POINT_SIZE ), pointSize ) ) + if(!Equals(mController->GetDefaultFontSize(Text::Controller::POINT_SIZE), pointSize)) { - mController->SetDefaultFontSize( pointSize, Text::Controller::POINT_SIZE ); + mController->SetDefaultFontSize(pointSize, Text::Controller::POINT_SIZE); } break; } case Toolkit::TextVisual::Property::MULTI_LINE: { - mController->SetMultiLineEnabled( propertyValue.Get() ); + mController->SetMultiLineEnabled(propertyValue.Get()); break; } case Toolkit::TextVisual::Property::HORIZONTAL_ALIGNMENT: { - if( mController ) + if(mController) { - Text::HorizontalAlignment::Type alignment( static_cast< Text::HorizontalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( Toolkit::Text::GetHorizontalAlignmentEnumeration( propertyValue, alignment ) ) + Text::HorizontalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(Toolkit::Text::GetHorizontalAlignmentEnumeration(propertyValue, alignment)) { - mController->SetHorizontalAlignment( alignment ); + mController->SetHorizontalAlignment(alignment); } } break; } case Toolkit::TextVisual::Property::VERTICAL_ALIGNMENT: { - if( mController ) + if(mController) { - Toolkit::Text::VerticalAlignment::Type alignment( static_cast< Text::VerticalAlignment::Type >( -1 ) ); // Set to invalid value to ensure a valid mode does get set - if( Toolkit::Text::GetVerticalAlignmentEnumeration( propertyValue, alignment) ) + Toolkit::Text::VerticalAlignment::Type alignment(static_cast(-1)); // Set to invalid value to ensure a valid mode does get set + if(Toolkit::Text::GetVerticalAlignmentEnumeration(propertyValue, alignment)) { - mController->SetVerticalAlignment( alignment ); + mController->SetVerticalAlignment(alignment); } } break; } case Toolkit::TextVisual::Property::TEXT_COLOR: { - const Vector4& textColor = propertyValue.Get< Vector4 >(); - if( mController->GetDefaultColor() != textColor ) + const Vector4& textColor = propertyValue.Get(); + if(mController->GetDefaultColor() != textColor) { - mController->SetDefaultColor( textColor ); + mController->SetDefaultColor(textColor); } break; } case Toolkit::TextVisual::Property::SHADOW: { - SetShadowProperties( mController, propertyValue, Text::EffectStyle::DEFAULT ); + SetShadowProperties(mController, propertyValue, Text::EffectStyle::DEFAULT); break; } case Toolkit::TextVisual::Property::UNDERLINE: { - SetUnderlineProperties( mController, propertyValue, Text::EffectStyle::DEFAULT ); + SetUnderlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT); break; } case Toolkit::DevelTextVisual::Property::OUTLINE: { - SetOutlineProperties( mController, propertyValue, Text::EffectStyle::DEFAULT ); + SetOutlineProperties(mController, propertyValue, Text::EffectStyle::DEFAULT); break; } case Toolkit::DevelTextVisual::Property::BACKGROUND: { - SetBackgroundProperties( mController, propertyValue, Text::EffectStyle::DEFAULT ); + SetBackgroundProperties(mController, propertyValue, Text::EffectStyle::DEFAULT); break; } } @@ -449,7 +445,7 @@ void TextVisual::DoSetProperty( Dali::Property::Index index, const Dali::Propert void TextVisual::UpdateRenderer() { Actor control = mControl.GetHandle(); - if( !control ) + if(!control) { // Nothing to do. return; @@ -458,67 +454,65 @@ void TextVisual::UpdateRenderer() // Calculates the size to be used to relayout. Vector2 relayoutSize; - const bool isWidthRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.z ) < Math::MACHINE_EPSILON_1000; - const bool isHeightRelative = fabsf( mImpl->mTransform.mOffsetSizeMode.w ) < Math::MACHINE_EPSILON_1000; + const bool isWidthRelative = fabsf(mImpl->mTransform.mOffsetSizeMode.z) < Math::MACHINE_EPSILON_1000; + const bool isHeightRelative = fabsf(mImpl->mTransform.mOffsetSizeMode.w) < Math::MACHINE_EPSILON_1000; // Round the size and offset to avoid pixel alignement issues. - relayoutSize.width = floorf( 0.5f + ( isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width ) ); - relayoutSize.height = floorf( 0.5f + ( isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height ) ); + relayoutSize.width = floorf(0.5f + (isWidthRelative ? mImpl->mControlSize.width * mImpl->mTransform.mSize.x : mImpl->mTransform.mSize.width)); + relayoutSize.height = floorf(0.5f + (isHeightRelative ? mImpl->mControlSize.height * mImpl->mTransform.mSize.y : mImpl->mTransform.mSize.height)); std::string text; - mController->GetText( text ); + mController->GetText(text); - if( ( fabsf( relayoutSize.width ) < Math::MACHINE_EPSILON_1000 ) || ( fabsf( relayoutSize.height ) < Math::MACHINE_EPSILON_1000 ) || text.empty() ) + if((fabsf(relayoutSize.width) < Math::MACHINE_EPSILON_1000) || (fabsf(relayoutSize.height) < Math::MACHINE_EPSILON_1000) || text.empty()) { // Remove the texture set and any renderer previously set. - RemoveRenderer( control ); + RemoveRenderer(control); // Nothing else to do if the relayout size is zero. - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); return; } - Dali::LayoutDirection::Type layoutDirection; - if( mController->IsMatchSystemLanguageDirection() ) + if(mController->IsMatchSystemLanguageDirection()) { - layoutDirection = static_cast( DevelWindow::Get( control ).GetRootLayer().GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(DevelWindow::Get(control).GetRootLayer().GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } else { - layoutDirection = static_cast( control.GetProperty( Dali::Actor::Property::LAYOUT_DIRECTION ).Get() ); + layoutDirection = static_cast(control.GetProperty(Dali::Actor::Property::LAYOUT_DIRECTION).Get()); } - const Text::Controller::UpdateTextType updateTextType = mController->Relayout( relayoutSize, layoutDirection ); + const Text::Controller::UpdateTextType updateTextType = mController->Relayout(relayoutSize, layoutDirection); - if( Text::Controller::NONE_UPDATED != ( Text::Controller::MODEL_UPDATED & updateTextType ) - || mRendererUpdateNeeded ) + if(Text::Controller::NONE_UPDATED != (Text::Controller::MODEL_UPDATED & updateTextType) || mRendererUpdateNeeded) { mRendererUpdateNeeded = false; // Remove the texture set and any renderer previously set. - RemoveRenderer( control ); + RemoveRenderer(control); - if( ( relayoutSize.width > Math::MACHINE_EPSILON_1000 ) && - ( relayoutSize.height > Math::MACHINE_EPSILON_1000 ) ) + if((relayoutSize.width > Math::MACHINE_EPSILON_1000) && + (relayoutSize.height > Math::MACHINE_EPSILON_1000)) { // Check whether it is a markup text with multiple text colors - const Vector4* const colorsBuffer = mController->GetTextModel()->GetColors(); - bool hasMultipleTextColors = ( NULL != colorsBuffer ); + const Vector4* const colorsBuffer = mController->GetTextModel()->GetColors(); + bool hasMultipleTextColors = (NULL != colorsBuffer); // Check whether the text contains any color glyph bool containsColorGlyph = false; - TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); - const Text::GlyphInfo* const glyphsBuffer = mController->GetTextModel()->GetGlyphs(); - const Text::Length numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs(); - for ( Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++ ) + TextAbstraction::FontClient fontClient = TextAbstraction::FontClient::Get(); + const Text::GlyphInfo* const glyphsBuffer = mController->GetTextModel()->GetGlyphs(); + const Text::Length numberOfGlyphs = mController->GetTextModel()->GetNumberOfGlyphs(); + for(Text::Length glyphIndex = 0; glyphIndex < numberOfGlyphs; glyphIndex++) { // Retrieve the glyph's info. const Text::GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex; // Whether the current glyph is a color one. - if( fontClient.IsColorGlyph( glyphInfo->fontId, glyphInfo->index ) ) + if(fontClient.IsColorGlyph(glyphInfo->fontId, glyphInfo->index)) { containsColorGlyph = true; break; @@ -527,194 +521,192 @@ void TextVisual::UpdateRenderer() // Check whether the text contains any style colors (e.g. underline color, shadow color, etc.) - bool shadowEnabled = false; - const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset(); - if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 ) + bool shadowEnabled = false; + const Vector2& shadowOffset = mController->GetTextModel()->GetShadowOffset(); + if(fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1) { shadowEnabled = true; } - const bool underlineEnabled = mController->GetTextModel()->IsUnderlineEnabled(); - const bool outlineEnabled = ( mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1 ); - const bool backgroundEnabled = mController->GetTextModel()->IsBackgroundEnabled();; - - const bool styleEnabled = ( shadowEnabled || underlineEnabled || outlineEnabled || backgroundEnabled ); + const bool underlineEnabled = mController->GetTextModel()->IsUnderlineEnabled(); + const bool outlineEnabled = (mController->GetTextModel()->GetOutlineWidth() > Math::MACHINE_EPSILON_1); + const bool backgroundEnabled = mController->GetTextModel()->IsBackgroundEnabled(); + ; + const bool styleEnabled = (shadowEnabled || underlineEnabled || outlineEnabled || backgroundEnabled); - AddRenderer( control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled ); + AddRenderer(control, relayoutSize, hasMultipleTextColors, containsColorGlyph, styleEnabled); // Text rendered and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } } } -void TextVisual::AddTexture( TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex ) +void TextVisual::AddTexture(TextureSet& textureSet, PixelData& data, Sampler& sampler, unsigned int textureSetIndex) { - Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, - data.GetPixelFormat(), - data.GetWidth(), - data.GetHeight() ); - texture.Upload( data ); - - textureSet.SetTexture( textureSetIndex, texture ); - textureSet.SetSampler( textureSetIndex, sampler ); + Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, + data.GetPixelFormat(), + data.GetWidth(), + data.GetHeight()); + texture.Upload(data); + + textureSet.SetTexture(textureSetIndex, texture); + textureSet.SetSampler(textureSetIndex, sampler); } -PixelData TextVisual::ConvertToPixelData( unsigned char* buffer, int width, int height, int offsetPosition, const Pixel::Format textPixelFormat ) +PixelData TextVisual::ConvertToPixelData(unsigned char* buffer, int width, int height, int offsetPosition, const Pixel::Format textPixelFormat) { - int bpp = Pixel::GetBytesPerPixel( textPixelFormat ); - unsigned int bufferSize = width * height * bpp; - unsigned char* dstBuffer = static_cast( malloc ( bufferSize ) ); - memcpy( dstBuffer, buffer + offsetPosition * bpp, bufferSize ); - PixelData pixelData = Dali::PixelData::New( dstBuffer, - bufferSize, - width, - height, - textPixelFormat, - Dali::PixelData::FREE ); + int bpp = Pixel::GetBytesPerPixel(textPixelFormat); + unsigned int bufferSize = width * height * bpp; + unsigned char* dstBuffer = static_cast(malloc(bufferSize)); + memcpy(dstBuffer, buffer + offsetPosition * bpp, bufferSize); + PixelData pixelData = Dali::PixelData::New(dstBuffer, + bufferSize, + width, + height, + textPixelFormat, + Dali::PixelData::FREE); return pixelData; } -void TextVisual::CreateTextureSet( TilingInfo& info, Renderer& renderer, Sampler& sampler, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled ) +void TextVisual::CreateTextureSet(TilingInfo& info, Renderer& renderer, Sampler& sampler, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled) { - - TextureSet textureSet = TextureSet::New(); + TextureSet textureSet = TextureSet::New(); unsigned int textureSetIndex = 0u; // Convert the buffer to pixel data to make it a texture. - if( info.textBuffer ) + if(info.textBuffer) { - PixelData data = ConvertToPixelData( info.textBuffer, info.width, info.height, info.offsetPosition, info.textPixelFormat ); - AddTexture( textureSet, data, sampler, textureSetIndex ); + PixelData data = ConvertToPixelData(info.textBuffer, info.width, info.height, info.offsetPosition, info.textPixelFormat); + AddTexture(textureSet, data, sampler, textureSetIndex); ++textureSetIndex; } - if( styleEnabled && info.styleBuffer ) + if(styleEnabled && info.styleBuffer) { - PixelData styleData = ConvertToPixelData( info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888 ); - AddTexture( textureSet, styleData, sampler, textureSetIndex ); + PixelData styleData = ConvertToPixelData(info.styleBuffer, info.width, info.height, info.offsetPosition, Pixel::RGBA8888); + AddTexture(textureSet, styleData, sampler, textureSetIndex); ++textureSetIndex; } - if( containsColorGlyph && !hasMultipleTextColors && info.maskBuffer ) + if(containsColorGlyph && !hasMultipleTextColors && info.maskBuffer) { - PixelData maskData = ConvertToPixelData( info.maskBuffer, info.width, info.height, info.offsetPosition, Pixel::L8 ); - AddTexture( textureSet, maskData, sampler, textureSetIndex ); + PixelData maskData = ConvertToPixelData(info.maskBuffer, info.width, info.height, info.offsetPosition, Pixel::L8); + AddTexture(textureSet, maskData, sampler, textureSetIndex); } - renderer.SetTextures( textureSet ); + renderer.SetTextures(textureSet); //Register transform properties - mImpl->mTransform.RegisterUniforms( renderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(renderer, Direction::LEFT_TO_RIGHT); // Enable the pre-multiplied alpha to improve the text quality - renderer.SetProperty( Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true ); - renderer.RegisterProperty( PREMULTIPLIED_ALPHA, 1.0f ); + renderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, true); + renderer.RegisterProperty(PREMULTIPLIED_ALPHA, 1.0f); // Set size and offset for the tiling. - renderer.RegisterProperty( SIZE, Vector2( info.width, info.height ) ); - renderer.RegisterProperty( OFFSET, Vector2( info.offSet.x, info.offSet.y ) ); - renderer.RegisterProperty( "uHasMultipleTextColors", static_cast( hasMultipleTextColors ) ); - renderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON); + renderer.RegisterProperty(SIZE, Vector2(info.width, info.height)); + renderer.RegisterProperty(OFFSET, Vector2(info.offSet.x, info.offSet.y)); + renderer.RegisterProperty("uHasMultipleTextColors", static_cast(hasMultipleTextColors)); + renderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); - mRendererList.push_back( renderer ); + mRendererList.push_back(renderer); } - -void TextVisual::AddRenderer( Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled ) +void TextVisual::AddRenderer(Actor& actor, const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled) { - Shader shader = GetTextShader( mFactoryCache, hasMultipleTextColors, containsColorGlyph, styleEnabled ); - mImpl->mRenderer.SetShader( shader ); + Shader shader = GetTextShader(mFactoryCache, hasMultipleTextColors, containsColorGlyph, styleEnabled); + mImpl->mRenderer.SetShader(shader); // Get the maximum size. const int maxTextureSize = Dali::GetMaxTextureSize(); // No tiling required. Use the default renderer. - if( size.height < maxTextureSize ) + if(size.height < maxTextureSize) { - TextureSet textureSet = GetTextTexture( size, hasMultipleTextColors, containsColorGlyph, styleEnabled ); + TextureSet textureSet = GetTextTexture(size, hasMultipleTextColors, containsColorGlyph, styleEnabled); - mImpl->mRenderer.SetTextures( textureSet ); + mImpl->mRenderer.SetTextures(textureSet); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); - mImpl->mRenderer.RegisterProperty( "uHasMultipleTextColors", static_cast( hasMultipleTextColors ) ); - mImpl->mRenderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); + mImpl->mRenderer.RegisterProperty("uHasMultipleTextColors", static_cast(hasMultipleTextColors)); + mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); - mRendererList.push_back( mImpl->mRenderer ); + mRendererList.push_back(mImpl->mRenderer); } // If the pixel data exceeds the maximum size, tiling is required. else { // Filter mode needs to be set to linear to produce better quality while scaling. Sampler sampler = Sampler::New(); - sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR ); + sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR); // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture - Pixel::Format textPixelFormat = ( containsColorGlyph || hasMultipleTextColors ) ? Pixel::RGBA8888 : Pixel::L8; + Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8; // Check the text direction Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection(); // Create a texture for the text without any styles - PixelData data = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat ); + PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat); - int verifiedWidth = data.GetWidth(); + int verifiedWidth = data.GetWidth(); int verifiedHeight = data.GetHeight(); // Set information for creating textures. - TilingInfo info( verifiedWidth, maxTextureSize, textPixelFormat ); + TilingInfo info(verifiedWidth, maxTextureSize, textPixelFormat); // Get the buffer of text. - Dali::DevelPixelData::PixelDataBuffer textPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( data ); - info.textBuffer = textPixelData.buffer; + Dali::DevelPixelData::PixelDataBuffer textPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(data); + info.textBuffer = textPixelData.buffer; - if( styleEnabled ) + if(styleEnabled) { // Create RGBA texture for all the text styles (without the text itself) - PixelData styleData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888 ); - Dali::DevelPixelData::PixelDataBuffer stylePixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( styleData ); - info.styleBuffer = stylePixelData.buffer; + PixelData styleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888); + Dali::DevelPixelData::PixelDataBuffer stylePixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(styleData); + info.styleBuffer = stylePixelData.buffer; } - if ( containsColorGlyph && !hasMultipleTextColors ) + if(containsColorGlyph && !hasMultipleTextColors) { // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation - PixelData maskData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8 ); - Dali::DevelPixelData::PixelDataBuffer maskPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer( maskData ); - info.maskBuffer = maskPixelData.buffer; + PixelData maskData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8); + Dali::DevelPixelData::PixelDataBuffer maskPixelData = Dali::DevelPixelData::ReleasePixelDataBuffer(maskData); + info.maskBuffer = maskPixelData.buffer; } // Get the current offset for recalculate the offset when tiling. Property::Map retMap; - mImpl->mTransform.GetPropertyMap( retMap ); - Property::Value* offsetValue = retMap.Find( Dali::Toolkit::Visual::Transform::Property::OFFSET ); - if( offsetValue ) + mImpl->mTransform.GetPropertyMap(retMap); + Property::Value* offsetValue = retMap.Find(Dali::Toolkit::Visual::Transform::Property::OFFSET); + if(offsetValue) { - offsetValue->Get( info.offSet ); + offsetValue->Get(info.offSet); } // Create a textureset in the default renderer. - CreateTextureSet( info, mImpl->mRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled ); + CreateTextureSet(info, mImpl->mRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled); verifiedHeight -= maxTextureSize; - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY ); + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY); int offsetPosition = verifiedWidth * maxTextureSize; // Create a renderer by cutting maxTextureSize. - while( verifiedHeight > 0 ) + while(verifiedHeight > 0) { - Renderer tilingRenderer = Renderer::New( geometry, shader ); - tilingRenderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT ); + Renderer tilingRenderer = Renderer::New(geometry, shader); + tilingRenderer.SetProperty(Dali::Renderer::Property::DEPTH_INDEX, Toolkit::DepthIndex::CONTENT); // New offset position of buffer for tiling. info.offsetPosition += offsetPosition; // New height for tiling. - info.height = ( verifiedHeight - maxTextureSize ) > 0 ? maxTextureSize : verifiedHeight; + info.height = (verifiedHeight - maxTextureSize) > 0 ? maxTextureSize : verifiedHeight; // New offset for tiling. info.offSet.y += maxTextureSize; // Create a textureset int the new tiling renderer. - CreateTextureSet( info, tilingRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled ); + CreateTextureSet(info, tilingRenderer, sampler, hasMultipleTextColors, containsColorGlyph, styleEnabled); verifiedHeight -= maxTextureSize; } @@ -722,125 +714,124 @@ void TextVisual::AddRenderer( Actor& actor, const Vector2& size, bool hasMultipl mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED; - for( RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter) + for(RendererContainer::iterator iter = mRendererList.begin(); iter != mRendererList.end(); ++iter) { Renderer renderer = (*iter); - if( renderer ) + if(renderer) { - actor.AddRenderer( renderer ); + actor.AddRenderer(renderer); } } } - -TextureSet TextVisual::GetTextTexture( const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled ) +TextureSet TextVisual::GetTextTexture(const Vector2& size, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled) { // Filter mode needs to be set to linear to produce better quality while scaling. Sampler sampler = Sampler::New(); - sampler.SetFilterMode( FilterMode::LINEAR, FilterMode::LINEAR ); + sampler.SetFilterMode(FilterMode::LINEAR, FilterMode::LINEAR); TextureSet textureSet = TextureSet::New(); // Create RGBA texture if the text contains emojis or multiple text colors, otherwise L8 texture - Pixel::Format textPixelFormat = ( containsColorGlyph || hasMultipleTextColors ) ? Pixel::RGBA8888 : Pixel::L8; + Pixel::Format textPixelFormat = (containsColorGlyph || hasMultipleTextColors) ? Pixel::RGBA8888 : Pixel::L8; // Check the text direction Toolkit::DevelText::TextDirection::Type textDirection = mController->GetTextDirection(); // Create a texture for the text without any styles - PixelData data = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat ); + PixelData data = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_STYLES, false, textPixelFormat); // It may happen the image atlas can't handle a pixel data it exceeds the maximum size. // In that case, create a texture. TODO: should tile the text. unsigned int textureSetIndex = 0u; - AddTexture( textureSet, data, sampler, textureSetIndex ); + AddTexture(textureSet, data, sampler, textureSetIndex); ++textureSetIndex; - if ( styleEnabled ) + if(styleEnabled) { // Create RGBA texture for all the text styles (without the text itself) - PixelData styleData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888 ); + PixelData styleData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_NO_TEXT, false, Pixel::RGBA8888); - AddTexture( textureSet, styleData, sampler, textureSetIndex ); + AddTexture(textureSet, styleData, sampler, textureSetIndex); ++textureSetIndex; } - if ( containsColorGlyph && !hasMultipleTextColors ) + if(containsColorGlyph && !hasMultipleTextColors) { // Create a L8 texture as a mask to avoid color glyphs (e.g. emojis) to be affected by text color animation - PixelData maskData = mTypesetter->Render( size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8 ); + PixelData maskData = mTypesetter->Render(size, textDirection, Text::Typesetter::RENDER_MASK, false, Pixel::L8); - AddTexture( textureSet, maskData, sampler, textureSetIndex ); + AddTexture(textureSet, maskData, sampler, textureSetIndex); } return textureSet; } -Shader TextVisual::GetTextShader( VisualFactoryCache& factoryCache, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled ) +Shader TextVisual::GetTextShader(VisualFactoryCache& factoryCache, bool hasMultipleTextColors, bool containsColorGlyph, bool styleEnabled) { Shader shader; - if( hasMultipleTextColors && !styleEnabled ) + if(hasMultipleTextColors && !styleEnabled) { // We don't animate text color if the text contains multiple colors - shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT); + if(!shader) { - shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_SHADER_FRAG ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT, shader ); + shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_SHADER_FRAG); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT, shader); } } - else if( hasMultipleTextColors && styleEnabled ) + else if(hasMultipleTextColors && styleEnabled) { // We don't animate text color if the text contains multiple colors - shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE); + if(!shader) { - shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_WITH_STYLE_SHADER_FRAG ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE, shader ); + shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_MULTI_COLOR_TEXT_WITH_STYLE_SHADER_FRAG); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_MULTI_COLOR_TEXT_WITH_STYLE, shader); } } - else if( !hasMultipleTextColors && !containsColorGlyph && !styleEnabled ) + else if(!hasMultipleTextColors && !containsColorGlyph && !styleEnabled) { - shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT); + if(!shader) { - shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_SHADER_FRAG ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT, shader ); + shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_SHADER_FRAG); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT, shader); } } - else if( !hasMultipleTextColors && !containsColorGlyph && styleEnabled ) + else if(!hasMultipleTextColors && !containsColorGlyph && styleEnabled) { - shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE); + if(!shader) { - shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_SHADER_FRAG ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE, shader ); + shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_SHADER_FRAG); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE, shader); } } - else if( !hasMultipleTextColors && containsColorGlyph && !styleEnabled ) + else if(!hasMultipleTextColors && containsColorGlyph && !styleEnabled) { - shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI); + if(!shader) { - shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_EMOJI_SHADER_FRAG ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI, shader ); + shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_EMOJI_SHADER_FRAG); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_EMOJI, shader); } } else // if( !hasMultipleTextColors && containsColorGlyph && styleEnabled ) { - shader = factoryCache.GetShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI ); - if( !shader ) + shader = factoryCache.GetShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI); + if(!shader) { - shader = Shader::New( SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI_SHADER_FRAG ); - shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT ); - factoryCache.SaveShader( VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI, shader ); + shader = Shader::New(SHADER_TEXT_VISUAL_SHADER_VERT, SHADER_TEXT_VISUAL_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI_SHADER_FRAG); + shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT); + factoryCache.SaveShader(VisualFactoryCache::TEXT_SHADER_SINGLE_COLOR_TEXT_WITH_STYLE_AND_EMOJI, shader); } } diff --git a/dali-toolkit/internal/visuals/texture-manager-impl.cpp b/dali-toolkit/internal/visuals/texture-manager-impl.cpp index 1db057b..0d34d55 100644 --- a/dali-toolkit/internal/visuals/texture-manager-impl.cpp +++ b/dali-toolkit/internal/visuals/texture-manager-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,40 +19,39 @@ #include // EXTERNAL HEADERS -#include -#include -#include #include #include -#include #include +#include #include +#include #include +#include +#include // INTERNAL HEADERS #include -#include #include #include +#include namespace { - -constexpr auto INITIAL_CACHE_NUMBER = size_t{0u}; -constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u}; +constexpr auto INITIAL_CACHE_NUMBER = size_t{0u}; +constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u}; constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u}; -constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS"; +constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS"; constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS"; size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue) { using Dali::EnvironmentVariable::GetEnvironmentVariable; - auto numberString = GetEnvironmentVariable(environmentVariable); - auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0; + auto numberString = GetEnvironmentVariable(environmentVariable); + auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0; constexpr auto MAX_NUMBER_OF_THREADS = 100u; - DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS ); - return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue; + DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS); + return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue; } size_t GetNumberOfLocalLoaderThreads() @@ -69,43 +68,38 @@ size_t GetNumberOfRemoteLoaderThreads() namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - #ifdef DEBUG_ENABLED -Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" ); - -#define GET_LOAD_STATE_STRING( loadState ) \ - loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : \ - loadState == TextureManager::LoadState::LOADING ? "LOADING" : \ - loadState == TextureManager::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" : \ - loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \ - loadState == TextureManager::LoadState::MASK_APPLYING ? "MASK_APPLYING" : \ - loadState == TextureManager::LoadState::MASK_APPLIED ? "MASK_APPLIED" : \ - loadState == TextureManager::LoadState::UPLOADED ? "UPLOADED" : \ - loadState == TextureManager::LoadState::CANCELLED ? "CANCELLED" : \ - loadState == TextureManager::LoadState::LOAD_FAILED ? "LOAD_FAILED" : "Unknown" +Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER"); + +#define GET_LOAD_STATE_STRING(loadState) \ + loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : loadState == TextureManager::LoadState::LOADING ? "LOADING" \ + : loadState == TextureManager::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" \ + : loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" \ + : loadState == TextureManager::LoadState::MASK_APPLYING ? "MASK_APPLYING" \ + : loadState == TextureManager::LoadState::MASK_APPLIED ? "MASK_APPLIED" \ + : loadState == TextureManager::LoadState::UPLOADED ? "UPLOADED" \ + : loadState == TextureManager::LoadState::CANCELLED ? "CANCELLED" \ + : loadState == TextureManager::LoadState::LOAD_FAILED ? "LOAD_FAILED" \ + : "Unknown" #endif -const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128 -const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture -const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct -const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index +const uint32_t DEFAULT_ATLAS_SIZE(1024u); ///< This size can fit 8 by 8 images of average size 128 * 128 +const Vector4 FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture +const int INVALID_INDEX(-1); ///< Invalid index used to represent a non-existant TextureInfo struct +const int INVALID_CACHE_INDEX(-1); ///< Invalid Cache index - -void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad ) +void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad) { - if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) ) + if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat())) { - if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD ) + if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD) { pixelBuffer.MultiplyColorByAlpha(); } @@ -120,19 +114,19 @@ void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad TextureManager::MaskingData::MaskingData() : mAlphaMaskUrl(), - mAlphaMaskId( INVALID_TEXTURE_ID ), - mContentScaleFactor( 1.0f ), - mCropToMask( true ) + mAlphaMaskId(INVALID_TEXTURE_ID), + mContentScaleFactor(1.0f), + mCropToMask(true) { } TextureManager::TextureManager() -: mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ), - mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ), +: mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); }), + mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); }), mExternalTextures(), mLifecycleObservers(), mLoadQueue(), - mCurrentTextureId( 0 ), + mCurrentTextureId(0), mQueueLoadFlag(false) { // Initialize the AddOn @@ -141,163 +135,147 @@ TextureManager::TextureManager() TextureManager::~TextureManager() { - for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter) + for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter) { (*iter)->TextureManagerDestroyed(); } } TextureSet TextureManager::LoadAnimatedImageTexture( - Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode, - bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver ) + Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver) { TextureSet textureSet; - if( synchronousLoading ) + if(synchronousLoading) { Devel::PixelBuffer pixelBuffer; - if( animatedImageLoading ) + if(animatedImageLoading) { - pixelBuffer = animatedImageLoading.LoadFrame( frameIndex ); + pixelBuffer = animatedImageLoading.LoadFrame(frameIndex); } - if( !pixelBuffer ) + if(!pixelBuffer) { DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n"); } else { PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer - if( !textureSet ) + if(!textureSet) { - Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), - pixelData.GetWidth(), pixelData.GetHeight() ); - texture.Upload( pixelData ); + Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight()); + texture.Upload(pixelData); textureSet = TextureSet::New(); - textureSet.SetTexture( 0u, texture ); + textureSet.SetTexture(0u, texture); } } } else { - auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; - textureId = RequestLoadInternal( animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, - SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, - true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex ); - TextureManager::LoadState loadState = GetTextureStateInternal( textureId ); - if( loadState == TextureManager::LoadState::UPLOADED ) + auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; + textureId = RequestLoadInternal(animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex); + TextureManager::LoadState loadState = GetTextureStateInternal(textureId); + if(loadState == TextureManager::LoadState::UPLOADED) { // UploadComplete has already been called - keep the same texture set - textureSet = GetTextureSet( textureId ); + textureSet = GetTextureSet(textureId); } } - if( textureSet ) + if(textureSet) { Sampler sampler = Sampler::New(); - sampler.SetWrapMode( wrapModeU, wrapModeV ); - textureSet.SetSampler( 0u, sampler ); + sampler.SetWrapMode(wrapModeU, wrapModeV); + textureSet.SetSampler(0u, sampler); } return textureSet; } Devel::PixelBuffer TextureManager::LoadPixelBuffer( - const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad ) + const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad) { Devel::PixelBuffer pixelBuffer; - if( synchronousLoading ) + if(synchronousLoading) { - if( url.IsValid() ) + if(url.IsValid()) { - pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode, - orientationCorrection ); - if( pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD ) + pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection); + if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD) { - PreMultiply( pixelBuffer, preMultiplyOnLoad ); + PreMultiply(pixelBuffer, preMultiplyOnLoad); } } } else { - RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, - false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, - preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u ); + RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u); } return pixelBuffer; } TextureSet TextureManager::LoadTexture( - const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, - Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo, - bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect, - Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus, - Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver, - AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection, - TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad ) + const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo, bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect, Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver, AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad) { TextureSet textureSet; loadingStatus = false; - textureRect = FULL_ATLAS_RECT; + textureRect = FULL_ATLAS_RECT; - if( VisualUrl::TEXTURE == url.GetProtocolType()) + if(VisualUrl::TEXTURE == url.GetProtocolType()) { std::string location = url.GetLocation(); - if( location.size() > 0u ) + if(location.size() > 0u) { - TextureId id = std::stoi( location ); - for( auto&& elem : mExternalTextures ) + TextureId id = std::stoi(location); + for(auto&& elem : mExternalTextures) { - if( elem.textureId == id ) + if(elem.textureId == id) { preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; - textureId = elem.textureId; + textureId = elem.textureId; return elem.textureSet; } } } } - else if( synchronousLoading ) + else if(synchronousLoading) { PixelData data; - if( url.IsValid() ) + if(url.IsValid()) { - Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode, - orientationCorrection ); - if( maskInfo && maskInfo->mAlphaMaskUrl.IsValid() ) + Devel::PixelBuffer pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection); + if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid()) { - Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile( maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), - FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true ); - if( maskPixelBuffer ) + Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true); + if(maskPixelBuffer) { - pixelBuffer.ApplyMask( maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask ); + pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask); } } - if( pixelBuffer ) + if(pixelBuffer) { - PreMultiply( pixelBuffer, preMultiplyOnLoad ); + PreMultiply(pixelBuffer, preMultiplyOnLoad); data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer } } - if( !data ) + if(!data) { DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous loading is failed\n"); } else { - if( atlasingStatus ) // attempt atlasing + if(atlasingStatus) // attempt atlasing { - textureSet = imageAtlasManager->Add( textureRect, data ); + textureSet = imageAtlasManager->Add(textureRect, data); } - if( !textureSet ) // big image, no atlasing or atlasing failed + if(!textureSet) // big image, no atlasing or atlasing failed { - atlasingStatus = false; - Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), - data.GetWidth(), data.GetHeight() ); - texture.Upload( data ); + atlasingStatus = false; + Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), data.GetWidth(), data.GetHeight()); + texture.Upload(data); textureSet = TextureSet::New(); - textureSet.SetTexture( 0u, texture ); + textureSet.SetTexture(0u, texture); } else { @@ -309,49 +287,49 @@ TextureSet TextureManager::LoadTexture( else { loadingStatus = true; - if( atlasingStatus ) + if(atlasingStatus) { - textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver); + textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver); } - if( !textureSet ) // big image, no atlasing or atlasing failed + if(!textureSet) // big image, no atlasing or atlasing failed { atlasingStatus = false; - if( !maskInfo || !maskInfo->mAlphaMaskUrl.IsValid() ) + if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid()) { - textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, - textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad ); + textureId = RequestLoad(url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad); } else { - maskInfo->mAlphaMaskId = RequestMaskLoad( maskInfo->mAlphaMaskUrl ); - textureId = RequestLoad( url, - maskInfo->mAlphaMaskId, - maskInfo->mContentScaleFactor, - desiredSize, - fittingMode, samplingMode, - TextureManager::NO_ATLAS, - maskInfo->mCropToMask, - textureObserver, - orientationCorrection, - reloadPolicy, preMultiplyOnLoad ); + maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl); + textureId = RequestLoad(url, + maskInfo->mAlphaMaskId, + maskInfo->mContentScaleFactor, + desiredSize, + fittingMode, + samplingMode, + TextureManager::NO_ATLAS, + maskInfo->mCropToMask, + textureObserver, + orientationCorrection, + reloadPolicy, + preMultiplyOnLoad); } - TextureManager::LoadState loadState = GetTextureStateInternal( textureId ); - if( loadState == TextureManager::LoadState::UPLOADED ) + TextureManager::LoadState loadState = GetTextureStateInternal(textureId); + if(loadState == TextureManager::LoadState::UPLOADED) { // UploadComplete has already been called - keep the same texture set - textureSet = GetTextureSet( textureId ); + textureSet = GetTextureSet(textureId); } // If we are loading the texture, or waiting for the ready signal handler to complete, inform // caller that they need to wait. - loadingStatus = ( loadState == TextureManager::LoadState::LOADING || - loadState == TextureManager::LoadState::WAITING_FOR_MASK || - loadState == TextureManager::LoadState::MASK_APPLYING || - loadState == TextureManager::LoadState::MASK_APPLIED || - loadState == TextureManager::LoadState::NOT_STARTED || - mQueueLoadFlag ); - + loadingStatus = (loadState == TextureManager::LoadState::LOADING || + loadState == TextureManager::LoadState::WAITING_FOR_MASK || + loadState == TextureManager::LoadState::MASK_APPLYING || + loadState == TextureManager::LoadState::MASK_APPLIED || + loadState == TextureManager::LoadState::NOT_STARTED || + mQueueLoadFlag); } else { @@ -359,11 +337,11 @@ TextureSet TextureManager::LoadTexture( } } - if( ! atlasingStatus && textureSet ) + if(!atlasingStatus && textureSet) { Sampler sampler = Sampler::New(); - sampler.SetWrapMode( wrapModeU, wrapModeV ); - textureSet.SetSampler( 0u, sampler ); + sampler.SetWrapMode(wrapModeU, wrapModeV); + textureSet.SetSampler(0u, sampler); } return textureSet; @@ -378,11 +356,9 @@ TextureManager::TextureId TextureManager::RequestLoad( TextureUploadObserver* observer, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, - TextureManager::MultiplyOnLoad& preMultiplyOnLoad ) + TextureManager::MultiplyOnLoad& preMultiplyOnLoad) { - return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, - false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, - preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u ); + return RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u); } TextureManager::TextureId TextureManager::RequestLoad( @@ -397,20 +373,16 @@ TextureManager::TextureId TextureManager::RequestLoad( TextureUploadObserver* observer, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, - TextureManager::MultiplyOnLoad& preMultiplyOnLoad ) + TextureManager::MultiplyOnLoad& preMultiplyOnLoad) { - return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, - cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, - preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u ); + return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u); } -TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl ) +TextureManager::TextureId TextureManager::RequestMaskLoad(const VisualUrl& maskUrl) { // Use the normal load procedure to get the alpha mask. auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; - return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, - SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, - TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u ); + return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u); } TextureManager::TextureId TextureManager::RequestLoadInternal( @@ -428,13 +400,13 @@ TextureManager::TextureId TextureManager::RequestLoadInternal( TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad, Dali::AnimatedImageLoading animatedImageLoading, - uint32_t frameIndex ) + uint32_t frameIndex) { // First check if the requested Texture is cached. - bool isAnimatedImage = ( animatedImageLoading ) ? true : false; + bool isAnimatedImage = (animatedImageLoading) ? true : false; TextureHash textureHash = INITIAL_CACHE_NUMBER; - int cacheIndex = INVALID_CACHE_INDEX; + int cacheIndex = INVALID_CACHE_INDEX; if(storageType != StorageType::RETURN_PIXEL_BUFFER && !isAnimatedImage) { textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId); @@ -445,71 +417,64 @@ TextureManager::TextureId TextureManager::RequestLoadInternal( TextureManager::TextureId textureId = INVALID_TEXTURE_ID; // Check if the requested Texture exists in the cache. - if( cacheIndex != INVALID_CACHE_INDEX ) + if(cacheIndex != INVALID_CACHE_INDEX) { - if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy ) + if(TextureManager::ReloadPolicy::CACHED == reloadPolicy) { // Mark this texture being used by another client resource. Forced reload would replace the current texture // without the need for incrementing the reference count. - ++( mTextureInfoContainer[ cacheIndex ].referenceCount ); + ++(mTextureInfoContainer[cacheIndex].referenceCount); } - textureId = mTextureInfoContainer[ cacheIndex ].textureId; + textureId = mTextureInfoContainer[cacheIndex].textureId; // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info. - preMultiplyOnLoad = mTextureInfoContainer[ cacheIndex ].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; + preMultiplyOnLoad = mTextureInfoContainer[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY; - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n", - url.GetUrl().c_str(), observer, cacheIndex, textureId ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId); } - if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required + if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required { // We need a new Texture. - textureId = GenerateUniqueTextureId(); - bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD ); - mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(), - desiredSize, contentScale, fittingMode, samplingMode, - false, cropToMask, useAtlas, textureHash, orientationCorrection, - preMultiply, animatedImageLoading, frameIndex ) ); + textureId = GenerateUniqueTextureId(); + bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD); + mTextureInfoContainer.push_back(TextureInfo(textureId, maskTextureId, url.GetUrl(), desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex)); cacheIndex = mTextureInfoContainer.size() - 1u; - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n", - url.GetUrl().c_str(), observer, cacheIndex, textureId ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId); } // The below code path is common whether we are using the cache or not. // The textureInfoIndex now refers to either a pre-existing cached TextureInfo, // or a new TextureInfo just created. - TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] ); - textureInfo.maskTextureId = maskTextureId; - textureInfo.storageType = storageType; + TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]); + textureInfo.maskTextureId = maskTextureId; + textureInfo.storageType = storageType; textureInfo.orientationCorrection = orientationCorrection; - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", - GET_LOAD_STATE_STRING(textureInfo.loadState ) ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState)); // Force reloading of texture by setting loadState unless already loading or cancelled. - if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && - TextureManager::LoadState::LOADING != textureInfo.loadState && - TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState && - TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState && - TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState && - TextureManager::LoadState::CANCELLED != textureInfo.loadState ) + if(TextureManager::ReloadPolicy::FORCED == reloadPolicy && + TextureManager::LoadState::LOADING != textureInfo.loadState && + TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState && + TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState && + TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState && + TextureManager::LoadState::CANCELLED != textureInfo.loadState) { - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", - url.GetUrl().c_str(), observer, cacheIndex, textureId ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId); textureInfo.loadState = TextureManager::LoadState::NOT_STARTED; } // Check if we should add the observer. // Only do this if we have not loaded yet and it will not have loaded by the end of this method. - switch( textureInfo.loadState ) + switch(textureInfo.loadState) { case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing. case TextureManager::LoadState::NOT_STARTED: { - LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards + LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards break; } case TextureManager::LoadState::LOADING: @@ -517,14 +482,14 @@ TextureManager::TextureId TextureManager::RequestLoadInternal( case TextureManager::LoadState::MASK_APPLYING: case TextureManager::LoadState::MASK_APPLIED: { - ObserveTexture( textureInfo, observer ); + ObserveTexture(textureInfo, observer); break; } case TextureManager::LoadState::UPLOADED: { - if( observer ) + if(observer) { - LoadOrQueueTexture( textureInfo, observer ); + LoadOrQueueTexture(textureInfo, observer); } break; } @@ -533,15 +498,15 @@ TextureManager::TextureId TextureManager::RequestLoadInternal( // A cancelled texture hasn't finished loading yet. Treat as a loading texture // (it's ref count has already been incremented, above) textureInfo.loadState = TextureManager::LoadState::LOADING; - ObserveTexture( textureInfo, observer ); + ObserveTexture(textureInfo, observer); break; } case TextureManager::LoadState::LOAD_FINISHED: { // Loading has already completed. - if( observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER ) + if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER) { - LoadOrQueueTexture( textureInfo, observer ); + LoadOrQueueTexture(textureInfo, observer); } break; } @@ -551,35 +516,32 @@ TextureManager::TextureId TextureManager::RequestLoadInternal( return textureId; } -void TextureManager::Remove( const TextureManager::TextureId textureId, TextureUploadObserver* observer ) +void TextureManager::Remove(const TextureManager::TextureId textureId, TextureUploadObserver* observer) { - int textureInfoIndex = GetCacheIndexFromId( textureId ); - if( textureInfoIndex != INVALID_INDEX ) + int textureInfoIndex = GetCacheIndexFromId(textureId); + if(textureInfoIndex != INVALID_INDEX) { - TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] ); + TextureInfo& textureInfo(mTextureInfoContainer[textureInfoIndex]); - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, - "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s reference count = %d\n", - textureId, textureInfo.url.GetUrl().c_str(), - textureInfoIndex, GET_LOAD_STATE_STRING( textureInfo.loadState ), textureInfo.referenceCount ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s reference count = %d\n", textureId, textureInfo.url.GetUrl().c_str(), textureInfoIndex, GET_LOAD_STATE_STRING(textureInfo.loadState), textureInfo.referenceCount); // Decrement the reference count and check if this is the last user of this Texture. - if( --textureInfo.referenceCount <= 0 ) + if(--textureInfo.referenceCount <= 0) { // This is the last remove for this Texture. textureInfo.referenceCount = 0; - bool removeTextureInfo = false; + bool removeTextureInfo = false; // If loaded, we can remove the TextureInfo and the Atlas (if atlased). - if( textureInfo.loadState == LoadState::UPLOADED ) + if(textureInfo.loadState == LoadState::UPLOADED) { - if( textureInfo.atlas ) + if(textureInfo.atlas) { - textureInfo.atlas.Remove( textureInfo.atlasRect ); + textureInfo.atlas.Remove(textureInfo.atlasRect); } removeTextureInfo = true; } - else if( textureInfo.loadState == LoadState::LOADING ) + else if(textureInfo.loadState == LoadState::LOADING) { // We mark the textureInfo for removal. // Once the load has completed, this method will be called again. @@ -592,21 +554,21 @@ void TextureManager::Remove( const TextureManager::TextureId textureId, TextureU } // If the state allows us to remove the TextureInfo data, we do so. - if( removeTextureInfo ) + if(removeTextureInfo) { // Permanently remove the textureInfo struct. - mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex ); + mTextureInfoContainer.erase(mTextureInfoContainer.begin() + textureInfoIndex); } } - if( observer ) + if(observer) { // Remove element from the LoadQueue - for( auto&& element : mLoadQueue ) + for(auto&& element : mLoadQueue) { - if( element.mObserver == observer ) + if(element.mObserver == observer) { - mLoadQueue.Erase( &element ); + mLoadQueue.Erase(&element); break; } } @@ -614,37 +576,36 @@ void TextureManager::Remove( const TextureManager::TextureId textureId, TextureU } } -VisualUrl TextureManager::GetVisualUrl( TextureId textureId ) +VisualUrl TextureManager::GetVisualUrl(TextureId textureId) { VisualUrl visualUrl(""); - int cacheIndex = GetCacheIndexFromId( textureId ); + int cacheIndex = GetCacheIndexFromId(textureId); - if( cacheIndex != INVALID_CACHE_INDEX ) + if(cacheIndex != INVALID_CACHE_INDEX) { - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n", - cacheIndex, textureId ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n", cacheIndex, textureId); - TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] ); + TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]); visualUrl = cachedTextureInfo.url; } return visualUrl; } -TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId ) +TextureManager::LoadState TextureManager::GetTextureState(TextureId textureId) { LoadState loadState = TextureManager::LoadState::NOT_STARTED; - int cacheIndex = GetCacheIndexFromId( textureId ); - if( cacheIndex != INVALID_CACHE_INDEX ) + int cacheIndex = GetCacheIndexFromId(textureId); + if(cacheIndex != INVALID_CACHE_INDEX) { - TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] ); + TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]); loadState = cachedTextureInfo.loadState; } else { - for( auto&& elem : mExternalTextures ) + for(auto&& elem : mExternalTextures) { - if( elem.textureId == textureId ) + if(elem.textureId == textureId) { loadState = LoadState::UPLOADED; break; @@ -654,35 +615,35 @@ TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId ) return loadState; } -TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId ) +TextureManager::LoadState TextureManager::GetTextureStateInternal(TextureId textureId) { LoadState loadState = TextureManager::LoadState::NOT_STARTED; - int cacheIndex = GetCacheIndexFromId( textureId ); - if( cacheIndex != INVALID_CACHE_INDEX ) + int cacheIndex = GetCacheIndexFromId(textureId); + if(cacheIndex != INVALID_CACHE_INDEX) { - TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] ); + TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]); loadState = cachedTextureInfo.loadState; } return loadState; } -TextureSet TextureManager::GetTextureSet( TextureId textureId ) +TextureSet TextureManager::GetTextureSet(TextureId textureId) { - TextureSet textureSet;// empty handle + TextureSet textureSet; // empty handle - int cacheIndex = GetCacheIndexFromId( textureId ); - if( cacheIndex != INVALID_CACHE_INDEX ) + int cacheIndex = GetCacheIndexFromId(textureId); + if(cacheIndex != INVALID_CACHE_INDEX) { - TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] ); + TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]); textureSet = cachedTextureInfo.textureSet; } else { - for( auto&& elem : mExternalTextures ) + for(auto&& elem : mExternalTextures) { - if( elem.textureId == textureId ) + if(elem.textureId == textureId) { textureSet = elem.textureSet; break; @@ -692,34 +653,34 @@ TextureSet TextureManager::GetTextureSet( TextureId textureId ) return textureSet; } -std::string TextureManager::AddExternalTexture( TextureSet& textureSet ) +std::string TextureManager::AddExternalTexture(TextureSet& textureSet) { TextureManager::ExternalTextureInfo info; - info.textureId = GenerateUniqueTextureId(); + info.textureId = GenerateUniqueTextureId(); info.textureSet = textureSet; - mExternalTextures.emplace_back( info ); - return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) ); + mExternalTextures.emplace_back(info); + return VisualUrl::CreateTextureUrl(std::to_string(info.textureId)); } -TextureSet TextureManager::RemoveExternalTexture( const std::string& url ) +TextureSet TextureManager::RemoveExternalTexture(const std::string& url) { - if( url.size() > 0u ) + if(url.size() > 0u) { // get the location from the Url - VisualUrl parseUrl( url ); - if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() ) + VisualUrl parseUrl(url); + if(VisualUrl::TEXTURE == parseUrl.GetProtocolType()) { std::string location = parseUrl.GetLocation(); - if( location.size() > 0u ) + if(location.size() > 0u) { - TextureId id = std::stoi( location ); + TextureId id = std::stoi(location); const auto end = mExternalTextures.end(); - for( auto iter = mExternalTextures.begin(); iter != end; ++iter ) + for(auto iter = mExternalTextures.begin(); iter != end; ++iter) { - if( iter->textureId == id ) + if(iter->textureId == id) { auto textureSet = iter->textureSet; - mExternalTextures.erase( iter ); + mExternalTextures.erase(iter); return textureSet; } } @@ -729,59 +690,57 @@ TextureSet TextureManager::RemoveExternalTexture( const std::string& url ) return TextureSet(); } -void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer ) +void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer) { // make sure an observer doesn't observe the same object twice // otherwise it will get multiple calls to ObjectDestroyed() - DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer)); - mLifecycleObservers.PushBack( &observer ); + DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer)); + mLifecycleObservers.PushBack(&observer); } -void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer) +void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer) { // Find the observer... - auto endIter = mLifecycleObservers.End(); - for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter) + auto endIter = mLifecycleObservers.End(); + for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter) { - if( (*iter) == &observer) + if((*iter) == &observer) { - mLifecycleObservers.Erase( iter ); + mLifecycleObservers.Erase(iter); break; } } DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End()); } -void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer ) +void TextureManager::LoadOrQueueTexture(TextureInfo& textureInfo, TextureUploadObserver* observer) { - switch( textureInfo.loadState ) + switch(textureInfo.loadState) { case LoadState::NOT_STARTED: case LoadState::LOAD_FAILED: { - if( mQueueLoadFlag ) + if(mQueueLoadFlag) { - QueueLoadTexture( textureInfo, observer ); + QueueLoadTexture(textureInfo, observer); } else { - LoadTexture( textureInfo, observer ); + LoadTexture(textureInfo, observer); } break; } case LoadState::UPLOADED: { - if( mQueueLoadFlag ) + if(mQueueLoadFlag) { - QueueLoadTexture( textureInfo, observer ); + QueueLoadTexture(textureInfo, observer); } else { // The Texture has already loaded. The other observers have already been notified. // We need to send a "late" loaded notification for this observer. - observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet, - textureInfo.useAtlas, textureInfo.atlasRect, - textureInfo.preMultiplied ); + observer->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied); } break; } @@ -797,115 +756,104 @@ void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUpload } } -void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer ) +void TextureManager::QueueLoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer) { auto textureId = textureInfo.textureId; - mLoadQueue.PushBack( LoadQueueElement( textureId, observer) ); + mLoadQueue.PushBack(LoadQueueElement(textureId, observer)); - observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed ); + observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed); } -void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer ) +void TextureManager::LoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer) { - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", - textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F"); textureInfo.loadState = LoadState::LOADING; - if( !textureInfo.loadSynchronously ) + if(!textureInfo.loadSynchronously) { - auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders; - auto loadingHelperIt = loadersContainer.GetNext(); - auto premultiplyOnLoad = ( textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID ) ? - DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF; + auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders; + auto loadingHelperIt = loadersContainer.GetNext(); + auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF; DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End()); - if( textureInfo.animatedImageLoading ) + if(textureInfo.animatedImageLoading) { - loadingHelperIt->LoadAnimatedImage( textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex ); + loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex); } else { - loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, - textureInfo.desiredSize, textureInfo.fittingMode, - textureInfo.samplingMode, textureInfo.orientationCorrection, - premultiplyOnLoad ); + loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad); } } - ObserveTexture( textureInfo, observer ); + ObserveTexture(textureInfo, observer); } void TextureManager::ProcessQueuedTextures() { - for( auto&& element : mLoadQueue ) + for(auto&& element : mLoadQueue) { - if( !element.mObserver ) + if(!element.mObserver) { continue; } - int cacheIndex = GetCacheIndexFromId( element.mTextureId ); - if( cacheIndex != INVALID_CACHE_INDEX ) + int cacheIndex = GetCacheIndexFromId(element.mTextureId); + if(cacheIndex != INVALID_CACHE_INDEX) { - TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] ); - if( textureInfo.loadState == LoadState::UPLOADED ) + TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]); + if(textureInfo.loadState == LoadState::UPLOADED) { - element.mObserver->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet, - textureInfo.useAtlas, textureInfo.atlasRect, - textureInfo.preMultiplied ); + element.mObserver->UploadComplete(true, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied); } - else if ( textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER ) + else if(textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER) { - element.mObserver->LoadComplete( true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied ); + element.mObserver->LoadComplete(true, textureInfo.pixelBuffer, textureInfo.url, textureInfo.preMultiplied); } else { - LoadTexture( textureInfo, element.mObserver ); + LoadTexture(textureInfo, element.mObserver); } } } mLoadQueue.Clear(); } -void TextureManager::ObserveTexture( TextureInfo& textureInfo, - TextureUploadObserver* observer ) +void TextureManager::ObserveTexture(TextureInfo& textureInfo, + TextureUploadObserver* observer) { - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", - textureInfo.url.GetUrl().c_str(), observer ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer); - if( observer ) + if(observer) { - textureInfo.observerList.PushBack( observer ); - observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed ); + textureInfo.observerList.PushBack(observer); + observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed); } } -void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id, - Devel::PixelBuffer pixelBuffer ) +void TextureManager::AsyncLoadComplete(AsyncLoadingInfoContainerType& loadingContainer, uint32_t id, Devel::PixelBuffer pixelBuffer) { - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id); - if( loadingContainer.size() >= 1u ) + if(loadingContainer.size() >= 1u) { AsyncLoadingInfo loadingInfo = loadingContainer.front(); - if( loadingInfo.loadId == id ) + if(loadingInfo.loadId == id) { - int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId ); - if( cacheIndex != INVALID_CACHE_INDEX ) + int cacheIndex = GetCacheIndexFromId(loadingInfo.textureId); + if(cacheIndex != INVALID_CACHE_INDEX) { - TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] ); + TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]); - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, - " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n", - textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState); - if( textureInfo.loadState != LoadState::CANCELLED ) + if(textureInfo.loadState != LoadState::CANCELLED) { // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified) - PostLoad( textureInfo, pixelBuffer ); + PostLoad(textureInfo, pixelBuffer); } else { - Remove( textureInfo.textureId, nullptr ); + Remove(textureInfo.textureId, nullptr); } } } @@ -914,148 +862,146 @@ void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingCo } } -void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer ) +void TextureManager::PostLoad(TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer) { // Was the load successful? - if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) ) + if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0)) { // No atlas support for now - textureInfo.useAtlas = NO_ATLAS; + textureInfo.useAtlas = NO_ATLAS; textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied(); - if( textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE ) + if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE) { // If there is a mask texture ID associated with this texture, then apply the mask // if it's already loaded. If it hasn't, and the mask is still loading, // wait for the mask to finish loading. - if( textureInfo.maskTextureId != INVALID_TEXTURE_ID ) + if(textureInfo.maskTextureId != INVALID_TEXTURE_ID) { - if( textureInfo.loadState == LoadState::MASK_APPLYING ) + if(textureInfo.loadState == LoadState::MASK_APPLYING) { textureInfo.loadState = LoadState::MASK_APPLIED; - UploadTexture( pixelBuffer, textureInfo ); - NotifyObservers( textureInfo, true ); + UploadTexture(pixelBuffer, textureInfo); + NotifyObservers(textureInfo, true); } else { - LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId ); + LoadState maskLoadState = GetTextureStateInternal(textureInfo.maskTextureId); textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily - if( maskLoadState == LoadState::LOADING ) + if(maskLoadState == LoadState::LOADING) { textureInfo.loadState = LoadState::WAITING_FOR_MASK; } - else if( maskLoadState == LoadState::LOAD_FINISHED ) + else if(maskLoadState == LoadState::LOAD_FINISHED) { // Send New Task to Thread - ApplyMask( textureInfo, textureInfo.maskTextureId ); + ApplyMask(textureInfo, textureInfo.maskTextureId); } } } else { - UploadTexture( pixelBuffer, textureInfo ); - NotifyObservers( textureInfo, true ); + UploadTexture(pixelBuffer, textureInfo); + NotifyObservers(textureInfo, true); } } else { textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data - textureInfo.loadState = LoadState::LOAD_FINISHED; + textureInfo.loadState = LoadState::LOAD_FINISHED; - if( textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER ) + if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER) { - NotifyObservers( textureInfo, true ); + NotifyObservers(textureInfo, true); } else { // Check if there was another texture waiting for this load to complete // (e.g. if this was an image mask, and its load is on a different thread) - CheckForWaitingTexture( textureInfo ); + CheckForWaitingTexture(textureInfo); } } } else { textureInfo.loadState = LoadState::LOAD_FAILED; - CheckForWaitingTexture( textureInfo ); - NotifyObservers( textureInfo, false ); + CheckForWaitingTexture(textureInfo); + NotifyObservers(textureInfo, false); } } -void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo ) +void TextureManager::CheckForWaitingTexture(TextureInfo& maskTextureInfo) { // Search the cache, checking if any texture has this texture id as a // maskTextureId: const unsigned int size = mTextureInfoContainer.size(); - for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex ) + for(unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex) { - if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId && - mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK ) + if(mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId && + mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK) { - TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] ); + TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]); - if( maskTextureInfo.loadState == LoadState::LOAD_FINISHED ) + if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED) { // Send New Task to Thread - ApplyMask( textureInfo, maskTextureInfo.textureId ); + ApplyMask(textureInfo, maskTextureInfo.textureId); } else { textureInfo.pixelBuffer.Reset(); textureInfo.loadState = LoadState::LOAD_FAILED; - NotifyObservers( textureInfo, false ); + NotifyObservers(textureInfo, false); } } } } -void TextureManager::ApplyMask( TextureInfo& textureInfo, TextureId maskTextureId ) +void TextureManager::ApplyMask(TextureInfo& textureInfo, TextureId maskTextureId) { - int maskCacheIndex = GetCacheIndexFromId( maskTextureId ); - if( maskCacheIndex != INVALID_CACHE_INDEX ) + int maskCacheIndex = GetCacheIndexFromId(maskTextureId); + if(maskCacheIndex != INVALID_CACHE_INDEX) { Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer; - Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer; + Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer; textureInfo.pixelBuffer.Reset(); - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", - textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F"); - textureInfo.loadState = LoadState::MASK_APPLYING; - auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders; - auto loadingHelperIt = loadersContainer.GetNext(); - auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF; + textureInfo.loadState = LoadState::MASK_APPLYING; + auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders; + auto loadingHelperIt = loadersContainer.GetNext(); + auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF; DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End()); - loadingHelperIt->ApplyMask( textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad ); + loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad); } } -void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo ) +void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo) { - if( textureInfo.useAtlas != USE_ATLAS ) + if(textureInfo.useAtlas != USE_ATLAS) { - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId); // Check if this pixelBuffer is premultiplied textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied(); auto& renderingAddOn = RenderingAddOn::Get(); - if( renderingAddOn.IsValid() ) + if(renderingAddOn.IsValid()) { - renderingAddOn.CreateGeometry( textureInfo.textureId, pixelBuffer ); + renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer); } - Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), - pixelBuffer.GetWidth(), pixelBuffer.GetHeight() ); + Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight()); - PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer ); - texture.Upload( pixelData ); - if ( ! textureInfo.textureSet ) + PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); + texture.Upload(pixelData); + if(!textureInfo.textureSet) { textureInfo.textureSet = TextureSet::New(); } - textureInfo.textureSet.SetTexture( 0u, texture ); + textureInfo.textureSet.SetTexture(0u, texture); } // Update the load state. @@ -1065,7 +1011,7 @@ void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo textureInfo.loadState = LoadState::UPLOADED; } -void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success ) +void TextureManager::NotifyObservers(TextureInfo& textureInfo, bool success) { TextureId textureId = textureInfo.textureId; @@ -1075,7 +1021,7 @@ void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success ) mQueueLoadFlag = true; - while( info->observerList.Count() ) + while(info->observerList.Count()) { TextureUploadObserver* observer = info->observerList[0]; @@ -1087,40 +1033,38 @@ void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success ) // invalidating the reference to the textureInfo struct. // Texture load requests for the same URL are deferred until the end of this // method. - DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n", - textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState ) ); + DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n", textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState)); // It is possible for the observer to be deleted. // Disconnect and remove the observer first. - observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed ); + observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed); - info->observerList.Erase( info->observerList.begin() ); + info->observerList.Erase(info->observerList.begin()); - if( info->storageType == StorageType::RETURN_PIXEL_BUFFER ) + if(info->storageType == StorageType::RETURN_PIXEL_BUFFER) { - observer->LoadComplete( success, info->pixelBuffer, info->url, info->preMultiplied ); + observer->LoadComplete(success, info->pixelBuffer, info->url, info->preMultiplied); } else { - observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect, - info->preMultiplied ); + observer->UploadComplete(success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect, info->preMultiplied); } // Get the textureInfo from the container again as it may have been invalidated. - int textureInfoIndex = GetCacheIndexFromId( textureId ); - if( textureInfoIndex == INVALID_CACHE_INDEX) + int textureInfoIndex = GetCacheIndexFromId(textureId); + if(textureInfoIndex == INVALID_CACHE_INDEX) { break; // texture has been removed - can stop. } - info = &mTextureInfoContainer[ textureInfoIndex ]; + info = &mTextureInfoContainer[textureInfoIndex]; } mQueueLoadFlag = false; ProcessQueuedTextures(); - if( info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0 ) + if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0) { - Remove( info->textureId, nullptr ); + Remove(info->textureId, nullptr); } } @@ -1129,13 +1073,13 @@ TextureManager::TextureId TextureManager::GenerateUniqueTextureId() return mCurrentTextureId++; } -int TextureManager::GetCacheIndexFromId( const TextureId textureId ) +int TextureManager::GetCacheIndexFromId(const TextureId textureId) { const unsigned int size = mTextureInfoContainer.size(); - for( unsigned int i = 0; i < size; ++i ) + for(unsigned int i = 0; i < size; ++i) { - if( mTextureInfoContainer[i].textureId == textureId ) + if(mTextureInfoContainer[i].textureId == textureId) { return i; } @@ -1152,65 +1096,65 @@ TextureManager::TextureHash TextureManager::GenerateHash( const UseAtlas useAtlas, TextureId maskTextureId) { - std::string hashTarget( url ); - const size_t urlLength = hashTarget.length(); - const uint16_t width = size.GetWidth(); - const uint16_t height = size.GetWidth(); + std::string hashTarget(url); + const size_t urlLength = hashTarget.length(); + const uint16_t width = size.GetWidth(); + const uint16_t height = size.GetWidth(); // If either the width or height has been specified, include the resizing options in the hash - if( width != 0 || height != 0 ) + if(width != 0 || height != 0) { // We are appending 5 bytes to the URL to form the hash input. - hashTarget.resize( urlLength + 5u ); - char* hashTargetPtr = &( hashTarget[ urlLength ] ); + hashTarget.resize(urlLength + 5u); + char* hashTargetPtr = &(hashTarget[urlLength]); // Pack the width and height (4 bytes total). *hashTargetPtr++ = size.GetWidth() & 0xff; - *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff; + *hashTargetPtr++ = (size.GetWidth() >> 8u) & 0xff; *hashTargetPtr++ = size.GetHeight() & 0xff; - *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff; + *hashTargetPtr++ = (size.GetHeight() >> 8u) & 0xff; // Bit-pack the FittingMode, SamplingMode and atlasing. // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit - *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas; + *hashTargetPtr = (fittingMode << 4u) | (samplingMode << 1) | useAtlas; } else { // We are not including sizing information, but we still need an extra byte for atlasing. - hashTarget.resize( urlLength + 1u ); + hashTarget.resize(urlLength + 1u); // Add the atlasing to the hash input. - switch( useAtlas ) + switch(useAtlas) { case UseAtlas::NO_ATLAS: { - hashTarget[ urlLength ] = 'f'; + hashTarget[urlLength] = 'f'; break; } case UseAtlas::USE_ATLAS: { - hashTarget[ urlLength ] = 't'; + hashTarget[urlLength] = 't'; break; } } } - if( maskTextureId != INVALID_TEXTURE_ID ) + if(maskTextureId != INVALID_TEXTURE_ID) { auto textureIdIndex = hashTarget.length(); - hashTarget.resize( hashTarget.length() + sizeof( TextureId ) ); - unsigned char* hashTargetPtr = reinterpret_cast(&( hashTarget[ textureIdIndex ] )); + hashTarget.resize(hashTarget.length() + sizeof(TextureId)); + unsigned char* hashTargetPtr = reinterpret_cast(&(hashTarget[textureIdIndex])); // Append the texture id to the end of the URL byte by byte: // (to avoid SIGBUS / alignment issues) - for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter ) + for(size_t byteIter = 0; byteIter < sizeof(TextureId); ++byteIter) { *hashTargetPtr++ = maskTextureId & 0xff; maskTextureId >>= 8u; } } - return Dali::CalculateHash( hashTarget ); + return Dali::CalculateHash(hashTarget); } int TextureManager::FindCachedTexture( @@ -1228,25 +1172,24 @@ int TextureManager::FindCachedTexture( // Iterate through our hashes to find a match. const unsigned int count = mTextureInfoContainer.size(); - for( unsigned int i = 0u; i < count; ++i ) + for(unsigned int i = 0u; i < count; ++i) { - if( mTextureInfoContainer[i].hash == hash ) + if(mTextureInfoContainer[i].hash == hash) { // We have a match, now we check all the original parameters in case of a hash collision. - TextureInfo& textureInfo( mTextureInfoContainer[i] ); - - if( ( url == textureInfo.url.GetUrl() ) && - ( useAtlas == textureInfo.useAtlas ) && - ( maskTextureId == textureInfo.maskTextureId ) && - ( size == textureInfo.desiredSize ) && - ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) || - ( fittingMode == textureInfo.fittingMode && - samplingMode == textureInfo.samplingMode ) ) ) + TextureInfo& textureInfo(mTextureInfoContainer[i]); + + if((url == textureInfo.url.GetUrl()) && + (useAtlas == textureInfo.useAtlas) && + (maskTextureId == textureInfo.maskTextureId) && + (size == textureInfo.desiredSize) && + ((size.GetWidth() == 0 && size.GetHeight() == 0) || + (fittingMode == textureInfo.fittingMode && + samplingMode == textureInfo.samplingMode))) { // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different. // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false. - if( ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad ) - || ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied ) ) + if((preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad) || (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied)) { // The found Texture is a match. cacheIndex = i; @@ -1259,18 +1202,18 @@ int TextureManager::FindCachedTexture( return cacheIndex; } -void TextureManager::ObserverDestroyed( TextureUploadObserver* observer ) +void TextureManager::ObserverDestroyed(TextureUploadObserver* observer) { const unsigned int count = mTextureInfoContainer.size(); - for( unsigned int i = 0; i < count; ++i ) + for(unsigned int i = 0; i < count; ++i) { - TextureInfo& textureInfo( mTextureInfoContainer[i] ); - for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin(); - j != textureInfo.observerList.End(); ) + TextureInfo& textureInfo(mTextureInfoContainer[i]); + for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin(); + j != textureInfo.observerList.End();) { - if( *j == observer ) + if(*j == observer) { - j = textureInfo.observerList.Erase( j ); + j = textureInfo.observerList.Erase(j); } else { @@ -1280,53 +1223,51 @@ void TextureManager::ObserverDestroyed( TextureUploadObserver* observer ) } // Remove element from the LoadQueue - for( auto&& element : mLoadQueue ) + for(auto&& element : mLoadQueue) { - if( element.mObserver == observer ) + if(element.mObserver == observer) { element.mObserver = nullptr; } } } - TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager) -: AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager, - AsyncLoadingInfoContainerType()) +: AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager, AsyncLoadingInfoContainerType()) { } -void TextureManager::AsyncLoadingHelper::LoadAnimatedImage( TextureId textureId, - Dali::AnimatedImageLoading animatedImageLoading, - uint32_t frameIndex ) +void TextureManager::AsyncLoadingHelper::LoadAnimatedImage(TextureId textureId, + Dali::AnimatedImageLoading animatedImageLoading, + uint32_t frameIndex) { - mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) ); - auto id = DevelAsyncImageLoader::LoadAnimatedImage( mLoader, animatedImageLoading, frameIndex ); + mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId)); + auto id = DevelAsyncImageLoader::LoadAnimatedImage(mLoader, animatedImageLoading, frameIndex); mLoadingInfoContainer.back().loadId = id; } -void TextureManager::AsyncLoadingHelper::Load( TextureId textureId, - const VisualUrl& url, - ImageDimensions desiredSize, - FittingMode::Type fittingMode, - SamplingMode::Type samplingMode, - bool orientationCorrection, - DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad ) +void TextureManager::AsyncLoadingHelper::Load(TextureId textureId, + const VisualUrl& url, + ImageDimensions desiredSize, + FittingMode::Type fittingMode, + SamplingMode::Type samplingMode, + bool orientationCorrection, + DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) { - mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) ); - auto id = DevelAsyncImageLoader::Load( mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad ); + mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId)); + auto id = DevelAsyncImageLoader::Load(mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad); mLoadingInfoContainer.back().loadId = id; } -void TextureManager::AsyncLoadingHelper::ApplyMask( TextureId textureId, - Devel::PixelBuffer pixelBuffer, - Devel::PixelBuffer maskPixelBuffer, - float contentScale, - bool cropToMask, - DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad ) +void TextureManager::AsyncLoadingHelper::ApplyMask(TextureId textureId, + Devel::PixelBuffer pixelBuffer, + Devel::PixelBuffer maskPixelBuffer, + float contentScale, + bool cropToMask, + DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad) { - mLoadingInfoContainer.push_back( AsyncLoadingInfo( textureId ) ); - auto id = DevelAsyncImageLoader::ApplyMask( mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad ); + mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId)); + auto id = DevelAsyncImageLoader::ApplyMask(mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad); mLoadingInfoContainer.back().loadId = id; } @@ -1336,28 +1277,26 @@ TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs) } TextureManager::AsyncLoadingHelper::AsyncLoadingHelper( - Toolkit::AsyncImageLoader loader, - TextureManager& textureManager, - AsyncLoadingInfoContainerType&& loadingInfoContainer) + Toolkit::AsyncImageLoader loader, + TextureManager& textureManager, + AsyncLoadingInfoContainerType&& loadingInfoContainer) : mLoader(loader), mTextureManager(textureManager), mLoadingInfoContainer(std::move(loadingInfoContainer)) { DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect( - this, &AsyncLoadingHelper::AsyncLoadComplete); + this, &AsyncLoadingHelper::AsyncLoadComplete); } void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id, - Devel::PixelBuffer pixelBuffer ) + Devel::PixelBuffer pixelBuffer) { - mTextureManager.AsyncLoadComplete( mLoadingInfoContainer, id, pixelBuffer ); + mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer); } -Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements ) +Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements) { - return RenderingAddOn::Get().IsValid() ? - RenderingAddOn::Get().GetGeometry( textureId, frontElements, backElements) : - Geometry(); + return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry(); } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/texture-upload-observer.cpp b/dali-toolkit/internal/visuals/texture-upload-observer.cpp index 8ffd35f..5c46ff2 100644 --- a/dali-toolkit/internal/visuals/texture-upload-observer.cpp +++ b/dali-toolkit/internal/visuals/texture-upload-observer.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,19 +20,17 @@ namespace Dali { - namespace Toolkit { - TextureUploadObserver::TextureUploadObserver() { } TextureUploadObserver::~TextureUploadObserver() { - if( !mDestructionSignal.Empty() ) + if(!mDestructionSignal.Empty()) { - mDestructionSignal.Emit( this ); + mDestructionSignal.Emit(this); } } @@ -41,7 +39,6 @@ TextureUploadObserver::DestructionSignalType& TextureUploadObserver::Destruction return mDestructionSignal; } - } // namespace Toolkit } // namespace Dali diff --git a/dali-toolkit/internal/visuals/transition-data-impl.cpp b/dali-toolkit/internal/visuals/transition-data-impl.cpp index bda70a4b..43fe953 100644 --- a/dali-toolkit/internal/visuals/transition-data-impl.cpp +++ b/dali-toolkit/internal/visuals/transition-data-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,11 +19,11 @@ #include // EXTERNAL HEADERS +#include +#include #include #include #include -#include -#include #include using namespace Dali; @@ -40,23 +40,22 @@ const char* TOKEN_DURATION("duration"); const char* TOKEN_DELAY("delay"); const char* TOKEN_ALPHA_FUNCTION("alphaFunction"); - -DALI_ENUM_TO_STRING_TABLE_BEGIN( ALPHA_FUNCTION_BUILTIN ) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, LINEAR) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, REVERSE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SQUARE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SQUARE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SINE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SINE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT_SINE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_BACK) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, BOUNCE) -DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, SIN) -DALI_ENUM_TO_STRING_TABLE_END( ALPHA_FUNCTION_BUILTIN ) -} +DALI_ENUM_TO_STRING_TABLE_BEGIN(ALPHA_FUNCTION_BUILTIN) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, LINEAR) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, REVERSE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SQUARE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SQUARE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_SINE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_SINE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_IN_OUT_SINE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, EASE_OUT_BACK) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, BOUNCE) + DALI_ENUM_TO_STRING_WITH_SCOPE(AlphaFunction, SIN) +DALI_ENUM_TO_STRING_TABLE_END(ALPHA_FUNCTION_BUILTIN) +} // namespace namespace Dali { @@ -64,21 +63,19 @@ namespace Toolkit { namespace Internal { - namespace { - /// Parses a Property::Array and sets up the animator appropriately void ParseArray(TransitionData::Animator* animator, const Property::Array* array) { - bool valid = true; + bool valid = true; Vector4 controlPoints; - if( array && array->Count() >= 4 ) + if(array && array->Count() >= 4) { - for( size_t vecIdx = 0; vecIdx < 4; ++vecIdx ) + for(size_t vecIdx = 0; vecIdx < 4; ++vecIdx) { const Property::Value& v = array->GetElementAt(vecIdx); - if( v.GetType() == Property::FLOAT ) + if(v.GetType() == Property::FLOAT) { controlPoints[vecIdx] = v.Get(); } @@ -94,11 +91,11 @@ void ParseArray(TransitionData::Animator* animator, const Property::Array* array valid = false; } - if( valid ) + if(valid) { - Vector2 controlPoint1( controlPoints.x, controlPoints.y ); - Vector2 controlPoint2( controlPoints.z, controlPoints.w ); - animator->alphaFunction = AlphaFunction( controlPoint1, controlPoint2 ); + Vector2 controlPoint1(controlPoints.x, controlPoints.y); + Vector2 controlPoint2(controlPoints.z, controlPoints.w); + animator->alphaFunction = AlphaFunction(controlPoint1, controlPoint2); } else { @@ -109,64 +106,64 @@ void ParseArray(TransitionData::Animator* animator, const Property::Array* array /// Parses a string value and sets up the animator appropriately void ParseString(TransitionData::Animator* animator, std::string alphaFunctionValue) { - if( alphaFunctionValue == "LINEAR" ) + if(alphaFunctionValue == "LINEAR") { animator->alphaFunction = AlphaFunction(AlphaFunction::LINEAR); } - else if( ! alphaFunctionValue.compare(0, 5, "EASE_" ) ) + else if(!alphaFunctionValue.compare(0, 5, "EASE_")) { - if( alphaFunctionValue == "EASE_IN" ) + if(alphaFunctionValue == "EASE_IN") { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN); } - else if( alphaFunctionValue == "EASE_OUT" ) + else if(alphaFunctionValue == "EASE_OUT") { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT); } - else if( ! alphaFunctionValue.compare( 5, 3, "IN_" ) ) + else if(!alphaFunctionValue.compare(5, 3, "IN_")) { - if( ! alphaFunctionValue.compare(8, -1, "SQUARE" )) + if(!alphaFunctionValue.compare(8, -1, "SQUARE")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_SQUARE); } - else if( ! alphaFunctionValue.compare(8, -1, "OUT" )) + else if(!alphaFunctionValue.compare(8, -1, "OUT")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_OUT); } - else if( ! alphaFunctionValue.compare(8, -1, "OUT_SINE" )) + else if(!alphaFunctionValue.compare(8, -1, "OUT_SINE")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_OUT_SINE); } - else if( ! alphaFunctionValue.compare(8, -1, "SINE" )) + else if(!alphaFunctionValue.compare(8, -1, "SINE")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_IN_SINE); } } - else if( ! alphaFunctionValue.compare( 5, 4, "OUT_" ) ) + else if(!alphaFunctionValue.compare(5, 4, "OUT_")) { - if( ! alphaFunctionValue.compare(9, -1, "SQUARE" ) ) + if(!alphaFunctionValue.compare(9, -1, "SQUARE")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT_SQUARE); } - else if( ! alphaFunctionValue.compare(9, -1, "SINE" ) ) + else if(!alphaFunctionValue.compare(9, -1, "SINE")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT_SINE); } - else if( ! alphaFunctionValue.compare(9, -1, "BACK" ) ) + else if(!alphaFunctionValue.compare(9, -1, "BACK")) { animator->alphaFunction = AlphaFunction(AlphaFunction::EASE_OUT_BACK); } } } - else if( alphaFunctionValue == "REVERSE" ) + else if(alphaFunctionValue == "REVERSE") { animator->alphaFunction = AlphaFunction(AlphaFunction::REVERSE); } - else if( alphaFunctionValue == "BOUNCE" ) + else if(alphaFunctionValue == "BOUNCE") { animator->alphaFunction = AlphaFunction(AlphaFunction::BOUNCE); } - else if( alphaFunctionValue == "SIN" ) + else if(alphaFunctionValue == "SIN") { animator->alphaFunction = AlphaFunction(AlphaFunction::SIN); } @@ -181,141 +178,140 @@ TransitionData::~TransitionData() { } -TransitionDataPtr TransitionData::New( const Property::Array& value ) +TransitionDataPtr TransitionData::New(const Property::Array& value) { - TransitionDataPtr transitionData( new TransitionData() ); + TransitionDataPtr transitionData(new TransitionData()); transitionData->Initialize(value); return transitionData; } -TransitionDataPtr TransitionData::New( const Property::Map& value ) +TransitionDataPtr TransitionData::New(const Property::Map& value) { - TransitionDataPtr transitionData( new TransitionData() ); + TransitionDataPtr transitionData(new TransitionData()); transitionData->Initialize(value); return transitionData; } - -void TransitionData::Initialize( const Property::Map& map ) +void TransitionData::Initialize(const Property::Map& map) { - TransitionData::Animator* animator = ConvertMap( map ); - Add( animator ); + TransitionData::Animator* animator = ConvertMap(map); + Add(animator); } -void TransitionData::Initialize( const Property::Array& array ) +void TransitionData::Initialize(const Property::Array& array) { - for( unsigned int arrayIdx = 0, transitionArrayCount = array.Count(); arrayIdx < transitionArrayCount; ++arrayIdx ) + for(unsigned int arrayIdx = 0, transitionArrayCount = array.Count(); arrayIdx < transitionArrayCount; ++arrayIdx) { - const Property::Value& element = array.GetElementAt( arrayIdx ); + const Property::Value& element = array.GetElementAt(arrayIdx); // Expect each child to be an object representing an animator: const Property::Map* map = element.GetMap(); - if( map != NULL ) + if(map != NULL) { - TransitionData::Animator* animator = ConvertMap( *map ); - Add( animator ); + TransitionData::Animator* animator = ConvertMap(*map); + Add(animator); } } } -TransitionData::Animator* TransitionData::ConvertMap( const Property::Map& map) +TransitionData::Animator* TransitionData::ConvertMap(const Property::Map& map) { TransitionData::Animator* animator = new TransitionData::Animator(); - animator->alphaFunction = AlphaFunction::LINEAR; - animator->timePeriodDelay = 0.0f; - animator->timePeriodDuration = 1.0f; + animator->alphaFunction = AlphaFunction::LINEAR; + animator->timePeriodDelay = 0.0f; + animator->timePeriodDuration = 1.0f; - for( unsigned int mapIdx = 0; mapIdx < map.Count(); ++mapIdx ) + for(unsigned int mapIdx = 0; mapIdx < map.Count(); ++mapIdx) { - const KeyValuePair pair( map.GetKeyValue( mapIdx ) ); - if( pair.first.type == Property::Key::INDEX ) + const KeyValuePair pair(map.GetKeyValue(mapIdx)); + if(pair.first.type == Property::Key::INDEX) { continue; // We don't consider index keys. } - const std::string& key( pair.first.stringKey ); - const Property::Value& value( pair.second ); + const std::string& key(pair.first.stringKey); + const Property::Value& value(pair.second); - if( key == TOKEN_TARGET ) + if(key == TOKEN_TARGET) { - animator->objectName = value.Get< std::string >(); + animator->objectName = value.Get(); } - else if( key == TOKEN_PROPERTY ) + else if(key == TOKEN_PROPERTY) { - if( value.GetType() == Property::STRING ) + if(value.GetType() == Property::STRING) { - animator->propertyKey = Property::Key( value.Get() ); + animator->propertyKey = Property::Key(value.Get()); } else { - animator->propertyKey = Property::Key( value.Get() ); + animator->propertyKey = Property::Key(value.Get()); } } - else if( key == TOKEN_INITIAL_VALUE ) + else if(key == TOKEN_INITIAL_VALUE) { animator->initialValue = value; } - else if( key == TOKEN_TARGET_VALUE ) + else if(key == TOKEN_TARGET_VALUE) { animator->targetValue = value; } - else if( key == TOKEN_ANIMATOR ) + else if(key == TOKEN_ANIMATOR) { - animator->animate = true; - Property::Map animatorMap = value.Get< Property::Map >(); - for( size_t animatorMapIdx = 0; animatorMapIdx < animatorMap.Count(); ++animatorMapIdx ) + animator->animate = true; + Property::Map animatorMap = value.Get(); + for(size_t animatorMapIdx = 0; animatorMapIdx < animatorMap.Count(); ++animatorMapIdx) { - const KeyValuePair pair( animatorMap.GetKeyValue( animatorMapIdx ) ); + const KeyValuePair pair(animatorMap.GetKeyValue(animatorMapIdx)); - if( pair.first.type == Property::Key::INDEX ) + if(pair.first.type == Property::Key::INDEX) { continue; // We don't consider index keys. } - const std::string& key( pair.first.stringKey ); - const Property::Value& value( pair.second ); + const std::string& key(pair.first.stringKey); + const Property::Value& value(pair.second); - if( key == TOKEN_ALPHA_FUNCTION ) + if(key == TOKEN_ALPHA_FUNCTION) { - if( value.GetType() == Property::ARRAY ) + if(value.GetType() == Property::ARRAY) { ParseArray(animator, value.GetArray()); } - else if( value.GetType() == Property::VECTOR4 ) + else if(value.GetType() == Property::VECTOR4) { Vector4 controlPoints = value.Get(); - Vector2 controlPoint1( controlPoints.x, controlPoints.y ); - Vector2 controlPoint2( controlPoints.z, controlPoints.w ); - animator->alphaFunction = AlphaFunction( controlPoint1, controlPoint2 ); + Vector2 controlPoint1(controlPoints.x, controlPoints.y); + Vector2 controlPoint2(controlPoints.z, controlPoints.w); + animator->alphaFunction = AlphaFunction(controlPoint1, controlPoint2); } - else if( value.GetType() == Property::STRING ) + else if(value.GetType() == Property::STRING) { - ParseString(animator, value.Get< std::string >()); + ParseString(animator, value.Get()); } else { animator->animate = false; } } - else if( key == TOKEN_TIME_PERIOD ) + else if(key == TOKEN_TIME_PERIOD) { - Property::Map timeMap = value.Get< Property::Map >(); - for( size_t timeMapIdx = 0; timeMapIdx < timeMap.Count(); ++timeMapIdx ) + Property::Map timeMap = value.Get(); + for(size_t timeMapIdx = 0; timeMapIdx < timeMap.Count(); ++timeMapIdx) { - const KeyValuePair pair( timeMap.GetKeyValue( timeMapIdx ) ); - if( pair.first.type == Property::Key::INDEX ) + const KeyValuePair pair(timeMap.GetKeyValue(timeMapIdx)); + if(pair.first.type == Property::Key::INDEX) { continue; } - const std::string& key( pair.first.stringKey ); + const std::string& key(pair.first.stringKey); - if( key == TOKEN_DELAY ) + if(key == TOKEN_DELAY) { - animator->timePeriodDelay = pair.second.Get< float >(); + animator->timePeriodDelay = pair.second.Get(); } - else if( key == TOKEN_DURATION ) + else if(key == TOKEN_DURATION) { - animator->timePeriodDuration = pair.second.Get< float >(); + animator->timePeriodDuration = pair.second.Get(); } } } @@ -325,9 +321,9 @@ TransitionData::Animator* TransitionData::ConvertMap( const Property::Map& map) return animator; } -void TransitionData::Add( Animator* animator ) +void TransitionData::Add(Animator* animator) { - mAnimators.PushBack( animator ); + mAnimators.PushBack(animator); } TransitionData::Iterator TransitionData::Begin() const @@ -345,14 +341,14 @@ size_t TransitionData::Count() const return mAnimators.Count(); } -Property::Map TransitionData::GetAnimatorAt( size_t index ) +Property::Map TransitionData::GetAnimatorAt(size_t index) { - DALI_ASSERT_ALWAYS( index < Count() && "index exceeds bounds" ); + DALI_ASSERT_ALWAYS(index < Count() && "index exceeds bounds"); - Animator* animator = mAnimators[index]; + Animator* animator = mAnimators[index]; Property::Map map; map[TOKEN_TARGET] = animator->objectName; - if( animator->propertyKey.type == Property::Key::INDEX ) + if(animator->propertyKey.type == Property::Key::INDEX) { map[TOKEN_PROPERTY] = animator->propertyKey.indexKey; } @@ -360,32 +356,28 @@ Property::Map TransitionData::GetAnimatorAt( size_t index ) { map[TOKEN_PROPERTY] = animator->propertyKey.stringKey; } - if( animator->initialValue.GetType() != Property::NONE ) + if(animator->initialValue.GetType() != Property::NONE) { map[TOKEN_INITIAL_VALUE] = animator->initialValue; } - if( animator->targetValue.GetType() != Property::NONE ) + if(animator->targetValue.GetType() != Property::NONE) { map[TOKEN_TARGET_VALUE] = animator->targetValue; } - if( animator->animate ) + if(animator->animate) { Property::Map animateMap; - if( animator->alphaFunction.GetMode() == AlphaFunction::BUILTIN_FUNCTION ) + if(animator->alphaFunction.GetMode() == AlphaFunction::BUILTIN_FUNCTION) { - animateMap.Add(TOKEN_ALPHA_FUNCTION, GetEnumerationName( animator->alphaFunction.GetBuiltinFunction(), - ALPHA_FUNCTION_BUILTIN_TABLE, - ALPHA_FUNCTION_BUILTIN_TABLE_COUNT )); + animateMap.Add(TOKEN_ALPHA_FUNCTION, GetEnumerationName(animator->alphaFunction.GetBuiltinFunction(), ALPHA_FUNCTION_BUILTIN_TABLE, ALPHA_FUNCTION_BUILTIN_TABLE_COUNT)); } - else if( animator->alphaFunction.GetMode() == AlphaFunction::BEZIER ) + else if(animator->alphaFunction.GetMode() == AlphaFunction::BEZIER) { Vector4 controlPoints = animator->alphaFunction.GetBezierControlPoints(); - animateMap.Add( TOKEN_ALPHA_FUNCTION, controlPoints ); + animateMap.Add(TOKEN_ALPHA_FUNCTION, controlPoints); } - animateMap.Add(TOKEN_TIME_PERIOD, Property::Map() - .Add( TOKEN_DELAY, animator->timePeriodDelay ) - .Add( TOKEN_DURATION, animator->timePeriodDuration )); + animateMap.Add(TOKEN_TIME_PERIOD, Property::Map().Add(TOKEN_DELAY, animator->timePeriodDelay).Add(TOKEN_DURATION, animator->timePeriodDuration)); map[TOKEN_ANIMATOR] = animateMap; } diff --git a/dali-toolkit/internal/visuals/visual-base-data-impl.cpp b/dali-toolkit/internal/visuals/visual-base-data-impl.cpp index 67ab688..bb3f8d0 100644 --- a/dali-toolkit/internal/visuals/visual-base-data-impl.cpp +++ b/dali-toolkit/internal/visuals/visual-base-data-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. @@ -25,60 +25,58 @@ #include // INTERNAL INCLUDES -#include #include #include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -DALI_ENUM_TO_STRING_TABLE_BEGIN( SHADER_HINT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Shader::Hint, NONE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Shader::Hint, OUTPUT_IS_TRANSPARENT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Shader::Hint, MODIFIES_GEOMETRY ) -DALI_ENUM_TO_STRING_TABLE_END( SHADER_HINT ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( ALIGN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, TOP_BEGIN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, TOP_CENTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, TOP_END ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, CENTER_BEGIN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, CENTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, CENTER_END ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, BOTTOM_BEGIN ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, BOTTOM_CENTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Align, BOTTOM_END ) -DALI_ENUM_TO_STRING_TABLE_END( ALIGN ) - -DALI_ENUM_TO_STRING_TABLE_BEGIN( POLICY ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual::Transform::Policy, RELATIVE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual::Transform::Policy, ABSOLUTE ) -DALI_ENUM_TO_STRING_TABLE_END( POLICY ) - -Dali::Vector2 PointToVector2( Toolkit::Align::Type point, Toolkit::Direction::Type direction ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(SHADER_HINT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Shader::Hint, NONE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Shader::Hint, OUTPUT_IS_TRANSPARENT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Shader::Hint, MODIFIES_GEOMETRY) +DALI_ENUM_TO_STRING_TABLE_END(SHADER_HINT) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(ALIGN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, TOP_BEGIN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, TOP_CENTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, TOP_END) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, CENTER_BEGIN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, CENTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, CENTER_END) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, BOTTOM_BEGIN) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, BOTTOM_CENTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Align, BOTTOM_END) +DALI_ENUM_TO_STRING_TABLE_END(ALIGN) + +DALI_ENUM_TO_STRING_TABLE_BEGIN(POLICY) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual::Transform::Policy, RELATIVE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual::Transform::Policy, ABSOLUTE) +DALI_ENUM_TO_STRING_TABLE_END(POLICY) + +Dali::Vector2 PointToVector2(Toolkit::Align::Type point, Toolkit::Direction::Type direction) { - static const float pointToVector2[] = { 0.0f,0.0f, - 0.5f,0.0f, - 1.0f,0.0f, - 0.0f,0.5f, - 0.5f,0.5f, - 1.0f,0.5f, - 0.0f,1.0f, - 0.5f,1.0f, - 1.0f,1.0f }; - - Vector2 result( &pointToVector2[point*2] ); - if( direction == Direction::RIGHT_TO_LEFT ) + // clang-format off + static const float pointToVector2[] = {0.0f,0.0f, + 0.5f,0.0f, + 1.0f,0.0f, + 0.0f,0.5f, + 0.5f,0.5f, + 1.0f,0.5f, + 0.0f,1.0f, + 0.5f,1.0f, + 1.0f,1.0f}; + // clang-format on + + Vector2 result(&pointToVector2[point * 2]); + if(direction == Direction::RIGHT_TO_LEFT) { result.x = 1.0f - result.x; } @@ -86,27 +84,27 @@ Dali::Vector2 PointToVector2( Toolkit::Align::Type point, Toolkit::Direction::Ty return result; } -bool GetPolicyFromValue( const Property::Value& value, Vector2& policy ) +bool GetPolicyFromValue(const Property::Value& value, Vector2& policy) { bool success = false; - if( value.Get( policy ) ) + if(value.Get(policy)) { success = true; } else { const Property::Array* array = value.GetArray(); - if( array && array->Size() == 2 ) + if(array && array->Size() == 2) { - Toolkit::Visual::Transform::Policy::Type xPolicy = static_cast< Toolkit::Visual::Transform::Policy::Type >( -1 ); // Assign an invalid value so definitely changes - Toolkit::Visual::Transform::Policy::Type yPolicy = static_cast< Toolkit::Visual::Transform::Policy::Type >( -1 ); // Assign an invalid value so definitely changes + Toolkit::Visual::Transform::Policy::Type xPolicy = static_cast(-1); // Assign an invalid value so definitely changes + Toolkit::Visual::Transform::Policy::Type yPolicy = static_cast(-1); // Assign an invalid value so definitely changes - if( Scripting::GetEnumerationProperty< Toolkit::Visual::Transform::Policy::Type >( array->GetElementAt( 0 ), POLICY_TABLE, POLICY_TABLE_COUNT, xPolicy ) && - Scripting::GetEnumerationProperty< Toolkit::Visual::Transform::Policy::Type >( array->GetElementAt( 1 ), POLICY_TABLE, POLICY_TABLE_COUNT, yPolicy ) ) + if(Scripting::GetEnumerationProperty(array->GetElementAt(0), POLICY_TABLE, POLICY_TABLE_COUNT, xPolicy) && + Scripting::GetEnumerationProperty(array->GetElementAt(1), POLICY_TABLE, POLICY_TABLE_COUNT, yPolicy)) { policy.x = xPolicy; policy.y = yPolicy; - success = true; + success = true; } } } @@ -139,105 +137,105 @@ Internal::Visual::Base::Impl::~Impl() delete mCustomShader; } -Internal::Visual::Base::Impl::CustomShader::CustomShader( const Property::Map& map ) -: mGridSize( 1, 1 ), - mHints( Shader::Hint::NONE ) +Internal::Visual::Base::Impl::CustomShader::CustomShader(const Property::Map& map) +: mGridSize(1, 1), + mHints(Shader::Hint::NONE) { - SetPropertyMap( map ); + SetPropertyMap(map); } -void Internal::Visual::Base::Impl::CustomShader::SetPropertyMap( const Property::Map& shaderMap ) +void Internal::Visual::Base::Impl::CustomShader::SetPropertyMap(const Property::Map& shaderMap) { mVertexShader.clear(); mFragmentShader.clear(); - mGridSize = ImageDimensions( 1, 1 ); - mHints = Shader::Hint::NONE; + mGridSize = ImageDimensions(1, 1); + mHints = Shader::Hint::NONE; - Property::Value* vertexShaderValue = shaderMap.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER ); - if( vertexShaderValue ) + Property::Value* vertexShaderValue = shaderMap.Find(Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER); + if(vertexShaderValue) { - if( ! GetStringFromProperty( *vertexShaderValue, mVertexShader ) ) + if(!GetStringFromProperty(*vertexShaderValue, mVertexShader)) { - DALI_LOG_ERROR( "'%s' parameter does not correctly specify a string\n", CUSTOM_VERTEX_SHADER ); + DALI_LOG_ERROR("'%s' parameter does not correctly specify a string\n", CUSTOM_VERTEX_SHADER); } } - Property::Value* fragmentShaderValue = shaderMap.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER ); - if( fragmentShaderValue ) + Property::Value* fragmentShaderValue = shaderMap.Find(Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER); + if(fragmentShaderValue) { - if( ! GetStringFromProperty( *fragmentShaderValue, mFragmentShader ) ) + if(!GetStringFromProperty(*fragmentShaderValue, mFragmentShader)) { - DALI_LOG_ERROR( "'%s' parameter does not correctly specify a string\n", CUSTOM_FRAGMENT_SHADER ); + DALI_LOG_ERROR("'%s' parameter does not correctly specify a string\n", CUSTOM_FRAGMENT_SHADER); } } - Property::Value* subdivideXValue = shaderMap.Find( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, CUSTOM_SUBDIVIDE_GRID_X ); - if( subdivideXValue ) + Property::Value* subdivideXValue = shaderMap.Find(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, CUSTOM_SUBDIVIDE_GRID_X); + if(subdivideXValue) { int subdivideX; - if( !subdivideXValue->Get( subdivideX ) || subdivideX < 1 ) + if(!subdivideXValue->Get(subdivideX) || subdivideX < 1) { - DALI_LOG_ERROR( "'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_X ); + DALI_LOG_ERROR("'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_X); } else { - mGridSize = ImageDimensions( subdivideX, mGridSize.GetY() ); + mGridSize = ImageDimensions(subdivideX, mGridSize.GetY()); } } - Property::Value* subdivideYValue = shaderMap.Find( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, CUSTOM_SUBDIVIDE_GRID_Y ); - if( subdivideYValue ) + Property::Value* subdivideYValue = shaderMap.Find(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, CUSTOM_SUBDIVIDE_GRID_Y); + if(subdivideYValue) { int subdivideY; - if( !subdivideYValue->Get( subdivideY ) || subdivideY < 1 ) + if(!subdivideYValue->Get(subdivideY) || subdivideY < 1) { - DALI_LOG_ERROR( "'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_Y ); + DALI_LOG_ERROR("'%s' parameter does not correctly specify a value greater than 1\n", CUSTOM_SUBDIVIDE_GRID_Y); } else { - mGridSize = ImageDimensions( mGridSize.GetX(), subdivideY ); + mGridSize = ImageDimensions(mGridSize.GetX(), subdivideY); } } - Property::Value* hintsValue = shaderMap.Find( Toolkit::Visual::Shader::Property::HINTS, CUSTOM_SHADER_HINTS ); - if( hintsValue ) + Property::Value* hintsValue = shaderMap.Find(Toolkit::Visual::Shader::Property::HINTS, CUSTOM_SHADER_HINTS); + if(hintsValue) { - if ( ! Scripting::GetBitmaskEnumerationProperty( *hintsValue, SHADER_HINT_TABLE, SHADER_HINT_TABLE_COUNT, mHints ) ) + if(!Scripting::GetBitmaskEnumerationProperty(*hintsValue, SHADER_HINT_TABLE, SHADER_HINT_TABLE_COUNT, mHints)) { - DALI_LOG_ERROR( "'%s' parameter does not correctly specify a hint or an array of hint strings\n", CUSTOM_SHADER_HINTS ); + DALI_LOG_ERROR("'%s' parameter does not correctly specify a hint or an array of hint strings\n", CUSTOM_SHADER_HINTS); } } } -void Internal::Visual::Base::Impl::CustomShader::CreatePropertyMap( Property::Map& map ) const +void Internal::Visual::Base::Impl::CustomShader::CreatePropertyMap(Property::Map& map) const { - if( !mVertexShader.empty() || !mFragmentShader.empty() ) + if(!mVertexShader.empty() || !mFragmentShader.empty()) { Property::Map customShader; - if( !mVertexShader.empty() ) + if(!mVertexShader.empty()) { - customShader.Insert( Toolkit::Visual::Shader::Property::VERTEX_SHADER, mVertexShader ); + customShader.Insert(Toolkit::Visual::Shader::Property::VERTEX_SHADER, mVertexShader); } - if( !mFragmentShader.empty() ) + if(!mFragmentShader.empty()) { - customShader.Insert( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, mFragmentShader ); + customShader.Insert(Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, mFragmentShader); } - if( mGridSize.GetWidth() != 1 ) + if(mGridSize.GetWidth() != 1) { - customShader.Insert( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, mGridSize.GetWidth() ); + customShader.Insert(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_X, mGridSize.GetWidth()); } - if( mGridSize.GetHeight() != 1 ) + if(mGridSize.GetHeight() != 1) { - customShader.Insert( Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, mGridSize.GetHeight() ); + customShader.Insert(Toolkit::Visual::Shader::Property::SUBDIVIDE_GRID_Y, mGridSize.GetHeight()); } - if( mHints != Dali::Shader::Hint::NONE ) + if(mHints != Dali::Shader::Hint::NONE) { - customShader.Insert( Toolkit::Visual::Shader::Property::HINTS, static_cast< int >( mHints ) ); + customShader.Insert(Toolkit::Visual::Shader::Property::HINTS, static_cast(mHints)); } - map.Insert( Toolkit::Visual::Property::SHADER, customShader ); + map.Insert(Toolkit::Visual::Property::SHADER, customShader); } } @@ -253,52 +251,52 @@ Internal::Visual::Base::Impl::Transform::Transform() { } -void Internal::Visual::Base::Impl::Transform::SetPropertyMap( const Property::Map& map ) +void Internal::Visual::Base::Impl::Transform::SetPropertyMap(const Property::Map& map) { // Set default values - mOffset = Vector2( 0.0f,0.0f ); - mSize = Vector2( 1.0f,1.0f ); - mExtraSize = Vector2( 0.0f,0.0f ); - mOffsetSizeMode = Vector4( 0.0f,0.0f,0.0f,0.0f ); - mOrigin = Toolkit::Align::TOP_BEGIN; - mAnchorPoint = Toolkit::Align::TOP_BEGIN; - - UpdatePropertyMap( map ); + mOffset = Vector2(0.0f, 0.0f); + mSize = Vector2(1.0f, 1.0f); + mExtraSize = Vector2(0.0f, 0.0f); + mOffsetSizeMode = Vector4(0.0f, 0.0f, 0.0f, 0.0f); + mOrigin = Toolkit::Align::TOP_BEGIN; + mAnchorPoint = Toolkit::Align::TOP_BEGIN; + + UpdatePropertyMap(map); } -void Internal::Visual::Base::Impl::Transform::UpdatePropertyMap( const Property::Map& map ) +void Internal::Visual::Base::Impl::Transform::UpdatePropertyMap(const Property::Map& map) { - for( Property::Map::SizeType i(0); i( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin ); + Scripting::GetEnumerationProperty(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin); break; } case Toolkit::Visual::Transform::Property::ANCHOR_POINT: { - Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint ); + Scripting::GetEnumerationProperty(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint); break; } case Toolkit::Visual::Transform::Property::OFFSET_POLICY: { Vector2 policy; - if( GetPolicyFromValue( keyValue.second, policy ) ) + if(GetPolicyFromValue(keyValue.second, policy)) { mOffsetSizeMode.x = policy.x; mOffsetSizeMode.y = policy.y; @@ -308,7 +306,7 @@ void Internal::Visual::Base::Impl::Transform::UpdatePropertyMap( const Property: case Toolkit::Visual::Transform::Property::SIZE_POLICY: { Vector2 policy; - if( GetPolicyFromValue( keyValue.second, policy ) ) + if(GetPolicyFromValue(keyValue.second, policy)) { mOffsetSizeMode.z = policy.x; mOffsetSizeMode.w = policy.y; @@ -317,81 +315,82 @@ void Internal::Visual::Base::Impl::Transform::UpdatePropertyMap( const Property: } case Toolkit::DevelVisual::Transform::Property::EXTRA_SIZE: { - keyValue.second.Get( mExtraSize ); + keyValue.second.Get(mExtraSize); break; } } } - else // Key type is STRING + else // Key type is STRING { - if( keyValue.first == "offset" ) + if(keyValue.first == "offset") { - keyValue.second.Get( mOffset ); + keyValue.second.Get(mOffset); } - else if( keyValue.first == "size" ) + else if(keyValue.first == "size") { - keyValue.second.Get( mSize ); + keyValue.second.Get(mSize); } - else if( keyValue.first == "origin" ) + else if(keyValue.first == "origin") { - Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin ); + Scripting::GetEnumerationProperty(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mOrigin); } - else if( keyValue.first == "anchorPoint" ) + else if(keyValue.first == "anchorPoint") { - Scripting::GetEnumerationProperty< Toolkit::Align::Type >( keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint ); + Scripting::GetEnumerationProperty(keyValue.second, ALIGN_TABLE, ALIGN_TABLE_COUNT, mAnchorPoint); } - else if( keyValue.first == "offsetPolicy" ) + else if(keyValue.first == "offsetPolicy") { Vector2 policy; - if( GetPolicyFromValue( keyValue.second, policy ) ) + if(GetPolicyFromValue(keyValue.second, policy)) { mOffsetSizeMode.x = policy.x; mOffsetSizeMode.y = policy.y; } } - else if( keyValue.first == "sizePolicy" ) + else if(keyValue.first == "sizePolicy") { Vector2 policy; - if( GetPolicyFromValue( keyValue.second, policy ) ) + if(GetPolicyFromValue(keyValue.second, policy)) { mOffsetSizeMode.z = policy.x; mOffsetSizeMode.w = policy.y; } } - else if( keyValue.first == "extraSize" ) + else if(keyValue.first == "extraSize") { - keyValue.second.Get( mExtraSize ); + keyValue.second.Get(mExtraSize); } } } } -void Internal::Visual::Base::Impl::Transform::GetPropertyMap( Property::Map& map ) const +void Internal::Visual::Base::Impl::Transform::GetPropertyMap(Property::Map& map) const { map.Clear(); - map.Add( Toolkit::Visual::Transform::Property::OFFSET, mOffset ) - .Add( Toolkit::Visual::Transform::Property::SIZE, mSize ) - .Add( Toolkit::Visual::Transform::Property::ORIGIN, mOrigin ) - .Add( Toolkit::Visual::Transform::Property::ANCHOR_POINT, mAnchorPoint ) - .Add( Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2( mOffsetSizeMode.x, mOffsetSizeMode.y ) ) - .Add( Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2( mOffsetSizeMode.z, mOffsetSizeMode.w ) ) - .Add( Toolkit::DevelVisual::Transform::Property::EXTRA_SIZE, mExtraSize ); + map.Add(Toolkit::Visual::Transform::Property::OFFSET, mOffset) + .Add(Toolkit::Visual::Transform::Property::SIZE, mSize) + .Add(Toolkit::Visual::Transform::Property::ORIGIN, mOrigin) + .Add(Toolkit::Visual::Transform::Property::ANCHOR_POINT, mAnchorPoint) + .Add(Toolkit::Visual::Transform::Property::OFFSET_POLICY, Vector2(mOffsetSizeMode.x, mOffsetSizeMode.y)) + .Add(Toolkit::Visual::Transform::Property::SIZE_POLICY, Vector2(mOffsetSizeMode.z, mOffsetSizeMode.w)) + .Add(Toolkit::DevelVisual::Transform::Property::EXTRA_SIZE, mExtraSize); } -void Internal::Visual::Base::Impl::Transform::RegisterUniforms( Dali::Renderer renderer, Toolkit::Direction::Type direction ) +void Internal::Visual::Base::Impl::Transform::RegisterUniforms(Dali::Renderer renderer, Toolkit::Direction::Type direction) { mSizeIndex = renderer.RegisterProperty(SIZE, mSize); mOffsetIndex = renderer.RegisterProperty(OFFSET, direction == Toolkit::Direction::LEFT_TO_RIGHT ? mOffset : mOffset * Vector2(-1.0f, 1.0f)); - renderer.RegisterProperty( OFFSET_SIZE_MODE, mOffsetSizeMode ); - renderer.RegisterProperty( ORIGIN, PointToVector2( mOrigin, direction ) - Vector2(0.5,0.5) ); - renderer.RegisterProperty( ANCHOR_POINT, Vector2(0.5,0.5) - PointToVector2( mAnchorPoint, direction ) ); - renderer.RegisterProperty( EXTRA_SIZE, mExtraSize ); + renderer.RegisterProperty(OFFSET_SIZE_MODE, mOffsetSizeMode); + renderer.RegisterProperty(ORIGIN, PointToVector2(mOrigin, direction) - Vector2(0.5, 0.5)); + renderer.RegisterProperty(ANCHOR_POINT, Vector2(0.5, 0.5) - PointToVector2(mAnchorPoint, direction)); + renderer.RegisterProperty(EXTRA_SIZE, mExtraSize); } -Vector2 Internal::Visual::Base::Impl::Transform::GetVisualSize( const Vector2& controlSize ) +Vector2 Internal::Visual::Base::Impl::Transform::GetVisualSize(const Vector2& controlSize) { - return Vector2( Lerp( mOffsetSizeMode.z, mSize.x * controlSize.x, mSize.x ) , - Lerp( mOffsetSizeMode.w, mSize.y * controlSize.y, mSize.y ) ) + mExtraSize; + return Vector2(Lerp(mOffsetSizeMode.z, mSize.x * controlSize.x, mSize.x), + Lerp(mOffsetSizeMode.w, mSize.y * controlSize.y, mSize.y)) + + mExtraSize; } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/visual-base-impl.cpp b/dali-toolkit/internal/visuals/visual-base-impl.cpp old mode 100755 new mode 100644 index a814d6b..331eaf5 --- a/dali-toolkit/internal/visuals/visual-base-impl.cpp +++ b/dali-toolkit/internal/visuals/visual-base-impl.cpp @@ -20,55 +20,51 @@ // EXTERNAL HEADER #include -#include #include +#include #include //INTERNAL HEARDER -#include -#include -#include #include #include #include #include +#include +#include +#include namespace { #if defined(DEBUG_ENABLED) -Debug::Filter* gVisualBaseLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_VISUAL_BASE" ); +Debug::Filter* gVisualBaseLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VISUAL_BASE"); #endif -const char * const PRE_MULTIPLIED_ALPHA_PROPERTY( "preMultipliedAlpha" ); +const char* const PRE_MULTIPLIED_ALPHA_PROPERTY("preMultipliedAlpha"); } // namespace namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - -DALI_ENUM_TO_STRING_TABLE_BEGIN( VISUAL_FITTING_MODE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FIT_KEEP_ASPECT_RATIO ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FILL ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, OVER_FIT_KEEP_ASPECT_RATIO ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, CENTER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FIT_WIDTH ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Visual::FittingMode, FIT_HEIGHT ) -DALI_ENUM_TO_STRING_TABLE_END( VISUAL_FITTING_MODE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(VISUAL_FITTING_MODE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FIT_KEEP_ASPECT_RATIO) + DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FILL) + DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, OVER_FIT_KEEP_ASPECT_RATIO) + DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, CENTER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FIT_WIDTH) + DALI_ENUM_TO_STRING_WITH_SCOPE(Visual::FittingMode, FIT_HEIGHT) +DALI_ENUM_TO_STRING_TABLE_END(VISUAL_FITTING_MODE) } // namespace -Visual::Base::Base( VisualFactoryCache& factoryCache, FittingMode fittingMode, Toolkit::Visual::Type type ) -: mImpl( new Impl( fittingMode, type ) ), - mFactoryCache( factoryCache ) +Visual::Base::Base(VisualFactoryCache& factoryCache, FittingMode fittingMode, Toolkit::Visual::Type type) +: mImpl(new Impl(fittingMode, type)), + mFactoryCache(factoryCache) { } @@ -96,74 +92,74 @@ void Visual::Base::Initialize() } } -void Visual::Base::SetCustomShader( const Property::Map& shaderMap ) +void Visual::Base::SetCustomShader(const Property::Map& shaderMap) { - if( mImpl->mCustomShader ) + if(mImpl->mCustomShader) { - mImpl->mCustomShader->SetPropertyMap( shaderMap ); + mImpl->mCustomShader->SetPropertyMap(shaderMap); } else { - mImpl->mCustomShader = new Impl::CustomShader( shaderMap ); + mImpl->mCustomShader = new Impl::CustomShader(shaderMap); } // Let derived class know UpdateShader(); } -void Visual::Base::SetProperties( const Property::Map& propertyMap ) +void Visual::Base::SetProperties(const Property::Map& propertyMap) { - for( size_t i = 0; i < propertyMap.Count(); ++i ) + for(size_t i = 0; i < propertyMap.Count(); ++i) { - const KeyValuePair& pair = propertyMap.GetKeyValue( i ); - const Property::Key& key = pair.first; + const KeyValuePair& pair = propertyMap.GetKeyValue(i); + const Property::Key& key = pair.first; const Property::Value& value = pair.second; Property::Key matchKey = key; - if( matchKey.type == Property::Key::STRING ) + if(matchKey.type == Property::Key::STRING) { - if( matchKey == CUSTOM_SHADER ) + if(matchKey == CUSTOM_SHADER) { - matchKey = Property::Key( Toolkit::Visual::Property::SHADER ); + matchKey = Property::Key(Toolkit::Visual::Property::SHADER); } - else if( matchKey == TRANSFORM ) + else if(matchKey == TRANSFORM) { - matchKey = Property::Key( Toolkit::Visual::Property::TRANSFORM ); + matchKey = Property::Key(Toolkit::Visual::Property::TRANSFORM); } - else if( matchKey == PREMULTIPLIED_ALPHA ) + else if(matchKey == PREMULTIPLIED_ALPHA) { - matchKey = Property::Key( Toolkit::Visual::Property::PREMULTIPLIED_ALPHA ); + matchKey = Property::Key(Toolkit::Visual::Property::PREMULTIPLIED_ALPHA); } - else if( matchKey == MIX_COLOR ) + else if(matchKey == MIX_COLOR) { - matchKey = Property::Key( Toolkit::Visual::Property::MIX_COLOR ); + matchKey = Property::Key(Toolkit::Visual::Property::MIX_COLOR); } - else if( matchKey == OPACITY ) + else if(matchKey == OPACITY) { - matchKey = Property::Key( Toolkit::Visual::Property::OPACITY ); + matchKey = Property::Key(Toolkit::Visual::Property::OPACITY); } - else if( matchKey == VISUAL_FITTING_MODE ) + else if(matchKey == VISUAL_FITTING_MODE) { - matchKey = Property::Key( Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE ); + matchKey = Property::Key(Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE); } - else if( matchKey == CORNER_RADIUS ) + else if(matchKey == CORNER_RADIUS) { - matchKey = Property::Key( Toolkit::DevelVisual::Property::CORNER_RADIUS ); + matchKey = Property::Key(Toolkit::DevelVisual::Property::CORNER_RADIUS); } - else if( matchKey == CORNER_RADIUS_POLICY ) + else if(matchKey == CORNER_RADIUS_POLICY) { - matchKey = Property::Key( Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY ); + matchKey = Property::Key(Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY); } } - switch( matchKey.indexKey ) + switch(matchKey.indexKey) { case Toolkit::Visual::Property::SHADER: { Property::Map shaderMap; - if( value.Get( shaderMap ) ) + if(value.Get(shaderMap)) { - SetCustomShader( shaderMap ); + SetCustomShader(shaderMap); } break; } @@ -171,9 +167,9 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) case Toolkit::Visual::Property::TRANSFORM: { Property::Map map; - if( value.Get( map ) ) + if(value.Get(map)) { - mImpl->mTransform.SetPropertyMap( map ); + mImpl->mTransform.SetPropertyMap(map); } break; } @@ -181,9 +177,9 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) case Toolkit::Visual::Property::PREMULTIPLIED_ALPHA: { bool premultipliedAlpha = false; - if( value.Get( premultipliedAlpha ) ) + if(value.Get(premultipliedAlpha)) { - EnablePreMultipliedAlpha( premultipliedAlpha ); + EnablePreMultipliedAlpha(premultipliedAlpha); } break; } @@ -191,16 +187,16 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) case Toolkit::Visual::Property::MIX_COLOR: { Vector4 mixColor; - if( value.Get( mixColor ) ) + if(value.Get(mixColor)) { - if( value.GetType() == Property::VECTOR4 ) + if(value.GetType() == Property::VECTOR4) { - SetMixColor( mixColor ); + SetMixColor(mixColor); } else { Vector3 mixColor3(mixColor); - SetMixColor( mixColor3 ); + SetMixColor(mixColor3); } } break; @@ -208,23 +204,23 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) case Toolkit::Visual::Property::OPACITY: { float opacity; - if( value.Get( opacity ) ) + if(value.Get(opacity)) { mImpl->mMixColor.a = opacity; - SetMixColor( mImpl->mMixColor ); + SetMixColor(mImpl->mMixColor); } break; } case Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE: { - Scripting::GetEnumerationProperty< Visual::FittingMode >( - value, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT, mImpl->mFittingMode ); + Scripting::GetEnumerationProperty( + value, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT, mImpl->mFittingMode); break; } case Toolkit::DevelVisual::Property::CORNER_RADIUS: { float radius; - if( value.Get( radius ) ) + if(value.Get(radius)) { mImpl->mCornerRadius = radius; } @@ -233,9 +229,9 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) case Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY: { int policy; - if( value.Get( policy ) ) + if(value.Get(policy)) { - switch( policy ) + switch(policy) { case Toolkit::Visual::Transform::Policy::RELATIVE: case Toolkit::Visual::Transform::Policy::ABSOLUTE: @@ -245,7 +241,7 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) } default: { - DALI_LOG_ERROR( "Unsupported policy: %d\n", policy ); + DALI_LOG_ERROR("Unsupported policy: %d\n", policy); break; } } @@ -255,25 +251,24 @@ void Visual::Base::SetProperties( const Property::Map& propertyMap ) } } - DoSetProperties( propertyMap ); + DoSetProperties(propertyMap); } -void Visual::Base::SetTransformAndSize( const Property::Map& transform, Size controlSize ) +void Visual::Base::SetTransformAndSize(const Property::Map& transform, Size controlSize) { mImpl->mControlSize = controlSize; - mImpl->mTransform.UpdatePropertyMap( transform ); + mImpl->mTransform.UpdatePropertyMap(transform); #if defined(DEBUG_ENABLED) std::ostringstream oss; oss << transform; - DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, "Visual::Base::SetTransformAndSize(%s) - [\e[1;32mtransform: %s controlSize: (%3.1f, %3.1f)]\e[0m\n", - GetName().c_str(), oss.str().c_str(), controlSize.x, controlSize.y ); + DALI_LOG_INFO(gVisualBaseLogFilter, Debug::General, "Visual::Base::SetTransformAndSize(%s) - [\e[1;32mtransform: %s controlSize: (%3.1f, %3.1f)]\e[0m\n", GetName().c_str(), oss.str().c_str(), controlSize.x, controlSize.y); #endif OnSetTransform(); } -void Visual::Base::SetName( const std::string& name ) +void Visual::Base::SetName(const std::string& name) { mImpl->mName = name; } @@ -283,46 +278,46 @@ const std::string& Visual::Base::GetName() const return mImpl->mName; } -float Visual::Base::GetHeightForWidth( float width ) +float Visual::Base::GetHeightForWidth(float width) { - float aspectCorrectedHeight = 0.f; + float aspectCorrectedHeight = 0.f; Vector2 naturalSize; - GetNaturalSize( naturalSize ); - if( naturalSize.width ) + GetNaturalSize(naturalSize); + if(naturalSize.width) { aspectCorrectedHeight = naturalSize.height * width / naturalSize.width; } return aspectCorrectedHeight; } -float Visual::Base::GetWidthForHeight( float height ) +float Visual::Base::GetWidthForHeight(float height) { - float aspectCorrectedWidth = 0.f; + float aspectCorrectedWidth = 0.f; Vector2 naturalSize; - GetNaturalSize( naturalSize ); - if( naturalSize.height > 0.0f ) + GetNaturalSize(naturalSize); + if(naturalSize.height > 0.0f) { aspectCorrectedWidth = naturalSize.width * height / naturalSize.height; } return aspectCorrectedWidth; } -void Visual::Base::GetNaturalSize( Vector2& naturalSize ) +void Visual::Base::GetNaturalSize(Vector2& naturalSize) { naturalSize = Vector2::ZERO; } -void Visual::Base::DoAction( const Property::Index actionId, const Property::Value attributes ) +void Visual::Base::DoAction(const Property::Index actionId, const Property::Value attributes) { - OnDoAction( actionId, attributes ); + OnDoAction(actionId, attributes); } -void Visual::Base::SetDepthIndex( int index ) +void Visual::Base::SetDepthIndex(int index) { mImpl->mDepthIndex = index; - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( Renderer::Property::DEPTH_INDEX, mImpl->mDepthIndex ); + mImpl->mRenderer.SetProperty(Renderer::Property::DEPTH_INDEX, mImpl->mDepthIndex); } } @@ -331,13 +326,13 @@ int Visual::Base::GetDepthIndex() const return mImpl->mDepthIndex; } -void Visual::Base::SetOnScene( Actor& actor ) +void Visual::Base::SetOnScene(Actor& actor) { - if( !IsOnScene() ) + if(!IsOnScene()) { // To display the actor correctly, renderer should not be added to actor until all required resources are ready. // Thus the calling of actor.AddRenderer() should happen inside derived class as base class does not know the exact timing. - DoSetOnScene( actor ); + DoSetOnScene(actor); if(mImpl->mRenderer) { @@ -349,16 +344,16 @@ void Visual::Base::SetOnScene( Actor& actor ) } } -void Visual::Base::SetOffScene( Actor& actor ) +void Visual::Base::SetOffScene(Actor& actor) { - if( IsOnScene() ) + if(IsOnScene()) { - DoSetOffScene( actor ); + DoSetOffScene(actor); mImpl->mFlags &= ~Impl::IS_ON_SCENE; } } -void Visual::Base::CreatePropertyMap( Property::Map& map ) const +void Visual::Base::CreatePropertyMap(Property::Map& map) const { if(mImpl->mRenderer) { @@ -387,39 +382,38 @@ void Visual::Base::CreatePropertyMap( Property::Map& map ) const } Property::Map transform; - mImpl->mTransform.GetPropertyMap( transform ); - map.Insert( Toolkit::Visual::Property::TRANSFORM, transform ); + mImpl->mTransform.GetPropertyMap(transform); + map.Insert(Toolkit::Visual::Property::TRANSFORM, transform); - bool premultipliedAlpha( IsPreMultipliedAlphaEnabled() ); - map.Insert( Toolkit::Visual::Property::PREMULTIPLIED_ALPHA, premultipliedAlpha ); + bool premultipliedAlpha(IsPreMultipliedAlphaEnabled()); + map.Insert(Toolkit::Visual::Property::PREMULTIPLIED_ALPHA, premultipliedAlpha); // Note, Color and Primitive will also insert their own mix color into the map // which is ok, because they have a different key value range. - map.Insert( Toolkit::Visual::Property::MIX_COLOR, mImpl->mMixColor ); // vec4 - map.Insert( Toolkit::Visual::Property::OPACITY, mImpl->mMixColor.a ); + map.Insert(Toolkit::Visual::Property::MIX_COLOR, mImpl->mMixColor); // vec4 + map.Insert(Toolkit::Visual::Property::OPACITY, mImpl->mMixColor.a); - auto fittingModeString = Scripting::GetLinearEnumerationName< FittingMode >( - mImpl->mFittingMode, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT ); - map.Insert( Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE, fittingModeString ); + auto fittingModeString = Scripting::GetLinearEnumerationName( + mImpl->mFittingMode, VISUAL_FITTING_MODE_TABLE, VISUAL_FITTING_MODE_TABLE_COUNT); + map.Insert(Toolkit::DevelVisual::Property::VISUAL_FITTING_MODE, fittingModeString); - map.Insert( Toolkit::DevelVisual::Property::CORNER_RADIUS, mImpl->mCornerRadius ); - map.Insert( Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, static_cast< int >( mImpl->mCornerRadiusPolicy ) ); + map.Insert(Toolkit::DevelVisual::Property::CORNER_RADIUS, mImpl->mCornerRadius); + map.Insert(Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, static_cast(mImpl->mCornerRadiusPolicy)); } -void Visual::Base::CreateInstancePropertyMap( Property::Map& map ) const +void Visual::Base::CreateInstancePropertyMap(Property::Map& map) const { - DoCreateInstancePropertyMap( map ); + DoCreateInstancePropertyMap(map); - if( mImpl->mCustomShader ) + if(mImpl->mCustomShader) { - mImpl->mCustomShader->CreatePropertyMap( map ); + mImpl->mCustomShader->CreatePropertyMap(map); } } - -void Visual::Base::EnablePreMultipliedAlpha( bool preMultiplied ) +void Visual::Base::EnablePreMultipliedAlpha(bool preMultiplied) { - if( preMultiplied ) + if(preMultiplied) { mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA; } @@ -428,10 +422,10 @@ void Visual::Base::EnablePreMultipliedAlpha( bool preMultiplied ) mImpl->mFlags &= ~Impl::IS_PREMULTIPLIED_ALPHA; } - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_PRE_MULTIPLIED_ALPHA, preMultiplied); - mImpl->mRenderer.RegisterProperty( PRE_MULTIPLIED_ALPHA_PROPERTY, static_cast( preMultiplied ) ); + mImpl->mRenderer.RegisterProperty(PRE_MULTIPLIED_ALPHA_PROPERTY, static_cast(preMultiplied)); } } @@ -440,9 +434,9 @@ bool Visual::Base::IsPreMultipliedAlphaEnabled() const return mImpl->mFlags & Impl::IS_PREMULTIPLIED_ALPHA; } -void Visual::Base::DoSetOffScene( Actor& actor ) +void Visual::Base::DoSetOffScene(Actor& actor) { - actor.RemoveRenderer( mImpl->mRenderer ); + actor.RemoveRenderer(mImpl->mRenderer); } bool Visual::Base::IsOnScene() const @@ -460,7 +454,7 @@ bool Visual::Base::IsRoundedCornerRequired() const return !EqualsZero(mImpl->mCornerRadius) || mImpl->mNeedCornerRadius; } -void Visual::Base::OnDoAction( const Property::Index actionId, const Property::Value& attributes ) +void Visual::Base::OnDoAction(const Property::Index actionId, const Property::Value& attributes) { // May be overriden by derived class } @@ -469,79 +463,79 @@ void Visual::Base::RegisterMixColor() { // Only register if not already registered. // (Color and Primitive visuals will register their own and save to this index) - if( mImpl->mMixColorIndex == Property::INVALID_INDEX ) + if(mImpl->mMixColorIndex == Property::INVALID_INDEX) { mImpl->mMixColorIndex = mImpl->mRenderer.RegisterProperty( Toolkit::Visual::Property::MIX_COLOR, MIX_COLOR, - Vector3(mImpl->mMixColor) ); + Vector3(mImpl->mMixColor)); } - mImpl->mRenderer.SetProperty( DevelRenderer::Property::OPACITY, mImpl->mMixColor.a ); + mImpl->mRenderer.SetProperty(DevelRenderer::Property::OPACITY, mImpl->mMixColor.a); float preMultipliedAlpha = 0.0f; - if( IsPreMultipliedAlphaEnabled() ) + if(IsPreMultipliedAlphaEnabled()) { preMultipliedAlpha = 1.0f; } - mImpl->mRenderer.RegisterProperty( PRE_MULTIPLIED_ALPHA_PROPERTY, preMultipliedAlpha ); + mImpl->mRenderer.RegisterProperty(PRE_MULTIPLIED_ALPHA_PROPERTY, preMultipliedAlpha); } -void Visual::Base::SetMixColor( const Vector4& color ) +void Visual::Base::SetMixColor(const Vector4& color) { mImpl->mMixColor = color; - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( mImpl->mMixColorIndex, Vector3(color) ); - mImpl->mRenderer.SetProperty( DevelRenderer::Property::OPACITY, color.a ); + mImpl->mRenderer.SetProperty(mImpl->mMixColorIndex, Vector3(color)); + mImpl->mRenderer.SetProperty(DevelRenderer::Property::OPACITY, color.a); } } -void Visual::Base::SetMixColor( const Vector3& color ) +void Visual::Base::SetMixColor(const Vector3& color) { mImpl->mMixColor.r = color.r; mImpl->mMixColor.g = color.g; mImpl->mMixColor.b = color.b; - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - mImpl->mRenderer.SetProperty( mImpl->mMixColorIndex, color ); + mImpl->mRenderer.SetProperty(mImpl->mMixColorIndex, color); } } -void Visual::Base::AddEventObserver( Visual::EventObserver& observer) +void Visual::Base::AddEventObserver(Visual::EventObserver& observer) { mImpl->mEventObserver = &observer; } -void Visual::Base::RemoveEventObserver( Visual::EventObserver& observer ) +void Visual::Base::RemoveEventObserver(Visual::EventObserver& observer) { mImpl->mEventObserver = NULL; } void Visual::Base::ResourceReady(Toolkit::Visual::ResourceStatus resourceStatus) { - if( mImpl->mResourceStatus != resourceStatus ) + if(mImpl->mResourceStatus != resourceStatus) { mImpl->mResourceStatus = resourceStatus; - if( mImpl->mEventObserver ) + if(mImpl->mEventObserver) { // observer is currently a control impl - mImpl->mEventObserver->ResourceReady( *this ); + mImpl->mEventObserver->ResourceReady(*this); } } } bool Visual::Base::IsResourceReady() const { - return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ); + return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY); } bool Visual::Base::IsSynchronousLoadingRequired() const { - return ( mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING ); + return (mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING); } Toolkit::Visual::Type Visual::Base::GetType() const @@ -569,24 +563,24 @@ Renderer Visual::Base::GetRenderer() return mImpl->mRenderer; } -Property::Index Visual::Base::GetPropertyIndex( Property::Key key ) +Property::Index Visual::Base::GetPropertyIndex(Property::Key key) { - Property::Index index = mImpl->mRenderer.GetPropertyIndex( key ); + Property::Index index = mImpl->mRenderer.GetPropertyIndex(key); - if( index == Property::INVALID_INDEX ) + if(index == Property::INVALID_INDEX) { // Is it a shader property? Shader shader = mImpl->mRenderer.GetShader(); - index = shader.GetPropertyIndex( key ); - if( index != Property::INVALID_INDEX ) + index = shader.GetPropertyIndex(key); + if(index != Property::INVALID_INDEX) { // Yes - we should register it in the Renderer so it can be set / animated // independently, as shaders are shared across multiple renderers. - std::string keyName; - Property::Index keyIndex( Property::INVALID_KEY ); - if( key.type == Property::Key::INDEX ) + std::string keyName; + Property::Index keyIndex(Property::INVALID_KEY); + if(key.type == Property::Key::INDEX) { - keyName = shader.GetPropertyName( index ); + keyName = shader.GetPropertyName(index); keyIndex = key.indexKey; } else @@ -594,59 +588,59 @@ Property::Index Visual::Base::GetPropertyIndex( Property::Key key ) keyName = key.stringKey; // Leave keyIndex as INVALID_KEY - it can still be registered against the string key. } - Property::Value value = shader.GetProperty( index ); - index = mImpl->mRenderer.RegisterProperty( keyIndex, keyName, value ); + Property::Value value = shader.GetProperty(index); + index = mImpl->mRenderer.RegisterProperty(keyIndex, keyName, value); } } return index; } void Visual::Base::SetupTransition( - Dali::Animation& transition, + Dali::Animation& transition, Internal::TransitionData::Animator& animator, - Property::Index index, - Property::Value& initialValue, - Property::Value& targetValue ) + Property::Index index, + Property::Value& initialValue, + Property::Value& targetValue) { - if( index != Property::INVALID_INDEX ) + if(index != Property::INVALID_INDEX) { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { - if( animator.animate == false ) + if(animator.animate == false) { - mImpl->mRenderer.SetProperty( index, targetValue ); + mImpl->mRenderer.SetProperty(index, targetValue); } else { - if( animator.initialValue.GetType() != Property::NONE ) + if(animator.initialValue.GetType() != Property::NONE) { - mImpl->mRenderer.SetProperty( index, initialValue ); + mImpl->mRenderer.SetProperty(index, initialValue); } - if( ! transition ) + if(!transition) { - transition = Dali::Animation::New( 0.1f ); + transition = Dali::Animation::New(0.1f); } - transition.AnimateTo( Property( mImpl->mRenderer, index ), - targetValue, - animator.alphaFunction, - TimePeriod( animator.timePeriodDelay, - animator.timePeriodDuration ) ); + transition.AnimateTo(Property(mImpl->mRenderer, index), + targetValue, + animator.alphaFunction, + TimePeriod(animator.timePeriodDelay, + animator.timePeriodDuration)); } } } } void Visual::Base::AnimateProperty( - Dali::Animation& transition, - Internal::TransitionData::Animator& animator ) + Dali::Animation& transition, + Internal::TransitionData::Animator& animator) { #if defined(DEBUG_ENABLED) { std::ostringstream oss; oss << "Visual::Base::AnimateProperty(Visual:" << mImpl->mName << " Property:" << animator.propertyKey << " Target: " << animator.targetValue << std::endl; - DALI_LOG_INFO( gVisualBaseLogFilter, Debug::General, oss.str().c_str() ); + DALI_LOG_INFO(gVisualBaseLogFilter, Debug::General, oss.str().c_str()); } #endif @@ -657,107 +651,107 @@ void Visual::Base::AnimateProperty( (mImpl->mType == Toolkit::Visual::PRIMITIVE && animator.propertyKey == PrimitiveVisual::Property::MIX_COLOR)) { - AnimateMixColorProperty( transition, animator ); + AnimateMixColorProperty(transition, animator); } else if(animator.propertyKey == Toolkit::Visual::Property::OPACITY || - animator.propertyKey == OPACITY ) + animator.propertyKey == OPACITY) { - AnimateOpacityProperty( transition, animator ); + AnimateOpacityProperty(transition, animator); } - else if( mImpl->mRenderer ) + else if(mImpl->mRenderer) { - AnimateRendererProperty( transition, animator ); + AnimateRendererProperty(transition, animator); } } void Visual::Base::AnimateOpacityProperty( - Dali::Animation& transition, - Internal::TransitionData::Animator& animator ) + Dali::Animation& transition, + Internal::TransitionData::Animator& animator) { float targetOpacity; - if( animator.targetValue.Get( targetOpacity ) ) + if(animator.targetValue.Get(targetOpacity)) { mImpl->mMixColor.a = targetOpacity; } - SetupTransition( transition, animator, DevelRenderer::Property::OPACITY, animator.initialValue, animator.targetValue ); + SetupTransition(transition, animator, DevelRenderer::Property::OPACITY, animator.initialValue, animator.targetValue); } void Visual::Base::AnimateRendererProperty( - Dali::Animation& transition, - Internal::TransitionData::Animator& animator ) + Dali::Animation& transition, + Internal::TransitionData::Animator& animator) { - Property::Index index = GetPropertyIndex( animator.propertyKey ); - if( index != Property::INVALID_INDEX ) + Property::Index index = GetPropertyIndex(animator.propertyKey); + if(index != Property::INVALID_INDEX) { - if( animator.targetValue.GetType() != Property::NONE ) + if(animator.targetValue.GetType() != Property::NONE) { // Try writing target value into transform property map // if it's not a valid key, then it won't alter mTransform Property::Map map; - if( animator.propertyKey.type == Property::Key::INDEX ) + if(animator.propertyKey.type == Property::Key::INDEX) { - map.Add( animator.propertyKey.indexKey, animator.targetValue ); + map.Add(animator.propertyKey.indexKey, animator.targetValue); } else { - map.Add( animator.propertyKey.stringKey, animator.targetValue ); + map.Add(animator.propertyKey.stringKey, animator.targetValue); } - mImpl->mTransform.UpdatePropertyMap( map ); + mImpl->mTransform.UpdatePropertyMap(map); } - SetupTransition( transition, animator, index, animator.initialValue, animator.targetValue ); + SetupTransition(transition, animator, index, animator.initialValue, animator.targetValue); } } void Visual::Base::AnimateMixColorProperty( - Dali::Animation& transition, - Internal::TransitionData::Animator& animator ) + Dali::Animation& transition, + Internal::TransitionData::Animator& animator) { - Property::Index index = mImpl->mMixColorIndex; - bool animateOpacity = false; + Property::Index index = mImpl->mMixColorIndex; + bool animateOpacity = false; Property::Value initialOpacity; Property::Value targetOpacity; Property::Value initialMixColor; Property::Value targetMixColor; - if( index != Property::INVALID_INDEX ) + if(index != Property::INVALID_INDEX) { Vector4 initialColor; - if( animator.initialValue.Get(initialColor) ) + if(animator.initialValue.Get(initialColor)) { - if( animator.initialValue.GetType() == Property::VECTOR4 ) + if(animator.initialValue.GetType() == Property::VECTOR4) { // if there is an initial color specifying alpha, test it initialOpacity = initialColor.a; } - initialMixColor = Vector3( initialColor ); + initialMixColor = Vector3(initialColor); } // Set target value into data store - if( animator.targetValue.GetType() != Property::NONE ) + if(animator.targetValue.GetType() != Property::NONE) { Vector4 mixColor; animator.targetValue.Get(mixColor); - if( animator.targetValue.GetType() == Property::VECTOR4 ) + if(animator.targetValue.GetType() == Property::VECTOR4) { mImpl->mMixColor.a = mixColor.a; - targetOpacity = mixColor.a; - animateOpacity = true; + targetOpacity = mixColor.a; + animateOpacity = true; } mImpl->mMixColor.r = mixColor.r; mImpl->mMixColor.g = mixColor.g; mImpl->mMixColor.b = mixColor.b; - targetMixColor = Vector3(mixColor); + targetMixColor = Vector3(mixColor); } - SetupTransition( transition, animator, index, initialMixColor, targetMixColor ); - if( animateOpacity ) + SetupTransition(transition, animator, index, initialMixColor, targetMixColor); + if(animateOpacity) { - SetupTransition( transition, animator, DevelRenderer::Property::OPACITY, initialOpacity, targetOpacity ); + SetupTransition(transition, animator, DevelRenderer::Property::OPACITY, initialOpacity, targetOpacity); } } } @@ -822,7 +816,7 @@ Dali::Property Visual::Base::GetPropertyObject(Dali::Property::Key key) mImpl->mRenderer.SetProperty(Renderer::Property::BLEND_MODE, BlendMode::ON); - index = mImpl->mCornerRadiusIndex; + index = mImpl->mCornerRadiusIndex; mImpl->mNeedCornerRadius = true; // Change shader diff --git a/dali-toolkit/internal/visuals/visual-factory-cache.cpp b/dali-toolkit/internal/visuals/visual-factory-cache.cpp index e6a0efd..b4fde0a 100644 --- a/dali-toolkit/internal/visuals/visual-factory-cache.cpp +++ b/dali-toolkit/internal/visuals/visual-factory-cache.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,40 +18,37 @@ #include "visual-factory-cache.h" // EXTERNAL INCLUDES -#include #include +#include // INTERNAL INCLUDES +#include #include -#include #include -#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - -VisualFactoryCache::VisualFactoryCache( bool preMultiplyOnLoad ) -: mSvgRasterizeThread( NULL ), +VisualFactoryCache::VisualFactoryCache(bool preMultiplyOnLoad) +: mSvgRasterizeThread(NULL), mVectorAnimationManager(), mBrokenImageUrl(""), - mPreMultiplyOnLoad( preMultiplyOnLoad ) + mPreMultiplyOnLoad(preMultiplyOnLoad) { } VisualFactoryCache::~VisualFactoryCache() { - SvgRasterizeThread::TerminateThread( mSvgRasterizeThread ); + SvgRasterizeThread::TerminateThread(mSvgRasterizeThread); } -Geometry VisualFactoryCache::GetGeometry( GeometryType type ) +Geometry VisualFactoryCache::GetGeometry(GeometryType type) { - if( !mGeometry[type] && type == QUAD_GEOMETRY ) + if(!mGeometry[type] && type == QUAD_GEOMETRY) { mGeometry[type] = CreateQuadGeometry(); } @@ -59,53 +56,55 @@ Geometry VisualFactoryCache::GetGeometry( GeometryType type ) return mGeometry[type]; } -void VisualFactoryCache::SaveGeometry( GeometryType type, Geometry geometry ) +void VisualFactoryCache::SaveGeometry(GeometryType type, Geometry geometry) { mGeometry[type] = geometry; } -Shader VisualFactoryCache::GetShader( ShaderType type ) +Shader VisualFactoryCache::GetShader(ShaderType type) { return mShader[type]; } -void VisualFactoryCache::SaveShader( ShaderType type, Shader shader ) +void VisualFactoryCache::SaveShader(ShaderType type, Shader shader) { mShader[type] = shader; } Geometry VisualFactoryCache::CreateQuadGeometry() { - const float halfWidth = 0.5f; + const float halfWidth = 0.5f; const float halfHeight = 0.5f; - struct QuadVertex { Vector2 position;}; - QuadVertex quadVertexData[4] = + struct QuadVertex { - { Vector2(-halfWidth, -halfHeight) }, - { Vector2(-halfWidth, halfHeight) }, - { Vector2( halfWidth, -halfHeight) }, - { Vector2( halfWidth, halfHeight) } + Vector2 position; }; + QuadVertex quadVertexData[4] = + { + {Vector2(-halfWidth, -halfHeight)}, + {Vector2(-halfWidth, halfHeight)}, + {Vector2(halfWidth, -halfHeight)}, + {Vector2(halfWidth, halfHeight)}}; Property::Map quadVertexFormat; quadVertexFormat["aPosition"] = Property::VECTOR2; - VertexBuffer quadVertices = VertexBuffer::New( quadVertexFormat ); - quadVertices.SetData( quadVertexData, 4 ); + VertexBuffer quadVertices = VertexBuffer::New(quadVertexFormat); + quadVertices.SetData(quadVertexData, 4); // Create the geometry object Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( quadVertices ); - geometry.SetType( Geometry::TRIANGLE_STRIP ); + geometry.AddVertexBuffer(quadVertices); + geometry.SetType(Geometry::TRIANGLE_STRIP); return geometry; } ImageAtlasManagerPtr VisualFactoryCache::GetAtlasManager() { - if( !mAtlasManager ) + if(!mAtlasManager) { mAtlasManager = new ImageAtlasManager(); - mAtlasManager->SetBrokenImage( mBrokenImageUrl ); + mAtlasManager->SetBrokenImage(mBrokenImageUrl); } return mAtlasManager; @@ -123,7 +122,7 @@ NPatchLoader& VisualFactoryCache::GetNPatchLoader() SvgRasterizeThread* VisualFactoryCache::GetSVGRasterizationThread() { - if( !mSvgRasterizeThread ) + if(!mSvgRasterizeThread) { mSvgRasterizeThread = new SvgRasterizeThread(); mSvgRasterizeThread->Start(); @@ -133,78 +132,77 @@ SvgRasterizeThread* VisualFactoryCache::GetSVGRasterizationThread() VectorAnimationManager& VisualFactoryCache::GetVectorAnimationManager() { - if( !mVectorAnimationManager ) + if(!mVectorAnimationManager) { - mVectorAnimationManager = std::unique_ptr< VectorAnimationManager >( new VectorAnimationManager() ); + mVectorAnimationManager = std::unique_ptr(new VectorAnimationManager()); } return *mVectorAnimationManager; } -Geometry VisualFactoryCache::CreateGridGeometry( Uint16Pair gridSize ) +Geometry VisualFactoryCache::CreateGridGeometry(Uint16Pair gridSize) { - uint16_t gridWidth = gridSize.GetWidth(); + uint16_t gridWidth = gridSize.GetWidth(); uint16_t gridHeight = gridSize.GetHeight(); // Create vertices - Vector< Vector2 > vertices; - vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) ); + Vector vertices; + vertices.Reserve((gridWidth + 1) * (gridHeight + 1)); - for( int y = 0; y < gridHeight + 1; ++y ) + for(int y = 0; y < gridHeight + 1; ++y) { - for( int x = 0; x < gridWidth + 1; ++x ) + for(int x = 0; x < gridWidth + 1; ++x) { - vertices.PushBack( Vector2( (float)x/gridWidth - 0.5f, (float)y/gridHeight - 0.5f) ); + vertices.PushBack(Vector2((float)x / gridWidth - 0.5f, (float)y / gridHeight - 0.5f)); } } // Create indices - Vector< unsigned short > indices; - indices.Reserve( (gridWidth+2)*gridHeight*2 - 2); + Vector indices; + indices.Reserve((gridWidth + 2) * gridHeight * 2 - 2); - for( unsigned int row = 0u; row < gridHeight; ++row ) + for(unsigned int row = 0u; row < gridHeight; ++row) { - unsigned int rowStartIndex = row*(gridWidth+1u); - unsigned int nextRowStartIndex = rowStartIndex + gridWidth +1u; + unsigned int rowStartIndex = row * (gridWidth + 1u); + unsigned int nextRowStartIndex = rowStartIndex + gridWidth + 1u; - if( row != 0u ) // degenerate index on non-first row + if(row != 0u) // degenerate index on non-first row { - indices.PushBack( rowStartIndex ); + indices.PushBack(rowStartIndex); } - for( unsigned int column = 0u; column < gridWidth+1u; column++) // main strip + for(unsigned int column = 0u; column < gridWidth + 1u; column++) // main strip { - indices.PushBack( rowStartIndex + column); - indices.PushBack( nextRowStartIndex + column); + indices.PushBack(rowStartIndex + column); + indices.PushBack(nextRowStartIndex + column); } - if( row != gridHeight-1u ) // degenerate index on non-last row + if(row != gridHeight - 1u) // degenerate index on non-last row { - indices.PushBack( nextRowStartIndex + gridWidth ); + indices.PushBack(nextRowStartIndex + gridWidth); } } Property::Map vertexFormat; - vertexFormat[ "aPosition" ] = Property::VECTOR2; - VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat ); - if( vertices.Size() > 0 ) + vertexFormat["aPosition"] = Property::VECTOR2; + VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat); + if(vertices.Size() > 0) { - vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() ); + vertexBuffer.SetData(&vertices[0], vertices.Size()); } Property::Map indexFormat; - indexFormat[ "indices" ] = Property::INTEGER; - VertexBuffer indexVertexBuffer = VertexBuffer::New( indexFormat ); - + indexFormat["indices"] = Property::INTEGER; + VertexBuffer indexVertexBuffer = VertexBuffer::New(indexFormat); // Create the geometry object Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( vertexBuffer ); - if( indices.Size() > 0 ) + geometry.AddVertexBuffer(vertexBuffer); + if(indices.Size() > 0) { - geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() ); + geometry.SetIndexBuffer(&indices[0], indices.Size()); } - geometry.SetType( Geometry::TRIANGLE_STRIP ); + geometry.SetType(Geometry::TRIANGLE_STRIP); return geometry; } @@ -213,20 +211,19 @@ Texture VisualFactoryCache::GetBrokenVisualImage() { if(!mBrokenImageTexture && mBrokenImageUrl.size()) { - PixelData data; - Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl ); - if( pixelBuffer ) + PixelData data; + Devel::PixelBuffer pixelBuffer = LoadImageFromFile(mBrokenImageUrl); + if(pixelBuffer) { - data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer - mBrokenImageTexture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), - data.GetWidth(), data.GetHeight() ); - mBrokenImageTexture.Upload( data ); + data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer + mBrokenImageTexture = Texture::New(Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(), data.GetWidth(), data.GetHeight()); + mBrokenImageTexture.Upload(data); } } return mBrokenImageTexture; } -void VisualFactoryCache::SetPreMultiplyOnLoad( bool preMultiply ) +void VisualFactoryCache::SetPreMultiplyOnLoad(bool preMultiply) { mPreMultiplyOnLoad = preMultiply; } @@ -240,12 +237,12 @@ void VisualFactoryCache::SetBrokenImageUrl(const std::string& brokenImageUrl) { mBrokenImageUrl = brokenImageUrl; - if( !mAtlasManager ) + if(!mAtlasManager) { mAtlasManager = new ImageAtlasManager(); } - mAtlasManager->SetBrokenImage( mBrokenImageUrl ); + mAtlasManager->SetBrokenImage(mBrokenImageUrl); } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/visual-factory-impl.cpp b/dali-toolkit/internal/visuals/visual-factory-impl.cpp index 598f73d..8c4b2f8 100644 --- a/dali-toolkit/internal/visuals/visual-factory-impl.cpp +++ b/dali-toolkit/internal/visuals/visual-factory-impl.cpp @@ -18,51 +18,47 @@ #include // EXTERNAL INCLUDES +#include #include #include -#include #include -#include +#include // INTERNAL INCLUDES #include #include -#include -#include -#include +#include +#include +#include +#include #include #include #include -#include +#include #include #include #include #include #include #include -#include -#include -#include -#include #include -#include #include -#include +#include +#include +#include +#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { - #if defined(DEBUG_ENABLED) -Debug::Filter* gLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_CONTROL_VISUALS"); +Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_CONTROL_VISUALS"); #endif BaseHandle Create() @@ -72,18 +68,18 @@ BaseHandle Create() return handle; } -DALI_TYPE_REGISTRATION_BEGIN_CREATE( Toolkit::VisualFactory, Dali::BaseHandle, Create, true ) +DALI_TYPE_REGISTRATION_BEGIN_CREATE(Toolkit::VisualFactory, Dali::BaseHandle, Create, true) DALI_TYPE_REGISTRATION_END() const char* const BROKEN_IMAGE_FILE_NAME = "broken.png"; ///< The file name of the broken image. } // namespace -VisualFactory::VisualFactory( bool debugEnabled ) +VisualFactory::VisualFactory(bool debugEnabled) : mFactoryCache(), mImageVisualShaderFactory(), mSlotDelegate(this), - mDebugEnabled( debugEnabled ), - mPreMultiplyOnLoad( true ) + mDebugEnabled(debugEnabled), + mPreMultiplyOnLoad(true) { } @@ -91,67 +87,67 @@ VisualFactory::~VisualFactory() { } -void VisualFactory::OnStyleChangedSignal( Toolkit::StyleManager styleManager, StyleChange::Type type) +void VisualFactory::OnStyleChangedSignal(Toolkit::StyleManager styleManager, StyleChange::Type type) { - if( type == StyleChange::THEME_CHANGE ) + if(type == StyleChange::THEME_CHANGE) { - const std::string imageDirPath = AssetManager::GetDaliImagePath(); - std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME; + const std::string imageDirPath = AssetManager::GetDaliImagePath(); + std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME; - Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager ); - config["brokenImageUrl"].Get( brokenImageUrl ); + Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager); + config["brokenImageUrl"].Get(brokenImageUrl); - if( mFactoryCache ) + if(mFactoryCache) { mFactoryCache->SetBrokenImageUrl(brokenImageUrl); } } } -Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& propertyMap ) +Toolkit::Visual::Base VisualFactory::CreateVisual(const Property::Map& propertyMap) { Visual::BasePtr visualPtr; - Property::Value* typeValue = propertyMap.Find( Toolkit::Visual::Property::TYPE, VISUAL_TYPE ); + Property::Value* typeValue = propertyMap.Find(Toolkit::Visual::Property::TYPE, VISUAL_TYPE); Toolkit::DevelVisual::Type visualType = Toolkit::DevelVisual::IMAGE; // Default to IMAGE type. - if( typeValue ) + if(typeValue) { - Scripting::GetEnumerationProperty( *typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType ); + Scripting::GetEnumerationProperty(*typeValue, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT, visualType); } - switch( visualType ) + switch(visualType) { case Toolkit::Visual::BORDER: { - visualPtr = BorderVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = BorderVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::COLOR: { - visualPtr = ColorVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = ColorVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::GRADIENT: { - visualPtr = GradientVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = GradientVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::IMAGE: { - Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME ); - std::string imageUrl; - if( imageURLValue ) + Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME); + std::string imageUrl; + if(imageURLValue) { - if( imageURLValue->Get( imageUrl ) ) + if(imageURLValue->Get(imageUrl)) { - if( !imageUrl.empty() ) + if(!imageUrl.empty()) { - VisualUrl visualUrl( imageUrl ); + VisualUrl visualUrl(imageUrl); - switch( visualUrl.GetType() ) + switch(visualUrl.GetType()) { case VisualUrl::N_PATCH: { @@ -160,23 +156,23 @@ Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& property } case VisualUrl::SVG: { - visualPtr = SvgVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap ); + visualPtr = SvgVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap); break; } case VisualUrl::GIF: case VisualUrl::WEBP: { - visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap ); + visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap); break; } case VisualUrl::JSON: { - visualPtr = AnimatedVectorImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap ); + visualPtr = AnimatedVectorImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap); break; } case VisualUrl::REGULAR_IMAGE: { - visualPtr = ImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap ); + visualPtr = ImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, propertyMap); break; } } @@ -185,9 +181,9 @@ Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& property else { Property::Array* array = imageURLValue->GetArray(); - if( array ) + if(array) { - visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap ); + visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap); } } } @@ -196,33 +192,33 @@ Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& property case Toolkit::Visual::MESH: { - visualPtr = MeshVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = MeshVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::PRIMITIVE: { - visualPtr = PrimitiveVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = PrimitiveVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::WIREFRAME: { - visualPtr = WireframeVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = WireframeVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::TEXT: { - visualPtr = TextVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = TextVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::Visual::N_PATCH: { - Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME ); - std::string imageUrl; - if( imageURLValue && imageURLValue->Get( imageUrl ) ) + Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME); + std::string imageUrl; + if(imageURLValue && imageURLValue->Get(imageUrl)) { visualPtr = NPatchVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap); } @@ -231,31 +227,31 @@ Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& property case Toolkit::Visual::SVG: { - Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME ); - std::string imageUrl; - if( imageURLValue && imageURLValue->Get( imageUrl ) ) + Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME); + std::string imageUrl; + if(imageURLValue && imageURLValue->Get(imageUrl)) { - visualPtr = SvgVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap ); + visualPtr = SvgVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap); } break; } case Toolkit::Visual::ANIMATED_IMAGE: { - Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME ); - std::string imageUrl; - if( imageURLValue ) + Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME); + std::string imageUrl; + if(imageURLValue) { - if( imageURLValue->Get( imageUrl ) ) + if(imageURLValue->Get(imageUrl)) { - visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap ); + visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap); } else { Property::Array* array = imageURLValue->GetArray(); - if( array ) + if(array) { - visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap ); + visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), *array, propertyMap); } } } @@ -264,65 +260,58 @@ Toolkit::Visual::Base VisualFactory::CreateVisual( const Property::Map& property case Toolkit::DevelVisual::ANIMATED_GRADIENT: { - visualPtr = AnimatedGradientVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = AnimatedGradientVisual::New(GetFactoryCache(), propertyMap); break; } case Toolkit::DevelVisual::ANIMATED_VECTOR_IMAGE: { - Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME ); - std::string imageUrl; - if( imageURLValue && imageURLValue->Get( imageUrl ) ) + Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME); + std::string imageUrl; + if(imageURLValue && imageURLValue->Get(imageUrl)) { - visualPtr = AnimatedVectorImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap ); + visualPtr = AnimatedVectorImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), imageUrl, propertyMap); } break; } case Toolkit::DevelVisual::ARC: { - visualPtr = ArcVisual::New( GetFactoryCache(), propertyMap ); + visualPtr = ArcVisual::New(GetFactoryCache(), propertyMap); break; } } - DALI_LOG_INFO( gLogFilter, Debug::Concise, "VisualFactory::CreateVisual( VisualType:%s %s%s)\n", - Scripting::GetEnumerationName( visualType, - VISUAL_TYPE_TABLE, - VISUAL_TYPE_TABLE_COUNT ), - ( visualType == Toolkit::DevelVisual::IMAGE ) ? "url:" : "", - ( visualType == Toolkit::DevelVisual::IMAGE ) ? - ( ([&] (){ - // Return URL if present in PropertyMap else return "not found message" - Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME ); - return ( imageURLValue ) ? imageURLValue->Get().c_str() : "url not found in PropertyMap"; - })() - ) - : "" ); - - if( !visualPtr ) + DALI_LOG_INFO(gLogFilter, Debug::Concise, "VisualFactory::CreateVisual( VisualType:%s %s%s)\n", Scripting::GetEnumerationName(visualType, VISUAL_TYPE_TABLE, VISUAL_TYPE_TABLE_COUNT), (visualType == Toolkit::DevelVisual::IMAGE) ? "url:" : "", (visualType == Toolkit::DevelVisual::IMAGE) ? (([&]() { + // Return URL if present in PropertyMap else return "not found message" + Property::Value* imageURLValue = propertyMap.Find(Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME); + return (imageURLValue) ? imageURLValue->Get().c_str() : "url not found in PropertyMap"; + })()) + : ""); + + if(!visualPtr) { - DALI_LOG_ERROR( "VisualType unknown\n" ); + DALI_LOG_ERROR("VisualType unknown\n"); } - if( mDebugEnabled && visualType != Toolkit::DevelVisual::WIREFRAME ) + if(mDebugEnabled && visualType != Toolkit::DevelVisual::WIREFRAME) { //Create a WireframeVisual if we have debug enabled - visualPtr = WireframeVisual::New(GetFactoryCache(), visualPtr, propertyMap ); + visualPtr = WireframeVisual::New(GetFactoryCache(), visualPtr, propertyMap); } - return Toolkit::Visual::Base( visualPtr.Get() ); + return Toolkit::Visual::Base(visualPtr.Get()); } -Toolkit::Visual::Base VisualFactory::CreateVisual( const std::string& url, ImageDimensions size ) +Toolkit::Visual::Base VisualFactory::CreateVisual(const std::string& url, ImageDimensions size) { Visual::BasePtr visualPtr; - if( !url.empty() ) + if(!url.empty()) { // first resolve url type to know which visual to create - VisualUrl visualUrl( url ); - switch( visualUrl.GetType() ) + VisualUrl visualUrl(url); + switch(visualUrl.GetType()) { case VisualUrl::N_PATCH: { @@ -331,42 +320,42 @@ Toolkit::Visual::Base VisualFactory::CreateVisual( const std::string& url, Image } case VisualUrl::SVG: { - visualPtr = SvgVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl ); + visualPtr = SvgVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl); break; } case VisualUrl::GIF: case VisualUrl::WEBP: { - visualPtr = AnimatedImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl ); + visualPtr = AnimatedImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl); break; } case VisualUrl::JSON: { - visualPtr = AnimatedVectorImageVisual::New( GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl ); + visualPtr = AnimatedVectorImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl); break; } case VisualUrl::REGULAR_IMAGE: { - visualPtr = ImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, size ); + visualPtr = ImageVisual::New(GetFactoryCache(), GetImageVisualShaderFactory(), visualUrl, size); break; } } } - if( mDebugEnabled ) + if(mDebugEnabled) { //Create a WireframeVisual if we have debug enabled - visualPtr = WireframeVisual::New( GetFactoryCache(), visualPtr ); + visualPtr = WireframeVisual::New(GetFactoryCache(), visualPtr); } - return Toolkit::Visual::Base( visualPtr.Get() ); + return Toolkit::Visual::Base(visualPtr.Get()); } -void VisualFactory::SetPreMultiplyOnLoad( bool preMultiply ) +void VisualFactory::SetPreMultiplyOnLoad(bool preMultiply) { - if( mPreMultiplyOnLoad != preMultiply ) + if(mPreMultiplyOnLoad != preMultiply) { - GetFactoryCache().SetPreMultiplyOnLoad( preMultiply ); + GetFactoryCache().SetPreMultiplyOnLoad(preMultiply); } mPreMultiplyOnLoad = preMultiply; } @@ -383,19 +372,19 @@ Internal::TextureManager& VisualFactory::GetTextureManager() Internal::VisualFactoryCache& VisualFactory::GetFactoryCache() { - if( !mFactoryCache ) + if(!mFactoryCache) { - mFactoryCache = std::unique_ptr( new VisualFactoryCache( mPreMultiplyOnLoad ) ); + mFactoryCache = std::unique_ptr(new VisualFactoryCache(mPreMultiplyOnLoad)); - const std::string imageDirPath = AssetManager::GetDaliImagePath(); - std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME; + const std::string imageDirPath = AssetManager::GetDaliImagePath(); + std::string brokenImageUrl = imageDirPath + BROKEN_IMAGE_FILE_NAME; Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get(); - if( styleManager ) + if(styleManager) { - Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager ); - config["brokenImageUrl"].Get( brokenImageUrl ); - styleManager.StyleChangedSignal().Connect( mSlotDelegate, &VisualFactory::OnStyleChangedSignal ); + Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager); + config["brokenImageUrl"].Get(brokenImageUrl); + styleManager.StyleChangedSignal().Connect(mSlotDelegate, &VisualFactory::OnStyleChangedSignal); } mFactoryCache->SetBrokenImageUrl(brokenImageUrl); @@ -405,9 +394,9 @@ Internal::VisualFactoryCache& VisualFactory::GetFactoryCache() ImageVisualShaderFactory& VisualFactory::GetImageVisualShaderFactory() { - if( !mImageVisualShaderFactory ) + if(!mImageVisualShaderFactory) { - mImageVisualShaderFactory = std::unique_ptr< ImageVisualShaderFactory >( new ImageVisualShaderFactory() ); + mImageVisualShaderFactory = std::unique_ptr(new ImageVisualShaderFactory()); } return *mImageVisualShaderFactory; } diff --git a/dali-toolkit/internal/visuals/visual-string-constants.cpp b/dali-toolkit/internal/visuals/visual-string-constants.cpp index b9b78d0..9f1ad0a 100644 --- a/dali-toolkit/internal/visuals/visual-string-constants.cpp +++ b/dali-toolkit/internal/visuals/visual-string-constants.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,128 +19,124 @@ #include "visual-string-constants.h" // INTERNAL INCLUDES -#include #include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - -DALI_ENUM_TO_STRING_TABLE_BEGIN( VISUAL_TYPE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, BORDER ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, COLOR ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, GRADIENT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, IMAGE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, MESH ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, PRIMITIVE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, TEXT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, N_PATCH ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, SVG ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, ANIMATED_IMAGE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::Visual, WIREFRAME ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelVisual, ANIMATED_GRADIENT ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelVisual, ANIMATED_VECTOR_IMAGE ) -DALI_ENUM_TO_STRING_WITH_SCOPE( Toolkit::DevelVisual, ARC ) -DALI_ENUM_TO_STRING_TABLE_END( VISUAL_TYPE ) +DALI_ENUM_TO_STRING_TABLE_BEGIN(VISUAL_TYPE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, BORDER) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, COLOR) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, GRADIENT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, IMAGE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, MESH) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, PRIMITIVE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, TEXT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, N_PATCH) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, SVG) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, ANIMATED_IMAGE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::Visual, WIREFRAME) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelVisual, ANIMATED_GRADIENT) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelVisual, ANIMATED_VECTOR_IMAGE) + DALI_ENUM_TO_STRING_WITH_SCOPE(Toolkit::DevelVisual, ARC) +DALI_ENUM_TO_STRING_TABLE_END(VISUAL_TYPE) // Visual Type -const char * const VISUAL_TYPE( "visualType" ); +const char* const VISUAL_TYPE("visualType"); // Custom shader -const char * const CUSTOM_SHADER( "shader" ); -const char * const CUSTOM_VERTEX_SHADER( "vertexShader" ); -const char * const CUSTOM_FRAGMENT_SHADER( "fragmentShader" ); -const char * const CUSTOM_SUBDIVIDE_GRID_X( "subdivideGridX" ); -const char * const CUSTOM_SUBDIVIDE_GRID_Y( "subdivideGridY" ); -const char * const CUSTOM_SHADER_HINTS( "hints" ); +const char* const CUSTOM_SHADER("shader"); +const char* const CUSTOM_VERTEX_SHADER("vertexShader"); +const char* const CUSTOM_FRAGMENT_SHADER("fragmentShader"); +const char* const CUSTOM_SUBDIVIDE_GRID_X("subdivideGridX"); +const char* const CUSTOM_SUBDIVIDE_GRID_Y("subdivideGridY"); +const char* const CUSTOM_SHADER_HINTS("hints"); // Transform -const char * const TRANSFORM( "transform" ); -const char * const SIZE( "size" ); -const char * const OFFSET( "offset" ); -const char * const OFFSET_SIZE_MODE( "offsetSizeMode" ); -const char * const ORIGIN( "origin" ); -const char * const ANCHOR_POINT( "anchorPoint" ); -const char * const EXTRA_SIZE( "extraSize" ); +const char* const TRANSFORM("transform"); +const char* const SIZE("size"); +const char* const OFFSET("offset"); +const char* const OFFSET_SIZE_MODE("offsetSizeMode"); +const char* const ORIGIN("origin"); +const char* const ANCHOR_POINT("anchorPoint"); +const char* const EXTRA_SIZE("extraSize"); // Premultipled alpha -const char * const PREMULTIPLIED_ALPHA( "premultipliedAlpha" ); +const char* const PREMULTIPLIED_ALPHA("premultipliedAlpha"); // Mix color -const char * const MIX_COLOR( "mixColor" ); -const char * const OPACITY( "opacity" ); +const char* const MIX_COLOR("mixColor"); +const char* const OPACITY("opacity"); // Fitting mode -const char * const VISUAL_FITTING_MODE( "visualFittingMode" ); +const char* const VISUAL_FITTING_MODE("visualFittingMode"); // Corner radius -const char * const CORNER_RADIUS( "cornerRadius" ); -const char * const CORNER_RADIUS_POLICY( "cornerRadiusPolicy" ); +const char* const CORNER_RADIUS("cornerRadius"); +const char* const CORNER_RADIUS_POLICY("cornerRadiusPolicy"); // Color visual -const char * const RENDER_IF_TRANSPARENT_NAME( "renderIfTransparent" ); -const char * const BLUR_RADIUS_NAME( "blurRadius" ); +const char* const RENDER_IF_TRANSPARENT_NAME("renderIfTransparent"); +const char* const BLUR_RADIUS_NAME("blurRadius"); // Image visual -const char * const IMAGE_URL_NAME( "url" ); -const char * const ATLAS_RECT_UNIFORM_NAME( "uAtlasRect" ); -const char * const PIXEL_AREA_UNIFORM_NAME( "pixelArea" ); -const char * const WRAP_MODE_UNIFORM_NAME( "wrapMode" ); -const char * const IMAGE_WRAP_MODE_U("wrapModeU"); -const char * const IMAGE_WRAP_MODE_V("wrapModeV"); -const char * const IMAGE_BORDER( "border" ); -const char * const PIXEL_ALIGNED_UNIFORM_NAME( "uPixelAligned" ); -const char * const ANIMATED_IMAGE_URLS_NAME("urls"); -const char * const BATCH_SIZE_NAME("batchSize"); -const char * const CACHE_SIZE_NAME("cacheSize"); -const char * const FRAME_DELAY_NAME("frameDelay"); -const char * const LOOP_COUNT_NAME("loopCount"); -const char * const MASK_CONTENT_SCALE_NAME("maskContentScale"); -const char * const CROP_TO_MASK_NAME("cropToMask"); -const char * const LOAD_POLICY_NAME("loadPolicy"); -const char * const RELEASE_POLICY_NAME("releasePolicy"); -const char * const ORIENTATION_CORRECTION_NAME("orientationCorrection"); -const char * const AUXILIARY_IMAGE_NAME("auxiliaryImage"); -const char * const AUXILIARY_IMAGE_ALPHA_NAME("auxiliaryImageAlpha"); -const char * const PLAY_RANGE_NAME( "playRange" ); -const char * const PLAY_STATE_NAME( "playState" ); -const char * const CURRENT_FRAME_NUMBER_NAME( "currentFrameNumber" ); -const char * const TOTAL_FRAME_NUMBER_NAME( "totalFrameNumber" ); -const char * const STOP_BEHAVIOR_NAME( "stopBehavior" ); -const char * const LOOPING_MODE_NAME( "loopingMode" ); -const char * const IMAGE_ATLASING( "atlasing" ); -const char * const SYNCHRONOUS_LOADING( "synchronousLoading" ); -const char * const IMAGE_FITTING_MODE( "fittingMode" ); -const char * const IMAGE_SAMPLING_MODE( "samplingMode" ); -const char * const IMAGE_DESIRED_WIDTH( "desiredWidth" ); -const char * const IMAGE_DESIRED_HEIGHT( "desiredHeight" ); -const char * const ALPHA_MASK_URL("alphaMaskUrl"); -const char * const REDRAW_IN_SCALING_DOWN_NAME("redrawInScalingDown"); +const char* const IMAGE_URL_NAME("url"); +const char* const ATLAS_RECT_UNIFORM_NAME("uAtlasRect"); +const char* const PIXEL_AREA_UNIFORM_NAME("pixelArea"); +const char* const WRAP_MODE_UNIFORM_NAME("wrapMode"); +const char* const IMAGE_WRAP_MODE_U("wrapModeU"); +const char* const IMAGE_WRAP_MODE_V("wrapModeV"); +const char* const IMAGE_BORDER("border"); +const char* const PIXEL_ALIGNED_UNIFORM_NAME("uPixelAligned"); +const char* const ANIMATED_IMAGE_URLS_NAME("urls"); +const char* const BATCH_SIZE_NAME("batchSize"); +const char* const CACHE_SIZE_NAME("cacheSize"); +const char* const FRAME_DELAY_NAME("frameDelay"); +const char* const LOOP_COUNT_NAME("loopCount"); +const char* const MASK_CONTENT_SCALE_NAME("maskContentScale"); +const char* const CROP_TO_MASK_NAME("cropToMask"); +const char* const LOAD_POLICY_NAME("loadPolicy"); +const char* const RELEASE_POLICY_NAME("releasePolicy"); +const char* const ORIENTATION_CORRECTION_NAME("orientationCorrection"); +const char* const AUXILIARY_IMAGE_NAME("auxiliaryImage"); +const char* const AUXILIARY_IMAGE_ALPHA_NAME("auxiliaryImageAlpha"); +const char* const PLAY_RANGE_NAME("playRange"); +const char* const PLAY_STATE_NAME("playState"); +const char* const CURRENT_FRAME_NUMBER_NAME("currentFrameNumber"); +const char* const TOTAL_FRAME_NUMBER_NAME("totalFrameNumber"); +const char* const STOP_BEHAVIOR_NAME("stopBehavior"); +const char* const LOOPING_MODE_NAME("loopingMode"); +const char* const IMAGE_ATLASING("atlasing"); +const char* const SYNCHRONOUS_LOADING("synchronousLoading"); +const char* const IMAGE_FITTING_MODE("fittingMode"); +const char* const IMAGE_SAMPLING_MODE("samplingMode"); +const char* const IMAGE_DESIRED_WIDTH("desiredWidth"); +const char* const IMAGE_DESIRED_HEIGHT("desiredHeight"); +const char* const ALPHA_MASK_URL("alphaMaskUrl"); +const char* const REDRAW_IN_SCALING_DOWN_NAME("redrawInScalingDown"); // Text visual -const char * const TEXT_PROPERTY( "text" ); -const char * const FONT_FAMILY_PROPERTY( "fontFamily" ); -const char * const FONT_STYLE_PROPERTY( "fontStyle" ); -const char * const POINT_SIZE_PROPERTY( "pointSize" ); -const char * const MULTI_LINE_PROPERTY( "multiLine" ); -const char * const HORIZONTAL_ALIGNMENT_PROPERTY( "horizontalAlignment" ); -const char * const VERTICAL_ALIGNMENT_PROPERTY( "verticalAlignment" ); -const char * const TEXT_COLOR_PROPERTY( "textColor" ); -const char * const ENABLE_MARKUP_PROPERTY( "enableMarkup" ); -const char * const SHADOW_PROPERTY( "shadow" ); -const char * const UNDERLINE_PROPERTY( "underline" ); -const char * const OUTLINE_PROPERTY( "outline" ); -const char * const BACKGROUND_PROPERTY( "textBackground" ); - +const char* const TEXT_PROPERTY("text"); +const char* const FONT_FAMILY_PROPERTY("fontFamily"); +const char* const FONT_STYLE_PROPERTY("fontStyle"); +const char* const POINT_SIZE_PROPERTY("pointSize"); +const char* const MULTI_LINE_PROPERTY("multiLine"); +const char* const HORIZONTAL_ALIGNMENT_PROPERTY("horizontalAlignment"); +const char* const VERTICAL_ALIGNMENT_PROPERTY("verticalAlignment"); +const char* const TEXT_COLOR_PROPERTY("textColor"); +const char* const ENABLE_MARKUP_PROPERTY("enableMarkup"); +const char* const SHADOW_PROPERTY("shadow"); +const char* const UNDERLINE_PROPERTY("underline"); +const char* const OUTLINE_PROPERTY("outline"); +const char* const BACKGROUND_PROPERTY("textBackground"); //NPatch visual -const char * const BORDER_ONLY( "borderOnly" ); -const char * const BORDER( "border" ); +const char* const BORDER_ONLY("borderOnly"); +const char* const BORDER("border"); // non-animated property const char* const GRADIENT_TYPE_NAME("gradientType"); @@ -177,48 +173,47 @@ const char* const UNIFORM_ROTATE_ANGLE_NAME("rotate_angle"); const char* const UNIFORM_OFFSET_NAME("gradient_offset"); // Border visual -const char * const COLOR_NAME("borderColor"); -const char * const SIZE_NAME("borderSize"); -const char * const ANTI_ALIASING("antiAliasing"); +const char* const COLOR_NAME("borderColor"); +const char* const SIZE_NAME("borderSize"); +const char* const ANTI_ALIASING("antiAliasing"); // properties: radial gradient -const char * const CENTER_NAME("center"); // Property::VECTOR2 -const char * const RADIUS_NAME("radius"); // Property::FLOAT +const char* const CENTER_NAME("center"); // Property::VECTOR2 +const char* const RADIUS_NAME("radius"); // Property::FLOAT // properties: linear&radial gradient -const char * const STOP_OFFSET_NAME("stopOffset"); // Property::Array FLOAT -const char * const STOP_COLOR_NAME("stopColor"); // Property::Array VECTOR4 -const char * const UNITS_NAME("units"); // Property::String "userSpaceOnUse | objectBoundingBox" -const char * const SPREAD_METHOD_NAME("spreadMethod"); // Property::String "pad | reflect | repeat" +const char* const STOP_OFFSET_NAME("stopOffset"); // Property::Array FLOAT +const char* const STOP_COLOR_NAME("stopColor"); // Property::Array VECTOR4 +const char* const UNITS_NAME("units"); // Property::String "userSpaceOnUse | objectBoundingBox" +const char* const SPREAD_METHOD_NAME("spreadMethod"); // Property::String "pad | reflect | repeat" //mesh visual -const char * const OBJECT_URL_NAME( "objectUrl" ); -const char * const MATERIAL_URL_NAME( "materialUrl" ); -const char * const TEXTURES_PATH_NAME( "texturesPath" ); -const char * const SHADING_MODE_NAME( "shadingMode" ); -const char * const USE_MIPMAPPING_NAME( "useMipmapping" ); -const char * const USE_SOFT_NORMALS_NAME( "useSoftNormals" ); -const char * const LIGHT_POSITION_NAME( "lightPosition" ); - +const char* const OBJECT_URL_NAME("objectUrl"); +const char* const MATERIAL_URL_NAME("materialUrl"); +const char* const TEXTURES_PATH_NAME("texturesPath"); +const char* const SHADING_MODE_NAME("shadingMode"); +const char* const USE_MIPMAPPING_NAME("useMipmapping"); +const char* const USE_SOFT_NORMALS_NAME("useSoftNormals"); +const char* const LIGHT_POSITION_NAME("lightPosition"); //Primitive properties -const char * const PRIMITIVE_SHAPE( "shape" ); -const char * const SLICES( "slices" ); -const char * const STACKS( "stacks" ); -const char * const SCALE_TOP_RADIUS( "scaleTopRadius" ); -const char * const SCALE_BOTTOM_RADIUS( "scaleBottomRadius" ); -const char * const SCALE_HEIGHT( "scaleHeight" ); -const char * const SCALE_RADIUS( "scaleRadius" ); -const char * const SCALE_DIMENSIONS( "scaleDimensions" ); -const char * const BEVEL_PERCENTAGE( "bevelPercentage" ); -const char * const BEVEL_SMOOTHNESS( "bevelSmoothness" ); -const char * const LIGHT_POSITION_UNIFORM_NAME( "lightPosition" ); +const char* const PRIMITIVE_SHAPE("shape"); +const char* const SLICES("slices"); +const char* const STACKS("stacks"); +const char* const SCALE_TOP_RADIUS("scaleTopRadius"); +const char* const SCALE_BOTTOM_RADIUS("scaleBottomRadius"); +const char* const SCALE_HEIGHT("scaleHeight"); +const char* const SCALE_RADIUS("scaleRadius"); +const char* const SCALE_DIMENSIONS("scaleDimensions"); +const char* const BEVEL_PERCENTAGE("bevelPercentage"); +const char* const BEVEL_SMOOTHNESS("bevelSmoothness"); +const char* const LIGHT_POSITION_UNIFORM_NAME("lightPosition"); // Arc visual -const char * const THICKNESS_NAME( "thickness" ); -const char * const START_ANGLE_NAME( "startAngle" ); -const char * const SWEEP_ANGLE_NAME( "sweepAngle" ); -const char * const CAP_NAME( "cap" ); +const char* const THICKNESS_NAME("thickness"); +const char* const START_ANGLE_NAME("startAngle"); +const char* const SWEEP_ANGLE_NAME("sweepAngle"); +const char* const CAP_NAME("cap"); } // namespace Internal diff --git a/dali-toolkit/internal/visuals/visual-url.cpp b/dali-toolkit/internal/visuals/visual-url.cpp index 451ac06..e498313 100644 --- a/dali-toolkit/internal/visuals/visual-url.cpp +++ b/dali-toolkit/internal/visuals/visual-url.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,59 +26,57 @@ namespace Toolkit { namespace Internal { - namespace { - -VisualUrl::ProtocolType ResolveLocation( const std::string& url ) +VisualUrl::ProtocolType ResolveLocation(const std::string& url) { - const char* urlCStr = url.c_str(); - const uint32_t length = url.size(); - if( ( length > 7 ) && urlCStr[5] == ':' && urlCStr[6] == '/' && urlCStr[7] == '/' ) + const char* urlCStr = url.c_str(); + const uint32_t length = url.size(); + if((length > 7) && urlCStr[5] == ':' && urlCStr[6] == '/' && urlCStr[7] == '/') { // https:// - if( ( 'h' == tolower( urlCStr[0] ) )&& - ( 't' == tolower( urlCStr[1] ) )&& - ( 't' == tolower( urlCStr[2] ) )&& - ( 'p' == tolower( urlCStr[3] ) )&& - ( 's' == tolower( urlCStr[4] ) ) ) + if(('h' == tolower(urlCStr[0])) && + ('t' == tolower(urlCStr[1])) && + ('t' == tolower(urlCStr[2])) && + ('p' == tolower(urlCStr[3])) && + ('s' == tolower(urlCStr[4]))) { return VisualUrl::REMOTE; } } - else if( ( length > 6 ) && urlCStr[4] == ':' && urlCStr[5] == '/' && urlCStr[6] == '/' ) + else if((length > 6) && urlCStr[4] == ':' && urlCStr[5] == '/' && urlCStr[6] == '/') { // http:// or dali:// - const char hOrd = tolower( urlCStr[0] ); - const char tOra = tolower( urlCStr[1] ); - const char tOrl = tolower( urlCStr[2] ); - const char pOri = tolower( urlCStr[3] ); - if( ( 'h' == hOrd )&& - ( 't' == tOra )&& - ( 't' == tOrl )&& - ( 'p' == pOri ) ) + const char hOrd = tolower(urlCStr[0]); + const char tOra = tolower(urlCStr[1]); + const char tOrl = tolower(urlCStr[2]); + const char pOri = tolower(urlCStr[3]); + if(('h' == hOrd) && + ('t' == tOra) && + ('t' == tOrl) && + ('p' == pOri)) { return VisualUrl::REMOTE; } - if( ( 'd' == hOrd )&& - ( 'a' == tOra )&& - ( 'l' == tOrl )&& - ( 'i' == pOri ) ) + if(('d' == hOrd) && + ('a' == tOra) && + ('l' == tOrl) && + ('i' == pOri)) { return VisualUrl::TEXTURE; } } - else if( ( length > 5 ) && urlCStr[3] == ':' && urlCStr[4] == '/' && urlCStr[5] == '/' ) + else if((length > 5) && urlCStr[3] == ':' && urlCStr[4] == '/' && urlCStr[5] == '/') { // ftp:// or ssh:// - const char fOrS = tolower( urlCStr[0] ); - if( ( 'f' == fOrS )||( 's' == fOrS ) ) + const char fOrS = tolower(urlCStr[0]); + if(('f' == fOrS) || ('s' == fOrS)) { - const char tOrs = tolower( urlCStr[1] ); - if( ( 't' == tOrs )||( 's' == tOrs ) ) + const char tOrs = tolower(urlCStr[1]); + if(('t' == tOrs) || ('s' == tOrs)) { - const char pOrh = tolower( urlCStr[2] ); - if( ( 'p' == pOrh )||( 'h' == pOrh ) ) + const char pOrh = tolower(urlCStr[2]); + if(('p' == pOrh) || ('h' == pOrh)) { return VisualUrl::REMOTE; } @@ -88,65 +86,69 @@ VisualUrl::ProtocolType ResolveLocation( const std::string& url ) return VisualUrl::LOCAL; } - -VisualUrl::Type ResolveType( const std::string& url ) +VisualUrl::Type ResolveType(const std::string& url) { // if only one char in string, can only be regular image const std::size_t count = url.size(); - if( count > 0 ) + if(count > 0) { // parsing from the end for better chance of early outs - enum { SUFFIX, HASH, HASH_DOT } state = SUFFIX; - char SVG[ 4 ] = { 'g', 'v', 's', '.' }; - char GIF[ 4 ] = { 'f', 'i', 'g', '.' }; - char WEBP[ 5 ] = { 'p', 'b', 'e', 'w', '.' }; - char JSON[ 5 ] = { 'n', 'o', 's', 'j', '.' }; - unsigned int svgScore = 0; - unsigned int gifScore = 0; + enum + { + SUFFIX, + HASH, + HASH_DOT + } state = SUFFIX; + char SVG[4] = {'g', 'v', 's', '.'}; + char GIF[4] = {'f', 'i', 'g', '.'}; + char WEBP[5] = {'p', 'b', 'e', 'w', '.'}; + char JSON[5] = {'n', 'o', 's', 'j', '.'}; + unsigned int svgScore = 0; + unsigned int gifScore = 0; unsigned int webpScore = 0; unsigned int jsonScore = 0; - int index = count; - while( --index >= 0 ) + int index = count; + while(--index >= 0) { - const char currentChar = tolower( url[ index ] ); + const char currentChar = tolower(url[index]); const std::size_t offsetFromEnd = count - index - 1u; - if( ( offsetFromEnd < sizeof(SVG) )&&( currentChar == SVG[ offsetFromEnd ] ) ) + if((offsetFromEnd < sizeof(SVG)) && (currentChar == SVG[offsetFromEnd])) { // early out if SVG as can't be used in N patch for now - if( ++svgScore == sizeof(SVG) ) + if(++svgScore == sizeof(SVG)) { return VisualUrl::SVG; } } - if( ( offsetFromEnd < sizeof(GIF) )&&( currentChar == GIF[ offsetFromEnd ] ) ) + if((offsetFromEnd < sizeof(GIF)) && (currentChar == GIF[offsetFromEnd])) { // early out if GIF as can't be used in N patch for now - if( ++gifScore == sizeof(GIF) ) + if(++gifScore == sizeof(GIF)) { return VisualUrl::GIF; } } - if( ( offsetFromEnd < sizeof(WEBP) )&&( currentChar == WEBP[ offsetFromEnd ] ) ) + if((offsetFromEnd < sizeof(WEBP)) && (currentChar == WEBP[offsetFromEnd])) { // early out if WEBP as can't be used in N patch for now - if( ++webpScore == sizeof(WEBP) ) + if(++webpScore == sizeof(WEBP)) { return VisualUrl::WEBP; } } - if( ( offsetFromEnd < sizeof(JSON) )&&( currentChar == JSON[ offsetFromEnd ] ) ) + if((offsetFromEnd < sizeof(JSON)) && (currentChar == JSON[offsetFromEnd])) { // early out if JSON as can't be used in N patch for now - if( ++jsonScore == sizeof(JSON) ) + if(++jsonScore == sizeof(JSON)) { return VisualUrl::JSON; } } - switch( state ) + switch(state) { case SUFFIX: { - if( '.' == currentChar ) + if('.' == currentChar) { state = HASH; } @@ -154,7 +156,7 @@ VisualUrl::Type ResolveType( const std::string& url ) } case HASH: { - if( ( '#' == currentChar ) || ( '9' == currentChar ) ) + if(('#' == currentChar) || ('9' == currentChar)) { state = HASH_DOT; } @@ -167,7 +169,7 @@ VisualUrl::Type ResolveType( const std::string& url ) } case HASH_DOT: { - if( '.' == currentChar ) + if('.' == currentChar) { return VisualUrl::N_PATCH; } @@ -185,45 +187,44 @@ VisualUrl::Type ResolveType( const std::string& url ) return VisualUrl::REGULAR_IMAGE; } -} - +} // namespace VisualUrl::VisualUrl() : mUrl(), - mType( VisualUrl::REGULAR_IMAGE ), - mLocation( VisualUrl::LOCAL ) + mType(VisualUrl::REGULAR_IMAGE), + mLocation(VisualUrl::LOCAL) { } -VisualUrl::VisualUrl( const std::string& url ) -: mUrl( url ), - mType( VisualUrl::REGULAR_IMAGE ), - mLocation( VisualUrl::LOCAL ) +VisualUrl::VisualUrl(const std::string& url) +: mUrl(url), + mType(VisualUrl::REGULAR_IMAGE), + mLocation(VisualUrl::LOCAL) { - if( ! url.empty() ) + if(!url.empty()) { - mLocation = ResolveLocation( url ); - if( VisualUrl::TEXTURE != mLocation ) + mLocation = ResolveLocation(url); + if(VisualUrl::TEXTURE != mLocation) { // TEXTURE location url doesn't need type resolving, REGULAR_IMAGE is fine - mType = ResolveType( url ); + mType = ResolveType(url); } } } -VisualUrl::VisualUrl( const VisualUrl& url ) -: mUrl( url.mUrl ), - mType( url.mType ), - mLocation( url.mLocation ) +VisualUrl::VisualUrl(const VisualUrl& url) +: mUrl(url.mUrl), + mType(url.mType), + mLocation(url.mLocation) { } -VisualUrl& VisualUrl::operator=( const VisualUrl& url ) +VisualUrl& VisualUrl::operator=(const VisualUrl& url) { - if( &url != this ) + if(&url != this) { - mUrl = url.mUrl; - mType = url.mType; + mUrl = url.mUrl; + mType = url.mType; mLocation = url.mLocation; } return *this; @@ -256,21 +257,21 @@ bool VisualUrl::IsLocalResource() const std::string VisualUrl::GetLocation() const { - const auto location = mUrl.find( "://" ); - if( std::string::npos != location ) + const auto location = mUrl.find("://"); + if(std::string::npos != location) { - return mUrl.substr( location + 3u ); // 3 characters forwards from the start of :// + return mUrl.substr(location + 3u); // 3 characters forwards from the start of :// } return mUrl; } -std::string VisualUrl::CreateTextureUrl( const std::string& location ) +std::string VisualUrl::CreateTextureUrl(const std::string& location) { return "dali://" + location; } -} // Internal +} // namespace Internal -} // Toolkit +} // namespace Toolkit -} // Dali +} // namespace Dali diff --git a/dali-toolkit/internal/visuals/wireframe/wireframe-visual.cpp b/dali-toolkit/internal/visuals/wireframe/wireframe-visual.cpp index ead87c0..44998f6 100644 --- a/dali-toolkit/internal/visuals/wireframe/wireframe-visual.cpp +++ b/dali-toolkit/internal/visuals/wireframe/wireframe-visual.cpp @@ -19,60 +19,57 @@ #include "wireframe-visual.h" // INTERNAL INCLUDES -#include -#include +#include +#include #include +#include #include -#include -#include +#include namespace Dali { - namespace Toolkit { - namespace Internal { - namespace { -const char * const POSITION_ATTRIBUTE_NAME("aPosition"); -const char * const INDEX_NAME("indices"); -} +const char* const POSITION_ATTRIBUTE_NAME("aPosition"); +const char* const INDEX_NAME("indices"); +} // namespace -WireframeVisualPtr WireframeVisual::New( VisualFactoryCache& factoryCache, const Property::Map& properties ) +WireframeVisualPtr WireframeVisual::New(VisualFactoryCache& factoryCache, const Property::Map& properties) { Visual::BasePtr emtptyVisual; return New(factoryCache, emtptyVisual, properties); } -WireframeVisualPtr WireframeVisual::New( VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual ) +WireframeVisualPtr WireframeVisual::New(VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual) { WireframeVisualPtr wireframeVisual(new WireframeVisual(factoryCache, actualVisual)); wireframeVisual->Initialize(); return wireframeVisual; } -WireframeVisualPtr WireframeVisual::New( VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual, const Property::Map& properties ) +WireframeVisualPtr WireframeVisual::New(VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual, const Property::Map& properties) { - WireframeVisualPtr wireframeVisual( new WireframeVisual( factoryCache, actualVisual ) ); + WireframeVisualPtr wireframeVisual(new WireframeVisual(factoryCache, actualVisual)); // Instead of calling SetProperties, looking for the only valid property 'transform' - Property::Value* transformValue = properties.Find( Toolkit::Visual::Property::TRANSFORM, TRANSFORM ); - Property::Map transformMap; - if( transformValue && transformValue->Get( transformMap ) ) + Property::Value* transformValue = properties.Find(Toolkit::Visual::Property::TRANSFORM, TRANSFORM); + Property::Map transformMap; + if(transformValue && transformValue->Get(transformMap)) { - wireframeVisual->SetTransformAndSize( transformMap, Vector2::ZERO ); + wireframeVisual->SetTransformAndSize(transformMap, Vector2::ZERO); } wireframeVisual->Initialize(); return wireframeVisual; } -WireframeVisual::WireframeVisual( VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual ) -: Visual::Base( factoryCache, Visual::FittingMode::FILL, actualVisual ? actualVisual->GetType() : Toolkit::Visual::WIREFRAME ), - mActualVisual( actualVisual ) +WireframeVisual::WireframeVisual(VisualFactoryCache& factoryCache, Visual::BasePtr actualVisual) +: Visual::Base(factoryCache, Visual::FittingMode::FILL, actualVisual ? actualVisual->GetType() : Toolkit::Visual::WIREFRAME), + mActualVisual(actualVisual) { } @@ -80,132 +77,134 @@ WireframeVisual::~WireframeVisual() { } -float WireframeVisual::GetHeightForWidth( float width ) +float WireframeVisual::GetHeightForWidth(float width) { - if( mActualVisual ) + if(mActualVisual) { - return mActualVisual->GetHeightForWidth( width ); + return mActualVisual->GetHeightForWidth(width); } else { - return Visual::Base::GetHeightForWidth( width ); + return Visual::Base::GetHeightForWidth(width); } } -void WireframeVisual::GetNaturalSize( Vector2& naturalSize ) +void WireframeVisual::GetNaturalSize(Vector2& naturalSize) { - if( mActualVisual ) + if(mActualVisual) { - mActualVisual->GetNaturalSize( naturalSize ); + mActualVisual->GetNaturalSize(naturalSize); } else { - Visual::Base::GetNaturalSize( naturalSize ); + Visual::Base::GetNaturalSize(naturalSize); } } -void WireframeVisual::DoCreatePropertyMap( Property::Map& map ) const +void WireframeVisual::DoCreatePropertyMap(Property::Map& map) const { - if( mActualVisual ) + if(mActualVisual) { - mActualVisual->CreatePropertyMap( map ); + mActualVisual->CreatePropertyMap(map); } else { map.Clear(); - map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::WIREFRAME ); + map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::WIREFRAME); } } -void WireframeVisual::DoCreateInstancePropertyMap( Property::Map& map ) const +void WireframeVisual::DoCreateInstancePropertyMap(Property::Map& map) const { // Do nothing } -void WireframeVisual::DoSetProperties( const Property::Map& propertyMap ) +void WireframeVisual::DoSetProperties(const Property::Map& propertyMap) { - Property::Value* mixValue = propertyMap.Find( Toolkit::Visual::Property::MIX_COLOR, MIX_COLOR ); - if( mixValue ) + Property::Value* mixValue = propertyMap.Find(Toolkit::Visual::Property::MIX_COLOR, MIX_COLOR); + if(mixValue) { Vector4 mixColor; - mixValue->Get( mixColor ); - SetMixColor( mixColor ); + mixValue->Get(mixColor); + SetMixColor(mixColor); } } -void WireframeVisual::DoSetOnScene( Actor& actor ) +void WireframeVisual::DoSetOnScene(Actor& actor) { - actor.AddRenderer( mImpl->mRenderer ); + actor.AddRenderer(mImpl->mRenderer); // Wireframe generated and ready to display - ResourceReady( Toolkit::Visual::ResourceStatus::READY ); + ResourceReady(Toolkit::Visual::ResourceStatus::READY); } void WireframeVisual::OnInitialize() { - Shader shader = mFactoryCache.GetShader( VisualFactoryCache::WIREFRAME_SHADER ); - if( !shader ) + Shader shader = mFactoryCache.GetShader(VisualFactoryCache::WIREFRAME_SHADER); + if(!shader) { - shader = Shader::New( SHADER_WIREFRAME_VISUAL_SHADER_VERT, SHADER_WIREFRAME_VISUAL_SHADER_FRAG ); - mFactoryCache.SaveShader( VisualFactoryCache::WIREFRAME_SHADER, shader ); + shader = Shader::New(SHADER_WIREFRAME_VISUAL_SHADER_VERT, SHADER_WIREFRAME_VISUAL_SHADER_FRAG); + mFactoryCache.SaveShader(VisualFactoryCache::WIREFRAME_SHADER, shader); } - Geometry geometry = mFactoryCache.GetGeometry( VisualFactoryCache::WIREFRAME_GEOMETRY ); - if( !geometry ) + Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::WIREFRAME_GEOMETRY); + if(!geometry) { geometry = CreateQuadWireframeGeometry(); - mFactoryCache.SaveGeometry( VisualFactoryCache::WIREFRAME_GEOMETRY, geometry ); + mFactoryCache.SaveGeometry(VisualFactoryCache::WIREFRAME_GEOMETRY, geometry); } //Create the renderer - mImpl->mRenderer = Renderer::New( geometry, shader); + mImpl->mRenderer = Renderer::New(geometry, shader); //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } Geometry WireframeVisual::CreateQuadWireframeGeometry() { - const float halfWidth = 0.5f; + const float halfWidth = 0.5f; const float halfHeight = 0.5f; - struct QuadVertex { Vector2 position;}; - QuadVertex quadVertexData[4] = + struct QuadVertex { - { Vector2(-halfWidth, -halfHeight) }, - { Vector2( halfWidth, -halfHeight) }, - { Vector2( halfWidth, halfHeight) }, - { Vector2(-halfWidth, halfHeight) } + Vector2 position; }; + QuadVertex quadVertexData[4] = + { + {Vector2(-halfWidth, -halfHeight)}, + {Vector2(halfWidth, -halfHeight)}, + {Vector2(halfWidth, halfHeight)}, + {Vector2(-halfWidth, halfHeight)}}; Property::Map quadVertexFormat; quadVertexFormat[POSITION_ATTRIBUTE_NAME] = Property::VECTOR2; - VertexBuffer quadVertices = VertexBuffer::New( quadVertexFormat ); - quadVertices.SetData( quadVertexData, 4 ); + VertexBuffer quadVertices = VertexBuffer::New(quadVertexFormat); + quadVertices.SetData(quadVertexData, 4); // Create indices - unsigned short indexData[10] = { 0, 1, 1, 2, 2, 3, 3, 0 }; + unsigned short indexData[10] = {0, 1, 1, 2, 2, 3, 3, 0}; // Create the geometry object Geometry geometry = Geometry::New(); - geometry.AddVertexBuffer( quadVertices ); - geometry.SetIndexBuffer( indexData, sizeof(indexData)/sizeof(indexData[0]) ); - geometry.SetType( Geometry::LINES ); + geometry.AddVertexBuffer(quadVertices); + geometry.SetIndexBuffer(indexData, sizeof(indexData) / sizeof(indexData[0])); + geometry.SetType(Geometry::LINES); return geometry; } void WireframeVisual::OnSetTransform() { - if( mImpl->mRenderer ) + if(mImpl->mRenderer) { //Register transform properties - mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT ); + mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT); } } Visual::Base& WireframeVisual::GetVisualObject() { - if( mActualVisual ) + if(mActualVisual) { return *mActualVisual.Get(); } diff --git a/dali-toolkit/public-api/controls/control-impl.cpp b/dali-toolkit/public-api/controls/control-impl.cpp index c34dbb3..2c90452 100644 --- a/dali-toolkit/public-api/controls/control-impl.cpp +++ b/dali-toolkit/public-api/controls/control-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,20 +19,21 @@ #include // EXTERNAL INCLUDES +#include +#include #include #include #include +#include #include #include #include // for strcmp #include #include #include -#include -#include -#include // INTERNAL INCLUDES +#include #include #include #include @@ -44,13 +45,11 @@ #include #include #include +#include #include #include #include #include -#include -#include -#include namespace Dali { @@ -374,7 +373,7 @@ void Control::KeyboardEnter() bool Control::OnAccessibilityActivated() { - if( Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor( Self() ) ) + if(Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor(Self())) { return OnKeyboardEnter(); } @@ -489,14 +488,14 @@ void Control::Initialize() } Dali::TypeInfo type; - Self().GetTypeInfo( type ); - if (type) + Self().GetTypeInfo(type); + if(type) { auto typeName = type.GetName(); - DevelControl::AppendAccessibilityAttribute( Self(), "t", typeName ); + DevelControl::AppendAccessibilityAttribute(Self(), "t", typeName); } - if (Accessibility::IsUp()) + if(Accessibility::IsUp()) mImpl->AccessibilityRegister(); } @@ -546,14 +545,14 @@ void Control::EmitKeyInputFocusSignal(bool focusGained) { Dali::Toolkit::Control handle(GetOwner()); - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { - auto self = mImpl->GetAccessibilityObject( Self() ); - self->EmitFocused( focusGained ); + auto self = mImpl->GetAccessibilityObject(Self()); + self->EmitFocused(focusGained); auto parent = self->GetParent(); - if( parent && !self->GetStates()[Dali::Accessibility::State::MANAGES_DESCENDANTS] ) + if(parent && !self->GetStates()[Dali::Accessibility::State::MANAGES_DESCENDANTS]) { - parent->EmitActiveDescendantChanged( parent, self ); + parent->EmitActiveDescendantChanged(parent, self); } } @@ -596,7 +595,7 @@ void Control::OnSceneConnection(int depth) // Request to be laid out when the control is connected to the Scene. // Signal that a Relayout may be needed - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { mImpl->AccessibilityRegister(); } @@ -604,7 +603,7 @@ void Control::OnSceneConnection(int depth) void Control::OnSceneDisconnection() { - if( Accessibility::IsUp() ) + if(Accessibility::IsUp()) { mImpl->AccessibilityDeregister(); } @@ -633,30 +632,30 @@ void Control::OnPropertySet(Property::Index index, const Property::Value& proper { // If the clipping mode has been set, we may need to create a renderer. // Only do this if we are already on-stage as the OnSceneConnection will handle the off-stage clipping controls. - switch( index ) + switch(index) { case Actor::Property::CLIPPING_MODE: { - if( Self().GetProperty< bool >( Actor::Property::CONNECTED_TO_SCENE )) + if(Self().GetProperty(Actor::Property::CONNECTED_TO_SCENE)) { // Note: This method will handle whether creation of the renderer is required. - CreateClippingRenderer( *this ); + CreateClippingRenderer(*this); } break; } case Actor::Property::VISIBLE: { - if( Dali::Accessibility::IsUp() ) + if(Dali::Accessibility::IsUp()) { - Dali::Accessibility::Accessible::Get(Self())->EmitVisible( Self().GetProperty( Actor::Property::VISIBLE ).Get() ); + Dali::Accessibility::Accessible::Get(Self())->EmitVisible(Self().GetProperty(Actor::Property::VISIBLE).Get()); } break; } case Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE: { - if( Dali::Accessibility::IsUp() ) + if(Dali::Accessibility::IsUp()) { - Dali::Accessibility::Accessible::Get(Self())->Emit( Dali::Accessibility::ObjectPropertyChangeEvent::ROLE ); + Dali::Accessibility::Accessible::Get(Self())->Emit(Dali::Accessibility::ObjectPropertyChangeEvent::ROLE); } break; } diff --git a/docs/content/example-code/properties.cpp b/docs/content/example-code/properties.cpp index 61be376..e189407 100644 --- a/docs/content/example-code/properties.cpp +++ b/docs/content/example-code/properties.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,8 +15,8 @@ * */ -#include #include +#include #include using namespace Dali; @@ -24,29 +24,27 @@ using namespace Dali::Toolkit; namespace { - // The name we will use to register our custom property by. const char* const TAG_PROPERTY_NAME = "tagIdentifier"; // The image for our image view const char* const IMAGE_CARDS = "images/cards.jpg"; -} // namespace +} // namespace /** * This example shows how to set properties in C++ and how to register and look-up custom properties. * An image is added to the screen which changes and a custom property is added to the image-view. * This value is incremented every time the image is touched and the text-label is updated. */ -class PropertyController: public ConnectionTracker +class PropertyController : public ConnectionTracker { public: - - PropertyController( Application& application ) + PropertyController(Application& application) : mTagText(), - mTagPropertyIndex( Property::INVALID_INDEX ) + mTagPropertyIndex(Property::INVALID_INDEX) { // Connect to the Application's Init signal - application.InitSignal().Connect( this, &PropertyController::Create ); + application.InitSignal().Connect(this, &PropertyController::Create); } ~PropertyController() @@ -54,7 +52,7 @@ public: } // C++ EXAMPLE - void Create( Application& application ) + void Create(Application& application) { // Get the window handle Window window = application.GetWindow(); @@ -62,32 +60,32 @@ public: mImageView = ImageView::New(); // Set the property to move to the center - mImageView.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); + mImageView.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER); // Set another property to set the image-map Property::Map imageMap; - imageMap[ Visual::Property::TYPE ] = Visual::IMAGE; - imageMap[ ImageVisual::Property::URL ] = IMAGE_CARDS; - imageMap[ ImageVisual::Property::DESIRED_WIDTH ] = 100; - imageMap[ ImageVisual::Property::DESIRED_HEIGHT ] = 100; - mImageView.SetProperty( ImageView::Property::IMAGE, imageMap ); + imageMap[Visual::Property::TYPE] = Visual::IMAGE; + imageMap[ImageVisual::Property::URL] = IMAGE_CARDS; + imageMap[ImageVisual::Property::DESIRED_WIDTH] = 100; + imageMap[ImageVisual::Property::DESIRED_HEIGHT] = 100; + mImageView.SetProperty(ImageView::Property::IMAGE, imageMap); // Add the image view to the window - window.Add( mImageView ); + window.Add(mImageView); // Register a custom float property on mImageView and use it to store the number of times we are tapped - mTagPropertyIndex = mImageView.RegisterProperty( TAG_PROPERTY_NAME, 0, Property::READ_WRITE /* Event-side only, i.e. not animatable */ ); + mTagPropertyIndex = mImageView.RegisterProperty(TAG_PROPERTY_NAME, 0, Property::READ_WRITE /* Event-side only, i.e. not animatable */); // Connect to the touch-event - mImageView.TouchedSignal().Connect( this, &PropertyController::OnTouched ); + mImageView.TouchedSignal().Connect(this, &PropertyController::OnTouched); // Create text label - mTagText = Toolkit::TextLabel::New( "0" ); - mTagText.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER ); - mTagText.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); - mTagText.SetProperty( TextLabel::Property::TEXT_COLOR, Color::WHITE ); - mTagText.SetProperty( TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" ); - window.Add( mTagText ); + mTagText = Toolkit::TextLabel::New("0"); + mTagText.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER); + mTagText.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER); + mTagText.SetProperty(TextLabel::Property::TEXT_COLOR, Color::WHITE); + mTagText.SetProperty(TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER"); + window.Add(mTagText); } /** @@ -95,41 +93,40 @@ public: * param[in] touch The touch-event * return Set to true if the signal was consumed correctly */ - bool OnTouched( Actor actor, const TouchEvent& touch ) + bool OnTouched(Actor actor, const TouchEvent& touch) { int touchedCount = 0; // Look up the tag property by the cached property index. // Note: If the property belongs to a control in another library, or we do not know the index, we can look the index up first with: // Property::Index index = actor.GetPropertyIndex( TAG_PROPERTY_NAME ); - actor.GetProperty( mTagPropertyIndex ).Get( touchedCount ); + actor.GetProperty(mTagPropertyIndex).Get(touchedCount); // Increment and set back again ++touchedCount; - actor.SetProperty( mTagPropertyIndex, touchedCount ); + actor.SetProperty(mTagPropertyIndex, touchedCount); // Set the text in the text-label std::stringstream valueText; valueText << touchedCount; - mTagText.SetProperty( TextLabel::Property::TEXT, valueText.str() ); + mTagText.SetProperty(TextLabel::Property::TEXT, valueText.str()); return true; // Consumed meaning any gestures will be cancelled } // C++ EXAMPLE END private: - - ImageView mImageView; ///< An image view to show an image - TextLabel mTagText; ///< A text label used to show the last button pressed. - Property::Index mTagPropertyIndex; ///< A cached property index of our custom tag property. + ImageView mImageView; ///< An image view to show an image + TextLabel mTagText; ///< A text label used to show the last button pressed. + Property::Index mTagPropertyIndex; ///< A cached property index of our custom tag property. }; // Entry point for applications. -int main( int argc, char **argv ) +int main(int argc, char** argv) { - Application application = Application::New( &argc, &argv ); + Application application = Application::New(&argc, &argv); - PropertyController test( application ); + PropertyController test(application); application.MainLoop(); return 0; -- 2.7.4