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