[dali_1.4.26] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / docs / content / shared-javascript-and-cpp-documentation / creating-custom-controls.md
1 <!--
2 /**-->
3
4 [TOC]
5
6 # Creating Custom UI Controls {#creating-custom-controls}
7
8 DALi provides the ability to create custom UI controls.
9 This can be done by extending Dali::Toolkit::Control and Dali::Toolkit::Internal::Control classes.
10  
11 Custom controls are created using the [handle/body idiom](@ref handle-body-idiom) used in DALi.
12  
13 ![ ](../assets/img/creating-custom-controls/control-handle-body.png)
14 ![ ](creating-custom-controls/control-handle-body.png)
15  
16 Namespaces are important
17 + The handle & body classes should have the same name but in different namespaces
18 + TypeRegistry relies on this convention
19 + Here our custom control requires
20   + MyUIControl
21   + Internal::MyUIControl
22  
23 ### General Guidelines:
24 + Try to avoid adding C++ APIs as they become difficult to maintain.
25   + Use **properties** as much as possible as Controls should be data driven.
26   + These controls will be used through JavaScript and JSON files so need to be compatible.
27 + Bear in mind that the Control can be updated when the properties change (e.g. style change)
28   + Ensure control deals with these property changes gracefully
29   + Not just the first time they are set
30 + Use Visuals rather than creating several child Actors
31   + DALi rendering pipeline more efficient
32 + Accessibility actions should be considered when designing the Control.
33 + Consider using signals if the application needs to be react to changes in the control state.
34 + Use of Gestures should be preferred over analysing raw touch events
35 + Check if you need to chain up to base class if overriding certain methods
36  
37 ___________________________________________________________________________________________________
38
39 ## Rendering Content {#creating-controls-rendering-content}
40
41 To render content, the required actors can be created and added to the control itself as its children.
42 However, this solution is not fully optimised and means extra actors will be added, and thus, need to be processed by DALi.
43  
44 Controls should be as generic as possible so the recommendation is to re-use visuals to create the content required as described in the [Visuals](@ref visuals) section.
45 Currently, this is devel-api though, so is subject to change.
46  
47 ![ ](../assets/img/creating-custom-controls/rendering.png)
48 ![ ](creating-custom-controls/rendering.png)
49
50 To add a visual to a control, first create a Property for the visual of type MAP, and ensure the name has a suffix of "_VISUAL". Then the visual is normally defined in the stylesheet, and the definition sent via SetProperty(), where you would then create the visual:
51
52 ~~~{.cpp}
53 // C++
54 void Internal::MyUIControl::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
55 {
56   MyUIControl control = MyUIControl::DownCast( Dali::BaseHandle( object ) );
57   switch( index )
58   {
59     case MyUIControl::Property::MY_VISUAL:
60     {
61       Toolkit::VisualFactory visualFactory = Toolkit::VisualFactory::Get();
62       const Property::Map *map = value.GetMap();
63       if( map && !map->Empty() )
64       {
65         Toolkit::Visual::Base visual = visualFactory.CreateVisual( *map );
66         GetImplementation( control ).RegisterVisual( index, visual );
67       }
68       break;
69     }
70     //...
71   }
72 }
73 ~~~
74
75 The [Visuals](@ref visuals) section describes the property maps that can be used for each visual type.
76
77 ___________________________________________________________________________________________________
78
79 ## Ensuring Control is Stylable {#creating-controls-stylable}
80
81 DALi's property system allows custom controls to be easily styled.
82 The [JSON Syntax](@ref script-json-specification) is used in the stylesheets:
83  
84 **JSON Styling Syntax Example:**
85 ~~~
86 {
87   "styles":
88   {
89     "textfield":
90     {
91       "pointSize":18,
92       "primaryCursorColor":[0.0,0.72,0.9,1.0],
93       "secondaryCursorColor":[0.0,0.72,0.9,1.0],
94       "cursorWidth":1,
95       "selectionHighlightColor":[0.75,0.96,1.0,1.0],
96       "grabHandleImage" : "{DALI_STYLE_IMAGE_DIR}cursor_handler_drop_center.png",
97       "selectionHandleImageLeft" : {"filename":"{DALI_STYLE_IMAGE_DIR}selection_handle_drop_left.png" },
98       "selectionHandleImageRight": {"filename":"{DALI_STYLE_IMAGE_DIR}selection_handle_drop_right.png" }
99     }
100   }
101 }
102 ~~~
103  
104 Styling gives the UI designer the ability to change the look and feel of the control without any code changes.
105  
106 | Normal Style | Customized Style |
107 |:------------:|:----------------:|
108 |![ ](../assets/img/creating-custom-controls/popup-normal.png) ![ ](creating-custom-controls/popup-normal.png) | ![ ](../assets/img/creating-custom-controls/popup-styled.png) ![ ](creating-custom-controls/popup-styled.png)|
109  
110 More information regarding styling can be found in the [Styling](@ref styling) section.
111 ___________________________________________________________________________________________________
112
113 ### Type Registration {#creating-controls-type-registration}
114
115 The TypeRegistry is used to register your custom control.
116 This allows the creation of the control via a JSON file, as well as registering properties, signals and actions.
117  
118 To ensure your control is stylable, the process described in [Type Registration](@ref type-registration) should be followed.
119
120 #### Properties
121 To aid development, some macros are provided for registering properties which are described in the [Property](@ref properties) section.
122  
123 Control properties can be one of three types:
124  + **Event-side only:** A function is called to set this property or to retrieve the value of this property.
125                         Usually, the value is stored as a member parameter of the Impl class.
126                         Other operations can also be done, as required, in this called function.
127  + **Animatable Properties:** These are double-buffered properties that can be animated.
128  + **Custom Properties:** These are dynamic properties that are created for every single instance of the control.
129                           Therefore, these tend to take a lot of memory and are usually used by applications or other controls to dynamically set certain attributes on their children.
130                           The index for these properties can also be different for every instance.
131  
132 Careful consideration must be taken when choosing which property type to use for the properties of the custom control.
133 For example, an Animatable property type can be animated but requires a lot more resources (both in its execution and memory footprint) compared to an event-side only property.
134 ___________________________________________________________________________________________________
135
136 ## Control Services {#creating-controls-control-services}
137
138 ### Initialization {#creating-controls-init}
139
140 Controls are initialized in two steps: in the constructor, and then in the Initialize() method.
141 This is so that a handle/body connection is made within DALi Core.
142 See Dali::CustomActor & Dali::CustomActorImpl for more information.
143  
144 It is recommended to do provide a New() method in the custom control implementation where the Initialize() method should be called.
145
146 ~~~{.cpp}
147 // C++
148 MyUIControl Internal::MyUIControl::New()
149 {
150   // Create the implementation, temporarily owned on stack
151   IntrusivePtr< Internal::MyUIControl > controlImpl = new Internal::MyUIControl;
152
153   // Pass ownership to handle
154   MyUIControl handle( *controlImpl );
155
156   // Second-phase init of the implementation
157   controlImpl->Initialize();
158
159   return handle;
160 }
161 ~~~
162 Another advantage of using a New() method is that the constructor for MyUIControl can be made private (or protected).
163  
164 This will trigger the Dali::Toolkit::Internal::Control Initialize() method which will in-turn, call the virtual method OnInitialize().
165 This should be overridden by the custom ui control.
166 ~~~{.cpp}
167 // C++
168 void Internal::MyUIControl::OnInitialize()
169 {
170   // Create visuals using the VisualFactory, register events etc.
171   // Register any created visuals with Control base class
172 }
173 ~~~
174 ___________________________________________________________________________________________________
175
176 ### Control Behaviour {#creating-controls-behaviour}
177
178 Dali::Toolkit::Internal::Control provides several behaviours which are specified through its constructor (@ref Dali::Toolkit::Internal::Control::Control()).
179  
180 | Behaviour                            | Description                                                                                                    |
181 |--------------------------------------|----------------------------------------------------------------------------------------------------------------|
182 | CONTROL_BEHAVIOUR_DEFAULT              | Default behavior (size negotiation is on, style change is monitored, event callbacks are not called.                                      |
183 | DISABLE_SIZE_NEGOTIATION             | If our control does not need size negotiation, i.e. control will be skipped by the size negotiation algorithm. |
184 | REQUIRES_HOVER_EVENTS                | If our control requires [hover events](@ref creating-controls-events).                                         |
185 | REQUIRES_WHEEL_EVENTS                | If our control requires [wheel events](@ref creating-controls-events).                                         |
186 | DISABLE_STYLE_CHANGE_SIGNALS         | True if control should not monitor style change signals such as Theme/Font change.                                         |
187 | REQUIRES_KEYBOARD_NAVIGATION_SUPPORT | True if need to support keyboard navigation.                                                                   |
188 ___________________________________________________________________________________________________
189
190 ### Touch, Hover & Wheel Events {#creating-controls-events}
191
192 + A **touch** is when any touch occurs within the bounds of the custom actor. Connect to Dali::Actor::TouchSignal().
193 + A **hover event** is when a pointer moves within the bounds of a custom actor (e.g. mouse pointer or hover pointer).
194 + A **wheel event** is when the mouse wheel (or similar) is moved while hovering over an actor (via a mouse pointer or hover pointer).
195  
196 If the control needs to utilize hover and wheel events, then the correct behaviour flag should be used when constructing the control and then the appropriate method should be overridden.
197 ~~~{.cpp}
198 // C++
199 bool Internal::MyUIControl::OnHoverEvent( const HoverEvent& event )
200 {
201   bool consumed = false;
202
203   // Handle hover event
204
205   // Return true if handled/consumed, false otherwise
206   return consumed;
207 }
208 ~~~
209 ~~~{.cpp}
210 // C++
211 bool Internal::MyUIControl::OnWheelEvent( const WheelEvent& event )
212 {
213   bool consumed = false;
214
215   // Handle wheel event
216
217   // Return true if handled/consumed, false otherwise
218   return consumed;
219 }
220 ~~~
221 ___________________________________________________________________________________________________
222
223 ### Gestures {#creating-controls-gestures}
224
225 DALi has a gesture system which analyses a stream of touch events and attempts to determine the intention of the user.
226 The following gesture detectors are provided:
227  
228  + **Pan:** When the user starts panning (or dragging) one or more fingers.
229             The panning should start from within the bounds of the control.
230  + **Pinch:** Detects when two touch points move towards or away from each other.
231               The center point of the pinch should be within the bounds of the control.
232  + **Tap:** When the user taps within the bounds of the control.
233  + **LongPress:** When the user presses and holds on a certain point within the bounds of a control.
234  
235 The control base class provides basic set up to detect these gestures.
236 If any of these detectors are required then this can be specified in the OnInitialize() method (or as required).
237  
238 ~~~{.cpp}
239 // C++
240 void Internal::MyUIControl::OnInitialize()
241 {
242   // Only enable pan gesture detection
243   EnableGestureDetection( Gesture::Pan );
244
245   // Or if several gestures are required
246   EnableGestureDetection( Gesture::Type( Gesture::Pinch | Gesture::Tap | Gesture::LongPress ) );
247 }
248 ~~~
249  
250 The above snippet of code will only enable the default gesture detection for each type.
251 If customization of the gesture detection is required, then the gesture-detector can be retrieved and set up accordingly in the same method.
252  
253 ~~~{.cpp}
254 // C++
255 PanGestureDetector panGestureDetector = GetPanGestureDetector();
256 panGestureDetector.AddDirection( PanGestureDetector::DIRECTION_VERTICAL );
257 ~~~
258  
259 Finally, the appropriate method should be overridden:
260 ~~~{.cpp}
261 // C++
262 void Internal::MyUIControl::OnPan( const PanGesture& pan )
263 {
264   // Handle pan-gesture
265 }
266 ~~~
267 ~~~{.cpp}
268 // C++
269 void Internal::MyUIControl::OnPinch( const PinchGesture& pinch )
270 {
271   // Handle pinch-event
272 }
273 ~~~
274 ~~~{.cpp}
275 // C++
276 void Internal::MyUIControl::OnTap( const TapGesture& tap )
277 {
278   // Handle tap-gesture
279 }
280 ~~~
281 ~~~{.cpp}
282 // C++
283 void Internal::MyUIControl::OnLongPress( const LongPressGesture& longPress )
284 {
285   // Handle long-press-gesture
286 }
287 ~~~
288  
289 ___________________________________________________________________________________________________
290
291 ### Accessibility {#creating-controls-accessibility}
292
293 Accessibility is functionality that has been designed to aid usage by the visually impaired.
294 More information can be found in the [Accessibility](@ref accessibility) section.
295  
296 Accessibility behaviour can be customized in the control by overriding certain virtual methods.
297 This is detailed [here](@ref accessibilitycustomcontrol).
298  
299 ___________________________________________________________________________________________________
300
301 ### Signals {#creating-controls-signals}
302
303 If applications need to react to changes in the control state, controls can inform those applications using Dali::Signal.
304
305 First, create a signature of the function the signal will call in the handle header file:
306 ~~~{.cpp}
307 // C++: my-ui-control.h
308 typedef Signal< void () > SignalType;
309 ~~~
310  
311 Then Create methods to get to the signal:
312 ~~~{.cpp}
313 // C++: my-ui-control.h
314 MyUIControl::SignalType& MyCustomSignal();
315 ~~~
316
317 The source file should just call the impl:
318 ~~~{.cpp}
319 // C++: my-ui-control.cpp
320 MyUIControl::SignalType& MyUIControl::MyCustomSignal()
321 {
322   return Dali::Toolkit::GetImplementation( *this ).MyCustomSignal();
323 }
324 ~~~
325  
326 In the impl file, create an instance of the signal as follows and return it in the appropriate method:
327 ~~~{.cpp}
328 // C++: my-ui-control-impl.h
329 public:
330
331   MyUIControl::SignalType MyUIControl::MyCustomSignal()
332   {
333     return mMyCustomSignal;
334   }
335
336 private:
337
338   MyUIControl::SignalType mMyCustomSignal;
339 ~~~
340  
341 Then, when you wish to emit this signal:
342 ~~~{.cpp}
343 // C++: my-ui-control-impl.cpp
344 mMyCustomSignal.Emit();
345 ~~~
346 There is no need to check if there is anything connected to this signal as this is done by the framework.
347  
348 The application can then connect to the signal as follows:
349 ~~~{.cpp}
350 void AppFunction()
351 {
352   // Do Something
353 }
354
355 ...
356
357 customControl.MyCustomSignal.Connect( this, &AppFunction );
358 ~~~
359  
360 ___________________________________________________________________________________________________
361
362 ### Children Added/Removed {#creating-controls-children}
363
364 Methods are provided that can be overridden if notification is required when a child is added or removed from our control.
365 An up call to the Control class is necessary if these methods are overridden.
366  
367 ~~~{.cpp}
368 // C++
369 void Internal::MyUIControl::OnChildAdd( Actor& child );
370 {
371   // Do any other operations required upon child addition
372
373   // Up call to Control at the end
374   Control::OnChildAdd( child );
375 }
376 ~~~
377 ~~~{.cpp}
378 // C++
379 void Internal::MyUIControl::OnChildRemove( Actor& child );
380 {
381   // Do any other operations required upon child removal
382
383   // Up call to Control at the end
384   Control::OnChildRemove( child );
385 }
386 ~~~
387  
388 Avoid adding or removing the child again within these methods.
389  
390 ___________________________________________________________________________________________________
391
392 ### Stage Connection {#creating-controls-stage}
393
394 Methods are provided that can be overridden if notification is required when our control is connected to or disconnected from the stage.
395 An up call to the Control class is necessary if these methods are overridden.
396  
397 ~~~{.cpp}
398 // C++
399 void Internal::MyUIControl::OnStageConnection( int depth )
400 {
401   // Do any other operations required upon stage connection
402
403   // Up call to Control at the end
404   Control::OnStageConnection( depth );
405 }
406 ~~~
407 ~~~{.cpp}
408 // C++
409 void Internal::MyUIControl::OnStageDisconnection()
410 {
411   // Do any other operations required upon stage disconnection
412
413   // Up call to Control at the end
414   Control::OnStageDisconnection();
415 }
416 ~~~
417  
418 ___________________________________________________________________________________________________
419
420 ### Size Negotiation {#creating-controls-size-negotiation}
421
422 The following methods must be overridden for size negotiation to work correctly with a custom control.
423  
424 ~~~{.cpp}
425 // C++
426 Vector3 Internal::MyUIControl::GetNaturalSize()
427 {
428   // Return the natural size of the control
429   // This depends on our layout
430   // If we have one visual, then we can return the natural size of that
431   // If we have more visuals, then we need to calculate their positions within our control and work out the overall size we would like our control to be
432
433   // After working out the natural size of visuals that belong to this control,
434   // should also chain up to ensure other visuals belonging to the base class are
435   // also taken into account:
436   Vector2 baseSize = Control::GetNaturalSize(); // returns the size of the background.
437 }
438 ~~~
439 ~~~{.cpp}
440 // C++
441 float Internal::MyUIControl::GetHeightForWidth( float width )
442 {
443   // Called by the size negotiation algorithm if we have a fixed width
444   // We should calculate the height we would like our control to be for that width
445
446   // Should also chain up to determine the base class's preferred height:
447   float baseHeight = Control::GetHeightForWidth( width );
448
449 }
450 ~~~
451 ~~~{.cpp}
452 // C++
453 float Internal::MyUIControl::GetWidthForHeight( float height )
454 {
455   // Called by the size negotiation algorithm if we have a fixed height
456   // We should calculate the width we would like our control to be for that height
457
458   // Should also chain up to determine the base class's preferred width:
459   float baseWidth = Control::GetWidth( height );
460 }
461 ~~~
462 ~~~{.cpp}
463 // C++
464 void Internal::MyUIControl::OnRelayout( const Vector2& size, RelayoutContainer& container )
465 {
466   // The size is what we have been given and what our control needs to fit into
467   // Here, we need to set the position and the size of our visuals
468   // If we have other controls/actors as children
469   //  - Add the control/actor to the container paired with the size required
470   //  - To ensure this works, you need to set up the control with a relayout policy of USE_ASSIGNED_SIZE
471   //  - DO NOT CALL SetSize on this control: This will trigger another size negotiation calculation
472   // DO NOT chain up to base class.
473 }
474 ~~~
475 More information on size negotiation can be found [here](@ref size-negotiation-controls).
476  
477 ___________________________________________________________________________________________________
478
479 ### Clipping Support {#creating-controls-clipping}
480
481 When an Actor is set to clip its children, the renderers have to be added manually in order to specify what its children need to clip to.
482 The Control base class automates the creation of the visuals when it is set to clip its children.
483  
484 This is only done if the application or custom control writer has not
485 added any Renderers to the Control or registered any visuals
486 (regardless of whether these visuals are enabled or not).
487  
488 If custom control writers want to define the clipping visuals themselves, then they should register all required visuals before the control is staged.
489  
490 ___________________________________________________________________________________________________
491
492 ### Other Features {#creating-controls-other}
493
494  + [Background](@ref background)
495  
496 ___________________________________________________________________________________________________
497
498 @class _Guide_Creating_UI_Controls
499
500 */