├── .gitignore ├── test ├── main.cpp ├── CMakeLists.txt ├── binding.test.cpp └── property.test.cpp ├── .gitmodules ├── cmake └── Findnod-signal.cmake ├── LICENSE.md ├── CMakeLists.txt ├── include └── bindey │ ├── binding.h │ └── property.h ├── .github └── workflows │ └── ci.yml ├── .clang-format └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.a 2 | *.lib 3 | *.o 4 | *.pdb 5 | .DS_Store 6 | -------------------------------------------------------------------------------- /test/main.cpp: -------------------------------------------------------------------------------- 1 | #define CATCH_CONFIG_MAIN 2 | #include 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/Catch2"] 2 | path = lib/Catch2 3 | url = git@github.com:catchorg/Catch2.git 4 | [submodule "lib/nod"] 5 | path = lib/nod 6 | url = git@github.com:fr00b0/nod.git 7 | -------------------------------------------------------------------------------- /cmake/Findnod-signal.cmake: -------------------------------------------------------------------------------- 1 | 2 | set(NOD_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/lib/nod") 3 | 4 | add_library(nod-signal INTERFACE) 5 | target_include_directories( 6 | nod-signal 7 | INTERFACE 8 | ${NOD_ROOT}/include 9 | ) 10 | 11 | set_target_properties( 12 | nod-signal 13 | PROPERTIES 14 | CXX_STANDARD 11 15 | CXX_EXTENSIONS off 16 | ) 17 | -------------------------------------------------------------------------------- /test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | list( APPEND SOURCE_tests binding.test.cpp ) 3 | list( APPEND SOURCE_tests property.test.cpp ) 4 | list( APPEND SOURCE_tests main.cpp ) 5 | 6 | add_executable( bindey-test ${SOURCE_tests} ) 7 | target_link_libraries( 8 | bindey-test 9 | PRIVATE 10 | bindey 11 | Catch2::Catch2 12 | ) 13 | 14 | ### add tests to CTest 15 | include(CTest) 16 | include(Catch) 17 | catch_discover_tests(bindey-test) 18 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Kevin Dixon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /test/binding.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | #include 7 | 8 | TEST_CASE( "Bind Property to Property" ) 9 | { 10 | bindey::property source; 11 | bindey::property dest; 12 | 13 | bindey::bind( source, dest ); 14 | 15 | source( "radical" ); 16 | CHECK( dest() == "radical" ); 17 | } 18 | 19 | struct Button 20 | { 21 | void setText( const std::string& text ) 22 | { 23 | this->text = text; 24 | } 25 | 26 | std::string text; 27 | }; 28 | 29 | namespace bindey 30 | { 31 | 32 | template <> 33 | binding bind( property& from, Button& to ) 34 | { 35 | return from.onChanged( [&]( const auto& newValue ) { to.setText( newValue ); } ); 36 | } 37 | } // namespace bindey 38 | 39 | TEST_CASE( "Bind Property to Object" ) 40 | { 41 | bindey::property name; 42 | Button button; 43 | 44 | bindey::bind( name, button ); 45 | 46 | name( "demo" ); 47 | 48 | CHECK( button.text == "demo" ); 49 | } 50 | 51 | TEST_CASE( "Binding Converter" ) 52 | { 53 | bindey::property value; 54 | bindey::property stringValue; 55 | 56 | bindey::bind( value, stringValue, []( const auto& value ) { return std::to_string( value ); } ); 57 | 58 | value( 7 ); 59 | CHECK( stringValue() == "7" ); 60 | } 61 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required( VERSION 3.12 ) 2 | 3 | project( bindey LANGUAGES CXX ) 4 | 5 | ### Options 6 | option( BINDEY_BUILD_TESTS "Build Tests" OFF ) 7 | option( BINDEY_USE_BUNDLED_NODSIGNAL "Use Bundled nod::signal" ON ) 8 | set( BINDEY_NODSIGNAL_TARGET "nod-signal" CACHE STRING 9 | "If your build system supplies nod signal as a CMake Target override this with your library name" ) 10 | 11 | ### Find nod-signal 12 | if( BINDEY_USE_BUNDLED_NODSIGNAL ) 13 | list( APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/cmake ) 14 | find_package( nod-signal REQUIRED ) 15 | endif() 16 | 17 | ### Library 18 | 19 | list( APPEND FILES_source include/bindey/binding.h ) 20 | list( APPEND FILES_source include/bindey/property.h ) 21 | source_group( TREE ${CMAKE_CURRENT_SOURCE_DIR}/include FILES ${FILES_source} ) 22 | 23 | add_library( bindey INTERFACE ${FILES_source} ) 24 | target_include_directories( 25 | bindey 26 | INTERFACE 27 | include 28 | ) 29 | 30 | target_link_libraries( 31 | bindey 32 | INTERFACE 33 | ${BINDEY_NODSIGNAL_TARGET} 34 | ) 35 | 36 | target_compile_features( 37 | bindey 38 | INTERFACE 39 | cxx_std_14 40 | ) 41 | 42 | ### Tests 43 | 44 | if ( BINDEY_BUILD_TESTS ) 45 | enable_testing() 46 | add_subdirectory( lib/Catch2 ) 47 | list( APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/lib/Catch2/contrib ) 48 | add_subdirectory( test ) 49 | endif() 50 | -------------------------------------------------------------------------------- /include/bindey/binding.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "property.h" 4 | 5 | #include 6 | 7 | #include 8 | #include 9 | 10 | namespace bindey 11 | { 12 | 13 | using binding = nod::connection; 14 | using scoped_binding = nod::scoped_connection; 15 | 16 | /** 17 | * base binding signature 18 | */ 19 | template 20 | binding bind( property& from, To& to ); 21 | 22 | /** 23 | * binds two properties of the same type 24 | */ 25 | template 26 | binding bind( property& from, property& to ) 27 | { 28 | return from.onChanged( [&]( const auto& newValue ) { to( newValue ); } ); 29 | } 30 | 31 | /** 32 | * binds two properties of differing types using a Converter callable 33 | * @param from property to observe 34 | * @param to property to write to 35 | * @param bindingConverter a callable to invoke to convert between the types 36 | */ 37 | template 38 | binding bind( property& from, property& to, Converter&& bindingConverter ) 39 | { 40 | static_assert( std::is_convertible>::value, 41 | "Wrong Signature for binding converter!" ); 42 | 43 | return from.onChanged( 44 | [&to, converter = bindingConverter]( const auto& newValue ) { to( converter( newValue ) ); } ); 45 | } 46 | 47 | } // namespace bindey 48 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: [pull_request] 4 | 5 | env: 6 | # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) 7 | BUILD_TYPE: Release 8 | 9 | jobs: 10 | Build-And-Test: 11 | runs-on: macos-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | submodules: true 17 | 18 | - name: Create Build Environment 19 | # Some projects don't allow in-source building, so create a separate build directory 20 | # We'll use this as our working directory for all subsequent commands 21 | run: cmake -E make_directory ${{runner.workspace}}/build 22 | 23 | - name: Configure 24 | shell: bash 25 | working-directory: ${{runner.workspace}}/build 26 | run: cmake $GITHUB_WORKSPACE -GXcode -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DBINDEY_BUILD_TESTS=ON 27 | env: 28 | CC: clang 29 | CXX: clang 30 | 31 | - name: Build 32 | working-directory: ${{runner.workspace}}/build 33 | shell: bash 34 | run: cmake --build . --config $BUILD_TYPE 35 | env: 36 | CC: clang 37 | CXX: clang 38 | 39 | - name: Test 40 | working-directory: ${{runner.workspace}}/build 41 | shell: bash 42 | # Execute tests defined by the CMake configuration. 43 | # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail 44 | run: ctest -C $BUILD_TYPE 45 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | AccessModifierOffset: -4 2 | AlignAfterOpenBracket: Align 3 | AlignConsecutiveAssignments: true 4 | AlignConsecutiveDeclarations: true 5 | AlignEscapedNewlinesLeft: true 6 | AlignOperands: true 7 | AlignTrailingComments: true 8 | AllowAllParametersOfDeclarationOnNextLine: true 9 | AllowShortBlocksOnASingleLine: false 10 | AllowShortFunctionsOnASingleLine: None 11 | AllowShortIfStatementsOnASingleLine: false 12 | AllowShortLoopsOnASingleLine: false 13 | AlwaysBreakBeforeMultilineStrings: false 14 | AlwaysBreakTemplateDeclarations: true 15 | BinPackArguments: false 16 | BinPackParameters: false 17 | BraceWrapping: 18 | AfterClass: true 19 | AfterControlStatement: true 20 | AfterEnum: true 21 | AfterFunction: true 22 | AfterNamespace: true 23 | AfterObjCDeclaration: true 24 | AfterStruct: true 25 | AfterUnion: true 26 | BeforeCatch: true 27 | BeforeElse: true 28 | IndentBraces: false 29 | BreakBeforeBinaryOperators: NonAssignment 30 | BreakBeforeBraces: Custom 31 | BreakBeforeTernaryOperators: true 32 | BreakConstructorInitializersBeforeComma: true 33 | ColumnLimit: 120 34 | CommentPragmas: '^!' 35 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 36 | ConstructorInitializerIndentWidth: 0 37 | ContinuationIndentWidth: 4 38 | Cpp11BracedListStyle: true 39 | DerivePointerAlignment: false 40 | DisableFormat: false 41 | ExperimentalAutoDetectBinPacking: false 42 | ForEachMacros: [ foreach, BOOST_FOREACH ] 43 | IndentCaseLabels: true 44 | IndentFunctionDeclarationAfterType: false 45 | IndentWidth: 4 46 | IndentWrappedFunctionNames: false 47 | KeepEmptyLinesAtTheStartOfBlocks: true 48 | Language: Cpp 49 | MaxEmptyLinesToKeep: 2 50 | NamespaceIndentation: None 51 | ObjCSpaceAfterProperty: false 52 | ObjCSpaceBeforeProtocolList: true 53 | PenaltyBreakBeforeFirstCallParameter: 19 54 | PenaltyBreakComment: 300 55 | PenaltyBreakFirstLessLess: 120 56 | PenaltyBreakString: 1000 57 | PenaltyExcessCharacter: 100 58 | PenaltyReturnTypeOnItsOwnLine: 600 59 | PointerAlignment: Left 60 | SpaceAfterCStyleCast: true 61 | SpaceBeforeAssignmentOperators: true 62 | SpaceBeforeParens: ControlStatements 63 | SpaceInEmptyParentheses: false 64 | SpacesBeforeTrailingComments: 1 65 | SpacesInAngles: false 66 | SpacesInContainerLiterals: true 67 | SpacesInCStyleCastParentheses: false 68 | SpacesInParentheses: true 69 | SpacesInSquareBrackets: false 70 | Standard: Cpp11 71 | TabWidth: 4 72 | UseTab: Never 73 | -------------------------------------------------------------------------------- /test/property.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | TEST_CASE( "Default ctor / Basic Contract" ) 6 | { 7 | bindey::property boolProp; 8 | 9 | // properties are default initialized 10 | CHECK( boolProp.get() == false ); 11 | 12 | boolProp.set( false ); 13 | CHECK( boolProp.get() == false ); 14 | 15 | boolProp.set( true ); 16 | CHECK( boolProp.get() == true ); 17 | } 18 | 19 | TEST_CASE( "Value ctor" ) 20 | { 21 | bindey::property boolProp( true ); 22 | 23 | // properties are default initialized 24 | CHECK( boolProp.get() == true ); 25 | 26 | boolProp.set( false ); 27 | CHECK( boolProp.get() == false ); 28 | 29 | boolProp.set( true ); 30 | CHECK( boolProp.get() == true ); 31 | } 32 | 33 | TEST_CASE( "Change Notitfcations" ) 34 | { 35 | bindey::property boolProp; 36 | REQUIRE( boolProp.get() == false ); 37 | 38 | bool wasCalled = false; 39 | boolProp.onChanged( [&]( const auto& ) { wasCalled = true; } ); 40 | 41 | boolProp.set( false ); 42 | REQUIRE( wasCalled == false ); 43 | 44 | boolProp.set( true ); 45 | REQUIRE( wasCalled == true ); 46 | 47 | boolProp.onChangedAndNow( [&]( const auto& val ) { REQUIRE( val == true ); } ); 48 | } 49 | 50 | TEST_CASE( "Always Update" ) 51 | { 52 | bindey::property boolProp; 53 | REQUIRE( boolProp() == false ); 54 | 55 | int count = 0; 56 | boolProp.onChanged( [&]( const auto& val ) { 57 | switch ( count ) 58 | { 59 | case 0: 60 | REQUIRE( val == true ); 61 | break; 62 | 63 | case 1: 64 | REQUIRE( val == false ); 65 | break; 66 | 67 | case 2: 68 | REQUIRE( val == false ); 69 | break; 70 | 71 | default: 72 | FAIL( "callback should not have occured" ); 73 | break; 74 | } 75 | 76 | count++; 77 | } ); 78 | 79 | boolProp( true ); 80 | 81 | boolProp( false ); 82 | 83 | boolProp( false ); 84 | } 85 | 86 | TEST_CASE( "safe_property" ) 87 | { 88 | bindey::safe_property boolProp; 89 | REQUIRE( boolProp.get() == false ); 90 | 91 | bool wasCalled = false; 92 | boolProp.onChanged( [&]( const auto& ) { wasCalled = true; } ); 93 | 94 | boolProp.set( false ); 95 | REQUIRE( wasCalled == false ); 96 | 97 | boolProp.set( true ); 98 | REQUIRE( wasCalled == true ); 99 | 100 | boolProp.onChangedAndNow( [&]( const auto& val ) { REQUIRE( val == true ); } ); 101 | } 102 | -------------------------------------------------------------------------------- /include/bindey/property.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include 6 | 7 | namespace bindey 8 | { 9 | 10 | /** 11 | * Optional always_update policy to notify subscribers everytime the property value is set, not just when it changes 12 | */ 13 | class always_update 14 | { 15 | public: 16 | template 17 | bool operator()( const T&, const T& ) const 18 | { 19 | return true; 20 | } 21 | }; 22 | 23 | template , 25 | typename Signal = nod::unsafe_signal> 26 | class property 27 | { 28 | public: 29 | property() 30 | { 31 | } 32 | property( T&& value ) 33 | : mStorage( std::move( value ) ) 34 | { 35 | } 36 | 37 | /** 38 | * gets the current value 39 | * @return const reference to the value 40 | */ 41 | const T& get() const 42 | { 43 | return mStorage; 44 | } 45 | 46 | /** 47 | * gets the current value 48 | * @return mutable reference to the value 49 | */ 50 | T& get() 51 | { 52 | return mStorage; 53 | } 54 | 55 | const T& operator()() const 56 | { 57 | return get(); 58 | } 59 | 60 | T& operator()() 61 | { 62 | return get(); 63 | } 64 | 65 | /** 66 | * sets the value of the property. 67 | * @param value the new value 68 | * @discussion the value will only be updated if the UpdatePolicy's critera is met. 69 | * if the value is changed, then the @ref changed event will be fired. 70 | */ 71 | void set( const T& value ) 72 | { 73 | if ( UpdatePolicy{}( mStorage, value ) ) 74 | { 75 | mStorage = value; 76 | changed( mStorage ); 77 | } 78 | } 79 | 80 | void set( T&& value ) 81 | { 82 | if ( UpdatePolicy{}( mStorage, value ) ) 83 | { 84 | mStorage = std::move( value ); 85 | changed( mStorage ); 86 | } 87 | } 88 | 89 | void operator()( const T& value ) 90 | { 91 | set( value ); 92 | } 93 | 94 | void operator()( T&& value ) 95 | { 96 | set( std::move( value ) ); 97 | } 98 | 99 | /** 100 | * this signal is invoked whenever the the value changes per the UpdatePolicy 101 | * @discussion nod::unsafe_signal is used here for speed. Take care of your own threading. 102 | */ 103 | Signal changed; 104 | 105 | /** 106 | * convience function to attach a change listener to this property 107 | */ 108 | auto onChanged( typename decltype( changed )::slot_type&& c ) 109 | { 110 | return changed.connect( std::move( c ) ); 111 | } 112 | 113 | /** 114 | * convience function to attach a change listener to this property and call it right away 115 | */ 116 | auto onChangedAndNow( typename decltype( changed )::slot_type&& c ) 117 | { 118 | auto connection = onChanged( std::move( c ) ); 119 | changed( mStorage ); 120 | return connection; 121 | } 122 | 123 | 124 | private: 125 | T mStorage{}; 126 | }; 127 | 128 | /** 129 | * thread safe property type based on nod::signal 130 | */ 131 | template > 132 | using safe_property = property>; 133 | 134 | } // namespace bindey 135 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bindey 2 | 3 | Everyone knows Model-View-ViewModel is the best architecture, but how can we realize it in C++ applications with minimal overhead, and no complicated framework impositions? 4 | 5 | `bindey` provides the basic building block of MVVM -- an observable "Property" and a databinding mechanism. 6 | 7 | ## Property Usage 8 | 9 | At minimum, `bindey::property` can allow you to avoid writing getters and setters. Consider this example: 10 | 11 | ``` 12 | #include 13 | 14 | using namespace bindey; 15 | 16 | class Person 17 | { 18 | public: 19 | property name; 20 | property age; 21 | }; 22 | ``` 23 | Then we can use it like this: 24 | ``` 25 | Person p; 26 | p.name("Kevin"); 27 | p.age(666); 28 | 29 | auto thatDudesName = p.name(); 30 | auto ageIsJustANumber = p.age(); 31 | ``` 32 | 33 | `property` default initializes its value with `{}`, and of course allows initialization. 34 | ``` 35 | Person::Person() 36 | : name("Default Name") 37 | , age(0) 38 | {} 39 | ``` 40 | ## Data Binding 41 | `bindey` provides a simple binding mechanism to connect a "source" `property` to an arbitrary object. This base signature is 42 | ``` 43 | template 44 | binding bind( property& from, To& to ); 45 | ``` 46 | And a specialization for `property` to `property` binding of the same type is provided. 47 | ``` 48 | template 49 | binding bind( property& from, property& to ) 50 | { 51 | return from.onChanged( [&]( const auto& newValue ) { to( newValue ); } ); 52 | } 53 | ``` 54 | 55 | ### Writing Your Own Bindings 56 | Where this becomes fun is when you get to reduce boilerplate. For example, assume a `Button` class from some UI Framework. 57 | ``` 58 | struct Button 59 | { 60 | void setText(const std::string& text) 61 | { 62 | this->text = text; 63 | } 64 | 65 | std::string text; 66 | }; 67 | ``` 68 | To make your life better, simply implement a template speciailization in the `bindey` namespace. 69 | ``` 70 | namespace bindey 71 | { 72 | template <> 73 | binding bind( property& from, Button& to ) 74 | { 75 | return from.onChanged( [&]( const auto& newValue ){ to.setText( newValue ); } ); 76 | } 77 | } // namespace bindey 78 | ``` 79 | Then, bind your property to the button as needed: 80 | ``` 81 | bindey::property name; 82 | ... 83 | Button someButton; 84 | ... 85 | bindey::bind( name, someButton ); 86 | ``` 87 | 88 | ### Binding Lifetimes 89 | The result of a call to `bind` is a `bindey::binding` object. If this return value is discarded, then the binding's lifetime is coupled to the `property`'s. 90 | 91 | Otherwise, this token can be used to disconnect the binding as needed, the easiest way is to capture it in a `scoped_binding` object. 92 | 93 | For example, if your binding involves objects who's lifetime you do not control, you should certainly capture the binding to avoid crashes. 94 | ``` 95 | struct GreatObj 96 | { 97 | GreatObj(Button* b) 98 | { 99 | mSomeButton = b; 100 | mButtonBinding = bindey::bind( name, *mSomeButton ); 101 | } 102 | 103 | void updateButton(Button* newB) 104 | { 105 | mSomeButton = nullptr; 106 | mButtonBinding = {}; // disconnect from old button 107 | if( newB != nullptr ) 108 | { 109 | mSomeButton = newB; 110 | mButtonBinding = bindey::bind( name, *mSomeButton ); 111 | } 112 | } 113 | 114 | bindey::scoped_binding mButtonBinding; 115 | }; 116 | ``` 117 | --------------------------------------------------------------------------------