Allows updating MinimumDistance and MinimumPanEvents of pan gestures.
[platform/core/uifw/dali-core.git] / dali / internal / event / events / pan-gesture / pan-gesture-processor.cpp
1 /*
2  * Copyright (c) 2023 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/pan-gesture-processor.h>
20
21 #if defined(DEBUG_ENABLED)
22 #include <sstream>
23 #endif
24
25 // EXTERNAL INCLUDES
26 #include <algorithm>
27
28 // INTERNAL INCLUDES
29 #include <dali/integration-api/debug.h>
30 #include <dali/integration-api/trace.h>
31 #include <dali/internal/event/common/scene-impl.h>
32 #include <dali/internal/event/events/gesture-requests.h>
33 #include <dali/internal/event/events/multi-point-event-util.h>
34 #include <dali/internal/event/events/pan-gesture/pan-gesture-event.h>
35 #include <dali/internal/event/events/pan-gesture/pan-gesture-impl.h>
36 #include <dali/internal/event/events/pan-gesture/pan-gesture-recognizer.h>
37 #include <dali/internal/event/render-tasks/render-task-impl.h>
38 #include <dali/internal/update/gestures/scene-graph-pan-gesture.h>
39 #include <dali/internal/update/manager/update-manager.h>
40 #include <dali/public-api/actors/actor.h>
41 #include <dali/public-api/common/dali-common.h>
42 #include <dali/public-api/events/pan-gesture.h>
43 #include <dali/public-api/math/vector2.h>
44
45 namespace Dali
46 {
47 namespace Internal
48 {
49 namespace // unnamed namespace
50 {
51 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_PERFORMANCE_MARKER, false);
52 #if defined(DEBUG_ENABLED)
53 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_PAN_PROCESSOR");
54
55 const char* GESTURE_STATES[6] =
56   {
57     "CLEAR",
58     "STARTED",
59     "CONTINUING",
60     "FINISHED",
61     "CANCELLED",
62     "POSSIBLE"};
63
64 #endif // defined(DEBUG_ENABLED)
65
66 const unsigned long MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY(50u);
67
68 /**
69  * Functor which checks whether the specified actor is attached to the gesture detector.
70  * If the actor is attached, it also checks whether the number of touches of the current pan event
71  * are within the range of that expected by the detector.
72  * It returns true if it is no longer attached or the touches are out of range.
73  * This can be used in remove_if functions.
74  */
75 struct IsNotAttachedAndOutsideTouchesRangeFunctor
76 {
77   /**
78    * Constructor
79    * @param[in]  actor                 The actor to check whether it is attached.
80    * @param[in]  touches               The number of touches in the current pan event.
81    * @param[in]  outsideRangeEmitters  Reference to container where emitters outside of the touches range should be added.
82    */
83   IsNotAttachedAndOutsideTouchesRangeFunctor(Actor* actor, unsigned int touches, GestureDetectorContainer& outsideRangeEmitters)
84   : actorToCheck(actor),
85     numberOfTouches(touches),
86     outsideTouchesRangeEmitters(outsideRangeEmitters)
87   {
88   }
89
90   /**
91    * Returns true if not attached, false if it is still attached.
92    * Additionally, checks if the number of touches has changed and stops sending the pan to a particular
93    * detector if it exceeds the range of that detector.
94    * @param[in]  detector  The detector to check.
95    * @return true, if not attached, false otherwise.
96    */
97   bool operator()(GestureDetector* detector) const
98   {
99     bool remove(!detector->IsAttached(*actorToCheck));
100
101     if(!remove)
102     {
103       PanGestureDetector* panDetector(static_cast<PanGestureDetector*>(detector));
104
105       // Ensure number of touch points is within the range of our emitter. If it isn't then remove
106       // this emitter and add it to the outsideTouchesRangeEmitters container
107       if((numberOfTouches < panDetector->GetMinimumTouchesRequired()) ||
108          (numberOfTouches > panDetector->GetMaximumTouchesRequired()))
109       {
110         remove = true;
111         outsideTouchesRangeEmitters.push_back(detector);
112       }
113     }
114
115     return remove;
116   }
117
118   Actor*                    actorToCheck;                ///< The actor to check whether it is attached or not.
119   unsigned int              numberOfTouches;             ///< The number of touches in the pan event.
120   GestureDetectorContainer& outsideTouchesRangeEmitters; ///< Emitters that are outside of the range of current pan.
121 };
122
123 } // unnamed namespace
124
125 PanGestureProcessor::PanGestureProcessor(SceneGraph::UpdateManager& updateManager)
126 : GestureProcessor(GestureType::PAN),
127   mPanGestureDetectors(),
128   mCurrentPanEmitters(),
129   mCurrentRenderTask(),
130   mPossiblePanPosition(),
131   mMinTouchesRequired(1),
132   mMaxTouchesRequired(1),
133   mMaxMotionEventAge(std::numeric_limits<uint32_t>::max()),
134   mCurrentPanEvent(nullptr),
135   mSceneObject(SceneGraph::PanGesture::New()) // Create scene object to store pan information.
136 {
137   // Pass ownership to scene-graph; scene object lives for the lifecycle of UpdateManager
138   updateManager.SetPanGestureProcessor(mSceneObject);
139 }
140
141 PanGestureProcessor::~PanGestureProcessor()
142 {
143   mSceneObject = nullptr; // mSceneObject is owned and destroyed by update manager (there is only one of these for now)
144 }
145
146 void PanGestureProcessor::Process(Scene& scene, const PanGestureEvent& panEvent)
147 {
148 #if defined(DEBUG_ENABLED)
149   DALI_LOG_TRACE_METHOD(gLogFilter);
150
151   DALI_LOG_INFO(gLogFilter, Debug::General, "    Pan Event\n");
152   DALI_LOG_INFO(gLogFilter, Debug::General, "      State: %s  Touches: %d  Time: %d  TimeDelta: %d\n", GESTURE_STATES[static_cast<uint8_t>(panEvent.state)], panEvent.numberOfTouches, panEvent.time, panEvent.timeDelta);
153   DALI_LOG_INFO(gLogFilter, Debug::General, "      Positions: Current: (%.0f, %.0f), Previous: (%.0f, %.0f)\n", panEvent.currentPosition.x, panEvent.currentPosition.y, panEvent.previousPosition.x, panEvent.previousPosition.y);
154 #endif
155
156   DALI_TRACE_SCOPE(gTraceFilter, "DALI_PROCESS_PAN_GESTURE");
157
158   switch(panEvent.state)
159   {
160     case GestureState::POSSIBLE:
161     {
162       mCurrentPanEmitters.clear();
163       ResetActor();
164
165       HitTestAlgorithm::Results hitTestResults;
166       if(GetFeededActor())
167       {
168         SetActor(GetFeededActor());
169         mPossiblePanPosition = panEvent.currentPosition;
170       }
171       else if(HitTest(scene, panEvent.currentPosition, hitTestResults))
172       {
173         SetActor(&GetImplementation(hitTestResults.actor));
174         mPossiblePanPosition = panEvent.currentPosition;
175       }
176       break;
177     }
178
179     case GestureState::STARTED:
180     {
181       // Requires a core update
182       mNeedsUpdate = true;
183
184       // The pan gesture should only be sent to the gesture detector which first received it so that
185       // it can be told when the gesture ends as well.
186
187       HitTestAlgorithm::Results hitTestResults;
188       if(GetFeededActor())
189       {
190         hitTestResults.actor = Dali::Actor(GetFeededActor());
191         hitTestResults.renderTask = GetFeededRenderTask();
192
193         Vector2 actorCoords;
194         GetFeededActor()->ScreenToLocal(*hitTestResults.renderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y);
195         hitTestResults.actorCoordinates = actorCoords;
196       }
197       else
198       {
199         HitTest(scene, panEvent.previousPosition, hitTestResults); // Hit Test previous position
200       }
201
202       if(hitTestResults.actor)
203       {
204         // If the current hit actor is different from the one we touched down on then set accordingly & update initial pan position
205         if(&GetImplementation(hitTestResults.actor) != GetCurrentGesturedActor())
206         {
207           mPossiblePanPosition = panEvent.previousPosition;
208           SetActor(&GetImplementation(hitTestResults.actor));
209         }
210
211         // Record the current render-task for Screen->Actor coordinate conversions
212         mCurrentRenderTask = hitTestResults.renderTask;
213
214         // Set mCurrentPanEvent to use inside overridden methods called in ProcessAndEmit()
215         mCurrentPanEvent = &panEvent;
216         if(GetFeededActor())
217         {
218           ProcessAndEmitActor(hitTestResults, GetFeededGestureDetector());
219         }
220         else
221         {
222           ProcessAndEmit(hitTestResults);
223         }
224         mCurrentPanEvent = nullptr;
225       }
226       else
227       {
228         ResetActor();
229         mCurrentPanEmitters.clear();
230       }
231       break;
232     }
233
234     case GestureState::CONTINUING:
235     {
236       // Requires a core update
237       mNeedsUpdate = true;
238       Actor* currentGesturedActor = GetCurrentGesturedActor();
239       if(GetFeededActor() && GetFeededActor() != currentGesturedActor && (mCurrentPanEmitters.empty() || (currentGesturedActor && currentGesturedActor->NeedGesturePropagation())) && GetFeededGestureDetector())
240       {
241         if(currentGesturedActor)
242         {
243           currentGesturedActor->SetNeedGesturePropagation(false);
244         }
245         mCurrentPanEvent = &panEvent;
246         if(GetFeededActor()->IsHittable() && CheckGestureDetector(GetFeededGestureDetector(), GetFeededActor()))
247         {
248           mCurrentPanEmitters.clear();
249           ResetActor();
250
251           // Record the current render-task for Screen->Actor coordinate conversions
252           mCurrentRenderTask = GetFeededRenderTask();
253
254           Vector2 actorCoords;
255           GetFeededActor()->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y);
256
257           mCurrentPanEmitters.push_back(GetFeededGestureDetector());
258           SetActor(GetFeededActor());
259           GetFeededGestureDetector()->SetDetected(true);
260           EmitPanSignal(GetFeededActor(), mCurrentPanEmitters, panEvent, actorCoords, GestureState::STARTED, mCurrentRenderTask);
261         }
262         mCurrentPanEvent = nullptr;
263       }
264       DALI_FALLTHROUGH;
265     }
266
267     case GestureState::FINISHED:
268     case GestureState::CANCELLED:
269     {
270       // Only send subsequent pan gesture signals if we processed the pan gesture when it started.
271       // Check if actor is still touchable.
272       Actor* currentGesturedActor = GetCurrentGesturedActor();
273       if(currentGesturedActor)
274       {
275         if(currentGesturedActor->IsHittable() && !mCurrentPanEmitters.empty() && mCurrentRenderTask)
276         {
277           GestureDetectorContainer outsideTouchesRangeEmitters;
278
279           // Removes emitters that no longer have the actor attached
280           // Also remove emitters whose touches are outside the range of the current pan event and add them to outsideTouchesRangeEmitters
281           GestureDetectorContainer::iterator endIter = std::remove_if(mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), IsNotAttachedAndOutsideTouchesRangeFunctor(currentGesturedActor, panEvent.numberOfTouches, outsideTouchesRangeEmitters));
282           mCurrentPanEmitters.erase(endIter, mCurrentPanEmitters.end());
283
284           Vector2 actorCoords;
285           if(!outsideTouchesRangeEmitters.empty() || !mCurrentPanEmitters.empty())
286           {
287             currentGesturedActor->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoords.x, actorCoords.y, panEvent.currentPosition.x, panEvent.currentPosition.y);
288             // EmitPanSignal checks whether we have a valid actor and whether the container we are passing in has emitters before it emits the pan.
289             EmitPanSignal(currentGesturedActor, outsideTouchesRangeEmitters, panEvent, actorCoords, GestureState::FINISHED, mCurrentRenderTask);
290             EmitPanSignal(currentGesturedActor, mCurrentPanEmitters, panEvent, actorCoords, panEvent.state, mCurrentRenderTask);
291           }
292
293           if(mCurrentPanEmitters.empty())
294           {
295             // If we have no emitters attached then clear pan actor as well.
296             ResetActor();
297           }
298
299           // Clear current gesture detectors if pan gesture has ended or been cancelled.
300           if((panEvent.state == GestureState::FINISHED) || (panEvent.state == GestureState::CANCELLED))
301           {
302             mCurrentPanEmitters.clear();
303             ResetActor();
304           }
305         }
306         else
307         {
308           mCurrentPanEmitters.clear();
309           ResetActor();
310         }
311       }
312       break;
313     }
314
315     case GestureState::CLEAR:
316     {
317       DALI_ABORT("Incorrect state received from Integration layer: CLEAR\n");
318       break;
319     }
320   }
321 }
322
323 void PanGestureProcessor::AddGestureDetector(PanGestureDetector* gestureDetector, Scene& scene, int32_t minDistance, int32_t minPanEvents)
324 {
325   bool firstRegistration(mPanGestureDetectors.empty());
326
327   mPanGestureDetectors.push_back(gestureDetector);
328
329   if(firstRegistration)
330   {
331     mMinTouchesRequired = gestureDetector->GetMinimumTouchesRequired();
332     mMaxTouchesRequired = gestureDetector->GetMaximumTouchesRequired();
333     mMaxMotionEventAge  = gestureDetector->GetMaximumMotionEventAge();
334
335     PanGestureRequest request;
336     request.minTouches        = mMinTouchesRequired;
337     request.maxTouches        = mMaxTouchesRequired;
338     request.maxMotionEventAge = mMaxMotionEventAge;
339
340     Size size          = scene.GetSize();
341     mGestureRecognizer = new PanGestureRecognizer(*this, Vector2(size.width, size.height), static_cast<const PanGestureRequest&>(request), minDistance, minPanEvents);
342   }
343   else
344   {
345     UpdateDetection();
346   }
347 }
348
349 void PanGestureProcessor::RemoveGestureDetector(PanGestureDetector* gestureDetector)
350 {
351   if(!mCurrentPanEmitters.empty())
352   {
353     // Check if the removed detector was one that is currently being panned and remove it from emitters.
354     GestureDetectorContainer::iterator endIter = std::remove(mCurrentPanEmitters.begin(), mCurrentPanEmitters.end(), gestureDetector);
355     mCurrentPanEmitters.erase(endIter, mCurrentPanEmitters.end());
356
357     // If we no longer have any emitters, then we should clear mCurrentGesturedActor as well
358     if(mCurrentPanEmitters.empty())
359     {
360       ResetActor();
361     }
362   }
363
364   // Find the detector...
365   PanGestureDetectorContainer::iterator endIter = std::remove(mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector);
366   DALI_ASSERT_DEBUG(endIter != mPanGestureDetectors.end());
367
368   // ...and remove it
369   mPanGestureDetectors.erase(endIter, mPanGestureDetectors.end());
370
371   if(mPanGestureDetectors.empty())
372   {
373     mGestureRecognizer = nullptr;
374   }
375   else
376   {
377     UpdateDetection();
378   }
379 }
380
381 void PanGestureProcessor::GestureDetectorUpdated(PanGestureDetector* gestureDetector)
382 {
383   DALI_ASSERT_DEBUG(find(mPanGestureDetectors.begin(), mPanGestureDetectors.end(), gestureDetector) != mPanGestureDetectors.end());
384
385   UpdateDetection();
386 }
387
388 bool PanGestureProcessor::SetPanGestureProperties(const Dali::PanGesture& pan)
389 {
390   // If we are currently processing a pan gesture then just ignore
391   if(mCurrentPanEmitters.empty() && mSceneObject)
392   {
393     const PanGesture& panImpl(GetImplementation(pan));
394
395     // We update the scene object directly rather than sending a message.
396     // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
397     mSceneObject->AddGesture(panImpl);
398
399     if(GestureState::STARTED == panImpl.GetState() || GestureState::CONTINUING == panImpl.GetState())
400     {
401       mNeedsUpdate = true;
402     }
403   }
404
405   return mNeedsUpdate;
406 }
407
408 void PanGestureProcessor::EnableProfiling()
409 {
410   mSceneObject->EnableProfiling();
411 }
412
413 void PanGestureProcessor::SetPredictionMode(int mode)
414 {
415   if((mode < 0) || (mode >= SceneGraph::PanGesture::NUM_PREDICTION_MODES))
416   {
417     mode = SceneGraph::PanGesture::DEFAULT_PREDICTION_MODE;
418   }
419   SceneGraph::PanGesture::PredictionMode modeEnum = static_cast<SceneGraph::PanGesture::PredictionMode>(mode);
420   mSceneObject->SetPredictionMode(modeEnum);
421 }
422
423 void PanGestureProcessor::SetPredictionAmount(unsigned int amount)
424 {
425   mSceneObject->SetPredictionAmount(amount);
426 }
427
428 void PanGestureProcessor::SetMaximumPredictionAmount(unsigned int amount)
429 {
430   mSceneObject->SetMaximumPredictionAmount(amount);
431 }
432
433 void PanGestureProcessor::SetMinimumPredictionAmount(unsigned int amount)
434 {
435   mSceneObject->SetMinimumPredictionAmount(amount);
436 }
437
438 void PanGestureProcessor::SetPredictionAmountAdjustment(unsigned int amount)
439 {
440   mSceneObject->SetPredictionAmountAdjustment(amount);
441 }
442
443 void PanGestureProcessor::SetSmoothingMode(int mode)
444 {
445   if((mode < 0) || (mode >= SceneGraph::PanGesture::NUM_SMOOTHING_MODES))
446   {
447     mode = SceneGraph::PanGesture::DEFAULT_SMOOTHING_MODE;
448   }
449   SceneGraph::PanGesture::SmoothingMode modeEnum = static_cast<SceneGraph::PanGesture::SmoothingMode>(mode);
450   mSceneObject->SetSmoothingMode(modeEnum);
451 }
452
453 void PanGestureProcessor::SetSmoothingAmount(float amount)
454 {
455   mSceneObject->SetSmoothingAmount(amount);
456 }
457
458 void PanGestureProcessor::SetUseActualTimes(bool value)
459 {
460   mSceneObject->SetUseActualTimes(value);
461 }
462
463 void PanGestureProcessor::SetInterpolationTimeRange(int value)
464 {
465   mSceneObject->SetInterpolationTimeRange(value);
466 }
467
468 void PanGestureProcessor::SetScalarOnlyPredictionEnabled(bool value)
469 {
470   mSceneObject->SetScalarOnlyPredictionEnabled(value);
471 }
472
473 void PanGestureProcessor::SetTwoPointPredictionEnabled(bool value)
474 {
475   mSceneObject->SetTwoPointPredictionEnabled(value);
476 }
477
478 void PanGestureProcessor::SetTwoPointInterpolatePastTime(int value)
479 {
480   mSceneObject->SetTwoPointInterpolatePastTime(value);
481 }
482
483 void PanGestureProcessor::SetTwoPointVelocityBias(float value)
484 {
485   mSceneObject->SetTwoPointVelocityBias(value);
486 }
487
488 void PanGestureProcessor::SetTwoPointAccelerationBias(float value)
489 {
490   mSceneObject->SetTwoPointAccelerationBias(value);
491 }
492
493 void PanGestureProcessor::SetMultitapSmoothingRange(int value)
494 {
495   mSceneObject->SetMultitapSmoothingRange(value);
496 }
497
498 void PanGestureProcessor::SetMinimumDistance(int32_t value)
499 {
500   if(mGestureRecognizer)
501   {
502     PanGestureRecognizer* panRecognizer = dynamic_cast<PanGestureRecognizer*>(mGestureRecognizer.Get());
503     if(panRecognizer)
504     {
505       panRecognizer->SetMinimumDistance(value);
506     }
507   }
508 }
509
510 void PanGestureProcessor::SetMinimumPanEvents(int32_t value)
511 {
512   if(mGestureRecognizer)
513   {
514     PanGestureRecognizer* panRecognizer = dynamic_cast<PanGestureRecognizer*>(mGestureRecognizer.Get());
515     if(panRecognizer)
516     {
517       panRecognizer->SetMinimumPanEvents(value);
518     }
519   }
520 }
521
522
523 const SceneGraph::PanGesture& PanGestureProcessor::GetSceneObject() const
524 {
525   return *mSceneObject;
526 }
527
528 void PanGestureProcessor::UpdateDetection()
529 {
530   DALI_ASSERT_DEBUG(!mPanGestureDetectors.empty());
531
532   uint32_t minimumRequired       = std::numeric_limits<uint32_t>::max();
533   uint32_t maximumRequired       = 0;
534   uint32_t maximumMotionEventAge = std::numeric_limits<uint32_t>::max();
535
536   for(PanGestureDetectorContainer::iterator iter = mPanGestureDetectors.begin(), endIter = mPanGestureDetectors.end(); iter != endIter; ++iter)
537   {
538     PanGestureDetector* detector(*iter);
539
540     if(detector)
541     {
542       uint32_t minimum = detector->GetMinimumTouchesRequired();
543       if(minimum < minimumRequired)
544       {
545         minimumRequired = minimum;
546       }
547
548       uint32_t maximum = detector->GetMaximumTouchesRequired();
549       if(maximum > maximumRequired)
550       {
551         maximumRequired = maximum;
552       }
553
554       uint32_t maximumAge = detector->GetMaximumMotionEventAge();
555       if(maximumAge < maximumMotionEventAge)
556       {
557         maximumMotionEventAge = maximumAge;
558       }
559     }
560   }
561
562   if((minimumRequired != mMinTouchesRequired) || (maximumRequired != mMaxTouchesRequired) || (maximumMotionEventAge != mMaxMotionEventAge))
563   {
564     mMinTouchesRequired = minimumRequired;
565     mMaxTouchesRequired = maximumRequired;
566     mMaxMotionEventAge  = maximumMotionEventAge;
567
568     PanGestureRequest request;
569     request.minTouches        = mMinTouchesRequired;
570     request.maxTouches        = mMaxTouchesRequired;
571     request.maxMotionEventAge = mMaxMotionEventAge;
572     mGestureRecognizer->Update(request);
573   }
574 }
575
576 void PanGestureProcessor::EmitPanSignal(Actor*                          actor,
577                                         const GestureDetectorContainer& gestureDetectors,
578                                         const PanGestureEvent&          panEvent,
579                                         Vector2                         localCurrent,
580                                         GestureState                    state,
581                                         RenderTaskPtr                   renderTask)
582 {
583   if(actor && !gestureDetectors.empty())
584   {
585     Internal::PanGesturePtr pan(new Internal::PanGesture(state));
586
587     pan->SetTime(panEvent.time);
588
589     pan->SetNumberOfTouches(panEvent.numberOfTouches);
590     pan->SetScreenPosition(panEvent.currentPosition);
591     pan->SetPosition(localCurrent);
592     pan->SetSourceType(panEvent.sourceType);
593     pan->SetSourceData(panEvent.sourceData);
594
595     RenderTask& renderTaskImpl(*renderTask.Get());
596
597     Vector2 localPrevious;
598     actor->ScreenToLocal(renderTaskImpl, localPrevious.x, localPrevious.y, panEvent.previousPosition.x, panEvent.previousPosition.y);
599
600     pan->SetDisplacement(localCurrent - localPrevious);
601     Vector2 previousPos(panEvent.previousPosition);
602     if(state == GestureState::STARTED)
603     {
604       previousPos = mPossiblePanPosition;
605     }
606
607     pan->SetScreenDisplacement(panEvent.currentPosition - previousPos);
608
609     // Avoid dividing by 0
610     if(panEvent.timeDelta > 0)
611     {
612       Vector2 velocity;
613       velocity.x = pan->GetDisplacement().x / static_cast<float>(panEvent.timeDelta);
614       velocity.y = pan->GetDisplacement().y / static_cast<float>(panEvent.timeDelta);
615       pan->SetVelocity(velocity);
616
617       Vector2 screenVelocity;
618       screenVelocity.x = pan->GetScreenDisplacement().x / static_cast<float>(panEvent.timeDelta);
619       screenVelocity.y = pan->GetScreenDisplacement().y / static_cast<float>(panEvent.timeDelta);
620       pan->SetScreenVelocity(screenVelocity);
621     }
622
623     // When the gesture ends, we may incorrectly get a ZERO velocity (as we have lifted our finger without any movement)
624     // so we should use the last recorded velocity instead in this scenario.
625     if((state == GestureState::FINISHED) && (pan->GetScreenVelocity() == Vector2::ZERO) &&
626        (panEvent.timeDelta < MAXIMUM_TIME_WITH_VALID_LAST_VELOCITY))
627     {
628       pan->SetVelocity(mLastVelocity);
629       pan->SetScreenVelocity(mLastScreenVelocity);
630     }
631     else
632     {
633       // Store the current velocity for future iterations.
634       mLastVelocity       = pan->GetVelocity();
635       mLastScreenVelocity = pan->GetScreenVelocity();
636     }
637
638     if(mSceneObject)
639     {
640       // We update the scene object directly rather than sending a message.
641       // Sending a message could cause unnecessary delays, the scene object ensure thread safe behaviour.
642       mSceneObject->AddGesture(*pan.Get());
643     }
644
645     DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_EMIT_PAN_GESTURE_SIGNAL", [&](std::ostringstream& oss) {
646       oss << "[" << gestureDetectors.size() << "]";
647     });
648
649     Dali::Actor actorHandle(actor);
650
651     const GestureDetectorContainer::const_iterator endIter = gestureDetectors.end();
652     for(GestureDetectorContainer::const_iterator iter = gestureDetectors.begin(); iter != endIter; ++iter)
653     {
654       static_cast<PanGestureDetector*>(*iter)->EmitPanGestureSignal(actorHandle, Dali::PanGesture(pan.Get()));
655     }
656
657     DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_EMIT_PAN_GESTURE_SIGNAL", [&](std::ostringstream& oss) {
658       oss << "[" << gestureDetectors.size() << "]";
659     });
660   }
661 }
662
663 void PanGestureProcessor::OnGesturedActorStageDisconnection()
664 {
665   mCurrentPanEmitters.clear();
666 }
667
668 bool PanGestureProcessor::CheckGestureDetector(GestureDetector* detector, Actor* actor)
669 {
670   DALI_ASSERT_DEBUG(mCurrentPanEvent);
671
672   bool                retVal(false);
673   PanGestureDetector* panDetector(static_cast<PanGestureDetector*>(detector));
674
675   if((mCurrentPanEvent->numberOfTouches >= panDetector->GetMinimumTouchesRequired()) &&
676      (mCurrentPanEvent->numberOfTouches <= panDetector->GetMaximumTouchesRequired()))
677   {
678     // Check if the detector requires directional panning.
679     if(panDetector->RequiresDirectionalPan() && mCurrentRenderTask)
680     {
681       // It does, calculate the angle of the pan in local actor coordinates and ensures it fits
682       // the detector's criteria.
683       RenderTask& renderTaskImpl = *mCurrentRenderTask.Get();
684
685       Vector2 startPosition, currentPosition;
686       actor->ScreenToLocal(renderTaskImpl, startPosition.x, startPosition.y, mPossiblePanPosition.x, mPossiblePanPosition.y);
687       actor->ScreenToLocal(renderTaskImpl, currentPosition.x, currentPosition.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y);
688       Vector2 displacement(currentPosition - startPosition);
689
690       Radian angle(atanf(displacement.y / displacement.x));
691
692       /////////////////////////////
693       //            |            //
694       //            |            //
695       //   Q3 (-,-) | Q4 (+,-)   //
696       //            |            //
697       //    ----------------- +x //
698       //            |            //
699       //   Q2 (-,+) | Q1 (+,+)   //
700       //            |            //
701       //            |            //
702       //           +y            //
703       /////////////////////////////
704       // Quadrant 1: As is
705       // Quadrant 2: 180 degrees + angle
706       // Quadrant 3: angle - 180 degrees
707       // Quadrant 4: As is
708       /////////////////////////////
709
710       if(displacement.x < 0.0f)
711       {
712         if(displacement.y >= 0.0f)
713         {
714           // Quadrant 2
715           angle.radian += Math::PI;
716         }
717         else
718         {
719           // Quadrant 3
720           angle.radian -= Math::PI;
721         }
722       }
723
724       if(panDetector->CheckAngleAllowed(angle))
725       {
726         retVal = true;
727       }
728     }
729     else
730     {
731       // Directional panning not required so we can use this actor and gesture detector.
732       retVal = true;
733     }
734   }
735   return retVal;
736 }
737
738 void PanGestureProcessor::EmitGestureSignal(Actor* actor, const GestureDetectorContainer& gestureDetectors, Vector2 actorCoordinates)
739 {
740   DALI_ASSERT_DEBUG(mCurrentPanEvent);
741
742   mCurrentPanEmitters.clear();
743   ResetActor();
744
745   actor->ScreenToLocal(*mCurrentRenderTask.Get(), actorCoordinates.x, actorCoordinates.y, mCurrentPanEvent->currentPosition.x, mCurrentPanEvent->currentPosition.y);
746
747   EmitPanSignal(actor, gestureDetectors, *mCurrentPanEvent, actorCoordinates, mCurrentPanEvent->state, mCurrentRenderTask);
748
749   if(actor->OnScene())
750   {
751     mCurrentPanEmitters = gestureDetectors;
752     SetActor(actor);
753   }
754 }
755
756 } // namespace Internal
757
758 } // namespace Dali