e1c87300ece3f2490abb57b2230955075ceb6483
[platform/core/uifw/dali-core.git] / dali / internal / event / events / touch-event-processor.cpp
1 /*
2  * Copyright (c) 2020 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/touch-event-processor.h>
20
21 #if defined(DEBUG_ENABLED)
22 #include <sstream>
23 #endif
24
25 // INTERNAL INCLUDES
26 #include <dali/public-api/events/touch-event.h>
27 #include <dali/public-api/math/vector2.h>
28 #include <dali/public-api/signals/callback.h>
29 #include <dali/integration-api/debug.h>
30 #include <dali/integration-api/events/touch-event-integ.h>
31 #include <dali/internal/event/actors/actor-impl.h>
32 #include <dali/internal/event/actors/layer-impl.h>
33 #include <dali/internal/event/common/scene-impl.h>
34 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
35 #include <dali/internal/event/events/multi-point-event-util.h>
36 #include <dali/internal/event/events/touch-event-impl.h>
37 #include <dali/internal/event/render-tasks/render-task-impl.h>
38
39 namespace Dali
40 {
41
42 namespace Internal
43 {
44
45 namespace
46 {
47
48 #if defined(DEBUG_ENABLED)
49 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TOUCH_PROCESSOR" );
50
51 const char * TOUCH_POINT_STATE[ 6 ] =
52 {
53   "DOWN",
54   "UP",
55   "MOTION",
56   "LEAVE",
57   "STATIONARY",
58   "INTERRUPTED",
59 };
60
61 #endif // defined(DEBUG_ENABLED)
62
63
64 /**
65  *  Recursively deliver events to the actor and its parents, until the event is consumed or the stage is reached.
66  */
67 Dali::Actor EmitTouchSignals( Dali::Actor actor, const Dali::TouchEvent& touchEvent )
68 {
69   Dali::Actor consumedActor;
70
71   if ( actor )
72   {
73     Dali::Actor oldParent( actor.GetParent() );
74
75     Actor& actorImpl( GetImplementation(actor) );
76
77     bool consumed( false );
78
79     // Only emit the signal if the actor's touch signal has connections (or derived actor implementation requires touch).
80     if ( actorImpl.GetTouchRequired() )
81     {
82       consumed = actorImpl.EmitTouchEventSignal( touchEvent );
83     }
84
85     if ( consumed )
86     {
87       // One of this actor's listeners has consumed the event so set this actor as the consumed actor.
88       consumedActor = Dali::Actor( &actorImpl );
89     }
90     else
91     {
92       // The actor may have been removed/reparented during the signal callbacks.
93       Dali::Actor parent = actor.GetParent();
94
95       if ( parent &&
96            (parent == oldParent) )
97       {
98         // One of the actor's parents may consumed the event and they should be set as the consumed actor.
99         consumedActor = EmitTouchSignals( parent, touchEvent );
100       }
101     }
102   }
103
104   return consumedActor;
105 }
106
107 Dali::Actor AllocAndEmitTouchSignals( unsigned long time,  Dali::Actor actor, const Integration::Point& point )
108 {
109   TouchEventPtr touchEvent( new TouchEvent( time ) );
110   Dali::TouchEvent touchEventHandle( touchEvent.Get() );
111
112   touchEvent->AddPoint( point );
113
114   return EmitTouchSignals( actor, touchEventHandle );
115 }
116
117
118 /**
119  * Changes the state of the primary point to leave and emits the touch signals
120  */
121 Dali::Actor EmitTouchSignals( Actor* actor, RenderTask& renderTask, const TouchEventPtr& originalTouchEvent, PointState::Type state )
122 {
123   Dali::Actor consumingActor;
124
125   if( actor )
126   {
127     TouchEventPtr touchEventImpl = TouchEvent::Clone( *originalTouchEvent.Get() );
128
129     Integration::Point& primaryPoint = touchEventImpl->GetPoint( 0 );
130
131     const Vector2& screenPosition = primaryPoint.GetScreenPosition();
132     Vector2 localPosition;
133     actor->ScreenToLocal( renderTask, localPosition.x, localPosition.y, screenPosition.x, screenPosition.y );
134
135     primaryPoint.SetLocalPosition( localPosition );
136     primaryPoint.SetHitActor( Dali::Actor( actor ) );
137     primaryPoint.SetState( state );
138
139     consumingActor = EmitTouchSignals( Dali::Actor(actor), Dali::TouchEvent( touchEventImpl.Get() ) );
140   }
141
142   return consumingActor;
143 }
144
145 /**
146  * @brief Parses the primary touch point by performing a hit-test if necessary
147  *
148  * @param[out] hitTestResults The hit test results are put into this variable
149  * @param[in/out] capturingTouchActorObserver The observer for the capturing touch actor member
150  * @param[in] lastRenderTask The last render task member
151  * @param[in] currentPoint The current point information
152  * @param[in] scene The scene that this touch is related to
153  */
154 void ParsePrimaryTouchPoint(
155     HitTestAlgorithm::Results& hitTestResults,
156     ActorObserver& capturingTouchActorObserver,
157     const RenderTaskPtr& lastRenderTask,
158     const Integration::Point& currentPoint,
159     const Internal::Scene& scene )
160 {
161   Actor* capturingTouchActor = capturingTouchActorObserver.GetActor();
162
163   // We only set the capturing touch actor when the first touch-started actor captures all touch so if it's set, just use it
164   if( capturingTouchActor && lastRenderTask )
165   {
166     hitTestResults.actor = Dali::Actor( capturingTouchActor );
167     hitTestResults.renderTask = lastRenderTask;
168     const Vector2& screenPosition = currentPoint.GetScreenPosition();
169     capturingTouchActor->ScreenToLocal( *lastRenderTask, hitTestResults.actorCoordinates.x, hitTestResults.actorCoordinates.y, screenPosition.x, screenPosition.y );
170   }
171   else
172   {
173     HitTestAlgorithm::HitTest( scene.GetSize(), scene.GetRenderTaskList(), scene.GetLayerList(), currentPoint.GetScreenPosition(), hitTestResults );
174
175     if( currentPoint.GetState() == PointState::STARTED && hitTestResults.actor )
176     {
177       // If we've just started touch, then check whether the actor has requested to capture all touch events
178       Actor* hitActor = &GetImplementation( hitTestResults.actor );
179       if( hitActor->CapturesAllTouchAfterStart() )
180       {
181         capturingTouchActorObserver.SetActor( hitActor );
182       }
183     }
184   }
185 }
186
187 } // unnamed namespace
188
189 TouchEventProcessor::TouchEventProcessor( Scene& scene )
190 : mScene( scene ),
191   mLastPrimaryHitActor( MakeCallback( this, &TouchEventProcessor::OnObservedActorDisconnected ) ),
192   mLastConsumedActor(),
193   mCapturingTouchActor(),
194   mTouchDownConsumedActor(),
195   mLastRenderTask()
196 {
197   DALI_LOG_TRACE_METHOD( gLogFilter );
198 }
199
200 TouchEventProcessor::~TouchEventProcessor()
201 {
202   DALI_LOG_TRACE_METHOD( gLogFilter );
203 }
204
205 bool TouchEventProcessor::ProcessTouchEvent( const Integration::TouchEvent& event )
206 {
207   DALI_LOG_TRACE_METHOD( gLogFilter );
208   DALI_ASSERT_ALWAYS( !event.points.empty() && "Empty TouchEvent sent from Integration\n" );
209
210   PRINT_HIERARCHY(gLogFilter);
211
212   // 1) Check if it is an interrupted event - we should inform our last primary hit actor about this
213   //    and emit the stage signal as well.
214
215   if ( event.points[0].GetState() == PointState::INTERRUPTED )
216   {
217     Dali::Actor consumingActor;
218     Integration::Point currentPoint( event.points[0] );
219
220     Actor* lastPrimaryHitActor( mLastPrimaryHitActor.GetActor() );
221     if ( lastPrimaryHitActor )
222     {
223       Dali::Actor lastPrimaryHitActorHandle( lastPrimaryHitActor );
224       currentPoint.SetHitActor( lastPrimaryHitActorHandle );
225
226       consumingActor = AllocAndEmitTouchSignals( event.time, lastPrimaryHitActorHandle, currentPoint );
227     }
228
229     // If the last consumed actor was different to the primary hit actor then inform it as well (if it has not already been informed).
230     Actor* lastConsumedActor( mLastConsumedActor.GetActor() );
231     if ( lastConsumedActor &&
232          lastConsumedActor != lastPrimaryHitActor &&
233          lastConsumedActor != consumingActor )
234     {
235       Dali::Actor lastConsumedActorHandle( lastConsumedActor );
236       currentPoint.SetHitActor( lastConsumedActorHandle );
237       AllocAndEmitTouchSignals( event.time, lastConsumedActorHandle, currentPoint );
238     }
239
240     // Tell the touch-down consuming actor as well, if required
241     Actor* touchDownConsumedActor( mTouchDownConsumedActor.GetActor() );
242     if ( touchDownConsumedActor &&
243          touchDownConsumedActor != lastPrimaryHitActor &&
244          touchDownConsumedActor != lastConsumedActor &&
245          touchDownConsumedActor != consumingActor )
246     {
247       Dali::Actor touchDownConsumedActorHandle( touchDownConsumedActor );
248
249       currentPoint.SetHitActor( touchDownConsumedActorHandle );
250       AllocAndEmitTouchSignals( event.time, touchDownConsumedActorHandle, currentPoint );
251     }
252
253     mLastPrimaryHitActor.SetActor( nullptr );
254     mLastConsumedActor.SetActor( nullptr );
255     mCapturingTouchActor.SetActor( nullptr );
256     mTouchDownConsumedActor.SetActor( nullptr );
257     mLastRenderTask.Reset();
258
259     currentPoint.SetHitActor( Dali::Actor() );
260
261     TouchEventPtr touchEventImpl( new TouchEvent( event.time ) );
262     Dali::TouchEvent touchEventHandle( touchEventImpl.Get() );
263
264     touchEventImpl->AddPoint( currentPoint );
265
266     mScene.EmitTouchedSignal( touchEventHandle );
267     return false; // No need for hit testing & already an interrupted event so just return false
268   }
269
270   // 2) Hit Testing.
271   TouchEventPtr touchEventImpl( new TouchEvent( event.time ) );
272   Dali::TouchEvent touchEventHandle( touchEventImpl.Get() );
273
274   DALI_LOG_INFO( gLogFilter, Debug::Concise, "\n" );
275   DALI_LOG_INFO( gLogFilter, Debug::General, "Point(s): %d\n", event.GetPointCount() );
276
277   RenderTaskPtr currentRenderTask;
278   bool firstPointParsed = false;
279
280   for ( auto&& currentPoint : event.points )
281   {
282     HitTestAlgorithm::Results hitTestResults;
283     if( !firstPointParsed )
284     {
285       firstPointParsed = true;
286       ParsePrimaryTouchPoint( hitTestResults, mCapturingTouchActor, mLastRenderTask, currentPoint, mScene );
287
288       // Only set the currentRenderTask for the primary hit actor.
289       currentRenderTask = hitTestResults.renderTask;
290     }
291     else
292     {
293       HitTestAlgorithm::HitTest( mScene.GetSize(), mScene.GetRenderTaskList(), mScene.GetLayerList(), currentPoint.GetScreenPosition(), hitTestResults );
294     }
295
296     Integration::Point newPoint( currentPoint );
297     newPoint.SetHitActor( hitTestResults.actor );
298     newPoint.SetLocalPosition( hitTestResults.actorCoordinates );
299
300     touchEventImpl->AddPoint( newPoint );
301
302     DALI_LOG_INFO( gLogFilter, Debug::General, "  State(%s), Screen(%.0f, %.0f), HitActor(%p, %s), Local(%.2f, %.2f)\n",
303                    TOUCH_POINT_STATE[currentPoint.GetState()], currentPoint.GetScreenPosition().x, currentPoint.GetScreenPosition().y,
304                    ( hitTestResults.actor ? reinterpret_cast< void* >( &hitTestResults.actor.GetBaseObject() ) : NULL ),
305                    ( hitTestResults.actor ? hitTestResults.actor.GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str() : "" ),
306                    hitTestResults.actorCoordinates.x, hitTestResults.actorCoordinates.y );
307
308   }
309
310   // 3) Recursively deliver events to the actor and its parents, until the event is consumed or the stage is reached.
311
312   bool consumed = false;
313
314   // Emit the touch signal
315   Dali::Actor consumedActor;
316   if ( currentRenderTask )
317   {
318     consumedActor = EmitTouchSignals( touchEventImpl->GetPoint( 0 ).GetHitActor(), touchEventHandle );
319     consumed = consumedActor ? true : false;
320   }
321
322   Integration::Point& primaryPoint = touchEventImpl->GetPoint( 0 );
323   Dali::Actor primaryHitActor = primaryPoint.GetHitActor();
324   PointState::Type primaryPointState = primaryPoint.GetState();
325
326   DALI_LOG_INFO( gLogFilter, Debug::Concise, "PrimaryHitActor:     (%p) %s\n", primaryHitActor ? reinterpret_cast< void* >( &primaryHitActor.GetBaseObject() ) : NULL, primaryHitActor ? primaryHitActor.GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str() : "" );
327   DALI_LOG_INFO( gLogFilter, Debug::Concise, "ConsumedActor:       (%p) %s\n", consumedActor ? reinterpret_cast< void* >( &consumedActor.GetBaseObject() ) : NULL, consumedActor ? consumedActor.GetProperty< std::string >( Dali::Actor::Property::NAME ).c_str() : "" );
328
329   if ( ( primaryPointState == PointState::DOWN ) &&
330        ( touchEventImpl->GetPointCount() == 1 ) &&
331        ( consumedActor && consumedActor.GetProperty< bool >( Dali::Actor::Property::CONNECTED_TO_SCENE ) ) )
332   {
333     mTouchDownConsumedActor.SetActor( &GetImplementation( consumedActor ) );
334   }
335
336   // 4) Check if the last primary hit actor requires a leave event and if it was different to the current primary
337   //    hit actor.  Also process the last consumed actor in the same manner.
338
339   Actor* lastPrimaryHitActor( mLastPrimaryHitActor.GetActor() );
340   Actor* lastConsumedActor( mLastConsumedActor.GetActor() );
341   if( ( primaryPointState == PointState::MOTION ) || ( primaryPointState == PointState::UP ) || ( primaryPointState == PointState::STATIONARY ) )
342   {
343     if( mLastRenderTask )
344     {
345       Dali::Actor leaveEventConsumer;
346       RenderTask& lastRenderTaskImpl = *mLastRenderTask.Get();
347
348       if( lastPrimaryHitActor &&
349           lastPrimaryHitActor != primaryHitActor &&
350           lastPrimaryHitActor != consumedActor )
351       {
352         if( lastPrimaryHitActor->IsHittable() && IsActuallySensitive( lastPrimaryHitActor ) )
353         {
354           if ( lastPrimaryHitActor->GetLeaveRequired() )
355           {
356             DALI_LOG_INFO( gLogFilter, Debug::Concise, "LeaveActor(Hit):     (%p) %s\n", reinterpret_cast< void* >( lastPrimaryHitActor ), lastPrimaryHitActor->GetName().c_str() );
357             leaveEventConsumer = EmitTouchSignals( mLastPrimaryHitActor.GetActor(), lastRenderTaskImpl, touchEventImpl, PointState::LEAVE );
358           }
359         }
360         else
361         {
362           // At this point mLastPrimaryHitActor was touchable and sensitive in the previous touch event process but is not in the current one.
363           // An interrupted event is send to allow some actors to go back to their original state (i.e. Button controls)
364           DALI_LOG_INFO( gLogFilter, Debug::Concise, "InterruptedActor(Hit):     (%p) %s\n", reinterpret_cast< void* >( lastPrimaryHitActor ), lastPrimaryHitActor->GetName().c_str() );
365           leaveEventConsumer = EmitTouchSignals( mLastPrimaryHitActor.GetActor(), lastRenderTaskImpl, touchEventImpl, PointState::INTERRUPTED );
366         }
367       }
368
369       consumed |= leaveEventConsumer ? true : false;
370
371       // Check if the motion event has been consumed by another actor's listener.  In this case, the previously
372       // consumed actor's listeners may need to be informed (through a leave event).
373       // Further checks here to ensure we do not signal the same actor twice for the same event.
374       if ( lastConsumedActor &&
375            lastConsumedActor != consumedActor &&
376            lastConsumedActor != lastPrimaryHitActor &&
377            lastConsumedActor != primaryHitActor &&
378            lastConsumedActor != leaveEventConsumer )
379       {
380         if( lastConsumedActor->IsHittable() && IsActuallySensitive( lastConsumedActor ) )
381         {
382           if( lastConsumedActor->GetLeaveRequired() )
383           {
384             DALI_LOG_INFO( gLogFilter, Debug::Concise, "LeaveActor(Consume): (%p) %s\n", reinterpret_cast< void* >( lastConsumedActor ), lastConsumedActor->GetName().c_str() );
385             EmitTouchSignals( lastConsumedActor, lastRenderTaskImpl, touchEventImpl, PointState::LEAVE );
386           }
387         }
388         else
389         {
390           // At this point mLastConsumedActor was touchable and sensitive in the previous touch event process but is not in the current one.
391           // An interrupted event is send to allow some actors to go back to their original state (i.e. Button controls)
392           DALI_LOG_INFO( gLogFilter, Debug::Concise, "InterruptedActor(Consume):     (%p) %s\n", reinterpret_cast< void* >( lastConsumedActor ), lastConsumedActor->GetName().c_str() );
393           EmitTouchSignals( mLastConsumedActor.GetActor(), lastRenderTaskImpl, touchEventImpl, PointState::INTERRUPTED );
394         }
395       }
396     }
397   }
398
399   // 5) If our primary point is an Up event, then the primary point (in multi-touch) will change next
400   //    time so set our last primary actor to NULL.  Do the same to the last consumed actor as well.
401
402   if ( primaryPointState == PointState::UP )
403   {
404     mLastPrimaryHitActor.SetActor( nullptr );
405     mLastConsumedActor.SetActor( nullptr );
406     mCapturingTouchActor.SetActor( nullptr );
407     mLastRenderTask.Reset();
408   }
409   else
410   {
411     // The primaryHitActor may have been removed from the scene so ensure it is still on the scene before setting members.
412     if ( primaryHitActor && GetImplementation( primaryHitActor ).OnScene() )
413     {
414       mLastPrimaryHitActor.SetActor( &GetImplementation( primaryHitActor ) );
415
416       // Only observe the consumed actor if we have a primaryHitActor (check if it is still on the scene).
417       if ( consumedActor && GetImplementation( consumedActor ).OnScene() )
418       {
419         mLastConsumedActor.SetActor( &GetImplementation( consumedActor ) );
420       }
421       else
422       {
423         mLastConsumedActor.SetActor( NULL );
424       }
425
426       mLastRenderTask = currentRenderTask;
427     }
428     else
429     {
430       mLastPrimaryHitActor.SetActor( nullptr );
431       mLastConsumedActor.SetActor( nullptr );
432       mCapturingTouchActor.SetActor( nullptr );
433       mLastRenderTask.Reset();
434     }
435   }
436
437   // 6) Emit an interrupted event to the touch-down actor if it hasn't consumed the up and
438   //    emit the stage touched event if required.
439
440   if ( touchEventImpl->GetPointCount() == 1 ) // Only want the first touch and the last release
441   {
442     switch ( primaryPointState )
443     {
444       case PointState::UP:
445       {
446         Actor* touchDownConsumedActor( mTouchDownConsumedActor.GetActor() );
447         if ( touchDownConsumedActor &&
448              touchDownConsumedActor != consumedActor &&
449              touchDownConsumedActor != lastPrimaryHitActor &&
450              touchDownConsumedActor != lastConsumedActor )
451         {
452           Dali::Actor touchDownConsumedActorHandle( touchDownConsumedActor );
453
454           Integration::Point currentPoint = touchEventImpl->GetPoint( 0 );
455           currentPoint.SetHitActor( touchDownConsumedActorHandle );
456           currentPoint.SetState( PointState::INTERRUPTED );
457
458           AllocAndEmitTouchSignals( event.time, touchDownConsumedActorHandle, currentPoint );
459         }
460
461         mTouchDownConsumedActor.SetActor( NULL );
462
463         DALI_FALLTHROUGH;
464       }
465
466       case PointState::DOWN:
467       {
468         mScene.EmitTouchedSignal( touchEventHandle );
469         break;
470       }
471
472       case PointState::MOTION:
473       case PointState::LEAVE:
474       case PointState::STATIONARY:
475       case PointState::INTERRUPTED:
476       {
477         // Ignore
478         break;
479       }
480     }
481   }
482
483   return consumed;
484 }
485
486 void TouchEventProcessor::OnObservedActorDisconnected( Actor* actor )
487 {
488   if ( actor == mLastPrimaryHitActor.GetActor() )
489   {
490     Dali::Actor actorHandle( actor );
491
492     Integration::Point point;
493     point.SetState( PointState::INTERRUPTED );
494     point.SetHitActor( actorHandle );
495
496     TouchEventPtr touchEventImpl( new TouchEvent );
497     touchEventImpl->AddPoint( point );
498     Dali::TouchEvent touchEventHandle( touchEventImpl.Get() );
499
500     Dali::Actor eventConsumer = EmitTouchSignals( actorHandle, touchEventHandle );
501
502     if ( mLastConsumedActor.GetActor() != eventConsumer )
503     {
504       EmitTouchSignals( Dali::Actor( mLastConsumedActor.GetActor() ), touchEventHandle );
505     }
506
507     // Do not set mLastPrimaryHitActor to NULL we may be iterating through its observers
508
509     mLastConsumedActor.SetActor( NULL );
510     mLastRenderTask.Reset();
511   }
512 }
513
514 } // namespace Internal
515
516 } // namespace Dali