f54668e30936a76385da7b81963cc63e2c99cb57
[platform/core/uifw/dali-core.git] / dali / internal / event / events / touch-event-processor.cpp
1 //
2 // Copyright (c) 2014 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Flora License, Version 1.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://floralicense.org/license/
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 // CLASS HEADER
18 #include <dali/internal/event/events/touch-event-processor.h>
19
20 #if defined(DEBUG_ENABLED)
21 #include <sstream>
22 #endif
23
24 // INTERNAL INCLUDES
25 #include <dali/public-api/actors/renderable-actor.h>
26 #include <dali/public-api/math/vector2.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/integration-api/events/touch-event-integ.h>
29 #include <dali/internal/event/actors/actor-impl.h>
30 #include <dali/internal/event/actors/layer-impl.h>
31 #include <dali/internal/event/common/stage-impl.h>
32 #include <dali/internal/event/events/hit-test-algorithm-impl.h>
33 #include <dali/internal/event/render-tasks/render-task-impl.h>
34
35 namespace Dali
36 {
37
38 namespace Internal
39 {
40
41 namespace
42 {
43
44 bool IsActuallySensitive( Actor* actor );
45
46 #if defined(DEBUG_ENABLED)
47 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TOUCH_PROCESSOR" );
48
49 const char * TOUCH_POINT_STATE[TouchPoint::Last] =
50 {
51   "Down",
52   "Up",
53   "Motion",
54   "Leave",
55   "Stationary",
56   "Interrupted",
57 };
58
59 static const Debug::LogLevel HIERARCHY_DEBUG_LOG_LEVEL( Debug::Verbose );
60
61 static bool HIERARCHY_GEOMETRY( false );
62 static bool HIERARCHY_SENSITIVITY( false );
63 static bool HIERARCHY_TOUCH_REQUIRED( false );
64 static bool HIERARCHY_HITTABLE( false );
65
66 /**
67  * Prints out all the children of the given actor when debug is enabled.
68  *
69  * @param[in]  actor  The actor whose children to print.
70  * @param[in]  level  The number of " | " to put in front of the children.
71  */
72 void PrintChildren( Dali::Actor actor, int level )
73 {
74   std::ostringstream output;
75
76   for ( int t = 0; t < level; ++t )
77   {
78     output << " | ";
79   }
80
81   output << actor.GetName() << "(" << actor.GetTypeName() << ", " << actor.GetObjectPtr() << ")";
82
83   if ( HIERARCHY_GEOMETRY )
84   {
85     output << " Pos: " << actor.GetCurrentWorldPosition() << " Size: " << actor.GetCurrentSize() << " Scale: " << actor.GetCurrentWorldScale();
86   }
87
88   if ( HIERARCHY_SENSITIVITY )
89   {
90     output << " Sensitivity: " << ( IsActuallySensitive( &GetImplementation( actor ) ) ? "True " : "False " );
91   }
92
93   if ( HIERARCHY_TOUCH_REQUIRED )
94   {
95     output << " TouchRequired: " << ( GetImplementation(actor).GetTouchRequired() ? "True " : "False " );
96   }
97
98   if ( HIERARCHY_HITTABLE )
99   {
100     output << " Hittable: " << ( GetImplementation(actor).IsHittable() ? "True " : "False " );
101   }
102
103   output << std::endl;
104
105   DALI_LOG_INFO( gLogFilter, HIERARCHY_DEBUG_LOG_LEVEL, output.str().c_str() );
106
107   ++level;
108   unsigned int numChildren=actor.GetChildCount();
109   for ( unsigned int i=0; i<numChildren; ++i )
110   {
111     PrintChildren( actor.GetChildAt(i), level );
112   }
113   --level;
114 }
115
116 /**
117  * Prints the entire hierarchy of the scene.
118  */
119 void PrintHierarchy()
120 {
121   if ( gLogFilter->IsEnabledFor( HIERARCHY_DEBUG_LOG_LEVEL ) )
122   {
123     PrintChildren( Dali::Stage().GetCurrent().GetRootLayer(), 0 );
124   }
125 }
126
127 #define PRINT_HIERARCHY PrintHierarchy()
128
129 #else // defined(DEBUG_ENABLED)
130
131 #define PRINT_HIERARCHY
132
133 #endif // defined(DEBUG_ENABLED)
134
135 /**
136  *  Recursively deliver events to the actor and its parents, until the event is consumed or the stage is reached.
137  */
138 Dali::Actor EmitTouchSignals( Dali::Actor actor, RenderTask& renderTask, const TouchEvent& event )
139 {
140   Dali::Actor consumedActor;
141
142   if ( actor )
143   {
144     Dali::Actor oldParent( actor.GetParent() );
145
146     Actor& actorImpl( GetImplementation(actor) );
147
148     bool consumed( false );
149
150     // Only emit the signal if the actor's touch signal has connections (or derived actor implementation requires touch).
151     if ( actorImpl.GetTouchRequired() )
152     {
153       consumed = actorImpl.EmitTouchEventSignal( event );
154     }
155
156     if ( consumed )
157     {
158       // One of this actor's listeners has consumed the event so set this actor as the consumed actor.
159       consumedActor = Dali::Actor( &actorImpl );
160     }
161     else
162     {
163       // The actor may have been removed/reparented during the signal callbacks.
164       Dali::Actor parent = actor.GetParent();
165
166       if ( parent &&
167            (parent == oldParent) )
168       {
169         // One of the actor's parents may consumed the event and they should be set as the consumed actor.
170         consumedActor = EmitTouchSignals( parent, renderTask, event );
171       }
172     }
173   }
174
175   return consumedActor;
176 }
177
178 /**
179  * Changes the state of the primary point to leave and emits the touch signals
180  */
181 Dali::Actor EmitTouchSignals( Actor* actor, RenderTask& renderTask, const TouchEvent& originalEvent, TouchPoint::State state )
182 {
183   TouchEvent touchEvent( originalEvent );
184   TouchPoint& primaryPoint = touchEvent.points[0];
185
186   actor->ScreenToLocal( renderTask, primaryPoint.local.x, primaryPoint.local.y, primaryPoint.screen.x, primaryPoint.screen.y );
187
188   primaryPoint.hitActor = actor;
189   primaryPoint.state = state;
190
191   return EmitTouchSignals( Dali::Actor(actor), renderTask, touchEvent );
192 }
193
194 /**
195  * In the hit test algorithm above we do not descend actor tree if it is insensitive, so here, we
196  * should also check if any of the actor's parents has become insensitive since we last processed
197  * it.
198  */
199 bool IsActuallySensitive( Actor* actor )
200 {
201   bool sensitive = true;
202
203   while ( actor && sensitive )
204   {
205     sensitive = actor->IsSensitive();
206     actor = actor->GetParent();
207   }
208
209   return sensitive;
210 }
211
212 } // unnamed namespace
213
214 TouchEventProcessor::TouchEventProcessor( Stage& stage )
215 : mStage( stage ),
216   mLastPrimaryHitActor(),
217   mLastConsumedActor(),
218   mLastRenderTask()
219 {
220   DALI_LOG_TRACE_METHOD( gLogFilter );
221 }
222
223 TouchEventProcessor::~TouchEventProcessor()
224 {
225   DALI_LOG_TRACE_METHOD( gLogFilter );
226 }
227
228 void TouchEventProcessor::ProcessTouchEvent( const Integration::TouchEvent& event )
229 {
230   DALI_LOG_TRACE_METHOD( gLogFilter );
231
232   DALI_ASSERT_ALWAYS( !event.points.empty() && "Empty TouchEvent sent from Integration\n" );
233
234   Stage& stage = mStage;
235
236   PRINT_HIERARCHY;
237
238   // Copy so we can add the results of a hit-test.
239   TouchEvent touchEvent( event.time );
240
241   // 1) Check if it is an interrupted event - we should inform our last primary hit actor about this
242   //    and emit the stage signal as well.
243
244   if ( event.points[0].state == TouchPoint::Interrupted )
245   {
246     Dali::Actor consumingActor;
247     touchEvent.points.push_back(event.points[0]);
248
249     if ( mLastRenderTask )
250     {
251       RenderTask& lastRenderTaskImpl( GetImplementation( mLastRenderTask ) );
252
253       Actor* lastPrimaryHitActor( mLastPrimaryHitActor.GetActor() );
254       if ( lastPrimaryHitActor )
255       {
256         Dali::Actor lastPrimaryHitActorHandle( lastPrimaryHitActor );
257         touchEvent.points[0].hitActor = lastPrimaryHitActorHandle;
258         consumingActor = EmitTouchSignals( lastPrimaryHitActorHandle, lastRenderTaskImpl, touchEvent );
259       }
260
261       // If the last consumed actor was different to the primary hit actor then inform it as well (if it has not already been informed).
262       Actor* lastConsumedActor( mLastConsumedActor.GetActor() );
263       if ( lastConsumedActor &&
264            lastConsumedActor != lastPrimaryHitActor &&
265            lastConsumedActor != consumingActor )
266       {
267         Dali::Actor lastConsumedActorHandle( lastConsumedActor );
268         touchEvent.points[0].hitActor = lastConsumedActorHandle;
269         EmitTouchSignals( lastConsumedActorHandle, lastRenderTaskImpl, touchEvent );
270       }
271     }
272
273     mLastPrimaryHitActor.SetActor( NULL );
274     mLastConsumedActor.SetActor( NULL );
275     mLastRenderTask.Reset();
276
277     touchEvent.points[0].hitActor = NULL;
278     mStage.EmitTouchedSignal( touchEvent );
279
280     return; // No need for hit testing
281   }
282
283   // 2) Hit Testing.
284
285   DALI_LOG_INFO( gLogFilter, Debug::Concise, "\n" );
286   DALI_LOG_INFO( gLogFilter, Debug::General, "Point(s): %d\n", event.GetPointCount() );
287
288   Dali::RenderTask currentRenderTask;
289
290   for ( TouchPointContainerConstIterator iter = event.points.begin(), beginIter = event.points.begin(), endIter = event.points.end(); iter != endIter; ++iter )
291   {
292     HitTestAlgorithm::Results hitTestResults;
293     HitTestAlgorithm::HitTest( stage, iter->screen, hitTestResults );
294
295     TouchPoint newPoint( iter->deviceId, iter->state, iter->screen.x, iter->screen.y );
296     newPoint.hitActor = hitTestResults.actor;
297     newPoint.local = hitTestResults.actorCoordinates;
298
299     touchEvent.points.push_back( newPoint );
300
301     DALI_LOG_INFO( gLogFilter, Debug::General, "  State(%s), Screen(%.0f, %.0f), HitActor(%p, %s), Local(%.2f, %.2f)\n",
302                    TOUCH_POINT_STATE[iter->state], iter->screen.x, iter->screen.y,
303                    ( hitTestResults.actor ? (void*)&hitTestResults.actor.GetBaseObject() : NULL ),
304                    ( hitTestResults.actor ? hitTestResults.actor.GetName().c_str() : "" ),
305                    hitTestResults.actorCoordinates.x, hitTestResults.actorCoordinates.y );
306
307     // Only set the currentRenderTask for the primary hit actor.
308     if ( iter == beginIter && hitTestResults.renderTask )
309     {
310       currentRenderTask = hitTestResults.renderTask;
311     }
312   }
313
314   // 3) Recursively deliver events to the actor and its parents, until the event is consumed or the stage is reached.
315
316   // Emit the touch signal
317   Dali::Actor consumedActor;
318   if ( currentRenderTask )
319   {
320     consumedActor = EmitTouchSignals( touchEvent.points[0].hitActor, GetImplementation( currentRenderTask ), touchEvent );
321   }
322
323   TouchPoint& primaryPoint = touchEvent.points[0];
324   Dali::Actor primaryHitActor = primaryPoint.hitActor;
325   TouchPoint::State primaryPointState = primaryPoint.state;
326
327   DALI_LOG_INFO( gLogFilter, Debug::Concise, "PrimaryHitActor:     (%p) %s\n", primaryPoint.hitActor ? (void*)&primaryPoint.hitActor.GetBaseObject() : NULL, primaryPoint.hitActor ? primaryPoint.hitActor.GetName().c_str() : "" );
328   DALI_LOG_INFO( gLogFilter, Debug::Concise, "ConsumedActor:       (%p) %s\n", consumedActor ? (void*)&consumedActor.GetBaseObject() : NULL, consumedActor ? consumedActor.GetName().c_str() : "" );
329
330   // 4) Check if the last primary hit actor requires a leave event and if it was different to the current primary
331   //    hit actor.  Also process the last consumed actor in the same manner.
332
333   if( (primaryPointState == TouchPoint::Motion) || (primaryPointState == TouchPoint::Up) || (primaryPointState == TouchPoint::Stationary) )
334   {
335     if ( mLastRenderTask )
336     {
337       Dali::Actor leaveEventConsumer;
338       RenderTask& lastRenderTaskImpl( GetImplementation( mLastRenderTask ) );
339
340       Actor* lastPrimaryHitActor( mLastPrimaryHitActor.GetActor() );
341       if( lastPrimaryHitActor &&
342           lastPrimaryHitActor != primaryHitActor &&
343           lastPrimaryHitActor != consumedActor )
344       {
345         if( lastPrimaryHitActor->IsHittable() && IsActuallySensitive( lastPrimaryHitActor ) )
346         {
347           if ( lastPrimaryHitActor->GetLeaveRequired() )
348           {
349             DALI_LOG_INFO( gLogFilter, Debug::Concise, "LeaveActor(Hit):     (%p) %s\n", (void*)lastPrimaryHitActor, lastPrimaryHitActor->GetName().c_str() );
350             leaveEventConsumer = EmitTouchSignals( mLastPrimaryHitActor.GetActor(), lastRenderTaskImpl, touchEvent, TouchPoint::Leave );
351           }
352         }
353         else
354         {
355           // At this point mLastPrimaryHitActor was touchable and sensitive in the previous touch event process but is not in the current one.
356           // An interrupted event is send to allow some actors to go back to their original state (i.e. Button controls)
357           DALI_LOG_INFO( gLogFilter, Debug::Concise, "InterruptedActor(Hit):     (%p) %s\n", (void*)lastPrimaryHitActor, lastPrimaryHitActor->GetName().c_str() );
358           leaveEventConsumer = EmitTouchSignals( mLastPrimaryHitActor.GetActor(), lastRenderTaskImpl, touchEvent, TouchPoint::Interrupted );
359         }
360       }
361
362       // Check if the motion event has been consumed by another actor's listener.  In this case, the previously
363       // consumed actor's listeners may need to be informed (through a leave event).
364       // Further checks here to ensure we do not signal the same actor twice for the same event.
365       Actor* lastConsumedActor( mLastConsumedActor.GetActor() );
366       if ( lastConsumedActor &&
367            lastConsumedActor != consumedActor &&
368            lastConsumedActor != lastPrimaryHitActor &&
369            lastConsumedActor != primaryHitActor &&
370            lastConsumedActor != leaveEventConsumer )
371       {
372         if( lastConsumedActor->IsHittable() && IsActuallySensitive( lastConsumedActor ) )
373         {
374           if( lastConsumedActor->GetLeaveRequired() )
375           {
376             DALI_LOG_INFO( gLogFilter, Debug::Concise, "LeaveActor(Consume): (%p) %s\n", (void*)lastConsumedActor, lastConsumedActor->GetName().c_str() );
377             EmitTouchSignals( lastConsumedActor, lastRenderTaskImpl, touchEvent, TouchPoint::Leave );
378           }
379         }
380         else
381         {
382           // At this point mLastConsumedActor was touchable and sensitive in the previous touch event process but is not in the current one.
383           // An interrupted event is send to allow some actors to go back to their original state (i.e. Button controls)
384           DALI_LOG_INFO( gLogFilter, Debug::Concise, "InterruptedActor(Consume):     (%p) %s\n", (void*)lastConsumedActor, lastConsumedActor->GetName().c_str() );
385           EmitTouchSignals( mLastConsumedActor.GetActor(), lastRenderTaskImpl, touchEvent, TouchPoint::Interrupted );
386         }
387       }
388     }
389   }
390
391   // 5) If our primary point is an Up event, then the primary point (in multi-touch) will change next
392   //    time so set our last primary actor to NULL.  Do the same to the last consumed actor as well.
393
394   if ( primaryPointState == TouchPoint::Up )
395   {
396     mLastPrimaryHitActor.SetActor( NULL );
397     mLastConsumedActor.SetActor( NULL );
398     mLastRenderTask.Reset();
399   }
400   else
401   {
402     // The primaryHitActor may have been removed from the stage so ensure it is still on the stage before setting members.
403     if ( primaryHitActor && primaryHitActor.OnStage() )
404     {
405       mLastPrimaryHitActor.SetActor( &GetImplementation( primaryHitActor ) );
406
407       // Only observe the consumed actor if we have a primaryHitActor (check if it is still on stage).
408       if ( consumedActor && consumedActor.OnStage() )
409       {
410         mLastConsumedActor.SetActor( &GetImplementation( consumedActor ) );
411       }
412       else
413       {
414         mLastConsumedActor.SetActor( NULL );
415       }
416
417       mLastRenderTask = currentRenderTask;
418     }
419     else
420     {
421       mLastPrimaryHitActor.SetActor( NULL );
422       mLastConsumedActor.SetActor( NULL );
423       mLastRenderTask.Reset();
424     }
425   }
426
427   // 6) Emit the stage touched event if required.
428   if ( touchEvent.GetPointCount() == 1 ) // Only want the first touch and the last release
429   {
430     switch ( primaryPointState )
431     {
432       case TouchPoint::Down:
433       case TouchPoint::Up:
434       {
435         mStage.EmitTouchedSignal( touchEvent );
436         break;
437       }
438
439       case TouchPoint::Motion:
440       case TouchPoint::Leave:
441       case TouchPoint::Stationary:
442       case TouchPoint::Interrupted:
443       case TouchPoint::Last:
444       {
445         // Ignore
446         break;
447       }
448     }
449   }
450 }
451
452 TouchEventProcessor::ActorObserver::ActorObserver()
453 : mActor ( NULL ),
454   mActorDisconnected(false)
455 {
456   DALI_LOG_TRACE_METHOD( gLogFilter );
457 }
458
459 TouchEventProcessor::ActorObserver::~ActorObserver()
460 {
461   DALI_LOG_TRACE_METHOD( gLogFilter );
462   SetActor( NULL );
463 }
464
465 Actor* TouchEventProcessor::ActorObserver::GetActor()
466 {
467   return mActorDisconnected ? NULL : mActor;
468 }
469
470 void TouchEventProcessor::ActorObserver::SetActor( Actor* actor )
471 {
472   DALI_LOG_TRACE_METHOD( gLogFilter );
473
474   if ( mActor != actor )
475   {
476     ResetActor();
477
478     mActor = actor;
479
480     if ( mActor )
481     {
482       mActor->AddObserver( *this );
483       DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Start Observing:            %p\n", mActor);
484     }
485   }
486 }
487
488 void TouchEventProcessor::ActorObserver::ResetActor()
489 {
490   if ( mActor )
491   {
492     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Stop Observing:             %p\n", mActor);
493     mActor->RemoveObserver( *this );
494     mActor = NULL;
495     mActorDisconnected = false;
496   }
497 }
498
499 void TouchEventProcessor::ActorObserver::SceneObjectRemoved( ProxyObject& proxy )
500 {
501   DALI_LOG_TRACE_METHOD( gLogFilter );
502
503   if ( mActor == &proxy )
504   {
505     // do not call proxy.RemoveObserver here, proxy is currently iterating through observers... you wouldnt want to upset proxy now would you?
506     mActorDisconnected = true;
507   }
508 }
509
510 void TouchEventProcessor::ActorObserver::ProxyDestroyed(ProxyObject& proxy)
511 {
512   DALI_LOG_TRACE_METHOD( gLogFilter );
513
514   if ( mActor == &proxy )
515   {
516     DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Stop Observing:             %p\n", mActor);
517     mActor = NULL;
518   }
519 }
520
521 } // namespace Internal
522
523 } // namespace Dali