Refactor SceneGraphProperty handling code in event side to make RegisterProperty...
[platform/core/uifw/dali-core.git] / dali / internal / event / events / pan-gesture-processor.cpp
1 /*
2  * Copyright (c) 2018 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/event/events/pan-gesture-processor.h>
20
21 // EXTERNAL INCLUDES
22 #include <algorithm>
23
24 // INTERNAL INCLUDES
25 #include <dali/public-api/actors/actor.h>
26 #include <dali/public-api/common/dali-common.h>
27 #include <dali/public-api/events/pan-gesture.h>
28 #include <dali/public-api/math/vector2.h>
29 #include <dali/integration-api/events/pan-gesture-event.h>
30 #include <dali/integration-api/gesture-manager.h>
31 #include <dali/integration-api/debug.h>
32 #include <dali/internal/event/common/stage-impl.h>
33 #include <dali/internal/event/render-tasks/render-task-impl.h>
34 #include <dali/internal/update/gestures/scene-graph-pan-gesture.h>
35
36 namespace Dali
37 {
38
39 namespace Internal
40 {
41
42 namespace // unnamed namespace
43 {
44
45 const unsigned long MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY( 50u );
46
47 /**
48  * Functor which checks whether the specified actor is attached to the gesture detector.
49  * If the actor is attached, it also checks whether the number of touches of the current pan event
50  * are within the range of that expected by the detector.
51  * It returns true if it is no longer attached or the touches are out of range.
52  * This can be used in remove_if functions.
53  */
54 struct IsNotAttachedAndOutsideTouchesRangeFunctor
55 {
56   /**
57    * Constructor
58    * @param[in]  actor                 The actor to check whether it is attached.
59    * @param[in]  touches               The number of touches in the current pan event.
60    * @param[in]  outsideRangeEmitters  Reference to container where emitters outside of the touches range should be added.
61    */
62   IsNotAttachedAndOutsideTouchesRangeFunctor(Actor* actor, unsigned int touches, GestureDetectorContainer& outsideRangeEmitters)
63   : actorToCheck(actor),
64     numberOfTouches(touches),
65     outsideTouchesRangeEmitters(outsideRangeEmitters)
66   {
67   }
68
69   /**
70    * Returns true if not attached, false if it is still attached.
71    * Additionally, checks if the number of touches has changed and stops sending the pan to a particular
72    * detector if it exceeds the range of that detector.
73    * @param[in]  detector  The detector to check.
74    * @return true, if not attached, false otherwise.
75    */
76   bool operator()(GestureDetector* detector) const
77   {
78     bool remove(!detector->IsAttached(*actorToCheck));
79
80     if (!remove)
81     {
82       PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
83
84       // Ensure number of touch points is within the range of our emitter. If it isn't then remove
85       // this emitter and add it to the outsideTouchesRangeEmitters container
86       if ( (numberOfTouches < panDetector->GetMinimumTouchesRequired()) ||
87            (numberOfTouches > panDetector->GetMaximumTouchesRequired()) )
88       {
89         remove = true;
90         outsideTouchesRangeEmitters.push_back(detector);
91       }
92     }
93
94     return remove;
95   }
96
97   Actor* actorToCheck; ///< The actor to check whether it is attached or not.
98   unsigned int numberOfTouches; ///< The number of touches in the pan event.
99   GestureDetectorContainer& outsideTouchesRangeEmitters; ///< Emitters that are outside of the range of current pan.
100 };
101
102 } // unnamed namespace
103
104 PanGestureProcessor::PanGestureProcessor( Stage& stage, Integration::GestureManager& gestureManager, SceneGraph::UpdateManager& updateManager )
105 : GestureProcessor( Gesture::Pan ),
106   mStage( stage ),
107   mGestureManager( gestureManager ),
108   mGestureDetectors(),
109   mCurrentPanEmitters(),
110   mCurrentRenderTask(),
111   mPossiblePanPosition(),
112   mMinTouchesRequired( 1 ),
113   mMaxTouchesRequired( 1 ),
114   mCurrentPanEvent( NULL ),
115   mSceneObject( SceneGraph::PanGesture::New() ) // Create scene object to store pan information.
116 {
117   // Pass ownership to scene-graph; scene object lives for the lifecycle of UpdateManager
118   updateManager.SetPanGestureProcessor( mSceneObject );
119 }
120
121 PanGestureProcessor::~PanGestureProcessor()
122 {
123   mSceneObject = NULL; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
124 }
125
126 void PanGestureProcessor::Process( const Integration::PanGestureEvent& panEvent )
127 {
128   switch( panEvent.state )
129   {
130     case Gesture::Possible:
131     {
132       mCurrentPanEmitters.clear();
133       ResetActor();
134
135       HitTestAlgorithm::Results hitTestResults;
136       if( HitTest( mStage, panEvent.currentPosition, hitTestResults ) )
137       {
138         SetActor( &GetImplementation( hitTestResults.actor ) );
139         mPossiblePanPosition = panEvent.currentPosition;
140       }
141
142       break;
143     }
144
145     case Gesture::Started:
146     {
147       if ( GetCurrentGesturedActor() )
148       {
149         // The pan gesture should only be sent to the gesture detector which first received it so that
150         // it can be told when the gesture ends as well.
151
152         HitTestAlgorithm::Results hitTestResults;
153         HitTest( mStage, mPossiblePanPosition, hitTestResults ); // Hit test original possible position...
154
155         if ( hitTestResults.actor && ( GetCurrentGesturedActor() == &GetImplementation( hitTestResults.actor ) ) )
156         {
157           // Record the current render-task for Screen->Actor coordinate conversions
158           mCurrentRenderTask = hitTestResults.renderTask;
159
160           // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
161           mCurrentPanEvent = &panEvent;
162           ProcessAndEmit( hitTestResults );
163           mCurrentPanEvent = NULL;
164         }
165         else
166         {
167           ResetActor();
168           mCurrentPanEmitters.clear();
169         }
170       }
171       break;
172     }
173
174     case Gesture::Continuing:
175     case Gesture::Finished:
176     case Gesture::Cancelled:
177     {
178       // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
179       // Check if actor is still touchable.
180
181       Actor* currentGesturedActor = GetCurrentGesturedActor();
182       if ( currentGesturedActor )
183       {
184         if ( currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask )
185         {
186           GestureDetectorContainer outsideTouchesRangeEmitters;
187
188           // Removes emitters that no longer have the actor attached
189           // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
190           GestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(),
191                                                                        IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters) );
192           mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
193
194           Vector2 actorCoords;
195
196           if ( !outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty() )
197           {
198             currentGesturedActor->ScreenToLocal( *mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
199
200             // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
201             EmitPanSignal( currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, Gesture::Finished, mCurrentRenderTask);
202             EmitPanSignal( currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
203           }
204
205           if ( mCurrentPanEmitters.empty() )
206           {
207             // If we have no emitters attached then clear pan actor as well.
208             ResetActor();
209           }
210
211           // Clear current gesture detectors if pan gesture has ended or been cancelled.
212           if ( ( panEvent.state == Gesture::Finished ) || ( panEvent.state == Gesture::Cancelled ) )
213           {
214             mCurrentPanEmitters.clear();
215             ResetActor();
216           }
217         }
218         else
219         {
220           mCurrentPanEmitters.clear();
221           ResetActor();
222         }
223       }
224       break;
225     }
226
227     case Gesture::Clear:
228     {
229       DALI_ABORT( "Incorrect state received from Integration layer: Clear\n" );
230       break;
231     }
232   }
233 }
234
235 void PanGestureProcessor::AddGestureDetector( PanGestureDetector* gestureDetector )
236 {
237   bool firstRegistration(mGestureDetectors.empty());
238
239   mGestureDetectors.push_back(gestureDetector);
240
241   if (firstRegistration)
242   {
243     mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
244     mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
245
246     Integration::PanGestureRequest request;
247     request.minTouches = mMinTouchesRequired;
248     request.maxTouches = mMaxTouchesRequired;
249     mGestureManager.Register(request);
250   }
251   else
252   {
253     UpdateDetection();
254   }
255 }
256
257 void PanGestureProcessor::RemoveGestureDetector( PanGestureDetector* gestureDetector )
258 {
259   if (!mCurrentPanEmitters.empty())
260   {
261     // Check if the removed detector was one that is currently being panned and remove it from emitters.
262     GestureDetectorContainer::iterator endIter = std::remove( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector );
263     mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
264
265     // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
266     if ( mCurrentPanEmitters.empty() )
267     {
268       ResetActor();
269     }
270   }
271
272   // Find the detector...
273   PanGestureDetectorContainer::iterator endIter = std::remove( mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector );
274   DALI_ASSERT_DEBUG( endIter != mGestureDetectors.end() );
275
276   // ...and remove it
277   mGestureDetectors.erase(endIter, mGestureDetectors.end());
278
279   if (mGestureDetectors.empty())
280   {
281     Integration::GestureRequest request(Gesture::Pan);
282     mGestureManager.Unregister(request);
283   }
284   else
285   {
286     UpdateDetection();
287   }
288 }
289
290 void PanGestureProcessor::GestureDetectorUpdated( PanGestureDetector* gestureDetector )
291 {
292   DALI_ASSERT_DEBUG(find(mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector) != mGestureDetectors.end());
293
294   UpdateDetection();
295 }
296
297 void PanGestureProcessor::SetPanGestureProperties( const PanGesture& pan )
298 {
299   // If we are currently processing a pan gesture then just ignore
300   if ( mCurrentPanEmitters.empty() && mSceneObject )
301   {
302     // We update the scene object directly rather than sending a message.
303     // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
304     mSceneObject->AddGesture( pan );
305   }
306 }
307
308 void PanGestureProcessor::EnableProfiling()
309 {
310   mSceneObject->EnableProfiling();
311 }
312
313 void PanGestureProcessor::SetPredictionMode(int mode)
314 {
315   if( (mode < 0)
316       || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES) )
317   {
318     mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
319   }
320   SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
321   mSceneObject->SetPredictionMode(modeEnum);
322 }
323
324 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
325 {
326   mSceneObject->SetPredictionAmount(amount);
327 }
328
329 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
330 {
331   mSceneObject->SetMaximumPredictionAmount(amount);
332 }
333
334 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
335 {
336   mSceneObject->SetMinimumPredictionAmount(amount);
337 }
338
339 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
340 {
341   mSceneObject->SetPredictionAmountAdjustment(amount);
342 }
343
344 void PanGestureProcessor::SetSmoothingMode(int mode)
345 {
346   if( (mode < 0)
347       || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES) )
348   {
349     mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
350   }
351   SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
352   mSceneObject->SetSmoothingMode(modeEnum);
353 }
354
355 void PanGestureProcessor::SetSmoothingAmount(float amount)
356 {
357   mSceneObject->SetSmoothingAmount(amount);
358 }
359
360 void PanGestureProcessor::SetUseActualTimes( bool value )
361 {
362   mSceneObject->SetUseActualTimes( value );
363 }
364
365 void PanGestureProcessor::SetInterpolationTimeRange( int value )
366 {
367   mSceneObject->SetInterpolationTimeRange( value );
368 }
369
370 void PanGestureProcessor::SetScalarOnlyPredictionEnabled( bool value )
371 {
372   mSceneObject->SetScalarOnlyPredictionEnabled( value );
373 }
374
375 void PanGestureProcessor::SetTwoPointPredictionEnabled( bool value )
376 {
377   mSceneObject->SetTwoPointPredictionEnabled( value );
378 }
379
380 void PanGestureProcessor::SetTwoPointInterpolatePastTime( int value )
381 {
382   mSceneObject->SetTwoPointInterpolatePastTime( value );
383 }
384
385 void PanGestureProcessor::SetTwoPointVelocityBias( float value )
386 {
387   mSceneObject->SetTwoPointVelocityBias( value );
388 }
389
390 void PanGestureProcessor::SetTwoPointAccelerationBias( float value )
391 {
392   mSceneObject->SetTwoPointAccelerationBias( value );
393 }
394
395 void PanGestureProcessor::SetMultitapSmoothingRange( int value )
396 {
397   mSceneObject->SetMultitapSmoothingRange( value );
398 }
399
400 const SceneGraph::PanGesture& PanGestureProcessor::GetSceneObject() const
401 {
402   return *mSceneObject;
403 }
404
405 void PanGestureProcessor::UpdateDetection()
406 {
407   DALI_ASSERT_DEBUG(!mGestureDetectors.empty());
408
409   unsigned int minimumRequired = UINT_MAX;
410   unsigned int maximumRequired = 0;
411
412   for ( PanGestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
413   {
414     PanGestureDetector* detector(*iter);
415
416     if( detector )
417     {
418       unsigned int minimum = detector->GetMinimumTouchesRequired();
419       if (minimum < minimumRequired)
420       {
421         minimumRequired = minimum;
422       }
423
424       unsigned int maximum = detector->GetMaximumTouchesRequired();
425       if (maximum > maximumRequired)
426       {
427         maximumRequired = maximum;
428       }
429     }
430   }
431
432   if ( (minimumRequired != mMinTouchesRequired)||(maximumRequired != mMaxTouchesRequired) )
433   {
434     mMinTouchesRequired = minimumRequired;
435     mMaxTouchesRequired = maximumRequired;
436
437     Integration::PanGestureRequest request;
438     request.minTouches = mMinTouchesRequired;
439     request.maxTouches = mMaxTouchesRequired;
440     mGestureManager.Update(request);
441   }
442 }
443
444 void PanGestureProcessor::EmitPanSignal( Actor* actor,
445                                          const GestureDetectorContainer& gestureDetectors,
446                                          const Integration::PanGestureEvent& panEvent,
447                                          Vector2 localCurrent,
448                                          Gesture::State state,
449                                          RenderTaskPtr renderTask )
450 {
451   if ( actor && !gestureDetectors.empty() )
452   {
453     PanGesture pan(state);
454     pan.time = panEvent.time;
455
456     pan.numberOfTouches = panEvent.numberOfTouches;
457     pan.screenPosition = panEvent.currentPosition;
458     pan.position = localCurrent;
459
460     RenderTask& renderTaskImpl( *renderTask.Get() );
461
462     Vector2 localPrevious;
463     actor->ScreenToLocal( renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y );
464
465     pan.displacement = localCurrent - localPrevious;
466     Vector2 previousPos( panEvent.previousPosition );
467     if ( state == Gesture::Started )
468     {
469       previousPos = mPossiblePanPosition;
470     }
471
472     pan.screenDisplacement = panEvent.currentPosition - previousPos;
473
474     // Avoid dividing by 0
475     if ( panEvent.timeDelta > 0 )
476     {
477       pan.velocity.x = pan.displacement.x / static_cast<float>( panEvent.timeDelta );
478       pan.velocity.y = pan.displacement.y / static_cast<float>( panEvent.timeDelta );
479
480       pan.screenVelocity.x = pan.screenDisplacement.x / static_cast<float>( panEvent.timeDelta );
481       pan.screenVelocity.y = pan.screenDisplacement.y / static_cast<float>( panEvent.timeDelta );
482     }
483
484     // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
485     // so we should use the last recorded velocity instead in this scenario.
486     if ( ( state == Gesture::Finished ) && ( pan.screenVelocity == Vector2::ZERO ) &&
487          ( panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY ) )
488     {
489       pan.velocity = mLastVelocity;
490       pan.screenVelocity = mLastScreenVelocity;
491     }
492     else
493     {
494       // Store the current velocity for future iterations.
495       mLastVelocity = pan.velocity;
496       mLastScreenVelocity = pan.screenVelocity;
497     }
498
499     if ( mSceneObject )
500     {
501       // We update the scene object directly rather than sending a message.
502       // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
503       mSceneObject->AddGesture( pan );
504     }
505
506     Dali::Actor actorHandle( actor );
507     const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
508     for ( GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter )
509     {
510       static_cast< PanGestureDetector* >( *iter )->EmitPanGestureSignal( actorHandle, pan );
511     }
512   }
513 }
514
515 void PanGestureProcessor::OnGesturedActorStageDisconnection()
516 {
517   mCurrentPanEmitters.clear();
518 }
519
520 bool PanGestureProcessor::CheckGestureDetector( GestureDetector* detector, Actor* actor )
521 {
522   DALI_ASSERT_DEBUG( mCurrentPanEvent );
523
524   bool retVal( false );
525   PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
526
527   if ( ( mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired() ) &&
528        ( mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired() ) )
529   {
530     // Check if the detector requires directional panning.
531     if ( panDetector->RequiresDirectionalPan() && mCurrentRenderTask )
532     {
533       // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
534       // the detector's criteria.
535       RenderTask& renderTaskImpl = *mCurrentRenderTask.Get();
536
537       Vector2 startPosition, currentPosition;
538       actor->ScreenToLocal( renderTaskImpl, startPosition.x,   startPosition.y,   mPossiblePanPosition.x,              mPossiblePanPosition.y );
539       actor->ScreenToLocal( renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
540       Vector2 displacement( currentPosition - startPosition );
541
542       Radian angle( atanf( displacement.y / displacement.x ) );
543
544       /////////////////////////////
545       //            |            //
546       //            |            //
547       //   Q3 (-,-) | Q4 (+,-)   //
548       //            |            //
549       //    ----------------- +x //
550       //            |            //
551       //   Q2 (-,+) | Q1 (+,+)   //
552       //            |            //
553       //            |            //
554       //           +y            //
555       /////////////////////////////
556       // Quadrant 1: As is
557       // Quadrant 2: 180 degrees + angle
558       // Quadrant 3: angle - 180 degrees
559       // Quadrant 4: As is
560       /////////////////////////////
561
562       if ( displacement.x < 0.0f )
563       {
564         if ( displacement.y >= 0.0f )
565         {
566           // Quadrant 2
567           angle.radian += Math::PI;
568         }
569         else
570         {
571           // Quadrant 3
572           angle.radian -= Math::PI;
573         }
574       }
575
576       if ( panDetector->CheckAngleAllowed( angle ) )
577       {
578         retVal = true;
579       }
580     }
581     else
582     {
583       // Directional panning not required so we can use this actor and gesture detector.
584       retVal = true;
585     }
586   }
587   return retVal;
588 }
589
590 void PanGestureProcessor::EmitGestureSignal( Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates )
591 {
592   DALI_ASSERT_DEBUG ( mCurrentPanEvent );
593
594   mCurrentPanEmitters.clear();
595   ResetActor();
596
597   actor->ScreenToLocal( *mCurrentRenderTask.Get(), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
598
599   EmitPanSignal( actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask );
600
601   if ( actor->OnStage() )
602   {
603     mCurrentPanEmitters = gestureDetectors;
604     SetActor( actor );
605   }
606 }
607
608 } // namespace Internal
609
610 } // namespace Dali