Merge branch 'devel/master' into tizen
[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/scene-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( Integration::GestureManager& gestureManager, SceneGraph::UpdateManager& updateManager )
105 : GestureProcessor( Gesture::Pan ),
106   mGestureManager( gestureManager ),
107   mGestureDetectors(),
108   mCurrentPanEmitters(),
109   mCurrentRenderTask(),
110   mPossiblePanPosition(),
111   mMinTouchesRequired( 1 ),
112   mMaxTouchesRequired( 1 ),
113   mCurrentPanEvent( NULL ),
114   mSceneObject( SceneGraph::PanGesture::New() ) // Create scene object to store pan information.
115 {
116   // Pass ownership to scene-graph; scene object lives for the lifecycle of UpdateManager
117   updateManager.SetPanGestureProcessor( mSceneObject );
118 }
119
120 PanGestureProcessor::~PanGestureProcessor()
121 {
122   mSceneObject = NULL; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
123 }
124
125 void PanGestureProcessor::Process( Scene& scene, const Integration::PanGestureEvent& panEvent )
126 {
127   switch( panEvent.state )
128   {
129     case Gesture::Possible:
130     {
131       mCurrentPanEmitters.clear();
132       ResetActor();
133
134       HitTestAlgorithm::Results hitTestResults;
135       if( HitTest( scene, panEvent.currentPosition, hitTestResults ) )
136       {
137         SetActor( &GetImplementation( hitTestResults.actor ) );
138         mPossiblePanPosition = panEvent.currentPosition;
139       }
140
141       break;
142     }
143
144     case Gesture::Started:
145     {
146       if ( GetCurrentGesturedActor() )
147       {
148         // The pan gesture should only be sent to the gesture detector which first received it so that
149         // it can be told when the gesture ends as well.
150
151         HitTestAlgorithm::Results hitTestResults;
152         HitTest( scene, mPossiblePanPosition, hitTestResults ); // Hit test original possible position...
153
154         if ( hitTestResults.actor && ( GetCurrentGesturedActor() == &GetImplementation( hitTestResults.actor ) ) )
155         {
156           // Record the current render-task for Screen->Actor coordinate conversions
157           mCurrentRenderTask = hitTestResults.renderTask;
158
159           // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
160           mCurrentPanEvent = &panEvent;
161           ProcessAndEmit( hitTestResults );
162           mCurrentPanEvent = NULL;
163         }
164         else
165         {
166           ResetActor();
167           mCurrentPanEmitters.clear();
168         }
169       }
170       break;
171     }
172
173     case Gesture::Continuing:
174     case Gesture::Finished:
175     case Gesture::Cancelled:
176     {
177       // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
178       // Check if actor is still touchable.
179
180       Actor* currentGesturedActor = GetCurrentGesturedActor();
181       if ( currentGesturedActor )
182       {
183         if ( currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask )
184         {
185           GestureDetectorContainer outsideTouchesRangeEmitters;
186
187           // Removes emitters that no longer have the actor attached
188           // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
189           GestureDetectorContainer::iterator endIter = std::remove_if( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(),
190                                                                        IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters) );
191           mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
192
193           Vector2 actorCoords;
194
195           if ( !outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty() )
196           {
197             currentGesturedActor->ScreenToLocal( *mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y );
198
199             // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
200             EmitPanSignal( currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, Gesture::Finished, mCurrentRenderTask);
201             EmitPanSignal( currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
202           }
203
204           if ( mCurrentPanEmitters.empty() )
205           {
206             // If we have no emitters attached then clear pan actor as well.
207             ResetActor();
208           }
209
210           // Clear current gesture detectors if pan gesture has ended or been cancelled.
211           if ( ( panEvent.state == Gesture::Finished ) || ( panEvent.state == Gesture::Cancelled ) )
212           {
213             mCurrentPanEmitters.clear();
214             ResetActor();
215           }
216         }
217         else
218         {
219           mCurrentPanEmitters.clear();
220           ResetActor();
221         }
222       }
223       break;
224     }
225
226     case Gesture::Clear:
227     {
228       DALI_ABORT( "Incorrect state received from Integration layer: Clear\n" );
229       break;
230     }
231   }
232 }
233
234 void PanGestureProcessor::AddGestureDetector( PanGestureDetector* gestureDetector )
235 {
236   bool firstRegistration(mGestureDetectors.empty());
237
238   mGestureDetectors.push_back(gestureDetector);
239
240   if (firstRegistration)
241   {
242     mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
243     mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
244
245     Integration::PanGestureRequest request;
246     request.minTouches = mMinTouchesRequired;
247     request.maxTouches = mMaxTouchesRequired;
248     mGestureManager.Register(request);
249   }
250   else
251   {
252     UpdateDetection();
253   }
254 }
255
256 void PanGestureProcessor::RemoveGestureDetector( PanGestureDetector* gestureDetector )
257 {
258   if (!mCurrentPanEmitters.empty())
259   {
260     // Check if the removed detector was one that is currently being panned and remove it from emitters.
261     GestureDetectorContainer::iterator endIter = std::remove( mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector );
262     mCurrentPanEmitters.erase( endIter, mCurrentPanEmitters.end() );
263
264     // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
265     if ( mCurrentPanEmitters.empty() )
266     {
267       ResetActor();
268     }
269   }
270
271   // Find the detector...
272   PanGestureDetectorContainer::iterator endIter = std::remove( mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector );
273   DALI_ASSERT_DEBUG( endIter != mGestureDetectors.end() );
274
275   // ...and remove it
276   mGestureDetectors.erase(endIter, mGestureDetectors.end());
277
278   if (mGestureDetectors.empty())
279   {
280     Integration::GestureRequest request(Gesture::Pan);
281     mGestureManager.Unregister(request);
282   }
283   else
284   {
285     UpdateDetection();
286   }
287 }
288
289 void PanGestureProcessor::GestureDetectorUpdated( PanGestureDetector* gestureDetector )
290 {
291   DALI_ASSERT_DEBUG(find(mGestureDetectors.begin(), mGestureDetectors.end(), gestureDetector) != mGestureDetectors.end());
292
293   UpdateDetection();
294 }
295
296 void PanGestureProcessor::SetPanGestureProperties( const PanGesture& pan )
297 {
298   // If we are currently processing a pan gesture then just ignore
299   if ( mCurrentPanEmitters.empty() && mSceneObject )
300   {
301     // We update the scene object directly rather than sending a message.
302     // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
303     mSceneObject->AddGesture( pan );
304   }
305 }
306
307 void PanGestureProcessor::EnableProfiling()
308 {
309   mSceneObject->EnableProfiling();
310 }
311
312 void PanGestureProcessor::SetPredictionMode(int mode)
313 {
314   if( (mode < 0)
315       || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES) )
316   {
317     mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
318   }
319   SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
320   mSceneObject->SetPredictionMode(modeEnum);
321 }
322
323 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
324 {
325   mSceneObject->SetPredictionAmount(amount);
326 }
327
328 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
329 {
330   mSceneObject->SetMaximumPredictionAmount(amount);
331 }
332
333 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
334 {
335   mSceneObject->SetMinimumPredictionAmount(amount);
336 }
337
338 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
339 {
340   mSceneObject->SetPredictionAmountAdjustment(amount);
341 }
342
343 void PanGestureProcessor::SetSmoothingMode(int mode)
344 {
345   if( (mode < 0)
346       || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES) )
347   {
348     mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
349   }
350   SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
351   mSceneObject->SetSmoothingMode(modeEnum);
352 }
353
354 void PanGestureProcessor::SetSmoothingAmount(float amount)
355 {
356   mSceneObject->SetSmoothingAmount(amount);
357 }
358
359 void PanGestureProcessor::SetUseActualTimes( bool value )
360 {
361   mSceneObject->SetUseActualTimes( value );
362 }
363
364 void PanGestureProcessor::SetInterpolationTimeRange( int value )
365 {
366   mSceneObject->SetInterpolationTimeRange( value );
367 }
368
369 void PanGestureProcessor::SetScalarOnlyPredictionEnabled( bool value )
370 {
371   mSceneObject->SetScalarOnlyPredictionEnabled( value );
372 }
373
374 void PanGestureProcessor::SetTwoPointPredictionEnabled( bool value )
375 {
376   mSceneObject->SetTwoPointPredictionEnabled( value );
377 }
378
379 void PanGestureProcessor::SetTwoPointInterpolatePastTime( int value )
380 {
381   mSceneObject->SetTwoPointInterpolatePastTime( value );
382 }
383
384 void PanGestureProcessor::SetTwoPointVelocityBias( float value )
385 {
386   mSceneObject->SetTwoPointVelocityBias( value );
387 }
388
389 void PanGestureProcessor::SetTwoPointAccelerationBias( float value )
390 {
391   mSceneObject->SetTwoPointAccelerationBias( value );
392 }
393
394 void PanGestureProcessor::SetMultitapSmoothingRange( int value )
395 {
396   mSceneObject->SetMultitapSmoothingRange( value );
397 }
398
399 const SceneGraph::PanGesture& PanGestureProcessor::GetSceneObject() const
400 {
401   return *mSceneObject;
402 }
403
404 void PanGestureProcessor::UpdateDetection()
405 {
406   DALI_ASSERT_DEBUG(!mGestureDetectors.empty());
407
408   unsigned int minimumRequired = UINT_MAX;
409   unsigned int maximumRequired = 0;
410
411   for ( PanGestureDetectorContainer::iterator iter = mGestureDetectors.begin(), endIter = mGestureDetectors.end(); iter != endIter; ++iter )
412   {
413     PanGestureDetector* detector(*iter);
414
415     if( detector )
416     {
417       unsigned int minimum = detector->GetMinimumTouchesRequired();
418       if (minimum < minimumRequired)
419       {
420         minimumRequired = minimum;
421       }
422
423       unsigned int maximum = detector->GetMaximumTouchesRequired();
424       if (maximum > maximumRequired)
425       {
426         maximumRequired = maximum;
427       }
428     }
429   }
430
431   if ( (minimumRequired != mMinTouchesRequired)||(maximumRequired != mMaxTouchesRequired) )
432   {
433     mMinTouchesRequired = minimumRequired;
434     mMaxTouchesRequired = maximumRequired;
435
436     Integration::PanGestureRequest request;
437     request.minTouches = mMinTouchesRequired;
438     request.maxTouches = mMaxTouchesRequired;
439     mGestureManager.Update(request);
440   }
441 }
442
443 void PanGestureProcessor::EmitPanSignal( Actor* actor,
444                                          const GestureDetectorContainer& gestureDetectors,
445                                          const Integration::PanGestureEvent& panEvent,
446                                          Vector2 localCurrent,
447                                          Gesture::State state,
448                                          RenderTaskPtr renderTask )
449 {
450   if ( actor && !gestureDetectors.empty() )
451   {
452     PanGesture pan(state);
453     pan.time = panEvent.time;
454
455     pan.numberOfTouches = panEvent.numberOfTouches;
456     pan.screenPosition = panEvent.currentPosition;
457     pan.position = localCurrent;
458
459     RenderTask& renderTaskImpl( *renderTask.Get() );
460
461     Vector2 localPrevious;
462     actor->ScreenToLocal( renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y );
463
464     pan.displacement = localCurrent - localPrevious;
465     Vector2 previousPos( panEvent.previousPosition );
466     if ( state == Gesture::Started )
467     {
468       previousPos = mPossiblePanPosition;
469     }
470
471     pan.screenDisplacement = panEvent.currentPosition - previousPos;
472
473     // Avoid dividing by 0
474     if ( panEvent.timeDelta > 0 )
475     {
476       pan.velocity.x = pan.displacement.x / static_cast<float>( panEvent.timeDelta );
477       pan.velocity.y = pan.displacement.y / static_cast<float>( panEvent.timeDelta );
478
479       pan.screenVelocity.x = pan.screenDisplacement.x / static_cast<float>( panEvent.timeDelta );
480       pan.screenVelocity.y = pan.screenDisplacement.y / static_cast<float>( panEvent.timeDelta );
481     }
482
483     // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
484     // so we should use the last recorded velocity instead in this scenario.
485     if ( ( state == Gesture::Finished ) && ( pan.screenVelocity == Vector2::ZERO ) &&
486          ( panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY ) )
487     {
488       pan.velocity = mLastVelocity;
489       pan.screenVelocity = mLastScreenVelocity;
490     }
491     else
492     {
493       // Store the current velocity for future iterations.
494       mLastVelocity = pan.velocity;
495       mLastScreenVelocity = pan.screenVelocity;
496     }
497
498     if ( mSceneObject )
499     {
500       // We update the scene object directly rather than sending a message.
501       // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
502       mSceneObject->AddGesture( pan );
503     }
504
505     Dali::Actor actorHandle( actor );
506     const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
507     for ( GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter )
508     {
509       static_cast< PanGestureDetector* >( *iter )->EmitPanGestureSignal( actorHandle, pan );
510     }
511   }
512 }
513
514 void PanGestureProcessor::OnGesturedActorStageDisconnection()
515 {
516   mCurrentPanEmitters.clear();
517 }
518
519 bool PanGestureProcessor::CheckGestureDetector( GestureDetector* detector, Actor* actor )
520 {
521   DALI_ASSERT_DEBUG( mCurrentPanEvent );
522
523   bool retVal( false );
524   PanGestureDetector* panDetector( static_cast< PanGestureDetector* >( detector ) );
525
526   if ( ( mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired() ) &&
527        ( mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired() ) )
528   {
529     // Check if the detector requires directional panning.
530     if ( panDetector->RequiresDirectionalPan() && mCurrentRenderTask )
531     {
532       // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
533       // the detector's criteria.
534       RenderTask& renderTaskImpl = *mCurrentRenderTask.Get();
535
536       Vector2 startPosition, currentPosition;
537       actor->ScreenToLocal( renderTaskImpl, startPosition.x,   startPosition.y,   mPossiblePanPosition.x,              mPossiblePanPosition.y );
538       actor->ScreenToLocal( renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
539       Vector2 displacement( currentPosition - startPosition );
540
541       Radian angle( atanf( displacement.y / displacement.x ) );
542
543       /////////////////////////////
544       //            |            //
545       //            |            //
546       //   Q3 (-,-) | Q4 (+,-)   //
547       //            |            //
548       //    ----------------- +x //
549       //            |            //
550       //   Q2 (-,+) | Q1 (+,+)   //
551       //            |            //
552       //            |            //
553       //           +y            //
554       /////////////////////////////
555       // Quadrant 1: As is
556       // Quadrant 2: 180 degrees + angle
557       // Quadrant 3: angle - 180 degrees
558       // Quadrant 4: As is
559       /////////////////////////////
560
561       if ( displacement.x < 0.0f )
562       {
563         if ( displacement.y >= 0.0f )
564         {
565           // Quadrant 2
566           angle.radian += Math::PI;
567         }
568         else
569         {
570           // Quadrant 3
571           angle.radian -= Math::PI;
572         }
573       }
574
575       if ( panDetector->CheckAngleAllowed( angle ) )
576       {
577         retVal = true;
578       }
579     }
580     else
581     {
582       // Directional panning not required so we can use this actor and gesture detector.
583       retVal = true;
584     }
585   }
586   return retVal;
587 }
588
589 void PanGestureProcessor::EmitGestureSignal( Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates )
590 {
591   DALI_ASSERT_DEBUG ( mCurrentPanEvent );
592
593   mCurrentPanEmitters.clear();
594   ResetActor();
595
596   actor->ScreenToLocal( *mCurrentRenderTask.Get(), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y );
597
598   EmitPanSignal( actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask );
599
600   if ( actor->OnStage() )
601   {
602     mCurrentPanEmitters = gestureDetectors;
603     SetActor( actor );
604   }
605 }
606
607 } // namespace Internal
608
609 } // namespace Dali