Revert "[Tizen] Initialize surface before PreRender"
[platform/core/uifw/dali-adaptor.git] / dali / internal / window-system / common / window-render-surface.cpp
1 /*
2  * Copyright (c) 2021 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/window-system/common/window-render-surface.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23 #include <dali/integration-api/gl-abstraction.h>
24
25 // INTERNAL INCLUDES
26 #include <dali/integration-api/adaptor-framework/thread-synchronization-interface.h>
27 #include <dali/integration-api/adaptor-framework/trigger-event-factory.h>
28 #include <dali/internal/adaptor/common/adaptor-impl.h>
29 #include <dali/internal/adaptor/common/adaptor-internal-services.h>
30 #include <dali/internal/graphics/gles/egl-graphics.h>
31 #include <dali/internal/graphics/gles/egl-implementation.h>
32 #include <dali/internal/system/common/environment-variables.h>
33 #include <dali/internal/window-system/common/window-base.h>
34 #include <dali/internal/window-system/common/window-factory.h>
35 #include <dali/internal/window-system/common/window-system.h>
36
37 namespace Dali
38 {
39 namespace Internal
40 {
41 namespace Adaptor
42 {
43 namespace
44 {
45 const int   MINIMUM_DIMENSION_CHANGE(1); ///< Minimum change for window to be considered to have moved
46 const float FULL_UPDATE_RATIO(0.8f);     ///< Force full update when the dirty area is larget than this ratio
47
48 #if defined(DEBUG_ENABLED)
49 Debug::Filter* gWindowRenderSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_WINDOW_RENDER_SURFACE");
50 #endif
51
52 void MergeRects(Rect<int>& mergingRect, const std::vector<Rect<int>>& rects)
53 {
54   uint32_t i = 0;
55   if(mergingRect.IsEmpty())
56   {
57     for(; i < rects.size(); i++)
58     {
59       if(!rects[i].IsEmpty())
60       {
61         mergingRect = rects[i];
62         break;
63       }
64     }
65   }
66
67   for(; i < rects.size(); i++)
68   {
69     mergingRect.Merge(rects[i]);
70   }
71 }
72
73 void InsertRects(WindowRenderSurface::DamagedRectsContainer& damagedRectsList, const std::vector<Rect<int>>& damagedRects)
74 {
75   damagedRectsList.push_front(damagedRects);
76   if(damagedRectsList.size() > 4) // past triple buffers + current
77   {
78     damagedRectsList.pop_back();
79   }
80 }
81
82 Rect<int32_t> RecalculateRect0(Rect<int32_t>& rect, const Rect<int32_t>& surfaceSize)
83 {
84   return rect;
85 }
86
87 Rect<int32_t> RecalculateRect90(Rect<int32_t>& rect, const Rect<int32_t>& surfaceSize)
88 {
89   Rect<int32_t> newRect;
90   newRect.x      = surfaceSize.height - (rect.y + rect.height);
91   newRect.y      = rect.x;
92   newRect.width  = rect.height;
93   newRect.height = rect.width;
94   return newRect;
95 }
96
97 Rect<int32_t> RecalculateRect180(Rect<int32_t>& rect, const Rect<int32_t>& surfaceSize)
98 {
99   Rect<int32_t> newRect;
100   newRect.x      = surfaceSize.width - (rect.x + rect.width);
101   newRect.y      = surfaceSize.height - (rect.y + rect.height);
102   newRect.width  = rect.width;
103   newRect.height = rect.height;
104   return newRect;
105 }
106
107 Rect<int32_t> RecalculateRect270(Rect<int32_t>& rect, const Rect<int32_t>& surfaceSize)
108 {
109   Rect<int32_t> newRect;
110   newRect.x      = rect.y;
111   newRect.y      = surfaceSize.width - (rect.x + rect.width);
112   newRect.width  = rect.height;
113   newRect.height = rect.width;
114   return newRect;
115 }
116
117 using RecalculateRectFunction = Rect<int32_t> (*)(Rect<int32_t>&, const Rect<int32_t>&);
118
119 RecalculateRectFunction RecalculateRect[4] = {RecalculateRect0, RecalculateRect90, RecalculateRect180, RecalculateRect270};
120
121 } // unnamed namespace
122
123 WindowRenderSurface::WindowRenderSurface(Dali::PositionSize positionSize, Any surface, bool isTransparent)
124 : mEGL(nullptr),
125   mDisplayConnection(nullptr),
126   mPositionSize(positionSize),
127   mWindowBase(),
128   mThreadSynchronization(nullptr),
129   mRenderNotification(nullptr),
130   mPostRenderTrigger(),
131   mFrameRenderedTrigger(),
132   mGraphics(nullptr),
133   mEGLSurface(nullptr),
134   mEGLContext(nullptr),
135   mColorDepth(isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24),
136   mOutputTransformedSignal(),
137   mFrameCallbackInfoContainer(),
138   mBufferDamagedRects(),
139   mMutex(),
140   mWindowRotationAngle(0),
141   mScreenRotationAngle(0),
142   mDpiHorizontal(0),
143   mDpiVertical(0),
144   mOwnSurface(false),
145   mWindowRotationFinished(true),
146   mScreenRotationFinished(true),
147   mResizeFinished(true),
148   mDefaultScreenRotationAvailable(false),
149   mIsImeWindowSurface(false)
150 {
151   DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "Creating Window\n");
152   Initialize(surface);
153 }
154
155 WindowRenderSurface::~WindowRenderSurface()
156 {
157 }
158
159 void WindowRenderSurface::Initialize(Any surface)
160 {
161   // If width or height are zero, go full screen.
162   if((mPositionSize.width == 0) || (mPositionSize.height == 0))
163   {
164     // Default window size == screen size
165     mPositionSize.x = 0;
166     mPositionSize.y = 0;
167     WindowSystem::GetScreenSize(mPositionSize.width, mPositionSize.height);
168   }
169
170   // Create a window base
171   auto windowFactory = Dali::Internal::Adaptor::GetWindowFactory();
172   mWindowBase        = windowFactory->CreateWindowBase(mPositionSize, surface, (mColorDepth == COLOR_DEPTH_32 ? true : false));
173
174   // Connect signals
175   mWindowBase->OutputTransformedSignal().Connect(this, &WindowRenderSurface::OutputTransformed);
176
177   // Check screen rotation
178   mScreenRotationAngle = mWindowBase->GetScreenRotationAngle();
179   if(mScreenRotationAngle != 0)
180   {
181     mScreenRotationFinished         = false;
182     mResizeFinished                 = false;
183     mDefaultScreenRotationAvailable = true;
184     DALI_LOG_RELEASE_INFO("WindowRenderSurface::Initialize, screen rotation is enabled, screen rotation angle:[%d]\n", mScreenRotationAngle);
185   }
186 }
187
188 Any WindowRenderSurface::GetNativeWindow()
189 {
190   return mWindowBase->GetNativeWindow();
191 }
192
193 int WindowRenderSurface::GetNativeWindowId()
194 {
195   return mWindowBase->GetNativeWindowId();
196 }
197
198 void WindowRenderSurface::Map()
199 {
200   mWindowBase->Show();
201 }
202
203 void WindowRenderSurface::SetRenderNotification(TriggerEventInterface* renderNotification)
204 {
205   mRenderNotification = renderNotification;
206 }
207
208 void WindowRenderSurface::SetTransparency(bool transparent)
209 {
210   mWindowBase->SetTransparency(transparent);
211 }
212
213 void WindowRenderSurface::RequestRotation(int angle, int width, int height)
214 {
215   if(!mPostRenderTrigger)
216   {
217     mPostRenderTrigger = std::unique_ptr<TriggerEventInterface>(TriggerEventFactory::CreateTriggerEvent(MakeCallback(this, &WindowRenderSurface::ProcessPostRender),
218                                                                                                         TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER));
219   }
220
221   mPositionSize.width  = width;
222   mPositionSize.height = height;
223
224   mWindowRotationAngle    = angle;
225   mWindowRotationFinished = false;
226   mResizeFinished = false;
227
228   mWindowBase->SetWindowRotationAngle(mWindowRotationAngle);
229
230   DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::Rotate: angle = %d screen rotation = %d\n", mWindowRotationAngle, mScreenRotationAngle);
231 }
232
233 WindowBase* WindowRenderSurface::GetWindowBase()
234 {
235   return mWindowBase.get();
236 }
237
238 WindowBase::OutputSignalType& WindowRenderSurface::OutputTransformedSignal()
239 {
240   return mOutputTransformedSignal;
241 }
242
243 PositionSize WindowRenderSurface::GetPositionSize() const
244 {
245   return mPositionSize;
246 }
247
248 void WindowRenderSurface::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical)
249 {
250   if(mDpiHorizontal == 0 || mDpiVertical == 0)
251   {
252     const char* environmentDpiHorizontal = std::getenv(DALI_ENV_DPI_HORIZONTAL);
253     mDpiHorizontal                       = environmentDpiHorizontal ? std::atoi(environmentDpiHorizontal) : 0;
254
255     const char* environmentDpiVertical = std::getenv(DALI_ENV_DPI_VERTICAL);
256     mDpiVertical                       = environmentDpiVertical ? std::atoi(environmentDpiVertical) : 0;
257
258     if(mDpiHorizontal == 0 || mDpiVertical == 0)
259     {
260       mWindowBase->GetDpi(mDpiHorizontal, mDpiVertical);
261     }
262   }
263
264   dpiHorizontal = mDpiHorizontal;
265   dpiVertical   = mDpiVertical;
266 }
267
268 int WindowRenderSurface::GetOrientation() const
269 {
270   return mWindowBase->GetOrientation();
271 }
272
273 void WindowRenderSurface::InitializeGraphics()
274 {
275   mGraphics = &mAdaptor->GetGraphicsInterface();
276
277   DALI_ASSERT_ALWAYS(mGraphics && "Graphics interface is not created");
278
279   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
280   mEGL             = &eglGraphics->GetEglInterface();
281
282   if(mEGLContext == NULL)
283   {
284     // Create the OpenGL context for this window
285     Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>(*mEGL);
286     eglImpl.ChooseConfig(true, mColorDepth);
287     eglImpl.CreateWindowContext(mEGLContext);
288
289     // Create the OpenGL surface
290     CreateSurface();
291   }
292 }
293
294 void WindowRenderSurface::CreateSurface()
295 {
296   DALI_LOG_TRACE_METHOD(gWindowRenderSurfaceLogFilter);
297
298   int width, height;
299   if(mScreenRotationAngle == 0 || mScreenRotationAngle == 180)
300   {
301     width  = mPositionSize.width;
302     height = mPositionSize.height;
303   }
304   else
305   {
306     width  = mPositionSize.height;
307     height = mPositionSize.width;
308   }
309
310   // Create the EGL window
311   EGLNativeWindowType window = mWindowBase->CreateEglWindow(width, height);
312
313   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
314
315   Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation();
316   mEGLSurface                                   = eglImpl.CreateSurfaceWindow(window, mColorDepth);
317
318   DALI_LOG_RELEASE_INFO("WindowRenderSurface::CreateSurface: WinId (%d), w = %d h = %d angle = %d screen rotation = %d\n",
319                         mWindowBase->GetNativeWindowId(),
320                         mPositionSize.width,
321                         mPositionSize.height,
322                         mWindowRotationAngle,
323                         mScreenRotationAngle);
324 }
325
326 void WindowRenderSurface::DestroySurface()
327 {
328   DALI_LOG_TRACE_METHOD(gWindowRenderSurfaceLogFilter);
329
330   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
331   if(eglGraphics)
332   {
333     DALI_LOG_RELEASE_INFO("WindowRenderSurface::DestroySurface: WinId (%d)\n", mWindowBase->GetNativeWindowId());
334
335     Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation();
336
337     eglImpl.DestroySurface(mEGLSurface);
338     mEGLSurface = nullptr;
339
340     // Destroy context also
341     eglImpl.DestroyContext(mEGLContext);
342     mEGLContext = nullptr;
343
344     mWindowBase->DestroyEglWindow();
345   }
346 }
347
348 bool WindowRenderSurface::ReplaceGraphicsSurface()
349 {
350   DALI_LOG_TRACE_METHOD(gWindowRenderSurfaceLogFilter);
351
352   // Destroy the old one
353   mWindowBase->DestroyEglWindow();
354
355   int width, height;
356   if(mScreenRotationAngle == 0 || mScreenRotationAngle == 180)
357   {
358     width  = mPositionSize.width;
359     height = mPositionSize.height;
360   }
361   else
362   {
363     width  = mPositionSize.height;
364     height = mPositionSize.width;
365   }
366
367   // Create the EGL window
368   EGLNativeWindowType window = mWindowBase->CreateEglWindow(width, height);
369
370   // Set screen rotation
371   mScreenRotationFinished = false;
372
373   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
374
375   Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation();
376   return eglImpl.ReplaceSurfaceWindow(window, mEGLSurface, mEGLContext);
377 }
378
379 void WindowRenderSurface::MoveResize(Dali::PositionSize positionSize)
380 {
381   bool needToMove   = false;
382   bool needToResize = false;
383
384   // Check moving
385   if((fabs(positionSize.x - mPositionSize.x) >= MINIMUM_DIMENSION_CHANGE) ||
386      (fabs(positionSize.y - mPositionSize.y) >= MINIMUM_DIMENSION_CHANGE))
387   {
388     needToMove = true;
389   }
390
391   // Check resizing
392   if((fabs(positionSize.width - mPositionSize.width) >= MINIMUM_DIMENSION_CHANGE) ||
393      (fabs(positionSize.height - mPositionSize.height) >= MINIMUM_DIMENSION_CHANGE))
394   {
395     needToResize = true;
396   }
397
398   if(needToResize)
399   {
400     if(needToMove)
401     {
402       mWindowBase->MoveResize(positionSize);
403     }
404     else
405     {
406       mWindowBase->Resize(positionSize);
407     }
408
409     mResizeFinished = false;
410     mPositionSize   = positionSize;
411   }
412   else
413   {
414     if(needToMove)
415     {
416       mWindowBase->Move(positionSize);
417
418       mPositionSize = positionSize;
419     }
420   }
421
422   DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::MoveResize: %d, %d, %d, %d\n", mPositionSize.x, mPositionSize.y, mPositionSize.width, mPositionSize.height);
423 }
424
425 void WindowRenderSurface::StartRender()
426 {
427 }
428
429 bool WindowRenderSurface::PreRender(bool resizingSurface, const std::vector<Rect<int>>& damagedRects, Rect<int>& clippingRect)
430 {
431   mDamagedRects.assign(damagedRects.begin(), damagedRects.end());
432
433   Dali::Integration::Scene::FrameCallbackContainer callbacks;
434
435   Dali::Integration::Scene scene = mScene.GetHandle();
436   if(scene)
437   {
438     bool needFrameRenderedTrigger = false;
439
440     scene.GetFrameRenderedCallback(callbacks);
441     if(!callbacks.empty())
442     {
443       int frameRenderedSync = mWindowBase->CreateFrameRenderedSyncFence();
444       if(frameRenderedSync != -1)
445       {
446         Dali::Mutex::ScopedLock lock(mMutex);
447
448         DALI_LOG_RELEASE_INFO("WindowRenderSurface::PreRender: CreateFrameRenderedSyncFence [%d]\n", frameRenderedSync);
449
450         mFrameCallbackInfoContainer.push_back(std::unique_ptr<FrameCallbackInfo>(new FrameCallbackInfo(callbacks, frameRenderedSync)));
451
452         needFrameRenderedTrigger = true;
453       }
454       else
455       {
456         DALI_LOG_ERROR("WindowRenderSurface::PreRender: CreateFrameRenderedSyncFence is failed\n");
457       }
458
459       // Clear callbacks
460       callbacks.clear();
461     }
462
463     scene.GetFramePresentedCallback(callbacks);
464     if(!callbacks.empty())
465     {
466       int framePresentedSync = mWindowBase->CreateFramePresentedSyncFence();
467       if(framePresentedSync != -1)
468       {
469         Dali::Mutex::ScopedLock lock(mMutex);
470
471         DALI_LOG_RELEASE_INFO("WindowRenderSurface::PreRender: CreateFramePresentedSyncFence [%d]\n", framePresentedSync);
472
473         mFrameCallbackInfoContainer.push_back(std::unique_ptr<FrameCallbackInfo>(new FrameCallbackInfo(callbacks, framePresentedSync)));
474
475         needFrameRenderedTrigger = true;
476       }
477       else
478       {
479         DALI_LOG_ERROR("WindowRenderSurface::PreRender: CreateFramePresentedSyncFence is failed\n");
480       }
481
482       // Clear callbacks
483       callbacks.clear();
484     }
485
486     if(needFrameRenderedTrigger)
487     {
488       if(!mFrameRenderedTrigger)
489       {
490         mFrameRenderedTrigger = std::unique_ptr<TriggerEventInterface>(TriggerEventFactory::CreateTriggerEvent(MakeCallback(this, &WindowRenderSurface::ProcessFrameCallback),
491                                                                                                                TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER));
492       }
493       mFrameRenderedTrigger->Trigger();
494     }
495   }
496
497   /**
498     * wl_egl_window_tizen_set_rotation(SetEglWindowRotation)                -> PreRotation
499     * wl_egl_window_tizen_set_buffer_transform(SetEglWindowBufferTransform) -> Screen Rotation
500     * wl_egl_window_tizen_set_window_transform(SetEglWindowTransform)       -> Window Rotation
501     * These function should be called before calling first drawing gl Function.
502     * Notice : PreRotation is not used in the latest tizen,
503     *          because output transform event should be occured before egl window is not created.
504     */
505
506   if(mIsResizing || mDefaultScreenRotationAvailable)
507   {
508     int totalAngle = (mWindowRotationAngle + mScreenRotationAngle) % 360;
509
510     // Window rotate or screen rotate
511     if(!mWindowRotationFinished || !mScreenRotationFinished)
512     {
513       mWindowBase->SetEglWindowBufferTransform(totalAngle);
514
515       // Reset only screen rotation flag
516       mScreenRotationFinished = true;
517
518       DALI_LOG_RELEASE_INFO("WindowRenderSurface::PreRender: Set rotation [%d] [%d]\n", mWindowRotationAngle, mScreenRotationAngle);
519     }
520
521     // Only window rotate
522     if(!mWindowRotationFinished)
523     {
524       mWindowBase->SetEglWindowTransform(mWindowRotationAngle);
525     }
526
527     // Resize case
528     if(!mResizeFinished)
529     {
530       Dali::PositionSize positionSize;
531       positionSize.x = mPositionSize.x;
532       positionSize.y = mPositionSize.y;
533       if(totalAngle == 0 || totalAngle == 180)
534       {
535         positionSize.width  = mPositionSize.width;
536         positionSize.height = mPositionSize.height;
537       }
538       else
539       {
540         positionSize.width  = mPositionSize.height;
541         positionSize.height = mPositionSize.width;
542       }
543       mWindowBase->ResizeEglWindow(positionSize);
544       mResizeFinished = true;
545
546       DALI_LOG_RELEASE_INFO("WindowRenderSurface::PreRender: Set resize, x: %d, y: %d, w: %d, h:%d\n", positionSize.x, positionSize.y, positionSize.width, positionSize.height);
547     }
548
549     SetFullSwapNextFrame();
550     mDefaultScreenRotationAvailable = false;
551   }
552
553   SetBufferDamagedRects(mDamagedRects, clippingRect);
554
555   if(clippingRect.IsEmpty())
556   {
557     mDamagedRects.clear();
558   }
559
560   // This is now done when the render pass for the render surface begins
561   //  MakeContextCurrent();
562
563   return true;
564 }
565
566 void WindowRenderSurface::PostRender()
567 {
568   // Inform the gl implementation that rendering has finished before informing the surface
569   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
570   if(eglGraphics)
571   {
572     GlImplementation& mGLES = eglGraphics->GetGlesInterface();
573     mGLES.PostRender();
574
575     if((mIsResizing && !mWindowRotationFinished) || mIsImeWindowSurface)
576     {
577       if(mThreadSynchronization)
578       {
579         // Enable PostRender flag
580         mThreadSynchronization->PostRenderStarted();
581       }
582
583       if(!mWindowRotationFinished || mIsImeWindowSurface)
584       {
585         mPostRenderTrigger->Trigger();
586       }
587
588       if(mThreadSynchronization)
589       {
590         // Wait until the event-thread complete the rotation event processing
591         mThreadSynchronization->PostRenderWaitForCompletion();
592       }
593     }
594
595     SwapBuffers(mDamagedRects);
596
597     if(mRenderNotification)
598     {
599       mRenderNotification->Trigger();
600     }
601   }
602 }
603
604 void WindowRenderSurface::StopRender()
605 {
606 }
607
608 void WindowRenderSurface::SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization)
609 {
610   DALI_LOG_INFO(gWindowRenderSurfaceLogFilter, Debug::Verbose, "WindowRenderSurface::SetThreadSynchronization: called\n");
611
612   mThreadSynchronization = &threadSynchronization;
613 }
614
615 void WindowRenderSurface::ReleaseLock()
616 {
617   // Nothing to do.
618 }
619
620 Dali::RenderSurfaceInterface::Type WindowRenderSurface::GetSurfaceType()
621 {
622   return Dali::RenderSurfaceInterface::WINDOW_RENDER_SURFACE;
623 }
624
625 void WindowRenderSurface::MakeContextCurrent()
626 {
627   if(mEGL != nullptr)
628   {
629     mEGL->MakeContextCurrent(mEGLSurface, mEGLContext);
630   }
631 }
632
633 Integration::DepthBufferAvailable WindowRenderSurface::GetDepthBufferRequired()
634 {
635   return mGraphics ? mGraphics->GetDepthBufferRequired() : Integration::DepthBufferAvailable::FALSE;
636 }
637
638 Integration::StencilBufferAvailable WindowRenderSurface::GetStencilBufferRequired()
639 {
640   return mGraphics ? mGraphics->GetStencilBufferRequired() : Integration::StencilBufferAvailable::FALSE;
641 }
642
643 void WindowRenderSurface::InitializeImeSurface()
644 {
645   mIsImeWindowSurface = true;
646   if(!mPostRenderTrigger)
647   {
648     mPostRenderTrigger = std::unique_ptr<TriggerEventInterface>(TriggerEventFactory::CreateTriggerEvent(MakeCallback(this, &WindowRenderSurface::ProcessPostRender),
649                                                                                                         TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER));
650   }
651 }
652
653 void WindowRenderSurface::OutputTransformed()
654 {
655   int screenRotationAngle = mWindowBase->GetScreenRotationAngle();
656
657   if(mScreenRotationAngle != screenRotationAngle)
658   {
659     mScreenRotationAngle    = screenRotationAngle;
660     mScreenRotationFinished = false;
661     mResizeFinished         = false;
662
663     mOutputTransformedSignal.Emit();
664
665     DALI_LOG_RELEASE_INFO("WindowRenderSurface::OutputTransformed: window = %d screen = %d\n", mWindowRotationAngle, mScreenRotationAngle);
666   }
667   else
668   {
669     DALI_LOG_RELEASE_INFO("WindowRenderSurface::OutputTransformed: Ignore output transform [%d]\n", mScreenRotationAngle);
670   }
671 }
672
673 void WindowRenderSurface::ProcessPostRender()
674 {
675   if(!mWindowRotationFinished)
676   {
677     mWindowBase->WindowRotationCompleted(mWindowRotationAngle, mPositionSize.width, mPositionSize.height);
678     DALI_LOG_RELEASE_INFO("WindowRenderSurface::ProcessPostRender: Rotation Done\n");
679     mWindowRotationFinished = true;
680   }
681
682   if(mIsImeWindowSurface)
683   {
684     mWindowBase->ImeWindowReadyToRender();
685   }
686
687   if(mThreadSynchronization)
688   {
689     mThreadSynchronization->PostRenderComplete();
690   }
691 }
692
693 void WindowRenderSurface::ProcessFrameCallback()
694 {
695   Dali::Mutex::ScopedLock lock(mMutex);
696
697   for(auto&& iter : mFrameCallbackInfoContainer)
698   {
699     if(!iter->fileDescriptorMonitor)
700     {
701       iter->fileDescriptorMonitor = std::unique_ptr<FileDescriptorMonitor>(new FileDescriptorMonitor(iter->fileDescriptor,
702                                                                                                      MakeCallback(this, &WindowRenderSurface::OnFileDescriptorEventDispatched),
703                                                                                                      FileDescriptorMonitor::FD_READABLE));
704
705       DALI_LOG_RELEASE_INFO("WindowRenderSurface::ProcessFrameCallback: Add handler [%d]\n", iter->fileDescriptor);
706     }
707   }
708 }
709
710 void WindowRenderSurface::OnFileDescriptorEventDispatched(FileDescriptorMonitor::EventType eventBitMask, int fileDescriptor)
711 {
712   if(!(eventBitMask & FileDescriptorMonitor::FD_READABLE))
713   {
714     DALI_LOG_ERROR("WindowRenderSurface::OnFileDescriptorEventDispatched: file descriptor error [%d]\n", eventBitMask);
715     close(fileDescriptor);
716     return;
717   }
718
719   DALI_LOG_RELEASE_INFO("WindowRenderSurface::OnFileDescriptorEventDispatched: Frame rendered [%d]\n", fileDescriptor);
720
721   std::unique_ptr<FrameCallbackInfo> callbackInfo;
722   {
723     Dali::Mutex::ScopedLock lock(mMutex);
724     auto                    frameCallbackInfo = std::find_if(mFrameCallbackInfoContainer.begin(), mFrameCallbackInfoContainer.end(), [fileDescriptor](std::unique_ptr<FrameCallbackInfo>& callbackInfo) {
725       return callbackInfo->fileDescriptor == fileDescriptor;
726     });
727     if(frameCallbackInfo != mFrameCallbackInfoContainer.end())
728     {
729       callbackInfo = std::move(*frameCallbackInfo);
730
731       mFrameCallbackInfoContainer.erase(frameCallbackInfo);
732     }
733   }
734
735   // Call the connected callback
736   if(callbackInfo)
737   {
738     for(auto&& iter : (callbackInfo)->callbacks)
739     {
740       CallbackBase::Execute(*(iter.first), iter.second);
741     }
742   }
743 }
744
745 void WindowRenderSurface::SetBufferDamagedRects(const std::vector<Rect<int>>& damagedRects, Rect<int>& clippingRect)
746 {
747   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
748   if(eglGraphics)
749   {
750     Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation();
751     if(!eglImpl.IsPartialUpdateRequired())
752     {
753       return;
754     }
755
756     Rect<int> surfaceRect(0, 0, mPositionSize.width, mPositionSize.height);
757
758     if(mFullSwapNextFrame)
759     {
760       InsertRects(mBufferDamagedRects, std::vector<Rect<int>>(1, surfaceRect));
761       clippingRect = Rect<int>();
762       return;
763     }
764
765     EGLint bufferAge = eglImpl.GetBufferAge(mEGLSurface);
766
767     // Buffer age 0 means the back buffer in invalid and requires full swap
768     if(!damagedRects.size() || bufferAge == 0)
769     {
770       InsertRects(mBufferDamagedRects, std::vector<Rect<int>>(1, surfaceRect));
771       clippingRect = Rect<int>();
772       return;
773     }
774
775     // We push current frame damaged rects here, zero index for current frame
776     InsertRects(mBufferDamagedRects, damagedRects);
777
778     // Merge damaged rects into clipping rect
779     auto bufferDamagedRects = mBufferDamagedRects.begin();
780     while(bufferAge-- >= 0 && bufferDamagedRects != mBufferDamagedRects.end())
781     {
782       const std::vector<Rect<int>>& rects = *bufferDamagedRects++;
783       MergeRects(clippingRect, rects);
784     }
785
786     if(!clippingRect.Intersect(surfaceRect) || clippingRect.Area() > surfaceRect.Area() * FULL_UPDATE_RATIO)
787     {
788       // clipping area too big or doesn't intersect surface rect
789       clippingRect = Rect<int>();
790       return;
791     }
792
793     std::vector<Rect<int>>   damagedRegion;
794     Dali::Integration::Scene scene = mScene.GetHandle();
795     if(scene)
796     {
797       damagedRegion.push_back(RecalculateRect[std::min(scene.GetCurrentSurfaceOrientation() / 90, 3)](clippingRect, scene.GetCurrentSurfaceRect()));
798     }
799     else
800     {
801       damagedRegion.push_back(clippingRect);
802     }
803
804     eglImpl.SetDamageRegion(mEGLSurface, damagedRegion);
805   }
806 }
807
808 void WindowRenderSurface::SwapBuffers(const std::vector<Rect<int>>& damagedRects)
809 {
810   auto eglGraphics = static_cast<EglGraphics*>(mGraphics);
811   if(eglGraphics)
812   {
813     Rect<int32_t> surfaceRect;
814     int32_t       orientation = 0;
815
816     Dali::Integration::Scene scene = mScene.GetHandle();
817     if(scene)
818     {
819       surfaceRect = scene.GetCurrentSurfaceRect();
820       orientation = std::min(scene.GetCurrentSurfaceOrientation() / 90, 3);
821     }
822
823     Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation();
824
825     if(!eglImpl.IsPartialUpdateRequired() || mFullSwapNextFrame || !damagedRects.size() || (damagedRects[0].Area() > surfaceRect.Area() * FULL_UPDATE_RATIO))
826     {
827       mFullSwapNextFrame = false;
828       eglImpl.SwapBuffers(mEGLSurface);
829       return;
830     }
831
832     mFullSwapNextFrame = false;
833
834     std::vector<Rect<int>> mergedRects = damagedRects;
835
836     // Merge intersecting rects, form an array of non intersecting rects to help driver a bit
837     // Could be optional and can be removed, needs to be checked with and without on platform
838     const int n = mergedRects.size();
839     for(int i = 0; i < n - 1; i++)
840     {
841       if(mergedRects[i].IsEmpty())
842       {
843         continue;
844       }
845
846       for(int j = i + 1; j < n; j++)
847       {
848         if(mergedRects[j].IsEmpty())
849         {
850           continue;
851         }
852
853         if(mergedRects[i].Intersects(mergedRects[j]))
854         {
855           mergedRects[i].Merge(mergedRects[j]);
856           mergedRects[j].width  = 0;
857           mergedRects[j].height = 0;
858         }
859       }
860     }
861
862     int j = 0;
863     for(int i = 0; i < n; i++)
864     {
865       if(!mergedRects[i].IsEmpty())
866       {
867         mergedRects[j++] = RecalculateRect[orientation](mergedRects[i], surfaceRect);
868       }
869     }
870
871     if(j != 0)
872     {
873       mergedRects.resize(j);
874     }
875
876     if(!mergedRects.size() || (mergedRects[0].Area() > surfaceRect.Area() * FULL_UPDATE_RATIO))
877     {
878       eglImpl.SwapBuffers(mEGLSurface);
879     }
880     else
881     {
882       eglImpl.SwapBuffers(mEGLSurface, mergedRects);
883     }
884   }
885 }
886
887 } // namespace Adaptor
888
889 } // namespace Internal
890
891 } // namespace Dali